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/simulator-ui/src/java/main/ca/nengo/ui/configurable/PropertyInputPanel.java b/simulator-ui/src/java/main/ca/nengo/ui/configurable/PropertyInputPanel.java index 98bbd61a..f25887a9 100644 --- a/simulator-ui/src/java/main/ca/nengo/ui/configurable/PropertyInputPanel.java +++ b/simulator-ui/src/java/main/ca/nengo/ui/configurable/PropertyInputPanel.java @@ -1,205 +1,206 @@ /* The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is "PropertyInputPanel.java". Description: "Swing Input panel to be used to enter in the value for a ConfigParam @author Shu" The Initial Developer of the Original Code is Bryan Tripp & Centre for Theoretical Neuroscience, University of Waterloo. Copyright (C) 2006-2008. All Rights Reserved. Alternatively, the contents of this file may be used under the terms of the GNU Public License license (the GPL License), in which case the provisions of GPL License are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of the GPL License and not to allow others to use your version of this file under the MPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL License. If you do not delete the provisions above, a recipient may use your version of this file under either the MPL or the GPL License. */ package ca.nengo.ui.configurable; import java.awt.Component; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import ca.nengo.ui.lib.Style.NengoStyle; /** * Swing Input panel to be used to enter in the value for a ConfigParam * * @author Shu */ public abstract class PropertyInputPanel { private final JPanel innerPanel; private final JPanel outerPanel; private Property propDescriptor; private JLabel statusMessage; /** * @param property * A description of the Configuration parameter to be configured */ public PropertyInputPanel(Property property) { super(); this.propDescriptor = property; outerPanel = new JPanel(); outerPanel.setName(property.getName()); outerPanel.setToolTipText(property.getTooltip()); outerPanel.setLayout(new BoxLayout(outerPanel, BoxLayout.Y_AXIS)); outerPanel.setAlignmentY(JPanel.TOP_ALIGNMENT); outerPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0)); JPanel labelPanel=new JPanel(); labelPanel.setLayout(new BoxLayout(labelPanel, BoxLayout.X_AXIS)); labelPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT); JLabel label = new JLabel(property.getName()); label.setForeground(NengoStyle.COLOR_DARK_BLUE); label.setFont(NengoStyle.FONT_BOLD); labelPanel.add(label); JButton help=new JButton("<html><u>?</u></html>"); + help.setFocusable(false); help.setForeground(new java.awt.Color(120,120,180)); help.setBorderPainted(false); help.setContentAreaFilled(false); help.setFocusPainted(false); help.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null,propDescriptor.getTooltip(),propDescriptor.getName(),JOptionPane.INFORMATION_MESSAGE,null); } }); labelPanel.add(help); //labelPanel.add(Box.createHorizontalGlue()); // use this to right-justify question marks labelPanel.setMaximumSize(labelPanel.getMinimumSize()); // use this to keep question marks on left outerPanel.add(labelPanel); innerPanel = new JPanel(); innerPanel.setLayout(new BoxLayout(innerPanel, BoxLayout.X_AXIS)); innerPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT); outerPanel.add(innerPanel); statusMessage = new JLabel(""); statusMessage.setForeground(NengoStyle.COLOR_HIGH_SALIENCE); outerPanel.add(statusMessage); } /** * @param comp * Component to be added to the input panel */ protected void add(Component comp) { innerPanel.add(comp); } /** * @return */ protected JDialog getDialogParent() { /* * get the JDialog parent */ Container parent = outerPanel.getParent(); while (parent != null) { if (parent instanceof JDialog) { return (JDialog) parent; } parent = parent.getParent(); } throw new RuntimeException("Input panel does not have a dialog parent"); } /** * @param comp * Component to be removed from the input panel */ protected void removeFromPanel(Component comp) { innerPanel.remove(comp); } /** * @param msg */ protected void setStatusMsg(String msg) { statusMessage.setText(msg); } /** * @return Descriptor of the configuration parameter */ public Property getDescriptor() { return propDescriptor; } /** * @return TODO */ public JPanel getJPanel() { return outerPanel; } /** * @return TODO */ public String getName() { return outerPanel.getName(); } /** * @return Value of the parameter */ public abstract Object getValue(); /** * @return TODO */ public boolean isEnabled() { return innerPanel.isEnabled(); } /** * @return True if configuration parameter is set */ public abstract boolean isValueSet(); /** * @param enabled TODO */ public void setEnabled(boolean enabled) { innerPanel.setEnabled(enabled); } /** * @param value * Sets the configuration parameter */ public abstract void setValue(Object value); }
true
true
public PropertyInputPanel(Property property) { super(); this.propDescriptor = property; outerPanel = new JPanel(); outerPanel.setName(property.getName()); outerPanel.setToolTipText(property.getTooltip()); outerPanel.setLayout(new BoxLayout(outerPanel, BoxLayout.Y_AXIS)); outerPanel.setAlignmentY(JPanel.TOP_ALIGNMENT); outerPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0)); JPanel labelPanel=new JPanel(); labelPanel.setLayout(new BoxLayout(labelPanel, BoxLayout.X_AXIS)); labelPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT); JLabel label = new JLabel(property.getName()); label.setForeground(NengoStyle.COLOR_DARK_BLUE); label.setFont(NengoStyle.FONT_BOLD); labelPanel.add(label); JButton help=new JButton("<html><u>?</u></html>"); help.setForeground(new java.awt.Color(120,120,180)); help.setBorderPainted(false); help.setContentAreaFilled(false); help.setFocusPainted(false); help.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null,propDescriptor.getTooltip(),propDescriptor.getName(),JOptionPane.INFORMATION_MESSAGE,null); } }); labelPanel.add(help); //labelPanel.add(Box.createHorizontalGlue()); // use this to right-justify question marks labelPanel.setMaximumSize(labelPanel.getMinimumSize()); // use this to keep question marks on left outerPanel.add(labelPanel); innerPanel = new JPanel(); innerPanel.setLayout(new BoxLayout(innerPanel, BoxLayout.X_AXIS)); innerPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT); outerPanel.add(innerPanel); statusMessage = new JLabel(""); statusMessage.setForeground(NengoStyle.COLOR_HIGH_SALIENCE); outerPanel.add(statusMessage); }
public PropertyInputPanel(Property property) { super(); this.propDescriptor = property; outerPanel = new JPanel(); outerPanel.setName(property.getName()); outerPanel.setToolTipText(property.getTooltip()); outerPanel.setLayout(new BoxLayout(outerPanel, BoxLayout.Y_AXIS)); outerPanel.setAlignmentY(JPanel.TOP_ALIGNMENT); outerPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0)); JPanel labelPanel=new JPanel(); labelPanel.setLayout(new BoxLayout(labelPanel, BoxLayout.X_AXIS)); labelPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT); JLabel label = new JLabel(property.getName()); label.setForeground(NengoStyle.COLOR_DARK_BLUE); label.setFont(NengoStyle.FONT_BOLD); labelPanel.add(label); JButton help=new JButton("<html><u>?</u></html>"); help.setFocusable(false); help.setForeground(new java.awt.Color(120,120,180)); help.setBorderPainted(false); help.setContentAreaFilled(false); help.setFocusPainted(false); help.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null,propDescriptor.getTooltip(),propDescriptor.getName(),JOptionPane.INFORMATION_MESSAGE,null); } }); labelPanel.add(help); //labelPanel.add(Box.createHorizontalGlue()); // use this to right-justify question marks labelPanel.setMaximumSize(labelPanel.getMinimumSize()); // use this to keep question marks on left outerPanel.add(labelPanel); innerPanel = new JPanel(); innerPanel.setLayout(new BoxLayout(innerPanel, BoxLayout.X_AXIS)); innerPanel.setAlignmentX(JPanel.LEFT_ALIGNMENT); outerPanel.add(innerPanel); statusMessage = new JLabel(""); statusMessage.setForeground(NengoStyle.COLOR_HIGH_SALIENCE); outerPanel.add(statusMessage); }
diff --git a/src/main/java/com/lair/mtduck/irc/TickerIRCMessenger.java b/src/main/java/com/lair/mtduck/irc/TickerIRCMessenger.java index cf06a59..b1d7e70 100644 --- a/src/main/java/com/lair/mtduck/irc/TickerIRCMessenger.java +++ b/src/main/java/com/lair/mtduck/irc/TickerIRCMessenger.java @@ -1,95 +1,95 @@ package com.lair.mtduck.irc; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.lair.mtduck.mtgox.MtGoxManager; import org.jibble.pircbot.IrcException; import org.jibble.pircbot.PircBot; /** * */ public class TickerIRCMessenger extends PircBot { private static final Logger logger = LoggerFactory.getLogger(MtGoxManager.class); private String host; private String password; private String channel; private int priceUp = 0; private int priceDown = 0; private BigDecimal currentPrice = null; public TickerIRCMessenger(Properties properties) { this.setName("McDuck"); this.host = properties.getProperty("irc.server.host"); this.password = properties.getProperty("irc.server.password"); this.channel = properties.getProperty("irc.channel"); try { this.setEncoding("utf8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } public void connect() throws IrcException, IOException { connect(host, 6667, password); joinChannel(channel); sendMessage(channel, "Coin coin!"); // I'm that annoying :) } public void updateTicker(BigDecimal currentPrice) { this.currentPrice = currentPrice; if (priceUp == 0 && priceDown == 0) { initRefPrice(currentPrice); sendMessage("Current price is " + currentPrice.toPlainString() + ", setting priceUp to " + priceUp + " priceDown to " + priceDown); } else if (currentPrice.compareTo(new BigDecimal(priceUp)) > 0) { sendMessage("Price just broke " + priceUp + " upwards at " + currentPrice.toPlainString() + " !"); priceUp += 5; priceDown += 5; } else if (currentPrice.compareTo(new BigDecimal(priceDown)) < 0) { sendMessage("Price just broke " + priceDown + " downwards at " + currentPrice.toPlainString() + " !"); priceUp -= 5; priceDown -= 5; } } private void initRefPrice(BigDecimal currentPrice) { int result = currentPrice.intValue(); priceUp = result + 10 - (result % 5); priceDown = result - (result % 5); } public void sendMessage(String message) { sendMessage(channel, message); } @Override protected void onMessage(String channel, String sender, String login, String hostname, String message) { switch(message) { case "!price": sendMessage(channel, "Price is currently " + currentPrice); break; case "!refprices": sendMessage(channel, "priceUp is " + priceUp + " priceDown is " + priceDown); break; case "!gtfo": sendMessage(channel, "Okay :("); System.exit(0); break; case "!help": sendMessage(channel, "Available commands : !price !refprices !gtfo"); break; case "McDuck": - sendMessage(channel, "Coin coin ! (Type !help for a list of available commands"); + sendMessage(channel, "Coin coin ! (Type !help for a list of available commands)"); break; } } }
true
true
protected void onMessage(String channel, String sender, String login, String hostname, String message) { switch(message) { case "!price": sendMessage(channel, "Price is currently " + currentPrice); break; case "!refprices": sendMessage(channel, "priceUp is " + priceUp + " priceDown is " + priceDown); break; case "!gtfo": sendMessage(channel, "Okay :("); System.exit(0); break; case "!help": sendMessage(channel, "Available commands : !price !refprices !gtfo"); break; case "McDuck": sendMessage(channel, "Coin coin ! (Type !help for a list of available commands"); break; } }
protected void onMessage(String channel, String sender, String login, String hostname, String message) { switch(message) { case "!price": sendMessage(channel, "Price is currently " + currentPrice); break; case "!refprices": sendMessage(channel, "priceUp is " + priceUp + " priceDown is " + priceDown); break; case "!gtfo": sendMessage(channel, "Okay :("); System.exit(0); break; case "!help": sendMessage(channel, "Available commands : !price !refprices !gtfo"); break; case "McDuck": sendMessage(channel, "Coin coin ! (Type !help for a list of available commands)"); break; } }
diff --git a/CandroidSample/src/com/candroidsample/CaldroidSampleActivity.java b/CandroidSample/src/com/candroidsample/CaldroidSampleActivity.java index 027469f..dca0999 100644 --- a/CandroidSample/src/com/candroidsample/CaldroidSampleActivity.java +++ b/CandroidSample/src/com/candroidsample/CaldroidSampleActivity.java @@ -1,266 +1,266 @@ package com.candroidsample; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import android.annotation.SuppressLint; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTransaction; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.caldroid.CaldroidFragment; import com.caldroid.CaldroidListener; @SuppressLint("SimpleDateFormat") public class CaldroidSampleActivity extends FragmentActivity { private boolean undo = false; private CaldroidFragment caldroidFragment; private CaldroidFragment dialogCaldroidFragment; private void setCustomResourceForDates() { Calendar cal = Calendar.getInstance(); // Min date is last 7 days cal.add(Calendar.DATE, -3); Date blueDate = cal.getTime(); // Max date is next 7 days cal = Calendar.getInstance(); cal.add(Calendar.DATE, 4); Date greenDate = cal.getTime(); if (caldroidFragment != null) { caldroidFragment.setBackgroundResourceForDate(R.color.blue, blueDate); caldroidFragment.setBackgroundResourceForDate(R.color.green, greenDate); caldroidFragment.setTextColorForDate(R.color.white, blueDate); caldroidFragment.setTextColorForDate(R.color.white, greenDate); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy"); // Setup caldroid fragment // **** If you want normal CaldroidFragment, use below line **** caldroidFragment = new CaldroidFragment(); // ////////////////////////////////////////////////////////////////////// // **** This is to show customized fragment. If you want customized // version, uncomment below line **** // caldroidFragment = new CaldroidSampleCustomFragment(); // Setup arguments // If Activity is created after rotation if (savedInstanceState != null) { caldroidFragment.restoreStatesFromKey(savedInstanceState, "CALDROID_SAVED_STATE"); } // If activity is created from fresh else { Bundle args = new Bundle(); Calendar cal = Calendar.getInstance(); args.putInt(CaldroidFragment.MONTH, cal.get(Calendar.MONTH) + 1); args.putInt(CaldroidFragment.YEAR, cal.get(Calendar.YEAR)); args.putBoolean(CaldroidFragment.ENABLE_SWIPE, true); args.putBoolean(CaldroidFragment.FIT_ALL_MONTHS, false); // Uncomment this to customize startDayOfWeek // args.putInt("startDayOfWeek", 3); // Tuesday caldroidFragment.setArguments(args); } setCustomResourceForDates(); // Attach to the activity FragmentTransaction t = getSupportFragmentManager().beginTransaction(); t.replace(R.id.calendar1, caldroidFragment); t.commit(); // Setup listener final CaldroidListener listener = new CaldroidListener() { @Override public void onSelectDate(Date date, View view) { Toast.makeText(getApplicationContext(), formatter.format(date), Toast.LENGTH_SHORT).show(); } @Override public void onChangeMonth(int month, int year) { String text = "month: " + month + " year: " + year; Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show(); } @Override public void onLongClickDate(Date date, View view) { Toast.makeText(getApplicationContext(), "Long click " + formatter.format(date), Toast.LENGTH_SHORT).show(); } }; // Setup Caldroid caldroidFragment.setCaldroidListener(listener); final TextView textView = (TextView) findViewById(R.id.textview); final Button customizeButton = (Button) findViewById(R.id.customize_button); // Customize the calendar customizeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (undo) { customizeButton.setText(getString(R.string.customize)); textView.setText(""); // Reset calendar caldroidFragment.clearDisableDates(); caldroidFragment.clearSelectedDates(); caldroidFragment.setMinDate(null); caldroidFragment.setMaxDate(null); caldroidFragment.setShowNavigationArrows(true); caldroidFragment.setEnableSwipe(true); caldroidFragment.refreshView(); undo = false; return; } // Else undo = true; customizeButton.setText(getString(R.string.undo)); Calendar cal = Calendar.getInstance(); // Min date is last 7 days cal.add(Calendar.DATE, -7); Date minDate = cal.getTime(); // Max date is next 7 days cal = Calendar.getInstance(); cal.add(Calendar.DATE, 14); Date maxDate = cal.getTime(); // Set selected dates // From Date cal = Calendar.getInstance(); cal.add(Calendar.DATE, 2); Date fromDate = cal.getTime(); // To Date cal = Calendar.getInstance(); cal.add(Calendar.DATE, 3); Date toDate = cal.getTime(); // Set disabled dates ArrayList<Date> disabledDates = new ArrayList<Date>(); for (int i = 5; i < 8; i++) { cal = Calendar.getInstance(); cal.add(Calendar.DATE, i); disabledDates.add(cal.getTime()); } // Customize caldroidFragment.setMinDate(minDate); caldroidFragment.setMaxDate(maxDate); caldroidFragment.setDisableDates(disabledDates); caldroidFragment.setSelectedDates(fromDate, toDate); caldroidFragment.setShowNavigationArrows(false); caldroidFragment.setEnableSwipe(false); caldroidFragment.refreshView(); // Move to date - // cal = Calendar.getInstance(); - // cal.add(Calendar.MONTH, 12); - // caldroidFragment.moveToDate(cal.getTime()); +// cal = Calendar.getInstance(); +// cal.add(Calendar.MONTH, 12); +// caldroidFragment.moveToDate(cal.getTime()); String text = "Today: " + formatter.format(new Date()) + "\n"; text += "Min Date: " + formatter.format(minDate) + "\n"; text += "Max Date: " + formatter.format(maxDate) + "\n"; text += "Select From Date: " + formatter.format(fromDate) + "\n"; text += "Select To Date: " + formatter.format(toDate) + "\n"; for (Date date : disabledDates) { text += "Disabled Date: " + formatter.format(date) + "\n"; } textView.setText(text); } }); Button showDialogButton = (Button) findViewById(R.id.show_dialog_button); final Bundle state = savedInstanceState; showDialogButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Setup caldroid to use as dialog dialogCaldroidFragment = new CaldroidFragment(); dialogCaldroidFragment.setCaldroidListener(listener); // If activity is recovered from rotation final String dialogTag = "CALDROID_DIALOG_FRAGMENT"; if (state != null) { dialogCaldroidFragment.restoreDialogStatesFromKey( getSupportFragmentManager(), state, "DIALOG_CALDROID_SAVED_STATE", dialogTag); Bundle args = dialogCaldroidFragment.getArguments(); if (args == null) { args = new Bundle(); dialogCaldroidFragment.setArguments(args); } args.putString(CaldroidFragment.DIALOG_TITLE, "Select a date"); } else { // Setup arguments Bundle bundle = new Bundle(); // Setup dialogTitle bundle.putString(CaldroidFragment.DIALOG_TITLE, "Select a date"); dialogCaldroidFragment.setArguments(bundle); } dialogCaldroidFragment.show(getSupportFragmentManager(), dialogTag); } }); } /** * Save current states of the Caldroid here */ @Override protected void onSaveInstanceState(Bundle outState) { // TODO Auto-generated method stub super.onSaveInstanceState(outState); if (caldroidFragment != null) { caldroidFragment.saveStatesToKey(outState, "CALDROID_SAVED_STATE"); } if (dialogCaldroidFragment != null) { dialogCaldroidFragment.saveStatesToKey(outState, "DIALOG_CALDROID_SAVED_STATE"); } } }
true
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy"); // Setup caldroid fragment // **** If you want normal CaldroidFragment, use below line **** caldroidFragment = new CaldroidFragment(); // ////////////////////////////////////////////////////////////////////// // **** This is to show customized fragment. If you want customized // version, uncomment below line **** // caldroidFragment = new CaldroidSampleCustomFragment(); // Setup arguments // If Activity is created after rotation if (savedInstanceState != null) { caldroidFragment.restoreStatesFromKey(savedInstanceState, "CALDROID_SAVED_STATE"); } // If activity is created from fresh else { Bundle args = new Bundle(); Calendar cal = Calendar.getInstance(); args.putInt(CaldroidFragment.MONTH, cal.get(Calendar.MONTH) + 1); args.putInt(CaldroidFragment.YEAR, cal.get(Calendar.YEAR)); args.putBoolean(CaldroidFragment.ENABLE_SWIPE, true); args.putBoolean(CaldroidFragment.FIT_ALL_MONTHS, false); // Uncomment this to customize startDayOfWeek // args.putInt("startDayOfWeek", 3); // Tuesday caldroidFragment.setArguments(args); } setCustomResourceForDates(); // Attach to the activity FragmentTransaction t = getSupportFragmentManager().beginTransaction(); t.replace(R.id.calendar1, caldroidFragment); t.commit(); // Setup listener final CaldroidListener listener = new CaldroidListener() { @Override public void onSelectDate(Date date, View view) { Toast.makeText(getApplicationContext(), formatter.format(date), Toast.LENGTH_SHORT).show(); } @Override public void onChangeMonth(int month, int year) { String text = "month: " + month + " year: " + year; Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show(); } @Override public void onLongClickDate(Date date, View view) { Toast.makeText(getApplicationContext(), "Long click " + formatter.format(date), Toast.LENGTH_SHORT).show(); } }; // Setup Caldroid caldroidFragment.setCaldroidListener(listener); final TextView textView = (TextView) findViewById(R.id.textview); final Button customizeButton = (Button) findViewById(R.id.customize_button); // Customize the calendar customizeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (undo) { customizeButton.setText(getString(R.string.customize)); textView.setText(""); // Reset calendar caldroidFragment.clearDisableDates(); caldroidFragment.clearSelectedDates(); caldroidFragment.setMinDate(null); caldroidFragment.setMaxDate(null); caldroidFragment.setShowNavigationArrows(true); caldroidFragment.setEnableSwipe(true); caldroidFragment.refreshView(); undo = false; return; } // Else undo = true; customizeButton.setText(getString(R.string.undo)); Calendar cal = Calendar.getInstance(); // Min date is last 7 days cal.add(Calendar.DATE, -7); Date minDate = cal.getTime(); // Max date is next 7 days cal = Calendar.getInstance(); cal.add(Calendar.DATE, 14); Date maxDate = cal.getTime(); // Set selected dates // From Date cal = Calendar.getInstance(); cal.add(Calendar.DATE, 2); Date fromDate = cal.getTime(); // To Date cal = Calendar.getInstance(); cal.add(Calendar.DATE, 3); Date toDate = cal.getTime(); // Set disabled dates ArrayList<Date> disabledDates = new ArrayList<Date>(); for (int i = 5; i < 8; i++) { cal = Calendar.getInstance(); cal.add(Calendar.DATE, i); disabledDates.add(cal.getTime()); } // Customize caldroidFragment.setMinDate(minDate); caldroidFragment.setMaxDate(maxDate); caldroidFragment.setDisableDates(disabledDates); caldroidFragment.setSelectedDates(fromDate, toDate); caldroidFragment.setShowNavigationArrows(false); caldroidFragment.setEnableSwipe(false); caldroidFragment.refreshView(); // Move to date // cal = Calendar.getInstance(); // cal.add(Calendar.MONTH, 12); // caldroidFragment.moveToDate(cal.getTime()); String text = "Today: " + formatter.format(new Date()) + "\n"; text += "Min Date: " + formatter.format(minDate) + "\n"; text += "Max Date: " + formatter.format(maxDate) + "\n"; text += "Select From Date: " + formatter.format(fromDate) + "\n"; text += "Select To Date: " + formatter.format(toDate) + "\n"; for (Date date : disabledDates) { text += "Disabled Date: " + formatter.format(date) + "\n"; } textView.setText(text); } }); Button showDialogButton = (Button) findViewById(R.id.show_dialog_button); final Bundle state = savedInstanceState; showDialogButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Setup caldroid to use as dialog dialogCaldroidFragment = new CaldroidFragment(); dialogCaldroidFragment.setCaldroidListener(listener); // If activity is recovered from rotation final String dialogTag = "CALDROID_DIALOG_FRAGMENT"; if (state != null) { dialogCaldroidFragment.restoreDialogStatesFromKey( getSupportFragmentManager(), state, "DIALOG_CALDROID_SAVED_STATE", dialogTag); Bundle args = dialogCaldroidFragment.getArguments(); if (args == null) { args = new Bundle(); dialogCaldroidFragment.setArguments(args); } args.putString(CaldroidFragment.DIALOG_TITLE, "Select a date"); } else { // Setup arguments Bundle bundle = new Bundle(); // Setup dialogTitle bundle.putString(CaldroidFragment.DIALOG_TITLE, "Select a date"); dialogCaldroidFragment.setArguments(bundle); } dialogCaldroidFragment.show(getSupportFragmentManager(), dialogTag); } }); }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy"); // Setup caldroid fragment // **** If you want normal CaldroidFragment, use below line **** caldroidFragment = new CaldroidFragment(); // ////////////////////////////////////////////////////////////////////// // **** This is to show customized fragment. If you want customized // version, uncomment below line **** // caldroidFragment = new CaldroidSampleCustomFragment(); // Setup arguments // If Activity is created after rotation if (savedInstanceState != null) { caldroidFragment.restoreStatesFromKey(savedInstanceState, "CALDROID_SAVED_STATE"); } // If activity is created from fresh else { Bundle args = new Bundle(); Calendar cal = Calendar.getInstance(); args.putInt(CaldroidFragment.MONTH, cal.get(Calendar.MONTH) + 1); args.putInt(CaldroidFragment.YEAR, cal.get(Calendar.YEAR)); args.putBoolean(CaldroidFragment.ENABLE_SWIPE, true); args.putBoolean(CaldroidFragment.FIT_ALL_MONTHS, false); // Uncomment this to customize startDayOfWeek // args.putInt("startDayOfWeek", 3); // Tuesday caldroidFragment.setArguments(args); } setCustomResourceForDates(); // Attach to the activity FragmentTransaction t = getSupportFragmentManager().beginTransaction(); t.replace(R.id.calendar1, caldroidFragment); t.commit(); // Setup listener final CaldroidListener listener = new CaldroidListener() { @Override public void onSelectDate(Date date, View view) { Toast.makeText(getApplicationContext(), formatter.format(date), Toast.LENGTH_SHORT).show(); } @Override public void onChangeMonth(int month, int year) { String text = "month: " + month + " year: " + year; Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show(); } @Override public void onLongClickDate(Date date, View view) { Toast.makeText(getApplicationContext(), "Long click " + formatter.format(date), Toast.LENGTH_SHORT).show(); } }; // Setup Caldroid caldroidFragment.setCaldroidListener(listener); final TextView textView = (TextView) findViewById(R.id.textview); final Button customizeButton = (Button) findViewById(R.id.customize_button); // Customize the calendar customizeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (undo) { customizeButton.setText(getString(R.string.customize)); textView.setText(""); // Reset calendar caldroidFragment.clearDisableDates(); caldroidFragment.clearSelectedDates(); caldroidFragment.setMinDate(null); caldroidFragment.setMaxDate(null); caldroidFragment.setShowNavigationArrows(true); caldroidFragment.setEnableSwipe(true); caldroidFragment.refreshView(); undo = false; return; } // Else undo = true; customizeButton.setText(getString(R.string.undo)); Calendar cal = Calendar.getInstance(); // Min date is last 7 days cal.add(Calendar.DATE, -7); Date minDate = cal.getTime(); // Max date is next 7 days cal = Calendar.getInstance(); cal.add(Calendar.DATE, 14); Date maxDate = cal.getTime(); // Set selected dates // From Date cal = Calendar.getInstance(); cal.add(Calendar.DATE, 2); Date fromDate = cal.getTime(); // To Date cal = Calendar.getInstance(); cal.add(Calendar.DATE, 3); Date toDate = cal.getTime(); // Set disabled dates ArrayList<Date> disabledDates = new ArrayList<Date>(); for (int i = 5; i < 8; i++) { cal = Calendar.getInstance(); cal.add(Calendar.DATE, i); disabledDates.add(cal.getTime()); } // Customize caldroidFragment.setMinDate(minDate); caldroidFragment.setMaxDate(maxDate); caldroidFragment.setDisableDates(disabledDates); caldroidFragment.setSelectedDates(fromDate, toDate); caldroidFragment.setShowNavigationArrows(false); caldroidFragment.setEnableSwipe(false); caldroidFragment.refreshView(); // Move to date // cal = Calendar.getInstance(); // cal.add(Calendar.MONTH, 12); // caldroidFragment.moveToDate(cal.getTime()); String text = "Today: " + formatter.format(new Date()) + "\n"; text += "Min Date: " + formatter.format(minDate) + "\n"; text += "Max Date: " + formatter.format(maxDate) + "\n"; text += "Select From Date: " + formatter.format(fromDate) + "\n"; text += "Select To Date: " + formatter.format(toDate) + "\n"; for (Date date : disabledDates) { text += "Disabled Date: " + formatter.format(date) + "\n"; } textView.setText(text); } }); Button showDialogButton = (Button) findViewById(R.id.show_dialog_button); final Bundle state = savedInstanceState; showDialogButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Setup caldroid to use as dialog dialogCaldroidFragment = new CaldroidFragment(); dialogCaldroidFragment.setCaldroidListener(listener); // If activity is recovered from rotation final String dialogTag = "CALDROID_DIALOG_FRAGMENT"; if (state != null) { dialogCaldroidFragment.restoreDialogStatesFromKey( getSupportFragmentManager(), state, "DIALOG_CALDROID_SAVED_STATE", dialogTag); Bundle args = dialogCaldroidFragment.getArguments(); if (args == null) { args = new Bundle(); dialogCaldroidFragment.setArguments(args); } args.putString(CaldroidFragment.DIALOG_TITLE, "Select a date"); } else { // Setup arguments Bundle bundle = new Bundle(); // Setup dialogTitle bundle.putString(CaldroidFragment.DIALOG_TITLE, "Select a date"); dialogCaldroidFragment.setArguments(bundle); } dialogCaldroidFragment.show(getSupportFragmentManager(), dialogTag); } }); }
diff --git a/src/main/java/AssistedScene/GiftHouse.java b/src/main/java/AssistedScene/GiftHouse.java index 934e8a3..8588783 100644 --- a/src/main/java/AssistedScene/GiftHouse.java +++ b/src/main/java/AssistedScene/GiftHouse.java @@ -1,34 +1,34 @@ package AssistedScene; import Application.GameException; import Estate.EstateManager; import Player.Movement; import Prop.PropManager; import UI.CommandLine; public class GiftHouse implements Scene { private final GiftSelectorFactory factory; private final CommandLine commandLine = new CommandLine(); public GiftHouse(PropManager propManager, EstateManager estateManager) { factory = new GiftSelectorFactory(propManager, estateManager); } public void handle(String roleName, Movement movement) { showPromptMessage(); handleInput(roleName); } private void handleInput(String roleName) { try { factory.get(commandLine.waitForInput("请输入您要选择的礼品编号:")).select(roleName); } catch (GameException e) { - commandLine.output(e.getMessage()); + commandLine.outputInNewline(e.toString()); } } private void showPromptMessage() { commandLine.outputInNewline("欢迎光临礼品屋,请选择一件您 喜欢的礼品:"); commandLine.outputInNewline("礼品\t编号\n奖 金\t1\n点数卡\t2\n福 神\t3\n"); } }
true
true
private void handleInput(String roleName) { try { factory.get(commandLine.waitForInput("请输入您要选择的礼品编号:")).select(roleName); } catch (GameException e) { commandLine.output(e.getMessage()); } }
private void handleInput(String roleName) { try { factory.get(commandLine.waitForInput("请输入您要选择的礼品编号:")).select(roleName); } catch (GameException e) { commandLine.outputInNewline(e.toString()); } }
diff --git a/src/com/orangeleap/tangerine/service/rule/DroolsRuleAgent.java b/src/com/orangeleap/tangerine/service/rule/DroolsRuleAgent.java index 7679818c..0c93d89b 100644 --- a/src/com/orangeleap/tangerine/service/rule/DroolsRuleAgent.java +++ b/src/com/orangeleap/tangerine/service/rule/DroolsRuleAgent.java @@ -1,58 +1,58 @@ package com.orangeleap.tangerine.service.rule; import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.drools.agent.RuleAgent; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Service; @Service("droolsRuleAgent") public class DroolsRuleAgent implements ApplicationContextAware { private static final Log logger = LogFactory.getLog(DroolsRuleAgent.class); private RuleAgent ruleAgent = null; private ApplicationContext applicationContext; public static Properties getDroolsProperties() { String host = System.getProperty("drools.host"); String port = System.getProperty("drools.port"); // String url = "http://"+host+":"+port+"/drools/org.drools.brms.JBRMS/package/com.mpower/NEWEST"; // logger.debug("Setting Drools URL to "+url); Properties props = new Properties(); // props.put("url", url); props.put("newInstance", "false"); props.put("name","orangeleap"); -// props.put("poll", "30"); - props.put("cache", "/usr/local/drools/cache"); - props.put("dir","/usr/local/drools/rules"); + props.put("poll", System.getProperty("drools.pollinterval")); + props.put("cache", System.getProperty("drools.cachedir")); + props.put("dir",System.getProperty("drools.packagedir")); return props; } public DroolsRuleAgent() { } RuleAgent getRuleAgent() { if (ruleAgent == null) ruleAgent = RuleAgent.newRuleAgent(getDroolsProperties()); return ruleAgent; } void setRuleAgent(RuleAgent agent) { ruleAgent = agent; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }
true
true
public static Properties getDroolsProperties() { String host = System.getProperty("drools.host"); String port = System.getProperty("drools.port"); // String url = "http://"+host+":"+port+"/drools/org.drools.brms.JBRMS/package/com.mpower/NEWEST"; // logger.debug("Setting Drools URL to "+url); Properties props = new Properties(); // props.put("url", url); props.put("newInstance", "false"); props.put("name","orangeleap"); // props.put("poll", "30"); props.put("cache", "/usr/local/drools/cache"); props.put("dir","/usr/local/drools/rules"); return props; }
public static Properties getDroolsProperties() { String host = System.getProperty("drools.host"); String port = System.getProperty("drools.port"); // String url = "http://"+host+":"+port+"/drools/org.drools.brms.JBRMS/package/com.mpower/NEWEST"; // logger.debug("Setting Drools URL to "+url); Properties props = new Properties(); // props.put("url", url); props.put("newInstance", "false"); props.put("name","orangeleap"); props.put("poll", System.getProperty("drools.pollinterval")); props.put("cache", System.getProperty("drools.cachedir")); props.put("dir",System.getProperty("drools.packagedir")); return props; }
diff --git a/uk.ac.diamond.scisoft.analysis/src/uk/ac/diamond/scisoft/analysis/io/JavaImageSaver.java b/uk.ac.diamond.scisoft.analysis/src/uk/ac/diamond/scisoft/analysis/io/JavaImageSaver.java index 128a792cc..aaaf8d3ca 100644 --- a/uk.ac.diamond.scisoft.analysis/src/uk/ac/diamond/scisoft/analysis/io/JavaImageSaver.java +++ b/uk.ac.diamond.scisoft.analysis/src/uk/ac/diamond/scisoft/analysis/io/JavaImageSaver.java @@ -1,159 +1,159 @@ /* * Copyright 2011 Diamond Light Source 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 uk.ac.diamond.scisoft.analysis.io; import gda.analysis.io.IFileSaver; import gda.analysis.io.ScanFileHolderException; import java.awt.image.BufferedImage; import java.awt.image.RenderedImage; import java.io.File; import java.text.DecimalFormat; import java.text.NumberFormat; import javax.imageio.ImageIO; import javax.media.jai.TiledImage; import uk.ac.diamond.scisoft.analysis.dataset.AWTImageUtils; import uk.ac.diamond.scisoft.analysis.dataset.AbstractDataset; /** * Class that saves data from DataHolder using native Java ImageIO library * with built-in image reader/writer * * If the DataHolder contains more than one dataset then multiple image * files are saved with names labelled from 00001 to 99999. */ public class JavaImageSaver implements IFileSaver { static { ImageIO.scanForPlugins(); // in case the ImageIO jar has not been loaded yet } private String fileName = ""; private String fileType = ""; protected double maxVal; protected boolean unsigned = false; private int numBits; /** * @param FileName * which is the name of the file being passed to this class. * @param FileType * type of file to be saved * @param NumBits * number of bits in each pixel (greyscale representation); use > 32 for floats (TIFF only) * @param asUnsigned * treat dataset items as unsigned (unless saving as floats) */ public JavaImageSaver(String FileName, String FileType, int NumBits, boolean asUnsigned) { fileName = FileName; fileType = FileType; // format name numBits = NumBits; if (numBits <= 32) { maxVal = (1L << NumBits) - 1.0; // 2^NumBits - 1 (use long in case of overflow) unsigned = asUnsigned; } else { maxVal = 1.0; // flag to use doubles (TIFF only) } } @Override public void saveFile(DataHolder dh) throws ScanFileHolderException { File f = null; if (numBits <= 0) { throw new ScanFileHolderException( "Number of bits specified must be greater than 0"); } for (int i = 0, imax = dh.size(); i < imax; i++) { try { String name = null; if (imax == 1) { name = fileName; } else { try { name = fileName.substring(0, (fileName.lastIndexOf("."))); } catch (Exception e) { name = fileName; } NumberFormat format = new DecimalFormat("00000"); name = name + format.format(i + 1); } int l = name.lastIndexOf("."); if (l < 0) { name = name + "." + fileType; } f = new File(name); AbstractDataset data = dh.getDataset(i); if (numBits <= 16) { // test to see if the values of the data are within the // capabilities of format if (maxVal > 0 && data.max().doubleValue() > maxVal) { - throw new ScanFileHolderException("The value of a pixel exceeds the maximum value that " - + fileType + " is capable of handling. To save a " - + fileType + " it is recommended to use a ScaledSaver class. File " + throw new ScanFileHolderException("The value of a pixel exceeds the maximum value that " + + fileType + " is capable of handling. To save a " + + fileType + " it is recommended to use a ScaledSaver class. File " + fileName + " not written"); } if (unsigned && data.min().doubleValue() < 0) { throw new ScanFileHolderException( "The value of a pixel is less than 0. Recommended using a ScaledSaver class."); } BufferedImage image = AWTImageUtils.makeBufferedImage(data, numBits); if (image == null) { throw new ScanFileHolderException("Unable to create a buffered image to save file type"); } boolean w = writeImageLocked(image, fileType, f); if (!w) throw new ScanFileHolderException("No writer for '" + fileName + "' of type " + fileType); } else { TiledImage image = AWTImageUtils.makeTiledImage(data, numBits); if (image == null) { throw new ScanFileHolderException("Unable to create a tiled image to save file type"); } boolean w = writeImageLocked(image, fileType, f); if (!w) throw new ScanFileHolderException("No writer for '" + fileName + "' of type " + fileType); } } catch (ScanFileHolderException e) { throw e; } catch (Exception e) { throw new ScanFileHolderException("Error saving file '" + fileName + "'", e); } } } private boolean writeImageLocked(RenderedImage image, String fileType, File f) throws Exception { // Separate method added as may add file locking option. return ImageIO.write(image, fileType, f); } }
true
true
public void saveFile(DataHolder dh) throws ScanFileHolderException { File f = null; if (numBits <= 0) { throw new ScanFileHolderException( "Number of bits specified must be greater than 0"); } for (int i = 0, imax = dh.size(); i < imax; i++) { try { String name = null; if (imax == 1) { name = fileName; } else { try { name = fileName.substring(0, (fileName.lastIndexOf("."))); } catch (Exception e) { name = fileName; } NumberFormat format = new DecimalFormat("00000"); name = name + format.format(i + 1); } int l = name.lastIndexOf("."); if (l < 0) { name = name + "." + fileType; } f = new File(name); AbstractDataset data = dh.getDataset(i); if (numBits <= 16) { // test to see if the values of the data are within the // capabilities of format if (maxVal > 0 && data.max().doubleValue() > maxVal) { throw new ScanFileHolderException("The value of a pixel exceeds the maximum value that " + fileType + " is capable of handling. To save a " + fileType + " it is recommended to use a ScaledSaver class. File " + fileName + " not written"); } if (unsigned && data.min().doubleValue() < 0) { throw new ScanFileHolderException( "The value of a pixel is less than 0. Recommended using a ScaledSaver class."); } BufferedImage image = AWTImageUtils.makeBufferedImage(data, numBits); if (image == null) { throw new ScanFileHolderException("Unable to create a buffered image to save file type"); } boolean w = writeImageLocked(image, fileType, f); if (!w) throw new ScanFileHolderException("No writer for '" + fileName + "' of type " + fileType); } else { TiledImage image = AWTImageUtils.makeTiledImage(data, numBits); if (image == null) { throw new ScanFileHolderException("Unable to create a tiled image to save file type"); } boolean w = writeImageLocked(image, fileType, f); if (!w) throw new ScanFileHolderException("No writer for '" + fileName + "' of type " + fileType); } } catch (ScanFileHolderException e) { throw e; } catch (Exception e) { throw new ScanFileHolderException("Error saving file '" + fileName + "'", e); } } }
public void saveFile(DataHolder dh) throws ScanFileHolderException { File f = null; if (numBits <= 0) { throw new ScanFileHolderException( "Number of bits specified must be greater than 0"); } for (int i = 0, imax = dh.size(); i < imax; i++) { try { String name = null; if (imax == 1) { name = fileName; } else { try { name = fileName.substring(0, (fileName.lastIndexOf("."))); } catch (Exception e) { name = fileName; } NumberFormat format = new DecimalFormat("00000"); name = name + format.format(i + 1); } int l = name.lastIndexOf("."); if (l < 0) { name = name + "." + fileType; } f = new File(name); AbstractDataset data = dh.getDataset(i); if (numBits <= 16) { // test to see if the values of the data are within the // capabilities of format if (maxVal > 0 && data.max().doubleValue() > maxVal) { throw new ScanFileHolderException("The value of a pixel exceeds the maximum value that " + fileType + " is capable of handling. To save a " + fileType + " it is recommended to use a ScaledSaver class. File " + fileName + " not written"); } if (unsigned && data.min().doubleValue() < 0) { throw new ScanFileHolderException( "The value of a pixel is less than 0. Recommended using a ScaledSaver class."); } BufferedImage image = AWTImageUtils.makeBufferedImage(data, numBits); if (image == null) { throw new ScanFileHolderException("Unable to create a buffered image to save file type"); } boolean w = writeImageLocked(image, fileType, f); if (!w) throw new ScanFileHolderException("No writer for '" + fileName + "' of type " + fileType); } else { TiledImage image = AWTImageUtils.makeTiledImage(data, numBits); if (image == null) { throw new ScanFileHolderException("Unable to create a tiled image to save file type"); } boolean w = writeImageLocked(image, fileType, f); if (!w) throw new ScanFileHolderException("No writer for '" + fileName + "' of type " + fileType); } } catch (ScanFileHolderException e) { throw e; } catch (Exception e) { throw new ScanFileHolderException("Error saving file '" + fileName + "'", e); } } }
diff --git a/src/main/java/de/uniba/wiai/dsg/betsy/virtual/host/engines/VirtualActiveBpelEngine.java b/src/main/java/de/uniba/wiai/dsg/betsy/virtual/host/engines/VirtualActiveBpelEngine.java index dbe4ec26..0bf955b6 100644 --- a/src/main/java/de/uniba/wiai/dsg/betsy/virtual/host/engines/VirtualActiveBpelEngine.java +++ b/src/main/java/de/uniba/wiai/dsg/betsy/virtual/host/engines/VirtualActiveBpelEngine.java @@ -1,100 +1,102 @@ package de.uniba.wiai.dsg.betsy.virtual.host.engines; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import betsy.data.Process; import betsy.data.engines.activeBpel.ActiveBpelEngine; import de.uniba.wiai.dsg.betsy.Configuration; import de.uniba.wiai.dsg.betsy.virtual.host.VirtualBoxController; import de.uniba.wiai.dsg.betsy.virtual.host.VirtualEngine; import de.uniba.wiai.dsg.betsy.virtual.host.VirtualEnginePackageBuilder; import de.uniba.wiai.dsg.betsy.virtual.host.utils.ServiceAddress; public class VirtualActiveBpelEngine extends VirtualEngine { private final ActiveBpelEngine defaultEngine; private final Configuration config = Configuration.getInstance(); public VirtualActiveBpelEngine(VirtualBoxController vbc) { super(vbc); this.defaultEngine = new ActiveBpelEngine(); this.defaultEngine.setPackageBuilder(new VirtualEnginePackageBuilder()); } @Override public String getName() { return "active_bpel_v"; } @Override public List<ServiceAddress> getVerifiableServiceAddresses() { List<ServiceAddress> saList = new LinkedList<>(); saList.add(new ServiceAddress( - "http://localhost:8080/active-bpel/services", "Running")); + "http://localhost:8080/active-bpel/services")); + saList.add(new ServiceAddress("http://localhost:8080/BpelAdmin/", + "Running")); return saList; } @Override public Set<Integer> getRequiredPorts() { Set<Integer> portList = new HashSet<>(); portList.add(8080); return portList; } @Override public Integer getEndpointPort() { return 8080; } @Override public String getEndpointPath(Process process) { return "/active-bpel/services/" + process.getBpelFileNameWithoutExtension() + "TestInterfaceService"; } @Override public void buildArchives(Process process) { // use default engine's operations defaultEngine.buildArchives(process); } @Override public String getXsltPath() { return "src/main/xslt/" + defaultEngine.getName(); } @Override public void onPostDeployment() { // not required. deploy is in sync and does not return before engine is // deployed } @Override public void onPostDeployment(Process process) { // not required. deploy is in sync and does not return before process is // deployed } @Override public String getVMDeploymentDir() { return config.getValueAsString( "virtualisation.engines.active-bpel_v.deploymentDir", "/usr/share/tomcat5.5/bpr"); } @Override public String getVMLogfileDir() { return config.getValueAsString( "virtualisation.engines.active-bpel_v.logfileDir", "/usr/share/tomcat5.5/logs"); } @Override public String getTargetPackageExtension() { return "bpr"; } }
true
true
public List<ServiceAddress> getVerifiableServiceAddresses() { List<ServiceAddress> saList = new LinkedList<>(); saList.add(new ServiceAddress( "http://localhost:8080/active-bpel/services", "Running")); return saList; }
public List<ServiceAddress> getVerifiableServiceAddresses() { List<ServiceAddress> saList = new LinkedList<>(); saList.add(new ServiceAddress( "http://localhost:8080/active-bpel/services")); saList.add(new ServiceAddress("http://localhost:8080/BpelAdmin/", "Running")); return saList; }
diff --git a/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/study/StudyFile.java b/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/study/StudyFile.java index c7ed5596f..7af2f3796 100644 --- a/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/study/StudyFile.java +++ b/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/study/StudyFile.java @@ -1,572 +1,572 @@ /* * Dataverse Network - A web application to distribute, share and analyze quantitative data. * Copyright (C) 2007 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses * or write to the Free Software Foundation,Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301 USA */ /* * StudyFile.java * * Created on July 28, 2006, 2:59 PM * */ package edu.harvard.iq.dvn.core.study; import edu.harvard.iq.dvn.core.admin.NetworkRoleServiceLocal; import edu.harvard.iq.dvn.core.admin.RoleServiceLocal; import edu.harvard.iq.dvn.core.admin.UserGroup; import edu.harvard.iq.dvn.core.admin.VDCRole; import edu.harvard.iq.dvn.core.admin.VDCUser; import edu.harvard.iq.dvn.core.vdc.HarvestingDataverse; import edu.harvard.iq.dvn.core.vdc.VDC; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import javax.persistence.*; /** * * @author Ellen Kraffmiller */ @Entity @Inheritance(strategy=InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name="fileClass") public abstract class StudyFile implements Serializable { private String fileType; @Column(columnDefinition="TEXT") private String fileSystemLocation; private String originalFileType; private String unf; @OneToMany(mappedBy="studyFile", cascade={CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST}) private List<FileMetadata> fileMetadatas; /** * Creates a new instance of StudyFile */ public StudyFile() { fileMetadatas = new ArrayList<FileMetadata>(); } public StudyFile(Study study) { this.setStudy( study ); study.getStudyFiles().add(this); StudyFileActivity sfActivity = new StudyFileActivity(); this.setStudyFileActivity(sfActivity); sfActivity.setStudyFile(this); sfActivity.setStudy(this.getStudy()); //TODO: add both sides of relationship here //this.getStudy().getStudyFileActivity().add(sfActivity); fileMetadatas = new ArrayList<FileMetadata>(); } public List<FileMetadata> getFileMetadatas() { return fileMetadatas; } public void setFileMetadatas(List<FileMetadata> fileMetadatas) { this.fileMetadatas = fileMetadatas; } public String getFileType() { return fileType; } public void setFileType(String fileType) { this.fileType = fileType; } public String getFileSystemLocation() { return fileSystemLocation; } public void setFileSystemLocation(String fileSystemLocation) { this.fileSystemLocation = fileSystemLocation; } public String getOriginalFileType() { return originalFileType; } public void setOriginalFileType(String originalFileType) { this.originalFileType = originalFileType; } @ManyToOne(cascade = {CascadeType.MERGE}) @JoinColumn(nullable=false) private Study study; public Study getStudy() { return study; } public void setStudy(Study study) { this.study = study; } /** * Holds value of property displayOrder. */ private int displayOrder; /** * Getter for property displayOrder. * @return Value of property displayOrder. */ public int getDisplayOrder() { return this.displayOrder; } /** * Setter for property displayOrder. * @param displayOrder New value of property displayOrder. */ public void setDisplayOrder(int displayOrder) { this.displayOrder = displayOrder; } /** * Holds value of property id. */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; /** * Getter for property id. * @return Value of property id. */ public Long getId() { return this.id; } /** * Setter for property id. * @param id New value of property id. */ public void setId(Long id) { this.id = id; } /** * Holds value of property version. */ @Version private Long version; /** * Getter for property version. * @return Value of property version. */ public Long getVersion() { return this.version; } /** * Setter for property version. * @param version New value of property version. */ public void setVersion(Long version) { this.version = version; } /** * Holds value of property restricted. */ private boolean restricted; /** * Getter for property restricted. * @return Value of property restricted. */ public boolean isRestricted() { return this.restricted; } /** * Setter for property restricted. * @param restricted New value of property restricted. */ public void setRestricted(boolean restricted) { this.restricted = restricted; } /** * Holds value of property allowedGroups. */ @ManyToMany(cascade = {CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST}) private Collection<UserGroup> allowedGroups; /** * Getter for property allowedGroups. * @return Value of property allowedGroups. */ public Collection<UserGroup> getAllowedGroups() { return this.allowedGroups; } /** * Setter for property allowedGroups. * @param allowedGroups New value of property allowedGroups. */ public void setAllowedGroups(Collection<UserGroup> allowedGroups) { this.allowedGroups = allowedGroups; } /** * Holds value of property allowedUsers. */ @ManyToMany(cascade = {CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST}) private Collection<VDCUser> allowedUsers; /** * Getter for property allowedUsers. * @return Value of property allowedUsers. */ public Collection<VDCUser> getAllowedUsers() { return this.allowedUsers; } /** * Setter for property allowedUsers. * @param allowedUsers New value of property allowedUsers. */ public void setAllowedUsers(Collection<VDCUser> allowedUsers) { this.allowedUsers = allowedUsers; } /** * Holds value of property requestAccess. * If this is true, then the user can send a request to the vdc administrator * to be allowed to view the file. */ private boolean requestAccess; /** * Getter for property requestAccess. * @return Value of property requestAccess. */ public boolean isRequestAccess() { return this.requestAccess; } /** * Setter for property requestAccess. * @param requestAccess New value of property requestAccess. */ public void setRequestAccess(boolean requestAccess) { this.requestAccess = requestAccess; } /** * Holds value of property allowAccessRequest. */ private boolean allowAccessRequest; /** * Getter for property allowAccessRequest. * @return Value of property allowAccessRequest. */ public boolean isAllowAccessRequest() { return this.allowAccessRequest; } /** * Setter for property allowAccessRequest. * @param allowAccessRequest New value of property allowAccessRequest. */ public void setAllowAccessRequest(boolean allowAccessRequest) { this.allowAccessRequest = allowAccessRequest; } /** * Holds value of property dataTable. */ @OneToMany(mappedBy = "studyFile", cascade = {CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST}) private List<DataTable> dataTables; public List<DataTable> getDataTables() { return dataTables; } public void setDataTables(List<DataTable> dataTables) { this.dataTables = dataTables; } public boolean isSubsetRestrictedForUser(VDCUser user, VDC vdc, UserGroup ipUserGroup) { // the restrictions should be checked on the owner of the study, not the currentVDC (needs cleanup) VDC owner = this.getStudy().getOwner(); if (owner.isHarvestingDv()) { HarvestingDataverse hd = owner.getHarvestingDataverse(); return hd.isSubsetRestrictedForUser(user, ipUserGroup); } else { return isFileRestrictedForUser(user, owner, ipUserGroup); } } public boolean isFileRestrictedForUser(VDCUser user, VDC vdc, UserGroup ipUserGroup) { // the restrictions should be checked on the owner of the study, not the currentVDC (needs cleanup) vdc = this.getStudy().getOwner(); // first check if study is restricted, regardless of file permissions Study study = getStudy(); - if (study.isStudyRestrictedForUser( user)) { + if (study.isStudyRestrictedForUser( user, ipUserGroup)) { return true; } // then check dataverse level file permisssions if (vdc.areFilesRestrictedForUser(user, ipUserGroup)) { return true; } // otherwise check for restriction on file itself if (isRestricted()) { if (user == null) { if (ipUserGroup == null) { return true; } else { Iterator iter = this.getAllowedGroups().iterator(); while (iter.hasNext()) { UserGroup allowedGroup = (UserGroup) iter.next(); if (allowedGroup.equals(ipUserGroup)) { return false; } } return true; } } // 1. check if study is restricted (this part was moved a little higher; still need more cleanup) // 2. check network role if (user.getNetworkRole() != null && user.getNetworkRole().getName().equals(NetworkRoleServiceLocal.ADMIN)) { // If you are network admin, you can do anything! return false; } // 3. check vdc role VDCRole userRole = user.getVDCRole(vdc); if (userRole != null) { String userRoleName = userRole.getRole().getName(); if (userRoleName.equals(RoleServiceLocal.ADMIN) || userRoleName.equals(RoleServiceLocal.CURATOR)) { return false; } } //4. check if creator if (user.getId().equals(this.getStudy().getCreator().getId())) { return false; } // 5. check user Iterator iter = this.getAllowedUsers().iterator(); while (iter.hasNext()) { VDCUser allowedUser = (VDCUser) iter.next(); if (allowedUser.getId().equals(user.getId())) { return false; } } // 6. check groups iter = this.getAllowedGroups().iterator(); while (iter.hasNext()) { UserGroup allowedGroup = (UserGroup) iter.next(); if (user.getUserGroups().contains(allowedGroup)) { return false; } } return true; } else { return false; } } public boolean isUserInAllowedUsers(Long userId) { for (Iterator it = allowedUsers.iterator(); it.hasNext();) { VDCUser elem = (VDCUser) it.next(); if (elem.getId().equals(userId)) { return true; } } return false; } public boolean isGroupInAllowedGroups(Long groupId) { for (Iterator it = allowedGroups.iterator(); it.hasNext();) { UserGroup elem = (UserGroup) it.next(); if (elem.getId().equals(groupId)) { return true; } } return false; } /** * Holds value of property fileSystemName. */ private String fileSystemName; /** * Getter for property fileSystemName. * @return Value of property fileSystemName. */ public String getFileSystemName() { return this.fileSystemName; } /** * Setter for property fileSystemName. * @param fileSystemName New value of property fileSystemName. */ public void setFileSystemName(String fileSystemName) { this.fileSystemName = fileSystemName; } public boolean isRemote() { return fileSystemLocation != null && (fileSystemLocation.startsWith("http:") || fileSystemLocation.startsWith("https:") || fileSystemLocation.startsWith("ftp:")); } public int hashCode() { int hash = 0; hash += (this.id != null ? this.id.hashCode() : 0); return hash; } public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof StudyFile)) { return false; } StudyFile other = (StudyFile) object; if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) { return false; } return true; } @OneToOne(mappedBy = "studyFile", cascade = {CascadeType.REMOVE, CascadeType.MERGE, CascadeType.PERSIST}) private StudyFileActivity studyFileActivity; public StudyFileActivity getStudyFileActivity() { return studyFileActivity; } public void setStudyFileActivity(StudyFileActivity studyFileActivity) { this.studyFileActivity = studyFileActivity; } public String getUnf() { return this.unf; } public void setUnf(String unf) { this.unf = unf; } public abstract boolean isSubsettable(); public abstract boolean isUNFable(); public void clearData() { for (DataTable elem : this.getDataTables()) { if (elem != null && elem.getDataVariables() != null) { elem.getDataVariables().clear(); } } } // TODO: review how these methods are used // I believe it is still needed. At least the DSB ingest framework still // uses this method. (And I'm assuming we'll always want to be able to // get the filename of a given studyFile -- unless I'm missing something). // -- L.A. public String getFileName() { if (getLatestFileMetadata() == null) { return null; } return getLatestFileMetadata().getLabel(); } public String getLatestCategory() { return getLatestFileMetadata().getCategory(); } public String getFileName(Long versionNumber) { if (getFileMetadata(versionNumber) == null) { return null; } return getFileMetadata(versionNumber).getLabel(); } private FileMetadata getLatestFileMetadata() { FileMetadata fmd = null; for (FileMetadata fileMetadata : fileMetadatas) { if (fmd == null || fileMetadata.getStudyVersion().getVersionNumber().compareTo( fmd.getStudyVersion().getVersionNumber() ) > 0 ) { fmd = fileMetadata; } } return fmd; } private FileMetadata getFileMetadata (Long versionNumber) { if (versionNumber == null) { return getLatestFileMetadata(); } for (FileMetadata fileMetadata : fileMetadatas) { if (fileMetadata != null && fileMetadata.getStudyVersion() != null && versionNumber.equals( fileMetadata.getStudyVersion().getVersionNumber() ) ) { return fileMetadata; } } return null; } public FileMetadata getReleasedFileMetadata() { for (FileMetadata fileMetadata : fileMetadatas) { if (fileMetadata.getStudyVersion().isReleased() ) { return fileMetadata; } } return null; } // @Override // public String toString() { // return ToStringBuilder.reflectionToString(this, // ToStringStyle.MULTI_LINE_STYLE); // } }
true
true
public boolean isFileRestrictedForUser(VDCUser user, VDC vdc, UserGroup ipUserGroup) { // the restrictions should be checked on the owner of the study, not the currentVDC (needs cleanup) vdc = this.getStudy().getOwner(); // first check if study is restricted, regardless of file permissions Study study = getStudy(); if (study.isStudyRestrictedForUser( user)) { return true; } // then check dataverse level file permisssions if (vdc.areFilesRestrictedForUser(user, ipUserGroup)) { return true; } // otherwise check for restriction on file itself if (isRestricted()) { if (user == null) { if (ipUserGroup == null) { return true; } else { Iterator iter = this.getAllowedGroups().iterator(); while (iter.hasNext()) { UserGroup allowedGroup = (UserGroup) iter.next(); if (allowedGroup.equals(ipUserGroup)) { return false; } } return true; } } // 1. check if study is restricted (this part was moved a little higher; still need more cleanup) // 2. check network role if (user.getNetworkRole() != null && user.getNetworkRole().getName().equals(NetworkRoleServiceLocal.ADMIN)) { // If you are network admin, you can do anything! return false; } // 3. check vdc role VDCRole userRole = user.getVDCRole(vdc); if (userRole != null) { String userRoleName = userRole.getRole().getName(); if (userRoleName.equals(RoleServiceLocal.ADMIN) || userRoleName.equals(RoleServiceLocal.CURATOR)) { return false; } } //4. check if creator if (user.getId().equals(this.getStudy().getCreator().getId())) { return false; } // 5. check user Iterator iter = this.getAllowedUsers().iterator(); while (iter.hasNext()) { VDCUser allowedUser = (VDCUser) iter.next(); if (allowedUser.getId().equals(user.getId())) { return false; } } // 6. check groups iter = this.getAllowedGroups().iterator(); while (iter.hasNext()) { UserGroup allowedGroup = (UserGroup) iter.next(); if (user.getUserGroups().contains(allowedGroup)) { return false; } } return true; } else { return false; } }
public boolean isFileRestrictedForUser(VDCUser user, VDC vdc, UserGroup ipUserGroup) { // the restrictions should be checked on the owner of the study, not the currentVDC (needs cleanup) vdc = this.getStudy().getOwner(); // first check if study is restricted, regardless of file permissions Study study = getStudy(); if (study.isStudyRestrictedForUser( user, ipUserGroup)) { return true; } // then check dataverse level file permisssions if (vdc.areFilesRestrictedForUser(user, ipUserGroup)) { return true; } // otherwise check for restriction on file itself if (isRestricted()) { if (user == null) { if (ipUserGroup == null) { return true; } else { Iterator iter = this.getAllowedGroups().iterator(); while (iter.hasNext()) { UserGroup allowedGroup = (UserGroup) iter.next(); if (allowedGroup.equals(ipUserGroup)) { return false; } } return true; } } // 1. check if study is restricted (this part was moved a little higher; still need more cleanup) // 2. check network role if (user.getNetworkRole() != null && user.getNetworkRole().getName().equals(NetworkRoleServiceLocal.ADMIN)) { // If you are network admin, you can do anything! return false; } // 3. check vdc role VDCRole userRole = user.getVDCRole(vdc); if (userRole != null) { String userRoleName = userRole.getRole().getName(); if (userRoleName.equals(RoleServiceLocal.ADMIN) || userRoleName.equals(RoleServiceLocal.CURATOR)) { return false; } } //4. check if creator if (user.getId().equals(this.getStudy().getCreator().getId())) { return false; } // 5. check user Iterator iter = this.getAllowedUsers().iterator(); while (iter.hasNext()) { VDCUser allowedUser = (VDCUser) iter.next(); if (allowedUser.getId().equals(user.getId())) { return false; } } // 6. check groups iter = this.getAllowedGroups().iterator(); while (iter.hasNext()) { UserGroup allowedGroup = (UserGroup) iter.next(); if (user.getUserGroups().contains(allowedGroup)) { return false; } } return true; } else { return false; } }
diff --git a/fabric/fabric-core/src/main/scala/org/fusesource/fabric/internal/ContainerProviderUtils.java b/fabric/fabric-core/src/main/scala/org/fusesource/fabric/internal/ContainerProviderUtils.java index 82513edc2..b0965b40b 100644 --- a/fabric/fabric-core/src/main/scala/org/fusesource/fabric/internal/ContainerProviderUtils.java +++ b/fabric/fabric-core/src/main/scala/org/fusesource/fabric/internal/ContainerProviderUtils.java @@ -1,101 +1,101 @@ /** * Copyright (C) FuseSource, Inc. * http://fusesource.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.fusesource.fabric.internal; import java.net.MalformedURLException; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.fusesource.fabric.api.ZooKeeperClusterService; public class ContainerProviderUtils { private static final String REPLACE_FORMAT = "sed -i \"s/%s/%s/g\" %s"; public static final int DEFAULT_SSH_PORT = 8081; private ContainerProviderUtils() { //Utility Class } public static String buildStartupScript(URI proxy, String name, String path, String zooKeeperUrl, int sshPort, boolean isClusterServer, boolean debugContainer) throws MalformedURLException { StringBuilder sb = new StringBuilder(); sb.append("function run { echo \"Running: $*\" ; $* ; rc=$? ; if [ \"${rc}\" -ne 0 ]; then echo \"Command failed\" ; exit ${rc} ; fi ; }\n"); - sb.append("run mkdir ~/containers/ ").append("\n"); + sb.append("run -p mkdir ~/containers/ ").append("\n"); sb.append("run cd ~/containers/ ").append("\n"); sb.append("run mkdir -p ").append(name).append("\n"); sb.append("run cd ").append(name).append("\n"); extractTargzIntoDirectory(sb, proxy, "org.fusesource.fabric", "fuse-fabric", FabricConstants.VERSION); sb.append("run cd ").append("fuse-fabric-" + FabricConstants.VERSION).append("\n"); List<String> lines = new ArrayList<String>(); appendFile(sb, "etc/startup.properties", lines); replaceLineInFile(sb,"etc/system.properties","karaf.name=root","karaf.name = "+name); replaceLineInFile(sb,"etc/org.apache.karaf.shell.cfg","sshPort=8101","sshPort="+sshPort); if(isClusterServer) { appendFile(sb, "etc/system.properties", Arrays.asList(ZooKeeperClusterService.ENSEMBLE_AUTOSTART +"=true")); } else { appendFile(sb, "etc/system.properties", Arrays.asList("zookeeper.url = " + zooKeeperUrl)); } if(debugContainer) { sb.append("run export KARAF_DEBUG=true").append("\n"); } sb.append("run nohup bin/start").append("\n"); return sb.toString(); } private static String downloadAndStartMavenBundle(StringBuilder sb, URI proxy, String groupId, String artifactId, String version, String type) { String path = groupId.replaceAll("\\.", "/") + "/" + artifactId + "/" + version; String file = path + "/" + artifactId + "-" + version + "." + type; sb.append("run mkdir -p " + "system/").append(path).append("\n"); sb.append("run curl --show-error --silent --get --retry 20 --output system/").append(file).append(" ").append(proxy.resolve(file)).append("\n"); return file; } private static void replaceLineInFile(StringBuilder sb, String path, String pattern, String line) { sb.append(String.format(REPLACE_FORMAT,pattern,line,path)).append("\n"); } private static void appendFile(StringBuilder sb, String path, Iterable<String> lines) { final String MARKER = "END_OF_FILE"; sb.append("cat >> ").append(path).append(" <<'").append(MARKER).append("'\n"); for (String line : lines) { sb.append(line).append("\n"); } sb.append(MARKER).append("\n"); } private static void extractTargzIntoDirectory(StringBuilder sb, URI proxy, String groupId, String artifactId, String version) { String file = artifactId + "-" + version + ".tar.gz"; String directory = groupId.replaceAll("\\.", "/") + "/" + artifactId + "/" + version + "/"; String artifactParentUri = proxy.resolve(directory).toString(); String artifactUri = proxy.resolve(directory+file).toString(); //To cover the case of SNAPSHOT dependencies where URL can't be determined we are quering for the availale versions first if(version.contains("SNAPSHOT")) { sb.append("run export DISTRO_URL=`curl --silent ").append(artifactParentUri).append("| grep href | grep \"tar.gz\\\"\" | sed 's/^.*<a href=\"//' | sed 's/\".*$//' | tail -1`").append("\n"); } else { sb.append("run export DISTRO_URL=`").append(artifactUri).append("`").append("\n"); } sb.append("if [[ \"$DISTRO_URL\" == \"\" ]] ; then export DISTRO_URL=").append(artifactUri).append("; fi\n"); sb.append("run curl --show-error --silent --get --retry 20 --output ").append(file).append(" ").append("$DISTRO_URL").append("\n"); sb.append("run tar -xpzf ").append(file).append("\n"); } }
true
true
public static String buildStartupScript(URI proxy, String name, String path, String zooKeeperUrl, int sshPort, boolean isClusterServer, boolean debugContainer) throws MalformedURLException { StringBuilder sb = new StringBuilder(); sb.append("function run { echo \"Running: $*\" ; $* ; rc=$? ; if [ \"${rc}\" -ne 0 ]; then echo \"Command failed\" ; exit ${rc} ; fi ; }\n"); sb.append("run mkdir ~/containers/ ").append("\n"); sb.append("run cd ~/containers/ ").append("\n"); sb.append("run mkdir -p ").append(name).append("\n"); sb.append("run cd ").append(name).append("\n"); extractTargzIntoDirectory(sb, proxy, "org.fusesource.fabric", "fuse-fabric", FabricConstants.VERSION); sb.append("run cd ").append("fuse-fabric-" + FabricConstants.VERSION).append("\n"); List<String> lines = new ArrayList<String>(); appendFile(sb, "etc/startup.properties", lines); replaceLineInFile(sb,"etc/system.properties","karaf.name=root","karaf.name = "+name); replaceLineInFile(sb,"etc/org.apache.karaf.shell.cfg","sshPort=8101","sshPort="+sshPort); if(isClusterServer) { appendFile(sb, "etc/system.properties", Arrays.asList(ZooKeeperClusterService.ENSEMBLE_AUTOSTART +"=true")); } else { appendFile(sb, "etc/system.properties", Arrays.asList("zookeeper.url = " + zooKeeperUrl)); } if(debugContainer) { sb.append("run export KARAF_DEBUG=true").append("\n"); } sb.append("run nohup bin/start").append("\n"); return sb.toString(); }
public static String buildStartupScript(URI proxy, String name, String path, String zooKeeperUrl, int sshPort, boolean isClusterServer, boolean debugContainer) throws MalformedURLException { StringBuilder sb = new StringBuilder(); sb.append("function run { echo \"Running: $*\" ; $* ; rc=$? ; if [ \"${rc}\" -ne 0 ]; then echo \"Command failed\" ; exit ${rc} ; fi ; }\n"); sb.append("run -p mkdir ~/containers/ ").append("\n"); sb.append("run cd ~/containers/ ").append("\n"); sb.append("run mkdir -p ").append(name).append("\n"); sb.append("run cd ").append(name).append("\n"); extractTargzIntoDirectory(sb, proxy, "org.fusesource.fabric", "fuse-fabric", FabricConstants.VERSION); sb.append("run cd ").append("fuse-fabric-" + FabricConstants.VERSION).append("\n"); List<String> lines = new ArrayList<String>(); appendFile(sb, "etc/startup.properties", lines); replaceLineInFile(sb,"etc/system.properties","karaf.name=root","karaf.name = "+name); replaceLineInFile(sb,"etc/org.apache.karaf.shell.cfg","sshPort=8101","sshPort="+sshPort); if(isClusterServer) { appendFile(sb, "etc/system.properties", Arrays.asList(ZooKeeperClusterService.ENSEMBLE_AUTOSTART +"=true")); } else { appendFile(sb, "etc/system.properties", Arrays.asList("zookeeper.url = " + zooKeeperUrl)); } if(debugContainer) { sb.append("run export KARAF_DEBUG=true").append("\n"); } sb.append("run nohup bin/start").append("\n"); return sb.toString(); }
diff --git a/org.spoofax.interpreter.library.jsglr/src/main/java/org/spoofax/interpreter/library/jsglr/STRSGLR_open_parse_table.java b/org.spoofax.interpreter.library.jsglr/src/main/java/org/spoofax/interpreter/library/jsglr/STRSGLR_open_parse_table.java index 8507d6d9..ad1714b9 100644 --- a/org.spoofax.interpreter.library.jsglr/src/main/java/org/spoofax/interpreter/library/jsglr/STRSGLR_open_parse_table.java +++ b/org.spoofax.interpreter.library.jsglr/src/main/java/org/spoofax/interpreter/library/jsglr/STRSGLR_open_parse_table.java @@ -1,54 +1,54 @@ /* * Copyright (c) 2005-2011, Karl Trygve Kalleberg <karltk near strategoxt dot org> * * Licensed under the GNU Lesser General Public License, v2.1 */ package org.spoofax.interpreter.library.jsglr; import java.util.Map; import org.spoofax.interpreter.core.IContext; import org.spoofax.interpreter.core.InterpreterException; import org.spoofax.interpreter.stratego.Strategy; import org.spoofax.interpreter.terms.IStrategoInt; import org.spoofax.interpreter.terms.IStrategoTerm; import org.spoofax.jsglr.client.InvalidParseTableException; import org.spoofax.jsglr.client.ParseTable; public class STRSGLR_open_parse_table extends JSGLRPrimitive { public STRSGLR_open_parse_table() { super("STRSGLR_open_parse_table", 0, 1); } @Override public boolean call(IContext env, Strategy[] svars, IStrategoTerm[] tvars) throws InterpreterException { Map<IStrategoTerm, IStrategoInt> cache = getLibrary(env).getParseTableCache(); IStrategoInt cached = cache.get(tvars[0]); if (cached != null) { env.setCurrent(cached); - if(!cache.containsKey(cached.intValue())) + if(!cache.containsValue(cached.intValue())) throw new IllegalStateException("Inconsistent context: wrong JSGLR library instance"); return true; } IStrategoTerm tableTerm = tvars[0]; JSGLRLibrary lib = getLibrary(env); try { ParseTable pt = lib.getParseTableManager(env.getFactory()).loadFromTerm(tableTerm); IStrategoInt result = env.getFactory().makeInt(lib.addParseTable(pt)); env.setCurrent(result); cache.put(tvars[0], result); } catch (InvalidParseTableException e) { e.printStackTrace(); return false; } return true; } }
true
true
public boolean call(IContext env, Strategy[] svars, IStrategoTerm[] tvars) throws InterpreterException { Map<IStrategoTerm, IStrategoInt> cache = getLibrary(env).getParseTableCache(); IStrategoInt cached = cache.get(tvars[0]); if (cached != null) { env.setCurrent(cached); if(!cache.containsKey(cached.intValue())) throw new IllegalStateException("Inconsistent context: wrong JSGLR library instance"); return true; } IStrategoTerm tableTerm = tvars[0]; JSGLRLibrary lib = getLibrary(env); try { ParseTable pt = lib.getParseTableManager(env.getFactory()).loadFromTerm(tableTerm); IStrategoInt result = env.getFactory().makeInt(lib.addParseTable(pt)); env.setCurrent(result); cache.put(tvars[0], result); } catch (InvalidParseTableException e) { e.printStackTrace(); return false; } return true; }
public boolean call(IContext env, Strategy[] svars, IStrategoTerm[] tvars) throws InterpreterException { Map<IStrategoTerm, IStrategoInt> cache = getLibrary(env).getParseTableCache(); IStrategoInt cached = cache.get(tvars[0]); if (cached != null) { env.setCurrent(cached); if(!cache.containsValue(cached.intValue())) throw new IllegalStateException("Inconsistent context: wrong JSGLR library instance"); return true; } IStrategoTerm tableTerm = tvars[0]; JSGLRLibrary lib = getLibrary(env); try { ParseTable pt = lib.getParseTableManager(env.getFactory()).loadFromTerm(tableTerm); IStrategoInt result = env.getFactory().makeInt(lib.addParseTable(pt)); env.setCurrent(result); cache.put(tvars[0], result); } catch (InvalidParseTableException e) { e.printStackTrace(); return false; } return true; }
diff --git a/src/me/ellbristow/greylistVote/greylistVote.java b/src/me/ellbristow/greylistVote/greylistVote.java index c238ee2..6a41e70 100644 --- a/src/me/ellbristow/greylistVote/greylistVote.java +++ b/src/me/ellbristow/greylistVote/greylistVote.java @@ -1,630 +1,632 @@ package me.ellbristow.greylistVote; import java.io.File; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.ChatColor; import org.bukkit.OfflinePlayer; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.permissions.PermissionAttachment; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; public class greylistVote extends JavaPlugin { public static greylistVote plugin; public final Logger logger = Logger.getLogger("Minecraft"); public final greyBlockListener blockListener = new greyBlockListener(this); public final greyPlayerListener loginListener = new greyPlayerListener(this); protected FileConfiguration config; public FileConfiguration usersConfig = null; private File usersFile = null; @Override public void onDisable() { PluginDescriptionFile pdfFile = this.getDescription(); this.logger.info("[" + pdfFile.getName() + "] is now disabled."); } @Override public void onEnable() { PluginDescriptionFile pdfFile = this.getDescription(); this.logger.info("[" + pdfFile.getName() + "] version " + pdfFile.getVersion() + " is enabled."); PluginManager pm = getServer().getPluginManager(); pm.registerEvent(Event.Type.BLOCK_PLACE, blockListener, Event.Priority.Normal, this); pm.registerEvent(Event.Type.BLOCK_BREAK, blockListener, Event.Priority.Normal, this); pm.registerEvent(Event.Type.BLOCK_IGNITE, blockListener, Event.Priority.Normal, this); pm.registerEvent(Event.Type.PLAYER_LOGIN, loginListener, Event.Priority.Normal, this); this.config = this.getConfig(); this.config.set("required_votes", this.config.getInt("required_votes")); this.saveConfig(); this.usersConfig = this.getUsersConfig(); } public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if (commandLabel.equalsIgnoreCase("glv")) { if (args.length == 0) { PluginDescriptionFile pdfFile = this.getDescription(); sender.sendMessage(ChatColor.GOLD + pdfFile.getName() + " version " + pdfFile.getVersion() + " by " + pdfFile.getAuthors()); sender.sendMessage(ChatColor.GOLD + "Commands: {optional} [required]"); sender.sendMessage(ChatColor.GOLD + " /glv " + ChatColor.GRAY + ": View all GreylistVote commands"); sender.sendMessage(ChatColor.GOLD + " /greylist [player] || /gl [player] || /trust Player " + ChatColor.GRAY + ":"); sender.sendMessage(ChatColor.GRAY + " Increase player's reputation"); sender.sendMessage(ChatColor.GOLD + " /griefer [player] " + ChatColor.GRAY + ":"); sender.sendMessage(ChatColor.GRAY + " Reduce player's reputation"); sender.sendMessage(ChatColor.GOLD + " /votelist {player} || /glvlist {player} " + ChatColor.GRAY + ":"); sender.sendMessage(ChatColor.GRAY + " View your (or player's) reputation"); if (sender.hasPermission("greylistvote.admin")) { sender.sendMessage(ChatColor.RED + "Admin Commands:"); sender.sendMessage(ChatColor.GOLD + " /glv setrep [req. rep] " + ChatColor.GRAY + ": Set required reputation"); sender.sendMessage(ChatColor.GOLD + " /glv clearserver [player] " + ChatColor.GRAY + ": Remove player's Server votes"); sender.sendMessage(ChatColor.GOLD + " /glv clearall [player] " + ChatColor.GRAY + ": Remove all player's votes"); } return true; } else if (args.length == 2) { if (!sender.hasPermission("greylistvote.admin")) { sender.sendMessage(ChatColor.RED + "You do not have permission to do that!"); return false; } int reqVotes = config.getInt("required_votes", 2); if (args[0].equalsIgnoreCase("setrep")) { try { reqVotes = Integer.parseInt(args[1]); } catch(NumberFormatException nfe) { // Failed. Number not an integer sender.sendMessage(ChatColor.RED + "[req. votes] must be a number!" ); return false; } this.config.set("required_votes", reqVotes); this.saveConfig(); sender.sendMessage(ChatColor.GOLD + "Reputation requirement now set to " + ChatColor.WHITE + args[1]); sender.sendMessage(ChatColor.GOLD + "Player approval will be updated on next login."); return true; } else if (args[0].equalsIgnoreCase("clearserver")) { Player target = (Player) getServer().getOfflinePlayer(args[1]); if (target == null) { sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[0] + ChatColor.RED + "not found!"); return true; } String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null); String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null); String newVoteList = null; String newGriefList = null; String[] voteArray = null; String[] griefArray = null; if (griefList == null && voteList == null) { sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + target.getName() + ChatColor.RED + "does not have any votes!"); return true; } if (voteList != null) { voteArray = voteList.split(","); for (String vote : voteArray) { if (!vote.equals("Server")) { newVoteList += "," + vote; } } if (newVoteList != null) { newVoteList = newVoteList.replaceFirst(",",""); } usersConfig.set(target.getName().toLowerCase() + ".votes", newVoteList); } if (griefList != null) { griefArray = griefList.split(","); for (String vote : griefArray) { if (!vote.equals("Server")) { newGriefList += "," + vote; } } if (newGriefList != null) { newGriefList = newGriefList.replaceFirst(",",""); } usersConfig.set(target.getName().toLowerCase() + ".griefer", newGriefList); } saveUsersConfig(); int rep = 0; voteArray = null; griefArray = null; if (newVoteList != null) { voteArray = voteList.split(","); for (@SuppressWarnings("unused") String vote : voteArray) { rep++; } } if (griefList != null) { griefArray = griefList.split(","); for (@SuppressWarnings("unused") String vote : griefArray) { rep--; } } sender.sendMessage(ChatColor.GOLD + "'Server' votes removed from " + ChatColor.WHITE + target.getName()); target.sendMessage(ChatColor.GOLD + "Your Server Approval/Black-Ball votes were removed!"); if (rep >= reqVotes && !target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { setApproved(target); } else if (rep < reqVotes && target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { setGriefer(target); } } else if (args[0].equalsIgnoreCase("clearall")) { Player target = (Player) getServer().getOfflinePlayer(args[1]); if (target == null) { sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[0] + ChatColor.RED + "not found!"); return true; } String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null); String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null); if (griefList == null && voteList == null) { sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + target.getName() + ChatColor.RED + "does not have any votes!"); return true; } usersConfig.set(target.getName().toLowerCase() + ".votes", null); usersConfig.set(target.getName().toLowerCase() + ".griefer", null); sender.sendMessage(ChatColor.GOLD + "ALL votes removed from " + ChatColor.WHITE + target.getName()); target.sendMessage(ChatColor.RED + "Your reputation was reset to 0!"); if (0 >= reqVotes && !target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { setApproved(target); } else if (0 < reqVotes && target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { setGriefer(target); } } else { sender.sendMessage(ChatColor.RED + "Command not recognised!"); return false; } } return false; } else if (commandLabel.equalsIgnoreCase("greylist") || commandLabel.equalsIgnoreCase("gl") || commandLabel.equalsIgnoreCase("trust")) { if (args.length != 1) { // No player specified or too many arguments return false; } else { Player target = getServer().getOfflinePlayer(args[0]).getPlayer(); if (target == null) { // Player not online sender.sendMessage(args[0] + ChatColor.RED + " not found!"); return false; } int reqVotes = this.config.getInt("required_votes"); String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null); String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null); String[] voteArray = null; String[] griefArray = null; if (voteList != null) { voteArray = voteList.split(","); } else { voteList = ""; } if (griefList != null) { griefArray = griefList.split(","); } else { griefList = ""; } if (!(sender instanceof Player)) { // Voter is the console this.usersConfig.set(target.getName().toLowerCase() + ".votes", "Server"); this.usersConfig.set(target.getName().toLowerCase() + ".griefer", null); sender.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to " + reqVotes + "!"); Player[] onlinePlayers = getServer().getOnlinePlayers(); for (Player chatPlayer : onlinePlayers) { if (chatPlayer.getName() != target.getName()) { chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to " + reqVotes + " by the Server!"); } else { target.sendMessage(ChatColor.GOLD + "Your reputation was set to " + reqVotes + " by the Server!"); } } if (!target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { this.setApproved(target); } this.saveUsersConfig(); return true; } if (sender.getName().equalsIgnoreCase(target.getName())) { // Player voting for self sender.sendMessage(ChatColor.RED + "You cannot vote for yourself!"); return true; } boolean found = false; if (voteArray != null) { for (String vote : voteArray) { if (vote.equalsIgnoreCase(sender.getName())) { found = true; } } } if (found) { // Voter has already voted for this target player sender.sendMessage(ChatColor.RED + "You have already voted for " + ChatColor.WHITE + target.getName()); return true; } String newGriefList = null; if (griefArray != null) { for (String vote : griefArray) { if (!vote.equalsIgnoreCase(sender.getName())) { newGriefList += "," + vote; } } if (newGriefList != null) { newGriefList = newGriefList.replaceFirst(",", ""); usersConfig.set(target.getName().toLowerCase() + ".griefer", newGriefList); griefArray = newGriefList.split(","); } else { griefArray = null; } } sender.sendMessage(ChatColor.GOLD + "You have increased " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!"); Player[] onlinePlayers = getServer().getOnlinePlayers(); // Tell everyone about the reputation change for (Player chatPlayer : onlinePlayers) { if (chatPlayer.getName() != target.getName() && chatPlayer.getName() != sender.getName()) { chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " increased " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!"); } else if (chatPlayer.getName() != sender.getName()) { chatPlayer.sendMessage(sender.getName() + ChatColor.GREEN + " increased your reputation!"); chatPlayer.sendMessage(ChatColor.GOLD + "Type " + ChatColor.WHITE + "/votelist" + ChatColor.GOLD + " to check your reputation."); } } if (voteList.equals("")) { voteList = sender.getName(); } else { voteList = voteList + "," + sender.getName(); } this.usersConfig.set(target.getName().toLowerCase() + ".votes", voteList); voteArray = voteList.split(","); int rep = 0; if (voteArray.length != 0) { rep += voteArray.length; } - if (griefArray.length != 0) { - rep -= griefArray.length; + if (griefArray != null) { + if (griefArray.length != 0) { + rep -= griefArray.length; + } } if (rep >= reqVotes && !target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { // Enough votes received this.setApproved(target); } this.saveUsersConfig(); return true; } } else if (commandLabel.equalsIgnoreCase("griefer")) { if (args.length != 1) { // No player specified or too many arguments return false; } else { Player target = getServer().getOfflinePlayer(args[0]).getPlayer(); if (target == null) { // Player not online sender.sendMessage(args[0] + ChatColor.RED + " not found!"); return false; } int reqVotes = this.config.getInt("required_votes"); String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null); String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null); String[] voteArray = null; String[] griefArray = null; if (voteList != null) { voteArray = voteList.split(","); } else { voteList = ""; } if (griefList != null) { griefArray = griefList.split(","); } else { griefList = ""; } if (!(sender instanceof Player)) { // Voter is the console this.usersConfig.set(target.getName().toLowerCase() + ".griefer", "Server"); this.usersConfig.set(target.getName().toLowerCase() + ".votes", null); sender.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to -1!"); Player[] onlinePlayers = getServer().getOnlinePlayers(); for (Player chatPlayer : onlinePlayers) { if (chatPlayer.getName() != target.getName()) { chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to -1 by the Server!"); } else { target.sendMessage(ChatColor.GOLD + "Your reputation was set to -1 by the Server!"); } } if (target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { this.setGriefer(target); } this.saveUsersConfig(); return true; } if (sender.getName() == target.getName()) { // Player voting for self sender.sendMessage(ChatColor.RED + "You cannot vote for yourself!"); return true; } boolean found = false; if (griefArray != null) { for (String vote : griefArray) { if (vote.equalsIgnoreCase(sender.getName())) { found = true; } } } if (found) { // Voter has already voted for this target player sender.sendMessage(ChatColor.RED + "You have already voted for " + ChatColor.WHITE + target.getName()); return true; } String newVoteList = null; if (griefArray != null) { for (String vote : voteArray) { if (!vote.equalsIgnoreCase(sender.getName())) { newVoteList += "," + vote; } } if (newVoteList != null) { newVoteList = newVoteList.replaceFirst(",", ""); usersConfig.set(target.getName().toLowerCase() + ".griefer", newVoteList); voteArray = newVoteList.split(","); } else { voteArray = null; } } sender.sendMessage(ChatColor.GOLD + "You have reduced " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!"); Player[] onlinePlayers = getServer().getOnlinePlayers(); for (Player chatPlayer : onlinePlayers) { if (chatPlayer.getName() != target.getName() && chatPlayer.getName() != sender.getName()) { chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " reduced " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!"); } else if (chatPlayer.getName() != sender.getName()) { chatPlayer.sendMessage(sender.getName() + ChatColor.RED + " reduced your reputation!"); chatPlayer.sendMessage(ChatColor.GOLD + "Type " + ChatColor.WHITE + "/votelist" + ChatColor.GOLD + " to check your reputation."); } } if (griefList.equals("")) { griefList = sender.getName(); } else { griefList = griefList + "," + sender.getName(); } this.usersConfig.set(target.getName().toLowerCase() + ".griefer", griefList); griefArray = griefList.split(","); int rep = 0; if (voteArray != null) { rep += voteArray.length; } if (griefArray != null) { rep -= griefArray.length; } if (rep < reqVotes && target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { // Enough votes received this.setGriefer(target); } this.saveUsersConfig(); return true; } } else if (commandLabel.equalsIgnoreCase("votelist") || commandLabel.equalsIgnoreCase("glvlist")) { if (args.length == 0) { String voteList = this.usersConfig.getString(sender.getName().toLowerCase() + ".votes", null); String griefList = this.usersConfig.getString(sender.getName().toLowerCase() + ".griefer", null); int reqVotes = config.getInt("required_votes"); if (voteList == null && griefList == null) { sender.sendMessage(ChatColor.GOLD + "You have not received any votes."); sender.sendMessage(ChatColor.GOLD + "Current Reputation: " + ChatColor.WHITE + "0"); sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + reqVotes); } else { sender.sendMessage(ChatColor.GOLD + "You have received votes from:"); int reputation = 0; boolean serverVote = false; String[] voteArray = null; String[] griefArray = null; if (voteList != null) { voteArray = voteList.split(","); if (voteArray.length != 0) { String votes = ChatColor.GREEN + " Approvals: " + ChatColor.GOLD; for (String vote : voteArray) { votes = votes + vote + " "; if (vote.equals("Server")) { serverVote = true; } reputation ++; } if (serverVote) { reputation = reqVotes; } sender.sendMessage(votes); } } if (griefList != null) { griefArray = griefList.split(","); if (griefArray.length != 0) { String votes = ChatColor.DARK_GRAY + " Black-Balls: " + ChatColor.GOLD; serverVote = false; for (String vote : griefArray) { votes = votes + vote + " "; if (vote.equals("Server")) { serverVote = true; } reputation--; } if (serverVote) { reputation = -1; } sender.sendMessage(votes); } } String repText = ""; if (reputation >= reqVotes) { repText = " " + ChatColor.GREEN + reputation; } else { repText = " " + ChatColor.RED + reputation; } sender.sendMessage(ChatColor.GOLD + "Current Reputation:" + repText); sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + reqVotes); } return true; } else { OfflinePlayer checktarget = getServer().getOfflinePlayer(args[0]); String DN = null; String target = null; if (checktarget.isOnline()) { target = checktarget.getPlayer().getName(); DN = checktarget.getPlayer().getDisplayName(); } else { if (checktarget != null) { target = checktarget.getName(); DN = checktarget.getName(); } } if (target == null) { // Player not found sender.sendMessage(args[0] + ChatColor.RED + " not found!"); return false; } String voteList = this.usersConfig.getString(target.toLowerCase() + ".votes", null); String griefList = this.usersConfig.getString(target.toLowerCase() + ".griefer", null); int reqVotes = config.getInt("required_votes"); if (voteList == null && griefList == null) { sender.sendMessage(DN + ChatColor.GOLD + " has not received any votes."); sender.sendMessage(ChatColor.GOLD + "Current Reputation: " + ChatColor.WHITE + "0"); sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + reqVotes); } else { sender.sendMessage(DN + ChatColor.GOLD + " has received votes from:"); int reputation = 0; boolean serverVote = false; String[] voteArray = null; String[] griefArray = null; if (voteList != null) { voteArray = voteList.split(","); if (voteArray.length != 0) { String votes = ChatColor.GREEN + " Approvals: " + ChatColor.GOLD; for (String vote : voteArray) { votes = votes + vote + " "; if (vote.equals("Server")) { serverVote = true; } reputation ++; } if (serverVote) { reputation = reqVotes; } sender.sendMessage(votes); } } if (griefList != null) { griefArray = griefList.split(","); if (griefArray.length != 0) { String votes = ChatColor.DARK_GRAY + " Black-Balls: " + ChatColor.GOLD; serverVote = false; for (String vote : griefArray) { votes = votes + vote + " "; if (vote.equals("Server")) { serverVote = true; } reputation--; } if (serverVote) { reputation = -1; } sender.sendMessage(votes); } } String repText = ""; if (reputation >= reqVotes) { repText = " " + ChatColor.GREEN + reputation; } else { repText = " " + ChatColor.RED + reputation; } sender.sendMessage(ChatColor.GOLD + "Current Reputation:" + repText); sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + reqVotes); } return true; } } return false; } public void setApproved(Player target) { PermissionAttachment attachment = target.addAttachment(this); attachment.setPermission("greylistvote.build", true); Player[] onlinePlayers = getServer().getOnlinePlayers(); int reqVotes = config.getInt("required_votes"); for (Player chatPlayer : onlinePlayers) { if (chatPlayer.getName() != target.getName()) { chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation has reached " + reqVotes + "!"); chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + " can now build!"); } else { chatPlayer.sendMessage(ChatColor.GREEN + "Your reputation has reached " + reqVotes + "!"); chatPlayer.sendMessage(ChatColor.GREEN + "You can now build!"); } } } public void setGriefer(Player target) { PermissionAttachment attachment = target.addAttachment(this); attachment.setPermission("greylistvote.build", false); Player[] onlinePlayers = getServer().getOnlinePlayers(); int reqVotes = config.getInt("required_votes"); for (Player chatPlayer : onlinePlayers) { if (chatPlayer.getName() != target.getName()) { chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation has dropped below " + reqVotes + "!"); chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + " can no longer build!"); } else { chatPlayer.sendMessage(ChatColor.RED + "Your reputation has dropped below " + reqVotes + "!"); chatPlayer.sendMessage(ChatColor.RED + "Your build rights have been revoked!"); } } } public void loadUsersConfig() { if (this.usersFile == null) { this.usersFile = new File(getDataFolder(),"users.yml"); } this.usersConfig = YamlConfiguration.loadConfiguration(this.usersFile); } public FileConfiguration getUsersConfig() { if (this.usersConfig == null) { this.loadUsersConfig(); } return this.usersConfig; } public void saveUsersConfig() { if (this.usersConfig == null || this.usersFile == null) { return; } try { this.usersConfig.save(this.usersFile); } catch (IOException ex) { this.logger.log(Level.SEVERE, "Could not save " + this.usersFile, ex ); } } }
true
true
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if (commandLabel.equalsIgnoreCase("glv")) { if (args.length == 0) { PluginDescriptionFile pdfFile = this.getDescription(); sender.sendMessage(ChatColor.GOLD + pdfFile.getName() + " version " + pdfFile.getVersion() + " by " + pdfFile.getAuthors()); sender.sendMessage(ChatColor.GOLD + "Commands: {optional} [required]"); sender.sendMessage(ChatColor.GOLD + " /glv " + ChatColor.GRAY + ": View all GreylistVote commands"); sender.sendMessage(ChatColor.GOLD + " /greylist [player] || /gl [player] || /trust Player " + ChatColor.GRAY + ":"); sender.sendMessage(ChatColor.GRAY + " Increase player's reputation"); sender.sendMessage(ChatColor.GOLD + " /griefer [player] " + ChatColor.GRAY + ":"); sender.sendMessage(ChatColor.GRAY + " Reduce player's reputation"); sender.sendMessage(ChatColor.GOLD + " /votelist {player} || /glvlist {player} " + ChatColor.GRAY + ":"); sender.sendMessage(ChatColor.GRAY + " View your (or player's) reputation"); if (sender.hasPermission("greylistvote.admin")) { sender.sendMessage(ChatColor.RED + "Admin Commands:"); sender.sendMessage(ChatColor.GOLD + " /glv setrep [req. rep] " + ChatColor.GRAY + ": Set required reputation"); sender.sendMessage(ChatColor.GOLD + " /glv clearserver [player] " + ChatColor.GRAY + ": Remove player's Server votes"); sender.sendMessage(ChatColor.GOLD + " /glv clearall [player] " + ChatColor.GRAY + ": Remove all player's votes"); } return true; } else if (args.length == 2) { if (!sender.hasPermission("greylistvote.admin")) { sender.sendMessage(ChatColor.RED + "You do not have permission to do that!"); return false; } int reqVotes = config.getInt("required_votes", 2); if (args[0].equalsIgnoreCase("setrep")) { try { reqVotes = Integer.parseInt(args[1]); } catch(NumberFormatException nfe) { // Failed. Number not an integer sender.sendMessage(ChatColor.RED + "[req. votes] must be a number!" ); return false; } this.config.set("required_votes", reqVotes); this.saveConfig(); sender.sendMessage(ChatColor.GOLD + "Reputation requirement now set to " + ChatColor.WHITE + args[1]); sender.sendMessage(ChatColor.GOLD + "Player approval will be updated on next login."); return true; } else if (args[0].equalsIgnoreCase("clearserver")) { Player target = (Player) getServer().getOfflinePlayer(args[1]); if (target == null) { sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[0] + ChatColor.RED + "not found!"); return true; } String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null); String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null); String newVoteList = null; String newGriefList = null; String[] voteArray = null; String[] griefArray = null; if (griefList == null && voteList == null) { sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + target.getName() + ChatColor.RED + "does not have any votes!"); return true; } if (voteList != null) { voteArray = voteList.split(","); for (String vote : voteArray) { if (!vote.equals("Server")) { newVoteList += "," + vote; } } if (newVoteList != null) { newVoteList = newVoteList.replaceFirst(",",""); } usersConfig.set(target.getName().toLowerCase() + ".votes", newVoteList); } if (griefList != null) { griefArray = griefList.split(","); for (String vote : griefArray) { if (!vote.equals("Server")) { newGriefList += "," + vote; } } if (newGriefList != null) { newGriefList = newGriefList.replaceFirst(",",""); } usersConfig.set(target.getName().toLowerCase() + ".griefer", newGriefList); } saveUsersConfig(); int rep = 0; voteArray = null; griefArray = null; if (newVoteList != null) { voteArray = voteList.split(","); for (@SuppressWarnings("unused") String vote : voteArray) { rep++; } } if (griefList != null) { griefArray = griefList.split(","); for (@SuppressWarnings("unused") String vote : griefArray) { rep--; } } sender.sendMessage(ChatColor.GOLD + "'Server' votes removed from " + ChatColor.WHITE + target.getName()); target.sendMessage(ChatColor.GOLD + "Your Server Approval/Black-Ball votes were removed!"); if (rep >= reqVotes && !target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { setApproved(target); } else if (rep < reqVotes && target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { setGriefer(target); } } else if (args[0].equalsIgnoreCase("clearall")) { Player target = (Player) getServer().getOfflinePlayer(args[1]); if (target == null) { sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[0] + ChatColor.RED + "not found!"); return true; } String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null); String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null); if (griefList == null && voteList == null) { sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + target.getName() + ChatColor.RED + "does not have any votes!"); return true; } usersConfig.set(target.getName().toLowerCase() + ".votes", null); usersConfig.set(target.getName().toLowerCase() + ".griefer", null); sender.sendMessage(ChatColor.GOLD + "ALL votes removed from " + ChatColor.WHITE + target.getName()); target.sendMessage(ChatColor.RED + "Your reputation was reset to 0!"); if (0 >= reqVotes && !target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { setApproved(target); } else if (0 < reqVotes && target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { setGriefer(target); } } else { sender.sendMessage(ChatColor.RED + "Command not recognised!"); return false; } } return false; } else if (commandLabel.equalsIgnoreCase("greylist") || commandLabel.equalsIgnoreCase("gl") || commandLabel.equalsIgnoreCase("trust")) { if (args.length != 1) { // No player specified or too many arguments return false; } else { Player target = getServer().getOfflinePlayer(args[0]).getPlayer(); if (target == null) { // Player not online sender.sendMessage(args[0] + ChatColor.RED + " not found!"); return false; } int reqVotes = this.config.getInt("required_votes"); String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null); String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null); String[] voteArray = null; String[] griefArray = null; if (voteList != null) { voteArray = voteList.split(","); } else { voteList = ""; } if (griefList != null) { griefArray = griefList.split(","); } else { griefList = ""; } if (!(sender instanceof Player)) { // Voter is the console this.usersConfig.set(target.getName().toLowerCase() + ".votes", "Server"); this.usersConfig.set(target.getName().toLowerCase() + ".griefer", null); sender.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to " + reqVotes + "!"); Player[] onlinePlayers = getServer().getOnlinePlayers(); for (Player chatPlayer : onlinePlayers) { if (chatPlayer.getName() != target.getName()) { chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to " + reqVotes + " by the Server!"); } else { target.sendMessage(ChatColor.GOLD + "Your reputation was set to " + reqVotes + " by the Server!"); } } if (!target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { this.setApproved(target); } this.saveUsersConfig(); return true; } if (sender.getName().equalsIgnoreCase(target.getName())) { // Player voting for self sender.sendMessage(ChatColor.RED + "You cannot vote for yourself!"); return true; } boolean found = false; if (voteArray != null) { for (String vote : voteArray) { if (vote.equalsIgnoreCase(sender.getName())) { found = true; } } } if (found) { // Voter has already voted for this target player sender.sendMessage(ChatColor.RED + "You have already voted for " + ChatColor.WHITE + target.getName()); return true; } String newGriefList = null; if (griefArray != null) { for (String vote : griefArray) { if (!vote.equalsIgnoreCase(sender.getName())) { newGriefList += "," + vote; } } if (newGriefList != null) { newGriefList = newGriefList.replaceFirst(",", ""); usersConfig.set(target.getName().toLowerCase() + ".griefer", newGriefList); griefArray = newGriefList.split(","); } else { griefArray = null; } } sender.sendMessage(ChatColor.GOLD + "You have increased " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!"); Player[] onlinePlayers = getServer().getOnlinePlayers(); // Tell everyone about the reputation change for (Player chatPlayer : onlinePlayers) { if (chatPlayer.getName() != target.getName() && chatPlayer.getName() != sender.getName()) { chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " increased " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!"); } else if (chatPlayer.getName() != sender.getName()) { chatPlayer.sendMessage(sender.getName() + ChatColor.GREEN + " increased your reputation!"); chatPlayer.sendMessage(ChatColor.GOLD + "Type " + ChatColor.WHITE + "/votelist" + ChatColor.GOLD + " to check your reputation."); } } if (voteList.equals("")) { voteList = sender.getName(); } else { voteList = voteList + "," + sender.getName(); } this.usersConfig.set(target.getName().toLowerCase() + ".votes", voteList); voteArray = voteList.split(","); int rep = 0; if (voteArray.length != 0) { rep += voteArray.length; } if (griefArray.length != 0) { rep -= griefArray.length; } if (rep >= reqVotes && !target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { // Enough votes received this.setApproved(target); } this.saveUsersConfig(); return true; } } else if (commandLabel.equalsIgnoreCase("griefer")) { if (args.length != 1) { // No player specified or too many arguments return false; } else { Player target = getServer().getOfflinePlayer(args[0]).getPlayer(); if (target == null) { // Player not online sender.sendMessage(args[0] + ChatColor.RED + " not found!"); return false; } int reqVotes = this.config.getInt("required_votes"); String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null); String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null); String[] voteArray = null; String[] griefArray = null; if (voteList != null) { voteArray = voteList.split(","); } else { voteList = ""; } if (griefList != null) { griefArray = griefList.split(","); } else { griefList = ""; } if (!(sender instanceof Player)) { // Voter is the console this.usersConfig.set(target.getName().toLowerCase() + ".griefer", "Server"); this.usersConfig.set(target.getName().toLowerCase() + ".votes", null); sender.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to -1!"); Player[] onlinePlayers = getServer().getOnlinePlayers(); for (Player chatPlayer : onlinePlayers) { if (chatPlayer.getName() != target.getName()) { chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to -1 by the Server!"); } else { target.sendMessage(ChatColor.GOLD + "Your reputation was set to -1 by the Server!"); } } if (target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { this.setGriefer(target); } this.saveUsersConfig(); return true; } if (sender.getName() == target.getName()) { // Player voting for self sender.sendMessage(ChatColor.RED + "You cannot vote for yourself!"); return true; } boolean found = false; if (griefArray != null) { for (String vote : griefArray) { if (vote.equalsIgnoreCase(sender.getName())) { found = true; } } } if (found) { // Voter has already voted for this target player sender.sendMessage(ChatColor.RED + "You have already voted for " + ChatColor.WHITE + target.getName()); return true; } String newVoteList = null; if (griefArray != null) { for (String vote : voteArray) { if (!vote.equalsIgnoreCase(sender.getName())) { newVoteList += "," + vote; } } if (newVoteList != null) { newVoteList = newVoteList.replaceFirst(",", ""); usersConfig.set(target.getName().toLowerCase() + ".griefer", newVoteList); voteArray = newVoteList.split(","); } else { voteArray = null; } } sender.sendMessage(ChatColor.GOLD + "You have reduced " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!"); Player[] onlinePlayers = getServer().getOnlinePlayers(); for (Player chatPlayer : onlinePlayers) { if (chatPlayer.getName() != target.getName() && chatPlayer.getName() != sender.getName()) { chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " reduced " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!"); } else if (chatPlayer.getName() != sender.getName()) { chatPlayer.sendMessage(sender.getName() + ChatColor.RED + " reduced your reputation!"); chatPlayer.sendMessage(ChatColor.GOLD + "Type " + ChatColor.WHITE + "/votelist" + ChatColor.GOLD + " to check your reputation."); } } if (griefList.equals("")) { griefList = sender.getName(); } else { griefList = griefList + "," + sender.getName(); } this.usersConfig.set(target.getName().toLowerCase() + ".griefer", griefList); griefArray = griefList.split(","); int rep = 0; if (voteArray != null) { rep += voteArray.length; } if (griefArray != null) { rep -= griefArray.length; } if (rep < reqVotes && target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { // Enough votes received this.setGriefer(target); } this.saveUsersConfig(); return true; } } else if (commandLabel.equalsIgnoreCase("votelist") || commandLabel.equalsIgnoreCase("glvlist")) { if (args.length == 0) { String voteList = this.usersConfig.getString(sender.getName().toLowerCase() + ".votes", null); String griefList = this.usersConfig.getString(sender.getName().toLowerCase() + ".griefer", null); int reqVotes = config.getInt("required_votes"); if (voteList == null && griefList == null) { sender.sendMessage(ChatColor.GOLD + "You have not received any votes."); sender.sendMessage(ChatColor.GOLD + "Current Reputation: " + ChatColor.WHITE + "0"); sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + reqVotes); } else { sender.sendMessage(ChatColor.GOLD + "You have received votes from:"); int reputation = 0; boolean serverVote = false; String[] voteArray = null; String[] griefArray = null; if (voteList != null) { voteArray = voteList.split(","); if (voteArray.length != 0) { String votes = ChatColor.GREEN + " Approvals: " + ChatColor.GOLD; for (String vote : voteArray) { votes = votes + vote + " "; if (vote.equals("Server")) { serverVote = true; } reputation ++; } if (serverVote) { reputation = reqVotes; } sender.sendMessage(votes); } } if (griefList != null) { griefArray = griefList.split(","); if (griefArray.length != 0) { String votes = ChatColor.DARK_GRAY + " Black-Balls: " + ChatColor.GOLD; serverVote = false; for (String vote : griefArray) { votes = votes + vote + " "; if (vote.equals("Server")) { serverVote = true; } reputation--; } if (serverVote) { reputation = -1; } sender.sendMessage(votes); } } String repText = ""; if (reputation >= reqVotes) { repText = " " + ChatColor.GREEN + reputation; } else { repText = " " + ChatColor.RED + reputation; } sender.sendMessage(ChatColor.GOLD + "Current Reputation:" + repText); sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + reqVotes); } return true; } else { OfflinePlayer checktarget = getServer().getOfflinePlayer(args[0]); String DN = null; String target = null; if (checktarget.isOnline()) { target = checktarget.getPlayer().getName(); DN = checktarget.getPlayer().getDisplayName(); } else { if (checktarget != null) { target = checktarget.getName(); DN = checktarget.getName(); } } if (target == null) { // Player not found sender.sendMessage(args[0] + ChatColor.RED + " not found!"); return false; } String voteList = this.usersConfig.getString(target.toLowerCase() + ".votes", null); String griefList = this.usersConfig.getString(target.toLowerCase() + ".griefer", null); int reqVotes = config.getInt("required_votes"); if (voteList == null && griefList == null) { sender.sendMessage(DN + ChatColor.GOLD + " has not received any votes."); sender.sendMessage(ChatColor.GOLD + "Current Reputation: " + ChatColor.WHITE + "0"); sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + reqVotes); } else { sender.sendMessage(DN + ChatColor.GOLD + " has received votes from:"); int reputation = 0; boolean serverVote = false; String[] voteArray = null; String[] griefArray = null; if (voteList != null) { voteArray = voteList.split(","); if (voteArray.length != 0) { String votes = ChatColor.GREEN + " Approvals: " + ChatColor.GOLD; for (String vote : voteArray) { votes = votes + vote + " "; if (vote.equals("Server")) { serverVote = true; } reputation ++; } if (serverVote) { reputation = reqVotes; } sender.sendMessage(votes); } } if (griefList != null) { griefArray = griefList.split(","); if (griefArray.length != 0) { String votes = ChatColor.DARK_GRAY + " Black-Balls: " + ChatColor.GOLD; serverVote = false; for (String vote : griefArray) { votes = votes + vote + " "; if (vote.equals("Server")) { serverVote = true; } reputation--; } if (serverVote) { reputation = -1; } sender.sendMessage(votes); } } String repText = ""; if (reputation >= reqVotes) { repText = " " + ChatColor.GREEN + reputation; } else { repText = " " + ChatColor.RED + reputation; } sender.sendMessage(ChatColor.GOLD + "Current Reputation:" + repText); sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + reqVotes); } return true; } } return false; }
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) { if (commandLabel.equalsIgnoreCase("glv")) { if (args.length == 0) { PluginDescriptionFile pdfFile = this.getDescription(); sender.sendMessage(ChatColor.GOLD + pdfFile.getName() + " version " + pdfFile.getVersion() + " by " + pdfFile.getAuthors()); sender.sendMessage(ChatColor.GOLD + "Commands: {optional} [required]"); sender.sendMessage(ChatColor.GOLD + " /glv " + ChatColor.GRAY + ": View all GreylistVote commands"); sender.sendMessage(ChatColor.GOLD + " /greylist [player] || /gl [player] || /trust Player " + ChatColor.GRAY + ":"); sender.sendMessage(ChatColor.GRAY + " Increase player's reputation"); sender.sendMessage(ChatColor.GOLD + " /griefer [player] " + ChatColor.GRAY + ":"); sender.sendMessage(ChatColor.GRAY + " Reduce player's reputation"); sender.sendMessage(ChatColor.GOLD + " /votelist {player} || /glvlist {player} " + ChatColor.GRAY + ":"); sender.sendMessage(ChatColor.GRAY + " View your (or player's) reputation"); if (sender.hasPermission("greylistvote.admin")) { sender.sendMessage(ChatColor.RED + "Admin Commands:"); sender.sendMessage(ChatColor.GOLD + " /glv setrep [req. rep] " + ChatColor.GRAY + ": Set required reputation"); sender.sendMessage(ChatColor.GOLD + " /glv clearserver [player] " + ChatColor.GRAY + ": Remove player's Server votes"); sender.sendMessage(ChatColor.GOLD + " /glv clearall [player] " + ChatColor.GRAY + ": Remove all player's votes"); } return true; } else if (args.length == 2) { if (!sender.hasPermission("greylistvote.admin")) { sender.sendMessage(ChatColor.RED + "You do not have permission to do that!"); return false; } int reqVotes = config.getInt("required_votes", 2); if (args[0].equalsIgnoreCase("setrep")) { try { reqVotes = Integer.parseInt(args[1]); } catch(NumberFormatException nfe) { // Failed. Number not an integer sender.sendMessage(ChatColor.RED + "[req. votes] must be a number!" ); return false; } this.config.set("required_votes", reqVotes); this.saveConfig(); sender.sendMessage(ChatColor.GOLD + "Reputation requirement now set to " + ChatColor.WHITE + args[1]); sender.sendMessage(ChatColor.GOLD + "Player approval will be updated on next login."); return true; } else if (args[0].equalsIgnoreCase("clearserver")) { Player target = (Player) getServer().getOfflinePlayer(args[1]); if (target == null) { sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[0] + ChatColor.RED + "not found!"); return true; } String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null); String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null); String newVoteList = null; String newGriefList = null; String[] voteArray = null; String[] griefArray = null; if (griefList == null && voteList == null) { sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + target.getName() + ChatColor.RED + "does not have any votes!"); return true; } if (voteList != null) { voteArray = voteList.split(","); for (String vote : voteArray) { if (!vote.equals("Server")) { newVoteList += "," + vote; } } if (newVoteList != null) { newVoteList = newVoteList.replaceFirst(",",""); } usersConfig.set(target.getName().toLowerCase() + ".votes", newVoteList); } if (griefList != null) { griefArray = griefList.split(","); for (String vote : griefArray) { if (!vote.equals("Server")) { newGriefList += "," + vote; } } if (newGriefList != null) { newGriefList = newGriefList.replaceFirst(",",""); } usersConfig.set(target.getName().toLowerCase() + ".griefer", newGriefList); } saveUsersConfig(); int rep = 0; voteArray = null; griefArray = null; if (newVoteList != null) { voteArray = voteList.split(","); for (@SuppressWarnings("unused") String vote : voteArray) { rep++; } } if (griefList != null) { griefArray = griefList.split(","); for (@SuppressWarnings("unused") String vote : griefArray) { rep--; } } sender.sendMessage(ChatColor.GOLD + "'Server' votes removed from " + ChatColor.WHITE + target.getName()); target.sendMessage(ChatColor.GOLD + "Your Server Approval/Black-Ball votes were removed!"); if (rep >= reqVotes && !target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { setApproved(target); } else if (rep < reqVotes && target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { setGriefer(target); } } else if (args[0].equalsIgnoreCase("clearall")) { Player target = (Player) getServer().getOfflinePlayer(args[1]); if (target == null) { sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + args[0] + ChatColor.RED + "not found!"); return true; } String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null); String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null); if (griefList == null && voteList == null) { sender.sendMessage(ChatColor.RED + "Player " + ChatColor.WHITE + target.getName() + ChatColor.RED + "does not have any votes!"); return true; } usersConfig.set(target.getName().toLowerCase() + ".votes", null); usersConfig.set(target.getName().toLowerCase() + ".griefer", null); sender.sendMessage(ChatColor.GOLD + "ALL votes removed from " + ChatColor.WHITE + target.getName()); target.sendMessage(ChatColor.RED + "Your reputation was reset to 0!"); if (0 >= reqVotes && !target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { setApproved(target); } else if (0 < reqVotes && target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { setGriefer(target); } } else { sender.sendMessage(ChatColor.RED + "Command not recognised!"); return false; } } return false; } else if (commandLabel.equalsIgnoreCase("greylist") || commandLabel.equalsIgnoreCase("gl") || commandLabel.equalsIgnoreCase("trust")) { if (args.length != 1) { // No player specified or too many arguments return false; } else { Player target = getServer().getOfflinePlayer(args[0]).getPlayer(); if (target == null) { // Player not online sender.sendMessage(args[0] + ChatColor.RED + " not found!"); return false; } int reqVotes = this.config.getInt("required_votes"); String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null); String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null); String[] voteArray = null; String[] griefArray = null; if (voteList != null) { voteArray = voteList.split(","); } else { voteList = ""; } if (griefList != null) { griefArray = griefList.split(","); } else { griefList = ""; } if (!(sender instanceof Player)) { // Voter is the console this.usersConfig.set(target.getName().toLowerCase() + ".votes", "Server"); this.usersConfig.set(target.getName().toLowerCase() + ".griefer", null); sender.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to " + reqVotes + "!"); Player[] onlinePlayers = getServer().getOnlinePlayers(); for (Player chatPlayer : onlinePlayers) { if (chatPlayer.getName() != target.getName()) { chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to " + reqVotes + " by the Server!"); } else { target.sendMessage(ChatColor.GOLD + "Your reputation was set to " + reqVotes + " by the Server!"); } } if (!target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { this.setApproved(target); } this.saveUsersConfig(); return true; } if (sender.getName().equalsIgnoreCase(target.getName())) { // Player voting for self sender.sendMessage(ChatColor.RED + "You cannot vote for yourself!"); return true; } boolean found = false; if (voteArray != null) { for (String vote : voteArray) { if (vote.equalsIgnoreCase(sender.getName())) { found = true; } } } if (found) { // Voter has already voted for this target player sender.sendMessage(ChatColor.RED + "You have already voted for " + ChatColor.WHITE + target.getName()); return true; } String newGriefList = null; if (griefArray != null) { for (String vote : griefArray) { if (!vote.equalsIgnoreCase(sender.getName())) { newGriefList += "," + vote; } } if (newGriefList != null) { newGriefList = newGriefList.replaceFirst(",", ""); usersConfig.set(target.getName().toLowerCase() + ".griefer", newGriefList); griefArray = newGriefList.split(","); } else { griefArray = null; } } sender.sendMessage(ChatColor.GOLD + "You have increased " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!"); Player[] onlinePlayers = getServer().getOnlinePlayers(); // Tell everyone about the reputation change for (Player chatPlayer : onlinePlayers) { if (chatPlayer.getName() != target.getName() && chatPlayer.getName() != sender.getName()) { chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " increased " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!"); } else if (chatPlayer.getName() != sender.getName()) { chatPlayer.sendMessage(sender.getName() + ChatColor.GREEN + " increased your reputation!"); chatPlayer.sendMessage(ChatColor.GOLD + "Type " + ChatColor.WHITE + "/votelist" + ChatColor.GOLD + " to check your reputation."); } } if (voteList.equals("")) { voteList = sender.getName(); } else { voteList = voteList + "," + sender.getName(); } this.usersConfig.set(target.getName().toLowerCase() + ".votes", voteList); voteArray = voteList.split(","); int rep = 0; if (voteArray.length != 0) { rep += voteArray.length; } if (griefArray != null) { if (griefArray.length != 0) { rep -= griefArray.length; } } if (rep >= reqVotes && !target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { // Enough votes received this.setApproved(target); } this.saveUsersConfig(); return true; } } else if (commandLabel.equalsIgnoreCase("griefer")) { if (args.length != 1) { // No player specified or too many arguments return false; } else { Player target = getServer().getOfflinePlayer(args[0]).getPlayer(); if (target == null) { // Player not online sender.sendMessage(args[0] + ChatColor.RED + " not found!"); return false; } int reqVotes = this.config.getInt("required_votes"); String griefList = this.usersConfig.getString(target.getName().toLowerCase() + ".griefer", null); String voteList = this.usersConfig.getString(target.getName().toLowerCase() + ".votes", null); String[] voteArray = null; String[] griefArray = null; if (voteList != null) { voteArray = voteList.split(","); } else { voteList = ""; } if (griefList != null) { griefArray = griefList.split(","); } else { griefList = ""; } if (!(sender instanceof Player)) { // Voter is the console this.usersConfig.set(target.getName().toLowerCase() + ".griefer", "Server"); this.usersConfig.set(target.getName().toLowerCase() + ".votes", null); sender.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to -1!"); Player[] onlinePlayers = getServer().getOnlinePlayers(); for (Player chatPlayer : onlinePlayers) { if (chatPlayer.getName() != target.getName()) { chatPlayer.sendMessage(target.getName() + ChatColor.GOLD + "'s reputation was set to -1 by the Server!"); } else { target.sendMessage(ChatColor.GOLD + "Your reputation was set to -1 by the Server!"); } } if (target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { this.setGriefer(target); } this.saveUsersConfig(); return true; } if (sender.getName() == target.getName()) { // Player voting for self sender.sendMessage(ChatColor.RED + "You cannot vote for yourself!"); return true; } boolean found = false; if (griefArray != null) { for (String vote : griefArray) { if (vote.equalsIgnoreCase(sender.getName())) { found = true; } } } if (found) { // Voter has already voted for this target player sender.sendMessage(ChatColor.RED + "You have already voted for " + ChatColor.WHITE + target.getName()); return true; } String newVoteList = null; if (griefArray != null) { for (String vote : voteArray) { if (!vote.equalsIgnoreCase(sender.getName())) { newVoteList += "," + vote; } } if (newVoteList != null) { newVoteList = newVoteList.replaceFirst(",", ""); usersConfig.set(target.getName().toLowerCase() + ".griefer", newVoteList); voteArray = newVoteList.split(","); } else { voteArray = null; } } sender.sendMessage(ChatColor.GOLD + "You have reduced " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!"); Player[] onlinePlayers = getServer().getOnlinePlayers(); for (Player chatPlayer : onlinePlayers) { if (chatPlayer.getName() != target.getName() && chatPlayer.getName() != sender.getName()) { chatPlayer.sendMessage(sender.getName() + ChatColor.GOLD + " reduced " + ChatColor.WHITE + target.getName() + ChatColor.GOLD + "'s reputation!"); } else if (chatPlayer.getName() != sender.getName()) { chatPlayer.sendMessage(sender.getName() + ChatColor.RED + " reduced your reputation!"); chatPlayer.sendMessage(ChatColor.GOLD + "Type " + ChatColor.WHITE + "/votelist" + ChatColor.GOLD + " to check your reputation."); } } if (griefList.equals("")) { griefList = sender.getName(); } else { griefList = griefList + "," + sender.getName(); } this.usersConfig.set(target.getName().toLowerCase() + ".griefer", griefList); griefArray = griefList.split(","); int rep = 0; if (voteArray != null) { rep += voteArray.length; } if (griefArray != null) { rep -= griefArray.length; } if (rep < reqVotes && target.hasPermission("greylistvote.build") && !target.hasPermission("greylistvote.approved")) { // Enough votes received this.setGriefer(target); } this.saveUsersConfig(); return true; } } else if (commandLabel.equalsIgnoreCase("votelist") || commandLabel.equalsIgnoreCase("glvlist")) { if (args.length == 0) { String voteList = this.usersConfig.getString(sender.getName().toLowerCase() + ".votes", null); String griefList = this.usersConfig.getString(sender.getName().toLowerCase() + ".griefer", null); int reqVotes = config.getInt("required_votes"); if (voteList == null && griefList == null) { sender.sendMessage(ChatColor.GOLD + "You have not received any votes."); sender.sendMessage(ChatColor.GOLD + "Current Reputation: " + ChatColor.WHITE + "0"); sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + reqVotes); } else { sender.sendMessage(ChatColor.GOLD + "You have received votes from:"); int reputation = 0; boolean serverVote = false; String[] voteArray = null; String[] griefArray = null; if (voteList != null) { voteArray = voteList.split(","); if (voteArray.length != 0) { String votes = ChatColor.GREEN + " Approvals: " + ChatColor.GOLD; for (String vote : voteArray) { votes = votes + vote + " "; if (vote.equals("Server")) { serverVote = true; } reputation ++; } if (serverVote) { reputation = reqVotes; } sender.sendMessage(votes); } } if (griefList != null) { griefArray = griefList.split(","); if (griefArray.length != 0) { String votes = ChatColor.DARK_GRAY + " Black-Balls: " + ChatColor.GOLD; serverVote = false; for (String vote : griefArray) { votes = votes + vote + " "; if (vote.equals("Server")) { serverVote = true; } reputation--; } if (serverVote) { reputation = -1; } sender.sendMessage(votes); } } String repText = ""; if (reputation >= reqVotes) { repText = " " + ChatColor.GREEN + reputation; } else { repText = " " + ChatColor.RED + reputation; } sender.sendMessage(ChatColor.GOLD + "Current Reputation:" + repText); sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + reqVotes); } return true; } else { OfflinePlayer checktarget = getServer().getOfflinePlayer(args[0]); String DN = null; String target = null; if (checktarget.isOnline()) { target = checktarget.getPlayer().getName(); DN = checktarget.getPlayer().getDisplayName(); } else { if (checktarget != null) { target = checktarget.getName(); DN = checktarget.getName(); } } if (target == null) { // Player not found sender.sendMessage(args[0] + ChatColor.RED + " not found!"); return false; } String voteList = this.usersConfig.getString(target.toLowerCase() + ".votes", null); String griefList = this.usersConfig.getString(target.toLowerCase() + ".griefer", null); int reqVotes = config.getInt("required_votes"); if (voteList == null && griefList == null) { sender.sendMessage(DN + ChatColor.GOLD + " has not received any votes."); sender.sendMessage(ChatColor.GOLD + "Current Reputation: " + ChatColor.WHITE + "0"); sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + reqVotes); } else { sender.sendMessage(DN + ChatColor.GOLD + " has received votes from:"); int reputation = 0; boolean serverVote = false; String[] voteArray = null; String[] griefArray = null; if (voteList != null) { voteArray = voteList.split(","); if (voteArray.length != 0) { String votes = ChatColor.GREEN + " Approvals: " + ChatColor.GOLD; for (String vote : voteArray) { votes = votes + vote + " "; if (vote.equals("Server")) { serverVote = true; } reputation ++; } if (serverVote) { reputation = reqVotes; } sender.sendMessage(votes); } } if (griefList != null) { griefArray = griefList.split(","); if (griefArray.length != 0) { String votes = ChatColor.DARK_GRAY + " Black-Balls: " + ChatColor.GOLD; serverVote = false; for (String vote : griefArray) { votes = votes + vote + " "; if (vote.equals("Server")) { serverVote = true; } reputation--; } if (serverVote) { reputation = -1; } sender.sendMessage(votes); } } String repText = ""; if (reputation >= reqVotes) { repText = " " + ChatColor.GREEN + reputation; } else { repText = " " + ChatColor.RED + reputation; } sender.sendMessage(ChatColor.GOLD + "Current Reputation:" + repText); sender.sendMessage(ChatColor.GOLD + "Required Reputation: " + ChatColor.WHITE + reqVotes); } return true; } } return false; }
diff --git a/eXoApplication/poll/service/src/main/java/org/exoplatform/poll/service/Poll.java b/eXoApplication/poll/service/src/main/java/org/exoplatform/poll/service/Poll.java index 444895e9e..7674f5035 100755 --- a/eXoApplication/poll/service/src/main/java/org/exoplatform/poll/service/Poll.java +++ b/eXoApplication/poll/service/src/main/java/org/exoplatform/poll/service/Poll.java @@ -1,183 +1,187 @@ /*************************************************************************** * Copyright (C) 2003-2007 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * 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.exoplatform.poll.service ; import java.util.Date; import org.exoplatform.poll.service.impl.PollNodeTypes; import org.exoplatform.services.jcr.util.IdGenerator; /** * Created by The eXo Platform SARL * Author : Vu Duy Tu * [email protected] * Octo 25, 2007 */ public class Poll { private String id; private String parentPath; private String oldParentPath; private String owner; private Date createdDate; private String modifiedBy; private Date modifiedDate; private Date lastVote; private long timeOut = 0; private String question; private String[] option; private String[] vote; private String[] userVote; private boolean isMultiCheck = false ; private boolean isClosed = false ; private boolean isAgainVote = false ; private boolean showVote = true; private String votes; private String[] infoVote; private String expire; private String isAdmin = "false"; public Poll() { id = PollNodeTypes.POLL + IdGenerator.generate() ; createdDate = new Date() ; option = new String[] {}; vote = new String[] {}; userVote = new String[] {}; } public String getId() { return id; } public void setId(String id) { this.id = id; } public void setIsAdmin(String isAdmin) { this.isAdmin = isAdmin;} public String getIsAdmin() { return isAdmin;} public String getParentPath() { return parentPath; } public void setParentPath(String path) { this.parentPath = path; } public void setOldParentPath(String oldParentPath) { this.oldParentPath = oldParentPath;} public String getOldParentPath() { return oldParentPath; } /** * This method should calculate the id of the topic base on the id of the post * @return */ public String getTopicId() { return null; } /** * This method should calculate the id of the forum base on the id of the post * @return */ public String getForumId() { return null ;} public String getOwner(){return owner;} public void setOwner(String owner){this.owner = owner;} public Date getCreatedDate(){return createdDate;} public void setCreatedDate(Date createdDate){this.createdDate = createdDate;} public String getModifiedBy(){return modifiedBy;} public void setModifiedBy(String modifiedBy){this.modifiedBy = modifiedBy;} public Date getModifiedDate(){return modifiedDate;} public void setModifiedDate(Date modifiedDate){this.modifiedDate = modifiedDate;} public String getQuestion(){return question;} public void setQuestion(String question){this.question = question;} public long getTimeOut(){return timeOut;} public void setTimeOut(long timeOut){this.timeOut = timeOut;} public String[] getOption() { return this.option ; } public void setOption( String[] option) {this.option = option ; } public String[] getVote() { return vote; } public void setVote(String[] vote) { this.vote = vote; } public String[] getUserVote() {return userVote; } public void setUserVote( String[] userVote) { this.userVote = userVote;} public boolean getIsMultiCheck() { return isMultiCheck;} public void setIsMultiCheck(boolean isMultiCheck) { this.isMultiCheck = isMultiCheck;} public boolean getIsClosed() { return isClosed;} public void setIsClosed(boolean isClosed) { this.isClosed = isClosed;} public boolean getIsAgainVote() {return isAgainVote;} public void setIsAgainVote(boolean isAgainVote) {this.isAgainVote = isAgainVote;} public Date getLastVote() { return lastVote;} public void setLastVote(Date lastVote) {this.lastVote = lastVote;} public void setShowVote(boolean showVote) {this.showVote = showVote;} public boolean getShowVote() {return showVote;} public void setVotes() {} public String getVotes() { int size = 0; try { if(!isMultiCheck) size = userVote.length ; else for (int i = 0; i < userVote.length; i++) size += userVote[i].split(":").length -1 ; } catch (Exception e) {} votes = String.valueOf(size) ; return votes; } public void setInfoVote() { String[] userVotes = userVote; long size = 0 , temp = 1; if(!this.getIsMultiCheck()) { size = userVote.length ; } else { for (int i = 0; i < userVote.length; i++) { size += userVote[i].split(":").length -1 ;// root:1:2:4 --> user root checked option 1, 2 and 4 --> checked time is 3 } } temp = size; if(size == 0) size = 1; int l = vote.length; infoVote = new String[(l + 1)] ; for (int j = 0; j < l; j++) { String string = vote[j]; double tmp = Double.parseDouble(string) ; double k = (tmp*size)/100 ; - int t = (int)Math.round(k) ; - string = "" + (double) t*100/size ; - infoVote[j] = string + ":" + t ; + double t = (double)Math.round(k) ; + string = String.valueOf(t*100/size); + int dotPos = string.indexOf("."); + int numberAfterDot = string.length() - dotPos -1; + if (dotPos > 0 && numberAfterDot > 2) + string = string.substring(0, dotPos + 3); + infoVote[j] = string + ":" + t; } infoVote[l] = "" + temp ; if(this.getIsMultiCheck()) { infoVote[l] = String.valueOf(userVotes.length) ; } } public String[] getInfoVote() { return infoVote ;} public void setExpire(String expire) {this.expire = expire;} public String getExpire() { return expire;} }
true
true
public void setInfoVote() { String[] userVotes = userVote; long size = 0 , temp = 1; if(!this.getIsMultiCheck()) { size = userVote.length ; } else { for (int i = 0; i < userVote.length; i++) { size += userVote[i].split(":").length -1 ;// root:1:2:4 --> user root checked option 1, 2 and 4 --> checked time is 3 } } temp = size; if(size == 0) size = 1; int l = vote.length; infoVote = new String[(l + 1)] ; for (int j = 0; j < l; j++) { String string = vote[j]; double tmp = Double.parseDouble(string) ; double k = (tmp*size)/100 ; int t = (int)Math.round(k) ; string = "" + (double) t*100/size ; infoVote[j] = string + ":" + t ; } infoVote[l] = "" + temp ; if(this.getIsMultiCheck()) { infoVote[l] = String.valueOf(userVotes.length) ; } }
public void setInfoVote() { String[] userVotes = userVote; long size = 0 , temp = 1; if(!this.getIsMultiCheck()) { size = userVote.length ; } else { for (int i = 0; i < userVote.length; i++) { size += userVote[i].split(":").length -1 ;// root:1:2:4 --> user root checked option 1, 2 and 4 --> checked time is 3 } } temp = size; if(size == 0) size = 1; int l = vote.length; infoVote = new String[(l + 1)] ; for (int j = 0; j < l; j++) { String string = vote[j]; double tmp = Double.parseDouble(string) ; double k = (tmp*size)/100 ; double t = (double)Math.round(k) ; string = String.valueOf(t*100/size); int dotPos = string.indexOf("."); int numberAfterDot = string.length() - dotPos -1; if (dotPos > 0 && numberAfterDot > 2) string = string.substring(0, dotPos + 3); infoVote[j] = string + ":" + t; } infoVote[l] = "" + temp ; if(this.getIsMultiCheck()) { infoVote[l] = String.valueOf(userVotes.length) ; } }
diff --git a/src/pl/linet/Generuj.java b/src/pl/linet/Generuj.java index 539c6d5..8273580 100644 --- a/src/pl/linet/Generuj.java +++ b/src/pl/linet/Generuj.java @@ -1,315 +1,315 @@ package pl.linet; import com.lowagie.text.pdf.*; import com.lowagie.text.*; import com.lowagie.text.pdf.PdfPTable; import java.io.*; import javax.swing.JOptionPane; //import java.util.*; /** * @author kukems * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class Generuj { private String nazwa = "Biuro Pośrednictwa KREDYTOR", nip = "583-187-65-07", adres = "ul. Zakopiańska 28/1", kod = "80-142", miasto = "Gdańsk", miejsc = "Gdańsk", konto = "Multi Bank S.A. 45-1140-2017-0000-4102-0403-2470"; private String[] confArray = { nazwa, nip, adres, kod, miasto, miejsc, konto }; private Document document; /** * ustawia dane sprzedającego * */ public Generuj() { try { ObjectInputStream in = new ObjectInputStream(new FileInputStream( "config_fakturka.txt")); String[] txt_array = (String[]) in.readObject(); nazwa = txt_array[0]; nip = txt_array[1]; adres = txt_array[2]; kod = txt_array[3]; miasto = txt_array[4]; konto = txt_array[5]; miejsc = txt_array[6]; } catch (Exception E) { JOptionPane.showMessageDialog(null, "Wystąpił błąd skonfiguruj najpierw Moje Dane w menu konfiguracja" + E, "Błąd", JOptionPane.ERROR_MESSAGE); } } /** * Generuje plik pdf z argumentami jako danymi do faktury * * @param k_nazwa * - nazwa kupujacego * @param k_adres * - adres kupujacego * @param k_nip * - nip kupujacego * @param k_kod * @param k_miesc * @param usluga * @param pkwiu * @param ilosc * @param netto * - kwota netto * @param vat * @param platnosc * @param termin * @param numer_f * @param miesc * @param brutto * @param data * @param slownie */ public void generatePdf(String k_nazwa, String k_adres, String k_nip, String k_kod, String k_miesc, String usluga, String pkwiu, String ilosc, float netto, int vat, String platnosc, String termin, String numer_f, String data, String slownie) { // przeliczenia podatku float brutto = Przelicz.brutto(netto, vat); // skraca netto // TODO - przeliczanie z brutto netto = (float) Math.round(netto * 100) / 100; float podatek = Przelicz.podatek(netto, vat); document = new Document(); try { // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter .getInstance(document, new FileOutputStream("faktura.pdf")); document.open(); /* fonty */ BaseFont vera; if (System.getProperty("os.name").startsWith("Windows")) vera = BaseFont.createFont("C:\\Windows\\Fonts\\Arial.ttf", BaseFont.CP1250, BaseFont.EMBEDDED); else if (System.getProperty("os.name").equals("Mac OS X")) { - vera = BaseFont.createFont("/Library/Fonts/Georgia.ttf", + vera = BaseFont.createFont("/Library/Fonts/Arial.ttf", BaseFont.CP1250, BaseFont.EMBEDDED); } else { vera = BaseFont.createFont( "/usr/share/fonts/corefonts/arial.ttf", BaseFont.CP1250, BaseFont.EMBEDDED); } Font font = new Font(vera, 12); PdfPTable table1 = new PdfPTable(2); // ustawienia pierwszej tabeli table1.setWidthPercentage(100); table1.setSpacingBefore(5f); table1.setSpacingAfter(15f); - table1.addCell(new Paragraph("Faktura VAT ORGINAŁ/KOPIA", + table1.addCell(new Paragraph("Faktura VAT ORYGINAŁ/KOPIA", font)); table1.addCell(new Phrase("z dnia: " + data)); table1.addCell(new Phrase("nr. " + numer_f)); table1.addCell(new Phrase("Miejscowość: " + miejsc, font)); document.add(table1); /* * table1 zawiera table i table2 table - tabela z danymi * wystawiajacego fakture table2 - tabela z danymi odbiorcy faktury */ // tworzenie obiektow tabel PdfPTable table2 = new PdfPTable(4); // ustawienia tabeli sprzedawcy/nabywcy table2.setWidthPercentage(100); table2.setHeaderRows(1); // tabelki z danymi sprzedawcy/nabywcy PdfPCell cell_kup = new PdfPCell(new Phrase("Dane Nabywcy:")); cell_kup.setColspan(2); PdfPCell cell_sprzed = new PdfPCell(new Phrase("Dane Sprzedawcy:")); cell_sprzed.setColspan(2); table2.addCell(cell_sprzed); table2.addCell(cell_kup); table2.addCell("Nazwa:"); table2.addCell(new Phrase(nazwa, font)); table2.addCell("Nazwa:"); table2.addCell(new Phrase(k_nazwa, font)); table2.addCell("Nip"); table2.addCell(new Phrase(nip, font)); table2.addCell("Nip"); table2.addCell(new Phrase(k_nip, font)); table2.addCell("Adres"); table2.addCell(new Phrase(adres, font)); table2.addCell("Adres"); table2.addCell(new Phrase(k_adres, font)); table2.addCell(new Phrase("Miejscowość", font)); table2.addCell(new Phrase(kod + " " + miejsc, font)); table2.addCell(new Phrase("Miejscowość", font)); table2.addCell(new Phrase(k_kod + " " + k_miesc, font)); document.add(table2); // koniec tabeli sprzedawcy/nabywcy // tabela produktu // ustawienia tabelki float[] widths = { 6f, 1f, 1f, 1f, 2f, 2f, 1f, 2f }; PdfPTable pr_table = new PdfPTable(widths); pr_table.setSpacingBefore(15f); pr_table.setSpacingAfter(24); pr_table.setWidthPercentage(100); // dane tabeli produktu pr_table.addCell(new Phrase("Nazwa Towaru/Usługi", font)); pr_table.addCell(new Phrase("PKWiU", font)); pr_table.addCell(new Phrase("j.m", font)); pr_table.addCell(new Phrase("Ilość", font)); pr_table.addCell(new Phrase("Wartość netto", font)); pr_table.addCell(new Phrase("Kwota Podatku", font)); pr_table.addCell(new Phrase("% VAT", font)); pr_table.addCell(new Phrase("Wartość Brutto", font)); pr_table.addCell(new Phrase(usluga, font)); pr_table.addCell(pkwiu); pr_table.addCell(""); pr_table.addCell(ilosc); pr_table.addCell(Float.toString(netto)); pr_table.addCell(Float.toString(Przelicz.podatek(netto, vat))); pr_table.addCell(Integer.toString(vat)); pr_table.addCell(Float.toString(brutto)); document.add(pr_table); // koniec tabelki produktu // tabelka kontener PdfPTable kt_table = new PdfPTable(2); kt_table.setWidthPercentage(100); // tabelka płatności w kontener PdfPTable pl_table = new PdfPTable(2); PdfPCell pl_cell = new PdfPCell(new Phrase(" numer konta: " + konto)); pl_table.getDefaultCell().setHorizontalAlignment( Element.ALIGN_RIGHT); pl_cell.setColspan(2); pl_table.addCell(new Phrase("Sposób Zapłaty: " + platnosc, font)); pl_table.addCell(new Phrase("termin płatności: " + termin, font)); pl_table.addCell(pl_cell); pl_table.addCell(new Phrase("Do zapłaty: " + brutto + "zł", font)); pl_table.addCell(new Phrase("słownie: " + slownie, font)); // dodanie tabeli platności do kontenera kt_table.addCell(pl_table); // tabelka rozliczenie podatku float[] widths2 = { 0.5f, 1f, 2f, 2f }; PdfPTable pd_table = new PdfPTable(widths2); // ustawienia tabelki podatku pd_table.setWidthPercentage(100); // zawartość tabelki podatku PdfPCell pd_cell = new PdfPCell(new Phrase( "Rozliczenie sprzedaży według stawek podatku", font)); pd_cell.setColspan(4); pd_table.addCell(pd_cell); if (vat == 23) { pd_table.addCell("23%"); pd_table.addCell(Float.toString(netto)); pd_table.addCell(Float.toString(podatek)); pd_table.addCell(Float.toString(brutto)); pd_table.addCell("7%"); pd_table.addCell(""); pd_table.addCell(""); pd_table.addCell(""); } else if (vat == 7) { pd_table.addCell("23%"); pd_table.addCell(""); pd_table.addCell(""); pd_table.addCell(""); pd_table.addCell("7%"); pd_table.addCell(Float.toString(netto)); pd_table.addCell(Float.toString(podatek)); pd_table.addCell(Float.toString(brutto)); } else { pd_table.addCell("23%"); pd_table.addCell("vat musi byc 23 lub 7"); pd_table.addCell("vat musi byc 23 lub 7"); pd_table.addCell("musi byc 23 lub 7"); pd_table.addCell("7%"); pd_table.addCell("vat musi byc 23 lub 7"); pd_table.addCell("vat musi byc 23 lub 7"); pd_table.addCell("vat musi byc 23 lub 7"); pd_table.addCell("vat musi byc 23 lub 7"); } // pd_table.addCell("3%"); // pd_table.addCell("tutaj suma bez 3%"); // pd_table.addCell("tutaj suma vat 3%"); // pd_table.addCell("tutaj suma brutto 3%"); // // pd_table.addCell("0%"); // pd_table.addCell("tutaj suma bez 0%"); // pd_table.addCell("tutaj suma vat 0%"); // pd_table.addCell("tutaj suma brutto 0%"); // kt_table.addCell(pd_table); document.add(kt_table); // koniec tabelka kontener } catch (DocumentException docex) { System.err.println(docex.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } // step 5: we close the document document.close(); } public static void main(String[] args) { Generuj pdf = new Generuj(); } } class Przelicz { protected static float brutto(float netto, int vat) { float brutto = netto + podatek(netto, vat); brutto = (float) Math.round(brutto * 100) / 100; return brutto; } protected static float netto(float brutto, int vat) { float netto = brutto - podatek(brutto, vat); netto = (float) Math.round(netto * 100) / 100; return netto; } protected static float podatek(float netto, int vat) { // zamienia vat na procent float v = vat; v = v / 100; // skraca netto do dwóch liczb po przecinku float kwota_vat = netto * v; kwota_vat = kwota_vat * 100; kwota_vat = (float) Math.round(kwota_vat) / 100; return kwota_vat; } }
false
true
public void generatePdf(String k_nazwa, String k_adres, String k_nip, String k_kod, String k_miesc, String usluga, String pkwiu, String ilosc, float netto, int vat, String platnosc, String termin, String numer_f, String data, String slownie) { // przeliczenia podatku float brutto = Przelicz.brutto(netto, vat); // skraca netto // TODO - przeliczanie z brutto netto = (float) Math.round(netto * 100) / 100; float podatek = Przelicz.podatek(netto, vat); document = new Document(); try { // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter .getInstance(document, new FileOutputStream("faktura.pdf")); document.open(); /* fonty */ BaseFont vera; if (System.getProperty("os.name").startsWith("Windows")) vera = BaseFont.createFont("C:\\Windows\\Fonts\\Arial.ttf", BaseFont.CP1250, BaseFont.EMBEDDED); else if (System.getProperty("os.name").equals("Mac OS X")) { vera = BaseFont.createFont("/Library/Fonts/Georgia.ttf", BaseFont.CP1250, BaseFont.EMBEDDED); } else { vera = BaseFont.createFont( "/usr/share/fonts/corefonts/arial.ttf", BaseFont.CP1250, BaseFont.EMBEDDED); } Font font = new Font(vera, 12); PdfPTable table1 = new PdfPTable(2); // ustawienia pierwszej tabeli table1.setWidthPercentage(100); table1.setSpacingBefore(5f); table1.setSpacingAfter(15f); table1.addCell(new Paragraph("Faktura VAT ORGINAŁ/KOPIA", font)); table1.addCell(new Phrase("z dnia: " + data)); table1.addCell(new Phrase("nr. " + numer_f)); table1.addCell(new Phrase("Miejscowość: " + miejsc, font)); document.add(table1); /* * table1 zawiera table i table2 table - tabela z danymi * wystawiajacego fakture table2 - tabela z danymi odbiorcy faktury */ // tworzenie obiektow tabel PdfPTable table2 = new PdfPTable(4); // ustawienia tabeli sprzedawcy/nabywcy table2.setWidthPercentage(100); table2.setHeaderRows(1); // tabelki z danymi sprzedawcy/nabywcy PdfPCell cell_kup = new PdfPCell(new Phrase("Dane Nabywcy:")); cell_kup.setColspan(2); PdfPCell cell_sprzed = new PdfPCell(new Phrase("Dane Sprzedawcy:")); cell_sprzed.setColspan(2); table2.addCell(cell_sprzed); table2.addCell(cell_kup); table2.addCell("Nazwa:"); table2.addCell(new Phrase(nazwa, font)); table2.addCell("Nazwa:"); table2.addCell(new Phrase(k_nazwa, font)); table2.addCell("Nip"); table2.addCell(new Phrase(nip, font)); table2.addCell("Nip"); table2.addCell(new Phrase(k_nip, font)); table2.addCell("Adres"); table2.addCell(new Phrase(adres, font)); table2.addCell("Adres"); table2.addCell(new Phrase(k_adres, font)); table2.addCell(new Phrase("Miejscowość", font)); table2.addCell(new Phrase(kod + " " + miejsc, font)); table2.addCell(new Phrase("Miejscowość", font)); table2.addCell(new Phrase(k_kod + " " + k_miesc, font)); document.add(table2); // koniec tabeli sprzedawcy/nabywcy // tabela produktu // ustawienia tabelki float[] widths = { 6f, 1f, 1f, 1f, 2f, 2f, 1f, 2f }; PdfPTable pr_table = new PdfPTable(widths); pr_table.setSpacingBefore(15f); pr_table.setSpacingAfter(24); pr_table.setWidthPercentage(100); // dane tabeli produktu pr_table.addCell(new Phrase("Nazwa Towaru/Usługi", font)); pr_table.addCell(new Phrase("PKWiU", font)); pr_table.addCell(new Phrase("j.m", font)); pr_table.addCell(new Phrase("Ilość", font)); pr_table.addCell(new Phrase("Wartość netto", font)); pr_table.addCell(new Phrase("Kwota Podatku", font)); pr_table.addCell(new Phrase("% VAT", font)); pr_table.addCell(new Phrase("Wartość Brutto", font)); pr_table.addCell(new Phrase(usluga, font)); pr_table.addCell(pkwiu); pr_table.addCell(""); pr_table.addCell(ilosc); pr_table.addCell(Float.toString(netto)); pr_table.addCell(Float.toString(Przelicz.podatek(netto, vat))); pr_table.addCell(Integer.toString(vat)); pr_table.addCell(Float.toString(brutto)); document.add(pr_table); // koniec tabelki produktu // tabelka kontener PdfPTable kt_table = new PdfPTable(2); kt_table.setWidthPercentage(100); // tabelka płatności w kontener PdfPTable pl_table = new PdfPTable(2); PdfPCell pl_cell = new PdfPCell(new Phrase(" numer konta: " + konto)); pl_table.getDefaultCell().setHorizontalAlignment( Element.ALIGN_RIGHT); pl_cell.setColspan(2); pl_table.addCell(new Phrase("Sposób Zapłaty: " + platnosc, font)); pl_table.addCell(new Phrase("termin płatności: " + termin, font)); pl_table.addCell(pl_cell); pl_table.addCell(new Phrase("Do zapłaty: " + brutto + "zł", font)); pl_table.addCell(new Phrase("słownie: " + slownie, font)); // dodanie tabeli platności do kontenera kt_table.addCell(pl_table); // tabelka rozliczenie podatku float[] widths2 = { 0.5f, 1f, 2f, 2f }; PdfPTable pd_table = new PdfPTable(widths2); // ustawienia tabelki podatku pd_table.setWidthPercentage(100); // zawartość tabelki podatku PdfPCell pd_cell = new PdfPCell(new Phrase( "Rozliczenie sprzedaży według stawek podatku", font)); pd_cell.setColspan(4); pd_table.addCell(pd_cell); if (vat == 23) { pd_table.addCell("23%"); pd_table.addCell(Float.toString(netto)); pd_table.addCell(Float.toString(podatek)); pd_table.addCell(Float.toString(brutto)); pd_table.addCell("7%"); pd_table.addCell(""); pd_table.addCell(""); pd_table.addCell(""); } else if (vat == 7) { pd_table.addCell("23%"); pd_table.addCell(""); pd_table.addCell(""); pd_table.addCell(""); pd_table.addCell("7%"); pd_table.addCell(Float.toString(netto)); pd_table.addCell(Float.toString(podatek)); pd_table.addCell(Float.toString(brutto)); } else { pd_table.addCell("23%"); pd_table.addCell("vat musi byc 23 lub 7"); pd_table.addCell("vat musi byc 23 lub 7"); pd_table.addCell("musi byc 23 lub 7"); pd_table.addCell("7%"); pd_table.addCell("vat musi byc 23 lub 7"); pd_table.addCell("vat musi byc 23 lub 7"); pd_table.addCell("vat musi byc 23 lub 7"); pd_table.addCell("vat musi byc 23 lub 7"); } // pd_table.addCell("3%"); // pd_table.addCell("tutaj suma bez 3%"); // pd_table.addCell("tutaj suma vat 3%"); // pd_table.addCell("tutaj suma brutto 3%"); // // pd_table.addCell("0%"); // pd_table.addCell("tutaj suma bez 0%"); // pd_table.addCell("tutaj suma vat 0%"); // pd_table.addCell("tutaj suma brutto 0%"); // kt_table.addCell(pd_table); document.add(kt_table); // koniec tabelka kontener } catch (DocumentException docex) { System.err.println(docex.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } // step 5: we close the document document.close(); }
public void generatePdf(String k_nazwa, String k_adres, String k_nip, String k_kod, String k_miesc, String usluga, String pkwiu, String ilosc, float netto, int vat, String platnosc, String termin, String numer_f, String data, String slownie) { // przeliczenia podatku float brutto = Przelicz.brutto(netto, vat); // skraca netto // TODO - przeliczanie z brutto netto = (float) Math.round(netto * 100) / 100; float podatek = Przelicz.podatek(netto, vat); document = new Document(); try { // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter .getInstance(document, new FileOutputStream("faktura.pdf")); document.open(); /* fonty */ BaseFont vera; if (System.getProperty("os.name").startsWith("Windows")) vera = BaseFont.createFont("C:\\Windows\\Fonts\\Arial.ttf", BaseFont.CP1250, BaseFont.EMBEDDED); else if (System.getProperty("os.name").equals("Mac OS X")) { vera = BaseFont.createFont("/Library/Fonts/Arial.ttf", BaseFont.CP1250, BaseFont.EMBEDDED); } else { vera = BaseFont.createFont( "/usr/share/fonts/corefonts/arial.ttf", BaseFont.CP1250, BaseFont.EMBEDDED); } Font font = new Font(vera, 12); PdfPTable table1 = new PdfPTable(2); // ustawienia pierwszej tabeli table1.setWidthPercentage(100); table1.setSpacingBefore(5f); table1.setSpacingAfter(15f); table1.addCell(new Paragraph("Faktura VAT ORYGINAŁ/KOPIA", font)); table1.addCell(new Phrase("z dnia: " + data)); table1.addCell(new Phrase("nr. " + numer_f)); table1.addCell(new Phrase("Miejscowość: " + miejsc, font)); document.add(table1); /* * table1 zawiera table i table2 table - tabela z danymi * wystawiajacego fakture table2 - tabela z danymi odbiorcy faktury */ // tworzenie obiektow tabel PdfPTable table2 = new PdfPTable(4); // ustawienia tabeli sprzedawcy/nabywcy table2.setWidthPercentage(100); table2.setHeaderRows(1); // tabelki z danymi sprzedawcy/nabywcy PdfPCell cell_kup = new PdfPCell(new Phrase("Dane Nabywcy:")); cell_kup.setColspan(2); PdfPCell cell_sprzed = new PdfPCell(new Phrase("Dane Sprzedawcy:")); cell_sprzed.setColspan(2); table2.addCell(cell_sprzed); table2.addCell(cell_kup); table2.addCell("Nazwa:"); table2.addCell(new Phrase(nazwa, font)); table2.addCell("Nazwa:"); table2.addCell(new Phrase(k_nazwa, font)); table2.addCell("Nip"); table2.addCell(new Phrase(nip, font)); table2.addCell("Nip"); table2.addCell(new Phrase(k_nip, font)); table2.addCell("Adres"); table2.addCell(new Phrase(adres, font)); table2.addCell("Adres"); table2.addCell(new Phrase(k_adres, font)); table2.addCell(new Phrase("Miejscowość", font)); table2.addCell(new Phrase(kod + " " + miejsc, font)); table2.addCell(new Phrase("Miejscowość", font)); table2.addCell(new Phrase(k_kod + " " + k_miesc, font)); document.add(table2); // koniec tabeli sprzedawcy/nabywcy // tabela produktu // ustawienia tabelki float[] widths = { 6f, 1f, 1f, 1f, 2f, 2f, 1f, 2f }; PdfPTable pr_table = new PdfPTable(widths); pr_table.setSpacingBefore(15f); pr_table.setSpacingAfter(24); pr_table.setWidthPercentage(100); // dane tabeli produktu pr_table.addCell(new Phrase("Nazwa Towaru/Usługi", font)); pr_table.addCell(new Phrase("PKWiU", font)); pr_table.addCell(new Phrase("j.m", font)); pr_table.addCell(new Phrase("Ilość", font)); pr_table.addCell(new Phrase("Wartość netto", font)); pr_table.addCell(new Phrase("Kwota Podatku", font)); pr_table.addCell(new Phrase("% VAT", font)); pr_table.addCell(new Phrase("Wartość Brutto", font)); pr_table.addCell(new Phrase(usluga, font)); pr_table.addCell(pkwiu); pr_table.addCell(""); pr_table.addCell(ilosc); pr_table.addCell(Float.toString(netto)); pr_table.addCell(Float.toString(Przelicz.podatek(netto, vat))); pr_table.addCell(Integer.toString(vat)); pr_table.addCell(Float.toString(brutto)); document.add(pr_table); // koniec tabelki produktu // tabelka kontener PdfPTable kt_table = new PdfPTable(2); kt_table.setWidthPercentage(100); // tabelka płatności w kontener PdfPTable pl_table = new PdfPTable(2); PdfPCell pl_cell = new PdfPCell(new Phrase(" numer konta: " + konto)); pl_table.getDefaultCell().setHorizontalAlignment( Element.ALIGN_RIGHT); pl_cell.setColspan(2); pl_table.addCell(new Phrase("Sposób Zapłaty: " + platnosc, font)); pl_table.addCell(new Phrase("termin płatności: " + termin, font)); pl_table.addCell(pl_cell); pl_table.addCell(new Phrase("Do zapłaty: " + brutto + "zł", font)); pl_table.addCell(new Phrase("słownie: " + slownie, font)); // dodanie tabeli platności do kontenera kt_table.addCell(pl_table); // tabelka rozliczenie podatku float[] widths2 = { 0.5f, 1f, 2f, 2f }; PdfPTable pd_table = new PdfPTable(widths2); // ustawienia tabelki podatku pd_table.setWidthPercentage(100); // zawartość tabelki podatku PdfPCell pd_cell = new PdfPCell(new Phrase( "Rozliczenie sprzedaży według stawek podatku", font)); pd_cell.setColspan(4); pd_table.addCell(pd_cell); if (vat == 23) { pd_table.addCell("23%"); pd_table.addCell(Float.toString(netto)); pd_table.addCell(Float.toString(podatek)); pd_table.addCell(Float.toString(brutto)); pd_table.addCell("7%"); pd_table.addCell(""); pd_table.addCell(""); pd_table.addCell(""); } else if (vat == 7) { pd_table.addCell("23%"); pd_table.addCell(""); pd_table.addCell(""); pd_table.addCell(""); pd_table.addCell("7%"); pd_table.addCell(Float.toString(netto)); pd_table.addCell(Float.toString(podatek)); pd_table.addCell(Float.toString(brutto)); } else { pd_table.addCell("23%"); pd_table.addCell("vat musi byc 23 lub 7"); pd_table.addCell("vat musi byc 23 lub 7"); pd_table.addCell("musi byc 23 lub 7"); pd_table.addCell("7%"); pd_table.addCell("vat musi byc 23 lub 7"); pd_table.addCell("vat musi byc 23 lub 7"); pd_table.addCell("vat musi byc 23 lub 7"); pd_table.addCell("vat musi byc 23 lub 7"); } // pd_table.addCell("3%"); // pd_table.addCell("tutaj suma bez 3%"); // pd_table.addCell("tutaj suma vat 3%"); // pd_table.addCell("tutaj suma brutto 3%"); // // pd_table.addCell("0%"); // pd_table.addCell("tutaj suma bez 0%"); // pd_table.addCell("tutaj suma vat 0%"); // pd_table.addCell("tutaj suma brutto 0%"); // kt_table.addCell(pd_table); document.add(kt_table); // koniec tabelka kontener } catch (DocumentException docex) { System.err.println(docex.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } // step 5: we close the document document.close(); }
diff --git a/weaver/src/org/aspectj/weaver/patterns/TypePattern.java b/weaver/src/org/aspectj/weaver/patterns/TypePattern.java index dcd453fa6..ddd8e598e 100644 --- a/weaver/src/org/aspectj/weaver/patterns/TypePattern.java +++ b/weaver/src/org/aspectj/weaver/patterns/TypePattern.java @@ -1,617 +1,621 @@ /* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * 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: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.patterns; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Modifier; import java.util.Iterator; import java.util.Map; import org.aspectj.bridge.MessageUtil; import org.aspectj.util.FuzzyBoolean; import org.aspectj.weaver.BCException; import org.aspectj.weaver.ISourceContext; import org.aspectj.weaver.IntMap; import org.aspectj.weaver.ResolvedType; import org.aspectj.weaver.TypeVariableReference; import org.aspectj.weaver.UnresolvedType; import org.aspectj.weaver.VersionedDataInputStream; import org.aspectj.weaver.WeaverMessages; import org.aspectj.weaver.World; /** * On creation, type pattern only contains WildTypePattern nodes, not BindingType or ExactType. * * <p>Then we call resolveBindings() during compilation * During concretization of enclosing pointcuts, we call remapAdviceFormals * * @author Erik Hilsdale * @author Jim Hugunin */ public abstract class TypePattern extends PatternNode { public static class MatchKind { private String name; public MatchKind(String name) { this.name = name; } public String toString() { return name; } } public static final MatchKind STATIC = new MatchKind("STATIC"); public static final MatchKind DYNAMIC = new MatchKind("DYNAMIC"); public static final TypePattern ELLIPSIS = new EllipsisTypePattern(); public static final TypePattern ANY = new AnyTypePattern(); public static final TypePattern NO = new NoTypePattern(); protected boolean includeSubtypes; protected boolean isVarArgs = false; protected AnnotationTypePattern annotationPattern = AnnotationTypePattern.ANY; protected TypePatternList typeParameters = TypePatternList.EMPTY; protected TypePattern(boolean includeSubtypes,boolean isVarArgs,TypePatternList typeParams) { this.includeSubtypes = includeSubtypes; this.isVarArgs = isVarArgs; this.typeParameters = (typeParams == null ? TypePatternList.EMPTY : typeParams); } protected TypePattern(boolean includeSubtypes, boolean isVarArgs) { this(includeSubtypes,isVarArgs,null); } public AnnotationTypePattern getAnnotationPattern() { return annotationPattern; } public boolean isVarArgs() { return isVarArgs; } public boolean isStarAnnotation() { return annotationPattern == AnnotationTypePattern.ANY; } public boolean isArray() { return false; } protected TypePattern(boolean includeSubtypes) { this(includeSubtypes,false); } public void setAnnotationTypePattern(AnnotationTypePattern annPatt) { this.annotationPattern = annPatt; } public void setTypeParameters(TypePatternList typeParams) { this.typeParameters = typeParams; } public TypePatternList getTypeParameters() { return this.typeParameters; } public void setIsVarArgs(boolean isVarArgs) { this.isVarArgs = isVarArgs; } // answer conservatively... protected boolean couldEverMatchSameTypesAs(TypePattern other) { if (this.includeSubtypes || other.includeSubtypes) return true; if (this.annotationPattern != AnnotationTypePattern.ANY) return true; if (other.annotationPattern != AnnotationTypePattern.ANY) return true; return false; } //XXX non-final for Not, && and || public boolean matchesStatically(ResolvedType type) { if (includeSubtypes) { return matchesSubtypes(type); } else { return matchesExactly(type); } } public abstract FuzzyBoolean matchesInstanceof(ResolvedType type); public final FuzzyBoolean matches(ResolvedType type, MatchKind kind) { FuzzyBoolean typeMatch = null; //??? This is part of gracefully handling missing references if (type.isMissing()) return FuzzyBoolean.NO; if (kind == STATIC) { // typeMatch = FuzzyBoolean.fromBoolean(matchesStatically(type)); // return typeMatch.and(annotationPattern.matches(type)); return FuzzyBoolean.fromBoolean(matchesStatically(type)); } else if (kind == DYNAMIC) { //System.err.println("matching: " + this + " with " + type); // typeMatch = matchesInstanceof(type); //System.err.println(" got: " + ret); // return typeMatch.and(annotationPattern.matches(type)); return matchesInstanceof(type); } else { throw new IllegalArgumentException("kind must be DYNAMIC or STATIC"); } } protected abstract boolean matchesExactly(ResolvedType type); protected abstract boolean matchesExactly(ResolvedType type, ResolvedType annotatedType); protected boolean matchesSubtypes(ResolvedType type) { //System.out.println("matching: " + this + " to " + type); if (matchesExactly(type)) { //System.out.println(" true"); return true; } // pr124808 Iterator typesIterator = null; if (type.isTypeVariableReference()) { typesIterator = ((TypeVariableReference)type).getTypeVariable().getFirstBound().resolve(type.getWorld()).getDirectSupertypes(); } else { - typesIterator = type.getDirectSupertypes(); + // pr223605 + if (type.isRawType()) { + type = type.getGenericType(); + } + typesIterator = type.getDirectSupertypes(); } // FuzzyBoolean ret = FuzzyBoolean.NO; // ??? -eh for (Iterator i = typesIterator; i.hasNext(); ) { ResolvedType superType = (ResolvedType)i.next(); // TODO asc generics, temporary whilst matching isnt aware.. //if (superType.isParameterizedType()) superType = superType.getRawType().resolve(superType.getWorld()); if (matchesSubtypes(superType,type)) return true; } return false; } protected boolean matchesSubtypes(ResolvedType superType, ResolvedType annotatedType) { //System.out.println("matching: " + this + " to " + type); if (matchesExactly(superType,annotatedType)) { //System.out.println(" true"); return true; } // FuzzyBoolean ret = FuzzyBoolean.NO; // ??? -eh for (Iterator i = superType.getDirectSupertypes(); i.hasNext(); ) { ResolvedType superSuperType = (ResolvedType)i.next(); if (matchesSubtypes(superSuperType,annotatedType)) return true; } return false; } public UnresolvedType resolveExactType(IScope scope, Bindings bindings) { TypePattern p = resolveBindings(scope, bindings, false, true); if (!(p instanceof ExactTypePattern)) return ResolvedType.MISSING; return ((ExactTypePattern)p).getType(); } public UnresolvedType getExactType() { if (this instanceof ExactTypePattern) return ((ExactTypePattern)this).getType(); else return ResolvedType.MISSING; } protected TypePattern notExactType(IScope s) { s.getMessageHandler().handleMessage(MessageUtil.error( WeaverMessages.format(WeaverMessages.EXACT_TYPE_PATTERN_REQD), getSourceLocation())); return NO; } // public boolean assertExactType(IMessageHandler m) { // if (this instanceof ExactTypePattern) return true; // // //XXX should try harder to avoid multiple errors for one problem // m.handleMessage(MessageUtil.error("exact type pattern required", getSourceLocation())); // return false; // } /** * This can modify in place, or return a new TypePattern if the type changes. */ public TypePattern resolveBindings(IScope scope, Bindings bindings, boolean allowBinding, boolean requireExactType) { annotationPattern = annotationPattern.resolveBindings(scope,bindings,allowBinding); return this; } public void resolve(World world) { annotationPattern.resolve(world); } /** * return a version of this type pattern in which all type variable references have been * replaced by their corresponding entry in the map. */ public abstract TypePattern parameterizeWith(Map typeVariableMap,World w); public void postRead(ResolvedType enclosingType) { } public boolean isStar() { return false; } /** * This is called during concretization of pointcuts, it is used by BindingTypePattern * to return a new BindingTypePattern with a formal index appropiate for the advice, * rather than for the lexical declaration, i.e. this handles transforamtions through * named pointcuts. * <pre> * pointcut foo(String name): args(name); * --&gt; This makes a BindingTypePattern(0) pointing to the 0th formal * * before(Foo f, String n): this(f) && foo(n) { ... } * --&gt; when resolveReferences is called on the args from the above, it * will return a BindingTypePattern(1) * * before(Foo f): this(f) && foo(*) { ... } * --&gt; when resolveReferences is called on the args from the above, it * will return an ExactTypePattern(String) * </pre> */ public TypePattern remapAdviceFormals(IntMap bindings) { return this; } public static final byte WILD = 1; public static final byte EXACT = 2; public static final byte BINDING = 3; public static final byte ELLIPSIS_KEY = 4; public static final byte ANY_KEY = 5; public static final byte NOT = 6; public static final byte OR = 7; public static final byte AND = 8; public static final byte NO_KEY = 9; public static final byte ANY_WITH_ANNO = 10; public static final byte HAS_MEMBER = 11; public static TypePattern read(VersionedDataInputStream s, ISourceContext context) throws IOException { byte key = s.readByte(); switch(key) { case WILD: return WildTypePattern.read(s, context); case EXACT: return ExactTypePattern.read(s, context); case BINDING: return BindingTypePattern.read(s, context); case ELLIPSIS_KEY: return ELLIPSIS; case ANY_KEY: return ANY; case NO_KEY: return NO; case NOT: return NotTypePattern.read(s, context); case OR: return OrTypePattern.read(s, context); case AND: return AndTypePattern.read(s, context); case ANY_WITH_ANNO: return AnyWithAnnotationTypePattern.read(s,context); case HAS_MEMBER: return HasMemberTypePattern.read(s,context); } throw new BCException("unknown TypePattern kind: " + key); } public boolean isIncludeSubtypes() { return includeSubtypes; } } class EllipsisTypePattern extends TypePattern { /** * Constructor for EllipsisTypePattern. * @param includeSubtypes */ public EllipsisTypePattern() { super(false,false,new TypePatternList()); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern) */ protected boolean couldEverMatchSameTypesAs(TypePattern other) { return true; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesExactly(IType) */ protected boolean matchesExactly(ResolvedType type) { return false; } protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) { return false; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesInstanceof(IType) */ public FuzzyBoolean matchesInstanceof(ResolvedType type) { return FuzzyBoolean.NO; } /** * @see org.aspectj.weaver.patterns.PatternNode#write(DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(ELLIPSIS_KEY); } public String toString() { return ".."; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { return (obj instanceof EllipsisTypePattern); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return 17 * 37; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public TypePattern parameterizeWith(Map typeVariableMap,World w) { return this; } } class AnyTypePattern extends TypePattern { /** * Constructor for EllipsisTypePattern. * @param includeSubtypes */ public AnyTypePattern() { super(false,false,new TypePatternList()); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern) */ protected boolean couldEverMatchSameTypesAs(TypePattern other) { return true; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesExactly(IType) */ protected boolean matchesExactly(ResolvedType type) { return true; } protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) { return true; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesInstanceof(IType) */ public FuzzyBoolean matchesInstanceof(ResolvedType type) { return FuzzyBoolean.YES; } /** * @see org.aspectj.weaver.patterns.PatternNode#write(DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(ANY_KEY); } /** * @see org.aspectj.weaver.patterns.TypePattern#matches(IType, MatchKind) */ // public FuzzyBoolean matches(IType type, MatchKind kind) { // return FuzzyBoolean.YES; // } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesSubtypes(IType) */ protected boolean matchesSubtypes(ResolvedType type) { return true; } public boolean isStar() { return true; } public String toString() { return "*"; } public boolean equals(Object obj) { return (obj instanceof AnyTypePattern); } public int hashCode() { return 37; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public TypePattern parameterizeWith(Map arg0,World w) { return this; } } /** * This type represents a type pattern of '*' but with an annotation specified, * e.g. '@Color *' */ class AnyWithAnnotationTypePattern extends TypePattern { public AnyWithAnnotationTypePattern(AnnotationTypePattern atp) { super(false,false); annotationPattern = atp; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this,data); } protected boolean couldEverMatchSameTypesAs(TypePattern other) { return true; } protected boolean matchesExactly(ResolvedType type) { annotationPattern.resolve(type.getWorld()); boolean b = false; if (type.temporaryAnnotationTypes!=null) { b = annotationPattern.matches(type,type.temporaryAnnotationTypes).alwaysTrue(); } else { b = annotationPattern.matches(type).alwaysTrue(); } return b; } protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) { annotationPattern.resolve(type.getWorld()); return annotationPattern.matches(annotatedType).alwaysTrue(); } public FuzzyBoolean matchesInstanceof(ResolvedType type) { if (Modifier.isFinal(type.getModifiers())) { return FuzzyBoolean.fromBoolean(matchesExactly(type)); } return FuzzyBoolean.MAYBE; } public TypePattern parameterizeWith(Map typeVariableMap,World w) { AnyWithAnnotationTypePattern ret = new AnyWithAnnotationTypePattern(this.annotationPattern.parameterizeWith(typeVariableMap,w)); ret.copyLocationFrom(this); return ret; } public void write(DataOutputStream s) throws IOException { s.writeByte(TypePattern.ANY_WITH_ANNO); annotationPattern.write(s); writeLocation(s); } public static TypePattern read(VersionedDataInputStream s,ISourceContext c) throws IOException { AnnotationTypePattern annPatt = AnnotationTypePattern.read(s,c); AnyWithAnnotationTypePattern ret = new AnyWithAnnotationTypePattern(annPatt); ret.readLocation(c, s); return ret; } // public FuzzyBoolean matches(IType type, MatchKind kind) { // return FuzzyBoolean.YES; // } protected boolean matchesSubtypes(ResolvedType type) { return true; } public boolean isStar() { return false; } public String toString() { return annotationPattern+" *"; } public boolean equals(Object obj) { if (!(obj instanceof AnyWithAnnotationTypePattern)) return false; AnyWithAnnotationTypePattern awatp = (AnyWithAnnotationTypePattern) obj; return (annotationPattern.equals(awatp.annotationPattern)); } public int hashCode() { return annotationPattern.hashCode(); } } class NoTypePattern extends TypePattern { public NoTypePattern() { super(false,false,new TypePatternList()); } /* (non-Javadoc) * @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern) */ protected boolean couldEverMatchSameTypesAs(TypePattern other) { return false; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesExactly(IType) */ protected boolean matchesExactly(ResolvedType type) { return false; } protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) { return false; } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesInstanceof(IType) */ public FuzzyBoolean matchesInstanceof(ResolvedType type) { return FuzzyBoolean.NO; } /** * @see org.aspectj.weaver.patterns.PatternNode#write(DataOutputStream) */ public void write(DataOutputStream s) throws IOException { s.writeByte(NO_KEY); } /** * @see org.aspectj.weaver.patterns.TypePattern#matches(IType, MatchKind) */ // public FuzzyBoolean matches(IType type, MatchKind kind) { // return FuzzyBoolean.YES; // } /** * @see org.aspectj.weaver.patterns.TypePattern#matchesSubtypes(IType) */ protected boolean matchesSubtypes(ResolvedType type) { return false; } public boolean isStar() { return false; } public String toString() { return "<nothing>"; }//FIXME AV - bad! toString() cannot be parsed back (not idempotent) /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { return (obj instanceof NoTypePattern); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ public int hashCode() { return 17 * 37 * 37; } public Object accept(PatternNodeVisitor visitor, Object data) { return visitor.visit(this, data); } public TypePattern parameterizeWith(Map arg0,World w) { return this; } }
true
true
protected boolean matchesSubtypes(ResolvedType type) { //System.out.println("matching: " + this + " to " + type); if (matchesExactly(type)) { //System.out.println(" true"); return true; } // pr124808 Iterator typesIterator = null; if (type.isTypeVariableReference()) { typesIterator = ((TypeVariableReference)type).getTypeVariable().getFirstBound().resolve(type.getWorld()).getDirectSupertypes(); } else { typesIterator = type.getDirectSupertypes(); } // FuzzyBoolean ret = FuzzyBoolean.NO; // ??? -eh for (Iterator i = typesIterator; i.hasNext(); ) { ResolvedType superType = (ResolvedType)i.next(); // TODO asc generics, temporary whilst matching isnt aware.. //if (superType.isParameterizedType()) superType = superType.getRawType().resolve(superType.getWorld()); if (matchesSubtypes(superType,type)) return true; } return false; }
protected boolean matchesSubtypes(ResolvedType type) { //System.out.println("matching: " + this + " to " + type); if (matchesExactly(type)) { //System.out.println(" true"); return true; } // pr124808 Iterator typesIterator = null; if (type.isTypeVariableReference()) { typesIterator = ((TypeVariableReference)type).getTypeVariable().getFirstBound().resolve(type.getWorld()).getDirectSupertypes(); } else { // pr223605 if (type.isRawType()) { type = type.getGenericType(); } typesIterator = type.getDirectSupertypes(); } // FuzzyBoolean ret = FuzzyBoolean.NO; // ??? -eh for (Iterator i = typesIterator; i.hasNext(); ) { ResolvedType superType = (ResolvedType)i.next(); // TODO asc generics, temporary whilst matching isnt aware.. //if (superType.isParameterizedType()) superType = superType.getRawType().resolve(superType.getWorld()); if (matchesSubtypes(superType,type)) return true; } return false; }
diff --git a/java/testing/org/apache/derbyTesting/functionTests/tests/lang/ErrorCodeTest.java b/java/testing/org/apache/derbyTesting/functionTests/tests/lang/ErrorCodeTest.java index c6a56c38b..500d14514 100644 --- a/java/testing/org/apache/derbyTesting/functionTests/tests/lang/ErrorCodeTest.java +++ b/java/testing/org/apache/derbyTesting/functionTests/tests/lang/ErrorCodeTest.java @@ -1,271 +1,273 @@ /** * Derby - Class org.apache.derbyTesting.functionTests.tests.lang.ErrorCodeTest * * 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.derbyTesting.functionTests.tests.lang; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.derbyTesting.junit.BaseJDBCTestCase; import org.apache.derbyTesting.junit.LocaleTestSetup; import org.apache.derbyTesting.junit.TestConfiguration; import java.sql.ResultSet; import java.sql.Statement; import java.util.Locale; import org.apache.derbyTesting.junit.JDBC; public final class ErrorCodeTest extends BaseJDBCTestCase { /** * Public constructor required for running test as standalone JUnit. */ public ErrorCodeTest(String name) { super(name); } public static Test suite() { TestSuite suite = new TestSuite("errorcode Test"); suite.addTest(TestConfiguration.embeddedSuite(ErrorCodeTest.class)); return new LocaleTestSetup(suite, Locale.ENGLISH); } public void test_errorcode() throws Exception { ResultSet rs = null; Statement s = createStatement(); s.executeUpdate( "create table t(i int, s smallint)"); s.executeUpdate( "insert into t values (1,2)"); s.executeUpdate("insert into t values (1,2)"); s.executeUpdate("insert into t values (null,2)"); //-- parser error //-- bug 5701 assertStatementError("42X94",30000,s,"create table t(i nt, s smallint)"); //-- non-boolean where clause assertStatementError("42X19", 30000, s, "select * from t where i"); // -- invalid correlation name for "*" assertStatementError("42X10",30000, s, "select asdf.* from t"); //-- execution time error assertStatementError("22012",30000,s,"select i/0 from t"); // -- test ErrorMessages VTI rs = s.executeQuery( "select * from SYSCS_DIAG.error_Messages where " + "CAST(sql_state AS CHAR(5)) = '07000'"); String [][] expRS = new String [][] { {"07000", "At least one parameter to the current statement " + "is uninitialized.", "20000"} }; JDBC.assertFullResultSet(rs,expRS); // Test severe error messages. Existing messages should not change SQLState. // new ones can be added. rs = s.executeQuery("select * from SYSCS_DIAG.Error_messages where SEVERITY >= 40000 order by SQL_STATE"); //Utilities.showResultSet(rs); String [][] expectedRows = {{"08000","Connection closed by unknown interrupt.","40000"}, {"08001","A connection could not be established because the security token is larger than the maximum allowed by the network protocol.","40000"}, {"08001","A connection could not be established because the user id has a length of zero or is larger than the maximum allowed by the network protocol.","40000"}, {"08001","A connection could not be established because the password has a length of zero or is larger than the maximum allowed by the network protocol.","40000"}, {"08001","A connection could not be established because the external name (EXTNAM) has a length of zero or is larger than the maximum allowed by the network protocol.","40000"}, {"08001","A connection could not be established because the server name (SRVNAM) has a length of zero or is larger than the maximum allowed by the network protocol.","40000"}, {"08001","Required Derby DataSource property {0} not set.","40000"}, {"08001","{0} : Error connecting to server {1} on port {2} with message {3}.","40000"}, {"08001","SocketException: '{0}'","40000"}, {"08001","Unable to open stream on socket: '{0}'.","40000"}, {"08001","User id length ({0}) is outside the range of 1 to {1}.","40000"}, {"08001","Password length ({0}) is outside the range of 1 to {1}.","40000"}, {"08001","User id can not be null.","40000"}, {"08001","Password can not be null.","40000"}, {"08001","A connection could not be established because the database name '{0}' is larger than the maximum length allowed by the network protocol.","40000"}, {"08003","No current connection.","40000"}, {"08003","getConnection() is not valid on a closed PooledConnection.","40000"}, {"08003","Lob method called after connection was closed","40000"}, {"08003","The underlying physical connection is stale or closed.","40000"}, {"08004","Connection refused : {0}","40000"}, {"08004","Connection authentication failure occurred. Reason: {0}.","40000"}, {"08004","The connection was refused because the database {0} was not found.","40000"}, {"08004","Database connection refused.","40000"}, {"08004","User '{0}' cannot shut down database '{1}'. Only the database owner can perform this operation.","40000"}, {"08004","User '{0}' cannot (re)encrypt database '{1}'. Only the database owner can perform this operation.","40000"}, {"08004","User '{0}' cannot hard upgrade database '{1}'. Only the database owner can perform this operation.","40000"}, {"08004","Connection refused to database '{0}' because it is in replication slave mode.","40000"}, {"08004","User '{0}' cannot issue a replication operation on database '{1}'. Only the database owner can perform this operation.","40000"}, {"08004","Missing permission for user '{0}' to shutdown system [{1}].","40000"}, {"08004","Cannot check system permission to create database '{0}' [{1}].","40000"}, {"08004","Missing permission for user '{0}' to create database '{1}' [{2}].","40000"}, {"08004","Connection authentication failure occurred. Either the supplied credentials were invalid, or the database uses a password encryption scheme not compatible with the strong password substitution security mechanism. If this error started after upgrade, refer to the release note for DERBY-4483 for options.","40000"}, {"08006","An error occurred during connect reset and the connection has been terminated. See chained exceptions for details.","40000"}, {"08006","SocketException: '{0}'","40000"}, {"08006","A communications error has been detected: {0}.","40000"}, {"08006","An error occurred during a deferred connect reset and the connection has been terminated. See chained exceptions for details.","40000"}, {"08006","Insufficient data while reading from the network - expected a minimum of {0} bytes and received only {1} bytes. The connection has been terminated.","40000"}, {"08006","Attempt to fully materialize lob data that is too large for the JVM. The connection has been terminated.","40000"}, {"08006","A network protocol error was encountered and the connection has been terminated: {0}","40000"}, {"08006","org.apache.derby.jdbc.EmbeddedDriver is not registered with the JDBC driver manager","40000"}, {"08006","Database '{0}' shutdown.","45000"}, {"08006","Database '{0}' dropped.","45000"}, {"0A000","The DRDA command {0} is not currently implemented. The connection has been terminated.","40000"}, {"57017","There is no available conversion for the source code page, {0}, to the target code page, {1}. The connection has been terminated.","40000"}, {"58009","Network protocol exception: only one of the VCM, VCS length can be greater than 0. The connection has been terminated.","40000"}, {"58009","The connection was terminated because the encoding is not supported.","40000"}, {"58009","Network protocol exception: actual code point, {0}, does not match expected code point, {1}. The connection has been terminated.","40000"}, {"58009","Network protocol exception: DDM collection contains less than 4 bytes of data. The connection has been terminated.","40000"}, {"58009","Network protocol exception: collection stack not empty at end of same id chain parse. The connection has been terminated.","40000"}, {"58009","Network protocol exception: DSS length not 0 at end of same id chain parse. The connection has been terminated.","40000"}, {"58009","Network protocol exception: DSS chained with same id at end of same id chain parse. The connection has been terminated.","40000"}, {"58009","Network protocol exception: end of stream prematurely reached while reading InputStream, parameter #{0}. The connection has been terminated.","40000"}, {"58009","Network protocol exception: invalid FDOCA LID. The connection has been terminated.","40000"}, {"58009","Network protocol exception: SECTKN was not returned. The connection has been terminated.","40000"}, {"58009","Network protocol exception: only one of NVCM, NVCS can be non-null. The connection has been terminated.","40000"}, {"58009","Network protocol exception: SCLDTA length, {0}, is invalid for RDBNAM. The connection has been terminated.","40000"}, {"58009","Network protocol exception: SCLDTA length, {0}, is invalid for RDBCOLID. The connection has been terminated.","40000"}, {"58009","Network protocol exception: SCLDTA length, {0}, is invalid for PKGID. The connection has been terminated.","40000"}, {"58009","Network protocol exception: PKGNAMCSN length, {0}, is invalid at SQLAM {1}. The connection has been terminated.","40000"}, {"58010","A network protocol error was encountered. A connection could not be established because the manager {0} at level {1} is not supported by the server. ","40000"}, {"58014","The DDM command 0x{0} is not supported. The connection has been terminated.","40000"}, {"58015","The DDM object 0x{0} is not supported. The connection has been terminated.","40000"}, {"58016","The DDM parameter 0x{0} is not supported. The connection has been terminated.","40000"}, {"58017","The DDM parameter value 0x{0} is not supported. An input host variable may not be within the range the server supports. The connection has been terminated.","40000"}, {"XBM01","Startup failed due to an exception. See next exception for details. ","45000"}, {"XBM02","Startup failed due to missing functionality for {0}. Please ensure your classpath includes the correct Derby software.","45000"}, {"XBM03","Supplied value '{0}' for collation attribute is invalid, expecting UCS_BASIC or TERRITORY_BASED.","45000"}, {"XBM04","Collator support not available from the JVM for the database's locale '{0}'.","45000"}, {"XBM05","Startup failed due to missing product version information for {0}.","45000"}, {"XBM06","Startup failed. An encrypted database cannot be accessed without the correct boot password. ","45000"}, {"XBM07","Startup failed. Boot password must be at least 8 bytes long.","45000"}, {"XBM08","Could not instantiate {0} StorageFactory class {1}.","45000"}, {"XBM0A","The database directory '{0}' exists. However, it does not contain the expected '{1}' file. Perhaps Derby was brought down in the middle of creating this database. You may want to delete this directory and try creating the database again.","45000"}, + {"XBM0B","Failed to edit/write service properties file: {0}","45000"}, + {"XBM0C","Missing privilege for operation '{0}' on file '{1}': {2}", "45000"}, {"XBM0G","Failed to start encryption engine. Please make sure you are running Java 2 and have downloaded an encryption provider such as jce and put it in your class path. ","45000"}, {"XBM0H","Directory {0} cannot be created.","45000"}, {"XBM0I","Directory {0} cannot be removed.","45000"}, {"XBM0J","Directory {0} already exists.","45000"}, {"XBM0K","Unknown sub-protocol for database name {0}.","45000"}, {"XBM0L","Specified authentication scheme class {0} does implement the authentication interface {1}.","45000"}, {"XBM0M","Error creating instance of authentication scheme class {0}.","45000"}, {"XBM0N","JDBC Driver registration with java.sql.DriverManager failed. See next exception for details. ","45000"}, {"XBM0P","Service provider is read-only. Operation not permitted. ","45000"}, {"XBM0Q","File {0} not found. Please make sure that backup copy is the correct one and it is not corrupted.","45000"}, {"XBM0R","Unable to remove File {0}. ","45000"}, {"XBM0S","Unable to rename file '{0}' to '{1}'","45000"}, {"XBM0T","Ambiguous sub-protocol for database name {0}. ","45000"}, {"XBM0X","Supplied territory description '{0}' is invalid, expecting ln[_CO[_variant]]\nln=lower-case two-letter ISO-639 language code, CO=upper-case two-letter ISO-3166 country codes, see java.util.Locale.","45000"}, {"XBM0Y","Backup database directory {0} not found. Please make sure that the specified backup path is right.","45000"}, {"XBM0Z","Unable to copy file '{0}' to '{1}'. Please make sure that there is enough space and permissions are correct. ","45000"}, {"XCW00","Unsupported upgrade from '{0}' to '{1}'.","45000"}, {"XJ004","Database '{0}' not found.","40000"}, {"XJ015","Derby system shutdown.","50000"}, {"XJ028","The URL '{0}' is not properly formed.","40000"}, {"XJ040","Failed to start database '{0}' with class loader {1}, see the next exception for details.","40000"}, {"XJ041","Failed to create database '{0}', see the next exception for details.","40000"}, {"XJ048","Conflicting boot attributes specified: {0}","40000"}, {"XJ049","Conflicting create attributes specified.","40000"}, {"XJ05B","JDBC attribute '{0}' has an invalid value '{1}', valid values are '{2}'.","40000"}, {"XJ081","Conflicting create/restore/recovery attributes specified.","40000"}, {"XJ213","The traceLevel connection property does not have a valid format for a number.","40000"}, {"XRE20","Failover performed successfully for database '{0}', the database has been shutdown.","45000"}, {"XSDB0","Unexpected exception on in-memory page {0}","45000"}, {"XSDB1","Unknown page format at page {0}","45000"}, {"XSDB2","Unknown container format at container {0} : {1}","45000"}, {"XSDB3","Container information cannot change once written: was {0}, now {1}","45000"}, {"XSDB4","Page {0} is at version {1}, the log file contains change version {2}, either there are log records of this page missing, or this page did not get written out to disk properly.","45000"}, {"XSDB5","Log has change record on page {0}, which is beyond the end of the container.","45000"}, {"XSDB6","Another instance of Derby may have already booted the database {0}.","45000"}, {"XSDB7","WARNING: Derby (instance {0}) is attempting to boot the database {1} even though Derby (instance {2}) may still be active. Only one instance of Derby should boot a database at a time. Severe and non-recoverable corruption can result and may have already occurred.","45000"}, {"XSDB8","WARNING: Derby (instance {0}) is attempting to boot the database {1} even though Derby (instance {2}) may still be active. Only one instance of Derby should boot a database at a time. Severe and non-recoverable corruption can result if 2 instances of Derby boot on the same database at the same time. The derby.database.forceDatabaseLock=true property has been set, so the database will not boot until the db.lck is no longer present. Normally this file is removed when the first instance of Derby to boot on the database exits, but it may be left behind in some shutdowns. It will be necessary to remove the file by hand in that case. It is important to verify that no other VM is accessing the database before deleting the db.lck file by hand.","45000"}, {"XSDB9","Stream container {0} is corrupt.","45000"}, {"XSDBA","Attempt to allocate object {0} failed.","45000"}, {"XSDBB", "Unknown page format at page {0}, page dump follows: {1} ", "45000"}, {"XSDBC", "Write of container information to page 0 of container {0} failed. See nested error for more information. ", "45000"}, {"XSDG0","Page {0} could not be read from disk.","45000"}, {"XSDG1","Page {0} could not be written to disk, please check if the disk is full, or if a file system limit, such as a quota or a maximum file size, has been reached.","45000"}, {"XSDG2","Invalid checksum on Page {0}, expected={1}, on-disk version={2}, page dump follows: {3}","45000"}, {"XSDG3","Meta-data for {0} could not be accessed to {1} {2}","45000"}, {"XSDG5","Database is not in create mode when createFinished is called.","45000"}, {"XSDG6","Data segment directory not found in {0} backup during restore. Please make sure that backup copy is the right one and it is not corrupted.","45000"}, {"XSDG7","Directory {0} could not be removed during restore. Please make sure that permissions are correct.","45000"}, {"XSDG8","Unable to copy directory '{0}' to '{1}' during restore. Please make sure that there is enough space and permissions are correct. ","45000"}, {"XSDG9","Derby thread received an interrupt during a disk I/O operation, please check your application for the source of the interrupt.","45000"}, {"XSLA0","Cannot flush the log file to disk {0}.","45000"}, {"XSLA1","Log Record has been sent to the stream, but it cannot be applied to the store (Object {0}). This may cause recovery problems also.","45000"}, {"XSLA2","System will shutdown, got I/O Exception while accessing log file.","45000"}, {"XSLA3","Log Corrupted, has invalid data in the log stream.","45000"}, {"XSLA4","Cannot write to the log, most likely the log is full. Please delete unnecessary files. It is also possible that the file system is read only, or the disk has failed, or some other problems with the media. ","45000"}, {"XSLA5","Cannot read log stream for some reason to rollback transaction {0}.","45000"}, {"XSLA6","Cannot recover the database.","45000"}, {"XSLA7","Cannot redo operation {0} in the log.","45000"}, {"XSLA8","Cannot rollback transaction {0}, trying to compensate {1} operation with {2}","45000"}, {"XSLAA","The store has been marked for shutdown by an earlier exception.","45000"}, {"XSLAB","Cannot find log file {0}, please make sure your logDevice property is properly set with the correct path separator for your platform.","45000"}, {"XSLAC","Database at {0} have incompatible format with the current version of software, it may have been created by or upgraded by a later version.","45000"}, {"XSLAD","log Record at instant {2} in log file {3} corrupted. Expected log record length {0}, real length {1}.","45000"}, {"XSLAE","Control file at {0} cannot be written or updated.","45000"}, {"XSLAF","A Read Only database was created with dirty data buffers.","45000"}, {"XSLAH","A Read Only database is being updated.","45000"}, {"XSLAI","Cannot log the checkpoint log record","45000"}, {"XSLAJ","The logging system has been marked to shut down due to an earlier problem and will not allow any more operations until the system shuts down and restarts.","45000"}, {"XSLAK","Database has exceeded largest log file number {0}.","45000"}, {"XSLAL","log record size {2} exceeded the maximum allowable log file size {3}. Error encountered in log file {0}, position {1}.","45000"}, {"XSLAM","Cannot verify database format at {1} due to IOException.","45000"}, {"XSLAN","Database at {0} has an incompatible format with the current version of the software. The database was created by or upgraded by version {1}.","45000"}, {"XSLAO","Recovery failed unexpected problem {0}.","45000"}, {"XSLAP","Database at {0} is at version {1}. Beta databases cannot be upgraded,","45000"}, {"XSLAQ","cannot create log file at directory {0}.","45000"}, {"XSLAR","Unable to copy log file '{0}' to '{1}' during restore. Please make sure that there is enough space and permissions are correct. ","45000"}, {"XSLAS","Log directory {0} not found in backup during restore. Please make sure that backup copy is the correct one and it is not corrupted.","45000"}, {"XSLAT","The log directory '{0}' exists. The directory might belong to another database. Check that the location specified for the logDevice attribute is correct.","45000"}, {"XSTB0","An exception was thrown during transaction abort.","50000"}, {"XSTB2","Cannot log transaction changes, maybe trying to write to a read only database.","50000"}, {"XSTB3","Cannot abort transaction because the log manager is null, probably due to an earlier error.","50000"}, {"XSTB5","Creating database with logging disabled encountered unexpected problem.","50000"}, {"XSTB6","Cannot substitute a transaction table with another while one is already in use.","50000"}, {"XXXXX","Normal database session close.","40000"}, {"XRE04","Could not establish a connection to the peer of the replicated database '{0}' on address '{1}:{2}'.","40000"}, {"XRE04","Connection lost for replicated database '{0}'.","40000"}, {"XRE05","The log files on the master and slave are not in synch for replicated database '{0}'. The master log instant is {1}:{2}, whereas the slave log instant is {3}:{4}. This is FATAL for replication - replication will be stopped.","40000"}, {"XRE09","Cannot start replication slave mode for database '{0}'. The database has already been booted.","40000"}, {"XRE11","Could not perform operation '{0}' because the database '{1}' has not been booted.","40000"}, {"XRE21","Error occurred while performing failover for database '{0}', Failover attempt was aborted.","40000"}, {"XRE22","Replication master has already been booted for database '{0}'","40000"}, {"XRE41","Replication operation 'failover' or 'stopSlave' refused on the slave database because the connection with the master is working. Issue the 'failover' or 'stopMaster' operation on the master database instead.","40000"}, {"XRE42","Replicated database '{0}' shutdown.","40000"}}; JDBC.assertUnorderedResultSet(rs, expectedRows); s.executeUpdate("drop table t"); commit(); s.close(); } }
true
true
public void test_errorcode() throws Exception { ResultSet rs = null; Statement s = createStatement(); s.executeUpdate( "create table t(i int, s smallint)"); s.executeUpdate( "insert into t values (1,2)"); s.executeUpdate("insert into t values (1,2)"); s.executeUpdate("insert into t values (null,2)"); //-- parser error //-- bug 5701 assertStatementError("42X94",30000,s,"create table t(i nt, s smallint)"); //-- non-boolean where clause assertStatementError("42X19", 30000, s, "select * from t where i"); // -- invalid correlation name for "*" assertStatementError("42X10",30000, s, "select asdf.* from t"); //-- execution time error assertStatementError("22012",30000,s,"select i/0 from t"); // -- test ErrorMessages VTI rs = s.executeQuery( "select * from SYSCS_DIAG.error_Messages where " + "CAST(sql_state AS CHAR(5)) = '07000'"); String [][] expRS = new String [][] { {"07000", "At least one parameter to the current statement " + "is uninitialized.", "20000"} }; JDBC.assertFullResultSet(rs,expRS); // Test severe error messages. Existing messages should not change SQLState. // new ones can be added. rs = s.executeQuery("select * from SYSCS_DIAG.Error_messages where SEVERITY >= 40000 order by SQL_STATE"); //Utilities.showResultSet(rs); String [][] expectedRows = {{"08000","Connection closed by unknown interrupt.","40000"}, {"08001","A connection could not be established because the security token is larger than the maximum allowed by the network protocol.","40000"}, {"08001","A connection could not be established because the user id has a length of zero or is larger than the maximum allowed by the network protocol.","40000"}, {"08001","A connection could not be established because the password has a length of zero or is larger than the maximum allowed by the network protocol.","40000"}, {"08001","A connection could not be established because the external name (EXTNAM) has a length of zero or is larger than the maximum allowed by the network protocol.","40000"}, {"08001","A connection could not be established because the server name (SRVNAM) has a length of zero or is larger than the maximum allowed by the network protocol.","40000"}, {"08001","Required Derby DataSource property {0} not set.","40000"}, {"08001","{0} : Error connecting to server {1} on port {2} with message {3}.","40000"}, {"08001","SocketException: '{0}'","40000"}, {"08001","Unable to open stream on socket: '{0}'.","40000"}, {"08001","User id length ({0}) is outside the range of 1 to {1}.","40000"}, {"08001","Password length ({0}) is outside the range of 1 to {1}.","40000"}, {"08001","User id can not be null.","40000"}, {"08001","Password can not be null.","40000"}, {"08001","A connection could not be established because the database name '{0}' is larger than the maximum length allowed by the network protocol.","40000"}, {"08003","No current connection.","40000"}, {"08003","getConnection() is not valid on a closed PooledConnection.","40000"}, {"08003","Lob method called after connection was closed","40000"}, {"08003","The underlying physical connection is stale or closed.","40000"}, {"08004","Connection refused : {0}","40000"}, {"08004","Connection authentication failure occurred. Reason: {0}.","40000"}, {"08004","The connection was refused because the database {0} was not found.","40000"}, {"08004","Database connection refused.","40000"}, {"08004","User '{0}' cannot shut down database '{1}'. Only the database owner can perform this operation.","40000"}, {"08004","User '{0}' cannot (re)encrypt database '{1}'. Only the database owner can perform this operation.","40000"}, {"08004","User '{0}' cannot hard upgrade database '{1}'. Only the database owner can perform this operation.","40000"}, {"08004","Connection refused to database '{0}' because it is in replication slave mode.","40000"}, {"08004","User '{0}' cannot issue a replication operation on database '{1}'. Only the database owner can perform this operation.","40000"}, {"08004","Missing permission for user '{0}' to shutdown system [{1}].","40000"}, {"08004","Cannot check system permission to create database '{0}' [{1}].","40000"}, {"08004","Missing permission for user '{0}' to create database '{1}' [{2}].","40000"}, {"08004","Connection authentication failure occurred. Either the supplied credentials were invalid, or the database uses a password encryption scheme not compatible with the strong password substitution security mechanism. If this error started after upgrade, refer to the release note for DERBY-4483 for options.","40000"}, {"08006","An error occurred during connect reset and the connection has been terminated. See chained exceptions for details.","40000"}, {"08006","SocketException: '{0}'","40000"}, {"08006","A communications error has been detected: {0}.","40000"}, {"08006","An error occurred during a deferred connect reset and the connection has been terminated. See chained exceptions for details.","40000"}, {"08006","Insufficient data while reading from the network - expected a minimum of {0} bytes and received only {1} bytes. The connection has been terminated.","40000"}, {"08006","Attempt to fully materialize lob data that is too large for the JVM. The connection has been terminated.","40000"}, {"08006","A network protocol error was encountered and the connection has been terminated: {0}","40000"}, {"08006","org.apache.derby.jdbc.EmbeddedDriver is not registered with the JDBC driver manager","40000"}, {"08006","Database '{0}' shutdown.","45000"}, {"08006","Database '{0}' dropped.","45000"}, {"0A000","The DRDA command {0} is not currently implemented. The connection has been terminated.","40000"}, {"57017","There is no available conversion for the source code page, {0}, to the target code page, {1}. The connection has been terminated.","40000"}, {"58009","Network protocol exception: only one of the VCM, VCS length can be greater than 0. The connection has been terminated.","40000"}, {"58009","The connection was terminated because the encoding is not supported.","40000"}, {"58009","Network protocol exception: actual code point, {0}, does not match expected code point, {1}. The connection has been terminated.","40000"}, {"58009","Network protocol exception: DDM collection contains less than 4 bytes of data. The connection has been terminated.","40000"}, {"58009","Network protocol exception: collection stack not empty at end of same id chain parse. The connection has been terminated.","40000"}, {"58009","Network protocol exception: DSS length not 0 at end of same id chain parse. The connection has been terminated.","40000"}, {"58009","Network protocol exception: DSS chained with same id at end of same id chain parse. The connection has been terminated.","40000"}, {"58009","Network protocol exception: end of stream prematurely reached while reading InputStream, parameter #{0}. The connection has been terminated.","40000"}, {"58009","Network protocol exception: invalid FDOCA LID. The connection has been terminated.","40000"}, {"58009","Network protocol exception: SECTKN was not returned. The connection has been terminated.","40000"}, {"58009","Network protocol exception: only one of NVCM, NVCS can be non-null. The connection has been terminated.","40000"}, {"58009","Network protocol exception: SCLDTA length, {0}, is invalid for RDBNAM. The connection has been terminated.","40000"}, {"58009","Network protocol exception: SCLDTA length, {0}, is invalid for RDBCOLID. The connection has been terminated.","40000"}, {"58009","Network protocol exception: SCLDTA length, {0}, is invalid for PKGID. The connection has been terminated.","40000"}, {"58009","Network protocol exception: PKGNAMCSN length, {0}, is invalid at SQLAM {1}. The connection has been terminated.","40000"}, {"58010","A network protocol error was encountered. A connection could not be established because the manager {0} at level {1} is not supported by the server. ","40000"}, {"58014","The DDM command 0x{0} is not supported. The connection has been terminated.","40000"}, {"58015","The DDM object 0x{0} is not supported. The connection has been terminated.","40000"}, {"58016","The DDM parameter 0x{0} is not supported. The connection has been terminated.","40000"}, {"58017","The DDM parameter value 0x{0} is not supported. An input host variable may not be within the range the server supports. The connection has been terminated.","40000"}, {"XBM01","Startup failed due to an exception. See next exception for details. ","45000"}, {"XBM02","Startup failed due to missing functionality for {0}. Please ensure your classpath includes the correct Derby software.","45000"}, {"XBM03","Supplied value '{0}' for collation attribute is invalid, expecting UCS_BASIC or TERRITORY_BASED.","45000"}, {"XBM04","Collator support not available from the JVM for the database's locale '{0}'.","45000"}, {"XBM05","Startup failed due to missing product version information for {0}.","45000"}, {"XBM06","Startup failed. An encrypted database cannot be accessed without the correct boot password. ","45000"}, {"XBM07","Startup failed. Boot password must be at least 8 bytes long.","45000"}, {"XBM08","Could not instantiate {0} StorageFactory class {1}.","45000"}, {"XBM0A","The database directory '{0}' exists. However, it does not contain the expected '{1}' file. Perhaps Derby was brought down in the middle of creating this database. You may want to delete this directory and try creating the database again.","45000"}, {"XBM0G","Failed to start encryption engine. Please make sure you are running Java 2 and have downloaded an encryption provider such as jce and put it in your class path. ","45000"}, {"XBM0H","Directory {0} cannot be created.","45000"}, {"XBM0I","Directory {0} cannot be removed.","45000"}, {"XBM0J","Directory {0} already exists.","45000"}, {"XBM0K","Unknown sub-protocol for database name {0}.","45000"}, {"XBM0L","Specified authentication scheme class {0} does implement the authentication interface {1}.","45000"}, {"XBM0M","Error creating instance of authentication scheme class {0}.","45000"}, {"XBM0N","JDBC Driver registration with java.sql.DriverManager failed. See next exception for details. ","45000"}, {"XBM0P","Service provider is read-only. Operation not permitted. ","45000"}, {"XBM0Q","File {0} not found. Please make sure that backup copy is the correct one and it is not corrupted.","45000"}, {"XBM0R","Unable to remove File {0}. ","45000"}, {"XBM0S","Unable to rename file '{0}' to '{1}'","45000"}, {"XBM0T","Ambiguous sub-protocol for database name {0}. ","45000"}, {"XBM0X","Supplied territory description '{0}' is invalid, expecting ln[_CO[_variant]]\nln=lower-case two-letter ISO-639 language code, CO=upper-case two-letter ISO-3166 country codes, see java.util.Locale.","45000"}, {"XBM0Y","Backup database directory {0} not found. Please make sure that the specified backup path is right.","45000"}, {"XBM0Z","Unable to copy file '{0}' to '{1}'. Please make sure that there is enough space and permissions are correct. ","45000"}, {"XCW00","Unsupported upgrade from '{0}' to '{1}'.","45000"}, {"XJ004","Database '{0}' not found.","40000"}, {"XJ015","Derby system shutdown.","50000"}, {"XJ028","The URL '{0}' is not properly formed.","40000"}, {"XJ040","Failed to start database '{0}' with class loader {1}, see the next exception for details.","40000"}, {"XJ041","Failed to create database '{0}', see the next exception for details.","40000"}, {"XJ048","Conflicting boot attributes specified: {0}","40000"}, {"XJ049","Conflicting create attributes specified.","40000"}, {"XJ05B","JDBC attribute '{0}' has an invalid value '{1}', valid values are '{2}'.","40000"}, {"XJ081","Conflicting create/restore/recovery attributes specified.","40000"}, {"XJ213","The traceLevel connection property does not have a valid format for a number.","40000"}, {"XRE20","Failover performed successfully for database '{0}', the database has been shutdown.","45000"}, {"XSDB0","Unexpected exception on in-memory page {0}","45000"}, {"XSDB1","Unknown page format at page {0}","45000"}, {"XSDB2","Unknown container format at container {0} : {1}","45000"}, {"XSDB3","Container information cannot change once written: was {0}, now {1}","45000"}, {"XSDB4","Page {0} is at version {1}, the log file contains change version {2}, either there are log records of this page missing, or this page did not get written out to disk properly.","45000"}, {"XSDB5","Log has change record on page {0}, which is beyond the end of the container.","45000"}, {"XSDB6","Another instance of Derby may have already booted the database {0}.","45000"}, {"XSDB7","WARNING: Derby (instance {0}) is attempting to boot the database {1} even though Derby (instance {2}) may still be active. Only one instance of Derby should boot a database at a time. Severe and non-recoverable corruption can result and may have already occurred.","45000"}, {"XSDB8","WARNING: Derby (instance {0}) is attempting to boot the database {1} even though Derby (instance {2}) may still be active. Only one instance of Derby should boot a database at a time. Severe and non-recoverable corruption can result if 2 instances of Derby boot on the same database at the same time. The derby.database.forceDatabaseLock=true property has been set, so the database will not boot until the db.lck is no longer present. Normally this file is removed when the first instance of Derby to boot on the database exits, but it may be left behind in some shutdowns. It will be necessary to remove the file by hand in that case. It is important to verify that no other VM is accessing the database before deleting the db.lck file by hand.","45000"}, {"XSDB9","Stream container {0} is corrupt.","45000"}, {"XSDBA","Attempt to allocate object {0} failed.","45000"}, {"XSDBB", "Unknown page format at page {0}, page dump follows: {1} ", "45000"}, {"XSDBC", "Write of container information to page 0 of container {0} failed. See nested error for more information. ", "45000"}, {"XSDG0","Page {0} could not be read from disk.","45000"}, {"XSDG1","Page {0} could not be written to disk, please check if the disk is full, or if a file system limit, such as a quota or a maximum file size, has been reached.","45000"}, {"XSDG2","Invalid checksum on Page {0}, expected={1}, on-disk version={2}, page dump follows: {3}","45000"}, {"XSDG3","Meta-data for {0} could not be accessed to {1} {2}","45000"}, {"XSDG5","Database is not in create mode when createFinished is called.","45000"}, {"XSDG6","Data segment directory not found in {0} backup during restore. Please make sure that backup copy is the right one and it is not corrupted.","45000"}, {"XSDG7","Directory {0} could not be removed during restore. Please make sure that permissions are correct.","45000"}, {"XSDG8","Unable to copy directory '{0}' to '{1}' during restore. Please make sure that there is enough space and permissions are correct. ","45000"}, {"XSDG9","Derby thread received an interrupt during a disk I/O operation, please check your application for the source of the interrupt.","45000"}, {"XSLA0","Cannot flush the log file to disk {0}.","45000"}, {"XSLA1","Log Record has been sent to the stream, but it cannot be applied to the store (Object {0}). This may cause recovery problems also.","45000"}, {"XSLA2","System will shutdown, got I/O Exception while accessing log file.","45000"}, {"XSLA3","Log Corrupted, has invalid data in the log stream.","45000"}, {"XSLA4","Cannot write to the log, most likely the log is full. Please delete unnecessary files. It is also possible that the file system is read only, or the disk has failed, or some other problems with the media. ","45000"}, {"XSLA5","Cannot read log stream for some reason to rollback transaction {0}.","45000"}, {"XSLA6","Cannot recover the database.","45000"}, {"XSLA7","Cannot redo operation {0} in the log.","45000"}, {"XSLA8","Cannot rollback transaction {0}, trying to compensate {1} operation with {2}","45000"}, {"XSLAA","The store has been marked for shutdown by an earlier exception.","45000"}, {"XSLAB","Cannot find log file {0}, please make sure your logDevice property is properly set with the correct path separator for your platform.","45000"}, {"XSLAC","Database at {0} have incompatible format with the current version of software, it may have been created by or upgraded by a later version.","45000"}, {"XSLAD","log Record at instant {2} in log file {3} corrupted. Expected log record length {0}, real length {1}.","45000"}, {"XSLAE","Control file at {0} cannot be written or updated.","45000"}, {"XSLAF","A Read Only database was created with dirty data buffers.","45000"}, {"XSLAH","A Read Only database is being updated.","45000"}, {"XSLAI","Cannot log the checkpoint log record","45000"}, {"XSLAJ","The logging system has been marked to shut down due to an earlier problem and will not allow any more operations until the system shuts down and restarts.","45000"}, {"XSLAK","Database has exceeded largest log file number {0}.","45000"}, {"XSLAL","log record size {2} exceeded the maximum allowable log file size {3}. Error encountered in log file {0}, position {1}.","45000"}, {"XSLAM","Cannot verify database format at {1} due to IOException.","45000"}, {"XSLAN","Database at {0} has an incompatible format with the current version of the software. The database was created by or upgraded by version {1}.","45000"}, {"XSLAO","Recovery failed unexpected problem {0}.","45000"}, {"XSLAP","Database at {0} is at version {1}. Beta databases cannot be upgraded,","45000"}, {"XSLAQ","cannot create log file at directory {0}.","45000"}, {"XSLAR","Unable to copy log file '{0}' to '{1}' during restore. Please make sure that there is enough space and permissions are correct. ","45000"}, {"XSLAS","Log directory {0} not found in backup during restore. Please make sure that backup copy is the correct one and it is not corrupted.","45000"}, {"XSLAT","The log directory '{0}' exists. The directory might belong to another database. Check that the location specified for the logDevice attribute is correct.","45000"}, {"XSTB0","An exception was thrown during transaction abort.","50000"}, {"XSTB2","Cannot log transaction changes, maybe trying to write to a read only database.","50000"}, {"XSTB3","Cannot abort transaction because the log manager is null, probably due to an earlier error.","50000"}, {"XSTB5","Creating database with logging disabled encountered unexpected problem.","50000"}, {"XSTB6","Cannot substitute a transaction table with another while one is already in use.","50000"}, {"XXXXX","Normal database session close.","40000"}, {"XRE04","Could not establish a connection to the peer of the replicated database '{0}' on address '{1}:{2}'.","40000"}, {"XRE04","Connection lost for replicated database '{0}'.","40000"}, {"XRE05","The log files on the master and slave are not in synch for replicated database '{0}'. The master log instant is {1}:{2}, whereas the slave log instant is {3}:{4}. This is FATAL for replication - replication will be stopped.","40000"}, {"XRE09","Cannot start replication slave mode for database '{0}'. The database has already been booted.","40000"}, {"XRE11","Could not perform operation '{0}' because the database '{1}' has not been booted.","40000"}, {"XRE21","Error occurred while performing failover for database '{0}', Failover attempt was aborted.","40000"}, {"XRE22","Replication master has already been booted for database '{0}'","40000"}, {"XRE41","Replication operation 'failover' or 'stopSlave' refused on the slave database because the connection with the master is working. Issue the 'failover' or 'stopMaster' operation on the master database instead.","40000"}, {"XRE42","Replicated database '{0}' shutdown.","40000"}}; JDBC.assertUnorderedResultSet(rs, expectedRows); s.executeUpdate("drop table t"); commit(); s.close(); }
public void test_errorcode() throws Exception { ResultSet rs = null; Statement s = createStatement(); s.executeUpdate( "create table t(i int, s smallint)"); s.executeUpdate( "insert into t values (1,2)"); s.executeUpdate("insert into t values (1,2)"); s.executeUpdate("insert into t values (null,2)"); //-- parser error //-- bug 5701 assertStatementError("42X94",30000,s,"create table t(i nt, s smallint)"); //-- non-boolean where clause assertStatementError("42X19", 30000, s, "select * from t where i"); // -- invalid correlation name for "*" assertStatementError("42X10",30000, s, "select asdf.* from t"); //-- execution time error assertStatementError("22012",30000,s,"select i/0 from t"); // -- test ErrorMessages VTI rs = s.executeQuery( "select * from SYSCS_DIAG.error_Messages where " + "CAST(sql_state AS CHAR(5)) = '07000'"); String [][] expRS = new String [][] { {"07000", "At least one parameter to the current statement " + "is uninitialized.", "20000"} }; JDBC.assertFullResultSet(rs,expRS); // Test severe error messages. Existing messages should not change SQLState. // new ones can be added. rs = s.executeQuery("select * from SYSCS_DIAG.Error_messages where SEVERITY >= 40000 order by SQL_STATE"); //Utilities.showResultSet(rs); String [][] expectedRows = {{"08000","Connection closed by unknown interrupt.","40000"}, {"08001","A connection could not be established because the security token is larger than the maximum allowed by the network protocol.","40000"}, {"08001","A connection could not be established because the user id has a length of zero or is larger than the maximum allowed by the network protocol.","40000"}, {"08001","A connection could not be established because the password has a length of zero or is larger than the maximum allowed by the network protocol.","40000"}, {"08001","A connection could not be established because the external name (EXTNAM) has a length of zero or is larger than the maximum allowed by the network protocol.","40000"}, {"08001","A connection could not be established because the server name (SRVNAM) has a length of zero or is larger than the maximum allowed by the network protocol.","40000"}, {"08001","Required Derby DataSource property {0} not set.","40000"}, {"08001","{0} : Error connecting to server {1} on port {2} with message {3}.","40000"}, {"08001","SocketException: '{0}'","40000"}, {"08001","Unable to open stream on socket: '{0}'.","40000"}, {"08001","User id length ({0}) is outside the range of 1 to {1}.","40000"}, {"08001","Password length ({0}) is outside the range of 1 to {1}.","40000"}, {"08001","User id can not be null.","40000"}, {"08001","Password can not be null.","40000"}, {"08001","A connection could not be established because the database name '{0}' is larger than the maximum length allowed by the network protocol.","40000"}, {"08003","No current connection.","40000"}, {"08003","getConnection() is not valid on a closed PooledConnection.","40000"}, {"08003","Lob method called after connection was closed","40000"}, {"08003","The underlying physical connection is stale or closed.","40000"}, {"08004","Connection refused : {0}","40000"}, {"08004","Connection authentication failure occurred. Reason: {0}.","40000"}, {"08004","The connection was refused because the database {0} was not found.","40000"}, {"08004","Database connection refused.","40000"}, {"08004","User '{0}' cannot shut down database '{1}'. Only the database owner can perform this operation.","40000"}, {"08004","User '{0}' cannot (re)encrypt database '{1}'. Only the database owner can perform this operation.","40000"}, {"08004","User '{0}' cannot hard upgrade database '{1}'. Only the database owner can perform this operation.","40000"}, {"08004","Connection refused to database '{0}' because it is in replication slave mode.","40000"}, {"08004","User '{0}' cannot issue a replication operation on database '{1}'. Only the database owner can perform this operation.","40000"}, {"08004","Missing permission for user '{0}' to shutdown system [{1}].","40000"}, {"08004","Cannot check system permission to create database '{0}' [{1}].","40000"}, {"08004","Missing permission for user '{0}' to create database '{1}' [{2}].","40000"}, {"08004","Connection authentication failure occurred. Either the supplied credentials were invalid, or the database uses a password encryption scheme not compatible with the strong password substitution security mechanism. If this error started after upgrade, refer to the release note for DERBY-4483 for options.","40000"}, {"08006","An error occurred during connect reset and the connection has been terminated. See chained exceptions for details.","40000"}, {"08006","SocketException: '{0}'","40000"}, {"08006","A communications error has been detected: {0}.","40000"}, {"08006","An error occurred during a deferred connect reset and the connection has been terminated. See chained exceptions for details.","40000"}, {"08006","Insufficient data while reading from the network - expected a minimum of {0} bytes and received only {1} bytes. The connection has been terminated.","40000"}, {"08006","Attempt to fully materialize lob data that is too large for the JVM. The connection has been terminated.","40000"}, {"08006","A network protocol error was encountered and the connection has been terminated: {0}","40000"}, {"08006","org.apache.derby.jdbc.EmbeddedDriver is not registered with the JDBC driver manager","40000"}, {"08006","Database '{0}' shutdown.","45000"}, {"08006","Database '{0}' dropped.","45000"}, {"0A000","The DRDA command {0} is not currently implemented. The connection has been terminated.","40000"}, {"57017","There is no available conversion for the source code page, {0}, to the target code page, {1}. The connection has been terminated.","40000"}, {"58009","Network protocol exception: only one of the VCM, VCS length can be greater than 0. The connection has been terminated.","40000"}, {"58009","The connection was terminated because the encoding is not supported.","40000"}, {"58009","Network protocol exception: actual code point, {0}, does not match expected code point, {1}. The connection has been terminated.","40000"}, {"58009","Network protocol exception: DDM collection contains less than 4 bytes of data. The connection has been terminated.","40000"}, {"58009","Network protocol exception: collection stack not empty at end of same id chain parse. The connection has been terminated.","40000"}, {"58009","Network protocol exception: DSS length not 0 at end of same id chain parse. The connection has been terminated.","40000"}, {"58009","Network protocol exception: DSS chained with same id at end of same id chain parse. The connection has been terminated.","40000"}, {"58009","Network protocol exception: end of stream prematurely reached while reading InputStream, parameter #{0}. The connection has been terminated.","40000"}, {"58009","Network protocol exception: invalid FDOCA LID. The connection has been terminated.","40000"}, {"58009","Network protocol exception: SECTKN was not returned. The connection has been terminated.","40000"}, {"58009","Network protocol exception: only one of NVCM, NVCS can be non-null. The connection has been terminated.","40000"}, {"58009","Network protocol exception: SCLDTA length, {0}, is invalid for RDBNAM. The connection has been terminated.","40000"}, {"58009","Network protocol exception: SCLDTA length, {0}, is invalid for RDBCOLID. The connection has been terminated.","40000"}, {"58009","Network protocol exception: SCLDTA length, {0}, is invalid for PKGID. The connection has been terminated.","40000"}, {"58009","Network protocol exception: PKGNAMCSN length, {0}, is invalid at SQLAM {1}. The connection has been terminated.","40000"}, {"58010","A network protocol error was encountered. A connection could not be established because the manager {0} at level {1} is not supported by the server. ","40000"}, {"58014","The DDM command 0x{0} is not supported. The connection has been terminated.","40000"}, {"58015","The DDM object 0x{0} is not supported. The connection has been terminated.","40000"}, {"58016","The DDM parameter 0x{0} is not supported. The connection has been terminated.","40000"}, {"58017","The DDM parameter value 0x{0} is not supported. An input host variable may not be within the range the server supports. The connection has been terminated.","40000"}, {"XBM01","Startup failed due to an exception. See next exception for details. ","45000"}, {"XBM02","Startup failed due to missing functionality for {0}. Please ensure your classpath includes the correct Derby software.","45000"}, {"XBM03","Supplied value '{0}' for collation attribute is invalid, expecting UCS_BASIC or TERRITORY_BASED.","45000"}, {"XBM04","Collator support not available from the JVM for the database's locale '{0}'.","45000"}, {"XBM05","Startup failed due to missing product version information for {0}.","45000"}, {"XBM06","Startup failed. An encrypted database cannot be accessed without the correct boot password. ","45000"}, {"XBM07","Startup failed. Boot password must be at least 8 bytes long.","45000"}, {"XBM08","Could not instantiate {0} StorageFactory class {1}.","45000"}, {"XBM0A","The database directory '{0}' exists. However, it does not contain the expected '{1}' file. Perhaps Derby was brought down in the middle of creating this database. You may want to delete this directory and try creating the database again.","45000"}, {"XBM0B","Failed to edit/write service properties file: {0}","45000"}, {"XBM0C","Missing privilege for operation '{0}' on file '{1}': {2}", "45000"}, {"XBM0G","Failed to start encryption engine. Please make sure you are running Java 2 and have downloaded an encryption provider such as jce and put it in your class path. ","45000"}, {"XBM0H","Directory {0} cannot be created.","45000"}, {"XBM0I","Directory {0} cannot be removed.","45000"}, {"XBM0J","Directory {0} already exists.","45000"}, {"XBM0K","Unknown sub-protocol for database name {0}.","45000"}, {"XBM0L","Specified authentication scheme class {0} does implement the authentication interface {1}.","45000"}, {"XBM0M","Error creating instance of authentication scheme class {0}.","45000"}, {"XBM0N","JDBC Driver registration with java.sql.DriverManager failed. See next exception for details. ","45000"}, {"XBM0P","Service provider is read-only. Operation not permitted. ","45000"}, {"XBM0Q","File {0} not found. Please make sure that backup copy is the correct one and it is not corrupted.","45000"}, {"XBM0R","Unable to remove File {0}. ","45000"}, {"XBM0S","Unable to rename file '{0}' to '{1}'","45000"}, {"XBM0T","Ambiguous sub-protocol for database name {0}. ","45000"}, {"XBM0X","Supplied territory description '{0}' is invalid, expecting ln[_CO[_variant]]\nln=lower-case two-letter ISO-639 language code, CO=upper-case two-letter ISO-3166 country codes, see java.util.Locale.","45000"}, {"XBM0Y","Backup database directory {0} not found. Please make sure that the specified backup path is right.","45000"}, {"XBM0Z","Unable to copy file '{0}' to '{1}'. Please make sure that there is enough space and permissions are correct. ","45000"}, {"XCW00","Unsupported upgrade from '{0}' to '{1}'.","45000"}, {"XJ004","Database '{0}' not found.","40000"}, {"XJ015","Derby system shutdown.","50000"}, {"XJ028","The URL '{0}' is not properly formed.","40000"}, {"XJ040","Failed to start database '{0}' with class loader {1}, see the next exception for details.","40000"}, {"XJ041","Failed to create database '{0}', see the next exception for details.","40000"}, {"XJ048","Conflicting boot attributes specified: {0}","40000"}, {"XJ049","Conflicting create attributes specified.","40000"}, {"XJ05B","JDBC attribute '{0}' has an invalid value '{1}', valid values are '{2}'.","40000"}, {"XJ081","Conflicting create/restore/recovery attributes specified.","40000"}, {"XJ213","The traceLevel connection property does not have a valid format for a number.","40000"}, {"XRE20","Failover performed successfully for database '{0}', the database has been shutdown.","45000"}, {"XSDB0","Unexpected exception on in-memory page {0}","45000"}, {"XSDB1","Unknown page format at page {0}","45000"}, {"XSDB2","Unknown container format at container {0} : {1}","45000"}, {"XSDB3","Container information cannot change once written: was {0}, now {1}","45000"}, {"XSDB4","Page {0} is at version {1}, the log file contains change version {2}, either there are log records of this page missing, or this page did not get written out to disk properly.","45000"}, {"XSDB5","Log has change record on page {0}, which is beyond the end of the container.","45000"}, {"XSDB6","Another instance of Derby may have already booted the database {0}.","45000"}, {"XSDB7","WARNING: Derby (instance {0}) is attempting to boot the database {1} even though Derby (instance {2}) may still be active. Only one instance of Derby should boot a database at a time. Severe and non-recoverable corruption can result and may have already occurred.","45000"}, {"XSDB8","WARNING: Derby (instance {0}) is attempting to boot the database {1} even though Derby (instance {2}) may still be active. Only one instance of Derby should boot a database at a time. Severe and non-recoverable corruption can result if 2 instances of Derby boot on the same database at the same time. The derby.database.forceDatabaseLock=true property has been set, so the database will not boot until the db.lck is no longer present. Normally this file is removed when the first instance of Derby to boot on the database exits, but it may be left behind in some shutdowns. It will be necessary to remove the file by hand in that case. It is important to verify that no other VM is accessing the database before deleting the db.lck file by hand.","45000"}, {"XSDB9","Stream container {0} is corrupt.","45000"}, {"XSDBA","Attempt to allocate object {0} failed.","45000"}, {"XSDBB", "Unknown page format at page {0}, page dump follows: {1} ", "45000"}, {"XSDBC", "Write of container information to page 0 of container {0} failed. See nested error for more information. ", "45000"}, {"XSDG0","Page {0} could not be read from disk.","45000"}, {"XSDG1","Page {0} could not be written to disk, please check if the disk is full, or if a file system limit, such as a quota or a maximum file size, has been reached.","45000"}, {"XSDG2","Invalid checksum on Page {0}, expected={1}, on-disk version={2}, page dump follows: {3}","45000"}, {"XSDG3","Meta-data for {0} could not be accessed to {1} {2}","45000"}, {"XSDG5","Database is not in create mode when createFinished is called.","45000"}, {"XSDG6","Data segment directory not found in {0} backup during restore. Please make sure that backup copy is the right one and it is not corrupted.","45000"}, {"XSDG7","Directory {0} could not be removed during restore. Please make sure that permissions are correct.","45000"}, {"XSDG8","Unable to copy directory '{0}' to '{1}' during restore. Please make sure that there is enough space and permissions are correct. ","45000"}, {"XSDG9","Derby thread received an interrupt during a disk I/O operation, please check your application for the source of the interrupt.","45000"}, {"XSLA0","Cannot flush the log file to disk {0}.","45000"}, {"XSLA1","Log Record has been sent to the stream, but it cannot be applied to the store (Object {0}). This may cause recovery problems also.","45000"}, {"XSLA2","System will shutdown, got I/O Exception while accessing log file.","45000"}, {"XSLA3","Log Corrupted, has invalid data in the log stream.","45000"}, {"XSLA4","Cannot write to the log, most likely the log is full. Please delete unnecessary files. It is also possible that the file system is read only, or the disk has failed, or some other problems with the media. ","45000"}, {"XSLA5","Cannot read log stream for some reason to rollback transaction {0}.","45000"}, {"XSLA6","Cannot recover the database.","45000"}, {"XSLA7","Cannot redo operation {0} in the log.","45000"}, {"XSLA8","Cannot rollback transaction {0}, trying to compensate {1} operation with {2}","45000"}, {"XSLAA","The store has been marked for shutdown by an earlier exception.","45000"}, {"XSLAB","Cannot find log file {0}, please make sure your logDevice property is properly set with the correct path separator for your platform.","45000"}, {"XSLAC","Database at {0} have incompatible format with the current version of software, it may have been created by or upgraded by a later version.","45000"}, {"XSLAD","log Record at instant {2} in log file {3} corrupted. Expected log record length {0}, real length {1}.","45000"}, {"XSLAE","Control file at {0} cannot be written or updated.","45000"}, {"XSLAF","A Read Only database was created with dirty data buffers.","45000"}, {"XSLAH","A Read Only database is being updated.","45000"}, {"XSLAI","Cannot log the checkpoint log record","45000"}, {"XSLAJ","The logging system has been marked to shut down due to an earlier problem and will not allow any more operations until the system shuts down and restarts.","45000"}, {"XSLAK","Database has exceeded largest log file number {0}.","45000"}, {"XSLAL","log record size {2} exceeded the maximum allowable log file size {3}. Error encountered in log file {0}, position {1}.","45000"}, {"XSLAM","Cannot verify database format at {1} due to IOException.","45000"}, {"XSLAN","Database at {0} has an incompatible format with the current version of the software. The database was created by or upgraded by version {1}.","45000"}, {"XSLAO","Recovery failed unexpected problem {0}.","45000"}, {"XSLAP","Database at {0} is at version {1}. Beta databases cannot be upgraded,","45000"}, {"XSLAQ","cannot create log file at directory {0}.","45000"}, {"XSLAR","Unable to copy log file '{0}' to '{1}' during restore. Please make sure that there is enough space and permissions are correct. ","45000"}, {"XSLAS","Log directory {0} not found in backup during restore. Please make sure that backup copy is the correct one and it is not corrupted.","45000"}, {"XSLAT","The log directory '{0}' exists. The directory might belong to another database. Check that the location specified for the logDevice attribute is correct.","45000"}, {"XSTB0","An exception was thrown during transaction abort.","50000"}, {"XSTB2","Cannot log transaction changes, maybe trying to write to a read only database.","50000"}, {"XSTB3","Cannot abort transaction because the log manager is null, probably due to an earlier error.","50000"}, {"XSTB5","Creating database with logging disabled encountered unexpected problem.","50000"}, {"XSTB6","Cannot substitute a transaction table with another while one is already in use.","50000"}, {"XXXXX","Normal database session close.","40000"}, {"XRE04","Could not establish a connection to the peer of the replicated database '{0}' on address '{1}:{2}'.","40000"}, {"XRE04","Connection lost for replicated database '{0}'.","40000"}, {"XRE05","The log files on the master and slave are not in synch for replicated database '{0}'. The master log instant is {1}:{2}, whereas the slave log instant is {3}:{4}. This is FATAL for replication - replication will be stopped.","40000"}, {"XRE09","Cannot start replication slave mode for database '{0}'. The database has already been booted.","40000"}, {"XRE11","Could not perform operation '{0}' because the database '{1}' has not been booted.","40000"}, {"XRE21","Error occurred while performing failover for database '{0}', Failover attempt was aborted.","40000"}, {"XRE22","Replication master has already been booted for database '{0}'","40000"}, {"XRE41","Replication operation 'failover' or 'stopSlave' refused on the slave database because the connection with the master is working. Issue the 'failover' or 'stopMaster' operation on the master database instead.","40000"}, {"XRE42","Replicated database '{0}' shutdown.","40000"}}; JDBC.assertUnorderedResultSet(rs, expectedRows); s.executeUpdate("drop table t"); commit(); s.close(); }
diff --git a/app/scm/GitVersionControlSystem.java b/app/scm/GitVersionControlSystem.java index 6c03093..e4744a9 100644 --- a/app/scm/GitVersionControlSystem.java +++ b/app/scm/GitVersionControlSystem.java @@ -1,55 +1,56 @@ /* * Copyright 2011 Matthias van der Vlies * * 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 scm; import java.io.File; import play.Play; import core.ProcessManager; /** * Implementation for a GIT Version Control System */ public class GitVersionControlSystem implements VersionControlSystem { public String getFullGitPath() { final String path = Play.configuration.getProperty("path.git"); // return setting from application.conf or assume command is on the instance's path return path == null || path.isEmpty() ? "git" : path; } @Override public String checkout(final String pid, final String gitUrl) throws Exception { final String checkoutPid = "git-clone-" + pid; return ProcessManager.executeCommand(checkoutPid, getFullGitPath() + " clone " + gitUrl + " apps/" + pid); } @Override public String update(final String pid) throws Exception { final String checkoutPid = "git-pull-" + pid; return ProcessManager.executeCommand(checkoutPid, getFullGitPath() + " pull origin master", new File("apps/" + pid)); } @Override public String cleanup(final String pid) throws Exception { - final String checkoutPid = "git-checkout-" + pid; + final String cleanupPid = "git-cleanup-" + pid; final StringBuffer output = new StringBuffer(); - output.append(ProcessManager.executeCommand(checkoutPid, getFullGitPath() + " --git-dir=apps/" + pid + "/.git --work-tree=apps/" + pid + " checkout -- conf/application.conf")); + output.append(ProcessManager.executeCommand(cleanupPid, getFullGitPath() + " --git-dir=apps/" + pid + "/.git --work-tree=apps/" + pid + " checkout -- conf/application.conf")); + output.append(ProcessManager.executeCommand(cleanupPid, getFullGitPath() + " gc", new File("apps/" + pid))); return output.toString(); } }
false
true
public String cleanup(final String pid) throws Exception { final String checkoutPid = "git-checkout-" + pid; final StringBuffer output = new StringBuffer(); output.append(ProcessManager.executeCommand(checkoutPid, getFullGitPath() + " --git-dir=apps/" + pid + "/.git --work-tree=apps/" + pid + " checkout -- conf/application.conf")); return output.toString(); }
public String cleanup(final String pid) throws Exception { final String cleanupPid = "git-cleanup-" + pid; final StringBuffer output = new StringBuffer(); output.append(ProcessManager.executeCommand(cleanupPid, getFullGitPath() + " --git-dir=apps/" + pid + "/.git --work-tree=apps/" + pid + " checkout -- conf/application.conf")); output.append(ProcessManager.executeCommand(cleanupPid, getFullGitPath() + " gc", new File("apps/" + pid))); return output.toString(); }
diff --git a/org.amanzi.awe.views.reuse/src/org/amanzi/awe/views/reuse/views/Column.java b/org.amanzi.awe.views.reuse/src/org/amanzi/awe/views/reuse/views/Column.java index 8d57692fa..8ee37240b 100644 --- a/org.amanzi.awe.views.reuse/src/org/amanzi/awe/views/reuse/views/Column.java +++ b/org.amanzi.awe.views.reuse/src/org/amanzi/awe/views/reuse/views/Column.java @@ -1,325 +1,325 @@ /* AWE - Amanzi Wireless Explorer * http://awe.amanzi.org * (C) 2008-2009, AmanziTel AB * * This library is provided under the terms of the Eclipse Public License * as described at http://www.eclipse.org/legal/epl-v10.html. Any use, * reproduction or distribution of the library constitutes recipient's * acceptance of this agreement. * * This library is distributed WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ package org.amanzi.awe.views.reuse.views; import java.math.BigDecimal; import java.math.RoundingMode; import org.amanzi.awe.views.reuse.Distribute; import org.amanzi.neo.core.INeoConstants; import org.amanzi.neo.core.enums.GeoNeoRelationshipTypes; import org.amanzi.neo.core.enums.NetworkRelationshipTypes; import org.amanzi.neo.core.enums.NodeTypes; import org.amanzi.neo.core.utils.NeoUtils; import org.neo4j.graphdb.Direction; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; /** * <p> * Information about column * </p>. * * @author Cinkel_A * @since 1.0.0 */ public class Column implements Comparable<Column> { /** The min value. */ private Double minValue; /** The range. */ private Double range; /** The node. */ private Node node; /** The distribute. */ private Distribute distribute; /** The property value. */ private Object propertyValue; /** * Constructor. * * @param curValue - minimum number which enters into a column * @param range - range of column */ public Column(double curValue, double range) { minValue = curValue; this.range = range; node = null; } /** * Merge. * * @param prevCol the prev col */ public void merge(Column prevCol,GraphDatabaseService service) { minValue = prevCol.minValue; range += prevCol.range; node.setProperty(INeoConstants.PROPERTY_NAME_MIN_VALUE, minValue); node.setProperty(INeoConstants.PROPERTY_NAME_MAX_VALUE, minValue + range); Node prevNode = prevCol.getNode(); for (Relationship relation : prevNode.getRelationships(NetworkRelationshipTypes.AGGREGATE, Direction.OUTGOING)) { node.createRelationshipTo(relation.getOtherNode(node), NetworkRelationshipTypes.AGGREGATE); } GeoNeoRelationshipTypes linkType = GeoNeoRelationshipTypes.CHILD; Relationship parentLink = prevNode.getSingleRelationship(linkType, Direction.INCOMING); if(parentLink==null){ linkType = GeoNeoRelationshipTypes.NEXT; parentLink = prevNode.getSingleRelationship(linkType, Direction.INCOMING); } Node parentMain = parentLink.getOtherNode(prevNode); NeoUtils.deleteSingleNode(prevNode,service); node.setProperty(INeoConstants.PROPERTY_NAME_NAME, getColumnName()); prevCol.setNode(null); parentMain.createRelationshipTo(node, linkType); setSpacer(true); } /** * Sets the node. * * @param node the new node */ private void setNode(Node node) { this.node = node; } /** * Sets the value. * * @param countNode the new value */ public void setValue(int countNode) { if (node != null) { node.setProperty(INeoConstants.PROPERTY_VALUE_NAME, countNode); } } /** * Gets the node. * * @return the node */ public Node getNode() { return node; } /** * Instantiates a new column. * * @param aggrNode the aggr node * @param lastNode the last column node * @param curValue the cur value * @param range the range * @param distribute the distribute * @param propertyValue the property value */ public Column(Node aggrNode, Node lastNode, double curValue, double range, Distribute distribute, Object propertyValue,GraphDatabaseService service) { this(curValue, range); this.distribute = distribute; this.propertyValue = propertyValue; node = service.createNode(); node.setProperty(INeoConstants.PROPERTY_TYPE_NAME, NodeTypes.COUNT.getId()); node.setProperty(INeoConstants.PROPERTY_NAME_NAME, getColumnName()); node.setProperty(INeoConstants.PROPERTY_NAME_MIN_VALUE, minValue); node.setProperty(INeoConstants.PROPERTY_NAME_MAX_VALUE, minValue + range); node.setProperty(INeoConstants.PROPERTY_VALUE_NAME, 0); node.setProperty(INeoConstants.PROPERTY_AGGR_PARENT_ID, aggrNode.getId()); NeoUtils.addChild(aggrNode, node, aggrNode.equals(lastNode)?null:lastNode, service); } /** * Gets the column name. * * @return the column name */ private String getColumnName() { String nameCol; BigDecimal minValue = new BigDecimal(this.minValue); BigDecimal maxValue = new BigDecimal(this.minValue + this.range); if (propertyValue instanceof String) { return propertyValue.toString(); } if (distribute == Distribute.INTEGERS) { nameCol = (minValue.add(new BigDecimal(0.5))).setScale(0, RoundingMode.HALF_UP).toString(); } else if (propertyValue instanceof Integer) { - minValue = minValue.setScale(0, RoundingMode.UP); - maxValue = maxValue.setScale(0, RoundingMode.DOWN); - if (maxValue.subtract(minValue).compareTo(BigDecimal.ONE) < 1) { + minValue = minValue.setScale(0, RoundingMode.CEILING); + maxValue = maxValue.setScale(0, RoundingMode.FLOOR); + if (maxValue.subtract(minValue).compareTo(BigDecimal.ONE) < 0) { nameCol = minValue.toString(); } else { nameCol = minValue.toString() + "-" + maxValue.toString(); } } else { // TODO calculate scale depending on key.getRange() minValue = minValue.setScale(3, RoundingMode.HALF_UP); maxValue = maxValue.setScale(3, RoundingMode.HALF_UP); if (range == 0) { nameCol = minValue.toString(); } else { nameCol = minValue.toString() + "-" + maxValue.toString(); } } return nameCol; } /** * Set this column to be a chart spacer (no data). * * @param value the new spacer */ public void setSpacer(boolean value) { node.setProperty("spacer", value); } /** * Returns true if value in [minValue,minValue+range);. * * @param value the value * @return true, if successful */ public boolean containsValue(double value) { return value >= minValue && (range == 0 || value < minValue + range); } /** * Compare to. * * @param o the o * @return the int */ @Override public int compareTo(Column o) { return minValue.compareTo(o.minValue); } /** * Hash code. * * @return the int */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((minValue == null) ? 0 : minValue.hashCode()); return result; } /** * Equals. * * @param obj the obj * @return true, if successful */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Column other = (Column)obj; if (minValue == null) { if (other.minValue != null) return false; } else if (!minValue.equals(other.minValue)) return false; return true; } /** * Gets the min value. * * @return the min value */ public Double getMinValue() { return minValue; } /** * Sets the min value. * * @param minValue the new min value */ public void setMinValue(Double minValue) { this.minValue = minValue; } /** * Gets the range. * * @return the range */ public Double getRange() { return range; } /** * Sets the range. * * @param range the new range */ public void setRange(Double range) { this.range = range; } /** * Gets the distribute. * * @return the distribute */ public Distribute getDistribute() { return distribute; } /** * Sets the distribute. * * @param distribute the new distribute */ public void setDistribute(Distribute distribute) { this.distribute = distribute; } /** * Gets the property value. * * @return the property value */ public Object getPropertyValue() { return propertyValue; } /** * Sets the property value. * * @param propertyValue the new property value */ public void setPropertyValue(Object propertyValue) { this.propertyValue = propertyValue; } }
true
true
private String getColumnName() { String nameCol; BigDecimal minValue = new BigDecimal(this.minValue); BigDecimal maxValue = new BigDecimal(this.minValue + this.range); if (propertyValue instanceof String) { return propertyValue.toString(); } if (distribute == Distribute.INTEGERS) { nameCol = (minValue.add(new BigDecimal(0.5))).setScale(0, RoundingMode.HALF_UP).toString(); } else if (propertyValue instanceof Integer) { minValue = minValue.setScale(0, RoundingMode.UP); maxValue = maxValue.setScale(0, RoundingMode.DOWN); if (maxValue.subtract(minValue).compareTo(BigDecimal.ONE) < 1) { nameCol = minValue.toString(); } else { nameCol = minValue.toString() + "-" + maxValue.toString(); } } else { // TODO calculate scale depending on key.getRange() minValue = minValue.setScale(3, RoundingMode.HALF_UP); maxValue = maxValue.setScale(3, RoundingMode.HALF_UP); if (range == 0) { nameCol = minValue.toString(); } else { nameCol = minValue.toString() + "-" + maxValue.toString(); } } return nameCol; }
private String getColumnName() { String nameCol; BigDecimal minValue = new BigDecimal(this.minValue); BigDecimal maxValue = new BigDecimal(this.minValue + this.range); if (propertyValue instanceof String) { return propertyValue.toString(); } if (distribute == Distribute.INTEGERS) { nameCol = (minValue.add(new BigDecimal(0.5))).setScale(0, RoundingMode.HALF_UP).toString(); } else if (propertyValue instanceof Integer) { minValue = minValue.setScale(0, RoundingMode.CEILING); maxValue = maxValue.setScale(0, RoundingMode.FLOOR); if (maxValue.subtract(minValue).compareTo(BigDecimal.ONE) < 0) { nameCol = minValue.toString(); } else { nameCol = minValue.toString() + "-" + maxValue.toString(); } } else { // TODO calculate scale depending on key.getRange() minValue = minValue.setScale(3, RoundingMode.HALF_UP); maxValue = maxValue.setScale(3, RoundingMode.HALF_UP); if (range == 0) { nameCol = minValue.toString(); } else { nameCol = minValue.toString() + "-" + maxValue.toString(); } } return nameCol; }
diff --git a/pages/src/org/riotfamily/pages/riot/security/SiteUserPolicy.java b/pages/src/org/riotfamily/pages/riot/security/SiteUserPolicy.java index e0cd908ee..b6c7a7d02 100644 --- a/pages/src/org/riotfamily/pages/riot/security/SiteUserPolicy.java +++ b/pages/src/org/riotfamily/pages/riot/security/SiteUserPolicy.java @@ -1,76 +1,76 @@ package org.riotfamily.pages.riot.security; import java.util.Set; import javax.servlet.http.HttpServletRequest; import org.riotfamily.pages.dao.PageDao; import org.riotfamily.pages.mapping.PageResolver; import org.riotfamily.pages.model.Page; import org.riotfamily.pages.model.Site; import org.riotfamily.riot.security.auth.RiotUser; import org.riotfamily.riot.security.policy.AuthorizationPolicy; public class SiteUserPolicy implements AuthorizationPolicy { private PageResolver pageResolver; private int order = Integer.MAX_VALUE - 2; public SiteUserPolicy(PageDao pageDao) { this.pageResolver = new PageResolver(pageDao); } public int getOrder() { return this.order; } public void setOrder(int order) { this.order = order; } public int checkPermission(RiotUser riotUser, String action, Object object) { if (riotUser instanceof SiteUser) { SiteUser user = (SiteUser) riotUser; if (isLimited(user)) { boolean denied = false; - if (object.getClass().isArray()) { + if (object != null && object.getClass().isArray()) { Object[] objects = (Object[]) object; for (Object o : objects) { denied |= isDenied(user, o); } } else { denied &= isDenied(user, object); } if (denied) { return ACCESS_DENIED; } } } return ACCESS_ABSTAIN; } private boolean isDenied(SiteUser user, Object object) { if (object instanceof Site) { Site site = (Site) object; return !user.getSites().contains(site); } if (object instanceof HttpServletRequest) { HttpServletRequest request = (HttpServletRequest) object; Page page = pageResolver.getPage(request); return page != null && !user.getSites().contains(page.getSite()); } return false; } protected boolean isLimited(SiteUser siteUser) { Set<Site> sites = siteUser.getSites(); if (sites != null && sites.size() > 0) { return true; } return false; } }
true
true
public int checkPermission(RiotUser riotUser, String action, Object object) { if (riotUser instanceof SiteUser) { SiteUser user = (SiteUser) riotUser; if (isLimited(user)) { boolean denied = false; if (object.getClass().isArray()) { Object[] objects = (Object[]) object; for (Object o : objects) { denied |= isDenied(user, o); } } else { denied &= isDenied(user, object); } if (denied) { return ACCESS_DENIED; } } } return ACCESS_ABSTAIN; }
public int checkPermission(RiotUser riotUser, String action, Object object) { if (riotUser instanceof SiteUser) { SiteUser user = (SiteUser) riotUser; if (isLimited(user)) { boolean denied = false; if (object != null && object.getClass().isArray()) { Object[] objects = (Object[]) object; for (Object o : objects) { denied |= isDenied(user, o); } } else { denied &= isDenied(user, object); } if (denied) { return ACCESS_DENIED; } } } return ACCESS_ABSTAIN; }
diff --git a/src/main/java/org/bloodtorrent/repository/SuccessStoryRepository.java b/src/main/java/org/bloodtorrent/repository/SuccessStoryRepository.java index e723955..dce7b7f 100644 --- a/src/main/java/org/bloodtorrent/repository/SuccessStoryRepository.java +++ b/src/main/java/org/bloodtorrent/repository/SuccessStoryRepository.java @@ -1,25 +1,25 @@ package org.bloodtorrent.repository; import com.yammer.dropwizard.hibernate.AbstractDAO; import org.bloodtorrent.dto.SuccessStory; import org.hibernate.Query; import org.hibernate.SQLQuery; import org.hibernate.SessionFactory; import java.util.List; public class SuccessStoryRepository extends AbstractDAO<SuccessStory> { public SuccessStoryRepository(SessionFactory sessionFactory) { super(sessionFactory); } /** * List up at most 3 success stories for showing on main page. * @return */ public List<SuccessStory> list() { - Query query = currentSession().createQuery("from SuccessStory s where s.showMainPage like 'Y' order by s.createDate"); + Query query = currentSession().createQuery("from SuccessStory s where s.showMainPage like 'Y' order by s.createDate desc"); return list(query); } }
true
true
public List<SuccessStory> list() { Query query = currentSession().createQuery("from SuccessStory s where s.showMainPage like 'Y' order by s.createDate"); return list(query); }
public List<SuccessStory> list() { Query query = currentSession().createQuery("from SuccessStory s where s.showMainPage like 'Y' order by s.createDate desc"); return list(query); }
diff --git a/ace/component/src/org/icefaces/ace/component/dataexporter/DataExporter.java b/ace/component/src/org/icefaces/ace/component/dataexporter/DataExporter.java index b83a13de9..c19ff59ce 100644 --- a/ace/component/src/org/icefaces/ace/component/dataexporter/DataExporter.java +++ b/ace/component/src/org/icefaces/ace/component/dataexporter/DataExporter.java @@ -1,93 +1,93 @@ /* * Copyright 2004-2012 ICEsoft Technologies Canada Corp. * * 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.icefaces.ace.component.dataexporter; import java.io.IOException; import javax.faces.FacesException; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.event.AbortProcessingException; import javax.faces.event.FacesEvent; import org.icefaces.ace.component.datatable.DataTable; public class DataExporter extends DataExporterBase { private transient String path = null; private transient String source = ""; public void broadcast(FacesEvent event) throws AbortProcessingException { super.broadcast(event); if (event != null) { try { FacesContext facesContext = getFacesContext(); Exporter exporter = ExporterFactory.getExporterForType(getType()); UIComponent targetComponent = event.getComponent().findComponent(getTarget()); if (targetComponent == null) targetComponent = findComponentCustom(facesContext.getViewRoot(), getTarget()); if (targetComponent == null) throw new FacesException("Cannot find component \"" + getTarget() + "\" in view."); if (!(targetComponent instanceof DataTable)) throw new FacesException("Unsupported datasource target:\"" + targetComponent.getClass().getName() + "\", exporter must target a ACE DataTable."); int[] excludedColumnIndexes = resolveExcludedColumnIndexes(getExcludeColumns()); DataTable table = (DataTable) targetComponent; - String path = exporter.export(facesContext, table, getFileName(), isPageOnly(), excludedColumnIndexes, getEncoding(), getPreProcessor(), getPostProcessor(), isIncludeHeaders(), isIncludeFooters(), isSelectedRowsOnly()); + String path = exporter.export(facesContext, table, getFileName(), table.isLazy() || isPageOnly(), excludedColumnIndexes, getEncoding(), getPreProcessor(), getPostProcessor(), isIncludeHeaders(), isIncludeFooters(), isSelectedRowsOnly()); this.path = path; } catch (IOException e) { throw new FacesException(e); } } } private int[] resolveExcludedColumnIndexes(String columnsToExclude) { if (columnsToExclude == null || columnsToExclude.equals("")) return null; String[] columnIndexesAsString = columnsToExclude.split(","); int[] indexes = new int[columnIndexesAsString.length]; for (int i=0; i < indexes.length; i++) indexes[i] = Integer.parseInt(columnIndexesAsString[i].trim()); return indexes; } private UIComponent findComponentCustom(UIComponent base, String id) { if (base.getId().equals(id)) return base; java.util.List<UIComponent> children = base.getChildren(); UIComponent result = null; for (UIComponent child : children) { result = findComponentCustom(child, id); if (result != null) break; } return result; } public String getPath(String clientId) { if (this.source.equals(clientId)) { return this.path; } else { return null; } } public void setSource(String clientId) { this.source = clientId; } protected FacesContext getFacesContext() { return FacesContext.getCurrentInstance(); } }
true
true
public void broadcast(FacesEvent event) throws AbortProcessingException { super.broadcast(event); if (event != null) { try { FacesContext facesContext = getFacesContext(); Exporter exporter = ExporterFactory.getExporterForType(getType()); UIComponent targetComponent = event.getComponent().findComponent(getTarget()); if (targetComponent == null) targetComponent = findComponentCustom(facesContext.getViewRoot(), getTarget()); if (targetComponent == null) throw new FacesException("Cannot find component \"" + getTarget() + "\" in view."); if (!(targetComponent instanceof DataTable)) throw new FacesException("Unsupported datasource target:\"" + targetComponent.getClass().getName() + "\", exporter must target a ACE DataTable."); int[] excludedColumnIndexes = resolveExcludedColumnIndexes(getExcludeColumns()); DataTable table = (DataTable) targetComponent; String path = exporter.export(facesContext, table, getFileName(), isPageOnly(), excludedColumnIndexes, getEncoding(), getPreProcessor(), getPostProcessor(), isIncludeHeaders(), isIncludeFooters(), isSelectedRowsOnly()); this.path = path; } catch (IOException e) { throw new FacesException(e); } } }
public void broadcast(FacesEvent event) throws AbortProcessingException { super.broadcast(event); if (event != null) { try { FacesContext facesContext = getFacesContext(); Exporter exporter = ExporterFactory.getExporterForType(getType()); UIComponent targetComponent = event.getComponent().findComponent(getTarget()); if (targetComponent == null) targetComponent = findComponentCustom(facesContext.getViewRoot(), getTarget()); if (targetComponent == null) throw new FacesException("Cannot find component \"" + getTarget() + "\" in view."); if (!(targetComponent instanceof DataTable)) throw new FacesException("Unsupported datasource target:\"" + targetComponent.getClass().getName() + "\", exporter must target a ACE DataTable."); int[] excludedColumnIndexes = resolveExcludedColumnIndexes(getExcludeColumns()); DataTable table = (DataTable) targetComponent; String path = exporter.export(facesContext, table, getFileName(), table.isLazy() || isPageOnly(), excludedColumnIndexes, getEncoding(), getPreProcessor(), getPostProcessor(), isIncludeHeaders(), isIncludeFooters(), isSelectedRowsOnly()); this.path = path; } catch (IOException e) { throw new FacesException(e); } } }
diff --git a/src/groovy/org/pillarone/riskanalytics/application/ui/parameterization/view/ErrorPane.java b/src/groovy/org/pillarone/riskanalytics/application/ui/parameterization/view/ErrorPane.java index 82a45a65..4f05c5c2 100644 --- a/src/groovy/org/pillarone/riskanalytics/application/ui/parameterization/view/ErrorPane.java +++ b/src/groovy/org/pillarone/riskanalytics/application/ui/parameterization/view/ErrorPane.java @@ -1,63 +1,62 @@ package org.pillarone.riskanalytics.application.ui.parameterization.view; import com.ulcjava.base.application.*; import com.ulcjava.base.application.border.ULCTitledBorder; import com.ulcjava.base.application.util.Color; import com.ulcjava.base.application.util.Font; import org.pillarone.riskanalytics.application.ui.parameterization.model.ParameterViewModel; import org.pillarone.riskanalytics.application.util.LocaleResources; import org.pillarone.riskanalytics.core.parameterization.validation.ParameterValidationError; import java.util.Collection; public class ErrorPane { private ULCBoxPane content; private ULCBoxPane container; private ParameterViewModel model; public ErrorPane(ParameterViewModel model) { this.model = model; content = new ULCBoxPane(); container = new ULCBoxPane(1, 0); container.setBackground(Color.white); content.add(ULCBoxPane.BOX_EXPAND_EXPAND, new ULCScrollPane(container)); } public void addError(ParameterValidationError error) { container.add(ULCBoxPane.BOX_EXPAND_TOP, createLabel(error)); } public void addErrors(Collection<ParameterValidationError> errors) { for (ParameterValidationError error : errors) { addError(error); } container.add(ULCBoxPane.BOX_EXPAND_EXPAND, ULCFiller.createVerticalGlue()); } public void clear() { container.removeAll(); } private ULCComponent createLabel(ParameterValidationError error) { ULCBoxPane pane = new ULCBoxPane(1, 1); pane.setBackground(Color.white); - final String errorPath = model.findNodeForPath(error.getPath()).getDisplayPath(); - final ULCTitledBorder border = BorderFactory.createTitledBorder(errorPath); + final ULCTitledBorder border = BorderFactory.createTitledBorder(model.findNodeForPath(error.getPath()).getDisplayPath()); border.setTitleFont(border.getTitleFont().deriveFont(Font.PLAIN)); pane.setBorder(border); ULCLabel label = new ULCLabel(); label.setForeground(Color.red); label.setText(error.getLocalizedMessage(LocaleResources.getLocale())); label.setFont(label.getFont().deriveFont(Font.PLAIN)); pane.add(ULCBoxPane.BOX_EXPAND_TOP, label); return pane; } public ULCBoxPane getContent() { return content; } }
true
true
private ULCComponent createLabel(ParameterValidationError error) { ULCBoxPane pane = new ULCBoxPane(1, 1); pane.setBackground(Color.white); final String errorPath = model.findNodeForPath(error.getPath()).getDisplayPath(); final ULCTitledBorder border = BorderFactory.createTitledBorder(errorPath); border.setTitleFont(border.getTitleFont().deriveFont(Font.PLAIN)); pane.setBorder(border); ULCLabel label = new ULCLabel(); label.setForeground(Color.red); label.setText(error.getLocalizedMessage(LocaleResources.getLocale())); label.setFont(label.getFont().deriveFont(Font.PLAIN)); pane.add(ULCBoxPane.BOX_EXPAND_TOP, label); return pane; }
private ULCComponent createLabel(ParameterValidationError error) { ULCBoxPane pane = new ULCBoxPane(1, 1); pane.setBackground(Color.white); final ULCTitledBorder border = BorderFactory.createTitledBorder(model.findNodeForPath(error.getPath()).getDisplayPath()); border.setTitleFont(border.getTitleFont().deriveFont(Font.PLAIN)); pane.setBorder(border); ULCLabel label = new ULCLabel(); label.setForeground(Color.red); label.setText(error.getLocalizedMessage(LocaleResources.getLocale())); label.setFont(label.getFont().deriveFont(Font.PLAIN)); pane.add(ULCBoxPane.BOX_EXPAND_TOP, label); return pane; }
diff --git a/bundles/org.eclipse.equinox.frameworkadmin.equinox/src/org/eclipse/equinox/frameworkadmin/equinox/internal/utils/FileUtils.java b/bundles/org.eclipse.equinox.frameworkadmin.equinox/src/org/eclipse/equinox/frameworkadmin/equinox/internal/utils/FileUtils.java index 8a1891a3d..3395e919a 100644 --- a/bundles/org.eclipse.equinox.frameworkadmin.equinox/src/org/eclipse/equinox/frameworkadmin/equinox/internal/utils/FileUtils.java +++ b/bundles/org.eclipse.equinox.frameworkadmin.equinox/src/org/eclipse/equinox/frameworkadmin/equinox/internal/utils/FileUtils.java @@ -1,234 +1,236 @@ /******************************************************************************* * Copyright (c) 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.equinox.frameworkadmin.equinox.internal.utils; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.util.StringTokenizer; import org.eclipse.equinox.frameworkadmin.LauncherData; import org.eclipse.equinox.frameworkadmin.Manipulator; import org.eclipse.equinox.frameworkadmin.equinox.internal.EquinoxConstants; import org.eclipse.equinox.internal.frameworkadmin.utils.Utils; public class FileUtils { public static String getEclipseRealLocation(final Manipulator manipulator, final String location) { try { new URL(location); return location; } catch (MalformedURLException e) { // just ignore. } if (location.indexOf(":") >= 0) return location; LauncherData launcherData = manipulator.getLauncherData(); File home = launcherData.getHome(); File pluginsDir = null; if (home != null) pluginsDir = new File(home, EquinoxConstants.PLUGINS_DIR); else if (launcherData.getLauncher() != null) pluginsDir = new File(launcherData.getLauncher().getParentFile(), EquinoxConstants.PLUGINS_DIR); else if (launcherData.getFwJar() != null) pluginsDir = launcherData.getFwJar().getParentFile(); String pluginName = getPluginName(location); String ret = getEclipsePluginFullLocation(pluginName, pluginsDir); return ret; } private static String getPluginName(final String location) { int position = location.indexOf("_"); String pluginName = location; if (position >= 0) pluginName = location.substring(0, position); return pluginName; } public static String getRealLocation(Manipulator manipulator, final String location, boolean useEclipse) { if (location == null) return null; String ret = location; if (location.startsWith("reference:")) { ret = location.substring("reference:".length()); if (ret.endsWith(".jar/")) { ret = ret.substring(0, ret.length() - "/".length()); if (ret.startsWith("file:")) ret = ret.substring("file:".length()); } } if (location.startsWith("initial@")) ret = location.substring("initial@".length()); if (ret == location) if (useEclipse) return FileUtils.getEclipseRealLocation(manipulator, location); else return location; return getRealLocation(manipulator, ret, useEclipse); } public static boolean copy(File source, File target) throws IOException { //try { target.getParentFile().mkdirs(); target.createNewFile(); transferStreams(new FileInputStream(source), new FileOutputStream(target)); // } catch (FileNotFoundException e) { // e.printStackTrace(); // return false; // } catch (IOException e) { // e.printStackTrace(); // return false; // } return true; } /** * Transfers all available bytes from the given input stream to the given * output stream. Regardless of failure, this method closes both streams. * * @param source * @param destination * @throws IOException */ public static void transferStreams(InputStream source, OutputStream destination) throws IOException { source = new BufferedInputStream(source); destination = new BufferedOutputStream(destination); try { byte[] buffer = new byte[8192]; while (true) { int bytesRead = -1; if ((bytesRead = source.read(buffer)) == -1) break; destination.write(buffer, 0, bytesRead); } } finally { try { source.close(); } catch (IOException e) { e.printStackTrace(); // ignore } try { destination.close(); } catch (IOException e) { e.printStackTrace();// ignore } } } /** * If a bundle of the specified location is in the Eclipse plugin format (plugin-name_version.jar), * return version string.Otherwise, return null; * * @param url * @param pluginName * @return version string. If invalid format, return null. */ private static String getEclipseJarNamingVersion(URL url, final String pluginName) { - String location = Utils.replaceAll(url.getFile(), File.separator, "/"); + String location = url.getFile(); + if (!File.separator.equals("/")) + location = Utils.replaceAll(location, File.separator, "/"); String filename = null; if (location.indexOf(":") == -1) filename = location; else filename = location.substring(location.lastIndexOf(":") + 1); if (location.indexOf("/") == -1) filename = location; else filename = location.substring(location.lastIndexOf("/") + 1); // filename must be "jarName"_"version".jar //System.out.println("filename=" + filename); if (!filename.endsWith(".jar")) return null; filename = filename.substring(0, filename.lastIndexOf(".jar")); //System.out.println("filename=" + filename); if (filename.lastIndexOf("_") == -1) return null; String version = filename.substring(filename.lastIndexOf("_") + 1); filename = filename.substring(0, filename.lastIndexOf("_")); //System.out.println("filename=" + filename); if (filename.indexOf("_") != -1) return null; if (!filename.equals(pluginName)) return null; return version; } public static String getEclipsePluginFullLocation(String pluginName, File bundlesDir) { File[] lists = bundlesDir.listFiles(); URL ret = null; EclipseVersion maxVersion = null; if (lists == null) return null; for (int i = 0; i < lists.length; i++) { try { URL url = lists[i].toURL(); String version = getEclipseJarNamingVersion(url, pluginName); if (version != null) { EclipseVersion eclipseVersion = new EclipseVersion(version); if (maxVersion == null || eclipseVersion.compareTo(maxVersion) > 0) { ret = url; maxVersion = eclipseVersion; } } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } return (ret == null ? null : ret.toExternalForm()); } } class EclipseVersion implements Comparable { int major = 0; int minor = 0; int service = 0; String qualifier = null; EclipseVersion(String version) { StringTokenizer tok = new StringTokenizer(version, "."); if (!tok.hasMoreTokens()) return; this.major = Integer.parseInt(tok.nextToken()); if (!tok.hasMoreTokens()) return; this.minor = Integer.parseInt(tok.nextToken()); if (!tok.hasMoreTokens()) return; this.service = Integer.parseInt(tok.nextToken()); if (!tok.hasMoreTokens()) return; this.qualifier = tok.nextToken(); } public int compareTo(Object obj) { EclipseVersion target = (EclipseVersion) obj; if (target.major > this.major) return -1; if (target.major < this.major) return 1; if (target.minor > this.minor) return -1; if (target.minor < this.minor) return 1; if (target.service > this.service) return -1; if (target.service < this.service) return 1; return 0; } }
true
true
private static String getEclipseJarNamingVersion(URL url, final String pluginName) { String location = Utils.replaceAll(url.getFile(), File.separator, "/"); String filename = null; if (location.indexOf(":") == -1) filename = location; else filename = location.substring(location.lastIndexOf(":") + 1); if (location.indexOf("/") == -1) filename = location; else filename = location.substring(location.lastIndexOf("/") + 1); // filename must be "jarName"_"version".jar //System.out.println("filename=" + filename); if (!filename.endsWith(".jar")) return null; filename = filename.substring(0, filename.lastIndexOf(".jar")); //System.out.println("filename=" + filename); if (filename.lastIndexOf("_") == -1) return null; String version = filename.substring(filename.lastIndexOf("_") + 1); filename = filename.substring(0, filename.lastIndexOf("_")); //System.out.println("filename=" + filename); if (filename.indexOf("_") != -1) return null; if (!filename.equals(pluginName)) return null; return version; }
private static String getEclipseJarNamingVersion(URL url, final String pluginName) { String location = url.getFile(); if (!File.separator.equals("/")) location = Utils.replaceAll(location, File.separator, "/"); String filename = null; if (location.indexOf(":") == -1) filename = location; else filename = location.substring(location.lastIndexOf(":") + 1); if (location.indexOf("/") == -1) filename = location; else filename = location.substring(location.lastIndexOf("/") + 1); // filename must be "jarName"_"version".jar //System.out.println("filename=" + filename); if (!filename.endsWith(".jar")) return null; filename = filename.substring(0, filename.lastIndexOf(".jar")); //System.out.println("filename=" + filename); if (filename.lastIndexOf("_") == -1) return null; String version = filename.substring(filename.lastIndexOf("_") + 1); filename = filename.substring(0, filename.lastIndexOf("_")); //System.out.println("filename=" + filename); if (filename.indexOf("_") != -1) return null; if (!filename.equals(pluginName)) return null; return version; }
diff --git a/core/src/test/java/brooklyn/event/feed/shell/ShellFeedIntegrationTest.java b/core/src/test/java/brooklyn/event/feed/shell/ShellFeedIntegrationTest.java index 1326d5ae1..1bd484792 100644 --- a/core/src/test/java/brooklyn/event/feed/shell/ShellFeedIntegrationTest.java +++ b/core/src/test/java/brooklyn/event/feed/shell/ShellFeedIntegrationTest.java @@ -1,176 +1,176 @@ package brooklyn.event.feed.shell; import static org.testng.Assert.assertTrue; import java.util.Arrays; import java.util.concurrent.TimeUnit; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import brooklyn.entity.basic.Entities; import brooklyn.entity.basic.EntityLocal; import brooklyn.event.basic.BasicAttributeSensor; import brooklyn.event.feed.function.FunctionFeedTest; import brooklyn.event.feed.ssh.SshPollValue; import brooklyn.event.feed.ssh.SshValueFunctions; import brooklyn.location.basic.LocalhostMachineProvisioningLocation; import brooklyn.test.EntityTestUtils; import brooklyn.test.TestUtils; import brooklyn.test.entity.TestApplication; import brooklyn.test.entity.TestEntity; import brooklyn.util.MutableMap; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.io.Closeables; public class ShellFeedIntegrationTest { final static BasicAttributeSensor<String> SENSOR_STRING = new BasicAttributeSensor<String>(String.class, "aString", ""); final static BasicAttributeSensor<Integer> SENSOR_INT = new BasicAttributeSensor<Integer>(Integer.class, "anInt", ""); final static BasicAttributeSensor<Long> SENSOR_LONG = new BasicAttributeSensor<Long>(Long.class, "aLong", ""); private LocalhostMachineProvisioningLocation loc; private TestApplication app; private EntityLocal entity; private ShellFeed feed; @BeforeMethod(alwaysRun=true) public void setUp() throws Exception { loc = new LocalhostMachineProvisioningLocation(); app = new TestApplication(); entity = new TestEntity(app); Entities.startManagement(app); app.start(ImmutableList.of(loc)); } @AfterMethod(alwaysRun=true) public void tearDown() throws Exception { if (feed != null) feed.stop(); if (app != null) Entities.destroy(app); if (loc != null) Closeables.closeQuietly(loc); } @Test(groups="Integration") public void testReturnsShellExitStatus() throws Exception { feed = ShellFeed.builder() .entity(entity) .poll(new ShellPollConfig<Integer>(SENSOR_INT) .command("exit 123") .onSuccess(SshValueFunctions.exitStatus())) .build(); EntityTestUtils.assertAttributeEqualsEventually(entity, SENSOR_INT, 123); } @Test(groups="Integration") public void testShellTimesOut() throws Exception { feed = ShellFeed.builder() .entity(entity) .poll(new ShellPollConfig<String>(SENSOR_STRING) .command("sleep 10") .timeout(1, TimeUnit.MILLISECONDS) .onError(new FunctionFeedTest.ToStringFunction())) .build(); TestUtils.executeUntilSucceeds(MutableMap.of(), new Runnable() { public void run() { String val = entity.getAttribute(SENSOR_STRING); assertTrue(val != null && val.contains("timed out after 1ms"), "val="+val); }}); } @Test(groups="Integration") public void testShellUsesEnv() throws Exception { feed = ShellFeed.builder() .entity(entity) .poll(new ShellPollConfig<String>(SENSOR_STRING) .env(ImmutableMap.of("MYENV", "MYVAL")) .command("echo hello $MYENV") .onSuccess(SshValueFunctions.stdout())) .build(); TestUtils.executeUntilSucceeds(MutableMap.of(), new Runnable() { public void run() { String val = entity.getAttribute(SENSOR_STRING); assertTrue(val != null && val.contains("hello MYVAL"), "val="+val); }}); } @Test(groups="Integration") public void testReturnsShellStdout() throws Exception { feed = ShellFeed.builder() .entity(entity) .poll(new ShellPollConfig<String>(SENSOR_STRING) .command("echo hello") .onSuccess(SshValueFunctions.stdout())) .build(); TestUtils.executeUntilSucceeds(MutableMap.of(), new Runnable() { public void run() { String val = entity.getAttribute(SENSOR_STRING); assertTrue(val != null && val.contains("hello"), "val="+val); }}); } @Test(groups="Integration") public void testReturnsShellStderr() throws Exception { final String cmd = "thiscommanddoesnotexist"; feed = ShellFeed.builder() .entity(entity) .poll(new ShellPollConfig<String>(SENSOR_STRING) .command(cmd) .onSuccess(SshValueFunctions.stderr())) .build(); TestUtils.executeUntilSucceeds(MutableMap.of(), new Runnable() { public void run() { String val = entity.getAttribute(SENSOR_STRING); assertTrue(val != null && val.contains(cmd), "val="+val); }}); } @Test(groups="Integration") public void testFailsOnNonZeroWhenConfigured() throws Exception { feed = ShellFeed.builder() .entity(entity) .poll(new ShellPollConfig<String>(SENSOR_STRING) .command("exit 123") .failOnNonZeroResultCode(true) .onError(new FunctionFeedTest.ToStringFunction())) .build(); TestUtils.executeUntilSucceeds(MutableMap.of(), new Runnable() { public void run() { String val = entity.getAttribute(SENSOR_STRING); assertTrue(val != null && val.contains("Exit status 123"), "val="+val); }}); } // Example in ShellFeed javadoc @Test(groups="Integration") public void testDiskUsage() throws Exception { feed = ShellFeed.builder() .entity(entity) .poll(new ShellPollConfig<Long>(SENSOR_LONG) .command("df -P | tail -1") .failOnNonZeroResultCode(true) .onSuccess(new Function<SshPollValue, Long>() { public Long apply(SshPollValue input) { String[] parts = input.getStdout().split("[ \\t]+"); System.out.println("input="+input+"; parts="+Arrays.toString(parts)); return Long.parseLong(parts[2]); }})) .build(); TestUtils.executeUntilSucceeds(MutableMap.of(), new Runnable() { public void run() { Long val = entity.getAttribute(SENSOR_LONG); - assertTrue(val != null && val > 0); + assertTrue(val != null && val >= 0, "val="+val); }}); } }
true
true
public void testDiskUsage() throws Exception { feed = ShellFeed.builder() .entity(entity) .poll(new ShellPollConfig<Long>(SENSOR_LONG) .command("df -P | tail -1") .failOnNonZeroResultCode(true) .onSuccess(new Function<SshPollValue, Long>() { public Long apply(SshPollValue input) { String[] parts = input.getStdout().split("[ \\t]+"); System.out.println("input="+input+"; parts="+Arrays.toString(parts)); return Long.parseLong(parts[2]); }})) .build(); TestUtils.executeUntilSucceeds(MutableMap.of(), new Runnable() { public void run() { Long val = entity.getAttribute(SENSOR_LONG); assertTrue(val != null && val > 0); }}); }
public void testDiskUsage() throws Exception { feed = ShellFeed.builder() .entity(entity) .poll(new ShellPollConfig<Long>(SENSOR_LONG) .command("df -P | tail -1") .failOnNonZeroResultCode(true) .onSuccess(new Function<SshPollValue, Long>() { public Long apply(SshPollValue input) { String[] parts = input.getStdout().split("[ \\t]+"); System.out.println("input="+input+"; parts="+Arrays.toString(parts)); return Long.parseLong(parts[2]); }})) .build(); TestUtils.executeUntilSucceeds(MutableMap.of(), new Runnable() { public void run() { Long val = entity.getAttribute(SENSOR_LONG); assertTrue(val != null && val >= 0, "val="+val); }}); }
diff --git a/java/src/org/broadinstitute/sting/gatk/datasources/simpleDataSources/ResourcePool.java b/java/src/org/broadinstitute/sting/gatk/datasources/simpleDataSources/ResourcePool.java index 90564444a..19f1c96b5 100755 --- a/java/src/org/broadinstitute/sting/gatk/datasources/simpleDataSources/ResourcePool.java +++ b/java/src/org/broadinstitute/sting/gatk/datasources/simpleDataSources/ResourcePool.java @@ -1,212 +1,212 @@ package org.broadinstitute.sting.gatk.datasources.simpleDataSources; import org.broadinstitute.sting.utils.GenomeLoc; import org.broadinstitute.sting.utils.StingException; import org.broadinstitute.sting.utils.GenomeLocParser; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.util.HashMap; import java.util.Map; /** * User: hanna * Date: May 21, 2009 * Time: 10:55:26 AM * BROAD INSTITUTE SOFTWARE COPYRIGHT NOTICE AND AGREEMENT * Software and documentation are copyright 2005 by the Broad Institute. * All rights are reserved. * * Users acknowledge that this software is supplied without any warranty or support. * The Broad Institute is not responsible for its use, misuse, or * functionality. */ /** * A pool of open resources, all of which can create a closeable iterator. */ abstract class ResourcePool <T,I extends Iterator> { /** * All iterators of this reference-ordered data. */ private List<T> allResources = new ArrayList<T>(); /** * All iterators that are not currently in service. */ private List<T> availableResources = new ArrayList<T>(); /** * Which iterators are assigned to which pools. */ private Map<I,T> resourceAssignments = new HashMap<I,T>(); /** * Get an iterator whose position is before the specified location. Create a new one if none exists. * @param segment Target position for the iterator. * @return An iterator that can traverse the selected region. Should be able to iterate concurrently with other * iterators from tihs pool. */ public I iterator( DataStreamSegment segment ) { // Grab the first iterator in the list whose position is before the requested position. T selectedResource = null; synchronized (this) { selectedResource = selectBestExistingResource(segment, availableResources); // No iterator found? Create another. It is expected that // each iterator created will have its own file handle. if (selectedResource == null) { selectedResource = createNewResource(); addNewResource(selectedResource); } // Remove the iterator from the list of available iterators. availableResources.remove(selectedResource); + } - I iterator = createIteratorFromResource(segment, selectedResource); + I iterator = createIteratorFromResource(segment, selectedResource); - // Make a note of this assignment for proper releasing later. - resourceAssignments.put(iterator, selectedResource); + // Make a note of this assignment for proper releasing later. + resourceAssignments.put(iterator, selectedResource); - return iterator; - } + return iterator; } /** * Release the lock on the given iterator, returning it to the pool. * @param iterator Iterator to return to the pool. */ public void release( I iterator ) { synchronized(this) { // Find and remove the resource from the list of allocated resources. T resource = resourceAssignments.get( iterator ); Object obj = resourceAssignments.remove(iterator); // make sure we actually removed the assignment if (obj == null) throw new StingException("Failed to remove resource assignment; target key had no associated value in the resource assignment map"); // Return the resource to the pool. if( !allResources.contains(resource) ) throw new StingException("Iterator does not belong to the given pool."); availableResources.add(resource); } } /** * Add a resource to the list of available resources. Useful if derived classes * want to seed the pool with a set of at a given time (like at initialization). * @param resource The new resource to add. */ protected void addNewResource( T resource ) { synchronized(this) { allResources.add(resource); availableResources.add(resource); } } /** * If no appropriate resources are found in the pool, the system can create a new resource. * Delegate the creation of the resource to the subclass. * @return The new resource created. */ protected abstract T createNewResource(); /** * Find the most appropriate resource to acquire the specified data. * @param segment The data over which the resource is required. * @param availableResources A list of candidate resources to evaluate. * @return The best choice of the availableResources, or null if no resource meets the criteria. */ protected abstract T selectBestExistingResource( DataStreamSegment segment, List<T> availableResources ); /** * Create an iterator over the specified resource. * @param position The bounds of iteration. The first element of the iterator through the last element should all * be in the range described by position. * @param resource The resource from which to derive the iterator. * @return A new iterator over the given data. */ protected abstract I createIteratorFromResource( DataStreamSegment position, T resource ); /** * Retire this resource from service. * @param resource The resource to retire. */ protected abstract void closeResource(T resource); /** * Operating stats...get the number of total iterators. Package-protected * for unit testing. * @return An integer number of total iterators. */ int numIterators() { return allResources.size(); } /** * Operating stats...get the number of available iterators. Package-protected * for unit testing. * @return An integer number of available iterators. */ int numAvailableIterators() { return availableResources.size(); } } /** * Marker interface that represents an arbitrary consecutive segment within a data stream. */ interface DataStreamSegment { } /** * Models the entire stream of data. */ class EntireStream implements DataStreamSegment { } /** * Models a mapped position within a stream of GATK input data. */ class MappedStreamSegment implements DataStreamSegment { public final GenomeLoc locus; /** * Retrieves the first location covered by a mapped stream segment. * @return Location of the first base in this segment. */ public GenomeLoc getFirstLocation() { return GenomeLocParser.createGenomeLoc(locus.getContigIndex(),locus.getStart()); } public MappedStreamSegment(GenomeLoc locus) { this.locus = locus; } } /** * Models a position within the unmapped reads in a stream of GATK input data. */ class UnmappedStreamSegment implements DataStreamSegment { /** * Where does this region start, given 0 = the position of the first unmapped read. */ public final long position; /** * How many reads wide is this region? This size is generally treated as an upper bound. */ public final long size; /** * Create a new target location in an unmapped read stream. * @param position The 0-based index into the unmapped reads. Position 0 represents the first unmapped read. * @param size the size of the segment. */ public UnmappedStreamSegment( long position, long size ) { this.position = position; this.size = size; } }
false
true
public I iterator( DataStreamSegment segment ) { // Grab the first iterator in the list whose position is before the requested position. T selectedResource = null; synchronized (this) { selectedResource = selectBestExistingResource(segment, availableResources); // No iterator found? Create another. It is expected that // each iterator created will have its own file handle. if (selectedResource == null) { selectedResource = createNewResource(); addNewResource(selectedResource); } // Remove the iterator from the list of available iterators. availableResources.remove(selectedResource); I iterator = createIteratorFromResource(segment, selectedResource); // Make a note of this assignment for proper releasing later. resourceAssignments.put(iterator, selectedResource); return iterator; } }
public I iterator( DataStreamSegment segment ) { // Grab the first iterator in the list whose position is before the requested position. T selectedResource = null; synchronized (this) { selectedResource = selectBestExistingResource(segment, availableResources); // No iterator found? Create another. It is expected that // each iterator created will have its own file handle. if (selectedResource == null) { selectedResource = createNewResource(); addNewResource(selectedResource); } // Remove the iterator from the list of available iterators. availableResources.remove(selectedResource); } I iterator = createIteratorFromResource(segment, selectedResource); // Make a note of this assignment for proper releasing later. resourceAssignments.put(iterator, selectedResource); return iterator; }
diff --git a/src/org/griphyn/cPlanner/transfer/implementation/Windward.java b/src/org/griphyn/cPlanner/transfer/implementation/Windward.java index d4d1a4816..7132d65f4 100644 --- a/src/org/griphyn/cPlanner/transfer/implementation/Windward.java +++ b/src/org/griphyn/cPlanner/transfer/implementation/Windward.java @@ -1,528 +1,528 @@ /** * Copyright 2007-2008 University Of Southern California * * 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.griphyn.cPlanner.transfer.implementation; import edu.isi.pegasus.common.logging.LoggingKeys; import edu.isi.pegasus.planner.catalog.site.classes.GridGateway; import edu.isi.pegasus.planner.catalog.site.classes.SiteCatalogEntry; import org.griphyn.cPlanner.classes.ADag; import org.griphyn.cPlanner.classes.SubInfo; import org.griphyn.cPlanner.classes.TransferJob; import org.griphyn.cPlanner.classes.FileTransfer; import org.griphyn.cPlanner.classes.PegasusBag; import org.griphyn.cPlanner.common.LogManager; import org.griphyn.cPlanner.transfer.MultipleFTPerXFERJob; import org.griphyn.common.catalog.TransformationCatalogEntry; import org.griphyn.common.classes.TCType; import org.griphyn.common.util.Separator; import org.griphyn.cPlanner.cluster.aggregator.JobAggregatorFactory; import org.griphyn.cPlanner.cluster.JobAggregator; import java.io.File; import java.util.Collection; import java.util.List; import java.util.LinkedList; import java.util.Iterator; import org.griphyn.cPlanner.transfer.Refiner; import org.griphyn.cPlanner.classes.Profile; import java.util.ArrayList; /** * A Windward implementation that uses the seqexec client to execute * * -DC Transfer client to fetch the raw data sources * -Pegasus transfer client to fetch the patterns from the pattern catalog. * * @author Karan Vahi * @version $Revision$ */ public class Windward extends Abstract implements MultipleFTPerXFERJob { /** * The prefix to identify the raw data sources. */ public static final String DATA_SOURCE_PREFIX = "DS"; /** * A short description of the transfer implementation. */ public static final String DESCRIPTION = "Seqexec Transfer Wrapper around Pegasus Transfer and DC Transfer Client"; /** * The transformation namespace for for the transfer job. */ public static final String TRANSFORMATION_NAMESPACE = "windward"; /** * The name of the underlying transformation that is queried for in the * Transformation Catalog. */ public static final String TRANSFORMATION_NAME = "dc-transfer"; /** * The version number for the transfer job. */ public static final String TRANSFORMATION_VERSION = null; /** * The derivation namespace for for the transfer job. */ public static final String DERIVATION_NAMESPACE = "windward"; /** * The name of the underlying derivation. */ public static final String DERIVATION_NAME = "dc-transfer"; /** * The derivation version number for the transfer job. */ public static final String DERIVATION_VERSION = null; /** * The handle to the transfer implementation. */ private Transfer mPegasusTransfer; /** * The handle to the BAE transfer implementation. */ private BAE mBAETransfer; /** * The seqexec job aggregator. */ private JobAggregator mSeqExecAggregator; /** * The refiner beig used. */ private Refiner mRefiner; /** * The overloaded constructor, that is called by the Factory to load the * class. * * @param bag the bag of initialization objects. */ public Windward( PegasusBag bag ) { super( bag ); //should probably go through the factory mPegasusTransfer = new Transfer( bag ); mBAETransfer = new BAE( bag ); //just to pass the label have to send an empty ADag. //should be fixed ADag dag = new ADag(); dag.dagInfo.setLabel( "windward" ); mSeqExecAggregator = JobAggregatorFactory.loadInstance( JobAggregatorFactory.SEQ_EXEC_CLASS, dag, bag ); } /** * Sets the callback to the refiner, that has loaded this implementation. * * @param refiner the transfer refiner that loaded the implementation. */ public void setRefiner(Refiner refiner){ super.setRefiner( refiner ); //also set the refiner for hte internal pegasus transfer mPegasusTransfer.setRefiner( refiner ); mBAETransfer.setRefiner(refiner); mRefiner = refiner; } /** * * * @param job the SubInfo object for the job, in relation to which * the transfer node is being added. Either the transfer * node can be transferring this jobs input files to * the execution pool, or transferring this job's output * files to the output pool. * @param files collection of <code>FileTransfer</code> objects * representing the data files and staged executables to be * transferred. * @param execFiles subset collection of the files parameter, that identifies * the executable files that are being transferred. * @param txJobName the name of transfer node. * @param jobClass the job Class for the newly added job. Can be one of the * following: * stage-in * stage-out * inter-pool transfer * * @return the created TransferJob. */ public TransferJob createTransferJob( SubInfo job, Collection files, Collection execFiles, String txJobName, int jobClass) { //iterate through all the files and identify the patterns //and the other data sources Collection rawDataSources = new LinkedList(); Collection patterns = new LinkedList(); for( Iterator it = files.iterator(); it.hasNext(); ){ FileTransfer ft = ( FileTransfer )it.next(); //no way to distinguish a pattern right now /* if( ft.getLFN().startsWith( DATA_SOURCE_PREFIX ) && !ft.getSourceURL().getValue().endsWith( ".zip" )){ //it a raw data source that will have to be ingested rawDataSources.add( ft ); } else{ //everything else is a pattern patterns.add( ft ); }*/ rawDataSources.add( ft ); } List txJobs = new LinkedList(); //use the Pegasus Transfer to handle the patterns TransferJob patternTXJob = null; String patternTXJobStdin = null; List<String> txJobIDs = new LinkedList<String>(); if( !patterns.isEmpty() ){ patternTXJob = mPegasusTransfer.createTransferJob( job, patterns, null, txJobName, jobClass ); //get the stdin and set it as lof in the arguments patternTXJobStdin = patternTXJob.getStdIn(); StringBuffer patternArgs = new StringBuffer(); patternArgs.append( patternTXJob.getArguments() ).append( " " ). append( patternTXJobStdin ); patternTXJob.setArguments( patternArgs.toString() ); patternTXJob.setStdIn( "" ); txJobs.add( patternTXJob ); txJobIDs.add( patternTXJob.getID() ); } //this should in fact only be set // for non third party pools //we first check if there entry for transfer universe, //if no then go for globus // SiteInfo ePool = mSCHandle.getTXPoolEntry( job.getSiteHandle() ); // JobManager jobmanager = ePool.selectJobManager(this.TRANSFER_UNIVERSE,true); SiteCatalogEntry ePool = mSiteStore.lookup( job.getSiteHandle() ); GridGateway jobmanager = ePool.selectGridGateway( GridGateway.JOB_TYPE.transfer ); //use the DC transfer client to handle the data sources for( Iterator it = rawDataSources.iterator(); it.hasNext(); ){ FileTransfer ft = (FileTransfer)it.next(); List<FileTransfer> l = new LinkedList<FileTransfer>(); l.add( ft ); TransferJob dcTXJob = mBAETransfer.createTransferJob( job, l, null, txJobName, jobClass ); txJobs.add( dcTXJob ); - txJobIDs.add( patternTXJob.getID() ); + txJobIDs.add( dcTXJob.getID() ); } //only merging if more than only one data set being staged TransferJob txJob = null; if( txJobs.size() > 1 ){ //now lets merge all these jobs SubInfo merged = mSeqExecAggregator.construct( txJobs, "transfer", txJobName ); txJob = new TransferJob( merged ); //set the name of the merged job back to the name of //transfer job passed in the function call txJob.setName( txJobName ); txJob.setJobType( jobClass ); }else{ txJob = (TransferJob) txJobs.get( 0 ); } //if a pattern job was constructed add the pattern stdin //as an input file for condor to transfer if( patternTXJobStdin != null ){ txJob.condorVariables.addIPFileForTransfer( patternTXJobStdin ); } //take care of transfer of proxies this.checkAndTransferProxy( txJob ); //apply the priority to the transfer job this.applyPriority( txJob ); if(execFiles != null){ //we need to add setup jobs to change the XBit super.addSetXBitJobs( job, txJob, execFiles ); } mLogger.logEntityHierarchyMessage( LoggingKeys.DAX_ID, mRefiner.getWorkflow().getAbstractWorkflowID(), LoggingKeys.JOB_ID, txJobIDs ); return txJob; } /** * Returns a textual description of the transfer implementation. * * @return a short textual description */ public String getDescription(){ return this.DESCRIPTION; } /** * Returns a boolean indicating whether the transfer protocol being used by * the implementation preserves the X Bit or not while staging. * * @return boolean */ public boolean doesPreserveXBit(){ return false; } /** * Return a boolean indicating whether the transfers to be done always in * a third party transfer mode. A value of false, results in the * direct or peer to peer transfers being done. * <p> * A value of false does not preclude third party transfers. They still can * be done, by setting the property "pegasus.transfer.*.thirdparty.sites". * * @return boolean indicating whether to always use third party transfers * or not. * * @see PegasusProperties#getThirdPartySites(String) */ public boolean useThirdPartyTransferAlways(){ return false; } /** * Retrieves the transformation catalog entry for the executable that is * being used to transfer the files in the implementation. * * @param siteHandle the handle of the site where the transformation is * to be searched. * * @return the transformation catalog entry if found, else null. */ public TransformationCatalogEntry getTransformationCatalogEntry( String siteHandle ){ List tcentries = null; try { //namespace and version are null for time being tcentries = mTCHandle.getTCEntries(this.TRANSFORMATION_NAMESPACE, this.TRANSFORMATION_NAME, this.TRANSFORMATION_VERSION, siteHandle, TCType.INSTALLED); } catch (Exception e) { mLogger.log( "Unable to retrieve entry from TC for " + getCompleteTCName() + " Cause:" + e, LogManager.DEBUG_MESSAGE_LEVEL ); } return ( tcentries == null ) ? this.defaultTCEntry( this.TRANSFORMATION_NAMESPACE, this.TRANSFORMATION_NAME, this.TRANSFORMATION_VERSION, siteHandle ): //try using a default one (TransformationCatalogEntry) tcentries.get(0); } /** * Quotes a URL and returns it * * @param url String * @return quoted url */ protected String quote( String url ){ StringBuffer q = new StringBuffer(); q.append( "'" ).append( url ).append( "'" ); return q.toString(); } /** * Returns a default TC entry to be used for the DC transfer client. * * @param namespace the namespace of the transfer transformation * @param name the logical name of the transfer transformation * @param version the version of the transfer transformation * * @param site the site for which the default entry is required. * * * @return the default entry. */ protected TransformationCatalogEntry defaultTCEntry( String namespace, String name, String version, String site ){ TransformationCatalogEntry defaultTCEntry = null; //check if DC_HOME is set String dcHome = mSiteStore.getEnvironmentVariable( site, "DC_HOME" ); mLogger.log( "Creating a default TC entry for " + Separator.combine( namespace, name, version ) + " at site " + site, LogManager.DEBUG_MESSAGE_LEVEL ); //if home is still null if ( dcHome == null ){ //cannot create default TC mLogger.log( "Unable to create a default entry for " + Separator.combine( namespace, name, version ) + " as DC_HOME is not set in Site Catalog" , LogManager.DEBUG_MESSAGE_LEVEL ); //set the flag back to true return defaultTCEntry; } //get the essential environment variables required to get //it to work correctly List envs = this.getEnvironmentVariables( site ); if( envs == null ){ //cannot create default TC mLogger.log( "Unable to create a default entry for as could not construct necessary environment " + Separator.combine( namespace, name, version ) , LogManager.DEBUG_MESSAGE_LEVEL ); //set the flag back to true return defaultTCEntry; } //add the DC home to environments envs.add( new Profile( Profile.ENV, "DC_HOME", dcHome ) ); //remove trailing / if specified dcHome = ( dcHome.charAt( dcHome.length() - 1 ) == File.separatorChar )? dcHome.substring( 0, dcHome.length() - 1 ): dcHome; //construct the path to the jar StringBuffer path = new StringBuffer(); path.append( dcHome ).append( File.separator ). append( "bin" ).append( File.separator ). append( "dc-transfer" ); defaultTCEntry = new TransformationCatalogEntry( namespace, name, version ); defaultTCEntry.setPhysicalTransformation( path.toString() ); defaultTCEntry.setResourceId( site ); defaultTCEntry.setType( TCType.INSTALLED ); defaultTCEntry.setProfiles( envs ); //register back into the transformation catalog //so that we do not need to worry about creating it again try{ mTCHandle.addTCEntry( defaultTCEntry , false ); } catch( Exception e ){ //just log as debug. as this is more of a performance improvement //than anything else mLogger.log( "Unable to register in the TC the default entry " + defaultTCEntry.getLogicalTransformation() + " for site " + site, e, LogManager.DEBUG_MESSAGE_LEVEL ); } mLogger.log( "Created entry with path " + defaultTCEntry.getPhysicalTransformation(), LogManager.DEBUG_MESSAGE_LEVEL ); return defaultTCEntry; } /** * Returns the environment profiles that are required for the default * entry to sensibly work. * * @param site the site where the job is going to run. * * @return List of environment variables, else null in case where the * required environment variables could not be found. */ protected List getEnvironmentVariables( String site ){ List result = new ArrayList(1) ; //create the CLASSPATH from home String java = mSiteStore.getEnvironmentVariable( site, "JAVA_HOME" ); if( java == null ){ mLogger.log( "JAVA_HOME not set in site catalog for site " + site, LogManager.DEBUG_MESSAGE_LEVEL ); return null; } //we have both the environment variables result.add( new Profile( Profile.ENV, "JAVA_HOME", java ) ); return result; } /** * Returns the complete name for the transformation. * * @return the complete name. */ protected String getCompleteTCName(){ return Separator.combine(this.TRANSFORMATION_NAMESPACE, this.TRANSFORMATION_NAME, this.TRANSFORMATION_VERSION); } }
true
true
public TransferJob createTransferJob( SubInfo job, Collection files, Collection execFiles, String txJobName, int jobClass) { //iterate through all the files and identify the patterns //and the other data sources Collection rawDataSources = new LinkedList(); Collection patterns = new LinkedList(); for( Iterator it = files.iterator(); it.hasNext(); ){ FileTransfer ft = ( FileTransfer )it.next(); //no way to distinguish a pattern right now /* if( ft.getLFN().startsWith( DATA_SOURCE_PREFIX ) && !ft.getSourceURL().getValue().endsWith( ".zip" )){ //it a raw data source that will have to be ingested rawDataSources.add( ft ); } else{ //everything else is a pattern patterns.add( ft ); }*/ rawDataSources.add( ft ); } List txJobs = new LinkedList(); //use the Pegasus Transfer to handle the patterns TransferJob patternTXJob = null; String patternTXJobStdin = null; List<String> txJobIDs = new LinkedList<String>(); if( !patterns.isEmpty() ){ patternTXJob = mPegasusTransfer.createTransferJob( job, patterns, null, txJobName, jobClass ); //get the stdin and set it as lof in the arguments patternTXJobStdin = patternTXJob.getStdIn(); StringBuffer patternArgs = new StringBuffer(); patternArgs.append( patternTXJob.getArguments() ).append( " " ). append( patternTXJobStdin ); patternTXJob.setArguments( patternArgs.toString() ); patternTXJob.setStdIn( "" ); txJobs.add( patternTXJob ); txJobIDs.add( patternTXJob.getID() ); } //this should in fact only be set // for non third party pools //we first check if there entry for transfer universe, //if no then go for globus // SiteInfo ePool = mSCHandle.getTXPoolEntry( job.getSiteHandle() ); // JobManager jobmanager = ePool.selectJobManager(this.TRANSFER_UNIVERSE,true); SiteCatalogEntry ePool = mSiteStore.lookup( job.getSiteHandle() ); GridGateway jobmanager = ePool.selectGridGateway( GridGateway.JOB_TYPE.transfer ); //use the DC transfer client to handle the data sources for( Iterator it = rawDataSources.iterator(); it.hasNext(); ){ FileTransfer ft = (FileTransfer)it.next(); List<FileTransfer> l = new LinkedList<FileTransfer>(); l.add( ft ); TransferJob dcTXJob = mBAETransfer.createTransferJob( job, l, null, txJobName, jobClass ); txJobs.add( dcTXJob ); txJobIDs.add( patternTXJob.getID() ); } //only merging if more than only one data set being staged TransferJob txJob = null; if( txJobs.size() > 1 ){ //now lets merge all these jobs SubInfo merged = mSeqExecAggregator.construct( txJobs, "transfer", txJobName ); txJob = new TransferJob( merged ); //set the name of the merged job back to the name of //transfer job passed in the function call txJob.setName( txJobName ); txJob.setJobType( jobClass ); }else{ txJob = (TransferJob) txJobs.get( 0 ); } //if a pattern job was constructed add the pattern stdin //as an input file for condor to transfer if( patternTXJobStdin != null ){ txJob.condorVariables.addIPFileForTransfer( patternTXJobStdin ); } //take care of transfer of proxies this.checkAndTransferProxy( txJob ); //apply the priority to the transfer job this.applyPriority( txJob ); if(execFiles != null){ //we need to add setup jobs to change the XBit super.addSetXBitJobs( job, txJob, execFiles ); } mLogger.logEntityHierarchyMessage( LoggingKeys.DAX_ID, mRefiner.getWorkflow().getAbstractWorkflowID(), LoggingKeys.JOB_ID, txJobIDs ); return txJob; }
public TransferJob createTransferJob( SubInfo job, Collection files, Collection execFiles, String txJobName, int jobClass) { //iterate through all the files and identify the patterns //and the other data sources Collection rawDataSources = new LinkedList(); Collection patterns = new LinkedList(); for( Iterator it = files.iterator(); it.hasNext(); ){ FileTransfer ft = ( FileTransfer )it.next(); //no way to distinguish a pattern right now /* if( ft.getLFN().startsWith( DATA_SOURCE_PREFIX ) && !ft.getSourceURL().getValue().endsWith( ".zip" )){ //it a raw data source that will have to be ingested rawDataSources.add( ft ); } else{ //everything else is a pattern patterns.add( ft ); }*/ rawDataSources.add( ft ); } List txJobs = new LinkedList(); //use the Pegasus Transfer to handle the patterns TransferJob patternTXJob = null; String patternTXJobStdin = null; List<String> txJobIDs = new LinkedList<String>(); if( !patterns.isEmpty() ){ patternTXJob = mPegasusTransfer.createTransferJob( job, patterns, null, txJobName, jobClass ); //get the stdin and set it as lof in the arguments patternTXJobStdin = patternTXJob.getStdIn(); StringBuffer patternArgs = new StringBuffer(); patternArgs.append( patternTXJob.getArguments() ).append( " " ). append( patternTXJobStdin ); patternTXJob.setArguments( patternArgs.toString() ); patternTXJob.setStdIn( "" ); txJobs.add( patternTXJob ); txJobIDs.add( patternTXJob.getID() ); } //this should in fact only be set // for non third party pools //we first check if there entry for transfer universe, //if no then go for globus // SiteInfo ePool = mSCHandle.getTXPoolEntry( job.getSiteHandle() ); // JobManager jobmanager = ePool.selectJobManager(this.TRANSFER_UNIVERSE,true); SiteCatalogEntry ePool = mSiteStore.lookup( job.getSiteHandle() ); GridGateway jobmanager = ePool.selectGridGateway( GridGateway.JOB_TYPE.transfer ); //use the DC transfer client to handle the data sources for( Iterator it = rawDataSources.iterator(); it.hasNext(); ){ FileTransfer ft = (FileTransfer)it.next(); List<FileTransfer> l = new LinkedList<FileTransfer>(); l.add( ft ); TransferJob dcTXJob = mBAETransfer.createTransferJob( job, l, null, txJobName, jobClass ); txJobs.add( dcTXJob ); txJobIDs.add( dcTXJob.getID() ); } //only merging if more than only one data set being staged TransferJob txJob = null; if( txJobs.size() > 1 ){ //now lets merge all these jobs SubInfo merged = mSeqExecAggregator.construct( txJobs, "transfer", txJobName ); txJob = new TransferJob( merged ); //set the name of the merged job back to the name of //transfer job passed in the function call txJob.setName( txJobName ); txJob.setJobType( jobClass ); }else{ txJob = (TransferJob) txJobs.get( 0 ); } //if a pattern job was constructed add the pattern stdin //as an input file for condor to transfer if( patternTXJobStdin != null ){ txJob.condorVariables.addIPFileForTransfer( patternTXJobStdin ); } //take care of transfer of proxies this.checkAndTransferProxy( txJob ); //apply the priority to the transfer job this.applyPriority( txJob ); if(execFiles != null){ //we need to add setup jobs to change the XBit super.addSetXBitJobs( job, txJob, execFiles ); } mLogger.logEntityHierarchyMessage( LoggingKeys.DAX_ID, mRefiner.getWorkflow().getAbstractWorkflowID(), LoggingKeys.JOB_ID, txJobIDs ); return txJob; }
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/ManageWatchpointActionDelegate.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/ManageWatchpointActionDelegate.java index 7d3a69c8d..77ff6ca22 100644 --- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/ManageWatchpointActionDelegate.java +++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/ManageWatchpointActionDelegate.java @@ -1,283 +1,283 @@ package org.eclipse.jdt.internal.debug.ui.actions; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.debug.core.DebugException; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.IBreakpointManager; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.model.IBreakpoint; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.search.IJavaSearchConstants; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.ITypeNameRequestor; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.debug.core.IJavaBreakpoint; import org.eclipse.jdt.debug.core.IJavaFieldVariable; import org.eclipse.jdt.debug.core.IJavaWatchpoint; import org.eclipse.jdt.debug.core.JDIDebugModel; import org.eclipse.jdt.internal.corext.util.TypeInfo; import org.eclipse.jdt.internal.corext.util.TypeInfoRequestor; import org.eclipse.jdt.internal.debug.ui.BreakpointUtils; import org.eclipse.jdt.internal.debug.ui.JDIDebugUIPlugin; import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; public class ManageWatchpointActionDelegate extends AbstractManageBreakpointActionDelegate { public ManageWatchpointActionDelegate() { super(); fAddText= ActionMessages.getString("ManageWatchpointAction.Add_&Watchpoint_1"); //$NON-NLS-1$ fAddDescription= ActionMessages.getString("ManageWatchpointAction.Add_a_watchpoint_2"); //$NON-NLS-1$ fRemoveText= ActionMessages.getString("ManageWatchpointAction.Remove_&Watchpoint_4"); //$NON-NLS-1$ fRemoveDescription= ActionMessages.getString("ManageWatchpointAction.Remove_a_field_watchpoint_5"); //$NON-NLS-1$ } /** * @see IActionDelegate#run(IAction) */ public void run(IAction action) { if (getBreakpoint() == null) { try { IMember element= getMember(); if (element == null) { update(); return; } IType type = element.getDeclaringType(); int start = -1; int end = -1; ISourceRange range = element.getNameRange(); if (range != null) { start = range.getOffset(); end = start + range.getLength(); } Map attributes = new HashMap(10); BreakpointUtils.addJavaBreakpointAttributes(attributes, element); setBreakpoint(JDIDebugModel.createWatchpoint(BreakpointUtils.getBreakpointResource(type),type.getFullyQualifiedName(), element.getElementName(), -1, start, end, 0, true, attributes)); } catch (JavaModelException e) { JDIDebugUIPlugin.log(e); MessageDialog.openError(JDIDebugUIPlugin.getActiveWorkbenchShell(), ActionMessages.getString("ManageWatchpointAction.Problems_adding_watchpoint_7"), ActionMessages.getString("ManageWatchpointAction.The_selected_field_is_not_visible_in_the_currently_selected_debug_context._A_stack_frame_or_suspended_thread_which_contains_the_declaring_type_of_this_field_must_be_selected_1")); //$NON-NLS-1$ //$NON-NLS-2$ } catch (CoreException x) { JDIDebugUIPlugin.log(x); MessageDialog.openError(JDIDebugUIPlugin.getActiveWorkbenchShell(), ActionMessages.getString("ManageWatchpointAction.Problems_adding_watchpoint_7"), x.getMessage()); //$NON-NLS-1$ } } else { // remove breakpoint try { IBreakpointManager breakpointManager= DebugPlugin.getDefault().getBreakpointManager(); breakpointManager.removeBreakpoint(getBreakpoint(), true); } catch (CoreException x) { JDIDebugUIPlugin.log(x); MessageDialog.openError(JDIDebugUIPlugin.getActiveWorkbenchShell(), ActionMessages.getString("ManageWatchpointAction.Problems_removing_watchpoint_8"), x.getMessage()); //$NON-NLS-1$ } } update(); } protected IJavaBreakpoint getBreakpoint(IMember selectedField) { IBreakpointManager breakpointManager= DebugPlugin.getDefault().getBreakpointManager(); IBreakpoint[] breakpoints= breakpointManager.getBreakpoints(JDIDebugModel.getPluginIdentifier()); for (int i= 0; i < breakpoints.length; i++) { IBreakpoint breakpoint= breakpoints[i]; if (breakpoint instanceof IJavaWatchpoint) { try { if (equalFields(selectedField, (IJavaWatchpoint)breakpoint)) return (IJavaBreakpoint)breakpoint; } catch (CoreException e) { JDIDebugUIPlugin.log(e); } } } return null; } /** * Compare two fields. The default <code>equals()</code> * method for <code>IField</code> doesn't give the comparison desired. */ private boolean equalFields(IMember breakpointField, IJavaWatchpoint watchpoint) throws CoreException { return (breakpointField.getElementName().equals(watchpoint.getFieldName()) && breakpointField.getDeclaringType().getFullyQualifiedName().equals(watchpoint.getTypeName())); } protected IMember getMember(ISelection s) { if (s instanceof IStructuredSelection) { IStructuredSelection ss= (IStructuredSelection) s; if (ss.size() == 1) { Object o= ss.getFirstElement(); if (o instanceof IField) { return (IField) o; } else if (o instanceof IJavaFieldVariable) { return getField((IJavaFieldVariable) o); } } } return null; } /** * Return the associated IField (Java model) for the given * IJavaFieldVariable (JDI model) */ protected IField getField(IJavaFieldVariable variable) { String varName= null; try { varName= variable.getName(); } catch (DebugException x) { JDIDebugUIPlugin.log(x); return null; } IField field; List types= searchForDeclaringType(variable); Iterator iter= types.iterator(); while (iter.hasNext()) { IType type= (IType)iter.next(); field= type.getField(varName); if (field.exists()) { return field; } } return null; } /** * Returns a list of matching types (IType - Java model) that correspond to the * declaring type (ReferenceType - JDI model) of the given variable. */ protected List searchForDeclaringType(IJavaFieldVariable variable) { List types= new ArrayList(); ILaunch launch = variable.getDebugTarget().getLaunch(); if (launch == null) { return types; } ILaunchConfiguration configuration= launch.getLaunchConfiguration(); IJavaProject[] javaProjects = null; IWorkspace workspace= ResourcesPlugin.getWorkspace(); if (configuration != null) { // Launch configuration support try { String projectName= configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, ""); //$NON-NLS-1$ if (projectName.length() != 0) { javaProjects= new IJavaProject[] {JavaCore.create(workspace.getRoot().getProject(projectName))}; } else { IProject[] projects= ResourcesPlugin.getWorkspace().getRoot().getProjects(); IProject project; List projectList= new ArrayList(); for (int i= 0, numProjects= projects.length; i < numProjects; i++) { project= projects[i]; - if (project.hasNature(JavaCore.NATURE_ID)) { + if (project.isAccessible() && project.hasNature(JavaCore.NATURE_ID)) { projectList.add(JavaCore.create(project)); } } javaProjects= new IJavaProject[projectList.size()]; projectList.toArray(javaProjects); } } catch (CoreException e) { JDIDebugUIPlugin.log(e); } } if (javaProjects == null) { return types; } SearchEngine engine= new SearchEngine(); IJavaSearchScope scope= engine.createJavaSearchScope(javaProjects, true); String declaringType= null; try { declaringType= variable.getDeclaringType().getName(); } catch (DebugException x) { JDIDebugUIPlugin.log(x); return types; } ArrayList typeRefsFound= new ArrayList(3); ITypeNameRequestor requestor= new TypeInfoRequestor(typeRefsFound); try { engine.searchAllTypeNames(workspace, getPackage(declaringType), getTypeName(declaringType), IJavaSearchConstants.EXACT_MATCH, true, IJavaSearchConstants.CLASS, scope, requestor, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null); } catch (JavaModelException x) { JDIDebugUIPlugin.log(x); return types; } Iterator iter= typeRefsFound.iterator(); TypeInfo typeInfo= null; while (iter.hasNext()) { typeInfo= (TypeInfo)iter.next(); try { types.add(typeInfo.resolveType(scope)); } catch (JavaModelException jme) { JDIDebugUIPlugin.log(jme); } } return types; } /** * Returns the package name of the given fully qualified type name. * The package name is assumed to be the dot-separated prefix of the * type name. */ protected char[] getPackage(String fullyQualifiedName) { int index= fullyQualifiedName.lastIndexOf('.'); if (index == -1) { return new char[0]; } return fullyQualifiedName.substring(0, index).toCharArray(); } /** * Returns a simple type name from the given fully qualified type name. * The type name is assumed to be the last contiguous segment of the * fullyQualifiedName not containing a '.' or '$' */ protected char[] getTypeName(String fullyQualifiedName) { int index= fullyQualifiedName.lastIndexOf('.'); String typeName= fullyQualifiedName.substring(index + 1); int lastInnerClass= typeName.lastIndexOf('$'); if (lastInnerClass != -1) { typeName= typeName.substring(lastInnerClass + 1); } return typeName.toCharArray(); } /** * @see AbstractManageBreakpointActionDelegate#enableForMember(IMember) */ protected boolean enableForMember(IMember member) { return member instanceof IField; } }
true
true
protected List searchForDeclaringType(IJavaFieldVariable variable) { List types= new ArrayList(); ILaunch launch = variable.getDebugTarget().getLaunch(); if (launch == null) { return types; } ILaunchConfiguration configuration= launch.getLaunchConfiguration(); IJavaProject[] javaProjects = null; IWorkspace workspace= ResourcesPlugin.getWorkspace(); if (configuration != null) { // Launch configuration support try { String projectName= configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, ""); //$NON-NLS-1$ if (projectName.length() != 0) { javaProjects= new IJavaProject[] {JavaCore.create(workspace.getRoot().getProject(projectName))}; } else { IProject[] projects= ResourcesPlugin.getWorkspace().getRoot().getProjects(); IProject project; List projectList= new ArrayList(); for (int i= 0, numProjects= projects.length; i < numProjects; i++) { project= projects[i]; if (project.hasNature(JavaCore.NATURE_ID)) { projectList.add(JavaCore.create(project)); } } javaProjects= new IJavaProject[projectList.size()]; projectList.toArray(javaProjects); } } catch (CoreException e) { JDIDebugUIPlugin.log(e); } } if (javaProjects == null) { return types; } SearchEngine engine= new SearchEngine(); IJavaSearchScope scope= engine.createJavaSearchScope(javaProjects, true); String declaringType= null; try { declaringType= variable.getDeclaringType().getName(); } catch (DebugException x) { JDIDebugUIPlugin.log(x); return types; } ArrayList typeRefsFound= new ArrayList(3); ITypeNameRequestor requestor= new TypeInfoRequestor(typeRefsFound); try { engine.searchAllTypeNames(workspace, getPackage(declaringType), getTypeName(declaringType), IJavaSearchConstants.EXACT_MATCH, true, IJavaSearchConstants.CLASS, scope, requestor, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null); } catch (JavaModelException x) { JDIDebugUIPlugin.log(x); return types; } Iterator iter= typeRefsFound.iterator(); TypeInfo typeInfo= null; while (iter.hasNext()) { typeInfo= (TypeInfo)iter.next(); try { types.add(typeInfo.resolveType(scope)); } catch (JavaModelException jme) { JDIDebugUIPlugin.log(jme); } } return types; }
protected List searchForDeclaringType(IJavaFieldVariable variable) { List types= new ArrayList(); ILaunch launch = variable.getDebugTarget().getLaunch(); if (launch == null) { return types; } ILaunchConfiguration configuration= launch.getLaunchConfiguration(); IJavaProject[] javaProjects = null; IWorkspace workspace= ResourcesPlugin.getWorkspace(); if (configuration != null) { // Launch configuration support try { String projectName= configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, ""); //$NON-NLS-1$ if (projectName.length() != 0) { javaProjects= new IJavaProject[] {JavaCore.create(workspace.getRoot().getProject(projectName))}; } else { IProject[] projects= ResourcesPlugin.getWorkspace().getRoot().getProjects(); IProject project; List projectList= new ArrayList(); for (int i= 0, numProjects= projects.length; i < numProjects; i++) { project= projects[i]; if (project.isAccessible() && project.hasNature(JavaCore.NATURE_ID)) { projectList.add(JavaCore.create(project)); } } javaProjects= new IJavaProject[projectList.size()]; projectList.toArray(javaProjects); } } catch (CoreException e) { JDIDebugUIPlugin.log(e); } } if (javaProjects == null) { return types; } SearchEngine engine= new SearchEngine(); IJavaSearchScope scope= engine.createJavaSearchScope(javaProjects, true); String declaringType= null; try { declaringType= variable.getDeclaringType().getName(); } catch (DebugException x) { JDIDebugUIPlugin.log(x); return types; } ArrayList typeRefsFound= new ArrayList(3); ITypeNameRequestor requestor= new TypeInfoRequestor(typeRefsFound); try { engine.searchAllTypeNames(workspace, getPackage(declaringType), getTypeName(declaringType), IJavaSearchConstants.EXACT_MATCH, true, IJavaSearchConstants.CLASS, scope, requestor, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null); } catch (JavaModelException x) { JDIDebugUIPlugin.log(x); return types; } Iterator iter= typeRefsFound.iterator(); TypeInfo typeInfo= null; while (iter.hasNext()) { typeInfo= (TypeInfo)iter.next(); try { types.add(typeInfo.resolveType(scope)); } catch (JavaModelException jme) { JDIDebugUIPlugin.log(jme); } } return types; }
diff --git a/choco-parser/src/main/java/parser/flatzinc/ast/FGoal.java b/choco-parser/src/main/java/parser/flatzinc/ast/FGoal.java index 3657fc438..41a3e7b2b 100755 --- a/choco-parser/src/main/java/parser/flatzinc/ast/FGoal.java +++ b/choco-parser/src/main/java/parser/flatzinc/ast/FGoal.java @@ -1,237 +1,237 @@ /* * Copyright (c) 1999-2012, Ecole des Mines de Nantes * 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 Ecole des Mines de Nantes 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 REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package parser.flatzinc.ast; import org.slf4j.LoggerFactory; import parser.flatzinc.FZNException; import parser.flatzinc.ast.expression.EAnnotation; import parser.flatzinc.ast.expression.EArray; import parser.flatzinc.ast.expression.EIdentifier; import parser.flatzinc.ast.expression.Expression; import parser.flatzinc.ast.searches.IntSearch; import parser.flatzinc.ast.searches.Strategy; import parser.flatzinc.ast.searches.VarChoice; import solver.ResolutionPolicy; import solver.Solver; import solver.objective.ObjectiveManager; import solver.search.loop.AbstractSearchLoop; import solver.search.loop.monitors.SearchMonitorFactory; import solver.search.strategy.IntStrategyFactory; import solver.search.strategy.selectors.values.InDomainMin; import solver.search.strategy.selectors.variables.ActivityBased; import solver.search.strategy.selectors.variables.DomOverWDeg; import solver.search.strategy.selectors.variables.FirstFail; import solver.search.strategy.selectors.variables.ImpactBased; import solver.search.strategy.strategy.AbstractStrategy; import solver.search.strategy.strategy.Assignment; import solver.search.strategy.strategy.StrategiesSequencer; import solver.variables.IntVar; import solver.variables.Variable; import util.tools.ArrayUtils; import java.util.List; /* * User : CPRUDHOM * Mail : cprudhom(a)emn.fr * Date : 12 janv. 2010 * Since : Choco 2.1.1 * * Class for solve goals definition based on flatzinc-like objects. * * A solve goal is defined with: * </br> 'solve annotations satisfy;' * </br> or 'solve annotations maximize expression;' * /br> or 'solve annotations minimize expression;' */ public class FGoal { private enum Search { int_search, bool_search, set_search } public static void define_goal(GoalConf gc, Solver aSolver, List<EAnnotation> annotations, ResolutionPolicy type, Expression expr) { // First define solving process AbstractSearchLoop search = aSolver.getSearchLoop(); switch (type) { case SATISFACTION: break; default: IntVar obj = expr.intVarValue(aSolver); search.setObjectivemanager(new ObjectiveManager(obj, type, aSolver));// solver.setRestart(true); } if (gc.timeLimit > -1) { SearchMonitorFactory.limitTime(aSolver, gc.timeLimit); } aSolver.set(gc.searchPattern); // Then define search goal Variable[] vars = aSolver.getVars(); IntVar[] ivars = new IntVar[vars.length]; for (int i = 0; i < ivars.length; i++) { ivars[i] = (IntVar) vars[i]; } StringBuilder description = new StringBuilder(); if (annotations.size() > 0 && !gc.free) { AbstractStrategy strategy = null; if (annotations.size() > 1) { throw new UnsupportedOperationException("SolveGoal:: wrong annotations size"); } else { EAnnotation annotation = annotations.get(0); if (annotation.id.value.equals("seq_search")) { EArray earray = (EArray) annotation.exps.get(0); AbstractStrategy[] strategies = new AbstractStrategy[earray.what.size()]; for (int i = 0; i < strategies.length; i++) { strategies[i] = readSearchAnnotation((EAnnotation) earray.getWhat_i(i), aSolver, description); } strategy = new StrategiesSequencer(aSolver.getEnvironment(), strategies); } else { strategy = readSearchAnnotation(annotation, aSolver, description); } // solver.set(strategy); LoggerFactory.getLogger(FGoal.class).warn("% Fix seed"); aSolver.set( new StrategiesSequencer(aSolver.getEnvironment(), strategy, IntStrategyFactory.random(ivars, gc.seed)) ); System.out.println("% t:" + gc.seed); } } else { // no strategy OR use free search if (gc.dec_vars) { // select same decision variables as declared in file? Variable[] dvars = new Variable[0]; if (annotations.size() > 1) { throw new UnsupportedOperationException("SolveGoal:: wrong annotations size"); } else { EAnnotation annotation = annotations.get(0); if (annotation.id.value.equals("seq_search")) { EArray earray = (EArray) annotation.exps.get(0); for (int i = 0; i < earray.what.size(); i++) { - ArrayUtils.append(dvars, extractScope((EAnnotation) earray.getWhat_i(i), aSolver)); + dvars = ArrayUtils.append(dvars, extractScope((EAnnotation) earray.getWhat_i(i), aSolver)); } } else { dvars = ArrayUtils.append(dvars, extractScope(annotation, aSolver)); } } ivars = new IntVar[dvars.length]; for (int i = 0; i < dvars.length; i++) { ivars[i] = (IntVar) dvars[i]; } } LoggerFactory.getLogger(FGoal.class).warn("% No search annotation. Set default."); if (type == ResolutionPolicy.SATISFACTION && gc.all) { aSolver.set(new Assignment(new FirstFail(ivars), new InDomainMin())); } else { switch (gc.bbss) { case 2: description.append("ibs"); ImpactBased ibs = new ImpactBased(ivars, 2, 3, 10, gc.seed, false); ibs.setTimeLimit(gc.timeLimit); aSolver.set(ibs); break; case 3: description.append("wdeg"); DomOverWDeg dwd = new DomOverWDeg(ivars, gc.seed); aSolver.set(new Assignment(dwd, new InDomainMin())); break; case 4: description.append("first_fail"); aSolver.set(new Assignment(new FirstFail(ivars), new InDomainMin())); break; case 1: default: description.append("abs"); ActivityBased abs = new ActivityBased(aSolver, ivars, 0.999d, 0.2d, 8, 1.1d, 1, gc.seed); aSolver.set(abs); // if (type != ResolutionPolicy.SATISFACTION) { // also add LNS in optimization // aSolver.getSearchLoop().plugSearchMonitor(new ABSLNS(aSolver, ivars, gc.seed, abs, false, ivars.length / 2)); // } break; } } } gc.setDescription(description.toString()); } /** * Read search annotation and build corresponding strategy * * @param e {@link parser.flatzinc.ast.expression.EAnnotation} * @param solver solver within the search is defined * @return {@code true} if a search strategy is defined */ private static AbstractStrategy readSearchAnnotation(EAnnotation e, Solver solver, StringBuilder description) { Expression[] exps = new Expression[e.exps.size()]; e.exps.toArray(exps); Search search = Search.valueOf(e.id.value); VarChoice vchoice = VarChoice.valueOf(((EIdentifier) exps[1]).value); description.append(vchoice.toString()).append(";"); parser.flatzinc.ast.searches.Assignment assignment = parser.flatzinc.ast.searches.Assignment.valueOf(((EIdentifier) exps[2]).value); switch (search) { case int_search: case bool_search: IntVar[] scope = exps[0].toIntVarArray(solver); return IntSearch.build(scope, vchoice, assignment, Strategy.complete, solver); case set_search: default: LoggerFactory.getLogger(FGoal.class).error("Unknown search annotation " + e.toString()); throw new FZNException(); } } /** * Read search annotation and build corresponding strategy * * @param e {@link parser.flatzinc.ast.expression.EAnnotation} * @param solver solver within the search is defined * @return {@code true} if a search strategy is defined */ private static Variable[] extractScope(EAnnotation e, Solver solver) { Expression[] exps = new Expression[e.exps.size()]; e.exps.toArray(exps); Search search = Search.valueOf(e.id.value); switch (search) { case int_search: case bool_search: return exps[0].toIntVarArray(solver); case set_search: default: LoggerFactory.getLogger(FGoal.class).error("Unknown search annotation " + e.toString()); throw new FZNException(); } } }
true
true
public static void define_goal(GoalConf gc, Solver aSolver, List<EAnnotation> annotations, ResolutionPolicy type, Expression expr) { // First define solving process AbstractSearchLoop search = aSolver.getSearchLoop(); switch (type) { case SATISFACTION: break; default: IntVar obj = expr.intVarValue(aSolver); search.setObjectivemanager(new ObjectiveManager(obj, type, aSolver));// solver.setRestart(true); } if (gc.timeLimit > -1) { SearchMonitorFactory.limitTime(aSolver, gc.timeLimit); } aSolver.set(gc.searchPattern); // Then define search goal Variable[] vars = aSolver.getVars(); IntVar[] ivars = new IntVar[vars.length]; for (int i = 0; i < ivars.length; i++) { ivars[i] = (IntVar) vars[i]; } StringBuilder description = new StringBuilder(); if (annotations.size() > 0 && !gc.free) { AbstractStrategy strategy = null; if (annotations.size() > 1) { throw new UnsupportedOperationException("SolveGoal:: wrong annotations size"); } else { EAnnotation annotation = annotations.get(0); if (annotation.id.value.equals("seq_search")) { EArray earray = (EArray) annotation.exps.get(0); AbstractStrategy[] strategies = new AbstractStrategy[earray.what.size()]; for (int i = 0; i < strategies.length; i++) { strategies[i] = readSearchAnnotation((EAnnotation) earray.getWhat_i(i), aSolver, description); } strategy = new StrategiesSequencer(aSolver.getEnvironment(), strategies); } else { strategy = readSearchAnnotation(annotation, aSolver, description); } // solver.set(strategy); LoggerFactory.getLogger(FGoal.class).warn("% Fix seed"); aSolver.set( new StrategiesSequencer(aSolver.getEnvironment(), strategy, IntStrategyFactory.random(ivars, gc.seed)) ); System.out.println("% t:" + gc.seed); } } else { // no strategy OR use free search if (gc.dec_vars) { // select same decision variables as declared in file? Variable[] dvars = new Variable[0]; if (annotations.size() > 1) { throw new UnsupportedOperationException("SolveGoal:: wrong annotations size"); } else { EAnnotation annotation = annotations.get(0); if (annotation.id.value.equals("seq_search")) { EArray earray = (EArray) annotation.exps.get(0); for (int i = 0; i < earray.what.size(); i++) { ArrayUtils.append(dvars, extractScope((EAnnotation) earray.getWhat_i(i), aSolver)); } } else { dvars = ArrayUtils.append(dvars, extractScope(annotation, aSolver)); } } ivars = new IntVar[dvars.length]; for (int i = 0; i < dvars.length; i++) { ivars[i] = (IntVar) dvars[i]; } } LoggerFactory.getLogger(FGoal.class).warn("% No search annotation. Set default."); if (type == ResolutionPolicy.SATISFACTION && gc.all) { aSolver.set(new Assignment(new FirstFail(ivars), new InDomainMin())); } else { switch (gc.bbss) { case 2: description.append("ibs"); ImpactBased ibs = new ImpactBased(ivars, 2, 3, 10, gc.seed, false); ibs.setTimeLimit(gc.timeLimit); aSolver.set(ibs); break; case 3: description.append("wdeg"); DomOverWDeg dwd = new DomOverWDeg(ivars, gc.seed); aSolver.set(new Assignment(dwd, new InDomainMin())); break; case 4: description.append("first_fail"); aSolver.set(new Assignment(new FirstFail(ivars), new InDomainMin())); break; case 1: default: description.append("abs"); ActivityBased abs = new ActivityBased(aSolver, ivars, 0.999d, 0.2d, 8, 1.1d, 1, gc.seed); aSolver.set(abs); // if (type != ResolutionPolicy.SATISFACTION) { // also add LNS in optimization // aSolver.getSearchLoop().plugSearchMonitor(new ABSLNS(aSolver, ivars, gc.seed, abs, false, ivars.length / 2)); // } break; } } } gc.setDescription(description.toString()); }
public static void define_goal(GoalConf gc, Solver aSolver, List<EAnnotation> annotations, ResolutionPolicy type, Expression expr) { // First define solving process AbstractSearchLoop search = aSolver.getSearchLoop(); switch (type) { case SATISFACTION: break; default: IntVar obj = expr.intVarValue(aSolver); search.setObjectivemanager(new ObjectiveManager(obj, type, aSolver));// solver.setRestart(true); } if (gc.timeLimit > -1) { SearchMonitorFactory.limitTime(aSolver, gc.timeLimit); } aSolver.set(gc.searchPattern); // Then define search goal Variable[] vars = aSolver.getVars(); IntVar[] ivars = new IntVar[vars.length]; for (int i = 0; i < ivars.length; i++) { ivars[i] = (IntVar) vars[i]; } StringBuilder description = new StringBuilder(); if (annotations.size() > 0 && !gc.free) { AbstractStrategy strategy = null; if (annotations.size() > 1) { throw new UnsupportedOperationException("SolveGoal:: wrong annotations size"); } else { EAnnotation annotation = annotations.get(0); if (annotation.id.value.equals("seq_search")) { EArray earray = (EArray) annotation.exps.get(0); AbstractStrategy[] strategies = new AbstractStrategy[earray.what.size()]; for (int i = 0; i < strategies.length; i++) { strategies[i] = readSearchAnnotation((EAnnotation) earray.getWhat_i(i), aSolver, description); } strategy = new StrategiesSequencer(aSolver.getEnvironment(), strategies); } else { strategy = readSearchAnnotation(annotation, aSolver, description); } // solver.set(strategy); LoggerFactory.getLogger(FGoal.class).warn("% Fix seed"); aSolver.set( new StrategiesSequencer(aSolver.getEnvironment(), strategy, IntStrategyFactory.random(ivars, gc.seed)) ); System.out.println("% t:" + gc.seed); } } else { // no strategy OR use free search if (gc.dec_vars) { // select same decision variables as declared in file? Variable[] dvars = new Variable[0]; if (annotations.size() > 1) { throw new UnsupportedOperationException("SolveGoal:: wrong annotations size"); } else { EAnnotation annotation = annotations.get(0); if (annotation.id.value.equals("seq_search")) { EArray earray = (EArray) annotation.exps.get(0); for (int i = 0; i < earray.what.size(); i++) { dvars = ArrayUtils.append(dvars, extractScope((EAnnotation) earray.getWhat_i(i), aSolver)); } } else { dvars = ArrayUtils.append(dvars, extractScope(annotation, aSolver)); } } ivars = new IntVar[dvars.length]; for (int i = 0; i < dvars.length; i++) { ivars[i] = (IntVar) dvars[i]; } } LoggerFactory.getLogger(FGoal.class).warn("% No search annotation. Set default."); if (type == ResolutionPolicy.SATISFACTION && gc.all) { aSolver.set(new Assignment(new FirstFail(ivars), new InDomainMin())); } else { switch (gc.bbss) { case 2: description.append("ibs"); ImpactBased ibs = new ImpactBased(ivars, 2, 3, 10, gc.seed, false); ibs.setTimeLimit(gc.timeLimit); aSolver.set(ibs); break; case 3: description.append("wdeg"); DomOverWDeg dwd = new DomOverWDeg(ivars, gc.seed); aSolver.set(new Assignment(dwd, new InDomainMin())); break; case 4: description.append("first_fail"); aSolver.set(new Assignment(new FirstFail(ivars), new InDomainMin())); break; case 1: default: description.append("abs"); ActivityBased abs = new ActivityBased(aSolver, ivars, 0.999d, 0.2d, 8, 1.1d, 1, gc.seed); aSolver.set(abs); // if (type != ResolutionPolicy.SATISFACTION) { // also add LNS in optimization // aSolver.getSearchLoop().plugSearchMonitor(new ABSLNS(aSolver, ivars, gc.seed, abs, false, ivars.length / 2)); // } break; } } } gc.setDescription(description.toString()); }
diff --git a/lucene/test-framework/src/java/org/apache/lucene/util/_TestUtil.java b/lucene/test-framework/src/java/org/apache/lucene/util/_TestUtil.java index 848a7364d..c6dbdd682 100644 --- a/lucene/test-framework/src/java/org/apache/lucene/util/_TestUtil.java +++ b/lucene/test-framework/src/java/org/apache/lucene/util/_TestUtil.java @@ -1,710 +1,710 @@ package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.lang.reflect.Method; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.apache.lucene.codecs.Codec; import org.apache.lucene.codecs.PostingsFormat; import org.apache.lucene.codecs.lucene40.Lucene40Codec; import org.apache.lucene.codecs.perfield.PerFieldPostingsFormat; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.CheckIndex; import org.apache.lucene.index.ConcurrentMergeScheduler; import org.apache.lucene.index.DocsAndPositionsEnum; import org.apache.lucene.index.DocsEnum; import org.apache.lucene.index.FieldInfos; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexableField; import org.apache.lucene.index.LogMergePolicy; import org.apache.lucene.index.MergePolicy; import org.apache.lucene.index.MergeScheduler; import org.apache.lucene.index.MultiFields; import org.apache.lucene.index.Terms; import org.apache.lucene.index.TermsEnum; import org.apache.lucene.index.TieredMergePolicy; import org.apache.lucene.search.FieldDoc; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.junit.Assert; public class _TestUtil { /** Returns temp dir, based on String arg in its name; * does not create the directory. */ public static File getTempDir(String desc) { try { File f = createTempFile(desc, "tmp", LuceneTestCase.TEMP_DIR); f.delete(); LuceneTestCase.registerTempDir(f); return f; } catch (IOException e) { throw new RuntimeException(e); } } /** * Deletes a directory and everything underneath it. */ public static void rmDir(File dir) throws IOException { if (dir.exists()) { if (dir.isFile() && !dir.delete()) { throw new IOException("could not delete " + dir); } for (File f : dir.listFiles()) { if (f.isDirectory()) { rmDir(f); } else { if (!f.delete()) { throw new IOException("could not delete " + f); } } } if (!dir.delete()) { throw new IOException("could not delete " + dir); } } } /** * Convenience method: Unzip zipName + ".zip" under destDir, removing destDir first */ public static void unzip(File zipName, File destDir) throws IOException { ZipFile zipFile = new ZipFile(zipName); Enumeration<? extends ZipEntry> entries = zipFile.entries(); rmDir(destDir); destDir.mkdir(); LuceneTestCase.registerTempDir(destDir); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); InputStream in = zipFile.getInputStream(entry); File targetFile = new File(destDir, entry.getName()); if (entry.isDirectory()) { // allow unzipping with directory structure targetFile.mkdirs(); } else { if (targetFile.getParentFile()!=null) { // be on the safe side: do not rely on that directories are always extracted // before their children (although this makes sense, but is it guaranteed?) targetFile.getParentFile().mkdirs(); } OutputStream out = new BufferedOutputStream(new FileOutputStream(targetFile)); byte[] buffer = new byte[8192]; int len; while((len = in.read(buffer)) >= 0) { out.write(buffer, 0, len); } in.close(); out.close(); } } zipFile.close(); } public static void syncConcurrentMerges(IndexWriter writer) { syncConcurrentMerges(writer.getConfig().getMergeScheduler()); } public static void syncConcurrentMerges(MergeScheduler ms) { if (ms instanceof ConcurrentMergeScheduler) ((ConcurrentMergeScheduler) ms).sync(); } /** This runs the CheckIndex tool on the index in. If any * issues are hit, a RuntimeException is thrown; else, * true is returned. */ public static CheckIndex.Status checkIndex(Directory dir) throws IOException { return checkIndex(dir, true); } public static CheckIndex.Status checkIndex(Directory dir, boolean crossCheckTermVectors) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(1024); CheckIndex checker = new CheckIndex(dir); checker.setCrossCheckTermVectors(crossCheckTermVectors); checker.setInfoStream(new PrintStream(bos), false); CheckIndex.Status indexStatus = checker.checkIndex(null); if (indexStatus == null || indexStatus.clean == false) { System.out.println("CheckIndex failed"); System.out.println(bos.toString()); throw new RuntimeException("CheckIndex failed"); } else { if (LuceneTestCase.INFOSTREAM) { System.out.println(bos.toString()); } return indexStatus; } } // NOTE: only works for TMP and LMP!! public static void setUseCompoundFile(MergePolicy mp, boolean v) { if (mp instanceof TieredMergePolicy) { ((TieredMergePolicy) mp).setUseCompoundFile(v); } else if (mp instanceof LogMergePolicy) { ((LogMergePolicy) mp).setUseCompoundFile(v); } } /** start and end are BOTH inclusive */ public static int nextInt(Random r, int start, int end) { return start + r.nextInt(end-start+1); } public static String randomSimpleString(Random r) { final int end = r.nextInt(10); if (end == 0) { // allow 0 length return ""; } final char[] buffer = new char[end]; for (int i = 0; i < end; i++) { buffer[i] = (char) _TestUtil.nextInt(r, 97, 102); } return new String(buffer, 0, end); } /** Returns random string, including full unicode range. */ public static String randomUnicodeString(Random r) { return randomUnicodeString(r, 20); } /** * Returns a random string up to a certain length. */ public static String randomUnicodeString(Random r, int maxLength) { final int end = r.nextInt(maxLength); if (end == 0) { // allow 0 length return ""; } final char[] buffer = new char[end]; randomFixedLengthUnicodeString(r, buffer, 0, buffer.length); return new String(buffer, 0, end); } /** * Fills provided char[] with valid random unicode code * unit sequence. */ public static void randomFixedLengthUnicodeString(Random random, char[] chars, int offset, int length) { int i = offset; final int end = offset + length; while(i < end) { final int t = random.nextInt(5); if (0 == t && i < length - 1) { // Make a surrogate pair // High surrogate chars[i++] = (char) nextInt(random, 0xd800, 0xdbff); // Low surrogate chars[i++] = (char) nextInt(random, 0xdc00, 0xdfff); } else if (t <= 1) { chars[i++] = (char) random.nextInt(0x80); } else if (2 == t) { chars[i++] = (char) nextInt(random, 0x80, 0x7ff); } else if (3 == t) { chars[i++] = (char) nextInt(random, 0x800, 0xd7ff); } else if (4 == t) { chars[i++] = (char) nextInt(random, 0xe000, 0xffff); } } } private static final String[] HTML_CHAR_ENTITIES = { "AElig", "Aacute", "Acirc", "Agrave", "Alpha", "AMP", "Aring", "Atilde", "Auml", "Beta", "COPY", "Ccedil", "Chi", "Dagger", "Delta", "ETH", "Eacute", "Ecirc", "Egrave", "Epsilon", "Eta", "Euml", "Gamma", "GT", "Iacute", "Icirc", "Igrave", "Iota", "Iuml", "Kappa", "Lambda", "LT", "Mu", "Ntilde", "Nu", "OElig", "Oacute", "Ocirc", "Ograve", "Omega", "Omicron", "Oslash", "Otilde", "Ouml", "Phi", "Pi", "Prime", "Psi", "QUOT", "REG", "Rho", "Scaron", "Sigma", "THORN", "Tau", "Theta", "Uacute", "Ucirc", "Ugrave", "Upsilon", "Uuml", "Xi", "Yacute", "Yuml", "Zeta", "aacute", "acirc", "acute", "aelig", "agrave", "alefsym", "alpha", "amp", "and", "ang", "apos", "aring", "asymp", "atilde", "auml", "bdquo", "beta", "brvbar", "bull", "cap", "ccedil", "cedil", "cent", "chi", "circ", "clubs", "cong", "copy", "crarr", "cup", "curren", "dArr", "dagger", "darr", "deg", "delta", "diams", "divide", "eacute", "ecirc", "egrave", "empty", "emsp", "ensp", "epsilon", "equiv", "eta", "eth", "euml", "euro", "exist", "fnof", "forall", "frac12", "frac14", "frac34", "frasl", "gamma", "ge", "gt", "hArr", "harr", "hearts", "hellip", "iacute", "icirc", "iexcl", "igrave", "image", "infin", "int", "iota", "iquest", "isin", "iuml", "kappa", "lArr", "lambda", "lang", "laquo", "larr", "lceil", "ldquo", "le", "lfloor", "lowast", "loz", "lrm", "lsaquo", "lsquo", "lt", "macr", "mdash", "micro", "middot", "minus", "mu", "nabla", "nbsp", "ndash", "ne", "ni", "not", "notin", "nsub", "ntilde", "nu", "oacute", "ocirc", "oelig", "ograve", "oline", "omega", "omicron", "oplus", "or", "ordf", "ordm", "oslash", "otilde", "otimes", "ouml", "para", "part", "permil", "perp", "phi", "pi", "piv", "plusmn", "pound", "prime", "prod", "prop", "psi", "quot", "rArr", "radic", "rang", "raquo", "rarr", "rceil", "rdquo", "real", "reg", "rfloor", "rho", "rlm", "rsaquo", "rsquo", "sbquo", "scaron", "sdot", "sect", "shy", "sigma", "sigmaf", "sim", "spades", "sub", "sube", "sum", "sup", "sup1", "sup2", "sup3", "supe", "szlig", "tau", "there4", "theta", "thetasym", "thinsp", "thorn", "tilde", "times", "trade", "uArr", "uacute", "uarr", "ucirc", "ugrave", "uml", "upsih", "upsilon", "uuml", "weierp", "xi", "yacute", "yen", "yuml", "zeta", "zwj", "zwnj" }; public static String randomHtmlishString(Random random, int numElements) { final int end = random.nextInt(numElements); if (end == 0) { // allow 0 length return ""; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < end; i++) { int val = random.nextInt(25); switch(val) { case 0: sb.append("<p>"); break; case 1: { sb.append("<"); sb.append(" ".substring(nextInt(random, 0, 4))); sb.append(randomSimpleString(random)); for (int j = 0 ; j < nextInt(random, 0, 10) ; ++j) { sb.append(' '); sb.append(randomSimpleString(random)); sb.append(" ".substring(nextInt(random, 0, 1))); sb.append('='); sb.append(" ".substring(nextInt(random, 0, 1))); sb.append("\"".substring(nextInt(random, 0, 1))); sb.append(randomSimpleString(random)); sb.append("\"".substring(nextInt(random, 0, 1))); } sb.append(" ".substring(nextInt(random, 0, 4))); sb.append("/".substring(nextInt(random, 0, 1))); sb.append(">".substring(nextInt(random, 0, 1))); break; } case 2: { sb.append("</"); sb.append(" ".substring(nextInt(random, 0, 4))); sb.append(randomSimpleString(random)); sb.append(" ".substring(nextInt(random, 0, 4))); sb.append(">".substring(nextInt(random, 0, 1))); break; } case 3: sb.append(">"); break; case 4: sb.append("</p>"); break; case 5: sb.append("<!--"); break; case 6: sb.append("<!--#"); break; case 7: sb.append("<script><!-- f('"); break; case 8: sb.append("</script>"); break; case 9: sb.append("<?"); break; case 10: sb.append("?>"); break; case 11: sb.append("\""); break; case 12: sb.append("\\\""); break; case 13: sb.append("'"); break; case 14: sb.append("\\'"); break; case 15: sb.append("-->"); break; case 16: { sb.append("&"); switch(nextInt(random, 0, 2)) { case 0: sb.append(randomSimpleString(random)); break; case 1: sb.append(HTML_CHAR_ENTITIES[random.nextInt(HTML_CHAR_ENTITIES.length)]); break; } sb.append(";".substring(nextInt(random, 0, 1))); break; } case 17: { sb.append("&#"); if (0 == nextInt(random, 0, 1)) { sb.append(nextInt(random, 0, Integer.MAX_VALUE - 1)); sb.append(";".substring(nextInt(random, 0, 1))); } break; } case 18: { sb.append("&#x"); if (0 == nextInt(random, 0, 1)) { sb.append(Integer.toString(nextInt(random, 0, Integer.MAX_VALUE - 1), 16)); sb.append(";".substring(nextInt(random, 0, 1))); } break; } case 19: sb.append(";"); break; case 20: sb.append(nextInt(random, 0, Integer.MAX_VALUE - 1)); break; - case 21: sb.append("\n"); - case 22: sb.append(" ".substring(nextInt(random, 0, 10))); + case 21: sb.append("\n"); break; + case 22: sb.append(" ".substring(nextInt(random, 0, 10))); break; default: sb.append(randomSimpleString(random)); } } return sb.toString(); } private static final int[] blockStarts = { 0x0000, 0x0080, 0x0100, 0x0180, 0x0250, 0x02B0, 0x0300, 0x0370, 0x0400, 0x0500, 0x0530, 0x0590, 0x0600, 0x0700, 0x0750, 0x0780, 0x07C0, 0x0800, 0x0900, 0x0980, 0x0A00, 0x0A80, 0x0B00, 0x0B80, 0x0C00, 0x0C80, 0x0D00, 0x0D80, 0x0E00, 0x0E80, 0x0F00, 0x1000, 0x10A0, 0x1100, 0x1200, 0x1380, 0x13A0, 0x1400, 0x1680, 0x16A0, 0x1700, 0x1720, 0x1740, 0x1760, 0x1780, 0x1800, 0x18B0, 0x1900, 0x1950, 0x1980, 0x19E0, 0x1A00, 0x1A20, 0x1B00, 0x1B80, 0x1C00, 0x1C50, 0x1CD0, 0x1D00, 0x1D80, 0x1DC0, 0x1E00, 0x1F00, 0x2000, 0x2070, 0x20A0, 0x20D0, 0x2100, 0x2150, 0x2190, 0x2200, 0x2300, 0x2400, 0x2440, 0x2460, 0x2500, 0x2580, 0x25A0, 0x2600, 0x2700, 0x27C0, 0x27F0, 0x2800, 0x2900, 0x2980, 0x2A00, 0x2B00, 0x2C00, 0x2C60, 0x2C80, 0x2D00, 0x2D30, 0x2D80, 0x2DE0, 0x2E00, 0x2E80, 0x2F00, 0x2FF0, 0x3000, 0x3040, 0x30A0, 0x3100, 0x3130, 0x3190, 0x31A0, 0x31C0, 0x31F0, 0x3200, 0x3300, 0x3400, 0x4DC0, 0x4E00, 0xA000, 0xA490, 0xA4D0, 0xA500, 0xA640, 0xA6A0, 0xA700, 0xA720, 0xA800, 0xA830, 0xA840, 0xA880, 0xA8E0, 0xA900, 0xA930, 0xA960, 0xA980, 0xAA00, 0xAA60, 0xAA80, 0xABC0, 0xAC00, 0xD7B0, 0xE000, 0xF900, 0xFB00, 0xFB50, 0xFE00, 0xFE10, 0xFE20, 0xFE30, 0xFE50, 0xFE70, 0xFF00, 0xFFF0, 0x10000, 0x10080, 0x10100, 0x10140, 0x10190, 0x101D0, 0x10280, 0x102A0, 0x10300, 0x10330, 0x10380, 0x103A0, 0x10400, 0x10450, 0x10480, 0x10800, 0x10840, 0x10900, 0x10920, 0x10A00, 0x10A60, 0x10B00, 0x10B40, 0x10B60, 0x10C00, 0x10E60, 0x11080, 0x12000, 0x12400, 0x13000, 0x1D000, 0x1D100, 0x1D200, 0x1D300, 0x1D360, 0x1D400, 0x1F000, 0x1F030, 0x1F100, 0x1F200, 0x20000, 0x2A700, 0x2F800, 0xE0000, 0xE0100, 0xF0000, 0x100000 }; private static final int[] blockEnds = { 0x007F, 0x00FF, 0x017F, 0x024F, 0x02AF, 0x02FF, 0x036F, 0x03FF, 0x04FF, 0x052F, 0x058F, 0x05FF, 0x06FF, 0x074F, 0x077F, 0x07BF, 0x07FF, 0x083F, 0x097F, 0x09FF, 0x0A7F, 0x0AFF, 0x0B7F, 0x0BFF, 0x0C7F, 0x0CFF, 0x0D7F, 0x0DFF, 0x0E7F, 0x0EFF, 0x0FFF, 0x109F, 0x10FF, 0x11FF, 0x137F, 0x139F, 0x13FF, 0x167F, 0x169F, 0x16FF, 0x171F, 0x173F, 0x175F, 0x177F, 0x17FF, 0x18AF, 0x18FF, 0x194F, 0x197F, 0x19DF, 0x19FF, 0x1A1F, 0x1AAF, 0x1B7F, 0x1BBF, 0x1C4F, 0x1C7F, 0x1CFF, 0x1D7F, 0x1DBF, 0x1DFF, 0x1EFF, 0x1FFF, 0x206F, 0x209F, 0x20CF, 0x20FF, 0x214F, 0x218F, 0x21FF, 0x22FF, 0x23FF, 0x243F, 0x245F, 0x24FF, 0x257F, 0x259F, 0x25FF, 0x26FF, 0x27BF, 0x27EF, 0x27FF, 0x28FF, 0x297F, 0x29FF, 0x2AFF, 0x2BFF, 0x2C5F, 0x2C7F, 0x2CFF, 0x2D2F, 0x2D7F, 0x2DDF, 0x2DFF, 0x2E7F, 0x2EFF, 0x2FDF, 0x2FFF, 0x303F, 0x309F, 0x30FF, 0x312F, 0x318F, 0x319F, 0x31BF, 0x31EF, 0x31FF, 0x32FF, 0x33FF, 0x4DBF, 0x4DFF, 0x9FFF, 0xA48F, 0xA4CF, 0xA4FF, 0xA63F, 0xA69F, 0xA6FF, 0xA71F, 0xA7FF, 0xA82F, 0xA83F, 0xA87F, 0xA8DF, 0xA8FF, 0xA92F, 0xA95F, 0xA97F, 0xA9DF, 0xAA5F, 0xAA7F, 0xAADF, 0xABFF, 0xD7AF, 0xD7FF, 0xF8FF, 0xFAFF, 0xFB4F, 0xFDFF, 0xFE0F, 0xFE1F, 0xFE2F, 0xFE4F, 0xFE6F, 0xFEFF, 0xFFEF, 0xFFFF, 0x1007F, 0x100FF, 0x1013F, 0x1018F, 0x101CF, 0x101FF, 0x1029F, 0x102DF, 0x1032F, 0x1034F, 0x1039F, 0x103DF, 0x1044F, 0x1047F, 0x104AF, 0x1083F, 0x1085F, 0x1091F, 0x1093F, 0x10A5F, 0x10A7F, 0x10B3F, 0x10B5F, 0x10B7F, 0x10C4F, 0x10E7F, 0x110CF, 0x123FF, 0x1247F, 0x1342F, 0x1D0FF, 0x1D1FF, 0x1D24F, 0x1D35F, 0x1D37F, 0x1D7FF, 0x1F02F, 0x1F09F, 0x1F1FF, 0x1F2FF, 0x2A6DF, 0x2B73F, 0x2FA1F, 0xE007F, 0xE01EF, 0xFFFFF, 0x10FFFF }; /** Returns random string of length between 0-20 codepoints, all codepoints within the same unicode block. */ public static String randomRealisticUnicodeString(Random r) { return randomRealisticUnicodeString(r, 20); } /** Returns random string of length up to maxLength codepoints , all codepoints within the same unicode block. */ public static String randomRealisticUnicodeString(Random r, int maxLength) { return randomRealisticUnicodeString(r, 0, 20); } /** Returns random string of length between min and max codepoints, all codepoints within the same unicode block. */ public static String randomRealisticUnicodeString(Random r, int minLength, int maxLength) { final int end = minLength + r.nextInt(maxLength); final int block = r.nextInt(blockStarts.length); StringBuilder sb = new StringBuilder(); for (int i = 0; i < end; i++) sb.appendCodePoint(nextInt(r, blockStarts[block], blockEnds[block])); return sb.toString(); } /** Returns random string, with a given UTF-8 byte length*/ public static String randomFixedByteLengthUnicodeString(Random r, int length) { final char[] buffer = new char[length*3]; int bytes = length; int i = 0; for (; i < buffer.length && bytes != 0; i++) { int t; if (bytes >= 4) { t = r.nextInt(5); } else if (bytes >= 3) { t = r.nextInt(4); } else if (bytes >= 2) { t = r.nextInt(2); } else { t = 0; } if (t == 0) { buffer[i] = (char) r.nextInt(0x80); bytes--; } else if (1 == t) { buffer[i] = (char) nextInt(r, 0x80, 0x7ff); bytes -= 2; } else if (2 == t) { buffer[i] = (char) nextInt(r, 0x800, 0xd7ff); bytes -= 3; } else if (3 == t) { buffer[i] = (char) nextInt(r, 0xe000, 0xffff); bytes -= 3; } else if (4 == t) { // Make a surrogate pair // High surrogate buffer[i++] = (char) nextInt(r, 0xd800, 0xdbff); // Low surrogate buffer[i] = (char) nextInt(r, 0xdc00, 0xdfff); bytes -= 4; } } return new String(buffer, 0, i); } /** Return a Codec that can read any of the * default codecs and formats, but always writes in the specified * format. */ public static Codec alwaysPostingsFormat(final PostingsFormat format) { return new Lucene40Codec() { @Override public PostingsFormat getPostingsFormatForField(String field) { return format; } }; } // TODO: generalize all 'test-checks-for-crazy-codecs' to // annotations (LUCENE-3489) public static String getPostingsFormat(String field) { PostingsFormat p = Codec.getDefault().postingsFormat(); if (p instanceof PerFieldPostingsFormat) { return ((PerFieldPostingsFormat)p).getPostingsFormatForField(field).getName(); } else { return p.getName(); } } public static boolean anyFilesExceptWriteLock(Directory dir) throws IOException { String[] files = dir.listAll(); if (files.length > 1 || (files.length == 1 && !files[0].equals("write.lock"))) { return true; } else { return false; } } /** just tries to configure things to keep the open file * count lowish */ public static void reduceOpenFiles(IndexWriter w) { // keep number of open files lowish MergePolicy mp = w.getConfig().getMergePolicy(); if (mp instanceof LogMergePolicy) { LogMergePolicy lmp = (LogMergePolicy) mp; lmp.setMergeFactor(Math.min(5, lmp.getMergeFactor())); } else if (mp instanceof TieredMergePolicy) { TieredMergePolicy tmp = (TieredMergePolicy) mp; tmp.setMaxMergeAtOnce(Math.min(5, tmp.getMaxMergeAtOnce())); tmp.setSegmentsPerTier(Math.min(5, tmp.getSegmentsPerTier())); } MergeScheduler ms = w.getConfig().getMergeScheduler(); if (ms instanceof ConcurrentMergeScheduler) { ((ConcurrentMergeScheduler) ms).setMaxThreadCount(2); ((ConcurrentMergeScheduler) ms).setMaxMergeCount(3); } } /** Checks some basic behaviour of an AttributeImpl * @param reflectedValues contains a map with "AttributeClass#key" as values */ public static <T> void assertAttributeReflection(final AttributeImpl att, Map<String,T> reflectedValues) { final Map<String,Object> map = new HashMap<String,Object>(); att.reflectWith(new AttributeReflector() { public void reflect(Class<? extends Attribute> attClass, String key, Object value) { map.put(attClass.getName() + '#' + key, value); } }); Assert.assertEquals("Reflection does not produce same map", reflectedValues, map); } public static void keepFullyDeletedSegments(IndexWriter w) { try { // Carefully invoke what is a package-private (test // only, internal) method on IndexWriter: Method m = IndexWriter.class.getDeclaredMethod("keepFullyDeletedSegments"); m.setAccessible(true); m.invoke(w); } catch (Exception e) { // Should not happen? throw new RuntimeException(e); } } /** Adds field info for a Document. */ public static void add(Document doc, FieldInfos fieldInfos) { for (IndexableField field : doc) { fieldInfos.addOrUpdate(field.name(), field.fieldType()); } } /** * insecure, fast version of File.createTempFile * uses Random instead of SecureRandom. */ public static File createTempFile(String prefix, String suffix, File directory) throws IOException { // Force a prefix null check first if (prefix.length() < 3) { throw new IllegalArgumentException("prefix must be 3"); } String newSuffix = suffix == null ? ".tmp" : suffix; File result; do { result = genTempFile(prefix, newSuffix, directory); } while (!result.createNewFile()); return result; } /* Temp file counter */ private static int counter = 0; /* identify for differnt VM processes */ private static int counterBase = 0; private static class TempFileLocker {}; private static TempFileLocker tempFileLocker = new TempFileLocker(); private static File genTempFile(String prefix, String suffix, File directory) { int identify = 0; synchronized (tempFileLocker) { if (counter == 0) { int newInt = new Random().nextInt(); counter = ((newInt / 65535) & 0xFFFF) + 0x2710; counterBase = counter; } identify = counter++; } StringBuilder newName = new StringBuilder(); newName.append(prefix); newName.append(counterBase); newName.append(identify); newName.append(suffix); return new File(directory, newName.toString()); } public static void assertEquals(TopDocs expected, TopDocs actual) { Assert.assertEquals("wrong total hits", expected.totalHits, actual.totalHits); Assert.assertEquals("wrong maxScore", expected.getMaxScore(), actual.getMaxScore(), 0.0); Assert.assertEquals("wrong hit count", expected.scoreDocs.length, actual.scoreDocs.length); for(int hitIDX=0;hitIDX<expected.scoreDocs.length;hitIDX++) { final ScoreDoc expectedSD = expected.scoreDocs[hitIDX]; final ScoreDoc actualSD = actual.scoreDocs[hitIDX]; Assert.assertEquals("wrong hit docID", expectedSD.doc, actualSD.doc); Assert.assertEquals("wrong hit score", expectedSD.score, actualSD.score, 0.0); if (expectedSD instanceof FieldDoc) { Assert.assertTrue(actualSD instanceof FieldDoc); Assert.assertArrayEquals("wrong sort field values", ((FieldDoc) expectedSD).fields, ((FieldDoc) actualSD).fields); } else { Assert.assertFalse(actualSD instanceof FieldDoc); } } } // NOTE: this is likely buggy, and cannot clone fields // with tokenStreamValues, etc. Use at your own risk!! // TODO: is there a pre-existing way to do this!!! public static Document cloneDocument(Document doc1) { final Document doc2 = new Document(); for(IndexableField f : doc1) { Field field1 = (Field) f; Field field2 = new Field(field1.name(), field1.stringValue(), field1.fieldType()); doc2.add(field2); } return doc2; } // Returns a DocsEnum, but randomly sometimes uses a // DocsAndFreqsEnum, DocsAndPositionsEnum. Returns null // if field/term doesn't exist: public static DocsEnum docs(Random random, IndexReader r, String field, BytesRef term, Bits liveDocs, DocsEnum reuse, boolean needsFreqs) throws IOException { final Terms terms = MultiFields.getTerms(r, field); if (terms == null) { return null; } final TermsEnum termsEnum = terms.iterator(null); if (!termsEnum.seekExact(term, random.nextBoolean())) { return null; } if (random.nextBoolean()) { if (random.nextBoolean()) { // TODO: cast re-use to D&PE if we can...? DocsAndPositionsEnum docsAndPositions = termsEnum.docsAndPositions(liveDocs, null, true); if (docsAndPositions == null) { docsAndPositions = termsEnum.docsAndPositions(liveDocs, null, false); } if (docsAndPositions != null) { return docsAndPositions; } } final DocsEnum docsAndFreqs = termsEnum.docs(liveDocs, reuse, true); if (docsAndFreqs != null) { return docsAndFreqs; } } return termsEnum.docs(liveDocs, reuse, needsFreqs); } // Returns a DocsEnum from a positioned TermsEnum, but // randomly sometimes uses a DocsAndFreqsEnum, DocsAndPositionsEnum. public static DocsEnum docs(Random random, TermsEnum termsEnum, Bits liveDocs, DocsEnum reuse, boolean needsFreqs) throws IOException { if (random.nextBoolean()) { if (random.nextBoolean()) { // TODO: cast re-use to D&PE if we can...? DocsAndPositionsEnum docsAndPositions = termsEnum.docsAndPositions(liveDocs, null, true); if (docsAndPositions == null) { docsAndPositions = termsEnum.docsAndPositions(liveDocs, null, false); } if (docsAndPositions != null) { return docsAndPositions; } } final DocsEnum docsAndFreqs = termsEnum.docs(liveDocs, null, true); if (docsAndFreqs != null) { return docsAndFreqs; } } return termsEnum.docs(liveDocs, null, needsFreqs); } }
true
true
public static String randomHtmlishString(Random random, int numElements) { final int end = random.nextInt(numElements); if (end == 0) { // allow 0 length return ""; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < end; i++) { int val = random.nextInt(25); switch(val) { case 0: sb.append("<p>"); break; case 1: { sb.append("<"); sb.append(" ".substring(nextInt(random, 0, 4))); sb.append(randomSimpleString(random)); for (int j = 0 ; j < nextInt(random, 0, 10) ; ++j) { sb.append(' '); sb.append(randomSimpleString(random)); sb.append(" ".substring(nextInt(random, 0, 1))); sb.append('='); sb.append(" ".substring(nextInt(random, 0, 1))); sb.append("\"".substring(nextInt(random, 0, 1))); sb.append(randomSimpleString(random)); sb.append("\"".substring(nextInt(random, 0, 1))); } sb.append(" ".substring(nextInt(random, 0, 4))); sb.append("/".substring(nextInt(random, 0, 1))); sb.append(">".substring(nextInt(random, 0, 1))); break; } case 2: { sb.append("</"); sb.append(" ".substring(nextInt(random, 0, 4))); sb.append(randomSimpleString(random)); sb.append(" ".substring(nextInt(random, 0, 4))); sb.append(">".substring(nextInt(random, 0, 1))); break; } case 3: sb.append(">"); break; case 4: sb.append("</p>"); break; case 5: sb.append("<!--"); break; case 6: sb.append("<!--#"); break; case 7: sb.append("<script><!-- f('"); break; case 8: sb.append("</script>"); break; case 9: sb.append("<?"); break; case 10: sb.append("?>"); break; case 11: sb.append("\""); break; case 12: sb.append("\\\""); break; case 13: sb.append("'"); break; case 14: sb.append("\\'"); break; case 15: sb.append("-->"); break; case 16: { sb.append("&"); switch(nextInt(random, 0, 2)) { case 0: sb.append(randomSimpleString(random)); break; case 1: sb.append(HTML_CHAR_ENTITIES[random.nextInt(HTML_CHAR_ENTITIES.length)]); break; } sb.append(";".substring(nextInt(random, 0, 1))); break; } case 17: { sb.append("&#"); if (0 == nextInt(random, 0, 1)) { sb.append(nextInt(random, 0, Integer.MAX_VALUE - 1)); sb.append(";".substring(nextInt(random, 0, 1))); } break; } case 18: { sb.append("&#x"); if (0 == nextInt(random, 0, 1)) { sb.append(Integer.toString(nextInt(random, 0, Integer.MAX_VALUE - 1), 16)); sb.append(";".substring(nextInt(random, 0, 1))); } break; } case 19: sb.append(";"); break; case 20: sb.append(nextInt(random, 0, Integer.MAX_VALUE - 1)); break; case 21: sb.append("\n"); case 22: sb.append(" ".substring(nextInt(random, 0, 10))); default: sb.append(randomSimpleString(random)); } } return sb.toString(); }
public static String randomHtmlishString(Random random, int numElements) { final int end = random.nextInt(numElements); if (end == 0) { // allow 0 length return ""; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < end; i++) { int val = random.nextInt(25); switch(val) { case 0: sb.append("<p>"); break; case 1: { sb.append("<"); sb.append(" ".substring(nextInt(random, 0, 4))); sb.append(randomSimpleString(random)); for (int j = 0 ; j < nextInt(random, 0, 10) ; ++j) { sb.append(' '); sb.append(randomSimpleString(random)); sb.append(" ".substring(nextInt(random, 0, 1))); sb.append('='); sb.append(" ".substring(nextInt(random, 0, 1))); sb.append("\"".substring(nextInt(random, 0, 1))); sb.append(randomSimpleString(random)); sb.append("\"".substring(nextInt(random, 0, 1))); } sb.append(" ".substring(nextInt(random, 0, 4))); sb.append("/".substring(nextInt(random, 0, 1))); sb.append(">".substring(nextInt(random, 0, 1))); break; } case 2: { sb.append("</"); sb.append(" ".substring(nextInt(random, 0, 4))); sb.append(randomSimpleString(random)); sb.append(" ".substring(nextInt(random, 0, 4))); sb.append(">".substring(nextInt(random, 0, 1))); break; } case 3: sb.append(">"); break; case 4: sb.append("</p>"); break; case 5: sb.append("<!--"); break; case 6: sb.append("<!--#"); break; case 7: sb.append("<script><!-- f('"); break; case 8: sb.append("</script>"); break; case 9: sb.append("<?"); break; case 10: sb.append("?>"); break; case 11: sb.append("\""); break; case 12: sb.append("\\\""); break; case 13: sb.append("'"); break; case 14: sb.append("\\'"); break; case 15: sb.append("-->"); break; case 16: { sb.append("&"); switch(nextInt(random, 0, 2)) { case 0: sb.append(randomSimpleString(random)); break; case 1: sb.append(HTML_CHAR_ENTITIES[random.nextInt(HTML_CHAR_ENTITIES.length)]); break; } sb.append(";".substring(nextInt(random, 0, 1))); break; } case 17: { sb.append("&#"); if (0 == nextInt(random, 0, 1)) { sb.append(nextInt(random, 0, Integer.MAX_VALUE - 1)); sb.append(";".substring(nextInt(random, 0, 1))); } break; } case 18: { sb.append("&#x"); if (0 == nextInt(random, 0, 1)) { sb.append(Integer.toString(nextInt(random, 0, Integer.MAX_VALUE - 1), 16)); sb.append(";".substring(nextInt(random, 0, 1))); } break; } case 19: sb.append(";"); break; case 20: sb.append(nextInt(random, 0, Integer.MAX_VALUE - 1)); break; case 21: sb.append("\n"); break; case 22: sb.append(" ".substring(nextInt(random, 0, 10))); break; default: sb.append(randomSimpleString(random)); } } return sb.toString(); }
diff --git a/DistributedGroupMembership/src/ConnectionHandler.java b/DistributedGroupMembership/src/ConnectionHandler.java index b1de6b8..e50ed6f 100644 --- a/DistributedGroupMembership/src/ConnectionHandler.java +++ b/DistributedGroupMembership/src/ConnectionHandler.java @@ -1,127 +1,127 @@ import java.io.IOException; import java.io.StringReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; import java.util.ArrayList; import javax.xml.bind.JAXBException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.InputSource; import org.xml.sax.SAXException; public class ConnectionHandler implements Runnable { private boolean shouldRun = true; // private int port = 61233; private Config conf; private int bufferSize = 2048; private MembershipList list; public ConnectionHandler(MembershipList list, Config conf) { this.list = list; this.conf = conf; } public ConnectionHandler(MembershipList list, Config conf, int bufferSize) { this.list = list; this.conf = conf; this.bufferSize = bufferSize; } public void kill() { this.shouldRun = false; } public void run() { int port = Integer.parseInt(conf.valueFor("contactPort"));/*0; try { port = Integer.parseInt(conf.valueFor("contactPort")); } catch (IOException e) { System.out.println(e); return; }*/ DatagramSocket rcvSocket = null; try { rcvSocket = new DatagramSocket(port); } catch (SocketException e1) { System.out.println("Can't listen on port "+port); } byte[] buffer = new byte[bufferSize]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); System.out.println("Waiting for UDP packets: Started"); while(shouldRun) { try { rcvSocket.receive(packet); } catch (IOException e) { e.printStackTrace(); } String msg = new String(buffer, 0, packet.getLength()); System.out.println("\nMessage from: " + packet.getAddress().getHostAddress()); //+ msg); InputSource source = new InputSource(new StringReader(msg)); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db; Element a = null; try { db = dbf.newDocumentBuilder(); Document doc = db.parse(source); a = doc.getDocumentElement(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // Go this way, when the node receives a join-request from another node (maybe not necessary) if(a.getNodeName() == "join") { // Go this way, when the node receives a leave-request from another node - String newMember = packet.getAddress().toString(); + String newMember = packet.getAddress().getHostAddress(); System.out.println(newMember + " is joining the cluster."); list.get().add(new MembershipEntry(newMember)); } else if(a.getNodeName() == "leave") { // Go this way, when the node gets a membershiplist from another node } else if(a.getNodeName() == "membershipList") { ArrayList<MembershipEntry> receivedMemList = new ArrayList<MembershipEntry>(); try { receivedMemList = DstrMarshaller.unmarshallXML(msg); } catch (JAXBException e) { e.printStackTrace(); } MembershipController.updateMembershipList(list, receivedMemList, Integer.parseInt(conf.valueFor("TFail"))/1000); /* for(int i=0;i<receivedMemList.size();i++) { System.out.println(receivedMemList.get(i).getIPAddress()); } */ } } System.out.println("[" + this.getClass().toString() + "] is dying."); } }
true
true
public void run() { int port = Integer.parseInt(conf.valueFor("contactPort"));/*0; try { port = Integer.parseInt(conf.valueFor("contactPort")); } catch (IOException e) { System.out.println(e); return; }*/ DatagramSocket rcvSocket = null; try { rcvSocket = new DatagramSocket(port); } catch (SocketException e1) { System.out.println("Can't listen on port "+port); } byte[] buffer = new byte[bufferSize]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); System.out.println("Waiting for UDP packets: Started"); while(shouldRun) { try { rcvSocket.receive(packet); } catch (IOException e) { e.printStackTrace(); } String msg = new String(buffer, 0, packet.getLength()); System.out.println("\nMessage from: " + packet.getAddress().getHostAddress()); //+ msg); InputSource source = new InputSource(new StringReader(msg)); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db; Element a = null; try { db = dbf.newDocumentBuilder(); Document doc = db.parse(source); a = doc.getDocumentElement(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // Go this way, when the node receives a join-request from another node (maybe not necessary) if(a.getNodeName() == "join") { // Go this way, when the node receives a leave-request from another node String newMember = packet.getAddress().toString(); System.out.println(newMember + " is joining the cluster."); list.get().add(new MembershipEntry(newMember)); } else if(a.getNodeName() == "leave") { // Go this way, when the node gets a membershiplist from another node } else if(a.getNodeName() == "membershipList") { ArrayList<MembershipEntry> receivedMemList = new ArrayList<MembershipEntry>(); try { receivedMemList = DstrMarshaller.unmarshallXML(msg); } catch (JAXBException e) { e.printStackTrace(); } MembershipController.updateMembershipList(list, receivedMemList, Integer.parseInt(conf.valueFor("TFail"))/1000); /* for(int i=0;i<receivedMemList.size();i++) { System.out.println(receivedMemList.get(i).getIPAddress()); } */ } } System.out.println("[" + this.getClass().toString() + "] is dying."); }
public void run() { int port = Integer.parseInt(conf.valueFor("contactPort"));/*0; try { port = Integer.parseInt(conf.valueFor("contactPort")); } catch (IOException e) { System.out.println(e); return; }*/ DatagramSocket rcvSocket = null; try { rcvSocket = new DatagramSocket(port); } catch (SocketException e1) { System.out.println("Can't listen on port "+port); } byte[] buffer = new byte[bufferSize]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); System.out.println("Waiting for UDP packets: Started"); while(shouldRun) { try { rcvSocket.receive(packet); } catch (IOException e) { e.printStackTrace(); } String msg = new String(buffer, 0, packet.getLength()); System.out.println("\nMessage from: " + packet.getAddress().getHostAddress()); //+ msg); InputSource source = new InputSource(new StringReader(msg)); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db; Element a = null; try { db = dbf.newDocumentBuilder(); Document doc = db.parse(source); a = doc.getDocumentElement(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // Go this way, when the node receives a join-request from another node (maybe not necessary) if(a.getNodeName() == "join") { // Go this way, when the node receives a leave-request from another node String newMember = packet.getAddress().getHostAddress(); System.out.println(newMember + " is joining the cluster."); list.get().add(new MembershipEntry(newMember)); } else if(a.getNodeName() == "leave") { // Go this way, when the node gets a membershiplist from another node } else if(a.getNodeName() == "membershipList") { ArrayList<MembershipEntry> receivedMemList = new ArrayList<MembershipEntry>(); try { receivedMemList = DstrMarshaller.unmarshallXML(msg); } catch (JAXBException e) { e.printStackTrace(); } MembershipController.updateMembershipList(list, receivedMemList, Integer.parseInt(conf.valueFor("TFail"))/1000); /* for(int i=0;i<receivedMemList.size();i++) { System.out.println(receivedMemList.get(i).getIPAddress()); } */ } } System.out.println("[" + this.getClass().toString() + "] is dying."); }
diff --git a/src/org/intellij/erlang/ErlangCompletionContributor.java b/src/org/intellij/erlang/ErlangCompletionContributor.java index 27350a55..1628c7b1 100644 --- a/src/org/intellij/erlang/ErlangCompletionContributor.java +++ b/src/org/intellij/erlang/ErlangCompletionContributor.java @@ -1,157 +1,160 @@ /* * Copyright 2012 Sergey Ignatov * * 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.intellij.erlang; import com.intellij.codeInsight.completion.*; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFileFactory; import com.intellij.psi.impl.source.tree.TreeUtil; import com.intellij.psi.search.FilenameIndex; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.Function; import com.intellij.util.ProcessingContext; import com.intellij.util.containers.ContainerUtil; import org.intellij.erlang.parser.ErlangLexer; import org.intellij.erlang.parser.GeneratedParserUtilBase; import org.intellij.erlang.psi.*; import org.intellij.erlang.psi.impl.ErlangFileImpl; import org.intellij.erlang.psi.impl.ErlangPsiImplUtil; import org.jetbrains.annotations.NotNull; import java.util.Collection; import java.util.List; import static com.intellij.patterns.PlatformPatterns.psiElement; import static com.intellij.patterns.StandardPatterns.instanceOf; /** * @author ignatov */ public class ErlangCompletionContributor extends CompletionContributor { @Override public void beforeCompletion(@NotNull CompletionInitializationContext context) { PsiElement elementAt = context.getFile().findElementAt(context.getStartOffset()); PsiElement parent = elementAt == null ? null : elementAt.getParent(); ErlangExport export = PsiTreeUtil.getPrevSiblingOfType(parent, ErlangExport.class); ErlangRecordTuple recordTuple = PsiTreeUtil.getPrevSiblingOfType(parent, ErlangRecordTuple.class); if (parent instanceof ErlangExport || export != null || parent instanceof ErlangRecordTuple || recordTuple != null) { context.setDummyIdentifier("a"); } } public ErlangCompletionContributor() { extend(CompletionType.BASIC, psiElement().inFile(instanceOf(ErlangFileImpl.class)), new CompletionProvider<CompletionParameters>() { @Override protected void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) { // add completion for records on #<caret> PsiElement position = parameters.getPosition(); PsiElement parent = position.getParent().getParent(); PsiElement originalPosition = parameters.getOriginalPosition(); PsiElement originalParent = originalPosition != null ? originalPosition.getParent() : null; if (originalParent instanceof ErlangRecordExpression) { result.addAllElements(ErlangPsiImplUtil.getRecordLookupElements(position.getContainingFile())); } + else if (originalParent instanceof ErlangExportFunctions) { + result.addAllElements(ErlangPsiImplUtil.getFunctionLookupElements(position.getContainingFile(), true, null)); + } else { ErlangColonQualifiedExpression colonQualified = PsiTreeUtil.getParentOfType(position, ErlangColonQualifiedExpression.class); if (colonQualified != null) { result.addAllElements(ErlangPsiImplUtil.getFunctionLookupElements(position.getContainingFile(), false, colonQualified)); } else if (originalParent instanceof ErlangRecordFields || parent instanceof ErlangRecordField || parent instanceof ErlangRecordFields) { List<ErlangTypedExpr> fields = ErlangPsiImplUtil.getRecordFields(parent); result.addAllElements(ContainerUtil.map(fields, new Function<ErlangTypedExpr, LookupElement>() { @Override public LookupElement fun(ErlangTypedExpr a) { return LookupElementBuilder.create(a.getName()) .setIcon(ErlangIcons.FIELD) .setInsertHandler(new SingleCharInsertHandler('=')); } })); return; } else if (PsiTreeUtil.getParentOfType(position, ErlangExport.class) == null) { for (String keyword : suggestKeywords(position)) { result.addElement(LookupElementBuilder.create(keyword).setBold()); } if (PsiTreeUtil.getParentOfType(position, ErlangClauseBody.class) != null) { suggestModules(result, position); } } if (colonQualified == null && parent instanceof ErlangExpression && ErlangPsiImplUtil.inFunction(position)) { result.addAllElements(ErlangPsiImplUtil.getFunctionLookupElements(position.getContainingFile(), false, null)); } } } }); } private static void suggestModules(CompletionResultSet result, PsiElement position) { Project project = position.getProject(); Collection<VirtualFile> files = FilenameIndex.getAllFilesByExt(project, "erl", GlobalSearchScope.projectScope(project)); List<VirtualFile> standardModules = ContainerUtil.filter(FilenameIndex.getAllFilesByExt(project, "erl", GlobalSearchScope.allScope(project)), new Condition<VirtualFile>() { @Override public boolean value(VirtualFile virtualFile) { String canonicalPath = virtualFile.getCanonicalPath(); canonicalPath = FileUtil.toSystemIndependentName(canonicalPath != null ? canonicalPath : ""); String kernelRegExp = ".*/lib/kernel[\\-\\d\\.]+/src/.*\\.erl"; String stdlibRegExp = ".*/lib/stdlib[\\-\\d\\.]+/src/.*\\.erl"; return canonicalPath.matches(kernelRegExp) || canonicalPath.matches(stdlibRegExp); } });// todo: module with libs scope //noinspection unchecked for (VirtualFile file : ContainerUtil.concat(files, standardModules)) { if (file.getFileType() == ErlangFileType.INSTANCE) { result.addElement(LookupElementBuilder.create(file.getNameWithoutExtension()). setIcon(ErlangIcons.MODULE). setInsertHandler(new SingleCharInsertHandler(':'))); } } } private static Collection<String> suggestKeywords(PsiElement position) { TextRange posRange = position.getTextRange(); ErlangFile posFile = (ErlangFile) position.getContainingFile(); final TextRange range = new TextRange(0, posRange.getStartOffset()); final String text = range.isEmpty() ? CompletionInitializationContext.DUMMY_IDENTIFIER : range.substring(posFile.getText()); PsiFile file = PsiFileFactory.getInstance(posFile.getProject()).createFileFromText("a.erl", ErlangLanguage.INSTANCE, text, true, false); int completionOffset = posRange.getStartOffset() - range.getStartOffset(); GeneratedParserUtilBase.CompletionState state = new GeneratedParserUtilBase.CompletionState(completionOffset) { @Override public String convertItem(Object o) { if (o instanceof IElementType && ErlangLexer.KEYWORDS.contains((IElementType) o)) return o.toString(); return o instanceof String ? (String) o : null; } }; file.putUserData(GeneratedParserUtilBase.COMPLETION_STATE_KEY, state); TreeUtil.ensureParsed(file.getNode()); return state.items; } }
true
true
public ErlangCompletionContributor() { extend(CompletionType.BASIC, psiElement().inFile(instanceOf(ErlangFileImpl.class)), new CompletionProvider<CompletionParameters>() { @Override protected void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) { // add completion for records on #<caret> PsiElement position = parameters.getPosition(); PsiElement parent = position.getParent().getParent(); PsiElement originalPosition = parameters.getOriginalPosition(); PsiElement originalParent = originalPosition != null ? originalPosition.getParent() : null; if (originalParent instanceof ErlangRecordExpression) { result.addAllElements(ErlangPsiImplUtil.getRecordLookupElements(position.getContainingFile())); } else { ErlangColonQualifiedExpression colonQualified = PsiTreeUtil.getParentOfType(position, ErlangColonQualifiedExpression.class); if (colonQualified != null) { result.addAllElements(ErlangPsiImplUtil.getFunctionLookupElements(position.getContainingFile(), false, colonQualified)); } else if (originalParent instanceof ErlangRecordFields || parent instanceof ErlangRecordField || parent instanceof ErlangRecordFields) { List<ErlangTypedExpr> fields = ErlangPsiImplUtil.getRecordFields(parent); result.addAllElements(ContainerUtil.map(fields, new Function<ErlangTypedExpr, LookupElement>() { @Override public LookupElement fun(ErlangTypedExpr a) { return LookupElementBuilder.create(a.getName()) .setIcon(ErlangIcons.FIELD) .setInsertHandler(new SingleCharInsertHandler('=')); } })); return; } else if (PsiTreeUtil.getParentOfType(position, ErlangExport.class) == null) { for (String keyword : suggestKeywords(position)) { result.addElement(LookupElementBuilder.create(keyword).setBold()); } if (PsiTreeUtil.getParentOfType(position, ErlangClauseBody.class) != null) { suggestModules(result, position); } } if (colonQualified == null && parent instanceof ErlangExpression && ErlangPsiImplUtil.inFunction(position)) { result.addAllElements(ErlangPsiImplUtil.getFunctionLookupElements(position.getContainingFile(), false, null)); } } } }); }
public ErlangCompletionContributor() { extend(CompletionType.BASIC, psiElement().inFile(instanceOf(ErlangFileImpl.class)), new CompletionProvider<CompletionParameters>() { @Override protected void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) { // add completion for records on #<caret> PsiElement position = parameters.getPosition(); PsiElement parent = position.getParent().getParent(); PsiElement originalPosition = parameters.getOriginalPosition(); PsiElement originalParent = originalPosition != null ? originalPosition.getParent() : null; if (originalParent instanceof ErlangRecordExpression) { result.addAllElements(ErlangPsiImplUtil.getRecordLookupElements(position.getContainingFile())); } else if (originalParent instanceof ErlangExportFunctions) { result.addAllElements(ErlangPsiImplUtil.getFunctionLookupElements(position.getContainingFile(), true, null)); } else { ErlangColonQualifiedExpression colonQualified = PsiTreeUtil.getParentOfType(position, ErlangColonQualifiedExpression.class); if (colonQualified != null) { result.addAllElements(ErlangPsiImplUtil.getFunctionLookupElements(position.getContainingFile(), false, colonQualified)); } else if (originalParent instanceof ErlangRecordFields || parent instanceof ErlangRecordField || parent instanceof ErlangRecordFields) { List<ErlangTypedExpr> fields = ErlangPsiImplUtil.getRecordFields(parent); result.addAllElements(ContainerUtil.map(fields, new Function<ErlangTypedExpr, LookupElement>() { @Override public LookupElement fun(ErlangTypedExpr a) { return LookupElementBuilder.create(a.getName()) .setIcon(ErlangIcons.FIELD) .setInsertHandler(new SingleCharInsertHandler('=')); } })); return; } else if (PsiTreeUtil.getParentOfType(position, ErlangExport.class) == null) { for (String keyword : suggestKeywords(position)) { result.addElement(LookupElementBuilder.create(keyword).setBold()); } if (PsiTreeUtil.getParentOfType(position, ErlangClauseBody.class) != null) { suggestModules(result, position); } } if (colonQualified == null && parent instanceof ErlangExpression && ErlangPsiImplUtil.inFunction(position)) { result.addAllElements(ErlangPsiImplUtil.getFunctionLookupElements(position.getContainingFile(), false, null)); } } } }); }
diff --git a/src/uk/me/parabola/mkgmap/main/Main.java b/src/uk/me/parabola/mkgmap/main/Main.java index bfaf53ed..cba28192 100644 --- a/src/uk/me/parabola/mkgmap/main/Main.java +++ b/src/uk/me/parabola/mkgmap/main/Main.java @@ -1,370 +1,371 @@ /* * Copyright (C) 2007 Steve Ratcliffe * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * * Author: Steve Ratcliffe * Create date: 24-Sep-2007 */ package uk.me.parabola.mkgmap.main; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.ExecutionException; import uk.me.parabola.imgfmt.ExitException; import uk.me.parabola.log.Logger; import uk.me.parabola.mkgmap.ArgumentProcessor; import uk.me.parabola.mkgmap.CommandArgs; import uk.me.parabola.mkgmap.CommandArgsReader; import uk.me.parabola.mkgmap.Version; import uk.me.parabola.mkgmap.combiners.Combiner; import uk.me.parabola.mkgmap.combiners.FileInfo; import uk.me.parabola.mkgmap.combiners.GmapsuppBuilder; import uk.me.parabola.mkgmap.combiners.TdbBuilder; import uk.me.parabola.mkgmap.osmstyle.StyleFileLoader; import uk.me.parabola.mkgmap.osmstyle.StyleImpl; import uk.me.parabola.mkgmap.osmstyle.eval.SyntaxException; import uk.me.parabola.mkgmap.reader.osm.Style; import uk.me.parabola.mkgmap.reader.osm.StyleInfo; import uk.me.parabola.mkgmap.reader.overview.OverviewMapDataSource; /** * The new main program. There can be many filenames to process and there can * be differing outputs determined by options. So the actual work is mostly * done in other classes. This one just works out what is wanted. * * @author Steve Ratcliffe */ public class Main implements ArgumentProcessor { private static final Logger log = Logger.getLogger(Main.class); private final MapProcessor maker = new MapMaker(); // Final .img file combiners. private final List<Combiner> combiners = new ArrayList<Combiner>(); private final Map<String, MapProcessor> processMap = new HashMap<String, MapProcessor>(); private String styleFile = "classpath:styles"; private boolean verbose; private final List<Future<String>> futures = new LinkedList<Future<String>>(); private ExecutorService threadPool; // default number of threads private int maxJobs = 1; /** * The main program to make or combine maps. We now use a two pass process, * first going through the arguments and make any maps and collect names * to be used for creating summary files like the TDB and gmapsupp. * * @param args The command line arguments. */ public static void main(String[] args) { // We need at least one argument. if (args.length < 1) { System.err.println("Usage: mkgmap [options...] <file.osm>"); printHelp(System.err, getLang(), "options"); return; } Main mm = new Main(); try { // Read the command line arguments and process each filename found. CommandArgsReader commandArgs = new CommandArgsReader(mm); commandArgs.readArgs(args); } catch (ExitException e) { System.err.println(e.getMessage()); System.exit(1); } } /** * Grab the options help file and print it. * @param err The output print stream to write to. * @param lang A language hint. The help will be displayed in this * language if it has been translated. * @param file The help file to display. */ private static void printHelp(PrintStream err, String lang, String file) { String path = "/help/" + lang + '/' + file; InputStream stream = Main.class.getResourceAsStream(path); if (stream == null) { err.println("Could not find the help topic: " + file + ", sorry"); return; } BufferedReader r = new BufferedReader(new InputStreamReader(stream)); try { String line; while ((line = r.readLine()) != null) err.println(line); } catch (IOException e) { err.println("Could not read the help topic: " + file + ", sorry"); } } public void startOptions() { MapProcessor saver = new NameSaver(); processMap.put("img", saver); // Todo: instead of the direct saver, modify the file with the correct // family-id etc. processMap.put("typ", saver); // Normal map files. processMap.put("rgn", saver); processMap.put("tre", saver); processMap.put("lbl", saver); processMap.put("net", saver); processMap.put("nod", saver); } /** * Switch out to the appropriate class to process the filename. * * @param args The command arguments. * @param filename The filename to process. */ public void processFilename(final CommandArgs args, final String filename) { final String ext = extractExtension(filename); log.debug("file", filename, ", extension is", ext); final MapProcessor mp = mapMaker(ext); if(threadPool == null) { log.info("Creating thread pool with " + maxJobs + " threads"); threadPool = Executors.newFixedThreadPool(maxJobs); } log.info("Submitting job " + filename); futures.add(threadPool.submit(new Callable<String>() { public String call() { String output = mp.makeMap(args, filename); log.debug("adding output name", output); return output; } })); } private MapProcessor mapMaker(String ext) { MapProcessor mp = processMap.get(ext); if (mp == null) mp = maker; return mp; } public void processOption(String opt, String val) { log.debug("option:", opt, val); if (opt.equals("number-of-files")) { // This option always appears first. We use it to turn on/off // generation of the overview files if there is only one file // to process. int n = Integer.valueOf(val); if (n > 1) addTdbBuilder(); } else if (opt.equals("tdbfile")) { addTdbBuilder(); } else if (opt.equals("gmapsupp")) { addCombiner(new GmapsuppBuilder()); } else if (opt.equals("help")) { printHelp(System.out, getLang(), (val.length() > 0) ? val : "help"); } else if (opt.equals("style-file") || opt.equals("map-features")) { styleFile = val; } else if (opt.equals("verbose")) { verbose = true; } else if (opt.equals("list-styles")) { listStyles(); } else if (opt.equals("max-jobs")) { if(val.length() > 0) maxJobs = Integer.parseInt(val); else maxJobs = Runtime.getRuntime().availableProcessors(); if(maxJobs < 1) { log.warn("max-jobs has to be at least 1"); maxJobs = 1; } } else if (opt.equals("version")) { System.err.println(Version.VERSION); System.exit(0); } } private void addTdbBuilder() { TdbBuilder builder = new TdbBuilder(); builder.setOverviewSource(new OverviewMapDataSource()); addCombiner(builder); } private void listStyles() { String[] names; try { StyleFileLoader loader = StyleFileLoader.createStyleLoader(styleFile, null); names = loader.list(); loader.close(); } catch (FileNotFoundException e) { log.debug("didn't find style file", e); throw new ExitException("Could not list style file " + styleFile); } Arrays.sort(names); System.out.println("The following styles are available:"); for (String name : names) { Style style; try { style = new StyleImpl(styleFile, name); } catch (SyntaxException e) { System.err.println("Error in style: " + e.getMessage()); continue; } catch (FileNotFoundException e) { log.debug("could not find style", name); try { style = new StyleImpl(styleFile, null); } catch (SyntaxException e1) { System.err.println("Error in style: " + e1.getMessage()); continue; } catch (FileNotFoundException e1) { log.debug("could not find style", styleFile); continue; } } StyleInfo info = style.getInfo(); System.out.format("%-15s %6s: %s\n", name,info.getVersion(), info.getSummary()); if (verbose) { for (String s : info.getLongDescription().split("\n")) System.out.printf("\t%s\n", s.trim()); } } } private static String getLang() { return "en"; } private void addCombiner(Combiner combiner) { combiners.add(combiner); } public void endOptions(CommandArgs args) { List<String> filenames = new ArrayList<String>(); if(threadPool != null) { threadPool.shutdown(); while(!futures.isEmpty()) { try { try { // don't call get() until a job has finished if(futures.get(0).isDone()) filenames.add(futures.remove(0).get()); else Thread.sleep(10); } catch (ExecutionException e) { // Re throw the underlying exception Throwable cause = e.getCause(); if (cause instanceof Exception) throw (Exception) cause; else throw e; } } catch (Exception e) { - if (args.getProperties().getProperty("keep-going", false)) { + if(args.getProperties().getProperty("keep-going", false)) { System.err.println("ERROR: " + e.getMessage()); - System.err.println(" continuing regardless because --keep-going was given"); - } else { - throw (RuntimeException) e; + } + else { + System.err.println("Exiting - if you want to carry on regardless, use the --keep-going option"); + throw new ExitException(e.getMessage()); } } } } if (combiners.isEmpty()) return; log.info("Combining maps"); // Get them all set up. for (Combiner c : combiners) c.init(args); // Tell them about each filename for (String file : filenames) { if (file == null) continue; try { log.info(" " + file); FileInfo mapReader = FileInfo.getFileInfo(file); for (Combiner c : combiners) { c.onMapEnd(mapReader); } } catch (FileNotFoundException e) { log.error("could not open file", e); } } // All done, allow tidy up or file creation to happen for (Combiner c : combiners) { c.onFinish(); } } /** * Get the extension of the filename, ignoring any compression suffix. * * @param filename The original filename. * @return The file extension. */ private String extractExtension(String filename) { String[] parts = filename.toLowerCase(Locale.ENGLISH).split("\\."); List<String> ignore = Arrays.asList("gz", "bz2", "bz"); // We want the last part that is not gz, bz etc (and isn't the first part ;) for (int i = parts.length - 1; i > 0; i--) { String ext = parts[i]; if (!ignore.contains(ext)) return ext; } return ""; } /** * A null implementation that just returns the input name as the output. */ private static class NameSaver implements MapProcessor { public String makeMap(CommandArgs args, String filename) { return filename; } } }
false
true
public void endOptions(CommandArgs args) { List<String> filenames = new ArrayList<String>(); if(threadPool != null) { threadPool.shutdown(); while(!futures.isEmpty()) { try { try { // don't call get() until a job has finished if(futures.get(0).isDone()) filenames.add(futures.remove(0).get()); else Thread.sleep(10); } catch (ExecutionException e) { // Re throw the underlying exception Throwable cause = e.getCause(); if (cause instanceof Exception) throw (Exception) cause; else throw e; } } catch (Exception e) { if (args.getProperties().getProperty("keep-going", false)) { System.err.println("ERROR: " + e.getMessage()); System.err.println(" continuing regardless because --keep-going was given"); } else { throw (RuntimeException) e; } } } } if (combiners.isEmpty()) return; log.info("Combining maps"); // Get them all set up. for (Combiner c : combiners) c.init(args); // Tell them about each filename for (String file : filenames) { if (file == null) continue; try { log.info(" " + file); FileInfo mapReader = FileInfo.getFileInfo(file); for (Combiner c : combiners) { c.onMapEnd(mapReader); } } catch (FileNotFoundException e) { log.error("could not open file", e); } } // All done, allow tidy up or file creation to happen for (Combiner c : combiners) { c.onFinish(); } }
public void endOptions(CommandArgs args) { List<String> filenames = new ArrayList<String>(); if(threadPool != null) { threadPool.shutdown(); while(!futures.isEmpty()) { try { try { // don't call get() until a job has finished if(futures.get(0).isDone()) filenames.add(futures.remove(0).get()); else Thread.sleep(10); } catch (ExecutionException e) { // Re throw the underlying exception Throwable cause = e.getCause(); if (cause instanceof Exception) throw (Exception) cause; else throw e; } } catch (Exception e) { if(args.getProperties().getProperty("keep-going", false)) { System.err.println("ERROR: " + e.getMessage()); } else { System.err.println("Exiting - if you want to carry on regardless, use the --keep-going option"); throw new ExitException(e.getMessage()); } } } } if (combiners.isEmpty()) return; log.info("Combining maps"); // Get them all set up. for (Combiner c : combiners) c.init(args); // Tell them about each filename for (String file : filenames) { if (file == null) continue; try { log.info(" " + file); FileInfo mapReader = FileInfo.getFileInfo(file); for (Combiner c : combiners) { c.onMapEnd(mapReader); } } catch (FileNotFoundException e) { log.error("could not open file", e); } } // All done, allow tidy up or file creation to happen for (Combiner c : combiners) { c.onFinish(); } }
diff --git a/src/main/java/name/richardson/james/bukkit/utilities/command/HelpCommand.java b/src/main/java/name/richardson/james/bukkit/utilities/command/HelpCommand.java index 82438f4..286b4fe 100644 --- a/src/main/java/name/richardson/james/bukkit/utilities/command/HelpCommand.java +++ b/src/main/java/name/richardson/james/bukkit/utilities/command/HelpCommand.java @@ -1,104 +1,104 @@ /******************************************************************************* Copyright (c) 2013 James Richardson. HelpCommand.java is part of BukkitUtilities. BukkitUtilities 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. BukkitUtilities 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 BukkitUtilities. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package name.richardson.james.bukkit.utilities.command; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.List; import java.util.Map; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.plugin.PluginDescriptionFile; import name.richardson.james.bukkit.utilities.colours.ColourScheme; import name.richardson.james.bukkit.utilities.colours.CoreColourScheme; import name.richardson.james.bukkit.utilities.command.argument.CommandArgument; import name.richardson.james.bukkit.utilities.command.argument.InvalidArgumentException; import name.richardson.james.bukkit.utilities.localisation.LocalisedCoreColourScheme; @CommandArguments(arguments = {CommandArgument.class}) public class HelpCommand extends AbstractCommand { final static private ChatColor REQUIRED_ARGUMENT_COLOUR = ChatColor.YELLOW; final static private ChatColor OPTIONAL_ARGUMENT_COLOUR = ChatColor.GREEN; private final String label; private final ColourScheme localisedScheme; private final String pluginDescription; private final String pluginName; private final ColourScheme scheme; private String commandName; private Map<String, Command> commands = new HashMap<String, Command>(); private WeakReference<CommandSender> sender; public HelpCommand(final String label, final PluginDescriptionFile description) { this.label = label; this.pluginName = description.getFullName(); this.pluginDescription = description.getDescription(); this.scheme = new CoreColourScheme(); this.localisedScheme = new LocalisedCoreColourScheme(this.getResourceBundle()); } public void execute(final List<String> arguments, final CommandSender sender) { this.sender = new WeakReference<CommandSender>(sender); this.parseArguments(arguments); if (commands.containsKey(commandName) && commands.get(commandName).isAuthorized(sender)) { Command command = commands.get(commandName); String message = this.scheme.format(ColourScheme.Style.HEADER, command.getDescription()); this.sender.get().sendMessage(message); message = this.localisedScheme.format(ColourScheme.Style.ERROR, "list-item", this.label, command.getName(), this.colouriseUsage(this.getUsage())); this.sender.get().sendMessage(message); } else { String message = this.scheme.format(ColourScheme.Style.HEADER, this.pluginName); this.sender.get().sendMessage(message); this.sender.get().sendMessage(ChatColor.AQUA + this.pluginDescription); message = this.localisedScheme.format(ColourScheme.Style.WARNING, "usage-hint", this.label, this.getName()); this.sender.get().sendMessage(message); for (final Command command : this.commands.values()) { if (!command.isAuthorized(sender)) continue; - message = this.localisedScheme.format(ColourScheme.Style.ERROR, "list-item", this.label, command.getName(), this.colouriseUsage(this.getUsage())); + message = this.localisedScheme.format(ColourScheme.Style.ERROR, "list-item", "/" + this.label, command.getName(), this.colouriseUsage(this.getUsage())); this.sender.get().sendMessage(message); } } } public void setCommands(Map<String, Command> commands) { this.commands = commands; } protected void parseArguments(List<String> arguments) { try { super.parseArguments(arguments); this.commandName = (String) this.getArguments().get(0).getValue(); } catch (InvalidArgumentException e) { String message = this.scheme.format(ColourScheme.Style.ERROR, e.getMessage()); this.sender.get().sendMessage(message); } } protected void setArguments() { super.setArguments(); this.getArguments().get(0).setRequired(false); } private String colouriseUsage(String usage) { usage = usage.replaceAll("<", HelpCommand.REQUIRED_ARGUMENT_COLOUR + "<"); usage = usage.replaceAll("\\[", HelpCommand.OPTIONAL_ARGUMENT_COLOUR + "\\["); return usage; } }
true
true
public void execute(final List<String> arguments, final CommandSender sender) { this.sender = new WeakReference<CommandSender>(sender); this.parseArguments(arguments); if (commands.containsKey(commandName) && commands.get(commandName).isAuthorized(sender)) { Command command = commands.get(commandName); String message = this.scheme.format(ColourScheme.Style.HEADER, command.getDescription()); this.sender.get().sendMessage(message); message = this.localisedScheme.format(ColourScheme.Style.ERROR, "list-item", this.label, command.getName(), this.colouriseUsage(this.getUsage())); this.sender.get().sendMessage(message); } else { String message = this.scheme.format(ColourScheme.Style.HEADER, this.pluginName); this.sender.get().sendMessage(message); this.sender.get().sendMessage(ChatColor.AQUA + this.pluginDescription); message = this.localisedScheme.format(ColourScheme.Style.WARNING, "usage-hint", this.label, this.getName()); this.sender.get().sendMessage(message); for (final Command command : this.commands.values()) { if (!command.isAuthorized(sender)) continue; message = this.localisedScheme.format(ColourScheme.Style.ERROR, "list-item", this.label, command.getName(), this.colouriseUsage(this.getUsage())); this.sender.get().sendMessage(message); } } }
public void execute(final List<String> arguments, final CommandSender sender) { this.sender = new WeakReference<CommandSender>(sender); this.parseArguments(arguments); if (commands.containsKey(commandName) && commands.get(commandName).isAuthorized(sender)) { Command command = commands.get(commandName); String message = this.scheme.format(ColourScheme.Style.HEADER, command.getDescription()); this.sender.get().sendMessage(message); message = this.localisedScheme.format(ColourScheme.Style.ERROR, "list-item", this.label, command.getName(), this.colouriseUsage(this.getUsage())); this.sender.get().sendMessage(message); } else { String message = this.scheme.format(ColourScheme.Style.HEADER, this.pluginName); this.sender.get().sendMessage(message); this.sender.get().sendMessage(ChatColor.AQUA + this.pluginDescription); message = this.localisedScheme.format(ColourScheme.Style.WARNING, "usage-hint", this.label, this.getName()); this.sender.get().sendMessage(message); for (final Command command : this.commands.values()) { if (!command.isAuthorized(sender)) continue; message = this.localisedScheme.format(ColourScheme.Style.ERROR, "list-item", "/" + this.label, command.getName(), this.colouriseUsage(this.getUsage())); this.sender.get().sendMessage(message); } } }
diff --git a/source/src/net/grinder/engine/agent/AgentImplementation.java b/source/src/net/grinder/engine/agent/AgentImplementation.java index f1209bc1..5b76cf19 100644 --- a/source/src/net/grinder/engine/agent/AgentImplementation.java +++ b/source/src/net/grinder/engine/agent/AgentImplementation.java @@ -1,514 +1,514 @@ // Copyright (C) 2000 Paco Gomez // Copyright (C) 2000 - 2008 Philip Aston // Copyright (C) 2004 Bertrand Ave // Copyright (C) 2008 Pawel Lacinski // All rights reserved. // // This file is part of The Grinder software distribution. Refer to // the file LICENSE which is part of The Grinder distribution for // licensing details. The Grinder distribution is available on the // Internet at http://grinder.sourceforge.net/ // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. package net.grinder.engine.agent; import java.io.File; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Timer; import java.util.TimerTask; import net.grinder.common.GrinderBuild; import net.grinder.common.GrinderException; import net.grinder.common.GrinderProperties; import net.grinder.common.Logger; import net.grinder.communication.ClientReceiver; import net.grinder.communication.ClientSender; import net.grinder.communication.CommunicationException; import net.grinder.communication.ConnectionType; import net.grinder.communication.Connector; import net.grinder.communication.FanOutStreamSender; import net.grinder.communication.IgnoreShutdownSender; import net.grinder.communication.MessageDispatchSender; import net.grinder.communication.MessagePump; import net.grinder.communication.TeeSender; import net.grinder.engine.common.ConnectorFactory; import net.grinder.engine.common.EngineException; import net.grinder.engine.common.ScriptLocation; import net.grinder.engine.communication.ConsoleListener; import net.grinder.messages.agent.StartGrinderMessage; import net.grinder.messages.console.AgentAddress; import net.grinder.messages.console.AgentProcessReportMessage; import net.grinder.util.AllocateLowestNumberImplementation; import net.grinder.util.Directory; import net.grinder.util.Directory.DirectoryException; import net.grinder.util.thread.Condition; /** * This is the entry point of The Grinder agent process. * * @author Paco Gomez * @author Philip Aston * @author Bertrand Ave * @author Pawel Lacinski * @version $Revision: 3865 $ */ public final class AgentImplementation implements Agent { private final Logger m_logger; private final File m_alternateFile; private final boolean m_proceedWithoutConsole; private final Timer m_timer = new Timer(true); private final Condition m_eventSynchronisation = new Condition(); private final AgentIdentityImplementation m_agentIdentity; private final ConsoleListener m_consoleListener; private final FanOutStreamSender m_fanOutStreamSender = new FanOutStreamSender(3); private final ConnectorFactory m_connectorFactory = new ConnectorFactory(ConnectionType.AGENT); /** * We use an most one file store throughout an agent's life, but can't * initialise it until we've read the properties and connected to the console. */ private volatile FileStore m_fileStore; /** * Constructor. * * @param logger Logger. * @param alternateFile Alternative properties file, or <code>null</code>. * @param proceedWithoutConsole <code>true</code> => proceed if a console * connection could not be made. * @throws GrinderException If an error occurs. */ public AgentImplementation(Logger logger, File alternateFile, boolean proceedWithoutConsole) throws GrinderException { m_logger = logger; m_alternateFile = alternateFile; m_proceedWithoutConsole = proceedWithoutConsole; m_consoleListener = new ConsoleListener(m_eventSynchronisation, m_logger); m_agentIdentity = new AgentIdentityImplementation(getHostName(), new AllocateLowestNumberImplementation()); } /** * Run the Grinder agent process. * * @throws GrinderException * If an error occurs. */ public void run() throws GrinderException { StartGrinderMessage startMessage = null; ConsoleCommunication consoleCommunication = null; try { while (true) { m_logger.output(GrinderBuild.getName()); ScriptLocation script = null; GrinderProperties properties; do { properties = new GrinderProperties( m_alternateFile != null ? m_alternateFile : GrinderProperties.DEFAULT_PROPERTIES); if (startMessage != null) { properties.putAll(startMessage.getProperties()); } m_agentIdentity.setName( properties.getProperty("grinder.hostID", getHostName())); final Connector connector = properties.getBoolean("grinder.useConsole", true) ? m_connectorFactory.create(properties) : null; // We only reconnect if the connection details have changed. if (consoleCommunication != null && !consoleCommunication.getConnector().equals(connector)) { shutdownConsoleCommunication(consoleCommunication); consoleCommunication = null; - startMessage = null; + // Accept any startMessage from previous console - see bug 2092881. } if (consoleCommunication == null && connector != null) { try { consoleCommunication = new ConsoleCommunication(connector); m_logger.output( "connected to console at " + connector.getEndpointAsString()); } catch (CommunicationException e) { if (m_proceedWithoutConsole) { m_logger.error( e.getMessage() + ", proceeding without the console; set " + "grinder.useConsole=false to disable this warning."); } else { m_logger.error(e.getMessage()); return; } } } if (consoleCommunication != null && startMessage == null) { m_logger.output("waiting for console signal"); m_consoleListener.waitForMessage(); if (m_consoleListener.received(ConsoleListener.START)) { startMessage = m_consoleListener.getLastStartGrinderMessage(); continue; // Loop to handle new properties. } else { break; // Another message, check at end of outer while loop. } } if (startMessage != null) { final GrinderProperties messageProperties = startMessage.getProperties(); final Directory fileStoreDirectory = m_fileStore.getDirectory(); // Convert relative path to absolute path. messageProperties.setAssociatedFile( fileStoreDirectory.getFile( messageProperties.getAssociatedFile())); final File consoleScript = messageProperties.resolveRelativeFile( messageProperties.getFile(GrinderProperties.SCRIPT, GrinderProperties.DEFAULT_SCRIPT)); // We only fall back to the agent properties if the start message // doesn't specify a script and there is no default script. if (messageProperties.containsKey(GrinderProperties.SCRIPT) || consoleScript.canRead()) { // The script directory may not be the file's direct parent. script = new ScriptLocation(fileStoreDirectory, consoleScript); } m_agentIdentity.setNumber(startMessage.getAgentNumber()); } else { m_agentIdentity.setNumber(-1); } if (script == null) { final File scriptFile = properties.resolveRelativeFile( properties.getFile(GrinderProperties.SCRIPT, GrinderProperties.DEFAULT_SCRIPT)); try { script = new ScriptLocation(scriptFile); } catch (DirectoryException e) { m_logger.error("The script '" + scriptFile + "' does not exist."); break; } } if (!script.getFile().canRead()) { m_logger.error("The script file '" + script + "' does not exist or is not readable."); script = null; break; } } while (script == null); if (script != null) { final String jvmArguments = properties.getProperty("grinder.jvm.arguments"); final WorkerFactory workerFactory; if (!properties.getBoolean("grinder.debug.singleprocess", false)) { final WorkerProcessCommandLine workerCommandLine = new WorkerProcessCommandLine(properties, System.getProperties(), jvmArguments); m_logger.output( "Worker process command line: " + workerCommandLine); workerFactory = new ProcessWorkerFactory( workerCommandLine, m_agentIdentity, m_fanOutStreamSender, consoleCommunication != null, script, properties); } else { m_logger.output( "DEBUG MODE: Spawning threads rather than processes"); if (jvmArguments != null) { m_logger.output("WARNING grinder.jvm.arguments (" + jvmArguments + ") ignored in single process mode"); } workerFactory = new DebugThreadWorkerFactory( m_agentIdentity, m_fanOutStreamSender, consoleCommunication != null, script, properties); } final WorkerLauncher workerLauncher = new WorkerLauncher(properties.getInt("grinder.processes", 1), workerFactory, m_eventSynchronisation, m_logger); final int increment = properties.getInt("grinder.processIncrement", 0); if (increment > 0) { final boolean moreProcessesToStart = workerLauncher.startSomeWorkers( properties.getInt("grinder.initialProcesses", increment)); if (moreProcessesToStart) { final int incrementInterval = properties.getInt("grinder.processIncrementInterval", 60000); final RampUpTimerTask rampUpTimerTask = new RampUpTimerTask(workerLauncher, increment); m_timer.scheduleAtFixedRate( rampUpTimerTask, incrementInterval, incrementInterval); } } else { workerLauncher.startAllWorkers(); } // Wait for a termination event. synchronized (m_eventSynchronisation) { final long maximumShutdownTime = 20000; long consoleSignalTime = -1; while (!workerLauncher.allFinished()) { if (consoleSignalTime == -1 && m_consoleListener.checkForMessage(ConsoleListener.ANY ^ ConsoleListener.START)) { workerLauncher.dontStartAnyMore(); consoleSignalTime = System.currentTimeMillis(); } if (consoleSignalTime >= 0 && System.currentTimeMillis() - consoleSignalTime > maximumShutdownTime) { m_logger.output("forcibly terminating unresponsive processes"); // destroyAllWorkers() also prevents any more workers from // starting. workerLauncher.destroyAllWorkers(); } m_eventSynchronisation.waitNoInterrruptException( maximumShutdownTime); } } workerLauncher.shutdown(); } if (consoleCommunication == null) { break; } else { // Ignore any pending start messages. m_consoleListener.discardMessages(ConsoleListener.START); if (!m_consoleListener.received(ConsoleListener.ANY)) { // We've got here naturally, without a console signal. m_logger.output("finished, waiting for console signal"); m_consoleListener.waitForMessage(); } if (m_consoleListener.received(ConsoleListener.START)) { startMessage = m_consoleListener.getLastStartGrinderMessage(); } else if (m_consoleListener.received(ConsoleListener.STOP | ConsoleListener.SHUTDOWN)) { break; } else { // ConsoleListener.RESET or natural death. startMessage = null; } } } } finally { shutdownConsoleCommunication(consoleCommunication); } } private void shutdownConsoleCommunication( ConsoleCommunication consoleCommunication) { if (consoleCommunication != null) { consoleCommunication.shutdown(); } m_consoleListener.discardMessages(ConsoleListener.ANY); } /** * Clean up resources. */ public void shutdown() { m_timer.cancel(); m_fanOutStreamSender.shutdown(); m_consoleListener.shutdown(); m_logger.output("finished"); } private static String getHostName() { try { return InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { return "UNNAMED HOST"; } } private static class RampUpTimerTask extends TimerTask { private final WorkerLauncher m_processLauncher; private final int m_processIncrement; public RampUpTimerTask(WorkerLauncher processLauncher, int processIncrement) { m_processLauncher = processLauncher; m_processIncrement = processIncrement; } public void run() { try { final boolean moreProcessesToStart = m_processLauncher.startSomeWorkers(m_processIncrement); if (!moreProcessesToStart) { super.cancel(); } } catch (EngineException e) { // Really an assertion. Can't use logger because its not thread-safe. System.err.println("Failed to start processes"); e.printStackTrace(); } } } private final class ConsoleCommunication { private final ClientSender m_sender; private final Connector m_connector; private final TimerTask m_reportRunningTask; private final MessagePump m_messagePump; public ConsoleCommunication(Connector connector) throws CommunicationException, FileStore.FileStoreException { final ClientReceiver receiver = ClientReceiver.connect(connector, new AgentAddress(m_agentIdentity)); m_sender = ClientSender.connect(receiver); m_connector = connector; if (m_fileStore == null) { // Only create the file store if we connected. m_fileStore = new FileStore( new File("./" + m_agentIdentity.getName() + "-file-store"), m_logger); } m_sender.send( new AgentProcessReportMessage( m_agentIdentity, AgentProcessReportMessage.STATE_STARTED, m_fileStore.getCacheHighWaterMark())); final MessageDispatchSender fileStoreMessageDispatcher = new MessageDispatchSender(); m_fileStore.registerMessageHandlers(fileStoreMessageDispatcher); final MessageDispatchSender messageDispatcher = new MessageDispatchSender(); m_consoleListener.registerMessageHandlers(messageDispatcher); // Everything that the file store doesn't handle is tee'd to the // worker processes and our message handlers. fileStoreMessageDispatcher.addFallback( new TeeSender(messageDispatcher, new IgnoreShutdownSender(m_fanOutStreamSender))); m_messagePump = new MessagePump(receiver, fileStoreMessageDispatcher, 1); m_reportRunningTask = new TimerTask() { public void run() { try { m_sender.send( new AgentProcessReportMessage( m_agentIdentity, AgentProcessReportMessage.STATE_RUNNING, m_fileStore.getCacheHighWaterMark())); } catch (CommunicationException e) { cancel(); e.printStackTrace(); } } }; m_timer.schedule(m_reportRunningTask, 1000, 1000); } public Connector getConnector() { return m_connector; } public void shutdown() { m_reportRunningTask.cancel(); try { m_sender.send( new AgentProcessReportMessage( m_agentIdentity, AgentProcessReportMessage.STATE_FINISHED, m_fileStore.getCacheHighWaterMark())); } catch (CommunicationException e) { // Ignore - peer has probably shut down. } finally { m_messagePump.shutdown(); } } } }
true
true
public void run() throws GrinderException { StartGrinderMessage startMessage = null; ConsoleCommunication consoleCommunication = null; try { while (true) { m_logger.output(GrinderBuild.getName()); ScriptLocation script = null; GrinderProperties properties; do { properties = new GrinderProperties( m_alternateFile != null ? m_alternateFile : GrinderProperties.DEFAULT_PROPERTIES); if (startMessage != null) { properties.putAll(startMessage.getProperties()); } m_agentIdentity.setName( properties.getProperty("grinder.hostID", getHostName())); final Connector connector = properties.getBoolean("grinder.useConsole", true) ? m_connectorFactory.create(properties) : null; // We only reconnect if the connection details have changed. if (consoleCommunication != null && !consoleCommunication.getConnector().equals(connector)) { shutdownConsoleCommunication(consoleCommunication); consoleCommunication = null; startMessage = null; } if (consoleCommunication == null && connector != null) { try { consoleCommunication = new ConsoleCommunication(connector); m_logger.output( "connected to console at " + connector.getEndpointAsString()); } catch (CommunicationException e) { if (m_proceedWithoutConsole) { m_logger.error( e.getMessage() + ", proceeding without the console; set " + "grinder.useConsole=false to disable this warning."); } else { m_logger.error(e.getMessage()); return; } } } if (consoleCommunication != null && startMessage == null) { m_logger.output("waiting for console signal"); m_consoleListener.waitForMessage(); if (m_consoleListener.received(ConsoleListener.START)) { startMessage = m_consoleListener.getLastStartGrinderMessage(); continue; // Loop to handle new properties. } else { break; // Another message, check at end of outer while loop. } } if (startMessage != null) { final GrinderProperties messageProperties = startMessage.getProperties(); final Directory fileStoreDirectory = m_fileStore.getDirectory(); // Convert relative path to absolute path. messageProperties.setAssociatedFile( fileStoreDirectory.getFile( messageProperties.getAssociatedFile())); final File consoleScript = messageProperties.resolveRelativeFile( messageProperties.getFile(GrinderProperties.SCRIPT, GrinderProperties.DEFAULT_SCRIPT)); // We only fall back to the agent properties if the start message // doesn't specify a script and there is no default script. if (messageProperties.containsKey(GrinderProperties.SCRIPT) || consoleScript.canRead()) { // The script directory may not be the file's direct parent. script = new ScriptLocation(fileStoreDirectory, consoleScript); } m_agentIdentity.setNumber(startMessage.getAgentNumber()); } else { m_agentIdentity.setNumber(-1); } if (script == null) { final File scriptFile = properties.resolveRelativeFile( properties.getFile(GrinderProperties.SCRIPT, GrinderProperties.DEFAULT_SCRIPT)); try { script = new ScriptLocation(scriptFile); } catch (DirectoryException e) { m_logger.error("The script '" + scriptFile + "' does not exist."); break; } } if (!script.getFile().canRead()) { m_logger.error("The script file '" + script + "' does not exist or is not readable."); script = null; break; } } while (script == null); if (script != null) { final String jvmArguments = properties.getProperty("grinder.jvm.arguments"); final WorkerFactory workerFactory; if (!properties.getBoolean("grinder.debug.singleprocess", false)) { final WorkerProcessCommandLine workerCommandLine = new WorkerProcessCommandLine(properties, System.getProperties(), jvmArguments); m_logger.output( "Worker process command line: " + workerCommandLine); workerFactory = new ProcessWorkerFactory( workerCommandLine, m_agentIdentity, m_fanOutStreamSender, consoleCommunication != null, script, properties); } else { m_logger.output( "DEBUG MODE: Spawning threads rather than processes"); if (jvmArguments != null) { m_logger.output("WARNING grinder.jvm.arguments (" + jvmArguments + ") ignored in single process mode"); } workerFactory = new DebugThreadWorkerFactory( m_agentIdentity, m_fanOutStreamSender, consoleCommunication != null, script, properties); } final WorkerLauncher workerLauncher = new WorkerLauncher(properties.getInt("grinder.processes", 1), workerFactory, m_eventSynchronisation, m_logger); final int increment = properties.getInt("grinder.processIncrement", 0); if (increment > 0) { final boolean moreProcessesToStart = workerLauncher.startSomeWorkers( properties.getInt("grinder.initialProcesses", increment)); if (moreProcessesToStart) { final int incrementInterval = properties.getInt("grinder.processIncrementInterval", 60000); final RampUpTimerTask rampUpTimerTask = new RampUpTimerTask(workerLauncher, increment); m_timer.scheduleAtFixedRate( rampUpTimerTask, incrementInterval, incrementInterval); } } else { workerLauncher.startAllWorkers(); } // Wait for a termination event. synchronized (m_eventSynchronisation) { final long maximumShutdownTime = 20000; long consoleSignalTime = -1; while (!workerLauncher.allFinished()) { if (consoleSignalTime == -1 && m_consoleListener.checkForMessage(ConsoleListener.ANY ^ ConsoleListener.START)) { workerLauncher.dontStartAnyMore(); consoleSignalTime = System.currentTimeMillis(); } if (consoleSignalTime >= 0 && System.currentTimeMillis() - consoleSignalTime > maximumShutdownTime) { m_logger.output("forcibly terminating unresponsive processes"); // destroyAllWorkers() also prevents any more workers from // starting. workerLauncher.destroyAllWorkers(); } m_eventSynchronisation.waitNoInterrruptException( maximumShutdownTime); } } workerLauncher.shutdown(); } if (consoleCommunication == null) { break; } else { // Ignore any pending start messages. m_consoleListener.discardMessages(ConsoleListener.START); if (!m_consoleListener.received(ConsoleListener.ANY)) { // We've got here naturally, without a console signal. m_logger.output("finished, waiting for console signal"); m_consoleListener.waitForMessage(); } if (m_consoleListener.received(ConsoleListener.START)) { startMessage = m_consoleListener.getLastStartGrinderMessage(); } else if (m_consoleListener.received(ConsoleListener.STOP | ConsoleListener.SHUTDOWN)) { break; } else { // ConsoleListener.RESET or natural death. startMessage = null; } } } } finally { shutdownConsoleCommunication(consoleCommunication); } }
public void run() throws GrinderException { StartGrinderMessage startMessage = null; ConsoleCommunication consoleCommunication = null; try { while (true) { m_logger.output(GrinderBuild.getName()); ScriptLocation script = null; GrinderProperties properties; do { properties = new GrinderProperties( m_alternateFile != null ? m_alternateFile : GrinderProperties.DEFAULT_PROPERTIES); if (startMessage != null) { properties.putAll(startMessage.getProperties()); } m_agentIdentity.setName( properties.getProperty("grinder.hostID", getHostName())); final Connector connector = properties.getBoolean("grinder.useConsole", true) ? m_connectorFactory.create(properties) : null; // We only reconnect if the connection details have changed. if (consoleCommunication != null && !consoleCommunication.getConnector().equals(connector)) { shutdownConsoleCommunication(consoleCommunication); consoleCommunication = null; // Accept any startMessage from previous console - see bug 2092881. } if (consoleCommunication == null && connector != null) { try { consoleCommunication = new ConsoleCommunication(connector); m_logger.output( "connected to console at " + connector.getEndpointAsString()); } catch (CommunicationException e) { if (m_proceedWithoutConsole) { m_logger.error( e.getMessage() + ", proceeding without the console; set " + "grinder.useConsole=false to disable this warning."); } else { m_logger.error(e.getMessage()); return; } } } if (consoleCommunication != null && startMessage == null) { m_logger.output("waiting for console signal"); m_consoleListener.waitForMessage(); if (m_consoleListener.received(ConsoleListener.START)) { startMessage = m_consoleListener.getLastStartGrinderMessage(); continue; // Loop to handle new properties. } else { break; // Another message, check at end of outer while loop. } } if (startMessage != null) { final GrinderProperties messageProperties = startMessage.getProperties(); final Directory fileStoreDirectory = m_fileStore.getDirectory(); // Convert relative path to absolute path. messageProperties.setAssociatedFile( fileStoreDirectory.getFile( messageProperties.getAssociatedFile())); final File consoleScript = messageProperties.resolveRelativeFile( messageProperties.getFile(GrinderProperties.SCRIPT, GrinderProperties.DEFAULT_SCRIPT)); // We only fall back to the agent properties if the start message // doesn't specify a script and there is no default script. if (messageProperties.containsKey(GrinderProperties.SCRIPT) || consoleScript.canRead()) { // The script directory may not be the file's direct parent. script = new ScriptLocation(fileStoreDirectory, consoleScript); } m_agentIdentity.setNumber(startMessage.getAgentNumber()); } else { m_agentIdentity.setNumber(-1); } if (script == null) { final File scriptFile = properties.resolveRelativeFile( properties.getFile(GrinderProperties.SCRIPT, GrinderProperties.DEFAULT_SCRIPT)); try { script = new ScriptLocation(scriptFile); } catch (DirectoryException e) { m_logger.error("The script '" + scriptFile + "' does not exist."); break; } } if (!script.getFile().canRead()) { m_logger.error("The script file '" + script + "' does not exist or is not readable."); script = null; break; } } while (script == null); if (script != null) { final String jvmArguments = properties.getProperty("grinder.jvm.arguments"); final WorkerFactory workerFactory; if (!properties.getBoolean("grinder.debug.singleprocess", false)) { final WorkerProcessCommandLine workerCommandLine = new WorkerProcessCommandLine(properties, System.getProperties(), jvmArguments); m_logger.output( "Worker process command line: " + workerCommandLine); workerFactory = new ProcessWorkerFactory( workerCommandLine, m_agentIdentity, m_fanOutStreamSender, consoleCommunication != null, script, properties); } else { m_logger.output( "DEBUG MODE: Spawning threads rather than processes"); if (jvmArguments != null) { m_logger.output("WARNING grinder.jvm.arguments (" + jvmArguments + ") ignored in single process mode"); } workerFactory = new DebugThreadWorkerFactory( m_agentIdentity, m_fanOutStreamSender, consoleCommunication != null, script, properties); } final WorkerLauncher workerLauncher = new WorkerLauncher(properties.getInt("grinder.processes", 1), workerFactory, m_eventSynchronisation, m_logger); final int increment = properties.getInt("grinder.processIncrement", 0); if (increment > 0) { final boolean moreProcessesToStart = workerLauncher.startSomeWorkers( properties.getInt("grinder.initialProcesses", increment)); if (moreProcessesToStart) { final int incrementInterval = properties.getInt("grinder.processIncrementInterval", 60000); final RampUpTimerTask rampUpTimerTask = new RampUpTimerTask(workerLauncher, increment); m_timer.scheduleAtFixedRate( rampUpTimerTask, incrementInterval, incrementInterval); } } else { workerLauncher.startAllWorkers(); } // Wait for a termination event. synchronized (m_eventSynchronisation) { final long maximumShutdownTime = 20000; long consoleSignalTime = -1; while (!workerLauncher.allFinished()) { if (consoleSignalTime == -1 && m_consoleListener.checkForMessage(ConsoleListener.ANY ^ ConsoleListener.START)) { workerLauncher.dontStartAnyMore(); consoleSignalTime = System.currentTimeMillis(); } if (consoleSignalTime >= 0 && System.currentTimeMillis() - consoleSignalTime > maximumShutdownTime) { m_logger.output("forcibly terminating unresponsive processes"); // destroyAllWorkers() also prevents any more workers from // starting. workerLauncher.destroyAllWorkers(); } m_eventSynchronisation.waitNoInterrruptException( maximumShutdownTime); } } workerLauncher.shutdown(); } if (consoleCommunication == null) { break; } else { // Ignore any pending start messages. m_consoleListener.discardMessages(ConsoleListener.START); if (!m_consoleListener.received(ConsoleListener.ANY)) { // We've got here naturally, without a console signal. m_logger.output("finished, waiting for console signal"); m_consoleListener.waitForMessage(); } if (m_consoleListener.received(ConsoleListener.START)) { startMessage = m_consoleListener.getLastStartGrinderMessage(); } else if (m_consoleListener.received(ConsoleListener.STOP | ConsoleListener.SHUTDOWN)) { break; } else { // ConsoleListener.RESET or natural death. startMessage = null; } } } } finally { shutdownConsoleCommunication(consoleCommunication); } }
diff --git a/kmelia/kmelia-war/src/main/java/com/stratelia/webactiv/kmelia/servlets/KmeliaRequestRouter.java b/kmelia/kmelia-war/src/main/java/com/stratelia/webactiv/kmelia/servlets/KmeliaRequestRouter.java index 058432ca8..97c3d92b1 100644 --- a/kmelia/kmelia-war/src/main/java/com/stratelia/webactiv/kmelia/servlets/KmeliaRequestRouter.java +++ b/kmelia/kmelia-war/src/main/java/com/stratelia/webactiv/kmelia/servlets/KmeliaRequestRouter.java @@ -1,2628 +1,2630 @@ /** * Copyright (C) 2000 - 2009 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://repository.silverpeas.com/legal/licensing" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.stratelia.webactiv.kmelia.servlets; import java.io.File; import java.io.IOException; import java.net.URLEncoder; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import javax.servlet.http.HttpServletRequest; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.fileupload.FileItem; import org.xml.sax.SAXException; import com.silverpeas.form.DataRecord; import com.silverpeas.form.Form; import com.silverpeas.form.FormException; import com.silverpeas.form.PagesContext; import com.silverpeas.form.RecordSet; import com.silverpeas.kmelia.KmeliaConstants; import com.silverpeas.kmelia.updatechainhelpers.UpdateChainHelper; import com.silverpeas.kmelia.updatechainhelpers.UpdateChainHelperContext; import com.silverpeas.publicationTemplate.PublicationTemplate; import com.silverpeas.publicationTemplate.PublicationTemplateException; import com.silverpeas.publicationTemplate.PublicationTemplateImpl; import com.silverpeas.publicationTemplate.PublicationTemplateManager; import com.silverpeas.thumbnail.ThumbnailRuntimeException; import com.silverpeas.thumbnail.control.ThumbnailController; import com.silverpeas.thumbnail.model.ThumbnailDetail; import com.silverpeas.util.FileUtil; import com.silverpeas.util.ForeignPK; import com.silverpeas.util.MimeTypes; import com.silverpeas.util.StringUtil; import com.silverpeas.util.ZipManager; import com.silverpeas.util.i18n.I18NHelper; import com.silverpeas.util.web.servlet.FileUploadUtil; import com.stratelia.silverpeas.peasCore.ComponentContext; import com.stratelia.silverpeas.peasCore.ComponentSessionController; import com.stratelia.silverpeas.peasCore.MainSessionController; import com.stratelia.silverpeas.peasCore.URLManager; import com.stratelia.silverpeas.peasCore.servlets.ComponentRequestRouter; import com.stratelia.silverpeas.selection.Selection; import com.stratelia.silverpeas.silvertrace.SilverTrace; import com.stratelia.silverpeas.versioning.model.Document; import com.stratelia.silverpeas.versioning.model.DocumentVersion; import com.stratelia.silverpeas.versioning.util.VersioningUtil; import com.stratelia.silverpeas.wysiwyg.control.WysiwygController; import com.stratelia.webactiv.SilverpeasRole; import com.stratelia.webactiv.beans.admin.ProfileInst; import com.stratelia.webactiv.kmelia.KmeliaSecurity; import com.stratelia.webactiv.kmelia.control.KmeliaSessionController; import com.stratelia.webactiv.kmelia.control.ejb.KmeliaHelper; import com.stratelia.webactiv.kmelia.model.FileFolder; import com.stratelia.webactiv.kmelia.model.TopicDetail; import com.stratelia.webactiv.kmelia.model.UserCompletePublication; import com.stratelia.webactiv.kmelia.model.UserPublication; import com.stratelia.webactiv.kmelia.model.updatechain.FieldUpdateChainDescriptor; import com.stratelia.webactiv.kmelia.model.updatechain.Fields; import com.stratelia.webactiv.util.DateUtil; import com.stratelia.webactiv.util.FileRepositoryManager; import com.stratelia.webactiv.util.GeneralPropertiesManager; import com.stratelia.webactiv.util.ResourceLocator; import com.stratelia.webactiv.util.WAAttributeValuePair; import com.stratelia.webactiv.util.fileFolder.FileFolderManager; import com.stratelia.webactiv.util.node.model.NodeDetail; import com.stratelia.webactiv.util.node.model.NodePK; import com.stratelia.webactiv.util.publication.info.model.InfoDetail; import com.stratelia.webactiv.util.publication.info.model.InfoImageDetail; import com.stratelia.webactiv.util.publication.info.model.InfoTextDetail; import com.stratelia.webactiv.util.publication.info.model.ModelDetail; import com.stratelia.webactiv.util.publication.model.Alias; import com.stratelia.webactiv.util.publication.model.CompletePublication; import com.stratelia.webactiv.util.publication.model.PublicationDetail; public class KmeliaRequestRouter extends ComponentRequestRouter { private static final long serialVersionUID = 1L; /** * This method creates a KmeliaSessionController instance * @param mainSessionCtrl The MainSessionController instance * @param context Context of current component instance * @return a KmeliaSessionController instance */ @Override public ComponentSessionController createComponentSessionController( MainSessionController mainSessionCtrl, ComponentContext context) { ComponentSessionController component = (ComponentSessionController) new KmeliaSessionController( mainSessionCtrl, context); return component; } /** * This method has to be implemented in the component request rooter class. returns the session * control bean name to be put in the request object ex : for almanach, returns "almanach" */ @Override public String getSessionControlBeanName() { return "kmelia"; } /** * This method has to be implemented by the component request rooter it has to compute a * destination page * @param function The entering request function ( : "Main.jsp") * @param componentSC The component Session Control, build and initialised. * @param request The entering request. The request rooter need it to get parameters * @return The complete destination URL for a forward (ex : * "/almanach/jsp/almanach.jsp?flag=user") */ @Override public String getDestination(String function, ComponentSessionController componentSC, HttpServletRequest request) { SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function); String destination = ""; String rootDestination = "/kmelia/jsp/"; boolean profileError = false; boolean kmaxMode = false; boolean toolboxMode = false; try { KmeliaSessionController kmelia = (KmeliaSessionController) componentSC; SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "getComponentRootName() = " + kmelia.getComponentRootName()); if ("kmax".equals(kmelia.getComponentRootName())) { kmaxMode = true; kmelia.isKmaxMode = true; } request.setAttribute("KmaxMode", Boolean.valueOf(kmaxMode)); toolboxMode = KmeliaHelper.isToolbox(kmelia.getComponentId()); // Set language choosen by the user setLanguage(request, kmelia); if (function.startsWith("Main")) { resetWizard(kmelia); if (kmaxMode) { destination = getDestination("KmaxMain", componentSC, request); kmelia.setSessionTopic(null); kmelia.setSessionPath(""); } else { destination = getDestination("GoToTopic", componentSC, request); } } else if (function.startsWith("portlet")) { kmelia.setSessionPublication(null); String flag = componentSC.getUserRoleLevel(); if (kmaxMode) { destination = rootDestination + "kmax_portlet.jsp?Profile=" + flag; } else { destination = rootDestination + "portlet.jsp?Profile=user"; } } else if (function.equals("FlushTrashCan")) { kmelia.flushTrashCan(); if (kmaxMode) { destination = getDestination("KmaxMain", kmelia, request); } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else if (function.equals("GoToDirectory")) { String topicId = request.getParameter("Id"); String path = null; if (StringUtil.isDefined(topicId)) { NodeDetail topic = kmelia.getNodeHeader(topicId); path = topic.getPath(); } else { path = request.getParameter("Path"); } FileFolder folder = new FileFolder(path); request.setAttribute("Directory", folder); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); destination = rootDestination + "repository.jsp"; } else if (function.equals("GoToTopic")) { String topicId = (String) request.getAttribute("Id"); if (!StringUtil.isDefined(topicId)) { topicId = request.getParameter("Id"); if (!StringUtil.isDefined(topicId)) { topicId = "0"; } } TopicDetail currentTopic = kmelia.getTopic(topicId, true); processPath(kmelia, null); kmelia.setSessionPublication(null); resetWizard(kmelia); request.setAttribute("CurrentTopic", currentTopic); request.setAttribute("PathString", kmelia.getSessionPathString()); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Treeview", kmelia.getTreeview()); request.setAttribute("DisplayNBPublis", Boolean.valueOf(kmelia.displayNbPublis())); request.setAttribute("DisplaySearch", new Boolean(kmelia.isSearchOnTopicsEnabled())); // rechercher si le theme a un descripteur request.setAttribute("HaveDescriptor", Boolean.valueOf(kmelia. isTopicHaveUpdateChainDescriptor())); if ("noRights".equalsIgnoreCase(currentTopic.getNodeDetail().getUserRole())) { destination = rootDestination + "toCrossTopic.jsp"; } else { request.setAttribute("Profile", kmelia.getUserTopicProfile(topicId)); request.setAttribute("IsGuest", Boolean.valueOf(kmelia.getUserDetail().isAccessGuest())); request.setAttribute("RightsOnTopicsEnabled", Boolean.valueOf(kmelia. isRightsOnTopicsEnabled())); request.setAttribute("WysiwygDescription", kmelia.getWysiwygOnTopic()); if (kmelia.isTreeStructure()) { destination = rootDestination + "topicManager.jsp"; } else { destination = rootDestination + "simpleListOfPublications.jsp"; } } } else if (function.equals("GoToCurrentTopic")) { if (kmelia.getSessionTopic() != null) { String id = kmelia.getSessionTopic().getNodePK().getId(); request.setAttribute("Id", id); destination = getDestination("GoToTopic", kmelia, request); } else { destination = getDestination("Main", kmelia, request); } } else if (function.equals("GoToBasket")) { destination = rootDestination + "basket.jsp"; } else if (function.equals("ViewPublicationsToValidate")) { destination = rootDestination + "publicationsToValidate.jsp"; } else if (function.startsWith("searchResult")) { resetWizard(kmelia); String id = request.getParameter("Id"); String type = request.getParameter("Type"); String fileAlreadyOpened = request.getParameter("FileOpened"); if (type.equals("Publication") || type.equals("com.stratelia.webactiv.calendar.backbone.TodoDetail") || type.equals("Attachment") || type.equals("Document")) { KmeliaSecurity security = new KmeliaSecurity(kmelia.getOrganizationController()); try { boolean accessAuthorized = security.isAccessAuthorized(kmelia.getComponentId(), kmelia.getUserId(), id, "Publication"); if (accessAuthorized) { if (type.equals("Attachment")) { String attachmentId = request.getParameter("AttachmentId"); request.setAttribute("AttachmentId", attachmentId); destination = getDestination("ViewPublication", kmelia, request); } else if (type.equals("Document")) { String documentId = request.getParameter("DocumentId"); request.setAttribute("DocumentId", documentId); destination = getDestination("ViewPublication", kmelia, request); } else { if (kmaxMode) { request.setAttribute("FileAlreadyOpened", fileAlreadyOpened); destination = getDestination("ViewPublication", kmelia, request); } else if (toolboxMode) { processPath(kmelia, id); // we have to find which page contains the right publication List<UserPublication> publications = new ArrayList<UserPublication>( kmelia.getSessionTopic().getPublicationDetails()); UserPublication publication = null; int pubIndex = -1; for (int p = 0; p < publications.size() && pubIndex == -1; p++) { publication = publications.get(p); if (id.equals(publication.getPublication().getPK().getId())) { pubIndex = p; } } int nbPubliPerPage = kmelia.getNbPublicationsPerPage(); if (nbPubliPerPage == 0) { nbPubliPerPage = pubIndex; } int ipage = pubIndex / nbPubliPerPage; kmelia.setIndexOfFirstPubToDisplay(Integer.toString(ipage * nbPubliPerPage)); request.setAttribute("PubIdToHighlight", id); destination = getDestination("GoToCurrentTopic", kmelia, request); } else { request.setAttribute("FileAlreadyOpened", fileAlreadyOpened); processPath(kmelia, id); destination = getDestination("ViewPublication", kmelia, request); } } } else { destination = "/admin/jsp/accessForbidden.jsp"; } } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e); destination = getDocumentNotFoundDestination(kmelia, request); } } else if (type.equals("Node")) { if (kmaxMode) { // Simuler l'action d'un utilisateur ayant sélectionné la valeur id d'un axe // SearchCombination est un chemin /0/4/i NodeDetail node = kmelia.getNodeHeader(id); String path = node.getPath() + id; request.setAttribute("SearchCombination", path); destination = getDestination("KmaxSearch", componentSC, request); } else { try { request.setAttribute("Id", id); destination = getDestination("GoToTopic", componentSC, request); } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e); destination = getDocumentNotFoundDestination(kmelia, request); } } } else if (type.equals("Wysiwyg")) { if (id.startsWith("Node")) { id = id.substring(5, id.length()); request.setAttribute("Id", id); destination = getDestination("GoToTopic", componentSC, request); } else { /* * if (kmaxMode) destination = getDestination("KmaxViewPublication", kmelia, request); * else */ destination = getDestination("ViewPublication", kmelia, request); } } else { request.setAttribute("Id", "0"); destination = getDestination("GoToTopic", componentSC, request); } } else if (function.startsWith("GoToFilesTab")) { String id = request.getParameter("Id"); try { processPath(kmelia, id); if (toolboxMode) { UserCompletePublication userPubComplete = kmelia.getUserCompletePublication(id); kmelia.setSessionPublication(userPubComplete); kmelia.setSessionOwner(true); destination = getDestination("ViewAttachments", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e); destination = getDocumentNotFoundDestination(kmelia, request); } } else if (function.startsWith("publicationManager")) { String flag = kmelia.getProfile(); request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "publicationManager.jsp?Profile=" + flag; // thumbnail error for front explication if (request.getParameter("errorThumbnail") != null) { destination = destination + "&resultThumbnail=" + request.getParameter("errorThumbnail"); } } else if (function.equals("ToAddTopic")) { String topicId = request.getParameter("Id"); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(topicId))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { String isLink = request.getParameter("IsLink"); if (StringUtil.isDefined(isLink)) { request.setAttribute("IsLink", Boolean.TRUE); } List<NodeDetail> path = kmelia.getTopicPath(topicId); request.setAttribute("Path", kmelia.displayPath(path, false, 3)); request.setAttribute("PathLinked", kmelia.displayPath(path, true, 3)); request.setAttribute("Translation", kmelia.getCurrentLanguage()); request.setAttribute("PopupDisplay", Boolean.TRUE); request.setAttribute("NotificationAllowed", Boolean.valueOf(kmelia.isNotificationAllowed())); request.setAttribute("Parent", kmelia.getNodeHeader(topicId)); if (kmelia.isRightsOnTopicsEnabled()) { request.setAttribute("PopupDisplay", Boolean.FALSE); request.setAttribute("Profiles", kmelia.getTopicProfiles()); // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } destination = rootDestination + "addTopic.jsp"; } } else if ("ToUpdateTopic".equals(function)) { String id = request.getParameter("Id"); NodeDetail node = kmelia.getSubTopicDetail(id); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(id)) && !SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(node.getFatherPK().getId()))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { request.setAttribute("NodeDetail", node); List<NodeDetail> path = kmelia.getTopicPath(id); request.setAttribute("Path", kmelia.displayPath(path, false, 3)); request.setAttribute("PathLinked", kmelia.displayPath(path, true, 3)); request.setAttribute("Translation", kmelia.getCurrentLanguage()); request.setAttribute("PopupDisplay", Boolean.TRUE); request.setAttribute("NotificationAllowed", Boolean.valueOf(kmelia.isNotificationAllowed())); if (kmelia.isRightsOnTopicsEnabled()) { request.setAttribute("PopupDisplay", Boolean.FALSE); request.setAttribute("Profiles", kmelia.getTopicProfiles(id)); if (node.haveInheritedRights()) { request.setAttribute("RightsDependsOn", "AnotherTopic"); } else if (node.haveLocalRights()) { request.setAttribute("RightsDependsOn", "ThisTopic"); } else { // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } } destination = rootDestination + "updateTopicNew.jsp"; } } else if (function.equals("AddTopic")) { String name = request.getParameter("Name"); String description = request.getParameter("Description"); String alertType = request.getParameter("AlertType"); if (!StringUtil.isDefined(alertType)) { alertType = "None"; } String rightsUsed = request.getParameter("RightsUsed"); String path = request.getParameter("Path"); String parentId = request.getParameter("ParentId"); NodeDetail topic = new NodeDetail("-1", name, description, null, null, null, "0", "X"); I18NHelper.setI18NInfo(topic, request); if (StringUtil.isDefined(path)) { topic.setType(NodeDetail.FILE_LINK_TYPE); topic.setPath(path); } int rightsDependsOn = -1; if (StringUtil.isDefined(rightsUsed)) { if ("father".equalsIgnoreCase(rightsUsed)) { NodeDetail father = kmelia.getSessionTopic().getNodeDetail(); rightsDependsOn = father.getRightsDependsOn(); } else { rightsDependsOn = 0; } topic.setRightsDependsOn(rightsDependsOn); } NodePK nodePK = kmelia.addSubTopic(topic, alertType, parentId); if (kmelia.isRightsOnTopicsEnabled()) { if (rightsDependsOn == 0) { request.setAttribute("NodeId", nodePK.getId()); destination = getDestination("ViewTopicProfiles", componentSC, request); } else { destination = getDestination("GoToCurrentTopic", componentSC, request); } } else { request.setAttribute("urlToReload", "GoToCurrentTopic"); destination = rootDestination + "closeWindow.jsp"; } } else if ("UpdateTopic".equals(function)) { String name = request.getParameter("Name"); String description = request.getParameter("Description"); String alertType = request.getParameter("AlertType"); if (!StringUtil.isDefined(alertType)) { alertType = "None"; } String id = request.getParameter("ChildId"); String path = request.getParameter("Path"); NodeDetail topic = new NodeDetail(id, name, description, null, null, null, "0", "X"); I18NHelper.setI18NInfo(topic, request); if (StringUtil.isDefined(path)) { topic.setType(NodeDetail.FILE_LINK_TYPE); topic.setPath(path); } kmelia.updateTopicHeader(topic, alertType); if (kmelia.isRightsOnTopicsEnabled()) { int rightsUsed = Integer.parseInt(request.getParameter("RightsUsed")); topic = kmelia.getNodeHeader(id); if (topic.getRightsDependsOn() != rightsUsed) { // rights dependency have changed if (rightsUsed == -1) { kmelia.updateTopicDependency(topic, false); destination = getDestination("GoToCurrentTopic", componentSC, request); } else { kmelia.updateTopicDependency(topic, true); request.setAttribute("NodeId", id); destination = getDestination("ViewTopicProfiles", componentSC, request); } } else { destination = getDestination("GoToCurrentTopic", componentSC, request); } } else { request.setAttribute("urlToReload", "GoToCurrentTopic"); destination = rootDestination + "closeWindow.jsp"; } } else if (function.equals("DeleteTopic")) { String id = request.getParameter("Id"); kmelia.deleteTopic(id); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ViewClone")) { PublicationDetail pubDetail = kmelia.getSessionPublication().getPublication().getPublicationDetail(); // Reload clone and put it into session String cloneId = pubDetail.getCloneId(); UserCompletePublication userPubComplete = kmelia.getUserCompletePublication(cloneId); kmelia.setSessionClone(userPubComplete); request.setAttribute("Publication", userPubComplete); request.setAttribute("Profile", kmelia.getProfile()); request.setAttribute("VisiblePublicationId", pubDetail.getPK().getId()); putXMLDisplayerIntoRequest(userPubComplete.getPublication().getPublicationDetail(), kmelia, request); destination = rootDestination + "clone.jsp"; } else if (function.equals("ViewPublication")) { String id = request.getParameter("PubId"); if (!StringUtil.isDefined(id)) { id = request.getParameter("Id"); if (!StringUtil.isDefined(id)) { id = (String) request.getAttribute("PubId"); } } - boolean checkPath = StringUtil.getBooleanValue(request.getParameter("CheckPath")); - if (checkPath) { - processPath(kmelia, id); - } else { - processPath(kmelia, null); + if (!kmaxMode) { + boolean checkPath = StringUtil.getBooleanValue(request.getParameter("CheckPath")); + if (checkPath) { + processPath(kmelia, id); + } else { + processPath(kmelia, null); + } } UserCompletePublication userPubComplete = null; if (StringUtil.isDefined(id)) { userPubComplete = kmelia.getUserCompletePublication(id, true); kmelia.setSessionPublication(userPubComplete); PublicationDetail pubDetail = userPubComplete.getPublication().getPublicationDetail(); if (pubDetail.haveGotClone()) { UserCompletePublication clone = kmelia.getUserCompletePublication(pubDetail.getCloneId()); kmelia.setSessionClone(clone); } } else { userPubComplete = kmelia.getSessionPublication(); id = userPubComplete.getPublication().getPublicationDetail().getPK().getId(); } if (toolboxMode) { destination = rootDestination + "publicationManager.jsp?Action=UpdateView&PubId=" + id + "&Profile=" + kmelia.getProfile(); } else { List<String> publicationLanguages = kmelia.getPublicationLanguages(); // languages of // publication // header and attachments if (publicationLanguages.contains(kmelia.getCurrentLanguage())) { request.setAttribute("ContentLanguage", kmelia.getCurrentLanguage()); } else { request.setAttribute("ContentLanguage", checkLanguage(kmelia, userPubComplete. getPublication().getPublicationDetail())); } request.setAttribute("Languages", publicationLanguages); // see also management Collection<ForeignPK> links = userPubComplete.getPublication().getLinkList(); HashSet<String> linkedList = new HashSet<String>(); for (ForeignPK link : links) { linkedList.add(link.getId() + "/" + link.getInstanceId()); } // put into session the current list of selected publications (see also) request.getSession().setAttribute(KmeliaConstants.PUB_TO_LINK_SESSION_KEY, linkedList); request.setAttribute("Publication", userPubComplete); request.setAttribute("PubId", id); request.setAttribute("ValidationStep", kmelia.getValidationStep()); request.setAttribute("ValidationType", new Integer(kmelia.getValidationType())); // check if user is writer with approval right (versioning case) request.setAttribute("WriterApproval", Boolean.valueOf(kmelia.isWriterApproval(id))); request.setAttribute("NotificationAllowed", Boolean.valueOf(kmelia.isNotificationAllowed())); // check is requested publication is an alias checkAlias(kmelia, userPubComplete); if (userPubComplete.isAlias()) { request.setAttribute("Profile", "user"); request.setAttribute("IsAlias", "1"); } else { request.setAttribute("Profile", kmelia.getProfile()); } request.setAttribute("Wizard", kmelia.getWizard()); request.setAttribute("Rang", new Integer(kmelia.getRang())); if (kmelia.getSessionPublicationsList() != null) { request.setAttribute("NbPublis", new Integer(kmelia.getSessionPublicationsList().size())); } else { request.setAttribute("NbPublis", new Integer(1)); } putXMLDisplayerIntoRequest(userPubComplete.getPublication().getPublicationDetail(), kmelia, request); String fileAlreadyOpened = (String) request.getAttribute("FileAlreadyOpened"); boolean alreadyOpened = "1".equals(fileAlreadyOpened); String attachmentId = (String) request.getAttribute("AttachmentId"); String documentId = (String) request.getAttribute("DocumentId"); if (!alreadyOpened && kmelia.openSingleAttachmentAutomatically() && !kmelia.isCurrentPublicationHaveContent()) { request.setAttribute("SingleAttachmentURL", kmelia. getFirstAttachmentURLOfCurrentPublication()); } else if (!alreadyOpened && attachmentId != null) { request.setAttribute("SingleAttachmentURL", kmelia.getAttachmentURL(attachmentId)); } else if (!alreadyOpened && documentId != null) { request.setAttribute("SingleAttachmentURL", kmelia.getAttachmentURL(documentId)); } destination = rootDestination + "publication.jsp"; } } else if (function.equals("PreviousPublication")) { // récupération de la publication précédente String pubId = kmelia.getPrevious(); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("NextPublication")) { // récupération de la publication suivante String pubId = kmelia.getNext(); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.startsWith("copy")) { String objectType = request.getParameter("Object"); String objectId = request.getParameter("Id"); if (StringUtil.isDefined(objectType) && "Node".equalsIgnoreCase(objectType)) { kmelia.copyTopic(objectId); } else { kmelia.copyPublication(objectId); } destination = URLManager.getURL(URLManager.CMP_CLIPBOARD) + "Idle.jsp?message=REFRESHCLIPBOARD"; } else if (function.startsWith("cut")) { String objectType = request.getParameter("Object"); String objectId = request.getParameter("Id"); if (StringUtil.isDefined(objectType) && "Node".equalsIgnoreCase(objectType)) { kmelia.cutTopic(objectId); } else { kmelia.cutPublication(objectId); } destination = URLManager.getURL(URLManager.CMP_CLIPBOARD) + "Idle.jsp?message=REFRESHCLIPBOARD"; } else if (function.startsWith("paste")) { kmelia.paste(); destination = URLManager.getURL(URLManager.CMP_CLIPBOARD) + "Idle.jsp"; } else if (function.startsWith("ToAlertUserAttachment")) { // utilisation de alertUser et alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserAttachment: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { String attachmentId = request.getParameter("AttachmentOrDocumentId"); destination = kmelia.initAlertUserAttachment(attachmentId, false); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserAttachment: function = " + function + "=> destination=" + destination); } else if (function.startsWith("ToAlertUserDocument")) { // utilisation de alertUser et alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserDocument: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { String documentId = request.getParameter("AttachmentOrDocumentId"); destination = kmelia.initAlertUserAttachment(documentId, true); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserDocument: function = " + function + "=> destination=" + destination); } else if (function.startsWith("ToAlertUser")) { // utilisation de alertUser et alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUser: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { destination = kmelia.initAlertUser(); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUser: function = " + function + "=> destination=" + destination); } else if (function.equals("ReadingControl")) { PublicationDetail publication = kmelia.getSessionPublication().getPublication().getPublicationDetail(); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Publication", publication); request.setAttribute("UserIds", kmelia.getUserIdsOfTopic()); // paramètre du wizard request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "readingControlManager.jsp"; } else if (function.startsWith("ViewAttachments")) { String flag = kmelia.getProfile(); // Versioning is out of "Always visible publication" mode if (kmelia.isCloneNeeded() && !kmelia.isVersionControlled()) { kmelia.clonePublication(); } // put current publication if (!kmelia.isVersionControlled()) { request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getPublication().getPublicationDetail()); } else { request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPublication(). getPublication().getPublicationDetail()); } // Paramètres du wizard setWizardParams(request, kmelia); // Paramètres de i18n List<String> attachmentLanguages = kmelia.getAttachmentLanguages(); if (attachmentLanguages.contains(kmelia.getCurrentLanguage())) { request.setAttribute("Language", kmelia.getCurrentLanguage()); } else { request.setAttribute("Language", checkLanguage(kmelia)); } request.setAttribute("Languages", attachmentLanguages); request.setAttribute("XmlFormForFiles", kmelia.getXmlFormForFiles()); destination = rootDestination + "attachmentManager.jsp?profile=" + flag; } else if (function.equals("DeletePublication")) { String pubId = (String) request.getParameter("PubId"); kmelia.deletePublication(pubId); if (kmaxMode) { destination = getDestination("Main", kmelia, request); } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else if (function.equals("DeleteClone")) { kmelia.deleteClone(); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ViewValidationSteps")) { request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Publication", kmelia.getSessionPubliOrClone().getPublication(). getPublicationDetail()); request.setAttribute("ValidationSteps", kmelia.getValidationSteps()); request.setAttribute("Role", kmelia.getProfile()); destination = rootDestination + "validationSteps.jsp"; } else if (function.equals("ValidatePublication")) { String pubId = kmelia.getSessionPublication().getPublication().getPublicationDetail().getPK().getId(); SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function + " pubId=" + pubId); boolean validationComplete = kmelia.validatePublication(pubId); if (validationComplete) { request.setAttribute("Action", "ValidationComplete"); } else { request.setAttribute("Action", "ValidationInProgress"); } request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ForceValidatePublication")) { String pubId = kmelia.getSessionPublication().getPublication().getPublicationDetail().getPK().getId(); kmelia.forcePublicationValidation(pubId); request.setAttribute("Action", "ValidationComplete"); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("WantToRefusePubli")) { PublicationDetail pubDetail = kmelia.getSessionPubliOrClone().getPublication().getPublicationDetail(); request.setAttribute("PublicationToRefuse", pubDetail); destination = rootDestination + "refusalMotive.jsp"; } else if (function.equals("Unvalidate")) { String motive = request.getParameter("Motive"); String pubId = kmelia.getSessionPublication().getPublication().getPublicationDetail().getPK().getId(); SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function + " pubId=" + pubId); kmelia.unvalidatePublication(pubId, motive); request.setAttribute("Action", "Unvalidate"); if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } else if (function.equals("WantToSuspendPubli")) { String pubId = request.getParameter("PubId"); PublicationDetail pubDetail = kmelia.getPublicationDetail(pubId); request.setAttribute("PublicationToSuspend", pubDetail); destination = rootDestination + "defermentMotive.jsp"; } else if (function.equals("SuspendPublication")) { String motive = request.getParameter("Motive"); String pubId = request.getParameter("PubId"); kmelia.suspendPublication(pubId, motive); request.setAttribute("Action", "Suspend"); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("DraftIn")) { kmelia.draftInPublication(); if (kmelia.getSessionClone() != null) { // draft have generate a clone destination = getDestination("ViewClone", componentSC, request); } else { String pubId = kmelia.getSessionPubliOrClone().getPublication().getPublicationDetail().getPK().getId(); String flag = kmelia.getProfile(); String from = request.getParameter("From"); if (StringUtil.isDefined(from)) { destination = getDestination(from, componentSC, request); } else { destination = rootDestination + "publicationManager.jsp?Action=UpdateView&PubId=" + pubId + "&Profile=" + flag; } } } else if (function.equals("DraftOut")) { kmelia.draftOutPublication(); destination = getDestination("ViewPublication", componentSC, request); } else if (function.equals("ToTopicWysiwyg")) { String topicId = request.getParameter("Id"); String subTopicId = request.getParameter("ChildId"); String flag = kmelia.getProfile(); NodeDetail topic = kmelia.getSubTopicDetail(subTopicId); destination = request.getScheme() + "://" + kmelia.getServerNameAndPort() + URLManager.getApplicationURL() + "/wysiwyg/jsp/htmlEditor.jsp?"; destination += "SpaceId=" + kmelia.getSpaceId(); destination += "&SpaceName=" + URLEncoder.encode(kmelia.getSpaceLabel(), "UTF-8"); destination += "&ComponentId=" + kmelia.getComponentId(); destination += "&ComponentName=" + URLEncoder.encode(kmelia.getComponentLabel(), "UTF-8"); destination += "&BrowseInfo=" + URLEncoder.encode(kmelia.getSessionPathString() + " > " + topic.getName() + " > " + kmelia.getString("TopicWysiwyg"), "UTF-8"); destination += "&ObjectId=Node_" + subTopicId; destination += "&Language=fr"; destination += "&ReturnUrl=" + URLEncoder.encode(URLManager.getApplicationURL() + URLManager.getURL(kmelia.getSpaceId(), kmelia.getComponentId()) + "FromTopicWysiwyg?Action=Search&Id=" + topicId + "&ChildId=" + subTopicId + "&Profile=" + flag, "UTF-8"); } else if (function.equals("FromTopicWysiwyg")) { String subTopicId = request.getParameter("ChildId"); kmelia.processTopicWysiwyg(subTopicId); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("TopicUp")) { String subTopicId = request.getParameter("ChildId"); kmelia.changeSubTopicsOrder("up", subTopicId); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("TopicDown")) { String subTopicId = request.getParameter("ChildId"); kmelia.changeSubTopicsOrder("down", subTopicId); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ChangeTopicStatus")) { String subTopicId = request.getParameter("ChildId"); String newStatus = request.getParameter("Status"); String recursive = request.getParameter("Recursive"); if (recursive != null && recursive.equals("1")) { kmelia.changeTopicStatus(newStatus, subTopicId, true); } else { kmelia.changeTopicStatus(newStatus, subTopicId, false); } destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ViewOnly")) { String id = request.getParameter("documentId"); destination = rootDestination + "publicationViewOnly.jsp?Id=" + id; } else if (function.equals("SeeAlso")) { String action = request.getParameter("Action"); if (!StringUtil.isDefined(action)) { action = "LinkAuthorView"; } request.setAttribute("Action", action); // check if requested publication is an alias UserCompletePublication userPubComplete = kmelia.getSessionPublication(); checkAlias(kmelia, userPubComplete); if (userPubComplete.isAlias()) { request.setAttribute("Profile", "user"); request.setAttribute("IsAlias", "1"); } else { request.setAttribute("Profile", kmelia.getProfile()); } // paramètres du wizard request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "seeAlso.jsp"; } else if (function.equals("DeleteSeeAlso")) { String[] pubIds = request.getParameterValues("PubIds"); List<ForeignPK> infoLinks = new ArrayList<ForeignPK>(); StringTokenizer tokens = null; for (String pubId : pubIds) { tokens = new StringTokenizer(pubId, "/"); infoLinks.add(new ForeignPK(tokens.nextToken(), tokens.nextToken())); } if (infoLinks.size() > 0) { kmelia.deleteInfoLinks(kmelia.getSessionPublication().getId(), infoLinks); } destination = getDestination("SeeAlso", kmelia, request); } else if (function.equals("ImportFileUpload")) { destination = processFormUpload(kmelia, request, rootDestination, false); } else if (function.equals("ImportFilesUpload")) { destination = processFormUpload(kmelia, request, rootDestination, true); } else if (function.equals("ExportAttachementsToPDF")) { String topicId = request.getParameter("TopicId"); // build an exploitable list by importExportPeas SilverTrace.info("kmelia", "KmeliaSessionController.getAllVisiblePublicationsByTopic()", "root.MSG_PARAM_VALUE", "topicId =" + topicId); List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublicationsByTopic(topicId); request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("RootId", topicId); // Go to importExportPeas destination = "/RimportExportPeas/jsp/ExportPDF"; } else if (function.equals("NewPublication")) { destination = rootDestination + "publicationManager.jsp?Action=New&CheckPath=0&Profile=" + kmelia.getProfile(); } else if (function.equals("AddPublication")) { List<FileItem> parameters = FileUploadUtil.parseRequest(request); // create publication PublicationDetail pubDetail = getPublicationDetail(parameters, kmelia); String newPubId = kmelia.createPublication(pubDetail); // create vignette if exists processVignette(parameters, kmelia, pubDetail.getInstanceId(), Integer.valueOf(newPubId)); request.setAttribute("PubId", newPubId); processPath(kmelia, newPubId); String wizard = kmelia.getWizard(); if ("progress".equals(wizard)) { UserCompletePublication userPubComplete = kmelia.getUserCompletePublication(newPubId); kmelia.setSessionPublication(userPubComplete); String position = FileUploadUtil.getParameter(parameters, "Position"); setWizardParams(request, kmelia); request.setAttribute("Position", position); request.setAttribute("Publication", userPubComplete); request.setAttribute("Profile", kmelia.getProfile()); destination = getDestination("WizardNext", kmelia, request); } else { StringBuffer requestURI = request.getRequestURL(); destination = requestURI.substring(0, requestURI.indexOf("AddPublication")) + "ViewPublication?PubId=" + newPubId; } } else if (function.equals("UpdatePublication")) { List<FileItem> parameters = FileUploadUtil.parseRequest(request); PublicationDetail pubDetail = getPublicationDetail(parameters, kmelia); kmelia.updatePublication(pubDetail); String id = pubDetail.getPK().getId(); processVignette(parameters, kmelia, pubDetail.getInstanceId(), Integer.valueOf(id)); String wizard = kmelia.getWizard(); if (wizard.equals("progress")) { UserCompletePublication userPubComplete = kmelia.getUserCompletePublication(id); String position = FileUploadUtil.getParameter(parameters, "Position"); setWizardParams(request, kmelia); request.setAttribute("Position", position); request.setAttribute("Publication", userPubComplete); request.setAttribute("Profile", kmelia.getProfile()); destination = getDestination("WizardNext", kmelia, request); } else { if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else { request.setAttribute("PubId", id); request.setAttribute("CheckPath", "1"); destination = getDestination("ViewPublication", kmelia, request); } } } else if (function.equals("SelectValidator")) { destination = kmelia.initUPToSelectValidator(""); } else if (function.equals("Comments")) { String id = request.getParameter("PubId"); String flag = kmelia.getProfile(); if (!kmaxMode) { processPath(kmelia, id); } // paramètre du wizard request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "comments.jsp?PubId=" + id + "&Profile=" + flag; } else if (function.equals("PublicationPaths")) { // paramètre du wizard request.setAttribute("Wizard", kmelia.getWizard()); PublicationDetail publication = kmelia.getSessionPublication().getPublication().getPublicationDetail(); String pubId = publication.getPK().getId(); request.setAttribute("Publication", publication); request.setAttribute("PathList", kmelia.getPublicationFathers(pubId)); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Topics", kmelia.getAllTopics()); List<Alias> aliases = kmelia.getAliases(); request.setAttribute("Aliases", aliases); request.setAttribute("OtherComponents", kmelia.getOtherComponents(aliases)); destination = rootDestination + "publicationPaths.jsp"; } else if (function.equals("SetPath")) { String[] topics = request.getParameterValues("topicChoice"); String loadedComponentIds = request.getParameter("LoadedComponentIds"); Alias alias = null; List<Alias> aliases = new ArrayList<Alias>(); for (int i = 0; topics != null && i < topics.length; i++) { String topicId = topics[i]; SilverTrace.debug("kmelia", "KmeliaRequestRouter.setPath()", "root.MSG_GEN_PARAM_VALUE", "topicId = " + topicId); StringTokenizer tokenizer = new StringTokenizer(topicId, ","); String nodeId = tokenizer.nextToken(); String instanceId = tokenizer.nextToken(); alias = new Alias(nodeId, instanceId); alias.setUserId(kmelia.getUserId()); aliases.add(alias); } // Tous les composants ayant un alias n'ont pas forcément été chargés List<Alias> oldAliases = kmelia.getAliases(); Alias oldAlias; for (int a = 0; a < oldAliases.size(); a++) { oldAlias = oldAliases.get(a); if (loadedComponentIds.indexOf(oldAlias.getInstanceId()) == -1) { // le composant de l'alias n'a pas été chargé aliases.add(oldAlias); } } kmelia.setAliases(aliases); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ShowAliasTree")) { String componentId = request.getParameter("ComponentId"); request.setAttribute("Tree", kmelia.getAliasTreeview(componentId)); request.setAttribute("Aliases", kmelia.getAliases()); destination = rootDestination + "treeview4PublicationPaths.jsp"; } else if (function.equals("AddLinksToPublication")) { String id = request.getParameter("PubId"); String topicId = request.getParameter("TopicId"); HashSet<String> list = (HashSet<String>) request.getSession().getAttribute( KmeliaConstants.PUB_TO_LINK_SESSION_KEY); int nb = kmelia.addPublicationsToLink(id, list); request.setAttribute("NbLinks", Integer.toString(nb)); destination = rootDestination + "publicationLinksManager.jsp?Action=Add&Id=" + topicId; } else if (function.equals("ExportComponent")) { if (kmaxMode) { destination = getDestination("KmaxExportComponent", kmelia, request); } else { // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublications(); request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("RootId", "0"); // Go to importExportPeas destination = "/RimportExportPeas/jsp/ExportItems"; } } else if (function.equals("ExportTopic")) { if (kmaxMode) { destination = getDestination("KmaxExportPublications", kmelia, request); } else { // récupération du topicId String topicId = request.getParameter("TopicId"); // build an exploitable list by importExportPeas SilverTrace.info("kmelia", "KmeliaSessionController.getAllVisiblePublicationsByTopic()", "root.MSG_PARAM_VALUE", "topicId =" + topicId); List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublicationsByTopic(topicId); request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("RootId", topicId); // Go to importExportPeas destination = "/RimportExportPeas/jsp/ExportItems"; } } else if (function.equals("ToPubliContent")) { CompletePublication completePublication = kmelia.getSessionPubliOrClone().getPublication(); if (completePublication.getModelDetail() != null) { destination = getDestination("ToDBModel", kmelia, request); } else if (WysiwygController.haveGotWysiwyg(kmelia.getSpaceId(), kmelia.getComponentId(), completePublication.getPublicationDetail().getPK().getId())) { destination = getDestination("ToWysiwyg", kmelia, request); } else { String infoId = completePublication.getPublicationDetail().getInfoId(); if (infoId == null || "0".equals(infoId)) { List<String> usedModels = (List<String>) kmelia.getModelUsed(); if (usedModels.size() == 1) { String modelId = usedModels.get(0); if ("WYSIWYG".equals(modelId)) { // Wysiwyg content destination = getDestination("ToWysiwyg", kmelia, request); } else if (isInteger(modelId)) { // DB template ModelDetail model = kmelia.getModelDetail(modelId); request.setAttribute("ModelDetail", model); destination = getDestination("ToDBModel", kmelia, request); } else { // XML template setXMLForm(request, kmelia, modelId); // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getPublication().getPublicationDetail()); // Parametres du Wizard setWizardParams(request, kmelia); destination = rootDestination + "xmlForm.jsp"; } } else { destination = getDestination("ListModels", kmelia, request); } } else { destination = getDestination("GoToXMLForm", kmelia, request); } } } else if (function.equals("ListModels")) { Collection<String> modelUsed = kmelia.getModelUsed(); Collection<PublicationTemplate> listModelXml = new ArrayList<PublicationTemplate>(); List<PublicationTemplate> templates = new ArrayList<PublicationTemplate>(); try { templates = getPublicationTemplateManager().getPublicationTemplates(); // recherche de la liste des modèles utilisables PublicationTemplate xmlForm; Iterator<PublicationTemplate> iterator = templates.iterator(); while (iterator.hasNext()) { xmlForm = iterator.next(); // recherche si le modèle est dans la liste if (modelUsed.contains(xmlForm.getFileName())) { listModelXml.add(xmlForm); } } request.setAttribute("XMLForms", listModelXml); } catch (Exception e) { SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination(ListModels)", "root.MSG_GEN_PARAM_VALUE", "", e); } // put dbForms Collection<ModelDetail> dbForms = kmelia.getAllModels(); // recherche de la liste des modèles utilisables Collection<ModelDetail> listModelForm = new ArrayList<ModelDetail>(); ModelDetail modelDetail; Iterator<ModelDetail> iterator = dbForms.iterator(); while (iterator.hasNext()) { modelDetail = iterator.next(); // recherche si le modèle est dans la liste if (modelUsed.contains(modelDetail.getId())) { listModelForm.add(modelDetail); } } request.setAttribute("DBForms", listModelForm); // recherche si modele Wysiwyg utilisable boolean wysiwygValid = false; if (modelUsed.contains("WYSIWYG")) { wysiwygValid = true; } request.setAttribute("WysiwygValid", Boolean.valueOf(wysiwygValid)); // s'il n'y a pas de modèles selectionnés, les présenter tous if (((listModelXml == null) || (listModelXml.isEmpty())) && ((listModelForm == null) || (listModelForm.isEmpty())) && (!wysiwygValid)) { request.setAttribute("XMLForms", templates); request.setAttribute("DBForms", dbForms); request.setAttribute("WysiwygValid", Boolean.TRUE); } // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPublication(). getPublication().getPublicationDetail()); // Paramètres du wizard setWizardParams(request, kmelia); destination = rootDestination + "modelsList.jsp"; } else if (function.equals("ModelUsed")) { try { List<PublicationTemplate> templates = getPublicationTemplateManager().getPublicationTemplates(); request.setAttribute("XMLForms", templates); } catch (Exception e) { SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination(ModelUsed)", "root.MSG_GEN_PARAM_VALUE", "", e); } // put dbForms Collection<ModelDetail> dbForms = kmelia.getAllModels(); request.setAttribute("DBForms", dbForms); Collection<String> modelUsed = kmelia.getModelUsed(); request.setAttribute("ModelUsed", modelUsed); destination = rootDestination + "modelUsedList.jsp"; } else if (function.equals("SelectModel")) { Object o = request.getParameterValues("modelChoice"); if (o != null) { kmelia.addModelUsed((String[]) o); } destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ToWysiwyg")) { if (kmelia.isCloneNeeded()) { kmelia.clonePublication(); } // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getPublication().getPublicationDetail()); // Parametres du Wizard setWizardParams(request, kmelia); request.setAttribute("CurrentLanguage", checkLanguage(kmelia)); destination = rootDestination + "toWysiwyg.jsp"; } else if (function.equals("FromWysiwyg")) { String id = request.getParameter("PubId"); // Parametres du Wizard String wizard = kmelia.getWizard(); setWizardParams(request, kmelia); if (wizard.equals("progress")) { request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { if (kmelia.getSessionClone() != null && id.equals(kmelia.getSessionClone().getPublication().getPublicationDetail().getPK(). getId())) { destination = getDestination("ViewClone", componentSC, request); } else { destination = getDestination("ViewPublication", componentSC, request); } } } else if (function.equals("ToDBModel")) { String modelId = request.getParameter("ModelId"); if (StringUtil.isDefined(modelId)) { ModelDetail model = kmelia.getModelDetail(modelId); request.setAttribute("ModelDetail", model); } // put current publication request.setAttribute("CompletePublication", kmelia.getSessionPubliOrClone().getPublication()); request.setAttribute("NotificationAllowed", Boolean.valueOf(kmelia.isNotificationAllowed())); // Paramètres du wizard setWizardParams(request, kmelia); destination = rootDestination + "modelManager.jsp"; } else if (function.equals("UpdateDBModelContent")) { ResourceLocator publicationSettings = kmelia.getPublicationSettings(); List<InfoTextDetail> textDetails = new ArrayList<InfoTextDetail>(); List<InfoImageDetail> imageDetails = new ArrayList<InfoImageDetail>(); String theText = null; int textOrder = 0; int imageOrder = 0; String logicalName = ""; String physicalName = ""; long size = 0; String type = ""; String mimeType = ""; File dir = null; InfoDetail infos = null; boolean imageTrouble = false; boolean runOnUnix = !FileUtil.isWindows(); List<FileItem> parameters = FileUploadUtil.parseRequest(request); String modelId = FileUploadUtil.getParameter(parameters, "ModelId"); // Parametres du Wizard setWizardParams(request, kmelia); Iterator<FileItem> iter = parameters.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField() && item.getFieldName().startsWith("WATXTVAR")) { theText = item.getString(); textOrder = new Integer(item.getFieldName().substring(8, item.getFieldName().length())).intValue(); textDetails.add(new InfoTextDetail(null, new Integer(textOrder).toString(), null, theText)); } else if (!item.isFormField()) { logicalName = item.getName(); if (logicalName != null && logicalName.length() > 0) { // the part actually contained a file if (runOnUnix) { logicalName = logicalName.replace('\\', File.separatorChar); SilverTrace.info("kmelia", "KmeliaRequestRouter.UpdateDBModelContent", "root.MSG_GEN_PARAM_VALUE", "fileName on Unix = " + logicalName); } logicalName = logicalName.substring(logicalName.lastIndexOf(File.separator) + 1, logicalName. length()); type = logicalName.substring(logicalName.lastIndexOf(".") + 1, logicalName.length()); physicalName = new Long(new Date().getTime()).toString() + "." + type; mimeType = item.getContentType(); size = item.getSize(); dir = new File(FileRepositoryManager.getAbsolutePath(kmelia.getComponentId()) + publicationSettings.getString("imagesSubDirectory") + File.separator + physicalName); if (type.equalsIgnoreCase("gif") || type.equalsIgnoreCase("jpg") || type.equalsIgnoreCase("jpeg") || type.equalsIgnoreCase("png")) { item.write(dir); imageOrder++; if (size > 0) { imageDetails.add(new InfoImageDetail(null, new Integer(imageOrder).toString(), null, physicalName, logicalName, "", mimeType, size)); imageTrouble = false; } else { imageTrouble = true; } } else { imageTrouble = true; } } else { // the field did not contain a file } } } infos = new InfoDetail(null, textDetails, imageDetails, null, ""); CompletePublication completePub = kmelia.getSessionPubliOrClone().getPublication(); if (completePub.getModelDetail() == null) { kmelia.createInfoModelDetail("useless", modelId, infos); } else { kmelia.updateInfoDetail("useless", infos); } if (imageTrouble) { request.setAttribute("ImageTrouble", Boolean.TRUE); } String wizard = kmelia.getWizard(); if (wizard.equals("progress")) { request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { destination = getDestination("ToDBModel", kmelia, request); } } else if (function.equals("GoToXMLForm")) { String xmlFormName = request.getParameter("Name"); setXMLForm(request, kmelia, xmlFormName); // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getPublication().getPublicationDetail()); // Parametres du Wizard setWizardParams(request, kmelia); destination = rootDestination + "xmlForm.jsp"; } else if (function.equals("UpdateXMLForm")) { if (kmelia.isCloneNeeded()) { kmelia.clonePublication(); } if (!StringUtil.isDefined(request.getCharacterEncoding())) { request.setCharacterEncoding("UTF-8"); } String encoding = request.getCharacterEncoding(); List<FileItem> items = FileUploadUtil.parseRequest(request); PublicationDetail pubDetail = kmelia.getSessionPubliOrClone().getPublication().getPublicationDetail(); String xmlFormShortName = null; // Is it the creation of the content or an update ? String infoId = pubDetail.getInfoId(); if (infoId == null || "0".equals(infoId)) { String xmlFormName = FileUploadUtil.getParameter(items, "Name", null, encoding); // The publication have no content // We have to register xmlForm to publication xmlFormShortName = xmlFormName.substring(xmlFormName.indexOf("/") + 1, xmlFormName.indexOf(".")); pubDetail.setInfoId(xmlFormShortName); kmelia.updatePublication(pubDetail); } else { xmlFormShortName = pubDetail.getInfoId(); } String pubId = pubDetail.getPK().getId(); PublicationTemplate pub = getPublicationTemplateManager().getPublicationTemplate(kmelia.getComponentId() + ":" + xmlFormShortName); RecordSet set = pub.getRecordSet(); Form form = pub.getUpdateForm(); String language = checkLanguage(kmelia, pubDetail); DataRecord data = set.getRecord(pubId, language); if (data == null) { data = set.getEmptyRecord(); data.setId(pubId); data.setLanguage(language); } PagesContext context = new PagesContext("myForm", "3", kmelia.getLanguage(), false, kmelia.getComponentId(), kmelia.getUserId()); context.setEncoding("UTF-8"); if (!kmaxMode) { context.setNodeId(kmelia.getSessionTopic().getNodeDetail().getNodePK().getId()); } context.setObjectId(pubId); context.setContentLanguage(kmelia.getCurrentLanguage()); form.update(items, data, context); set.save(data); // update publication to change updateDate and updaterId kmelia.updatePublication(pubDetail); // Parametres du Wizard setWizardParams(request, kmelia); if (kmelia.getWizard().equals("progress")) { // on est en mode Wizard request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else if (kmaxMode) { destination = getDestination("ViewAttachments", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } } else if (function.startsWith("ToOrderPublications")) { List<UserPublication> publications = kmelia.getSessionPublicationsList(); request.setAttribute("Publications", publications); request.setAttribute("Path", kmelia.getSessionPath()); destination = rootDestination + "orderPublications.jsp"; } else if (function.startsWith("OrderPublications")) { String sortedIds = request.getParameter("sortedIds"); StringTokenizer tokenizer = new StringTokenizer(sortedIds, ","); List<String> ids = new ArrayList<String>(); while (tokenizer.hasMoreTokens()) { ids.add(tokenizer.nextToken()); } kmelia.orderPublications(ids); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ToOrderTopics")) { String id = request.getParameter("Id"); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(id))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { TopicDetail topic = kmelia.getTopic(id); request.setAttribute("Nodes", topic.getNodeDetail().getChildrenDetails()); destination = rootDestination + "orderTopics.jsp"; } } else if (function.startsWith("Wizard")) { destination = processWizard(function, kmelia, request, rootDestination); } else if (function.equals("ViewPdcPositions")) { // Parametres du Wizard setWizardParams(request, kmelia); destination = rootDestination + "pdcPositions.jsp"; } else if (function.equals("ViewTopicProfiles")) { String role = request.getParameter("Role"); if (!StringUtil.isDefined(role)) { role = SilverpeasRole.admin.toString(); } String id = request.getParameter("NodeId"); if (!StringUtil.isDefined(id)) { id = (String) request.getAttribute("NodeId"); } request.setAttribute("Profiles", kmelia.getTopicProfiles(id)); NodeDetail topic = kmelia.getNodeHeader(id); ProfileInst profile = null; if (topic.haveInheritedRights()) { profile = kmelia.getTopicProfile(role, Integer.toString(topic.getRightsDependsOn())); request.setAttribute("RightsDependsOn", "AnotherTopic"); } else if (topic.haveLocalRights()) { profile = kmelia.getTopicProfile(role, Integer.toString(topic.getRightsDependsOn())); request.setAttribute("RightsDependsOn", "ThisTopic"); } else { profile = kmelia.getProfile(role); // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } request.setAttribute("CurrentProfile", profile); request.setAttribute("Groups", kmelia.groupIds2Groups(profile.getAllGroups())); request.setAttribute("Users", kmelia.userIds2Users(profile.getAllUsers())); request.setAttribute("Path", kmelia.getSessionPath()); request.setAttribute("NodeDetail", topic); destination = rootDestination + "topicProfiles.jsp"; } else if (function.equals("TopicProfileSelection")) { String role = request.getParameter("Role"); String nodeId = request.getParameter("NodeId"); try { kmelia.initUserPanelForTopicProfile(role, nodeId); } catch (Exception e) { SilverTrace.warn("jobStartPagePeas", "JobStartPagePeasRequestRouter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } destination = Selection.getSelectionURL(Selection.TYPE_USERS_GROUPS); } else if (function.equals("TopicProfileSetUsersAndGroups")) { String role = request.getParameter("Role"); String nodeId = request.getParameter("NodeId"); kmelia.updateTopicRole(role, nodeId); request.setAttribute("urlToReload", "ViewTopicProfiles?Role=" + role + "&NodeId=" + nodeId); destination = rootDestination + "closeWindow.jsp"; } else if (function.equals("TopicProfileRemove")) { String profileId = request.getParameter("Id"); kmelia.deleteTopicRole(profileId); destination = getDestination("ViewTopicProfiles", componentSC, request); } else if (function.equals("CloseWindow")) { destination = rootDestination + "closeWindow.jsp"; } else if (function.startsWith("UpdateChain")) { destination = processUpdateChainOperation(rootDestination, function, kmelia, request); } /*************************** * Kmax mode **************************/ else if (function.equals("KmaxMain")) { destination = rootDestination + "kmax.jsp?Action=KmaxView&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAxisManager")) { destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxViewAxis&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAddAxis")) { String newAxisName = request.getParameter("Name"); String newAxisDescription = request.getParameter("Description"); NodeDetail axis = new NodeDetail("-1", newAxisName, newAxisDescription, DateUtil.today2SQLDate(), kmelia. getUserId(), null, "0", "X"); // I18N I18NHelper.setI18NInfo(axis, request); kmelia.addAxis(axis); request.setAttribute("urlToReload", "KmaxAxisManager"); destination = rootDestination + "closeWindow.jsp"; } else if (function.equals("KmaxUpdateAxis")) { String axisId = request.getParameter("AxisId"); String newAxisName = request.getParameter("AxisName"); String newAxisDescription = request.getParameter("AxisDescription"); NodeDetail axis = new NodeDetail(axisId, newAxisName, newAxisDescription, null, null, null, "0", "X"); // I18N I18NHelper.setI18NInfo(axis, request); kmelia.updateAxis(axis); destination = getDestination("KmaxAxisManager", componentSC, request); } else if (function.equals("KmaxDeleteAxis")) { String axisId = request.getParameter("AxisId"); kmelia.deleteAxis(axisId); destination = getDestination("KmaxAxisManager", componentSC, request); } else if (function.equals("KmaxManageAxis")) { String axisId = request.getParameter("AxisId"); String translation = request.getParameter("Translation"); request.setAttribute("Translation", translation); destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxManageAxis&Profile=" + kmelia.getProfile() + "&AxisId=" + axisId; } else if (function.equals("KmaxManagePosition")) { String positionId = request.getParameter("PositionId"); String translation = request.getParameter("Translation"); request.setAttribute("Translation", translation); destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxManagePosition&Profile=" + kmelia.getProfile() + "&PositionId=" + positionId; } else if (function.equals("KmaxAddPosition")) { String axisId = request.getParameter("AxisId"); String newPositionName = request.getParameter("Name"); String newPositionDescription = request.getParameter("Description"); String translation = request.getParameter("Translation"); NodeDetail position = new NodeDetail("toDefine", newPositionName, newPositionDescription, null, null, null, "0", "X"); // I18N I18NHelper.setI18NInfo(position, request); kmelia.addPosition(axisId, position); request.setAttribute("AxisId", axisId); request.setAttribute("Translation", translation); destination = getDestination("KmaxManageAxis", componentSC, request); } else if (function.equals("KmaxUpdatePosition")) { String positionId = request.getParameter("PositionId"); String positionName = request.getParameter("PositionName"); String positionDescription = request.getParameter("PositionDescription"); NodeDetail position = new NodeDetail(positionId, positionName, positionDescription, null, null, null, "0", "X"); // I18N I18NHelper.setI18NInfo(position, request); kmelia.updatePosition(position); destination = getDestination("KmaxAxisManager", componentSC, request); } else if (function.equals("KmaxDeletePosition")) { String positionId = request.getParameter("PositionId"); kmelia.deletePosition(positionId); destination = getDestination("KmaxAxisManager", componentSC, request); } else if (function.equals("KmaxViewUnbalanced")) { List<UserPublication> publications = kmelia.getUnbalancedPublications(); kmelia.setSessionPublicationsList(publications); kmelia.orderPubs(); destination = rootDestination + "kmax.jsp?Action=KmaxViewUnbalanced&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxViewBasket")) { TopicDetail basket = kmelia.getTopic("1"); List<UserPublication> publications = (List<UserPublication>) basket.getPublicationDetails(); kmelia.setSessionPublicationsList(publications); kmelia.orderPubs(); destination = rootDestination + "kmax.jsp?Action=KmaxViewBasket&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxViewToValidate")) { destination = rootDestination + "kmax.jsp?Action=KmaxViewToValidate&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxSearch")) { String axisValuesStr = request.getParameter("SearchCombination"); if (!StringUtil.isDefined(axisValuesStr)) { axisValuesStr = (String) request.getAttribute("SearchCombination"); } String timeCriteria = request.getParameter("TimeCriteria"); SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "axisValuesStr = " + axisValuesStr + " timeCriteria=" + timeCriteria); List<String> combination = kmelia.getCombination(axisValuesStr); List<UserPublication> publications = null; if (StringUtil.isDefined(timeCriteria) && !timeCriteria.equals("X")) { publications = kmelia.search(combination, new Integer(timeCriteria).intValue()); } else { publications = kmelia.search(combination); } SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "publications = " + publications + " Combination=" + combination + " timeCriteria=" + timeCriteria); kmelia.setIndexOfFirstPubToDisplay("0"); kmelia.orderPubs(); kmelia.setSessionCombination(combination); kmelia.setSessionTimeCriteria(timeCriteria); destination = rootDestination + "kmax.jsp?Action=KmaxSearchResult&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxSearchResult")) { if (kmelia.getSessionCombination() == null) { destination = getDestination("KmaxMain", kmelia, request); } else { destination = rootDestination + "kmax.jsp?Action=KmaxSearchResult&Profile=" + kmelia.getProfile(); } } else if (function.equals("KmaxViewCombination")) { setWizardParams(request, kmelia); request.setAttribute("CurrentCombination", kmelia.getCurrentCombination()); destination = rootDestination + "kmax_viewCombination.jsp?Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAddCoordinate")) { String pubId = request.getParameter("PubId"); String axisValuesStr = request.getParameter("SearchCombination"); StringTokenizer st = new StringTokenizer(axisValuesStr, ","); List<String> combination = new ArrayList<String>(); String axisValue = ""; while (st.hasMoreTokens()) { axisValue = st.nextToken(); // axisValue is xx/xx/xx where xx are nodeId axisValue = axisValue.substring(axisValue.lastIndexOf('/') + 1, axisValue.length()); combination.add(axisValue); } kmelia.addPublicationToCombination(pubId, combination); // Store current combination kmelia.setCurrentCombination(kmelia.getCombination(axisValuesStr)); destination = getDestination("KmaxViewCombination", kmelia, request); } else if (function.equals("KmaxDeleteCoordinate")) { String coordinateId = request.getParameter("CoordinateId"); String pubId = request.getParameter("PubId"); SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "coordinateId = " + coordinateId + " PubId=" + pubId); kmelia.deletePublicationFromCombination(pubId, coordinateId); destination = getDestination("KmaxViewCombination", kmelia, request); } else if (function.equals("KmaxExportComponent")) { // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublications(); request.setAttribute("selectedResultsWa", publicationsIds); // Go to importExportPeas destination = "/RimportExportPeas/jsp/KmaxExportComponent"; } else if (function.equals("KmaxExportPublications")) { // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getCurrentPublicationsList(); List<String> combination = kmelia.getSessionCombination(); // get the time axis String timeCriteria = null; if (kmelia.isTimeAxisUsed() && StringUtil.isDefined(kmelia.getSessionTimeCriteria())) { ResourceLocator timeSettings = new ResourceLocator("com.stratelia.webactiv.kmelia.multilang.timeAxisBundle", kmelia. getLanguage()); if (kmelia.getSessionTimeCriteria().equals("X")) { timeCriteria = null; } else { timeCriteria = "<b>" + kmelia.getString("TimeAxis") + "</b> > " + timeSettings.getString(kmelia.getSessionTimeCriteria(), ""); } } request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("Combination", combination); request.setAttribute("TimeCriteria", timeCriteria); // Go to importExportPeas destination = "/RimportExportPeas/jsp/KmaxExportPublications"; }/************ End Kmax Mode *****************/ else { destination = rootDestination + function; } if (profileError) { String sessionTimeout = GeneralPropertiesManager.getGeneralResourceLocator().getString("sessionTimeout"); destination = sessionTimeout; } SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "destination = " + destination); } catch (Exception exce_all) { request.setAttribute("javax.servlet.jsp.jspException", exce_all); return "/admin/jsp/errorpageMain.jsp"; } return destination; } private String getDocumentNotFoundDestination(KmeliaSessionController kmelia, HttpServletRequest request) { request.setAttribute("ComponentId", kmelia.getComponentId()); return "/admin/jsp/documentNotFound.jsp"; } private PublicationDetail getPublicationDetail(List<FileItem> parameters, KmeliaSessionController kmelia) throws Exception { String id = FileUploadUtil.getParameter(parameters, "PubId"); String status = FileUploadUtil.getParameter(parameters, "Status"); String name = FileUploadUtil.getParameter(parameters, "Name"); String description = FileUploadUtil.getParameter(parameters, "Description"); String keywords = FileUploadUtil.getParameter(parameters, "Keywords"); String beginDate = FileUploadUtil.getParameter(parameters, "BeginDate"); String endDate = FileUploadUtil.getParameter(parameters, "EndDate"); String version = FileUploadUtil.getParameter(parameters, "Version"); String importance = FileUploadUtil.getParameter(parameters, "Importance"); String beginHour = FileUploadUtil.getParameter(parameters, "BeginHour"); String endHour = FileUploadUtil.getParameter(parameters, "EndHour"); String author = FileUploadUtil.getParameter(parameters, "Author"); String targetValidatorId = FileUploadUtil.getParameter(parameters, "ValideurId"); String tempId = FileUploadUtil.getParameter(parameters, "TempId"); String infoId = FileUploadUtil.getParameter(parameters, "InfoId"); String draftOutDate = FileUploadUtil.getParameter(parameters, "DraftOutDate"); Date jBeginDate = null; Date jEndDate = null; Date jDraftOutDate = null; if (StringUtil.isDefined(beginDate)) { jBeginDate = DateUtil.stringToDate(beginDate, kmelia.getLanguage()); } if (StringUtil.isDefined(endDate)) { jEndDate = DateUtil.stringToDate(endDate, kmelia.getLanguage()); } if (StringUtil.isDefined(draftOutDate)) { jDraftOutDate = DateUtil.stringToDate(draftOutDate, kmelia.getLanguage()); } String pubId = "X"; if (StringUtil.isDefined(id)) { pubId = id; } PublicationDetail pubDetail = new PublicationDetail(pubId, name, description, null, jBeginDate, jEndDate, null, importance, version, keywords, "", status, "", author); pubDetail.setBeginHour(beginHour); pubDetail.setEndHour(endHour); pubDetail.setStatus(status); pubDetail.setDraftOutDate(jDraftOutDate); if (StringUtil.isDefined(targetValidatorId)) { pubDetail.setTargetValidatorId(targetValidatorId); } pubDetail.setCloneId(tempId); if (StringUtil.isDefined(infoId)) { pubDetail.setInfoId(infoId); } I18NHelper.setI18NInfo(pubDetail, parameters); return pubDetail; } private static boolean isInteger(String id) { try { Integer.parseInt(id); return true; } catch (NumberFormatException e) { return false; } } private void processVignette(List<FileItem> parameters, KmeliaSessionController kmelia, String instanceId, int pubId) throws Exception { // First, check if image have been uploaded FileItem file = FileUploadUtil.getFile(parameters, "WAIMGVAR0"); String mimeType = null; String physicalName = null; if (file != null) { String logicalName = file.getName().replace('\\', '/'); if (logicalName != null) { logicalName = logicalName.substring(logicalName.lastIndexOf('/') + 1, logicalName.length()); mimeType = FileUtil.getMimeType(logicalName); String type = FileRepositoryManager.getFileExtension(logicalName); if (FileUtil.isImage(logicalName)) { physicalName = String.valueOf(System.currentTimeMillis()) + '.' + type; File dir = new File(FileRepositoryManager.getAbsolutePath(kmelia.getComponentId()) + kmelia.getPublicationSettings().getString("imagesSubDirectory")); if (!dir.exists()) { dir.mkdirs(); } File target = new File(dir, physicalName); file.write(target); } } } // If no image have been uploaded, check if one have been picked up from a gallery if (physicalName == null) { // on a pas d'image, regarder s'il y a une provenant de la galerie String nameImageFromGallery = FileUploadUtil.getParameter(parameters, "valueImageGallery"); if (StringUtil.isDefined(nameImageFromGallery)) { physicalName = nameImageFromGallery; mimeType = "image/jpeg"; } } // If one image is defined, save it through Thumbnail service if (StringUtil.isDefined(physicalName)) { ThumbnailDetail detail = new ThumbnailDetail(instanceId, pubId, ThumbnailDetail.THUMBNAIL_OBJECTTYPE_PUBLICATION_VIGNETTE); detail.setOriginalFileName(physicalName); detail.setMimeType(mimeType); try { int[] thumbnailSize = kmelia.getThumbnailWidthAndHeight(); ThumbnailController.updateThumbnail(detail, thumbnailSize[0], thumbnailSize[1]); } catch (ThumbnailRuntimeException e) { SilverTrace.error("Thumbnail", "ThumbnailRequestRouter.addThumbnail", "root.MSG_GEN_PARAM_VALUE", e); try { ThumbnailController.deleteThumbnail(detail); } catch (Exception exp) { SilverTrace.info("Thumbnail", "ThumbnailRequestRouter.addThumbnail - remove after error", "root.MSG_GEN_PARAM_VALUE", exp); } } } } /** * Process Form Upload for publications import * @param kmeliaScc * @param request * @param routDestination * @return destination */ private String processFormUpload(KmeliaSessionController kmeliaScc, HttpServletRequest request, String routeDestination, boolean isMassiveMode) { String destination = ""; String topicId = ""; String importMode = KmeliaSessionController.UNITARY_IMPORT_MODE; boolean draftMode = false; String logicalName = ""; String message = ""; String tempFolderName = ""; String tempFolderPath = ""; String fileType = ""; long fileSize = 0; long processStart = new Date().getTime(); ResourceLocator attachmentResourceLocator = new ResourceLocator( "com.stratelia.webactiv.util.attachment.multilang.attachment", kmeliaScc.getLanguage()); FileItem fileItem = null; int versionType = DocumentVersion.TYPE_DEFAULT_VERSION; try { List<FileItem> items = FileUploadUtil.parseRequest(request); topicId = FileUploadUtil.getParameter(items, "topicId"); importMode = FileUploadUtil.getParameter(items, "opt_importmode"); String sVersionType = FileUploadUtil.getParameter(items, "opt_versiontype"); if (StringUtil.isDefined(sVersionType)) { versionType = Integer.parseInt(sVersionType); } String sDraftMode = FileUploadUtil.getParameter(items, "chk_draft"); if (StringUtil.isDefined(sDraftMode)) { draftMode = StringUtil.getBooleanValue(sDraftMode); } fileItem = FileUploadUtil.getFile(items, "file_name"); if (fileItem != null) { logicalName = fileItem.getName(); if (logicalName != null) { boolean runOnUnix = !FileUtil.isWindows(); if (runOnUnix) { logicalName = logicalName.replace('\\', File.separatorChar); SilverTrace.info("kmelia", "KmeliaRequestRouter.processFormUpload", "root.MSG_GEN_PARAM_VALUE", "fileName on Unix = " + logicalName); } logicalName = logicalName.substring(logicalName.lastIndexOf(File.separator) + 1, logicalName.length()); // Name of temp folder: timestamp and userId tempFolderName = new Long(new Date().getTime()).toString() + "_" + kmeliaScc.getUserId(); // Mime type of the file fileType = fileItem.getContentType(); // Zip contentType not detected under Firefox ! if (request.getHeader("User-Agent") != null && request.getHeader("User-Agent").indexOf("MSIE") == -1) { fileType = MimeTypes.ARCHIVE_MIME_TYPE; } fileSize = fileItem.getSize(); // Directory Temp for the uploaded file tempFolderPath = FileRepositoryManager.getAbsolutePath(kmeliaScc.getComponentId()) + GeneralPropertiesManager.getGeneralResourceLocator().getString( "RepositoryTypeTemp") + File.separator + tempFolderName; if (!new File(tempFolderPath).exists()) { FileRepositoryManager.createAbsolutePath( kmeliaScc.getComponentId(), GeneralPropertiesManager.getGeneralResourceLocator(). getString("RepositoryTypeTemp") + File.separator + tempFolderName); } // Creation of the file in the temp folder File fileUploaded = new File(FileRepositoryManager.getAbsolutePath(kmeliaScc.getComponentId()) + GeneralPropertiesManager.getGeneralResourceLocator().getString( "RepositoryTypeTemp") + File.separator + tempFolderName + File.separator + logicalName); fileItem.write(fileUploaded); // Is a real file ? if (fileSize > 0) { SilverTrace.debug("kmelia", "KmeliaRequestRouter.processFormUpload()", "root.MSG_GEN_PARAM_VALUE", "fileUploaded = " + fileUploaded + " fileSize=" + fileSize + " fileType=" + fileType + " importMode=" + importMode + " draftMode=" + draftMode); int nbFiles = 1; // Compute nbFiles only in unitary Import mode if (!importMode.equals(KmeliaSessionController.UNITARY_IMPORT_MODE) && fileUploaded.getName().toLowerCase().endsWith(".zip")) { nbFiles = ZipManager.getNbFiles(fileUploaded); } // Import !! List<PublicationDetail> publicationDetails = kmeliaScc.importFile(fileUploaded, fileType, topicId, importMode, draftMode, versionType); long processDuration = new Date().getTime() - processStart; // Title for popup report String importModeTitle = ""; if (importMode.equals(KmeliaSessionController.UNITARY_IMPORT_MODE)) { importModeTitle = kmeliaScc.getString("kmelia.ImportModeUnitaireTitre"); } else { importModeTitle = kmeliaScc.getString("kmelia.ImportModeMassifTitre"); } SilverTrace.debug("kmelia", "KmeliaRequestRouter.processFormUpload()", "root.MSG_GEN_PARAM_VALUE", "nbFiles = " + nbFiles + " publicationDetails=" + publicationDetails + " ProcessDuration=" + processDuration + " ImportMode=" + importMode + " Draftmode=" + draftMode + " Title=" + importModeTitle); request.setAttribute("PublicationsDetails", publicationDetails); request.setAttribute("NbFiles", new Integer(nbFiles)); request.setAttribute("ProcessDuration", FileRepositoryManager.formatFileUploadTime( processDuration)); request.setAttribute("ImportMode", importMode); request.setAttribute("DraftMode", Boolean.valueOf(draftMode)); request.setAttribute("Title", importModeTitle); destination = routeDestination + "reportImportFiles.jsp"; } else { // File access failed message = attachmentResourceLocator.getString("liaisonInaccessible"); request.setAttribute("Message", message); request.setAttribute("TopicId", topicId); destination = routeDestination + "importOneFile.jsp"; if (isMassiveMode) { destination = routeDestination + "importMultiFiles.jsp"; } } FileFolderManager.deleteFolder(tempFolderPath); } else { // the field did not contain a file request.setAttribute("Message", attachmentResourceLocator.getString("liaisonInaccessible")); request.setAttribute("TopicId", topicId); destination = routeDestination + "importOneFile.jsp"; if (isMassiveMode) { destination = routeDestination + "importMultiFiles.jsp"; } } } } /* * catch (IOException e) { //File size exceeds Maximum file size message = * attachmentResourceLocator.getString("fichierTropGrand")+ " (" + * FileRepositoryManager.formatFileSize(maxFileSize) + "&nbsp;" + * attachmentResourceLocator.getString("maximum") +") !!"; * request.setAttribute("Message",message); request.setAttribute("TopicId",topicId); * destination = routeDestination + "importOneFile.jsp"; if (isMassiveMode) destination = * routeDestination + "importMultiFiles.jsp"; } */ catch (Exception e) { // Other exception request.setAttribute("Message", e.getMessage()); request.setAttribute("TopicId", topicId); destination = routeDestination + "importOneFile.jsp"; if (isMassiveMode) { destination = routeDestination + "importMultiFiles.jsp"; } SilverTrace.warn("kmelia", "KmeliaRequestRouter.processFormUpload()", "root.EX_LOAD_ATTACHMENT_FAILED", e); } return destination; } private void processPath(KmeliaSessionController kmeliaSC, String id) throws RemoteException { TopicDetail currentTopic = null; if (!StringUtil.isDefined(id)) { currentTopic = kmeliaSC.getSessionTopic(); } else { currentTopic = kmeliaSC.getPublicationTopic(id); // Calcul du chemin de la } // publication Collection<NodeDetail> pathColl = currentTopic.getPath(); String linkedPathString = kmeliaSC.displayPath(pathColl, true, 3); String pathString = kmeliaSC.displayPath(pathColl, false, 3); kmeliaSC.setSessionPath(linkedPathString); kmeliaSC.setSessionPathString(pathString); } private void putXMLDisplayerIntoRequest(PublicationDetail pubDetail, KmeliaSessionController kmelia, HttpServletRequest request) throws PublicationTemplateException, FormException { String infoId = pubDetail.getInfoId(); String pubId = pubDetail.getPK().getId(); if (!isInteger(infoId)) { PublicationTemplateImpl pubTemplate = (PublicationTemplateImpl) getPublicationTemplateManager().getPublicationTemplate(pubDetail. getPK().getInstanceId() + ":" + infoId); // RecordTemplate recordTemplate = pubTemplate.getRecordTemplate(); Form formView = pubTemplate.getViewForm(); // get displayed language String language = checkLanguage(kmelia, pubDetail); RecordSet recordSet = pubTemplate.getRecordSet(); DataRecord data = recordSet.getRecord(pubId, language); if (data == null) { data = recordSet.getEmptyRecord(); data.setId(pubId); } request.setAttribute("XMLForm", formView); request.setAttribute("XMLData", data); } } private String processWizard(String function, KmeliaSessionController kmeliaSC, HttpServletRequest request, String rootDestination) throws RemoteException, PublicationTemplateException, FormException { String destination = ""; if (function.equals("WizardStart")) { // récupération de l'id du thème dans lequel on veux mettre la // publication // si on ne viens pas d'un theme-tracker String topicId = request.getParameter("TopicId"); if (StringUtil.isDefined(topicId)) { TopicDetail topic = kmeliaSC.getTopic(topicId); kmeliaSC.setSessionTopic(topic); } // recherche du dernier onglet String wizardLast = "1"; List<String> invisibleTabs = kmeliaSC.getInvisibleTabs(); if ((kmeliaSC.isPDCClassifyingMandatory() && invisibleTabs.indexOf( KmeliaSessionController.TAB_PDC) == -1) || kmeliaSC.isKmaxMode) { wizardLast = "4"; } else if (invisibleTabs.indexOf(KmeliaSessionController.TAB_ATTACHMENTS) == -1) { wizardLast = "3"; } else if (invisibleTabs.indexOf(KmeliaSessionController.TAB_CONTENT) == -1) { wizardLast = "2"; } kmeliaSC.setWizardLast(wizardLast); request.setAttribute("WizardLast", wizardLast); kmeliaSC.setWizard("progress"); request.setAttribute("Action", "Wizard"); request.setAttribute("Profile", kmeliaSC.getProfile()); destination = rootDestination + "wizardPublicationManager.jsp"; } else if (function.equals("WizardHeader")) { // passage des paramètres String id = request.getParameter("PubId"); if (!StringUtil.isDefined(id)) { id = (String) request.getAttribute("PubId"); } request.setAttribute("WizardRow", kmeliaSC.getWizardRow()); request.setAttribute("WizardLast", kmeliaSC.getWizardLast()); request.setAttribute("Action", "UpdateWizard"); request.setAttribute("Profile", kmeliaSC.getProfile()); request.setAttribute("PubId", id); destination = rootDestination + "wizardPublicationManager.jsp"; } else if (function.equals("WizardNext")) { // redirige vers l'onglet suivant de l'assistant de publication String position = request.getParameter("Position"); if (!StringUtil.isDefined(position)) { position = (String) request.getAttribute("Position"); } String next = "End"; String wizardRow = kmeliaSC.getWizardRow(); request.setAttribute("WizardRow", wizardRow); int numRow = 0; if (StringUtil.isDefined(wizardRow)) { numRow = Integer.parseInt(wizardRow); } List<String> invisibleTabs = kmeliaSC.getInvisibleTabs(); if (position.equals("View")) { if (invisibleTabs.indexOf(KmeliaSessionController.TAB_CONTENT) == -1) { // on passe à la page du contenu next = "Content"; if (numRow <= 2) { wizardRow = "2"; } else if (numRow < Integer.parseInt(wizardRow)) { wizardRow = Integer.toString(numRow); } } else if (invisibleTabs.indexOf(KmeliaSessionController.TAB_ATTACHMENTS) == -1) { next = "Attachment"; if (numRow <= 3) { wizardRow = "3"; } else if (numRow < Integer.parseInt(wizardRow)) { wizardRow = Integer.toString(numRow); } } else if (kmeliaSC.isPDCClassifyingMandatory() && invisibleTabs.indexOf(KmeliaSessionController.TAB_PDC) == -1) { if (numRow <= 4) { wizardRow = "4"; } else if (numRow < Integer.parseInt(wizardRow)) { wizardRow = Integer.toString(numRow); } next = "Pdc"; } else if (kmeliaSC.isKmaxMode) { if (numRow <= 4) { wizardRow = "4"; } else if (numRow < Integer.parseInt(wizardRow)) { wizardRow = Integer.toString(numRow); } next = "KmaxClassification"; } } else if (position.equals("Content")) { if (invisibleTabs.indexOf(KmeliaSessionController.TAB_ATTACHMENTS) == -1) { next = "Attachment"; if (numRow <= 3) { wizardRow = "3"; } else if (numRow < Integer.parseInt(wizardRow)) { wizardRow = Integer.toString(numRow); } } else if (kmeliaSC.isPDCClassifyingMandatory() && invisibleTabs.indexOf(KmeliaSessionController.TAB_PDC) == -1) { if (numRow <= 4) { wizardRow = "4"; } else if (numRow < Integer.parseInt(wizardRow)) { wizardRow = Integer.toString(numRow); } next = "Pdc"; } else if (kmeliaSC.isKmaxMode) { if (numRow <= 4) { wizardRow = "4"; } else if (numRow < Integer.parseInt(wizardRow)) { wizardRow = Integer.toString(numRow); } next = "KmaxClassification"; } } else if (position.equals("Attachment")) { if (kmeliaSC.isPDCClassifyingMandatory() && invisibleTabs.indexOf(KmeliaSessionController.TAB_PDC) == -1) { next = "Pdc"; } else if (kmeliaSC.isKmaxMode) { next = "KmaxClassification"; } else { next = "End"; } if (!next.equals("End")) { if (numRow <= 4) { wizardRow = "4"; } else if (numRow < Integer.parseInt(wizardRow)) { wizardRow = Integer.toString(numRow); } } } else if (position.equals("Pdc") || position.equals("KmaxClassification")) { if (numRow <= 4) { wizardRow = "4"; } else if (numRow < Integer.parseInt(wizardRow)) { wizardRow = Integer.toString(numRow); } next = "End"; } // mise à jour du rang en cours kmeliaSC.setWizardRow(wizardRow); // passage des paramètres setWizardParams(request, kmeliaSC); if (next.equals("View")) { destination = getDestination("WizardStart", kmeliaSC, request); } else if (next.equals("Content")) { destination = getDestination("ToPubliContent", kmeliaSC, request); } else if (next.equals("Attachment")) { destination = getDestination("ViewAttachments", kmeliaSC, request); } else if (next.equals("Pdc")) { destination = getDestination("ViewPdcPositions", kmeliaSC, request); } else if (next.equals("KmaxClassification")) { destination = getDestination("KmaxViewCombination", kmeliaSC, request); } else if (next.equals("End")) { // terminer la publication : la sortir du mode brouillon kmeliaSC.setWizard("finish"); kmeliaSC.draftOutPublication(); destination = getDestination("ViewPublication", kmeliaSC, request); } } return destination; } private void setWizardParams(HttpServletRequest request, KmeliaSessionController kmelia) { // Paramètres du wizard request.setAttribute("Wizard", kmelia.getWizard()); request.setAttribute("WizardRow", kmelia.getWizardRow()); request.setAttribute("WizardLast", kmelia.getWizardLast()); } private void resetWizard(KmeliaSessionController kmelia) { kmelia.setWizard("none"); kmelia.setWizardLast("0"); kmelia.setWizardRow("0"); } private void setXMLForm(HttpServletRequest request, KmeliaSessionController kmelia, String xmlFormName) throws PublicationTemplateException, FormException { PublicationDetail pubDetail = kmelia.getSessionPubliOrClone().getPublication().getPublicationDetail(); String pubId = pubDetail.getPK().getId(); String xmlFormShortName = null; if (!StringUtil.isDefined(xmlFormName)) { xmlFormShortName = pubDetail.getInfoId(); xmlFormName = null; } else { xmlFormShortName = xmlFormName.substring(xmlFormName.indexOf("/") + 1, xmlFormName.indexOf(".")); SilverTrace.info("kmelia", "KmeliaRequestRouter.setXMLForm()", "root.MSG_GEN_PARAM_VALUE", "xmlFormShortName = " + xmlFormShortName); // register xmlForm to publication getPublicationTemplateManager().addDynamicPublicationTemplate(kmelia.getComponentId() + ":" + xmlFormShortName, xmlFormName); } PublicationTemplateImpl pubTemplate = (PublicationTemplateImpl) getPublicationTemplateManager().getPublicationTemplate(kmelia. getComponentId() + ":" + xmlFormShortName, xmlFormName); Form formUpdate = pubTemplate.getUpdateForm(); RecordSet recordSet = pubTemplate.getRecordSet(); // get displayed language String language = checkLanguage(kmelia, pubDetail); DataRecord data = recordSet.getRecord(pubId, language); if (data == null) { data = recordSet.getEmptyRecord(); data.setId(pubId); } request.setAttribute("Form", formUpdate); request.setAttribute("Data", data); request.setAttribute("XMLFormName", xmlFormName); } private void setLanguage(HttpServletRequest request, KmeliaSessionController kmelia) { String language = request.getParameter("SwitchLanguage"); if (StringUtil.isDefined(language)) { kmelia.setCurrentLanguage(language); } request.setAttribute("Language", kmelia.getCurrentLanguage()); } private String checkLanguage(KmeliaSessionController kmelia) { return checkLanguage(kmelia, kmelia.getSessionPublication().getPublication(). getPublicationDetail()); } private String checkLanguage(KmeliaSessionController kmelia, PublicationDetail pubDetail) { return pubDetail.getLanguageToDisplay(kmelia.getCurrentLanguage()); } private void checkAlias(KmeliaSessionController kmelia, UserCompletePublication publication) { if (!kmelia.getComponentId().equals( publication.getPublication().getPublicationDetail().getPK().getInstanceId())) { publication.setAlias(true); } } private void updatePubliDuringUpdateChain(String id, HttpServletRequest request, KmeliaSessionController kmelia) throws RemoteException { // enregistrement des modifications de la publi String name = request.getParameter("Name"); String description = request.getParameter("Description"); String keywords = request.getParameter("Keywords"); String tree = request.getParameter("Tree"); String[] topics = request.getParameterValues("topicChoice"); // sauvegarde des données Fields fields = kmelia.getFieldUpdateChain(); FieldUpdateChainDescriptor field = kmelia.getFieldUpdateChain().getName(); field.setName("Name"); field.setValue(name); fields.setName(field); field = kmelia.getFieldUpdateChain().getDescription(); field.setName("Description"); field.setValue(description); fields.setDescription(field); field = kmelia.getFieldUpdateChain().getKeywords(); field.setName("Keywords"); field.setValue(keywords); fields.setKeywords(field); field = kmelia.getFieldUpdateChain().getTree(); if (field != null) { field.setName("Topics"); field.setValue(tree); fields.setTree(field); } fields.setTopics(topics); kmelia.setFieldUpdateChain(fields); Date jBeginDate = null; Date jEndDate = null; String pubId = "X"; if (StringUtil.isDefined(id)) { pubId = id; } PublicationDetail pubDetail = new PublicationDetail(pubId, name, description, null, jBeginDate, jEndDate, null, "0", "", keywords, "", "", "", ""); pubDetail.setStatus("Valid"); I18NHelper.setI18NInfo(pubDetail, request); try { // Execute helper String helperClassName = kmelia.getFieldUpdateChain().getHelper(); UpdateChainHelper helper; helper = (UpdateChainHelper) Class.forName(helperClassName).newInstance(); UpdateChainHelperContext uchc = new UpdateChainHelperContext(pubDetail, kmelia); uchc.setAllTopics(kmelia.getAllTopics()); helper.execute(uchc); pubDetail = uchc.getPubDetail(); // mettre à jour les emplacements si necessaire String[] calculedTopics = uchc.getTopics(); if (calculedTopics != null) { topics = calculedTopics; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } kmelia.updatePublication(pubDetail); Alias alias = null; List<Alias> aliases = new ArrayList<Alias>(); for (int i = 0; topics != null && i < topics.length; i++) { String topicId = topics[i]; StringTokenizer tokenizer = new StringTokenizer(topicId, ","); String nodeId = tokenizer.nextToken(); String instanceId = tokenizer.nextToken(); alias = new Alias(nodeId, instanceId); alias.setUserId(kmelia.getUserId()); aliases.add(alias); } kmelia.setAliases(pubDetail.getPK(), aliases); } private String processUpdateChainOperation(String rootDestination, String function, KmeliaSessionController kmelia, HttpServletRequest request) throws IOException, ClassNotFoundException, SAXException, ParserConfigurationException { if (function.equals("UpdateChainInit")) { // récupération du descripteur kmelia.initUpdateChainDescriptor(); // Modification par chaine de toutes les publications du thème : // positionnement sur la première publi String pubId = kmelia.getFirst(); request.setAttribute("PubId", pubId); // initialiser le topic en cours kmelia.initUpdateChainTopicChoice(pubId); return getDestination("UpdateChainPublications", kmelia, request); } else if (function.equals("UpdateChainPublications")) { String id = (String) request.getAttribute("PubId"); request.setAttribute("Action", "UpdateChain"); request.setAttribute("Profile", kmelia.getProfile()); request.setAttribute("PubId", id); request.setAttribute("SaveFields", kmelia.getFieldUpdateChain()); if (StringUtil.isDefined(id)) { request.setAttribute("Rang", new Integer(kmelia.getRang())); if (kmelia.getSessionPublicationsList() != null) { request.setAttribute("NbPublis", new Integer(kmelia.getSessionPublicationsList().size())); } else { request.setAttribute("NbPublis", new Integer(1)); } // request.setAttribute("PathList",kmelia.getPublicationFathers(id)); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Topics", kmelia.getUpdateChainTopics()); // mise à jour de la publication en session pour récupérer les alias UserCompletePublication userPubComplete = kmelia.getUserCompletePublication(id); kmelia.setSessionPublication(userPubComplete); List<Alias> aliases = kmelia.getAliases(); request.setAttribute("Aliases", aliases); // url du fichier joint request.setAttribute("FileUrl", kmelia.getFirstAttachmentURLOfCurrentPublication()); return rootDestination + "updateByChain.jsp"; } } else if (function.equals("UpdateChainNextUpdate")) { String id = request.getParameter("PubId"); updatePubliDuringUpdateChain(id, request, kmelia); // récupération de la publication suivante String nextPubId = kmelia.getNext(); request.setAttribute("PubId", nextPubId); return getDestination("UpdateChainPublications", kmelia, request); } else if (function.equals("UpdateChainLastUpdate")) { String id = request.getParameter("PubId"); updatePubliDuringUpdateChain(id, request, kmelia); // mise à jour du theme pour le retour request.setAttribute("Id", kmelia.getSessionTopic().getNodePK().getId()); return getDestination("GoToTopic", kmelia, request); } else if (function.equals("UpdateChainSkipUpdate")) { // récupération de la publication suivante String pubId = kmelia.getNext(); request.setAttribute("PubId", pubId); return getDestination("UpdateChainPublications", kmelia, request); } else if (function.equals("UpdateChainEndUpdate")) { // mise à jour du theme pour le retour request.setAttribute("Id", kmelia.getSessionTopic().getNodePK().getId()); return getDestination("GoToTopic", kmelia, request); } else if (function.equals("UpdateChainUpdateAll")) { // mise à jour du theme pour le retour request.setAttribute("Id", kmelia.getSessionTopic().getNodePK().getId()); // enregistrement des modifications sur toutes les publications restantes // publication courante String id = request.getParameter("PubId"); updatePubliDuringUpdateChain(id, request, kmelia); // passer à la suivante si elle existe int rang = kmelia.getRang(); int nbPublis = kmelia.getSessionPublicationsList().size(); while (rang < nbPublis - 1) { String pubId = kmelia.getNext(); updatePubliDuringUpdateChain(pubId, request, kmelia); rang = kmelia.getRang(); } // retour au thème return getDestination("GoToTopic", kmelia, request); } return ""; } /** * Gets an instance of PublicationTemplateManager. * @return an instance of PublicationTemplateManager. */ public PublicationTemplateManager getPublicationTemplateManager() { return PublicationTemplateManager.getInstance(); } }
true
true
public String getDestination(String function, ComponentSessionController componentSC, HttpServletRequest request) { SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function); String destination = ""; String rootDestination = "/kmelia/jsp/"; boolean profileError = false; boolean kmaxMode = false; boolean toolboxMode = false; try { KmeliaSessionController kmelia = (KmeliaSessionController) componentSC; SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "getComponentRootName() = " + kmelia.getComponentRootName()); if ("kmax".equals(kmelia.getComponentRootName())) { kmaxMode = true; kmelia.isKmaxMode = true; } request.setAttribute("KmaxMode", Boolean.valueOf(kmaxMode)); toolboxMode = KmeliaHelper.isToolbox(kmelia.getComponentId()); // Set language choosen by the user setLanguage(request, kmelia); if (function.startsWith("Main")) { resetWizard(kmelia); if (kmaxMode) { destination = getDestination("KmaxMain", componentSC, request); kmelia.setSessionTopic(null); kmelia.setSessionPath(""); } else { destination = getDestination("GoToTopic", componentSC, request); } } else if (function.startsWith("portlet")) { kmelia.setSessionPublication(null); String flag = componentSC.getUserRoleLevel(); if (kmaxMode) { destination = rootDestination + "kmax_portlet.jsp?Profile=" + flag; } else { destination = rootDestination + "portlet.jsp?Profile=user"; } } else if (function.equals("FlushTrashCan")) { kmelia.flushTrashCan(); if (kmaxMode) { destination = getDestination("KmaxMain", kmelia, request); } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else if (function.equals("GoToDirectory")) { String topicId = request.getParameter("Id"); String path = null; if (StringUtil.isDefined(topicId)) { NodeDetail topic = kmelia.getNodeHeader(topicId); path = topic.getPath(); } else { path = request.getParameter("Path"); } FileFolder folder = new FileFolder(path); request.setAttribute("Directory", folder); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); destination = rootDestination + "repository.jsp"; } else if (function.equals("GoToTopic")) { String topicId = (String) request.getAttribute("Id"); if (!StringUtil.isDefined(topicId)) { topicId = request.getParameter("Id"); if (!StringUtil.isDefined(topicId)) { topicId = "0"; } } TopicDetail currentTopic = kmelia.getTopic(topicId, true); processPath(kmelia, null); kmelia.setSessionPublication(null); resetWizard(kmelia); request.setAttribute("CurrentTopic", currentTopic); request.setAttribute("PathString", kmelia.getSessionPathString()); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Treeview", kmelia.getTreeview()); request.setAttribute("DisplayNBPublis", Boolean.valueOf(kmelia.displayNbPublis())); request.setAttribute("DisplaySearch", new Boolean(kmelia.isSearchOnTopicsEnabled())); // rechercher si le theme a un descripteur request.setAttribute("HaveDescriptor", Boolean.valueOf(kmelia. isTopicHaveUpdateChainDescriptor())); if ("noRights".equalsIgnoreCase(currentTopic.getNodeDetail().getUserRole())) { destination = rootDestination + "toCrossTopic.jsp"; } else { request.setAttribute("Profile", kmelia.getUserTopicProfile(topicId)); request.setAttribute("IsGuest", Boolean.valueOf(kmelia.getUserDetail().isAccessGuest())); request.setAttribute("RightsOnTopicsEnabled", Boolean.valueOf(kmelia. isRightsOnTopicsEnabled())); request.setAttribute("WysiwygDescription", kmelia.getWysiwygOnTopic()); if (kmelia.isTreeStructure()) { destination = rootDestination + "topicManager.jsp"; } else { destination = rootDestination + "simpleListOfPublications.jsp"; } } } else if (function.equals("GoToCurrentTopic")) { if (kmelia.getSessionTopic() != null) { String id = kmelia.getSessionTopic().getNodePK().getId(); request.setAttribute("Id", id); destination = getDestination("GoToTopic", kmelia, request); } else { destination = getDestination("Main", kmelia, request); } } else if (function.equals("GoToBasket")) { destination = rootDestination + "basket.jsp"; } else if (function.equals("ViewPublicationsToValidate")) { destination = rootDestination + "publicationsToValidate.jsp"; } else if (function.startsWith("searchResult")) { resetWizard(kmelia); String id = request.getParameter("Id"); String type = request.getParameter("Type"); String fileAlreadyOpened = request.getParameter("FileOpened"); if (type.equals("Publication") || type.equals("com.stratelia.webactiv.calendar.backbone.TodoDetail") || type.equals("Attachment") || type.equals("Document")) { KmeliaSecurity security = new KmeliaSecurity(kmelia.getOrganizationController()); try { boolean accessAuthorized = security.isAccessAuthorized(kmelia.getComponentId(), kmelia.getUserId(), id, "Publication"); if (accessAuthorized) { if (type.equals("Attachment")) { String attachmentId = request.getParameter("AttachmentId"); request.setAttribute("AttachmentId", attachmentId); destination = getDestination("ViewPublication", kmelia, request); } else if (type.equals("Document")) { String documentId = request.getParameter("DocumentId"); request.setAttribute("DocumentId", documentId); destination = getDestination("ViewPublication", kmelia, request); } else { if (kmaxMode) { request.setAttribute("FileAlreadyOpened", fileAlreadyOpened); destination = getDestination("ViewPublication", kmelia, request); } else if (toolboxMode) { processPath(kmelia, id); // we have to find which page contains the right publication List<UserPublication> publications = new ArrayList<UserPublication>( kmelia.getSessionTopic().getPublicationDetails()); UserPublication publication = null; int pubIndex = -1; for (int p = 0; p < publications.size() && pubIndex == -1; p++) { publication = publications.get(p); if (id.equals(publication.getPublication().getPK().getId())) { pubIndex = p; } } int nbPubliPerPage = kmelia.getNbPublicationsPerPage(); if (nbPubliPerPage == 0) { nbPubliPerPage = pubIndex; } int ipage = pubIndex / nbPubliPerPage; kmelia.setIndexOfFirstPubToDisplay(Integer.toString(ipage * nbPubliPerPage)); request.setAttribute("PubIdToHighlight", id); destination = getDestination("GoToCurrentTopic", kmelia, request); } else { request.setAttribute("FileAlreadyOpened", fileAlreadyOpened); processPath(kmelia, id); destination = getDestination("ViewPublication", kmelia, request); } } } else { destination = "/admin/jsp/accessForbidden.jsp"; } } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e); destination = getDocumentNotFoundDestination(kmelia, request); } } else if (type.equals("Node")) { if (kmaxMode) { // Simuler l'action d'un utilisateur ayant sélectionné la valeur id d'un axe // SearchCombination est un chemin /0/4/i NodeDetail node = kmelia.getNodeHeader(id); String path = node.getPath() + id; request.setAttribute("SearchCombination", path); destination = getDestination("KmaxSearch", componentSC, request); } else { try { request.setAttribute("Id", id); destination = getDestination("GoToTopic", componentSC, request); } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e); destination = getDocumentNotFoundDestination(kmelia, request); } } } else if (type.equals("Wysiwyg")) { if (id.startsWith("Node")) { id = id.substring(5, id.length()); request.setAttribute("Id", id); destination = getDestination("GoToTopic", componentSC, request); } else { /* * if (kmaxMode) destination = getDestination("KmaxViewPublication", kmelia, request); * else */ destination = getDestination("ViewPublication", kmelia, request); } } else { request.setAttribute("Id", "0"); destination = getDestination("GoToTopic", componentSC, request); } } else if (function.startsWith("GoToFilesTab")) { String id = request.getParameter("Id"); try { processPath(kmelia, id); if (toolboxMode) { UserCompletePublication userPubComplete = kmelia.getUserCompletePublication(id); kmelia.setSessionPublication(userPubComplete); kmelia.setSessionOwner(true); destination = getDestination("ViewAttachments", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e); destination = getDocumentNotFoundDestination(kmelia, request); } } else if (function.startsWith("publicationManager")) { String flag = kmelia.getProfile(); request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "publicationManager.jsp?Profile=" + flag; // thumbnail error for front explication if (request.getParameter("errorThumbnail") != null) { destination = destination + "&resultThumbnail=" + request.getParameter("errorThumbnail"); } } else if (function.equals("ToAddTopic")) { String topicId = request.getParameter("Id"); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(topicId))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { String isLink = request.getParameter("IsLink"); if (StringUtil.isDefined(isLink)) { request.setAttribute("IsLink", Boolean.TRUE); } List<NodeDetail> path = kmelia.getTopicPath(topicId); request.setAttribute("Path", kmelia.displayPath(path, false, 3)); request.setAttribute("PathLinked", kmelia.displayPath(path, true, 3)); request.setAttribute("Translation", kmelia.getCurrentLanguage()); request.setAttribute("PopupDisplay", Boolean.TRUE); request.setAttribute("NotificationAllowed", Boolean.valueOf(kmelia.isNotificationAllowed())); request.setAttribute("Parent", kmelia.getNodeHeader(topicId)); if (kmelia.isRightsOnTopicsEnabled()) { request.setAttribute("PopupDisplay", Boolean.FALSE); request.setAttribute("Profiles", kmelia.getTopicProfiles()); // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } destination = rootDestination + "addTopic.jsp"; } } else if ("ToUpdateTopic".equals(function)) { String id = request.getParameter("Id"); NodeDetail node = kmelia.getSubTopicDetail(id); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(id)) && !SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(node.getFatherPK().getId()))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { request.setAttribute("NodeDetail", node); List<NodeDetail> path = kmelia.getTopicPath(id); request.setAttribute("Path", kmelia.displayPath(path, false, 3)); request.setAttribute("PathLinked", kmelia.displayPath(path, true, 3)); request.setAttribute("Translation", kmelia.getCurrentLanguage()); request.setAttribute("PopupDisplay", Boolean.TRUE); request.setAttribute("NotificationAllowed", Boolean.valueOf(kmelia.isNotificationAllowed())); if (kmelia.isRightsOnTopicsEnabled()) { request.setAttribute("PopupDisplay", Boolean.FALSE); request.setAttribute("Profiles", kmelia.getTopicProfiles(id)); if (node.haveInheritedRights()) { request.setAttribute("RightsDependsOn", "AnotherTopic"); } else if (node.haveLocalRights()) { request.setAttribute("RightsDependsOn", "ThisTopic"); } else { // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } } destination = rootDestination + "updateTopicNew.jsp"; } } else if (function.equals("AddTopic")) { String name = request.getParameter("Name"); String description = request.getParameter("Description"); String alertType = request.getParameter("AlertType"); if (!StringUtil.isDefined(alertType)) { alertType = "None"; } String rightsUsed = request.getParameter("RightsUsed"); String path = request.getParameter("Path"); String parentId = request.getParameter("ParentId"); NodeDetail topic = new NodeDetail("-1", name, description, null, null, null, "0", "X"); I18NHelper.setI18NInfo(topic, request); if (StringUtil.isDefined(path)) { topic.setType(NodeDetail.FILE_LINK_TYPE); topic.setPath(path); } int rightsDependsOn = -1; if (StringUtil.isDefined(rightsUsed)) { if ("father".equalsIgnoreCase(rightsUsed)) { NodeDetail father = kmelia.getSessionTopic().getNodeDetail(); rightsDependsOn = father.getRightsDependsOn(); } else { rightsDependsOn = 0; } topic.setRightsDependsOn(rightsDependsOn); } NodePK nodePK = kmelia.addSubTopic(topic, alertType, parentId); if (kmelia.isRightsOnTopicsEnabled()) { if (rightsDependsOn == 0) { request.setAttribute("NodeId", nodePK.getId()); destination = getDestination("ViewTopicProfiles", componentSC, request); } else { destination = getDestination("GoToCurrentTopic", componentSC, request); } } else { request.setAttribute("urlToReload", "GoToCurrentTopic"); destination = rootDestination + "closeWindow.jsp"; } } else if ("UpdateTopic".equals(function)) { String name = request.getParameter("Name"); String description = request.getParameter("Description"); String alertType = request.getParameter("AlertType"); if (!StringUtil.isDefined(alertType)) { alertType = "None"; } String id = request.getParameter("ChildId"); String path = request.getParameter("Path"); NodeDetail topic = new NodeDetail(id, name, description, null, null, null, "0", "X"); I18NHelper.setI18NInfo(topic, request); if (StringUtil.isDefined(path)) { topic.setType(NodeDetail.FILE_LINK_TYPE); topic.setPath(path); } kmelia.updateTopicHeader(topic, alertType); if (kmelia.isRightsOnTopicsEnabled()) { int rightsUsed = Integer.parseInt(request.getParameter("RightsUsed")); topic = kmelia.getNodeHeader(id); if (topic.getRightsDependsOn() != rightsUsed) { // rights dependency have changed if (rightsUsed == -1) { kmelia.updateTopicDependency(topic, false); destination = getDestination("GoToCurrentTopic", componentSC, request); } else { kmelia.updateTopicDependency(topic, true); request.setAttribute("NodeId", id); destination = getDestination("ViewTopicProfiles", componentSC, request); } } else { destination = getDestination("GoToCurrentTopic", componentSC, request); } } else { request.setAttribute("urlToReload", "GoToCurrentTopic"); destination = rootDestination + "closeWindow.jsp"; } } else if (function.equals("DeleteTopic")) { String id = request.getParameter("Id"); kmelia.deleteTopic(id); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ViewClone")) { PublicationDetail pubDetail = kmelia.getSessionPublication().getPublication().getPublicationDetail(); // Reload clone and put it into session String cloneId = pubDetail.getCloneId(); UserCompletePublication userPubComplete = kmelia.getUserCompletePublication(cloneId); kmelia.setSessionClone(userPubComplete); request.setAttribute("Publication", userPubComplete); request.setAttribute("Profile", kmelia.getProfile()); request.setAttribute("VisiblePublicationId", pubDetail.getPK().getId()); putXMLDisplayerIntoRequest(userPubComplete.getPublication().getPublicationDetail(), kmelia, request); destination = rootDestination + "clone.jsp"; } else if (function.equals("ViewPublication")) { String id = request.getParameter("PubId"); if (!StringUtil.isDefined(id)) { id = request.getParameter("Id"); if (!StringUtil.isDefined(id)) { id = (String) request.getAttribute("PubId"); } } boolean checkPath = StringUtil.getBooleanValue(request.getParameter("CheckPath")); if (checkPath) { processPath(kmelia, id); } else { processPath(kmelia, null); } UserCompletePublication userPubComplete = null; if (StringUtil.isDefined(id)) { userPubComplete = kmelia.getUserCompletePublication(id, true); kmelia.setSessionPublication(userPubComplete); PublicationDetail pubDetail = userPubComplete.getPublication().getPublicationDetail(); if (pubDetail.haveGotClone()) { UserCompletePublication clone = kmelia.getUserCompletePublication(pubDetail.getCloneId()); kmelia.setSessionClone(clone); } } else { userPubComplete = kmelia.getSessionPublication(); id = userPubComplete.getPublication().getPublicationDetail().getPK().getId(); } if (toolboxMode) { destination = rootDestination + "publicationManager.jsp?Action=UpdateView&PubId=" + id + "&Profile=" + kmelia.getProfile(); } else { List<String> publicationLanguages = kmelia.getPublicationLanguages(); // languages of // publication // header and attachments if (publicationLanguages.contains(kmelia.getCurrentLanguage())) { request.setAttribute("ContentLanguage", kmelia.getCurrentLanguage()); } else { request.setAttribute("ContentLanguage", checkLanguage(kmelia, userPubComplete. getPublication().getPublicationDetail())); } request.setAttribute("Languages", publicationLanguages); // see also management Collection<ForeignPK> links = userPubComplete.getPublication().getLinkList(); HashSet<String> linkedList = new HashSet<String>(); for (ForeignPK link : links) { linkedList.add(link.getId() + "/" + link.getInstanceId()); } // put into session the current list of selected publications (see also) request.getSession().setAttribute(KmeliaConstants.PUB_TO_LINK_SESSION_KEY, linkedList); request.setAttribute("Publication", userPubComplete); request.setAttribute("PubId", id); request.setAttribute("ValidationStep", kmelia.getValidationStep()); request.setAttribute("ValidationType", new Integer(kmelia.getValidationType())); // check if user is writer with approval right (versioning case) request.setAttribute("WriterApproval", Boolean.valueOf(kmelia.isWriterApproval(id))); request.setAttribute("NotificationAllowed", Boolean.valueOf(kmelia.isNotificationAllowed())); // check is requested publication is an alias checkAlias(kmelia, userPubComplete); if (userPubComplete.isAlias()) { request.setAttribute("Profile", "user"); request.setAttribute("IsAlias", "1"); } else { request.setAttribute("Profile", kmelia.getProfile()); } request.setAttribute("Wizard", kmelia.getWizard()); request.setAttribute("Rang", new Integer(kmelia.getRang())); if (kmelia.getSessionPublicationsList() != null) { request.setAttribute("NbPublis", new Integer(kmelia.getSessionPublicationsList().size())); } else { request.setAttribute("NbPublis", new Integer(1)); } putXMLDisplayerIntoRequest(userPubComplete.getPublication().getPublicationDetail(), kmelia, request); String fileAlreadyOpened = (String) request.getAttribute("FileAlreadyOpened"); boolean alreadyOpened = "1".equals(fileAlreadyOpened); String attachmentId = (String) request.getAttribute("AttachmentId"); String documentId = (String) request.getAttribute("DocumentId"); if (!alreadyOpened && kmelia.openSingleAttachmentAutomatically() && !kmelia.isCurrentPublicationHaveContent()) { request.setAttribute("SingleAttachmentURL", kmelia. getFirstAttachmentURLOfCurrentPublication()); } else if (!alreadyOpened && attachmentId != null) { request.setAttribute("SingleAttachmentURL", kmelia.getAttachmentURL(attachmentId)); } else if (!alreadyOpened && documentId != null) { request.setAttribute("SingleAttachmentURL", kmelia.getAttachmentURL(documentId)); } destination = rootDestination + "publication.jsp"; } } else if (function.equals("PreviousPublication")) { // récupération de la publication précédente String pubId = kmelia.getPrevious(); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("NextPublication")) { // récupération de la publication suivante String pubId = kmelia.getNext(); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.startsWith("copy")) { String objectType = request.getParameter("Object"); String objectId = request.getParameter("Id"); if (StringUtil.isDefined(objectType) && "Node".equalsIgnoreCase(objectType)) { kmelia.copyTopic(objectId); } else { kmelia.copyPublication(objectId); } destination = URLManager.getURL(URLManager.CMP_CLIPBOARD) + "Idle.jsp?message=REFRESHCLIPBOARD"; } else if (function.startsWith("cut")) { String objectType = request.getParameter("Object"); String objectId = request.getParameter("Id"); if (StringUtil.isDefined(objectType) && "Node".equalsIgnoreCase(objectType)) { kmelia.cutTopic(objectId); } else { kmelia.cutPublication(objectId); } destination = URLManager.getURL(URLManager.CMP_CLIPBOARD) + "Idle.jsp?message=REFRESHCLIPBOARD"; } else if (function.startsWith("paste")) { kmelia.paste(); destination = URLManager.getURL(URLManager.CMP_CLIPBOARD) + "Idle.jsp"; } else if (function.startsWith("ToAlertUserAttachment")) { // utilisation de alertUser et alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserAttachment: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { String attachmentId = request.getParameter("AttachmentOrDocumentId"); destination = kmelia.initAlertUserAttachment(attachmentId, false); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserAttachment: function = " + function + "=> destination=" + destination); } else if (function.startsWith("ToAlertUserDocument")) { // utilisation de alertUser et alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserDocument: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { String documentId = request.getParameter("AttachmentOrDocumentId"); destination = kmelia.initAlertUserAttachment(documentId, true); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserDocument: function = " + function + "=> destination=" + destination); } else if (function.startsWith("ToAlertUser")) { // utilisation de alertUser et alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUser: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { destination = kmelia.initAlertUser(); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUser: function = " + function + "=> destination=" + destination); } else if (function.equals("ReadingControl")) { PublicationDetail publication = kmelia.getSessionPublication().getPublication().getPublicationDetail(); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Publication", publication); request.setAttribute("UserIds", kmelia.getUserIdsOfTopic()); // paramètre du wizard request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "readingControlManager.jsp"; } else if (function.startsWith("ViewAttachments")) { String flag = kmelia.getProfile(); // Versioning is out of "Always visible publication" mode if (kmelia.isCloneNeeded() && !kmelia.isVersionControlled()) { kmelia.clonePublication(); } // put current publication if (!kmelia.isVersionControlled()) { request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getPublication().getPublicationDetail()); } else { request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPublication(). getPublication().getPublicationDetail()); } // Paramètres du wizard setWizardParams(request, kmelia); // Paramètres de i18n List<String> attachmentLanguages = kmelia.getAttachmentLanguages(); if (attachmentLanguages.contains(kmelia.getCurrentLanguage())) { request.setAttribute("Language", kmelia.getCurrentLanguage()); } else { request.setAttribute("Language", checkLanguage(kmelia)); } request.setAttribute("Languages", attachmentLanguages); request.setAttribute("XmlFormForFiles", kmelia.getXmlFormForFiles()); destination = rootDestination + "attachmentManager.jsp?profile=" + flag; } else if (function.equals("DeletePublication")) { String pubId = (String) request.getParameter("PubId"); kmelia.deletePublication(pubId); if (kmaxMode) { destination = getDestination("Main", kmelia, request); } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else if (function.equals("DeleteClone")) { kmelia.deleteClone(); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ViewValidationSteps")) { request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Publication", kmelia.getSessionPubliOrClone().getPublication(). getPublicationDetail()); request.setAttribute("ValidationSteps", kmelia.getValidationSteps()); request.setAttribute("Role", kmelia.getProfile()); destination = rootDestination + "validationSteps.jsp"; } else if (function.equals("ValidatePublication")) { String pubId = kmelia.getSessionPublication().getPublication().getPublicationDetail().getPK().getId(); SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function + " pubId=" + pubId); boolean validationComplete = kmelia.validatePublication(pubId); if (validationComplete) { request.setAttribute("Action", "ValidationComplete"); } else { request.setAttribute("Action", "ValidationInProgress"); } request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ForceValidatePublication")) { String pubId = kmelia.getSessionPublication().getPublication().getPublicationDetail().getPK().getId(); kmelia.forcePublicationValidation(pubId); request.setAttribute("Action", "ValidationComplete"); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("WantToRefusePubli")) { PublicationDetail pubDetail = kmelia.getSessionPubliOrClone().getPublication().getPublicationDetail(); request.setAttribute("PublicationToRefuse", pubDetail); destination = rootDestination + "refusalMotive.jsp"; } else if (function.equals("Unvalidate")) { String motive = request.getParameter("Motive"); String pubId = kmelia.getSessionPublication().getPublication().getPublicationDetail().getPK().getId(); SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function + " pubId=" + pubId); kmelia.unvalidatePublication(pubId, motive); request.setAttribute("Action", "Unvalidate"); if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } else if (function.equals("WantToSuspendPubli")) { String pubId = request.getParameter("PubId"); PublicationDetail pubDetail = kmelia.getPublicationDetail(pubId); request.setAttribute("PublicationToSuspend", pubDetail); destination = rootDestination + "defermentMotive.jsp"; } else if (function.equals("SuspendPublication")) { String motive = request.getParameter("Motive"); String pubId = request.getParameter("PubId"); kmelia.suspendPublication(pubId, motive); request.setAttribute("Action", "Suspend"); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("DraftIn")) { kmelia.draftInPublication(); if (kmelia.getSessionClone() != null) { // draft have generate a clone destination = getDestination("ViewClone", componentSC, request); } else { String pubId = kmelia.getSessionPubliOrClone().getPublication().getPublicationDetail().getPK().getId(); String flag = kmelia.getProfile(); String from = request.getParameter("From"); if (StringUtil.isDefined(from)) { destination = getDestination(from, componentSC, request); } else { destination = rootDestination + "publicationManager.jsp?Action=UpdateView&PubId=" + pubId + "&Profile=" + flag; } } } else if (function.equals("DraftOut")) { kmelia.draftOutPublication(); destination = getDestination("ViewPublication", componentSC, request); } else if (function.equals("ToTopicWysiwyg")) { String topicId = request.getParameter("Id"); String subTopicId = request.getParameter("ChildId"); String flag = kmelia.getProfile(); NodeDetail topic = kmelia.getSubTopicDetail(subTopicId); destination = request.getScheme() + "://" + kmelia.getServerNameAndPort() + URLManager.getApplicationURL() + "/wysiwyg/jsp/htmlEditor.jsp?"; destination += "SpaceId=" + kmelia.getSpaceId(); destination += "&SpaceName=" + URLEncoder.encode(kmelia.getSpaceLabel(), "UTF-8"); destination += "&ComponentId=" + kmelia.getComponentId(); destination += "&ComponentName=" + URLEncoder.encode(kmelia.getComponentLabel(), "UTF-8"); destination += "&BrowseInfo=" + URLEncoder.encode(kmelia.getSessionPathString() + " > " + topic.getName() + " > " + kmelia.getString("TopicWysiwyg"), "UTF-8"); destination += "&ObjectId=Node_" + subTopicId; destination += "&Language=fr"; destination += "&ReturnUrl=" + URLEncoder.encode(URLManager.getApplicationURL() + URLManager.getURL(kmelia.getSpaceId(), kmelia.getComponentId()) + "FromTopicWysiwyg?Action=Search&Id=" + topicId + "&ChildId=" + subTopicId + "&Profile=" + flag, "UTF-8"); } else if (function.equals("FromTopicWysiwyg")) { String subTopicId = request.getParameter("ChildId"); kmelia.processTopicWysiwyg(subTopicId); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("TopicUp")) { String subTopicId = request.getParameter("ChildId"); kmelia.changeSubTopicsOrder("up", subTopicId); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("TopicDown")) { String subTopicId = request.getParameter("ChildId"); kmelia.changeSubTopicsOrder("down", subTopicId); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ChangeTopicStatus")) { String subTopicId = request.getParameter("ChildId"); String newStatus = request.getParameter("Status"); String recursive = request.getParameter("Recursive"); if (recursive != null && recursive.equals("1")) { kmelia.changeTopicStatus(newStatus, subTopicId, true); } else { kmelia.changeTopicStatus(newStatus, subTopicId, false); } destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ViewOnly")) { String id = request.getParameter("documentId"); destination = rootDestination + "publicationViewOnly.jsp?Id=" + id; } else if (function.equals("SeeAlso")) { String action = request.getParameter("Action"); if (!StringUtil.isDefined(action)) { action = "LinkAuthorView"; } request.setAttribute("Action", action); // check if requested publication is an alias UserCompletePublication userPubComplete = kmelia.getSessionPublication(); checkAlias(kmelia, userPubComplete); if (userPubComplete.isAlias()) { request.setAttribute("Profile", "user"); request.setAttribute("IsAlias", "1"); } else { request.setAttribute("Profile", kmelia.getProfile()); } // paramètres du wizard request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "seeAlso.jsp"; } else if (function.equals("DeleteSeeAlso")) { String[] pubIds = request.getParameterValues("PubIds"); List<ForeignPK> infoLinks = new ArrayList<ForeignPK>(); StringTokenizer tokens = null; for (String pubId : pubIds) { tokens = new StringTokenizer(pubId, "/"); infoLinks.add(new ForeignPK(tokens.nextToken(), tokens.nextToken())); } if (infoLinks.size() > 0) { kmelia.deleteInfoLinks(kmelia.getSessionPublication().getId(), infoLinks); } destination = getDestination("SeeAlso", kmelia, request); } else if (function.equals("ImportFileUpload")) { destination = processFormUpload(kmelia, request, rootDestination, false); } else if (function.equals("ImportFilesUpload")) { destination = processFormUpload(kmelia, request, rootDestination, true); } else if (function.equals("ExportAttachementsToPDF")) { String topicId = request.getParameter("TopicId"); // build an exploitable list by importExportPeas SilverTrace.info("kmelia", "KmeliaSessionController.getAllVisiblePublicationsByTopic()", "root.MSG_PARAM_VALUE", "topicId =" + topicId); List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublicationsByTopic(topicId); request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("RootId", topicId); // Go to importExportPeas destination = "/RimportExportPeas/jsp/ExportPDF"; } else if (function.equals("NewPublication")) { destination = rootDestination + "publicationManager.jsp?Action=New&CheckPath=0&Profile=" + kmelia.getProfile(); } else if (function.equals("AddPublication")) { List<FileItem> parameters = FileUploadUtil.parseRequest(request); // create publication PublicationDetail pubDetail = getPublicationDetail(parameters, kmelia); String newPubId = kmelia.createPublication(pubDetail); // create vignette if exists processVignette(parameters, kmelia, pubDetail.getInstanceId(), Integer.valueOf(newPubId)); request.setAttribute("PubId", newPubId); processPath(kmelia, newPubId); String wizard = kmelia.getWizard(); if ("progress".equals(wizard)) { UserCompletePublication userPubComplete = kmelia.getUserCompletePublication(newPubId); kmelia.setSessionPublication(userPubComplete); String position = FileUploadUtil.getParameter(parameters, "Position"); setWizardParams(request, kmelia); request.setAttribute("Position", position); request.setAttribute("Publication", userPubComplete); request.setAttribute("Profile", kmelia.getProfile()); destination = getDestination("WizardNext", kmelia, request); } else { StringBuffer requestURI = request.getRequestURL(); destination = requestURI.substring(0, requestURI.indexOf("AddPublication")) + "ViewPublication?PubId=" + newPubId; } } else if (function.equals("UpdatePublication")) { List<FileItem> parameters = FileUploadUtil.parseRequest(request); PublicationDetail pubDetail = getPublicationDetail(parameters, kmelia); kmelia.updatePublication(pubDetail); String id = pubDetail.getPK().getId(); processVignette(parameters, kmelia, pubDetail.getInstanceId(), Integer.valueOf(id)); String wizard = kmelia.getWizard(); if (wizard.equals("progress")) { UserCompletePublication userPubComplete = kmelia.getUserCompletePublication(id); String position = FileUploadUtil.getParameter(parameters, "Position"); setWizardParams(request, kmelia); request.setAttribute("Position", position); request.setAttribute("Publication", userPubComplete); request.setAttribute("Profile", kmelia.getProfile()); destination = getDestination("WizardNext", kmelia, request); } else { if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else { request.setAttribute("PubId", id); request.setAttribute("CheckPath", "1"); destination = getDestination("ViewPublication", kmelia, request); } } } else if (function.equals("SelectValidator")) { destination = kmelia.initUPToSelectValidator(""); } else if (function.equals("Comments")) { String id = request.getParameter("PubId"); String flag = kmelia.getProfile(); if (!kmaxMode) { processPath(kmelia, id); } // paramètre du wizard request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "comments.jsp?PubId=" + id + "&Profile=" + flag; } else if (function.equals("PublicationPaths")) { // paramètre du wizard request.setAttribute("Wizard", kmelia.getWizard()); PublicationDetail publication = kmelia.getSessionPublication().getPublication().getPublicationDetail(); String pubId = publication.getPK().getId(); request.setAttribute("Publication", publication); request.setAttribute("PathList", kmelia.getPublicationFathers(pubId)); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Topics", kmelia.getAllTopics()); List<Alias> aliases = kmelia.getAliases(); request.setAttribute("Aliases", aliases); request.setAttribute("OtherComponents", kmelia.getOtherComponents(aliases)); destination = rootDestination + "publicationPaths.jsp"; } else if (function.equals("SetPath")) { String[] topics = request.getParameterValues("topicChoice"); String loadedComponentIds = request.getParameter("LoadedComponentIds"); Alias alias = null; List<Alias> aliases = new ArrayList<Alias>(); for (int i = 0; topics != null && i < topics.length; i++) { String topicId = topics[i]; SilverTrace.debug("kmelia", "KmeliaRequestRouter.setPath()", "root.MSG_GEN_PARAM_VALUE", "topicId = " + topicId); StringTokenizer tokenizer = new StringTokenizer(topicId, ","); String nodeId = tokenizer.nextToken(); String instanceId = tokenizer.nextToken(); alias = new Alias(nodeId, instanceId); alias.setUserId(kmelia.getUserId()); aliases.add(alias); } // Tous les composants ayant un alias n'ont pas forcément été chargés List<Alias> oldAliases = kmelia.getAliases(); Alias oldAlias; for (int a = 0; a < oldAliases.size(); a++) { oldAlias = oldAliases.get(a); if (loadedComponentIds.indexOf(oldAlias.getInstanceId()) == -1) { // le composant de l'alias n'a pas été chargé aliases.add(oldAlias); } } kmelia.setAliases(aliases); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ShowAliasTree")) { String componentId = request.getParameter("ComponentId"); request.setAttribute("Tree", kmelia.getAliasTreeview(componentId)); request.setAttribute("Aliases", kmelia.getAliases()); destination = rootDestination + "treeview4PublicationPaths.jsp"; } else if (function.equals("AddLinksToPublication")) { String id = request.getParameter("PubId"); String topicId = request.getParameter("TopicId"); HashSet<String> list = (HashSet<String>) request.getSession().getAttribute( KmeliaConstants.PUB_TO_LINK_SESSION_KEY); int nb = kmelia.addPublicationsToLink(id, list); request.setAttribute("NbLinks", Integer.toString(nb)); destination = rootDestination + "publicationLinksManager.jsp?Action=Add&Id=" + topicId; } else if (function.equals("ExportComponent")) { if (kmaxMode) { destination = getDestination("KmaxExportComponent", kmelia, request); } else { // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublications(); request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("RootId", "0"); // Go to importExportPeas destination = "/RimportExportPeas/jsp/ExportItems"; } } else if (function.equals("ExportTopic")) { if (kmaxMode) { destination = getDestination("KmaxExportPublications", kmelia, request); } else { // récupération du topicId String topicId = request.getParameter("TopicId"); // build an exploitable list by importExportPeas SilverTrace.info("kmelia", "KmeliaSessionController.getAllVisiblePublicationsByTopic()", "root.MSG_PARAM_VALUE", "topicId =" + topicId); List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublicationsByTopic(topicId); request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("RootId", topicId); // Go to importExportPeas destination = "/RimportExportPeas/jsp/ExportItems"; } } else if (function.equals("ToPubliContent")) { CompletePublication completePublication = kmelia.getSessionPubliOrClone().getPublication(); if (completePublication.getModelDetail() != null) { destination = getDestination("ToDBModel", kmelia, request); } else if (WysiwygController.haveGotWysiwyg(kmelia.getSpaceId(), kmelia.getComponentId(), completePublication.getPublicationDetail().getPK().getId())) { destination = getDestination("ToWysiwyg", kmelia, request); } else { String infoId = completePublication.getPublicationDetail().getInfoId(); if (infoId == null || "0".equals(infoId)) { List<String> usedModels = (List<String>) kmelia.getModelUsed(); if (usedModels.size() == 1) { String modelId = usedModels.get(0); if ("WYSIWYG".equals(modelId)) { // Wysiwyg content destination = getDestination("ToWysiwyg", kmelia, request); } else if (isInteger(modelId)) { // DB template ModelDetail model = kmelia.getModelDetail(modelId); request.setAttribute("ModelDetail", model); destination = getDestination("ToDBModel", kmelia, request); } else { // XML template setXMLForm(request, kmelia, modelId); // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getPublication().getPublicationDetail()); // Parametres du Wizard setWizardParams(request, kmelia); destination = rootDestination + "xmlForm.jsp"; } } else { destination = getDestination("ListModels", kmelia, request); } } else { destination = getDestination("GoToXMLForm", kmelia, request); } } } else if (function.equals("ListModels")) { Collection<String> modelUsed = kmelia.getModelUsed(); Collection<PublicationTemplate> listModelXml = new ArrayList<PublicationTemplate>(); List<PublicationTemplate> templates = new ArrayList<PublicationTemplate>(); try { templates = getPublicationTemplateManager().getPublicationTemplates(); // recherche de la liste des modèles utilisables PublicationTemplate xmlForm; Iterator<PublicationTemplate> iterator = templates.iterator(); while (iterator.hasNext()) { xmlForm = iterator.next(); // recherche si le modèle est dans la liste if (modelUsed.contains(xmlForm.getFileName())) { listModelXml.add(xmlForm); } } request.setAttribute("XMLForms", listModelXml); } catch (Exception e) { SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination(ListModels)", "root.MSG_GEN_PARAM_VALUE", "", e); } // put dbForms Collection<ModelDetail> dbForms = kmelia.getAllModels(); // recherche de la liste des modèles utilisables Collection<ModelDetail> listModelForm = new ArrayList<ModelDetail>(); ModelDetail modelDetail; Iterator<ModelDetail> iterator = dbForms.iterator(); while (iterator.hasNext()) { modelDetail = iterator.next(); // recherche si le modèle est dans la liste if (modelUsed.contains(modelDetail.getId())) { listModelForm.add(modelDetail); } } request.setAttribute("DBForms", listModelForm); // recherche si modele Wysiwyg utilisable boolean wysiwygValid = false; if (modelUsed.contains("WYSIWYG")) { wysiwygValid = true; } request.setAttribute("WysiwygValid", Boolean.valueOf(wysiwygValid)); // s'il n'y a pas de modèles selectionnés, les présenter tous if (((listModelXml == null) || (listModelXml.isEmpty())) && ((listModelForm == null) || (listModelForm.isEmpty())) && (!wysiwygValid)) { request.setAttribute("XMLForms", templates); request.setAttribute("DBForms", dbForms); request.setAttribute("WysiwygValid", Boolean.TRUE); } // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPublication(). getPublication().getPublicationDetail()); // Paramètres du wizard setWizardParams(request, kmelia); destination = rootDestination + "modelsList.jsp"; } else if (function.equals("ModelUsed")) { try { List<PublicationTemplate> templates = getPublicationTemplateManager().getPublicationTemplates(); request.setAttribute("XMLForms", templates); } catch (Exception e) { SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination(ModelUsed)", "root.MSG_GEN_PARAM_VALUE", "", e); } // put dbForms Collection<ModelDetail> dbForms = kmelia.getAllModels(); request.setAttribute("DBForms", dbForms); Collection<String> modelUsed = kmelia.getModelUsed(); request.setAttribute("ModelUsed", modelUsed); destination = rootDestination + "modelUsedList.jsp"; } else if (function.equals("SelectModel")) { Object o = request.getParameterValues("modelChoice"); if (o != null) { kmelia.addModelUsed((String[]) o); } destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ToWysiwyg")) { if (kmelia.isCloneNeeded()) { kmelia.clonePublication(); } // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getPublication().getPublicationDetail()); // Parametres du Wizard setWizardParams(request, kmelia); request.setAttribute("CurrentLanguage", checkLanguage(kmelia)); destination = rootDestination + "toWysiwyg.jsp"; } else if (function.equals("FromWysiwyg")) { String id = request.getParameter("PubId"); // Parametres du Wizard String wizard = kmelia.getWizard(); setWizardParams(request, kmelia); if (wizard.equals("progress")) { request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { if (kmelia.getSessionClone() != null && id.equals(kmelia.getSessionClone().getPublication().getPublicationDetail().getPK(). getId())) { destination = getDestination("ViewClone", componentSC, request); } else { destination = getDestination("ViewPublication", componentSC, request); } } } else if (function.equals("ToDBModel")) { String modelId = request.getParameter("ModelId"); if (StringUtil.isDefined(modelId)) { ModelDetail model = kmelia.getModelDetail(modelId); request.setAttribute("ModelDetail", model); } // put current publication request.setAttribute("CompletePublication", kmelia.getSessionPubliOrClone().getPublication()); request.setAttribute("NotificationAllowed", Boolean.valueOf(kmelia.isNotificationAllowed())); // Paramètres du wizard setWizardParams(request, kmelia); destination = rootDestination + "modelManager.jsp"; } else if (function.equals("UpdateDBModelContent")) { ResourceLocator publicationSettings = kmelia.getPublicationSettings(); List<InfoTextDetail> textDetails = new ArrayList<InfoTextDetail>(); List<InfoImageDetail> imageDetails = new ArrayList<InfoImageDetail>(); String theText = null; int textOrder = 0; int imageOrder = 0; String logicalName = ""; String physicalName = ""; long size = 0; String type = ""; String mimeType = ""; File dir = null; InfoDetail infos = null; boolean imageTrouble = false; boolean runOnUnix = !FileUtil.isWindows(); List<FileItem> parameters = FileUploadUtil.parseRequest(request); String modelId = FileUploadUtil.getParameter(parameters, "ModelId"); // Parametres du Wizard setWizardParams(request, kmelia); Iterator<FileItem> iter = parameters.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField() && item.getFieldName().startsWith("WATXTVAR")) { theText = item.getString(); textOrder = new Integer(item.getFieldName().substring(8, item.getFieldName().length())).intValue(); textDetails.add(new InfoTextDetail(null, new Integer(textOrder).toString(), null, theText)); } else if (!item.isFormField()) { logicalName = item.getName(); if (logicalName != null && logicalName.length() > 0) { // the part actually contained a file if (runOnUnix) { logicalName = logicalName.replace('\\', File.separatorChar); SilverTrace.info("kmelia", "KmeliaRequestRouter.UpdateDBModelContent", "root.MSG_GEN_PARAM_VALUE", "fileName on Unix = " + logicalName); } logicalName = logicalName.substring(logicalName.lastIndexOf(File.separator) + 1, logicalName. length()); type = logicalName.substring(logicalName.lastIndexOf(".") + 1, logicalName.length()); physicalName = new Long(new Date().getTime()).toString() + "." + type; mimeType = item.getContentType(); size = item.getSize(); dir = new File(FileRepositoryManager.getAbsolutePath(kmelia.getComponentId()) + publicationSettings.getString("imagesSubDirectory") + File.separator + physicalName); if (type.equalsIgnoreCase("gif") || type.equalsIgnoreCase("jpg") || type.equalsIgnoreCase("jpeg") || type.equalsIgnoreCase("png")) { item.write(dir); imageOrder++; if (size > 0) { imageDetails.add(new InfoImageDetail(null, new Integer(imageOrder).toString(), null, physicalName, logicalName, "", mimeType, size)); imageTrouble = false; } else { imageTrouble = true; } } else { imageTrouble = true; } } else { // the field did not contain a file } } } infos = new InfoDetail(null, textDetails, imageDetails, null, ""); CompletePublication completePub = kmelia.getSessionPubliOrClone().getPublication(); if (completePub.getModelDetail() == null) { kmelia.createInfoModelDetail("useless", modelId, infos); } else { kmelia.updateInfoDetail("useless", infos); } if (imageTrouble) { request.setAttribute("ImageTrouble", Boolean.TRUE); } String wizard = kmelia.getWizard(); if (wizard.equals("progress")) { request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { destination = getDestination("ToDBModel", kmelia, request); } } else if (function.equals("GoToXMLForm")) { String xmlFormName = request.getParameter("Name"); setXMLForm(request, kmelia, xmlFormName); // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getPublication().getPublicationDetail()); // Parametres du Wizard setWizardParams(request, kmelia); destination = rootDestination + "xmlForm.jsp"; } else if (function.equals("UpdateXMLForm")) { if (kmelia.isCloneNeeded()) { kmelia.clonePublication(); } if (!StringUtil.isDefined(request.getCharacterEncoding())) { request.setCharacterEncoding("UTF-8"); } String encoding = request.getCharacterEncoding(); List<FileItem> items = FileUploadUtil.parseRequest(request); PublicationDetail pubDetail = kmelia.getSessionPubliOrClone().getPublication().getPublicationDetail(); String xmlFormShortName = null; // Is it the creation of the content or an update ? String infoId = pubDetail.getInfoId(); if (infoId == null || "0".equals(infoId)) { String xmlFormName = FileUploadUtil.getParameter(items, "Name", null, encoding); // The publication have no content // We have to register xmlForm to publication xmlFormShortName = xmlFormName.substring(xmlFormName.indexOf("/") + 1, xmlFormName.indexOf(".")); pubDetail.setInfoId(xmlFormShortName); kmelia.updatePublication(pubDetail); } else { xmlFormShortName = pubDetail.getInfoId(); } String pubId = pubDetail.getPK().getId(); PublicationTemplate pub = getPublicationTemplateManager().getPublicationTemplate(kmelia.getComponentId() + ":" + xmlFormShortName); RecordSet set = pub.getRecordSet(); Form form = pub.getUpdateForm(); String language = checkLanguage(kmelia, pubDetail); DataRecord data = set.getRecord(pubId, language); if (data == null) { data = set.getEmptyRecord(); data.setId(pubId); data.setLanguage(language); } PagesContext context = new PagesContext("myForm", "3", kmelia.getLanguage(), false, kmelia.getComponentId(), kmelia.getUserId()); context.setEncoding("UTF-8"); if (!kmaxMode) { context.setNodeId(kmelia.getSessionTopic().getNodeDetail().getNodePK().getId()); } context.setObjectId(pubId); context.setContentLanguage(kmelia.getCurrentLanguage()); form.update(items, data, context); set.save(data); // update publication to change updateDate and updaterId kmelia.updatePublication(pubDetail); // Parametres du Wizard setWizardParams(request, kmelia); if (kmelia.getWizard().equals("progress")) { // on est en mode Wizard request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else if (kmaxMode) { destination = getDestination("ViewAttachments", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } } else if (function.startsWith("ToOrderPublications")) { List<UserPublication> publications = kmelia.getSessionPublicationsList(); request.setAttribute("Publications", publications); request.setAttribute("Path", kmelia.getSessionPath()); destination = rootDestination + "orderPublications.jsp"; } else if (function.startsWith("OrderPublications")) { String sortedIds = request.getParameter("sortedIds"); StringTokenizer tokenizer = new StringTokenizer(sortedIds, ","); List<String> ids = new ArrayList<String>(); while (tokenizer.hasMoreTokens()) { ids.add(tokenizer.nextToken()); } kmelia.orderPublications(ids); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ToOrderTopics")) { String id = request.getParameter("Id"); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(id))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { TopicDetail topic = kmelia.getTopic(id); request.setAttribute("Nodes", topic.getNodeDetail().getChildrenDetails()); destination = rootDestination + "orderTopics.jsp"; } } else if (function.startsWith("Wizard")) { destination = processWizard(function, kmelia, request, rootDestination); } else if (function.equals("ViewPdcPositions")) { // Parametres du Wizard setWizardParams(request, kmelia); destination = rootDestination + "pdcPositions.jsp"; } else if (function.equals("ViewTopicProfiles")) { String role = request.getParameter("Role"); if (!StringUtil.isDefined(role)) { role = SilverpeasRole.admin.toString(); } String id = request.getParameter("NodeId"); if (!StringUtil.isDefined(id)) { id = (String) request.getAttribute("NodeId"); } request.setAttribute("Profiles", kmelia.getTopicProfiles(id)); NodeDetail topic = kmelia.getNodeHeader(id); ProfileInst profile = null; if (topic.haveInheritedRights()) { profile = kmelia.getTopicProfile(role, Integer.toString(topic.getRightsDependsOn())); request.setAttribute("RightsDependsOn", "AnotherTopic"); } else if (topic.haveLocalRights()) { profile = kmelia.getTopicProfile(role, Integer.toString(topic.getRightsDependsOn())); request.setAttribute("RightsDependsOn", "ThisTopic"); } else { profile = kmelia.getProfile(role); // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } request.setAttribute("CurrentProfile", profile); request.setAttribute("Groups", kmelia.groupIds2Groups(profile.getAllGroups())); request.setAttribute("Users", kmelia.userIds2Users(profile.getAllUsers())); request.setAttribute("Path", kmelia.getSessionPath()); request.setAttribute("NodeDetail", topic); destination = rootDestination + "topicProfiles.jsp"; } else if (function.equals("TopicProfileSelection")) { String role = request.getParameter("Role"); String nodeId = request.getParameter("NodeId"); try { kmelia.initUserPanelForTopicProfile(role, nodeId); } catch (Exception e) { SilverTrace.warn("jobStartPagePeas", "JobStartPagePeasRequestRouter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } destination = Selection.getSelectionURL(Selection.TYPE_USERS_GROUPS); } else if (function.equals("TopicProfileSetUsersAndGroups")) { String role = request.getParameter("Role"); String nodeId = request.getParameter("NodeId"); kmelia.updateTopicRole(role, nodeId); request.setAttribute("urlToReload", "ViewTopicProfiles?Role=" + role + "&NodeId=" + nodeId); destination = rootDestination + "closeWindow.jsp"; } else if (function.equals("TopicProfileRemove")) { String profileId = request.getParameter("Id"); kmelia.deleteTopicRole(profileId); destination = getDestination("ViewTopicProfiles", componentSC, request); } else if (function.equals("CloseWindow")) { destination = rootDestination + "closeWindow.jsp"; } else if (function.startsWith("UpdateChain")) { destination = processUpdateChainOperation(rootDestination, function, kmelia, request); } /*************************** * Kmax mode **************************/ else if (function.equals("KmaxMain")) { destination = rootDestination + "kmax.jsp?Action=KmaxView&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAxisManager")) { destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxViewAxis&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAddAxis")) { String newAxisName = request.getParameter("Name"); String newAxisDescription = request.getParameter("Description"); NodeDetail axis = new NodeDetail("-1", newAxisName, newAxisDescription, DateUtil.today2SQLDate(), kmelia. getUserId(), null, "0", "X"); // I18N I18NHelper.setI18NInfo(axis, request); kmelia.addAxis(axis); request.setAttribute("urlToReload", "KmaxAxisManager"); destination = rootDestination + "closeWindow.jsp"; } else if (function.equals("KmaxUpdateAxis")) { String axisId = request.getParameter("AxisId"); String newAxisName = request.getParameter("AxisName"); String newAxisDescription = request.getParameter("AxisDescription"); NodeDetail axis = new NodeDetail(axisId, newAxisName, newAxisDescription, null, null, null, "0", "X"); // I18N I18NHelper.setI18NInfo(axis, request); kmelia.updateAxis(axis); destination = getDestination("KmaxAxisManager", componentSC, request); } else if (function.equals("KmaxDeleteAxis")) { String axisId = request.getParameter("AxisId"); kmelia.deleteAxis(axisId); destination = getDestination("KmaxAxisManager", componentSC, request); } else if (function.equals("KmaxManageAxis")) { String axisId = request.getParameter("AxisId"); String translation = request.getParameter("Translation"); request.setAttribute("Translation", translation); destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxManageAxis&Profile=" + kmelia.getProfile() + "&AxisId=" + axisId; } else if (function.equals("KmaxManagePosition")) { String positionId = request.getParameter("PositionId"); String translation = request.getParameter("Translation"); request.setAttribute("Translation", translation); destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxManagePosition&Profile=" + kmelia.getProfile() + "&PositionId=" + positionId; } else if (function.equals("KmaxAddPosition")) { String axisId = request.getParameter("AxisId"); String newPositionName = request.getParameter("Name"); String newPositionDescription = request.getParameter("Description"); String translation = request.getParameter("Translation"); NodeDetail position = new NodeDetail("toDefine", newPositionName, newPositionDescription, null, null, null, "0", "X"); // I18N I18NHelper.setI18NInfo(position, request); kmelia.addPosition(axisId, position); request.setAttribute("AxisId", axisId); request.setAttribute("Translation", translation); destination = getDestination("KmaxManageAxis", componentSC, request); } else if (function.equals("KmaxUpdatePosition")) { String positionId = request.getParameter("PositionId"); String positionName = request.getParameter("PositionName"); String positionDescription = request.getParameter("PositionDescription"); NodeDetail position = new NodeDetail(positionId, positionName, positionDescription, null, null, null, "0", "X"); // I18N I18NHelper.setI18NInfo(position, request); kmelia.updatePosition(position); destination = getDestination("KmaxAxisManager", componentSC, request); } else if (function.equals("KmaxDeletePosition")) { String positionId = request.getParameter("PositionId"); kmelia.deletePosition(positionId); destination = getDestination("KmaxAxisManager", componentSC, request); } else if (function.equals("KmaxViewUnbalanced")) { List<UserPublication> publications = kmelia.getUnbalancedPublications(); kmelia.setSessionPublicationsList(publications); kmelia.orderPubs(); destination = rootDestination + "kmax.jsp?Action=KmaxViewUnbalanced&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxViewBasket")) { TopicDetail basket = kmelia.getTopic("1"); List<UserPublication> publications = (List<UserPublication>) basket.getPublicationDetails(); kmelia.setSessionPublicationsList(publications); kmelia.orderPubs(); destination = rootDestination + "kmax.jsp?Action=KmaxViewBasket&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxViewToValidate")) { destination = rootDestination + "kmax.jsp?Action=KmaxViewToValidate&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxSearch")) { String axisValuesStr = request.getParameter("SearchCombination"); if (!StringUtil.isDefined(axisValuesStr)) { axisValuesStr = (String) request.getAttribute("SearchCombination"); } String timeCriteria = request.getParameter("TimeCriteria"); SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "axisValuesStr = " + axisValuesStr + " timeCriteria=" + timeCriteria); List<String> combination = kmelia.getCombination(axisValuesStr); List<UserPublication> publications = null; if (StringUtil.isDefined(timeCriteria) && !timeCriteria.equals("X")) { publications = kmelia.search(combination, new Integer(timeCriteria).intValue()); } else { publications = kmelia.search(combination); } SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "publications = " + publications + " Combination=" + combination + " timeCriteria=" + timeCriteria); kmelia.setIndexOfFirstPubToDisplay("0"); kmelia.orderPubs(); kmelia.setSessionCombination(combination); kmelia.setSessionTimeCriteria(timeCriteria); destination = rootDestination + "kmax.jsp?Action=KmaxSearchResult&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxSearchResult")) { if (kmelia.getSessionCombination() == null) { destination = getDestination("KmaxMain", kmelia, request); } else { destination = rootDestination + "kmax.jsp?Action=KmaxSearchResult&Profile=" + kmelia.getProfile(); } } else if (function.equals("KmaxViewCombination")) { setWizardParams(request, kmelia); request.setAttribute("CurrentCombination", kmelia.getCurrentCombination()); destination = rootDestination + "kmax_viewCombination.jsp?Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAddCoordinate")) { String pubId = request.getParameter("PubId"); String axisValuesStr = request.getParameter("SearchCombination"); StringTokenizer st = new StringTokenizer(axisValuesStr, ","); List<String> combination = new ArrayList<String>(); String axisValue = ""; while (st.hasMoreTokens()) { axisValue = st.nextToken(); // axisValue is xx/xx/xx where xx are nodeId axisValue = axisValue.substring(axisValue.lastIndexOf('/') + 1, axisValue.length()); combination.add(axisValue); } kmelia.addPublicationToCombination(pubId, combination); // Store current combination kmelia.setCurrentCombination(kmelia.getCombination(axisValuesStr)); destination = getDestination("KmaxViewCombination", kmelia, request); } else if (function.equals("KmaxDeleteCoordinate")) { String coordinateId = request.getParameter("CoordinateId"); String pubId = request.getParameter("PubId"); SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "coordinateId = " + coordinateId + " PubId=" + pubId); kmelia.deletePublicationFromCombination(pubId, coordinateId); destination = getDestination("KmaxViewCombination", kmelia, request); } else if (function.equals("KmaxExportComponent")) { // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublications(); request.setAttribute("selectedResultsWa", publicationsIds); // Go to importExportPeas destination = "/RimportExportPeas/jsp/KmaxExportComponent"; } else if (function.equals("KmaxExportPublications")) { // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getCurrentPublicationsList(); List<String> combination = kmelia.getSessionCombination(); // get the time axis String timeCriteria = null; if (kmelia.isTimeAxisUsed() && StringUtil.isDefined(kmelia.getSessionTimeCriteria())) { ResourceLocator timeSettings = new ResourceLocator("com.stratelia.webactiv.kmelia.multilang.timeAxisBundle", kmelia. getLanguage()); if (kmelia.getSessionTimeCriteria().equals("X")) { timeCriteria = null; } else { timeCriteria = "<b>" + kmelia.getString("TimeAxis") + "</b> > " + timeSettings.getString(kmelia.getSessionTimeCriteria(), ""); } } request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("Combination", combination); request.setAttribute("TimeCriteria", timeCriteria); // Go to importExportPeas destination = "/RimportExportPeas/jsp/KmaxExportPublications"; }/************ End Kmax Mode *****************/ else { destination = rootDestination + function; } if (profileError) { String sessionTimeout = GeneralPropertiesManager.getGeneralResourceLocator().getString("sessionTimeout"); destination = sessionTimeout; } SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "destination = " + destination); } catch (Exception exce_all) { request.setAttribute("javax.servlet.jsp.jspException", exce_all); return "/admin/jsp/errorpageMain.jsp"; } return destination; }
public String getDestination(String function, ComponentSessionController componentSC, HttpServletRequest request) { SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function); String destination = ""; String rootDestination = "/kmelia/jsp/"; boolean profileError = false; boolean kmaxMode = false; boolean toolboxMode = false; try { KmeliaSessionController kmelia = (KmeliaSessionController) componentSC; SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "getComponentRootName() = " + kmelia.getComponentRootName()); if ("kmax".equals(kmelia.getComponentRootName())) { kmaxMode = true; kmelia.isKmaxMode = true; } request.setAttribute("KmaxMode", Boolean.valueOf(kmaxMode)); toolboxMode = KmeliaHelper.isToolbox(kmelia.getComponentId()); // Set language choosen by the user setLanguage(request, kmelia); if (function.startsWith("Main")) { resetWizard(kmelia); if (kmaxMode) { destination = getDestination("KmaxMain", componentSC, request); kmelia.setSessionTopic(null); kmelia.setSessionPath(""); } else { destination = getDestination("GoToTopic", componentSC, request); } } else if (function.startsWith("portlet")) { kmelia.setSessionPublication(null); String flag = componentSC.getUserRoleLevel(); if (kmaxMode) { destination = rootDestination + "kmax_portlet.jsp?Profile=" + flag; } else { destination = rootDestination + "portlet.jsp?Profile=user"; } } else if (function.equals("FlushTrashCan")) { kmelia.flushTrashCan(); if (kmaxMode) { destination = getDestination("KmaxMain", kmelia, request); } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else if (function.equals("GoToDirectory")) { String topicId = request.getParameter("Id"); String path = null; if (StringUtil.isDefined(topicId)) { NodeDetail topic = kmelia.getNodeHeader(topicId); path = topic.getPath(); } else { path = request.getParameter("Path"); } FileFolder folder = new FileFolder(path); request.setAttribute("Directory", folder); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); destination = rootDestination + "repository.jsp"; } else if (function.equals("GoToTopic")) { String topicId = (String) request.getAttribute("Id"); if (!StringUtil.isDefined(topicId)) { topicId = request.getParameter("Id"); if (!StringUtil.isDefined(topicId)) { topicId = "0"; } } TopicDetail currentTopic = kmelia.getTopic(topicId, true); processPath(kmelia, null); kmelia.setSessionPublication(null); resetWizard(kmelia); request.setAttribute("CurrentTopic", currentTopic); request.setAttribute("PathString", kmelia.getSessionPathString()); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Treeview", kmelia.getTreeview()); request.setAttribute("DisplayNBPublis", Boolean.valueOf(kmelia.displayNbPublis())); request.setAttribute("DisplaySearch", new Boolean(kmelia.isSearchOnTopicsEnabled())); // rechercher si le theme a un descripteur request.setAttribute("HaveDescriptor", Boolean.valueOf(kmelia. isTopicHaveUpdateChainDescriptor())); if ("noRights".equalsIgnoreCase(currentTopic.getNodeDetail().getUserRole())) { destination = rootDestination + "toCrossTopic.jsp"; } else { request.setAttribute("Profile", kmelia.getUserTopicProfile(topicId)); request.setAttribute("IsGuest", Boolean.valueOf(kmelia.getUserDetail().isAccessGuest())); request.setAttribute("RightsOnTopicsEnabled", Boolean.valueOf(kmelia. isRightsOnTopicsEnabled())); request.setAttribute("WysiwygDescription", kmelia.getWysiwygOnTopic()); if (kmelia.isTreeStructure()) { destination = rootDestination + "topicManager.jsp"; } else { destination = rootDestination + "simpleListOfPublications.jsp"; } } } else if (function.equals("GoToCurrentTopic")) { if (kmelia.getSessionTopic() != null) { String id = kmelia.getSessionTopic().getNodePK().getId(); request.setAttribute("Id", id); destination = getDestination("GoToTopic", kmelia, request); } else { destination = getDestination("Main", kmelia, request); } } else if (function.equals("GoToBasket")) { destination = rootDestination + "basket.jsp"; } else if (function.equals("ViewPublicationsToValidate")) { destination = rootDestination + "publicationsToValidate.jsp"; } else if (function.startsWith("searchResult")) { resetWizard(kmelia); String id = request.getParameter("Id"); String type = request.getParameter("Type"); String fileAlreadyOpened = request.getParameter("FileOpened"); if (type.equals("Publication") || type.equals("com.stratelia.webactiv.calendar.backbone.TodoDetail") || type.equals("Attachment") || type.equals("Document")) { KmeliaSecurity security = new KmeliaSecurity(kmelia.getOrganizationController()); try { boolean accessAuthorized = security.isAccessAuthorized(kmelia.getComponentId(), kmelia.getUserId(), id, "Publication"); if (accessAuthorized) { if (type.equals("Attachment")) { String attachmentId = request.getParameter("AttachmentId"); request.setAttribute("AttachmentId", attachmentId); destination = getDestination("ViewPublication", kmelia, request); } else if (type.equals("Document")) { String documentId = request.getParameter("DocumentId"); request.setAttribute("DocumentId", documentId); destination = getDestination("ViewPublication", kmelia, request); } else { if (kmaxMode) { request.setAttribute("FileAlreadyOpened", fileAlreadyOpened); destination = getDestination("ViewPublication", kmelia, request); } else if (toolboxMode) { processPath(kmelia, id); // we have to find which page contains the right publication List<UserPublication> publications = new ArrayList<UserPublication>( kmelia.getSessionTopic().getPublicationDetails()); UserPublication publication = null; int pubIndex = -1; for (int p = 0; p < publications.size() && pubIndex == -1; p++) { publication = publications.get(p); if (id.equals(publication.getPublication().getPK().getId())) { pubIndex = p; } } int nbPubliPerPage = kmelia.getNbPublicationsPerPage(); if (nbPubliPerPage == 0) { nbPubliPerPage = pubIndex; } int ipage = pubIndex / nbPubliPerPage; kmelia.setIndexOfFirstPubToDisplay(Integer.toString(ipage * nbPubliPerPage)); request.setAttribute("PubIdToHighlight", id); destination = getDestination("GoToCurrentTopic", kmelia, request); } else { request.setAttribute("FileAlreadyOpened", fileAlreadyOpened); processPath(kmelia, id); destination = getDestination("ViewPublication", kmelia, request); } } } else { destination = "/admin/jsp/accessForbidden.jsp"; } } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e); destination = getDocumentNotFoundDestination(kmelia, request); } } else if (type.equals("Node")) { if (kmaxMode) { // Simuler l'action d'un utilisateur ayant sélectionné la valeur id d'un axe // SearchCombination est un chemin /0/4/i NodeDetail node = kmelia.getNodeHeader(id); String path = node.getPath() + id; request.setAttribute("SearchCombination", path); destination = getDestination("KmaxSearch", componentSC, request); } else { try { request.setAttribute("Id", id); destination = getDestination("GoToTopic", componentSC, request); } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e); destination = getDocumentNotFoundDestination(kmelia, request); } } } else if (type.equals("Wysiwyg")) { if (id.startsWith("Node")) { id = id.substring(5, id.length()); request.setAttribute("Id", id); destination = getDestination("GoToTopic", componentSC, request); } else { /* * if (kmaxMode) destination = getDestination("KmaxViewPublication", kmelia, request); * else */ destination = getDestination("ViewPublication", kmelia, request); } } else { request.setAttribute("Id", "0"); destination = getDestination("GoToTopic", componentSC, request); } } else if (function.startsWith("GoToFilesTab")) { String id = request.getParameter("Id"); try { processPath(kmelia, id); if (toolboxMode) { UserCompletePublication userPubComplete = kmelia.getUserCompletePublication(id); kmelia.setSessionPublication(userPubComplete); kmelia.setSessionOwner(true); destination = getDestination("ViewAttachments", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } catch (Exception e) { SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e); destination = getDocumentNotFoundDestination(kmelia, request); } } else if (function.startsWith("publicationManager")) { String flag = kmelia.getProfile(); request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "publicationManager.jsp?Profile=" + flag; // thumbnail error for front explication if (request.getParameter("errorThumbnail") != null) { destination = destination + "&resultThumbnail=" + request.getParameter("errorThumbnail"); } } else if (function.equals("ToAddTopic")) { String topicId = request.getParameter("Id"); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(topicId))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { String isLink = request.getParameter("IsLink"); if (StringUtil.isDefined(isLink)) { request.setAttribute("IsLink", Boolean.TRUE); } List<NodeDetail> path = kmelia.getTopicPath(topicId); request.setAttribute("Path", kmelia.displayPath(path, false, 3)); request.setAttribute("PathLinked", kmelia.displayPath(path, true, 3)); request.setAttribute("Translation", kmelia.getCurrentLanguage()); request.setAttribute("PopupDisplay", Boolean.TRUE); request.setAttribute("NotificationAllowed", Boolean.valueOf(kmelia.isNotificationAllowed())); request.setAttribute("Parent", kmelia.getNodeHeader(topicId)); if (kmelia.isRightsOnTopicsEnabled()) { request.setAttribute("PopupDisplay", Boolean.FALSE); request.setAttribute("Profiles", kmelia.getTopicProfiles()); // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } destination = rootDestination + "addTopic.jsp"; } } else if ("ToUpdateTopic".equals(function)) { String id = request.getParameter("Id"); NodeDetail node = kmelia.getSubTopicDetail(id); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(id)) && !SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(node.getFatherPK().getId()))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { request.setAttribute("NodeDetail", node); List<NodeDetail> path = kmelia.getTopicPath(id); request.setAttribute("Path", kmelia.displayPath(path, false, 3)); request.setAttribute("PathLinked", kmelia.displayPath(path, true, 3)); request.setAttribute("Translation", kmelia.getCurrentLanguage()); request.setAttribute("PopupDisplay", Boolean.TRUE); request.setAttribute("NotificationAllowed", Boolean.valueOf(kmelia.isNotificationAllowed())); if (kmelia.isRightsOnTopicsEnabled()) { request.setAttribute("PopupDisplay", Boolean.FALSE); request.setAttribute("Profiles", kmelia.getTopicProfiles(id)); if (node.haveInheritedRights()) { request.setAttribute("RightsDependsOn", "AnotherTopic"); } else if (node.haveLocalRights()) { request.setAttribute("RightsDependsOn", "ThisTopic"); } else { // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } } destination = rootDestination + "updateTopicNew.jsp"; } } else if (function.equals("AddTopic")) { String name = request.getParameter("Name"); String description = request.getParameter("Description"); String alertType = request.getParameter("AlertType"); if (!StringUtil.isDefined(alertType)) { alertType = "None"; } String rightsUsed = request.getParameter("RightsUsed"); String path = request.getParameter("Path"); String parentId = request.getParameter("ParentId"); NodeDetail topic = new NodeDetail("-1", name, description, null, null, null, "0", "X"); I18NHelper.setI18NInfo(topic, request); if (StringUtil.isDefined(path)) { topic.setType(NodeDetail.FILE_LINK_TYPE); topic.setPath(path); } int rightsDependsOn = -1; if (StringUtil.isDefined(rightsUsed)) { if ("father".equalsIgnoreCase(rightsUsed)) { NodeDetail father = kmelia.getSessionTopic().getNodeDetail(); rightsDependsOn = father.getRightsDependsOn(); } else { rightsDependsOn = 0; } topic.setRightsDependsOn(rightsDependsOn); } NodePK nodePK = kmelia.addSubTopic(topic, alertType, parentId); if (kmelia.isRightsOnTopicsEnabled()) { if (rightsDependsOn == 0) { request.setAttribute("NodeId", nodePK.getId()); destination = getDestination("ViewTopicProfiles", componentSC, request); } else { destination = getDestination("GoToCurrentTopic", componentSC, request); } } else { request.setAttribute("urlToReload", "GoToCurrentTopic"); destination = rootDestination + "closeWindow.jsp"; } } else if ("UpdateTopic".equals(function)) { String name = request.getParameter("Name"); String description = request.getParameter("Description"); String alertType = request.getParameter("AlertType"); if (!StringUtil.isDefined(alertType)) { alertType = "None"; } String id = request.getParameter("ChildId"); String path = request.getParameter("Path"); NodeDetail topic = new NodeDetail(id, name, description, null, null, null, "0", "X"); I18NHelper.setI18NInfo(topic, request); if (StringUtil.isDefined(path)) { topic.setType(NodeDetail.FILE_LINK_TYPE); topic.setPath(path); } kmelia.updateTopicHeader(topic, alertType); if (kmelia.isRightsOnTopicsEnabled()) { int rightsUsed = Integer.parseInt(request.getParameter("RightsUsed")); topic = kmelia.getNodeHeader(id); if (topic.getRightsDependsOn() != rightsUsed) { // rights dependency have changed if (rightsUsed == -1) { kmelia.updateTopicDependency(topic, false); destination = getDestination("GoToCurrentTopic", componentSC, request); } else { kmelia.updateTopicDependency(topic, true); request.setAttribute("NodeId", id); destination = getDestination("ViewTopicProfiles", componentSC, request); } } else { destination = getDestination("GoToCurrentTopic", componentSC, request); } } else { request.setAttribute("urlToReload", "GoToCurrentTopic"); destination = rootDestination + "closeWindow.jsp"; } } else if (function.equals("DeleteTopic")) { String id = request.getParameter("Id"); kmelia.deleteTopic(id); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ViewClone")) { PublicationDetail pubDetail = kmelia.getSessionPublication().getPublication().getPublicationDetail(); // Reload clone and put it into session String cloneId = pubDetail.getCloneId(); UserCompletePublication userPubComplete = kmelia.getUserCompletePublication(cloneId); kmelia.setSessionClone(userPubComplete); request.setAttribute("Publication", userPubComplete); request.setAttribute("Profile", kmelia.getProfile()); request.setAttribute("VisiblePublicationId", pubDetail.getPK().getId()); putXMLDisplayerIntoRequest(userPubComplete.getPublication().getPublicationDetail(), kmelia, request); destination = rootDestination + "clone.jsp"; } else if (function.equals("ViewPublication")) { String id = request.getParameter("PubId"); if (!StringUtil.isDefined(id)) { id = request.getParameter("Id"); if (!StringUtil.isDefined(id)) { id = (String) request.getAttribute("PubId"); } } if (!kmaxMode) { boolean checkPath = StringUtil.getBooleanValue(request.getParameter("CheckPath")); if (checkPath) { processPath(kmelia, id); } else { processPath(kmelia, null); } } UserCompletePublication userPubComplete = null; if (StringUtil.isDefined(id)) { userPubComplete = kmelia.getUserCompletePublication(id, true); kmelia.setSessionPublication(userPubComplete); PublicationDetail pubDetail = userPubComplete.getPublication().getPublicationDetail(); if (pubDetail.haveGotClone()) { UserCompletePublication clone = kmelia.getUserCompletePublication(pubDetail.getCloneId()); kmelia.setSessionClone(clone); } } else { userPubComplete = kmelia.getSessionPublication(); id = userPubComplete.getPublication().getPublicationDetail().getPK().getId(); } if (toolboxMode) { destination = rootDestination + "publicationManager.jsp?Action=UpdateView&PubId=" + id + "&Profile=" + kmelia.getProfile(); } else { List<String> publicationLanguages = kmelia.getPublicationLanguages(); // languages of // publication // header and attachments if (publicationLanguages.contains(kmelia.getCurrentLanguage())) { request.setAttribute("ContentLanguage", kmelia.getCurrentLanguage()); } else { request.setAttribute("ContentLanguage", checkLanguage(kmelia, userPubComplete. getPublication().getPublicationDetail())); } request.setAttribute("Languages", publicationLanguages); // see also management Collection<ForeignPK> links = userPubComplete.getPublication().getLinkList(); HashSet<String> linkedList = new HashSet<String>(); for (ForeignPK link : links) { linkedList.add(link.getId() + "/" + link.getInstanceId()); } // put into session the current list of selected publications (see also) request.getSession().setAttribute(KmeliaConstants.PUB_TO_LINK_SESSION_KEY, linkedList); request.setAttribute("Publication", userPubComplete); request.setAttribute("PubId", id); request.setAttribute("ValidationStep", kmelia.getValidationStep()); request.setAttribute("ValidationType", new Integer(kmelia.getValidationType())); // check if user is writer with approval right (versioning case) request.setAttribute("WriterApproval", Boolean.valueOf(kmelia.isWriterApproval(id))); request.setAttribute("NotificationAllowed", Boolean.valueOf(kmelia.isNotificationAllowed())); // check is requested publication is an alias checkAlias(kmelia, userPubComplete); if (userPubComplete.isAlias()) { request.setAttribute("Profile", "user"); request.setAttribute("IsAlias", "1"); } else { request.setAttribute("Profile", kmelia.getProfile()); } request.setAttribute("Wizard", kmelia.getWizard()); request.setAttribute("Rang", new Integer(kmelia.getRang())); if (kmelia.getSessionPublicationsList() != null) { request.setAttribute("NbPublis", new Integer(kmelia.getSessionPublicationsList().size())); } else { request.setAttribute("NbPublis", new Integer(1)); } putXMLDisplayerIntoRequest(userPubComplete.getPublication().getPublicationDetail(), kmelia, request); String fileAlreadyOpened = (String) request.getAttribute("FileAlreadyOpened"); boolean alreadyOpened = "1".equals(fileAlreadyOpened); String attachmentId = (String) request.getAttribute("AttachmentId"); String documentId = (String) request.getAttribute("DocumentId"); if (!alreadyOpened && kmelia.openSingleAttachmentAutomatically() && !kmelia.isCurrentPublicationHaveContent()) { request.setAttribute("SingleAttachmentURL", kmelia. getFirstAttachmentURLOfCurrentPublication()); } else if (!alreadyOpened && attachmentId != null) { request.setAttribute("SingleAttachmentURL", kmelia.getAttachmentURL(attachmentId)); } else if (!alreadyOpened && documentId != null) { request.setAttribute("SingleAttachmentURL", kmelia.getAttachmentURL(documentId)); } destination = rootDestination + "publication.jsp"; } } else if (function.equals("PreviousPublication")) { // récupération de la publication précédente String pubId = kmelia.getPrevious(); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("NextPublication")) { // récupération de la publication suivante String pubId = kmelia.getNext(); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.startsWith("copy")) { String objectType = request.getParameter("Object"); String objectId = request.getParameter("Id"); if (StringUtil.isDefined(objectType) && "Node".equalsIgnoreCase(objectType)) { kmelia.copyTopic(objectId); } else { kmelia.copyPublication(objectId); } destination = URLManager.getURL(URLManager.CMP_CLIPBOARD) + "Idle.jsp?message=REFRESHCLIPBOARD"; } else if (function.startsWith("cut")) { String objectType = request.getParameter("Object"); String objectId = request.getParameter("Id"); if (StringUtil.isDefined(objectType) && "Node".equalsIgnoreCase(objectType)) { kmelia.cutTopic(objectId); } else { kmelia.cutPublication(objectId); } destination = URLManager.getURL(URLManager.CMP_CLIPBOARD) + "Idle.jsp?message=REFRESHCLIPBOARD"; } else if (function.startsWith("paste")) { kmelia.paste(); destination = URLManager.getURL(URLManager.CMP_CLIPBOARD) + "Idle.jsp"; } else if (function.startsWith("ToAlertUserAttachment")) { // utilisation de alertUser et alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserAttachment: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { String attachmentId = request.getParameter("AttachmentOrDocumentId"); destination = kmelia.initAlertUserAttachment(attachmentId, false); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserAttachment: function = " + function + "=> destination=" + destination); } else if (function.startsWith("ToAlertUserDocument")) { // utilisation de alertUser et alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserDocument: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { String documentId = request.getParameter("AttachmentOrDocumentId"); destination = kmelia.initAlertUserAttachment(documentId, true); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUserDocument: function = " + function + "=> destination=" + destination); } else if (function.startsWith("ToAlertUser")) { // utilisation de alertUser et alertUserPeas SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUser: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId=" + kmelia.getComponentId()); try { destination = kmelia.initAlertUser(); } catch (Exception e) { SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "ToAlertUser: function = " + function + "=> destination=" + destination); } else if (function.equals("ReadingControl")) { PublicationDetail publication = kmelia.getSessionPublication().getPublication().getPublicationDetail(); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Publication", publication); request.setAttribute("UserIds", kmelia.getUserIdsOfTopic()); // paramètre du wizard request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "readingControlManager.jsp"; } else if (function.startsWith("ViewAttachments")) { String flag = kmelia.getProfile(); // Versioning is out of "Always visible publication" mode if (kmelia.isCloneNeeded() && !kmelia.isVersionControlled()) { kmelia.clonePublication(); } // put current publication if (!kmelia.isVersionControlled()) { request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getPublication().getPublicationDetail()); } else { request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPublication(). getPublication().getPublicationDetail()); } // Paramètres du wizard setWizardParams(request, kmelia); // Paramètres de i18n List<String> attachmentLanguages = kmelia.getAttachmentLanguages(); if (attachmentLanguages.contains(kmelia.getCurrentLanguage())) { request.setAttribute("Language", kmelia.getCurrentLanguage()); } else { request.setAttribute("Language", checkLanguage(kmelia)); } request.setAttribute("Languages", attachmentLanguages); request.setAttribute("XmlFormForFiles", kmelia.getXmlFormForFiles()); destination = rootDestination + "attachmentManager.jsp?profile=" + flag; } else if (function.equals("DeletePublication")) { String pubId = (String) request.getParameter("PubId"); kmelia.deletePublication(pubId); if (kmaxMode) { destination = getDestination("Main", kmelia, request); } else { destination = getDestination("GoToCurrentTopic", kmelia, request); } } else if (function.equals("DeleteClone")) { kmelia.deleteClone(); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ViewValidationSteps")) { request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Publication", kmelia.getSessionPubliOrClone().getPublication(). getPublicationDetail()); request.setAttribute("ValidationSteps", kmelia.getValidationSteps()); request.setAttribute("Role", kmelia.getProfile()); destination = rootDestination + "validationSteps.jsp"; } else if (function.equals("ValidatePublication")) { String pubId = kmelia.getSessionPublication().getPublication().getPublicationDetail().getPK().getId(); SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function + " pubId=" + pubId); boolean validationComplete = kmelia.validatePublication(pubId); if (validationComplete) { request.setAttribute("Action", "ValidationComplete"); } else { request.setAttribute("Action", "ValidationInProgress"); } request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ForceValidatePublication")) { String pubId = kmelia.getSessionPublication().getPublication().getPublicationDetail().getPK().getId(); kmelia.forcePublicationValidation(pubId); request.setAttribute("Action", "ValidationComplete"); request.setAttribute("PubId", pubId); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("WantToRefusePubli")) { PublicationDetail pubDetail = kmelia.getSessionPubliOrClone().getPublication().getPublicationDetail(); request.setAttribute("PublicationToRefuse", pubDetail); destination = rootDestination + "refusalMotive.jsp"; } else if (function.equals("Unvalidate")) { String motive = request.getParameter("Motive"); String pubId = kmelia.getSessionPublication().getPublication().getPublicationDetail().getPK().getId(); SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "function = " + function + " pubId=" + pubId); kmelia.unvalidatePublication(pubId, motive); request.setAttribute("Action", "Unvalidate"); if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } else if (function.equals("WantToSuspendPubli")) { String pubId = request.getParameter("PubId"); PublicationDetail pubDetail = kmelia.getPublicationDetail(pubId); request.setAttribute("PublicationToSuspend", pubDetail); destination = rootDestination + "defermentMotive.jsp"; } else if (function.equals("SuspendPublication")) { String motive = request.getParameter("Motive"); String pubId = request.getParameter("PubId"); kmelia.suspendPublication(pubId, motive); request.setAttribute("Action", "Suspend"); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("DraftIn")) { kmelia.draftInPublication(); if (kmelia.getSessionClone() != null) { // draft have generate a clone destination = getDestination("ViewClone", componentSC, request); } else { String pubId = kmelia.getSessionPubliOrClone().getPublication().getPublicationDetail().getPK().getId(); String flag = kmelia.getProfile(); String from = request.getParameter("From"); if (StringUtil.isDefined(from)) { destination = getDestination(from, componentSC, request); } else { destination = rootDestination + "publicationManager.jsp?Action=UpdateView&PubId=" + pubId + "&Profile=" + flag; } } } else if (function.equals("DraftOut")) { kmelia.draftOutPublication(); destination = getDestination("ViewPublication", componentSC, request); } else if (function.equals("ToTopicWysiwyg")) { String topicId = request.getParameter("Id"); String subTopicId = request.getParameter("ChildId"); String flag = kmelia.getProfile(); NodeDetail topic = kmelia.getSubTopicDetail(subTopicId); destination = request.getScheme() + "://" + kmelia.getServerNameAndPort() + URLManager.getApplicationURL() + "/wysiwyg/jsp/htmlEditor.jsp?"; destination += "SpaceId=" + kmelia.getSpaceId(); destination += "&SpaceName=" + URLEncoder.encode(kmelia.getSpaceLabel(), "UTF-8"); destination += "&ComponentId=" + kmelia.getComponentId(); destination += "&ComponentName=" + URLEncoder.encode(kmelia.getComponentLabel(), "UTF-8"); destination += "&BrowseInfo=" + URLEncoder.encode(kmelia.getSessionPathString() + " > " + topic.getName() + " > " + kmelia.getString("TopicWysiwyg"), "UTF-8"); destination += "&ObjectId=Node_" + subTopicId; destination += "&Language=fr"; destination += "&ReturnUrl=" + URLEncoder.encode(URLManager.getApplicationURL() + URLManager.getURL(kmelia.getSpaceId(), kmelia.getComponentId()) + "FromTopicWysiwyg?Action=Search&Id=" + topicId + "&ChildId=" + subTopicId + "&Profile=" + flag, "UTF-8"); } else if (function.equals("FromTopicWysiwyg")) { String subTopicId = request.getParameter("ChildId"); kmelia.processTopicWysiwyg(subTopicId); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("TopicUp")) { String subTopicId = request.getParameter("ChildId"); kmelia.changeSubTopicsOrder("up", subTopicId); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("TopicDown")) { String subTopicId = request.getParameter("ChildId"); kmelia.changeSubTopicsOrder("down", subTopicId); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ChangeTopicStatus")) { String subTopicId = request.getParameter("ChildId"); String newStatus = request.getParameter("Status"); String recursive = request.getParameter("Recursive"); if (recursive != null && recursive.equals("1")) { kmelia.changeTopicStatus(newStatus, subTopicId, true); } else { kmelia.changeTopicStatus(newStatus, subTopicId, false); } destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ViewOnly")) { String id = request.getParameter("documentId"); destination = rootDestination + "publicationViewOnly.jsp?Id=" + id; } else if (function.equals("SeeAlso")) { String action = request.getParameter("Action"); if (!StringUtil.isDefined(action)) { action = "LinkAuthorView"; } request.setAttribute("Action", action); // check if requested publication is an alias UserCompletePublication userPubComplete = kmelia.getSessionPublication(); checkAlias(kmelia, userPubComplete); if (userPubComplete.isAlias()) { request.setAttribute("Profile", "user"); request.setAttribute("IsAlias", "1"); } else { request.setAttribute("Profile", kmelia.getProfile()); } // paramètres du wizard request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "seeAlso.jsp"; } else if (function.equals("DeleteSeeAlso")) { String[] pubIds = request.getParameterValues("PubIds"); List<ForeignPK> infoLinks = new ArrayList<ForeignPK>(); StringTokenizer tokens = null; for (String pubId : pubIds) { tokens = new StringTokenizer(pubId, "/"); infoLinks.add(new ForeignPK(tokens.nextToken(), tokens.nextToken())); } if (infoLinks.size() > 0) { kmelia.deleteInfoLinks(kmelia.getSessionPublication().getId(), infoLinks); } destination = getDestination("SeeAlso", kmelia, request); } else if (function.equals("ImportFileUpload")) { destination = processFormUpload(kmelia, request, rootDestination, false); } else if (function.equals("ImportFilesUpload")) { destination = processFormUpload(kmelia, request, rootDestination, true); } else if (function.equals("ExportAttachementsToPDF")) { String topicId = request.getParameter("TopicId"); // build an exploitable list by importExportPeas SilverTrace.info("kmelia", "KmeliaSessionController.getAllVisiblePublicationsByTopic()", "root.MSG_PARAM_VALUE", "topicId =" + topicId); List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublicationsByTopic(topicId); request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("RootId", topicId); // Go to importExportPeas destination = "/RimportExportPeas/jsp/ExportPDF"; } else if (function.equals("NewPublication")) { destination = rootDestination + "publicationManager.jsp?Action=New&CheckPath=0&Profile=" + kmelia.getProfile(); } else if (function.equals("AddPublication")) { List<FileItem> parameters = FileUploadUtil.parseRequest(request); // create publication PublicationDetail pubDetail = getPublicationDetail(parameters, kmelia); String newPubId = kmelia.createPublication(pubDetail); // create vignette if exists processVignette(parameters, kmelia, pubDetail.getInstanceId(), Integer.valueOf(newPubId)); request.setAttribute("PubId", newPubId); processPath(kmelia, newPubId); String wizard = kmelia.getWizard(); if ("progress".equals(wizard)) { UserCompletePublication userPubComplete = kmelia.getUserCompletePublication(newPubId); kmelia.setSessionPublication(userPubComplete); String position = FileUploadUtil.getParameter(parameters, "Position"); setWizardParams(request, kmelia); request.setAttribute("Position", position); request.setAttribute("Publication", userPubComplete); request.setAttribute("Profile", kmelia.getProfile()); destination = getDestination("WizardNext", kmelia, request); } else { StringBuffer requestURI = request.getRequestURL(); destination = requestURI.substring(0, requestURI.indexOf("AddPublication")) + "ViewPublication?PubId=" + newPubId; } } else if (function.equals("UpdatePublication")) { List<FileItem> parameters = FileUploadUtil.parseRequest(request); PublicationDetail pubDetail = getPublicationDetail(parameters, kmelia); kmelia.updatePublication(pubDetail); String id = pubDetail.getPK().getId(); processVignette(parameters, kmelia, pubDetail.getInstanceId(), Integer.valueOf(id)); String wizard = kmelia.getWizard(); if (wizard.equals("progress")) { UserCompletePublication userPubComplete = kmelia.getUserCompletePublication(id); String position = FileUploadUtil.getParameter(parameters, "Position"); setWizardParams(request, kmelia); request.setAttribute("Position", position); request.setAttribute("Publication", userPubComplete); request.setAttribute("Profile", kmelia.getProfile()); destination = getDestination("WizardNext", kmelia, request); } else { if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else { request.setAttribute("PubId", id); request.setAttribute("CheckPath", "1"); destination = getDestination("ViewPublication", kmelia, request); } } } else if (function.equals("SelectValidator")) { destination = kmelia.initUPToSelectValidator(""); } else if (function.equals("Comments")) { String id = request.getParameter("PubId"); String flag = kmelia.getProfile(); if (!kmaxMode) { processPath(kmelia, id); } // paramètre du wizard request.setAttribute("Wizard", kmelia.getWizard()); destination = rootDestination + "comments.jsp?PubId=" + id + "&Profile=" + flag; } else if (function.equals("PublicationPaths")) { // paramètre du wizard request.setAttribute("Wizard", kmelia.getWizard()); PublicationDetail publication = kmelia.getSessionPublication().getPublication().getPublicationDetail(); String pubId = publication.getPK().getId(); request.setAttribute("Publication", publication); request.setAttribute("PathList", kmelia.getPublicationFathers(pubId)); request.setAttribute("LinkedPathString", kmelia.getSessionPath()); request.setAttribute("Topics", kmelia.getAllTopics()); List<Alias> aliases = kmelia.getAliases(); request.setAttribute("Aliases", aliases); request.setAttribute("OtherComponents", kmelia.getOtherComponents(aliases)); destination = rootDestination + "publicationPaths.jsp"; } else if (function.equals("SetPath")) { String[] topics = request.getParameterValues("topicChoice"); String loadedComponentIds = request.getParameter("LoadedComponentIds"); Alias alias = null; List<Alias> aliases = new ArrayList<Alias>(); for (int i = 0; topics != null && i < topics.length; i++) { String topicId = topics[i]; SilverTrace.debug("kmelia", "KmeliaRequestRouter.setPath()", "root.MSG_GEN_PARAM_VALUE", "topicId = " + topicId); StringTokenizer tokenizer = new StringTokenizer(topicId, ","); String nodeId = tokenizer.nextToken(); String instanceId = tokenizer.nextToken(); alias = new Alias(nodeId, instanceId); alias.setUserId(kmelia.getUserId()); aliases.add(alias); } // Tous les composants ayant un alias n'ont pas forcément été chargés List<Alias> oldAliases = kmelia.getAliases(); Alias oldAlias; for (int a = 0; a < oldAliases.size(); a++) { oldAlias = oldAliases.get(a); if (loadedComponentIds.indexOf(oldAlias.getInstanceId()) == -1) { // le composant de l'alias n'a pas été chargé aliases.add(oldAlias); } } kmelia.setAliases(aliases); destination = getDestination("ViewPublication", kmelia, request); } else if (function.equals("ShowAliasTree")) { String componentId = request.getParameter("ComponentId"); request.setAttribute("Tree", kmelia.getAliasTreeview(componentId)); request.setAttribute("Aliases", kmelia.getAliases()); destination = rootDestination + "treeview4PublicationPaths.jsp"; } else if (function.equals("AddLinksToPublication")) { String id = request.getParameter("PubId"); String topicId = request.getParameter("TopicId"); HashSet<String> list = (HashSet<String>) request.getSession().getAttribute( KmeliaConstants.PUB_TO_LINK_SESSION_KEY); int nb = kmelia.addPublicationsToLink(id, list); request.setAttribute("NbLinks", Integer.toString(nb)); destination = rootDestination + "publicationLinksManager.jsp?Action=Add&Id=" + topicId; } else if (function.equals("ExportComponent")) { if (kmaxMode) { destination = getDestination("KmaxExportComponent", kmelia, request); } else { // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublications(); request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("RootId", "0"); // Go to importExportPeas destination = "/RimportExportPeas/jsp/ExportItems"; } } else if (function.equals("ExportTopic")) { if (kmaxMode) { destination = getDestination("KmaxExportPublications", kmelia, request); } else { // récupération du topicId String topicId = request.getParameter("TopicId"); // build an exploitable list by importExportPeas SilverTrace.info("kmelia", "KmeliaSessionController.getAllVisiblePublicationsByTopic()", "root.MSG_PARAM_VALUE", "topicId =" + topicId); List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublicationsByTopic(topicId); request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("RootId", topicId); // Go to importExportPeas destination = "/RimportExportPeas/jsp/ExportItems"; } } else if (function.equals("ToPubliContent")) { CompletePublication completePublication = kmelia.getSessionPubliOrClone().getPublication(); if (completePublication.getModelDetail() != null) { destination = getDestination("ToDBModel", kmelia, request); } else if (WysiwygController.haveGotWysiwyg(kmelia.getSpaceId(), kmelia.getComponentId(), completePublication.getPublicationDetail().getPK().getId())) { destination = getDestination("ToWysiwyg", kmelia, request); } else { String infoId = completePublication.getPublicationDetail().getInfoId(); if (infoId == null || "0".equals(infoId)) { List<String> usedModels = (List<String>) kmelia.getModelUsed(); if (usedModels.size() == 1) { String modelId = usedModels.get(0); if ("WYSIWYG".equals(modelId)) { // Wysiwyg content destination = getDestination("ToWysiwyg", kmelia, request); } else if (isInteger(modelId)) { // DB template ModelDetail model = kmelia.getModelDetail(modelId); request.setAttribute("ModelDetail", model); destination = getDestination("ToDBModel", kmelia, request); } else { // XML template setXMLForm(request, kmelia, modelId); // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getPublication().getPublicationDetail()); // Parametres du Wizard setWizardParams(request, kmelia); destination = rootDestination + "xmlForm.jsp"; } } else { destination = getDestination("ListModels", kmelia, request); } } else { destination = getDestination("GoToXMLForm", kmelia, request); } } } else if (function.equals("ListModels")) { Collection<String> modelUsed = kmelia.getModelUsed(); Collection<PublicationTemplate> listModelXml = new ArrayList<PublicationTemplate>(); List<PublicationTemplate> templates = new ArrayList<PublicationTemplate>(); try { templates = getPublicationTemplateManager().getPublicationTemplates(); // recherche de la liste des modèles utilisables PublicationTemplate xmlForm; Iterator<PublicationTemplate> iterator = templates.iterator(); while (iterator.hasNext()) { xmlForm = iterator.next(); // recherche si le modèle est dans la liste if (modelUsed.contains(xmlForm.getFileName())) { listModelXml.add(xmlForm); } } request.setAttribute("XMLForms", listModelXml); } catch (Exception e) { SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination(ListModels)", "root.MSG_GEN_PARAM_VALUE", "", e); } // put dbForms Collection<ModelDetail> dbForms = kmelia.getAllModels(); // recherche de la liste des modèles utilisables Collection<ModelDetail> listModelForm = new ArrayList<ModelDetail>(); ModelDetail modelDetail; Iterator<ModelDetail> iterator = dbForms.iterator(); while (iterator.hasNext()) { modelDetail = iterator.next(); // recherche si le modèle est dans la liste if (modelUsed.contains(modelDetail.getId())) { listModelForm.add(modelDetail); } } request.setAttribute("DBForms", listModelForm); // recherche si modele Wysiwyg utilisable boolean wysiwygValid = false; if (modelUsed.contains("WYSIWYG")) { wysiwygValid = true; } request.setAttribute("WysiwygValid", Boolean.valueOf(wysiwygValid)); // s'il n'y a pas de modèles selectionnés, les présenter tous if (((listModelXml == null) || (listModelXml.isEmpty())) && ((listModelForm == null) || (listModelForm.isEmpty())) && (!wysiwygValid)) { request.setAttribute("XMLForms", templates); request.setAttribute("DBForms", dbForms); request.setAttribute("WysiwygValid", Boolean.TRUE); } // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPublication(). getPublication().getPublicationDetail()); // Paramètres du wizard setWizardParams(request, kmelia); destination = rootDestination + "modelsList.jsp"; } else if (function.equals("ModelUsed")) { try { List<PublicationTemplate> templates = getPublicationTemplateManager().getPublicationTemplates(); request.setAttribute("XMLForms", templates); } catch (Exception e) { SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination(ModelUsed)", "root.MSG_GEN_PARAM_VALUE", "", e); } // put dbForms Collection<ModelDetail> dbForms = kmelia.getAllModels(); request.setAttribute("DBForms", dbForms); Collection<String> modelUsed = kmelia.getModelUsed(); request.setAttribute("ModelUsed", modelUsed); destination = rootDestination + "modelUsedList.jsp"; } else if (function.equals("SelectModel")) { Object o = request.getParameterValues("modelChoice"); if (o != null) { kmelia.addModelUsed((String[]) o); } destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ToWysiwyg")) { if (kmelia.isCloneNeeded()) { kmelia.clonePublication(); } // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getPublication().getPublicationDetail()); // Parametres du Wizard setWizardParams(request, kmelia); request.setAttribute("CurrentLanguage", checkLanguage(kmelia)); destination = rootDestination + "toWysiwyg.jsp"; } else if (function.equals("FromWysiwyg")) { String id = request.getParameter("PubId"); // Parametres du Wizard String wizard = kmelia.getWizard(); setWizardParams(request, kmelia); if (wizard.equals("progress")) { request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { if (kmelia.getSessionClone() != null && id.equals(kmelia.getSessionClone().getPublication().getPublicationDetail().getPK(). getId())) { destination = getDestination("ViewClone", componentSC, request); } else { destination = getDestination("ViewPublication", componentSC, request); } } } else if (function.equals("ToDBModel")) { String modelId = request.getParameter("ModelId"); if (StringUtil.isDefined(modelId)) { ModelDetail model = kmelia.getModelDetail(modelId); request.setAttribute("ModelDetail", model); } // put current publication request.setAttribute("CompletePublication", kmelia.getSessionPubliOrClone().getPublication()); request.setAttribute("NotificationAllowed", Boolean.valueOf(kmelia.isNotificationAllowed())); // Paramètres du wizard setWizardParams(request, kmelia); destination = rootDestination + "modelManager.jsp"; } else if (function.equals("UpdateDBModelContent")) { ResourceLocator publicationSettings = kmelia.getPublicationSettings(); List<InfoTextDetail> textDetails = new ArrayList<InfoTextDetail>(); List<InfoImageDetail> imageDetails = new ArrayList<InfoImageDetail>(); String theText = null; int textOrder = 0; int imageOrder = 0; String logicalName = ""; String physicalName = ""; long size = 0; String type = ""; String mimeType = ""; File dir = null; InfoDetail infos = null; boolean imageTrouble = false; boolean runOnUnix = !FileUtil.isWindows(); List<FileItem> parameters = FileUploadUtil.parseRequest(request); String modelId = FileUploadUtil.getParameter(parameters, "ModelId"); // Parametres du Wizard setWizardParams(request, kmelia); Iterator<FileItem> iter = parameters.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField() && item.getFieldName().startsWith("WATXTVAR")) { theText = item.getString(); textOrder = new Integer(item.getFieldName().substring(8, item.getFieldName().length())).intValue(); textDetails.add(new InfoTextDetail(null, new Integer(textOrder).toString(), null, theText)); } else if (!item.isFormField()) { logicalName = item.getName(); if (logicalName != null && logicalName.length() > 0) { // the part actually contained a file if (runOnUnix) { logicalName = logicalName.replace('\\', File.separatorChar); SilverTrace.info("kmelia", "KmeliaRequestRouter.UpdateDBModelContent", "root.MSG_GEN_PARAM_VALUE", "fileName on Unix = " + logicalName); } logicalName = logicalName.substring(logicalName.lastIndexOf(File.separator) + 1, logicalName. length()); type = logicalName.substring(logicalName.lastIndexOf(".") + 1, logicalName.length()); physicalName = new Long(new Date().getTime()).toString() + "." + type; mimeType = item.getContentType(); size = item.getSize(); dir = new File(FileRepositoryManager.getAbsolutePath(kmelia.getComponentId()) + publicationSettings.getString("imagesSubDirectory") + File.separator + physicalName); if (type.equalsIgnoreCase("gif") || type.equalsIgnoreCase("jpg") || type.equalsIgnoreCase("jpeg") || type.equalsIgnoreCase("png")) { item.write(dir); imageOrder++; if (size > 0) { imageDetails.add(new InfoImageDetail(null, new Integer(imageOrder).toString(), null, physicalName, logicalName, "", mimeType, size)); imageTrouble = false; } else { imageTrouble = true; } } else { imageTrouble = true; } } else { // the field did not contain a file } } } infos = new InfoDetail(null, textDetails, imageDetails, null, ""); CompletePublication completePub = kmelia.getSessionPubliOrClone().getPublication(); if (completePub.getModelDetail() == null) { kmelia.createInfoModelDetail("useless", modelId, infos); } else { kmelia.updateInfoDetail("useless", infos); } if (imageTrouble) { request.setAttribute("ImageTrouble", Boolean.TRUE); } String wizard = kmelia.getWizard(); if (wizard.equals("progress")) { request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { destination = getDestination("ToDBModel", kmelia, request); } } else if (function.equals("GoToXMLForm")) { String xmlFormName = request.getParameter("Name"); setXMLForm(request, kmelia, xmlFormName); // put current publication request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone(). getPublication().getPublicationDetail()); // Parametres du Wizard setWizardParams(request, kmelia); destination = rootDestination + "xmlForm.jsp"; } else if (function.equals("UpdateXMLForm")) { if (kmelia.isCloneNeeded()) { kmelia.clonePublication(); } if (!StringUtil.isDefined(request.getCharacterEncoding())) { request.setCharacterEncoding("UTF-8"); } String encoding = request.getCharacterEncoding(); List<FileItem> items = FileUploadUtil.parseRequest(request); PublicationDetail pubDetail = kmelia.getSessionPubliOrClone().getPublication().getPublicationDetail(); String xmlFormShortName = null; // Is it the creation of the content or an update ? String infoId = pubDetail.getInfoId(); if (infoId == null || "0".equals(infoId)) { String xmlFormName = FileUploadUtil.getParameter(items, "Name", null, encoding); // The publication have no content // We have to register xmlForm to publication xmlFormShortName = xmlFormName.substring(xmlFormName.indexOf("/") + 1, xmlFormName.indexOf(".")); pubDetail.setInfoId(xmlFormShortName); kmelia.updatePublication(pubDetail); } else { xmlFormShortName = pubDetail.getInfoId(); } String pubId = pubDetail.getPK().getId(); PublicationTemplate pub = getPublicationTemplateManager().getPublicationTemplate(kmelia.getComponentId() + ":" + xmlFormShortName); RecordSet set = pub.getRecordSet(); Form form = pub.getUpdateForm(); String language = checkLanguage(kmelia, pubDetail); DataRecord data = set.getRecord(pubId, language); if (data == null) { data = set.getEmptyRecord(); data.setId(pubId); data.setLanguage(language); } PagesContext context = new PagesContext("myForm", "3", kmelia.getLanguage(), false, kmelia.getComponentId(), kmelia.getUserId()); context.setEncoding("UTF-8"); if (!kmaxMode) { context.setNodeId(kmelia.getSessionTopic().getNodeDetail().getNodePK().getId()); } context.setObjectId(pubId); context.setContentLanguage(kmelia.getCurrentLanguage()); form.update(items, data, context); set.save(data); // update publication to change updateDate and updaterId kmelia.updatePublication(pubDetail); // Parametres du Wizard setWizardParams(request, kmelia); if (kmelia.getWizard().equals("progress")) { // on est en mode Wizard request.setAttribute("Position", "Content"); destination = getDestination("WizardNext", kmelia, request); } else { if (kmelia.getSessionClone() != null) { destination = getDestination("ViewClone", kmelia, request); } else if (kmaxMode) { destination = getDestination("ViewAttachments", kmelia, request); } else { destination = getDestination("ViewPublication", kmelia, request); } } } else if (function.startsWith("ToOrderPublications")) { List<UserPublication> publications = kmelia.getSessionPublicationsList(); request.setAttribute("Publications", publications); request.setAttribute("Path", kmelia.getSessionPath()); destination = rootDestination + "orderPublications.jsp"; } else if (function.startsWith("OrderPublications")) { String sortedIds = request.getParameter("sortedIds"); StringTokenizer tokenizer = new StringTokenizer(sortedIds, ","); List<String> ids = new ArrayList<String>(); while (tokenizer.hasMoreTokens()) { ids.add(tokenizer.nextToken()); } kmelia.orderPublications(ids); destination = getDestination("GoToCurrentTopic", kmelia, request); } else if (function.equals("ToOrderTopics")) { String id = request.getParameter("Id"); if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(id))) { destination = "/admin/jsp/accessForbidden.jsp"; } else { TopicDetail topic = kmelia.getTopic(id); request.setAttribute("Nodes", topic.getNodeDetail().getChildrenDetails()); destination = rootDestination + "orderTopics.jsp"; } } else if (function.startsWith("Wizard")) { destination = processWizard(function, kmelia, request, rootDestination); } else if (function.equals("ViewPdcPositions")) { // Parametres du Wizard setWizardParams(request, kmelia); destination = rootDestination + "pdcPositions.jsp"; } else if (function.equals("ViewTopicProfiles")) { String role = request.getParameter("Role"); if (!StringUtil.isDefined(role)) { role = SilverpeasRole.admin.toString(); } String id = request.getParameter("NodeId"); if (!StringUtil.isDefined(id)) { id = (String) request.getAttribute("NodeId"); } request.setAttribute("Profiles", kmelia.getTopicProfiles(id)); NodeDetail topic = kmelia.getNodeHeader(id); ProfileInst profile = null; if (topic.haveInheritedRights()) { profile = kmelia.getTopicProfile(role, Integer.toString(topic.getRightsDependsOn())); request.setAttribute("RightsDependsOn", "AnotherTopic"); } else if (topic.haveLocalRights()) { profile = kmelia.getTopicProfile(role, Integer.toString(topic.getRightsDependsOn())); request.setAttribute("RightsDependsOn", "ThisTopic"); } else { profile = kmelia.getProfile(role); // Rights of the component request.setAttribute("RightsDependsOn", "ThisComponent"); } request.setAttribute("CurrentProfile", profile); request.setAttribute("Groups", kmelia.groupIds2Groups(profile.getAllGroups())); request.setAttribute("Users", kmelia.userIds2Users(profile.getAllUsers())); request.setAttribute("Path", kmelia.getSessionPath()); request.setAttribute("NodeDetail", topic); destination = rootDestination + "topicProfiles.jsp"; } else if (function.equals("TopicProfileSelection")) { String role = request.getParameter("Role"); String nodeId = request.getParameter("NodeId"); try { kmelia.initUserPanelForTopicProfile(role, nodeId); } catch (Exception e) { SilverTrace.warn("jobStartPagePeas", "JobStartPagePeasRequestRouter.getDestination()", "root.EX_USERPANEL_FAILED", "function = " + function, e); } destination = Selection.getSelectionURL(Selection.TYPE_USERS_GROUPS); } else if (function.equals("TopicProfileSetUsersAndGroups")) { String role = request.getParameter("Role"); String nodeId = request.getParameter("NodeId"); kmelia.updateTopicRole(role, nodeId); request.setAttribute("urlToReload", "ViewTopicProfiles?Role=" + role + "&NodeId=" + nodeId); destination = rootDestination + "closeWindow.jsp"; } else if (function.equals("TopicProfileRemove")) { String profileId = request.getParameter("Id"); kmelia.deleteTopicRole(profileId); destination = getDestination("ViewTopicProfiles", componentSC, request); } else if (function.equals("CloseWindow")) { destination = rootDestination + "closeWindow.jsp"; } else if (function.startsWith("UpdateChain")) { destination = processUpdateChainOperation(rootDestination, function, kmelia, request); } /*************************** * Kmax mode **************************/ else if (function.equals("KmaxMain")) { destination = rootDestination + "kmax.jsp?Action=KmaxView&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAxisManager")) { destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxViewAxis&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAddAxis")) { String newAxisName = request.getParameter("Name"); String newAxisDescription = request.getParameter("Description"); NodeDetail axis = new NodeDetail("-1", newAxisName, newAxisDescription, DateUtil.today2SQLDate(), kmelia. getUserId(), null, "0", "X"); // I18N I18NHelper.setI18NInfo(axis, request); kmelia.addAxis(axis); request.setAttribute("urlToReload", "KmaxAxisManager"); destination = rootDestination + "closeWindow.jsp"; } else if (function.equals("KmaxUpdateAxis")) { String axisId = request.getParameter("AxisId"); String newAxisName = request.getParameter("AxisName"); String newAxisDescription = request.getParameter("AxisDescription"); NodeDetail axis = new NodeDetail(axisId, newAxisName, newAxisDescription, null, null, null, "0", "X"); // I18N I18NHelper.setI18NInfo(axis, request); kmelia.updateAxis(axis); destination = getDestination("KmaxAxisManager", componentSC, request); } else if (function.equals("KmaxDeleteAxis")) { String axisId = request.getParameter("AxisId"); kmelia.deleteAxis(axisId); destination = getDestination("KmaxAxisManager", componentSC, request); } else if (function.equals("KmaxManageAxis")) { String axisId = request.getParameter("AxisId"); String translation = request.getParameter("Translation"); request.setAttribute("Translation", translation); destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxManageAxis&Profile=" + kmelia.getProfile() + "&AxisId=" + axisId; } else if (function.equals("KmaxManagePosition")) { String positionId = request.getParameter("PositionId"); String translation = request.getParameter("Translation"); request.setAttribute("Translation", translation); destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxManagePosition&Profile=" + kmelia.getProfile() + "&PositionId=" + positionId; } else if (function.equals("KmaxAddPosition")) { String axisId = request.getParameter("AxisId"); String newPositionName = request.getParameter("Name"); String newPositionDescription = request.getParameter("Description"); String translation = request.getParameter("Translation"); NodeDetail position = new NodeDetail("toDefine", newPositionName, newPositionDescription, null, null, null, "0", "X"); // I18N I18NHelper.setI18NInfo(position, request); kmelia.addPosition(axisId, position); request.setAttribute("AxisId", axisId); request.setAttribute("Translation", translation); destination = getDestination("KmaxManageAxis", componentSC, request); } else if (function.equals("KmaxUpdatePosition")) { String positionId = request.getParameter("PositionId"); String positionName = request.getParameter("PositionName"); String positionDescription = request.getParameter("PositionDescription"); NodeDetail position = new NodeDetail(positionId, positionName, positionDescription, null, null, null, "0", "X"); // I18N I18NHelper.setI18NInfo(position, request); kmelia.updatePosition(position); destination = getDestination("KmaxAxisManager", componentSC, request); } else if (function.equals("KmaxDeletePosition")) { String positionId = request.getParameter("PositionId"); kmelia.deletePosition(positionId); destination = getDestination("KmaxAxisManager", componentSC, request); } else if (function.equals("KmaxViewUnbalanced")) { List<UserPublication> publications = kmelia.getUnbalancedPublications(); kmelia.setSessionPublicationsList(publications); kmelia.orderPubs(); destination = rootDestination + "kmax.jsp?Action=KmaxViewUnbalanced&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxViewBasket")) { TopicDetail basket = kmelia.getTopic("1"); List<UserPublication> publications = (List<UserPublication>) basket.getPublicationDetails(); kmelia.setSessionPublicationsList(publications); kmelia.orderPubs(); destination = rootDestination + "kmax.jsp?Action=KmaxViewBasket&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxViewToValidate")) { destination = rootDestination + "kmax.jsp?Action=KmaxViewToValidate&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxSearch")) { String axisValuesStr = request.getParameter("SearchCombination"); if (!StringUtil.isDefined(axisValuesStr)) { axisValuesStr = (String) request.getAttribute("SearchCombination"); } String timeCriteria = request.getParameter("TimeCriteria"); SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "axisValuesStr = " + axisValuesStr + " timeCriteria=" + timeCriteria); List<String> combination = kmelia.getCombination(axisValuesStr); List<UserPublication> publications = null; if (StringUtil.isDefined(timeCriteria) && !timeCriteria.equals("X")) { publications = kmelia.search(combination, new Integer(timeCriteria).intValue()); } else { publications = kmelia.search(combination); } SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "publications = " + publications + " Combination=" + combination + " timeCriteria=" + timeCriteria); kmelia.setIndexOfFirstPubToDisplay("0"); kmelia.orderPubs(); kmelia.setSessionCombination(combination); kmelia.setSessionTimeCriteria(timeCriteria); destination = rootDestination + "kmax.jsp?Action=KmaxSearchResult&Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxSearchResult")) { if (kmelia.getSessionCombination() == null) { destination = getDestination("KmaxMain", kmelia, request); } else { destination = rootDestination + "kmax.jsp?Action=KmaxSearchResult&Profile=" + kmelia.getProfile(); } } else if (function.equals("KmaxViewCombination")) { setWizardParams(request, kmelia); request.setAttribute("CurrentCombination", kmelia.getCurrentCombination()); destination = rootDestination + "kmax_viewCombination.jsp?Profile=" + kmelia.getProfile(); } else if (function.equals("KmaxAddCoordinate")) { String pubId = request.getParameter("PubId"); String axisValuesStr = request.getParameter("SearchCombination"); StringTokenizer st = new StringTokenizer(axisValuesStr, ","); List<String> combination = new ArrayList<String>(); String axisValue = ""; while (st.hasMoreTokens()) { axisValue = st.nextToken(); // axisValue is xx/xx/xx where xx are nodeId axisValue = axisValue.substring(axisValue.lastIndexOf('/') + 1, axisValue.length()); combination.add(axisValue); } kmelia.addPublicationToCombination(pubId, combination); // Store current combination kmelia.setCurrentCombination(kmelia.getCombination(axisValuesStr)); destination = getDestination("KmaxViewCombination", kmelia, request); } else if (function.equals("KmaxDeleteCoordinate")) { String coordinateId = request.getParameter("CoordinateId"); String pubId = request.getParameter("PubId"); SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "coordinateId = " + coordinateId + " PubId=" + pubId); kmelia.deletePublicationFromCombination(pubId, coordinateId); destination = getDestination("KmaxViewCombination", kmelia, request); } else if (function.equals("KmaxExportComponent")) { // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublications(); request.setAttribute("selectedResultsWa", publicationsIds); // Go to importExportPeas destination = "/RimportExportPeas/jsp/KmaxExportComponent"; } else if (function.equals("KmaxExportPublications")) { // build an exploitable list by importExportPeas List<WAAttributeValuePair> publicationsIds = kmelia.getCurrentPublicationsList(); List<String> combination = kmelia.getSessionCombination(); // get the time axis String timeCriteria = null; if (kmelia.isTimeAxisUsed() && StringUtil.isDefined(kmelia.getSessionTimeCriteria())) { ResourceLocator timeSettings = new ResourceLocator("com.stratelia.webactiv.kmelia.multilang.timeAxisBundle", kmelia. getLanguage()); if (kmelia.getSessionTimeCriteria().equals("X")) { timeCriteria = null; } else { timeCriteria = "<b>" + kmelia.getString("TimeAxis") + "</b> > " + timeSettings.getString(kmelia.getSessionTimeCriteria(), ""); } } request.setAttribute("selectedResultsWa", publicationsIds); request.setAttribute("Combination", combination); request.setAttribute("TimeCriteria", timeCriteria); // Go to importExportPeas destination = "/RimportExportPeas/jsp/KmaxExportPublications"; }/************ End Kmax Mode *****************/ else { destination = rootDestination + function; } if (profileError) { String sessionTimeout = GeneralPropertiesManager.getGeneralResourceLocator().getString("sessionTimeout"); destination = sessionTimeout; } SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "destination = " + destination); } catch (Exception exce_all) { request.setAttribute("javax.servlet.jsp.jspException", exce_all); return "/admin/jsp/errorpageMain.jsp"; } return destination; }
diff --git a/dspace/src/org/dspace/app/itemimport/ItemImport.java b/dspace/src/org/dspace/app/itemimport/ItemImport.java index a583373dc..61adaf15a 100755 --- a/dspace/src/org/dspace/app/itemimport/ItemImport.java +++ b/dspace/src/org/dspace/app/itemimport/ItemImport.java @@ -1,840 +1,840 @@ /* * ItemImport.java * * $Id$ * * Version: $Revision$ * * Date: $Date$ * * Copyright (c) 2002, Hewlett-Packard Company and Massachusetts * Institute of Technology. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of the Hewlett-Packard Company nor the name of the * Massachusetts Institute of Technology nor the names of their * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ package org.dspace.app.itemimport; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.StringTokenizer; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.traversal.NodeIterator; import org.xml.sax.SAXException; import org.apache.xpath.XPathAPI; import org.apache.commons.cli.Options; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.PosixParser; import org.dspace.authorize.AuthorizeException; import org.dspace.content.Bitstream; import org.dspace.content.BitstreamFormat; import org.dspace.content.Bundle; import org.dspace.content.Collection; import org.dspace.content.FormatIdentifier; import org.dspace.content.InstallItem; import org.dspace.content.WorkspaceItem; import org.dspace.content.Item; import org.dspace.core.ConfigurationManager; import org.dspace.core.Context; import org.dspace.core.Constants; import org.dspace.eperson.EPerson; import org.dspace.handle.HandleManager; import org.dspace.storage.rdbms.DatabaseManager; import org.dspace.workflow.WorkflowItem; import org.dspace.workflow.WorkflowManager; /* issues javadocs - even though it's not an API allow re-importing list of collections to choose from would be nice too */ /** * The Item importer does exactly that - imports items into * the repository. */ public class ItemImport { static boolean useWorkflow = false; public static void main(String argv[]) throws Exception { // create an options object and populate it CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption( "a", "add", false, "add items to DSpace"); options.addOption( "r", "replace", false, "replace items in mapfile"); options.addOption( "R", "remove", false, "remove items in mapfile"); options.addOption( "s", "source", true, "source of items (directory)"); options.addOption( "c", "collection", true, "destination collection databse ID"); options.addOption( "m", "mapfile", true, "mapfile items in mapfile"); - options.addOption( "e", "eperson", true, "remove items in mapfile"); + options.addOption( "e", "eperson", true, "email of eperson doing importing"); options.addOption( "w", "workflow", false, "send submission through collection's workflow"); options.addOption( "h", "help", false, "help"); CommandLine line = parser.parse( options, argv ); String command = null; // add replace remove, etc String sourcedir = null; String mapfile = null; String eperson = null; // db ID or email String [] collections = null; // db ID or handles if( line.hasOption('h') ) { HelpFormatter myhelp = new HelpFormatter(); myhelp.printHelp( "ItemImport\n", options ); System.out.println("\nadding items: ItemImport -a -e eperson -c collection -s sourcedir -m mapfile"); System.out.println("replacing items: ItemImport -r -e eperson -c collection -s sourcedir -m mapfile"); System.out.println("removing items: ItemImport -R -e eperson -m mapfile"); System.exit(0); } if( line.hasOption( 'a' ) ) { command = "add"; } if( line.hasOption( 'r' ) ) { command = "replace";} if( line.hasOption( 'R' ) ) { command = "remove"; } if( line.hasOption( 'w' ) ) { useWorkflow = true; } if( line.hasOption( 's' ) ) // source { sourcedir = line.getOptionValue( 's' ); } if( line.hasOption( 'm' ) ) // mapfile { mapfile = line.getOptionValue( 'm' ); } if( line.hasOption( 'e' ) ) // eperson { eperson = line.getOptionValue( 'e' ); } if( line.hasOption( 'c' ) ) // collections { collections = line.getOptionValues( 'c' ); } // now validate // must have a command set if( command == null ) { System.out.println("Error - must run with either add, replace, or remove (run with -h flag for details)"); System.exit(1); } else if( command.equals("add") || command.equals("replace") ) { if( sourcedir == null ) { System.out.println("Error - a source directory containing items must be set (run with -h flag for details)"); System.exit(1); } if( mapfile == null ) { System.out.println("Error - a map file to hold importing results must be specified (run with -h flag for details)"); System.exit(1); } if( eperson == null ) { System.out.println("Error - an eperson to do the importing must be specified (run with -h flag for details)"); System.exit(1); } if( collections == null ) { System.out.println("Error - at least one destination collection must be specified (run with -h flag for details)"); System.exit(1); } } else if( command.equals("remove") ) { if( eperson == null ) { System.out.println("Error - an eperson to do the importing must be specified"); System.exit(1); } if( mapfile == null ) { System.out.println("Error - a map file must be specified"); System.exit(1); } } ItemImport myloader = new ItemImport(); // create a context Context c = new Context(); // find the EPerson, assign to context EPerson myEPerson = null; if( eperson.indexOf('@') != -1) { // @ sign, must be an email myEPerson = EPerson.findByEmail( c, eperson ); } else { myEPerson = EPerson.find( c, Integer.parseInt( eperson ) ); } if( myEPerson == null ) { System.out.println( "Error, eperson cannot be found: " + eperson ); System.exit(1); } c.setCurrentUser( myEPerson ); // find collections Collection mycollection = null; // dont' need to validate collections set if command is "remove" if( !command.equals("remove") ) { if( collections[0].indexOf('/') != -1 ) { // has a / must be a handle mycollection = (Collection)HandleManager.resolveToObject( c, collections[0] ); // ensure it's a collection if( (mycollection == null) || (mycollection.getType() != Constants.COLLECTION) ) { mycollection = null; } } else if( collections != null ) { mycollection = Collection.find( c, Integer.parseInt( collections[0] ) ); } if( mycollection == null ) { System.out.println( "Error, collection cannot be found: " + collections[0] ); System.exit(1); } } // end of validating collections try { c.setIgnoreAuthorization( true ); if( command.equals( "add" ) ) { myloader.addItems( c, mycollection, sourcedir, mapfile ); } else if( command.equals( "replace" ) ) { myloader.replaceItems( c, mycollection, sourcedir, mapfile ); } else if( command.equals( "remove" ) ) { myloader.removeItems( c, mapfile ); } // complete all transactions c.complete(); } catch( Exception e ) { // abort all operations c.abort(); e.printStackTrace(); System.out.println( e ); } } private void addItems( Context c, Collection mycollection, String sourceDir, String mapFile ) throws Exception { System.out.println( "Adding items from directory: " + sourceDir ); System.out.println( "Generating mapfile: " + mapFile ); // create the mapfile File outFile = new File( mapFile ); PrintWriter mapOut = new PrintWriter( new FileWriter( outFile ) ); if( mapOut == null ) { throw new Exception("can't open mapfile: " + mapFile); } // now process the source directory File d = new java.io.File( sourceDir ); if( d == null ) { System.out.println("Error, cannot open source directory " + sourceDir); System.exit(1); } String [] dircontents = d.list(); for( int i = 0; i < dircontents.length; i++ ) { addItem( c, mycollection, sourceDir, dircontents[ i ], mapOut ); System.out.println( i + " " + dircontents[ i ] ); } mapOut.close(); } private void replaceItems( Context c, Collection mycollection, String sourceDir, String mapFile ) throws Exception { // verify the source directory File d = new java.io.File( sourceDir ); if( d == null ) { System.out.println("Error, cannot open source directory " + sourceDir); System.exit(1); } // read in HashMap first, to get list of handles & source dirs HashMap myhash = readMapFile( mapFile ); // for each handle, re-import the item, discard the new handle // and re-assign the old handle Iterator i = myhash.keySet().iterator(); ArrayList itemsToDelete = new ArrayList(); while( i.hasNext() ) { // get the old handle String newItemName = (String)i.next(); String oldHandle = (String)myhash.get(newItemName); Item oldItem = null; Item newItem = null; if( oldHandle.indexOf( '/' ) != -1 ) { System.out.println("\tReplacing: " + oldHandle); // add new item, locate old one oldItem = (Item)HandleManager.resolveToObject(c, oldHandle); } else { oldItem = Item.find( c, Integer.parseInt(oldHandle) ); } newItem = addItem(c, mycollection, sourceDir, newItemName, null); // schedule item for demolition itemsToDelete.add( oldItem ); } // now run through again, deleting items (do this last to avoid disasters!) // (this way deletes only happen if there have been no errors previously) i = itemsToDelete.iterator(); while( i.hasNext() ) { removeItem(c, (Item)i.next()); } } private void removeItems( Context c, String mapFile ) throws Exception { System.out.println( "Deleting items listed in mapfile: " + mapFile ); // read in the mapfile HashMap myhash = readMapFile( mapFile ); // now delete everything that appeared in the mapFile Iterator i = myhash.keySet().iterator(); while( i.hasNext() ) { String itemID = (String)myhash.get( i.next() ); if( itemID.indexOf( '/' ) != -1 ) { String myhandle = itemID; System.out.println("Deleting item " + myhandle); removeItem(c, myhandle); } else { // it's an ID Item myitem = Item.find(c, Integer.parseInt(itemID)); System.out.println("Deleting item " + itemID); removeItem(c, myitem); } } } /** item? try and add it to the archive * c * mycollection * path * itemname * handle - non-null means we have a pre-defined handle already * mapOut - mapfile we're writing */ private Item addItem( Context c, Collection mycollection, String path, String itemname, PrintWriter mapOut ) throws Exception { Item myitem = null; System.out.println("Adding item from directory " + itemname ); // create workspace item WorkspaceItem wi = WorkspaceItem.create(c, mycollection, false); myitem = wi.getItem(); // now fill out dublin core for item loadDublinCore( c, myitem, path + File.separatorChar + itemname + File.separatorChar + "dublin_core.xml" ); // and the bitstreams from the contents file // process contents file, add bistreams and bundles processContentsFile( c, myitem, path + File.separatorChar + itemname, "contents" ); if( useWorkflow ) { // don't process handle file // start up a workflow WorkflowManager.startWithoutNotify( c, wi ); // send ID to the mapfile if( mapOut != null ) mapOut.println( itemname + " " + myitem.getID() ); } else { // only process handle file if not using workflow system String myhandle = processHandleFile( c, myitem, path + File.separatorChar + itemname, "handle" ); // put item in system InstallItem.installItem(c, wi, myhandle); // find the handle, and output to map file myhandle = HandleManager.findHandle(c, myitem); if( mapOut != null ) mapOut.println( itemname + " " + myhandle ); } return myitem; } // remove, given the actual item private void removeItem( Context c, Item myitem ) throws Exception { Collection[] collections = myitem.getCollections(); // Remove item from all the collections it's in for (int i = 0; i < collections.length; i++) { collections[i].removeItem(myitem); } } // remove, given a handle private void removeItem( Context c, String myhandle ) throws Exception { // bit of a hack - to remove an item, you must remove it // from all collections it's a part of, then it will be removed Item myitem = (Item)HandleManager.resolveToObject(c, myhandle); if( myitem == null ) { System.out.println("Error - cannot locate item - already deleted?"); } removeItem( c, myitem ); } //////////////////////////////////// // utility methods //////////////////////////////////// // read in the map file and generate a hashmap of (file,handle) pairs private HashMap readMapFile( String filename ) throws Exception { HashMap myhash = new HashMap(); BufferedReader is = new BufferedReader( new FileReader( filename ) ); String line; while( ( line = is.readLine() ) != null ) { String myfile; String myhandle; // a line should be archive filename<whitespace>handle StringTokenizer st = new StringTokenizer( line ); if( st.hasMoreTokens() ) { myfile = st.nextToken(); } else throw new Exception("Bad mapfile line:\n" + line ); if( st.hasMoreTokens() ) { myhandle = st.nextToken(); } else throw new Exception("Bad mapfile line:\n" + line ); myhash.put( myfile, myhandle ); } is.close(); return myhash; } private void loadDublinCore(Context c, Item myitem, String filename) throws SQLException, IOException, ParserConfigurationException, SAXException, TransformerException //, AuthorizeException { Document document = loadXML(filename); // Get the nodes corresponding to formats NodeList dcNodes = XPathAPI.selectNodeList(document, "/dublin_core/dcvalue"); System.out.println("\tLoading dublin core from " + filename ); // Add each one as a new format to the registry for (int i=0; i < dcNodes.getLength(); i++) { Node n = dcNodes.item(i); addDCValue(myitem, n); } } private void addDCValue(Item i, Node n) throws TransformerException { String value = getStringValue(n); //n.getNodeValue(); //getElementData(n, "element"); String element = getAttributeValue(n, "element" ); String qualifier = getAttributeValue(n, "qualifier"); //NodeValue(); //getElementData(n, "qualifier"); String language = getAttributeValue(n, "language" ); System.out.println("\tElement: " + element + " Qualifier: " + qualifier + " Value: " + value ); if( qualifier.equals("none") ) qualifier = null; // if language isn't set, use the system's default value if( language.equals("") ) { language = ConfigurationManager.getProperty("default.language"); } // a goofy default, but there it is if( language == null ) { language = "en"; } i.addDC(element, qualifier, language, value); } /** * Return the String value of a Node */ public String getStringValue(Node node) { String value = node.getNodeValue(); if (node.hasChildNodes()) { Node first = node.getFirstChild(); if (first.getNodeType() == Node.TEXT_NODE) { return first.getNodeValue(); } } return value; } /** * Read in the handle file or return null if empty or doesn't exist */ private String processHandleFile( Context c, Item i, String path, String filename ) { String filePath = path + File.separatorChar + filename; String line = ""; String result = null; System.out.println( "Processing handle file: " + filename ); try { BufferedReader is = new BufferedReader( new FileReader( filePath ) ); // result gets contents of file, or null result = is.readLine(); System.out.println( "read handle: '" + result + "'"); is.close(); } catch( Exception e ) { // probably no handle file, just return null System.out.println( "It appears there is no handle file -- generating one" ); } return result; } /** * Given a contents file and an item, stuffing it with bitstreams from the * contents file */ private void processContentsFile( Context c, Item i, String path, String filename ) throws SQLException, IOException, AuthorizeException { String contentspath = path + File.separatorChar + filename; String line = ""; System.out.println( "\tProcessing contents file: " + contentspath ); BufferedReader is = new BufferedReader( new FileReader( contentspath ) ); while( ( line = is.readLine() ) != null ) { // look for a bundle name String bundleMarker = "\tbundle:"; int markerIndex = line.indexOf(bundleMarker); if( markerIndex == -1 ) { // no bundle found processContentFileEntry( c, i, path, line, null ); System.out.println( "\tBitstream: " + line ); } else { // found bundle String bundleName = line.substring(markerIndex+bundleMarker.length()); String bitstreamName = line.substring(0, markerIndex); processContentFileEntry( c, i, path, bitstreamName, bundleName ); System.out.println( "\tBitstream: " + bitstreamName + "\tBundle: " + bundleName ); } } is.close(); } // each entry represents a bitstream.... public void processContentFileEntry( Context c, Item i, String path, String fileName, String bundleName ) throws SQLException, IOException, AuthorizeException { String fullpath = path + File.separatorChar + fileName; // get an input stream BufferedInputStream bis = new BufferedInputStream( new FileInputStream( fullpath ) ); Bitstream bs = null; String newBundleName = bundleName; if( bundleName == null ) { // is it license.txt? if( fileName.equals("license.txt") ) { newBundleName = "LICENSE"; } else { // call it ORIGINAL newBundleName = "ORIGINAL"; } } // find the bundle Bundle [] bundles = i.getBundles( newBundleName ); Bundle targetBundle = null; if( bundles.length < 1 ) { // not found, create a new one targetBundle = i.createBundle( newBundleName ); } else { // put bitstreams into first bundle targetBundle = bundles[0]; } // now add the bitstream bs = targetBundle.createBitstream( bis ); bs.setName( fileName ); // Identify the format // FIXME - guessing format guesses license.txt incorrectly as a text file format! BitstreamFormat bf = FormatIdentifier.guessFormat(c, bs); bs.setFormat(bf); bs.update(); } // XML utility methods public String getAttributeValue(Node n, String myattributename) { String myvalue = ""; NamedNodeMap nm = n.getAttributes(); for (int i = 0; i < nm.getLength(); i++ ) { Node node = nm.item(i); String name = node.getNodeName(); String value = node.getNodeValue(); if(myattributename.equals(name)) { return value; } } return myvalue; } // XML utility methods stolen from administer. /** * Get the CDATA of a particular element. For example, if the XML document * contains: * <P> * <code> * &lt;foo&gt;&lt;mimetype&gt;application/pdf&lt;/mimetype&gt;&lt;/foo&gt; * </code> * passing this the <code>foo</code> node and <code>mimetype</code> will * return <code>application/pdf</code>.</P> * Why this isn't a core part of the XML API I do not know... * * @param parentElement the element, whose child element you want * the CDATA from * @param childName the name of the element you want the CDATA from * * @return the CDATA as a <code>String</code> */ private String getElementData( Node parentElement, String childName ) throws TransformerException { // Grab the child node Node childNode = XPathAPI.selectSingleNode(parentElement, childName); if (childNode == null) { // No child node, so no values return null; } // Get the #text Node dataNode = childNode.getFirstChild(); if (dataNode==null) { return null; } // Get the data String value = dataNode.getNodeValue().trim(); return value; } /** * Load in the XML from file. * * @param filename the filename to load from * * @return the DOM representation of the XML file */ private static Document loadXML( String filename ) throws IOException, ParserConfigurationException, SAXException { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); return builder.parse(new File(filename)); } }
true
true
public static void main(String argv[]) throws Exception { // create an options object and populate it CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption( "a", "add", false, "add items to DSpace"); options.addOption( "r", "replace", false, "replace items in mapfile"); options.addOption( "R", "remove", false, "remove items in mapfile"); options.addOption( "s", "source", true, "source of items (directory)"); options.addOption( "c", "collection", true, "destination collection databse ID"); options.addOption( "m", "mapfile", true, "mapfile items in mapfile"); options.addOption( "e", "eperson", true, "remove items in mapfile"); options.addOption( "w", "workflow", false, "send submission through collection's workflow"); options.addOption( "h", "help", false, "help"); CommandLine line = parser.parse( options, argv ); String command = null; // add replace remove, etc String sourcedir = null; String mapfile = null; String eperson = null; // db ID or email String [] collections = null; // db ID or handles if( line.hasOption('h') ) { HelpFormatter myhelp = new HelpFormatter(); myhelp.printHelp( "ItemImport\n", options ); System.out.println("\nadding items: ItemImport -a -e eperson -c collection -s sourcedir -m mapfile"); System.out.println("replacing items: ItemImport -r -e eperson -c collection -s sourcedir -m mapfile"); System.out.println("removing items: ItemImport -R -e eperson -m mapfile"); System.exit(0); } if( line.hasOption( 'a' ) ) { command = "add"; } if( line.hasOption( 'r' ) ) { command = "replace";} if( line.hasOption( 'R' ) ) { command = "remove"; } if( line.hasOption( 'w' ) ) { useWorkflow = true; } if( line.hasOption( 's' ) ) // source { sourcedir = line.getOptionValue( 's' ); } if( line.hasOption( 'm' ) ) // mapfile { mapfile = line.getOptionValue( 'm' ); } if( line.hasOption( 'e' ) ) // eperson { eperson = line.getOptionValue( 'e' ); } if( line.hasOption( 'c' ) ) // collections { collections = line.getOptionValues( 'c' ); } // now validate // must have a command set if( command == null ) { System.out.println("Error - must run with either add, replace, or remove (run with -h flag for details)"); System.exit(1); } else if( command.equals("add") || command.equals("replace") ) { if( sourcedir == null ) { System.out.println("Error - a source directory containing items must be set (run with -h flag for details)"); System.exit(1); } if( mapfile == null ) { System.out.println("Error - a map file to hold importing results must be specified (run with -h flag for details)"); System.exit(1); } if( eperson == null ) { System.out.println("Error - an eperson to do the importing must be specified (run with -h flag for details)"); System.exit(1); } if( collections == null ) { System.out.println("Error - at least one destination collection must be specified (run with -h flag for details)"); System.exit(1); } } else if( command.equals("remove") ) { if( eperson == null ) { System.out.println("Error - an eperson to do the importing must be specified"); System.exit(1); } if( mapfile == null ) { System.out.println("Error - a map file must be specified"); System.exit(1); } } ItemImport myloader = new ItemImport(); // create a context Context c = new Context(); // find the EPerson, assign to context EPerson myEPerson = null; if( eperson.indexOf('@') != -1) { // @ sign, must be an email myEPerson = EPerson.findByEmail( c, eperson ); } else { myEPerson = EPerson.find( c, Integer.parseInt( eperson ) ); } if( myEPerson == null ) { System.out.println( "Error, eperson cannot be found: " + eperson ); System.exit(1); } c.setCurrentUser( myEPerson ); // find collections Collection mycollection = null; // dont' need to validate collections set if command is "remove" if( !command.equals("remove") ) { if( collections[0].indexOf('/') != -1 ) { // has a / must be a handle mycollection = (Collection)HandleManager.resolveToObject( c, collections[0] ); // ensure it's a collection if( (mycollection == null) || (mycollection.getType() != Constants.COLLECTION) ) { mycollection = null; } } else if( collections != null ) { mycollection = Collection.find( c, Integer.parseInt( collections[0] ) ); } if( mycollection == null ) { System.out.println( "Error, collection cannot be found: " + collections[0] ); System.exit(1); } } // end of validating collections try { c.setIgnoreAuthorization( true ); if( command.equals( "add" ) ) { myloader.addItems( c, mycollection, sourcedir, mapfile ); } else if( command.equals( "replace" ) ) { myloader.replaceItems( c, mycollection, sourcedir, mapfile ); } else if( command.equals( "remove" ) ) { myloader.removeItems( c, mapfile ); } // complete all transactions c.complete(); } catch( Exception e ) { // abort all operations c.abort(); e.printStackTrace(); System.out.println( e ); } }
public static void main(String argv[]) throws Exception { // create an options object and populate it CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption( "a", "add", false, "add items to DSpace"); options.addOption( "r", "replace", false, "replace items in mapfile"); options.addOption( "R", "remove", false, "remove items in mapfile"); options.addOption( "s", "source", true, "source of items (directory)"); options.addOption( "c", "collection", true, "destination collection databse ID"); options.addOption( "m", "mapfile", true, "mapfile items in mapfile"); options.addOption( "e", "eperson", true, "email of eperson doing importing"); options.addOption( "w", "workflow", false, "send submission through collection's workflow"); options.addOption( "h", "help", false, "help"); CommandLine line = parser.parse( options, argv ); String command = null; // add replace remove, etc String sourcedir = null; String mapfile = null; String eperson = null; // db ID or email String [] collections = null; // db ID or handles if( line.hasOption('h') ) { HelpFormatter myhelp = new HelpFormatter(); myhelp.printHelp( "ItemImport\n", options ); System.out.println("\nadding items: ItemImport -a -e eperson -c collection -s sourcedir -m mapfile"); System.out.println("replacing items: ItemImport -r -e eperson -c collection -s sourcedir -m mapfile"); System.out.println("removing items: ItemImport -R -e eperson -m mapfile"); System.exit(0); } if( line.hasOption( 'a' ) ) { command = "add"; } if( line.hasOption( 'r' ) ) { command = "replace";} if( line.hasOption( 'R' ) ) { command = "remove"; } if( line.hasOption( 'w' ) ) { useWorkflow = true; } if( line.hasOption( 's' ) ) // source { sourcedir = line.getOptionValue( 's' ); } if( line.hasOption( 'm' ) ) // mapfile { mapfile = line.getOptionValue( 'm' ); } if( line.hasOption( 'e' ) ) // eperson { eperson = line.getOptionValue( 'e' ); } if( line.hasOption( 'c' ) ) // collections { collections = line.getOptionValues( 'c' ); } // now validate // must have a command set if( command == null ) { System.out.println("Error - must run with either add, replace, or remove (run with -h flag for details)"); System.exit(1); } else if( command.equals("add") || command.equals("replace") ) { if( sourcedir == null ) { System.out.println("Error - a source directory containing items must be set (run with -h flag for details)"); System.exit(1); } if( mapfile == null ) { System.out.println("Error - a map file to hold importing results must be specified (run with -h flag for details)"); System.exit(1); } if( eperson == null ) { System.out.println("Error - an eperson to do the importing must be specified (run with -h flag for details)"); System.exit(1); } if( collections == null ) { System.out.println("Error - at least one destination collection must be specified (run with -h flag for details)"); System.exit(1); } } else if( command.equals("remove") ) { if( eperson == null ) { System.out.println("Error - an eperson to do the importing must be specified"); System.exit(1); } if( mapfile == null ) { System.out.println("Error - a map file must be specified"); System.exit(1); } } ItemImport myloader = new ItemImport(); // create a context Context c = new Context(); // find the EPerson, assign to context EPerson myEPerson = null; if( eperson.indexOf('@') != -1) { // @ sign, must be an email myEPerson = EPerson.findByEmail( c, eperson ); } else { myEPerson = EPerson.find( c, Integer.parseInt( eperson ) ); } if( myEPerson == null ) { System.out.println( "Error, eperson cannot be found: " + eperson ); System.exit(1); } c.setCurrentUser( myEPerson ); // find collections Collection mycollection = null; // dont' need to validate collections set if command is "remove" if( !command.equals("remove") ) { if( collections[0].indexOf('/') != -1 ) { // has a / must be a handle mycollection = (Collection)HandleManager.resolveToObject( c, collections[0] ); // ensure it's a collection if( (mycollection == null) || (mycollection.getType() != Constants.COLLECTION) ) { mycollection = null; } } else if( collections != null ) { mycollection = Collection.find( c, Integer.parseInt( collections[0] ) ); } if( mycollection == null ) { System.out.println( "Error, collection cannot be found: " + collections[0] ); System.exit(1); } } // end of validating collections try { c.setIgnoreAuthorization( true ); if( command.equals( "add" ) ) { myloader.addItems( c, mycollection, sourcedir, mapfile ); } else if( command.equals( "replace" ) ) { myloader.replaceItems( c, mycollection, sourcedir, mapfile ); } else if( command.equals( "remove" ) ) { myloader.removeItems( c, mapfile ); } // complete all transactions c.complete(); } catch( Exception e ) { // abort all operations c.abort(); e.printStackTrace(); System.out.println( e ); } }
diff --git a/test/testline.java b/test/testline.java index c3a5cf6..6d16ee1 100644 --- a/test/testline.java +++ b/test/testline.java @@ -1,189 +1,189 @@ import java.io.OutputStream; import java.io.FileOutputStream; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.io.IOException; import java.lang.IllegalArgumentException; import scijava.roi.shape.Line; import scijava.roi.types.Vertex3D; import scijava.roi.types.LinePoints3D; class testline { public static void main(String[] args) { System.out.println("Running model tests"); { Line l1 = new Line(); double l1len = l1.length(); System.out.println("L1: " + l1 + " len=" + l1len); } { Vertex3D p1 = new Vertex3D(2,2,2); Vertex3D p2 = new Vertex3D(4,4,4); Line l2 = new Line(p1, p2); double l2len = l2.length(); System.out.println("L2: " + l2 + " len=" + l2len); } { Vertex3D p1 = new Vertex3D(2,2,0); Vertex3D p2 = new Vertex3D(4,4,0); Vertex3D pa[] = {p1, p2}; LinePoints3D lp = new LinePoints3D(pa); Line l3 = new Line(lp); double l3len = l3.length(); System.out.println("L3: " + l3 + " len=" + l3len); } try { Vertex3D p1 = new Vertex3D(2,2,5); Vertex3D p2 = new Vertex3D(4,4,4); Vertex3D p3 = new Vertex3D(4,2,5); Vertex3D pa[] = {p1, p2, p3}; LinePoints3D lp = new LinePoints3D(pa); Line l4 = new Line(lp); double l4len = l4.length(); System.out.println("L4 (FAIL): " + l4 + " len=" + l4len); } catch (java.lang.IllegalArgumentException e) { System.out.println("L4: Construction failed (expected): " + e); } try { Vertex3D p1 = new Vertex3D(2,2,5); Vertex3D pa[] = {p1}; LinePoints3D lp = new LinePoints3D(pa); Line l5 = new Line(lp); double l5len = l5.length(); System.out.println("L5 (FAIL): " + l5 + " len=" + l5len); } catch (java.lang.IllegalArgumentException e) { System.out.println("L5: Construction failed (expected): " + e); } // Output a ROI. { Vertex3D p1 = new Vertex3D(204.5653,187.6969,0); Vertex3D p2 = new Vertex3D(53.9834,19.7242,4); Line l6 = new Line(p1, p2); output(l6, "lineroi1"); } } static void output(Line line, String filename) { LinePoints3D pts = line.getPoints(); // Icy XML format. try { FileOutputStream ficy; ficy = new FileOutputStream(filename + ".xml"); - new PrintStream(ficy).printf("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n<root>\n<roi>\n<classname>icy.roi.ROI2DRectangle</classname>\n<id>1</id>\n<name>Rectangle2D</name>\n<color>-7703041</color>\n<selected_color>-3014684</selected_color>\n<stroke>2</stroke>\n<selected>true</selected>\n<z>-1</z>\n<t>-1</t>\n<c>-1</c>\n<top_left>\n<color>-3014684</color>\n<selected_color>-1</selected_color>\n<pos_x>%s</pos_x>\n<pos_y>%s</pos_y>\n<ray>6</ray>\n<visible>true</visible>\n</top_left>\n<bottom_right>\n<color>-3014684</color>\n<selected_color>-1</selected_color>\n<pos_x>%s</pos_x>\n<pos_y>%s</pos_y>\n<ray>6</ray>\n<visible>true</visible>\n</bottom_right>\n</roi>\n</root>\n", + new PrintStream(ficy).printf("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n<root>\n<roi>\n<classname>icy.roi.ROI2DLine</classname>\n<id>1</id>\n<name>Line2D</name>\n<color>-7703041</color>\n<selected_color>-3014684</selected_color>\n<stroke>2</stroke>\n<selected>true</selected>\n<z>-1</z>\n<t>-1</t>\n<c>-1</c>\n<pt1>\n<color>-3014684</color>\n<selected_color>-1</selected_color>\n<pos_x>%s</pos_x>\n<pos_y>%s</pos_y>\n<ray>6</ray>\n<visible>true</visible>\n</pt1>\n<pt2>\n<color>-3014684</color>\n<selected_color>-1</selected_color>\n<pos_x>%s</pos_x>\n<pos_y>%s</pos_y>\n<ray>6</ray>\n<visible>true</visible>\n</pt2>\n</roi>\n</root>\n", pts.points[0].vertex[0], pts.points[0].vertex[1], pts.points[1].vertex[0], pts.points[1].vertex[1]); ficy.close(); } catch (IOException e) { System.err.println ("Unable to write Icy roi.xml"); } // Simple text format. try { FileOutputStream ftxt; ftxt = new FileOutputStream(filename + ".txt"); new PrintStream(ftxt).printf("LINE %s,%s,%s,%s\n", pts.points[0].vertex[0], pts.points[0].vertex[1], pts.points[1].vertex[0], pts.points[1].vertex[1]); ftxt.close(); } catch (IOException e) { System.err.println ("Unable to write Icy roi.xml"); } // ImageJ binary format. try { String name = "SJROIMODEL"; byte data[] = new byte[128+(name.length()*2)]; double x1 = pts.points[0].vertex[0]; double y1 = pts.points[0].vertex[1]; double x2 = pts.points[1].vertex[0]; double y2 = pts.points[1].vertex[1]; data[0]=73; data[1]=111; data[2]=117; data[3]=116; putShort(data, 4, 223); // VERSION data[6] = (byte)3; // LINE putShort(data, 8, (short) Math.floor(Math.min(y1,y2))); // TOP putShort(data, 10, (short) Math.floor(Math.min(x1,x2))); // LEFT putShort(data, 12, (short) Math.ceil(Math.max(y1,y2))); // BOTTOM putShort(data, 14, (short) Math.ceil(Math.max(x1,x2))); // RIGHT putShort(data, 16, 2); // NCOORD putInt(data, 56, 0); // POSITION putFloat(data, 18, (float)x1); // X1 putFloat(data, 22, (float)y1); // Y1 putFloat(data, 26, (float)x2); // X2 putFloat(data, 30, (float)y2); // Y2 - putShort(data, 34, 4); // LINEWID + putShort(data, 34, 2); // LINEWID putInt(data, 40, 0xff0000ff); // LINECOL putInt(data, 44, 0); // FILLCOL for (int i=0; i<name.length(); i++) putShort(data, 128+i*2, name.charAt(i)); OutputStream fbin; fbin = new FileOutputStream(filename+".roi"); fbin.write(data); fbin.close(); } catch (IOException e) { System.err.println ("Unable to write Icy roi.xml"); } } static void putShort(byte data[], int base, int v) { data[base] = (byte)(v>>>8); data[base+1] = (byte)v; } static void putFloat(byte data[], int base, float v) { int tmp = Float.floatToIntBits(v); data[base] = (byte)(tmp>>24); data[base+1] = (byte)(tmp>>16); data[base+2] = (byte)(tmp>>8); data[base+3] = (byte)tmp; } static void putInt(byte data[], int base, int i) { data[base] = (byte)(i>>24); data[base+1] = (byte)(i>>16); data[base+2] = (byte)(i>>8); data[base+3] = (byte)i; } }
false
true
static void output(Line line, String filename) { LinePoints3D pts = line.getPoints(); // Icy XML format. try { FileOutputStream ficy; ficy = new FileOutputStream(filename + ".xml"); new PrintStream(ficy).printf("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n<root>\n<roi>\n<classname>icy.roi.ROI2DRectangle</classname>\n<id>1</id>\n<name>Rectangle2D</name>\n<color>-7703041</color>\n<selected_color>-3014684</selected_color>\n<stroke>2</stroke>\n<selected>true</selected>\n<z>-1</z>\n<t>-1</t>\n<c>-1</c>\n<top_left>\n<color>-3014684</color>\n<selected_color>-1</selected_color>\n<pos_x>%s</pos_x>\n<pos_y>%s</pos_y>\n<ray>6</ray>\n<visible>true</visible>\n</top_left>\n<bottom_right>\n<color>-3014684</color>\n<selected_color>-1</selected_color>\n<pos_x>%s</pos_x>\n<pos_y>%s</pos_y>\n<ray>6</ray>\n<visible>true</visible>\n</bottom_right>\n</roi>\n</root>\n", pts.points[0].vertex[0], pts.points[0].vertex[1], pts.points[1].vertex[0], pts.points[1].vertex[1]); ficy.close(); } catch (IOException e) { System.err.println ("Unable to write Icy roi.xml"); } // Simple text format. try { FileOutputStream ftxt; ftxt = new FileOutputStream(filename + ".txt"); new PrintStream(ftxt).printf("LINE %s,%s,%s,%s\n", pts.points[0].vertex[0], pts.points[0].vertex[1], pts.points[1].vertex[0], pts.points[1].vertex[1]); ftxt.close(); } catch (IOException e) { System.err.println ("Unable to write Icy roi.xml"); } // ImageJ binary format. try { String name = "SJROIMODEL"; byte data[] = new byte[128+(name.length()*2)]; double x1 = pts.points[0].vertex[0]; double y1 = pts.points[0].vertex[1]; double x2 = pts.points[1].vertex[0]; double y2 = pts.points[1].vertex[1]; data[0]=73; data[1]=111; data[2]=117; data[3]=116; putShort(data, 4, 223); // VERSION data[6] = (byte)3; // LINE putShort(data, 8, (short) Math.floor(Math.min(y1,y2))); // TOP putShort(data, 10, (short) Math.floor(Math.min(x1,x2))); // LEFT putShort(data, 12, (short) Math.ceil(Math.max(y1,y2))); // BOTTOM putShort(data, 14, (short) Math.ceil(Math.max(x1,x2))); // RIGHT putShort(data, 16, 2); // NCOORD putInt(data, 56, 0); // POSITION putFloat(data, 18, (float)x1); // X1 putFloat(data, 22, (float)y1); // Y1 putFloat(data, 26, (float)x2); // X2 putFloat(data, 30, (float)y2); // Y2 putShort(data, 34, 4); // LINEWID putInt(data, 40, 0xff0000ff); // LINECOL putInt(data, 44, 0); // FILLCOL for (int i=0; i<name.length(); i++) putShort(data, 128+i*2, name.charAt(i)); OutputStream fbin; fbin = new FileOutputStream(filename+".roi"); fbin.write(data); fbin.close(); } catch (IOException e) { System.err.println ("Unable to write Icy roi.xml"); } }
static void output(Line line, String filename) { LinePoints3D pts = line.getPoints(); // Icy XML format. try { FileOutputStream ficy; ficy = new FileOutputStream(filename + ".xml"); new PrintStream(ficy).printf("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n<root>\n<roi>\n<classname>icy.roi.ROI2DLine</classname>\n<id>1</id>\n<name>Line2D</name>\n<color>-7703041</color>\n<selected_color>-3014684</selected_color>\n<stroke>2</stroke>\n<selected>true</selected>\n<z>-1</z>\n<t>-1</t>\n<c>-1</c>\n<pt1>\n<color>-3014684</color>\n<selected_color>-1</selected_color>\n<pos_x>%s</pos_x>\n<pos_y>%s</pos_y>\n<ray>6</ray>\n<visible>true</visible>\n</pt1>\n<pt2>\n<color>-3014684</color>\n<selected_color>-1</selected_color>\n<pos_x>%s</pos_x>\n<pos_y>%s</pos_y>\n<ray>6</ray>\n<visible>true</visible>\n</pt2>\n</roi>\n</root>\n", pts.points[0].vertex[0], pts.points[0].vertex[1], pts.points[1].vertex[0], pts.points[1].vertex[1]); ficy.close(); } catch (IOException e) { System.err.println ("Unable to write Icy roi.xml"); } // Simple text format. try { FileOutputStream ftxt; ftxt = new FileOutputStream(filename + ".txt"); new PrintStream(ftxt).printf("LINE %s,%s,%s,%s\n", pts.points[0].vertex[0], pts.points[0].vertex[1], pts.points[1].vertex[0], pts.points[1].vertex[1]); ftxt.close(); } catch (IOException e) { System.err.println ("Unable to write Icy roi.xml"); } // ImageJ binary format. try { String name = "SJROIMODEL"; byte data[] = new byte[128+(name.length()*2)]; double x1 = pts.points[0].vertex[0]; double y1 = pts.points[0].vertex[1]; double x2 = pts.points[1].vertex[0]; double y2 = pts.points[1].vertex[1]; data[0]=73; data[1]=111; data[2]=117; data[3]=116; putShort(data, 4, 223); // VERSION data[6] = (byte)3; // LINE putShort(data, 8, (short) Math.floor(Math.min(y1,y2))); // TOP putShort(data, 10, (short) Math.floor(Math.min(x1,x2))); // LEFT putShort(data, 12, (short) Math.ceil(Math.max(y1,y2))); // BOTTOM putShort(data, 14, (short) Math.ceil(Math.max(x1,x2))); // RIGHT putShort(data, 16, 2); // NCOORD putInt(data, 56, 0); // POSITION putFloat(data, 18, (float)x1); // X1 putFloat(data, 22, (float)y1); // Y1 putFloat(data, 26, (float)x2); // X2 putFloat(data, 30, (float)y2); // Y2 putShort(data, 34, 2); // LINEWID putInt(data, 40, 0xff0000ff); // LINECOL putInt(data, 44, 0); // FILLCOL for (int i=0; i<name.length(); i++) putShort(data, 128+i*2, name.charAt(i)); OutputStream fbin; fbin = new FileOutputStream(filename+".roi"); fbin.write(data); fbin.close(); } catch (IOException e) { System.err.println ("Unable to write Icy roi.xml"); } }
diff --git a/src/com/vorsk/crossfitr/TimerActivity.java b/src/com/vorsk/crossfitr/TimerActivity.java index b0d9d63..d145cd7 100644 --- a/src/com/vorsk/crossfitr/TimerActivity.java +++ b/src/com/vorsk/crossfitr/TimerActivity.java @@ -1,337 +1,337 @@ package com.vorsk.crossfitr; import com.vorsk.crossfitr.models.WorkoutModel; import com.vorsk.crossfitr.models.WorkoutRow; import android.app.Activity; import android.app.Dialog; import android.content.Intent; import android.graphics.Color; import android.graphics.Typeface; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Handler; import android.os.Message; import android.text.method.ScrollingMovementMethod; import android.util.TypedValue; import android.view.View; import android.view.ViewTreeObserver; import android.view.ViewTreeObserver.OnGlobalLayoutListener; import android.widget.Button; import android.widget.TextView; public class TimerActivity extends Activity implements OnGlobalLayoutListener { static final int NUMBER_DIALOG_ID = 0; // Dialog variable private int mHour, mMin, mSec; private long startTime, id; private final long mFrequency = 100; // milliseconds private final int TICK_WHAT = 2; private boolean cdRun; NumberPicker mNumberPicker; Button mSetTimer, mFinish, mStartStop; TextView mWorkoutDescription, mStateLabel, mWorkoutName; Time timer = new Time(); private MediaPlayer mp; private Handler mHandler = new Handler() { public void handleMessage(Message m) { if(!cdRun) updateElapsedTime(); sendMessageDelayed(Message.obtain(this, TICK_WHAT), mFrequency); } }; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.timer_tab); setVolumeControlStream(AudioManager.STREAM_MUSIC); cdRun = false; // create model object WorkoutModel model = new WorkoutModel(this); // get the id passed from previous activity (workout lists) id = getIntent().getLongExtra("ID", -1); // if ID is invalid, go back to home screen if (id < 0) { getParent().setResult(RESULT_CANCELED); finish(); } // open model to put data into database model.open(); WorkoutRow workout = model.getByID(id); model.close(); Typeface roboto = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Light.ttf"); mStateLabel = (TextView) findViewById(R.id.state_label); mStateLabel.setTypeface(roboto); mStateLabel.setText(""); mWorkoutDescription = (TextView) findViewById(R.id.workout_des_time); - mWorkoutDescription.setMovementMethod(new ScrollingMovementMethod()); + //mWorkoutDescription.setMovementMethod(new ScrollingMovementMethod()); mWorkoutDescription.setTypeface(roboto); String workoutDesc = workout.description; workoutDesc.replace(",", "\n"); mWorkoutDescription.setText(workoutDesc); mWorkoutName = (TextView) findViewById(R.id.workout_name_time); mWorkoutName.setText(workout.name); mWorkoutName.setTypeface(roboto); mStartStop = (Button) findViewById(R.id.start_stop_button); ViewTreeObserver vto = mStartStop.getViewTreeObserver(); vto.addOnGlobalLayoutListener(this); mStartStop.setTypeface(roboto); //mStartStop.setText("0:00:00.0"); mStartStop.setEnabled(false); mSetTimer = (Button) findViewById(R.id.SetTimer); mSetTimer.setTypeface(roboto); mFinish = (Button) findViewById(R.id.finish_workout_button); mFinish.setTypeface(roboto); mFinish.setEnabled(false); mHandler.sendMessageDelayed(Message.obtain(mHandler, TICK_WHAT), mFrequency); // Opens Dialog on click mSetTimer.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { showDialog(NUMBER_DIALOG_ID); } }); } private NumberPickerDialog.OnNumberSetListener mNumberSetListener = new NumberPickerDialog.OnNumberSetListener() { public void onNumberSet(int selectedHour, int selectedMin, int selectedSec) { if (selectedHour == 0 && selectedMin == 0 && selectedSec == 0) { clearInput(); } else { clearAllTimer(); mHour = selectedHour; mMin = selectedMin; mSec = selectedSec; mStartStop.setEnabled(true); setDisplayBackgroundColor(0); } } }; /** * Clears the timer; sets everything to 0 */ public void clearAllTimer() { mHour = 0; mMin = 0; mSec = 0; startTime = 0; mStateLabel.setText("Press To Start"); mStateLabel.setTextColor(Color.GREEN); timer.reset(); updateElapsedTime(); } private void clearInput() { mHour = 0; mMin = 0; mSec = 0; } private void updateElapsedTime() { //if(!cdRun) mStartStop.setText(getFormattedElapsedTime()); } /** * Gets the start time for the timer in milliseconds * * @return start time in milliseconds */ public long getStartTime() { startTime = (mHour * 3600000) + (mMin * 60000) + (mSec * 1000); return startTime; } private String formatElapsedTime(long start) { long hours = 0; long minutes = 0; long seconds = 0; long tenths = 0; StringBuilder sb = new StringBuilder(); if (!checkForEnd(start)) { if (start < 1000) { tenths = start / 100; } else if (start < 60000) { seconds = start / 1000; start -= seconds * 1000; tenths = start / 100; } else if (start < 3600000) { minutes = start / 60000; start -= minutes * 60000; seconds = start / 1000; start -= seconds * 1000; tenths = start / 100; } else { hours = start / 3600000; start -= hours * 3600000; minutes = start / 60000; start -= minutes * 60000; seconds = start / 1000; start -= seconds * 1000; tenths = start / 100; } } sb.append(hours).append(":").append(formatDigits(minutes)).append(":") .append(formatDigits(seconds)).append(".").append(tenths); return sb.toString(); } private boolean checkForEnd(long time) { if (time < 0) { playSound(R.raw.boxing_bellx3); clearInput(); timer.reset(); mStateLabel.setText(""); ((TimeTabWidget) getParent()).getTabHost().getTabWidget() .getChildTabViewAt(1).setEnabled(true); ((TimeTabWidget) getParent()).getTabHost().getTabWidget() .getChildTabViewAt(2).setEnabled(true); setDisplayBackgroundColor(2); mSetTimer.setEnabled(true); mStartStop.setEnabled(false); mFinish.setEnabled(true); return true; } return false; } /** * Gets the current elapsed time in 0:00:00.00 format * * @return */ public String getFormattedElapsedTime() { return formatElapsedTime(getStartTime() - getElapsedTime()); } private long getElapsedTime() { return timer.getElapsedTime(); } public void onStartStopClicked(View V) { if (!timer.isRunning()) { ((TimeTabWidget) getParent()).getTabHost().getTabWidget() .getChildTabViewAt(1).setEnabled(false); ((TimeTabWidget) getParent()).getTabHost().getTabWidget() .getChildTabViewAt(2).setEnabled(false); playSound(R.raw.countdown_3_0); new CountDownTimer(3000, 100) { public void onTick(long millisUntilFinished) { mStartStop.setText("" + (millisUntilFinished / 1000 + 1)); mStartStop.setEnabled(false); setDisplayBackgroundColor(2); mStateLabel.setText(""); mSetTimer.setEnabled(false); mFinish.setEnabled(false); cdRun = true; } public void onFinish() { playSound(R.raw.bell_ring); //mStartStop.setText("Go!"); setDisplayBackgroundColor(1); mStateLabel.setText("Press To Stop"); mStateLabel.setTextColor(Color.RED); timer.start(); cdRun = false; mStartStop.setEnabled(true); } }.start(); } else { timer.stop(); ((TimeTabWidget) getParent()).getTabHost().getTabWidget() .getChildTabViewAt(1).setEnabled(true); ((TimeTabWidget) getParent()).getTabHost().getTabWidget() .getChildTabViewAt(2).setEnabled(true); mStateLabel.setText("Press To Start"); mStateLabel.setTextColor(Color.GREEN); setDisplayBackgroundColor(0); mSetTimer.setEnabled(true); mFinish.setEnabled(true); } } public void onFinishedClicked(View v) { Intent result = new Intent(); result.putExtra("time", getStartTime()); getParent().setResult(RESULT_OK, result); finish(); } private String formatDigits(long num) { return (num < 10) ? "0" + num : new Long(num).toString(); } @Override protected Dialog onCreateDialog(int id) { return new NumberPickerDialog(this, mNumberSetListener, 2, 0); } /** * Resizes mStartStop dynamically for smaller screen sizes */ public void onGlobalLayout() { if (1 < mStartStop.getLineCount()) { mStartStop.setTextSize(TypedValue.COMPLEX_UNIT_PX, mStartStop.getTextSize() - 2); } } /** * method to change background color * @param color */ private void setDisplayBackgroundColor(int color){ if(color == 0){ mStartStop.setBackgroundResource(R.drawable.tabata_display_go); } else if(color == 1){ mStartStop.setBackgroundResource(R.drawable.tabata_display_rest); } else if(color == 2){ mStartStop.setBackgroundResource(R.drawable.background_main); } } private void playSound(int r) { //Release any resources from previous MediaPlayer if (mp != null) { mp.release(); } // Create a new MediaPlayer to play this sound mp = MediaPlayer.create(this, r); mp.start(); } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.timer_tab); setVolumeControlStream(AudioManager.STREAM_MUSIC); cdRun = false; // create model object WorkoutModel model = new WorkoutModel(this); // get the id passed from previous activity (workout lists) id = getIntent().getLongExtra("ID", -1); // if ID is invalid, go back to home screen if (id < 0) { getParent().setResult(RESULT_CANCELED); finish(); } // open model to put data into database model.open(); WorkoutRow workout = model.getByID(id); model.close(); Typeface roboto = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Light.ttf"); mStateLabel = (TextView) findViewById(R.id.state_label); mStateLabel.setTypeface(roboto); mStateLabel.setText(""); mWorkoutDescription = (TextView) findViewById(R.id.workout_des_time); mWorkoutDescription.setMovementMethod(new ScrollingMovementMethod()); mWorkoutDescription.setTypeface(roboto); String workoutDesc = workout.description; workoutDesc.replace(",", "\n"); mWorkoutDescription.setText(workoutDesc); mWorkoutName = (TextView) findViewById(R.id.workout_name_time); mWorkoutName.setText(workout.name); mWorkoutName.setTypeface(roboto); mStartStop = (Button) findViewById(R.id.start_stop_button); ViewTreeObserver vto = mStartStop.getViewTreeObserver(); vto.addOnGlobalLayoutListener(this); mStartStop.setTypeface(roboto); //mStartStop.setText("0:00:00.0"); mStartStop.setEnabled(false); mSetTimer = (Button) findViewById(R.id.SetTimer); mSetTimer.setTypeface(roboto); mFinish = (Button) findViewById(R.id.finish_workout_button); mFinish.setTypeface(roboto); mFinish.setEnabled(false); mHandler.sendMessageDelayed(Message.obtain(mHandler, TICK_WHAT), mFrequency); // Opens Dialog on click mSetTimer.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { showDialog(NUMBER_DIALOG_ID); } }); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.timer_tab); setVolumeControlStream(AudioManager.STREAM_MUSIC); cdRun = false; // create model object WorkoutModel model = new WorkoutModel(this); // get the id passed from previous activity (workout lists) id = getIntent().getLongExtra("ID", -1); // if ID is invalid, go back to home screen if (id < 0) { getParent().setResult(RESULT_CANCELED); finish(); } // open model to put data into database model.open(); WorkoutRow workout = model.getByID(id); model.close(); Typeface roboto = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Light.ttf"); mStateLabel = (TextView) findViewById(R.id.state_label); mStateLabel.setTypeface(roboto); mStateLabel.setText(""); mWorkoutDescription = (TextView) findViewById(R.id.workout_des_time); //mWorkoutDescription.setMovementMethod(new ScrollingMovementMethod()); mWorkoutDescription.setTypeface(roboto); String workoutDesc = workout.description; workoutDesc.replace(",", "\n"); mWorkoutDescription.setText(workoutDesc); mWorkoutName = (TextView) findViewById(R.id.workout_name_time); mWorkoutName.setText(workout.name); mWorkoutName.setTypeface(roboto); mStartStop = (Button) findViewById(R.id.start_stop_button); ViewTreeObserver vto = mStartStop.getViewTreeObserver(); vto.addOnGlobalLayoutListener(this); mStartStop.setTypeface(roboto); //mStartStop.setText("0:00:00.0"); mStartStop.setEnabled(false); mSetTimer = (Button) findViewById(R.id.SetTimer); mSetTimer.setTypeface(roboto); mFinish = (Button) findViewById(R.id.finish_workout_button); mFinish.setTypeface(roboto); mFinish.setEnabled(false); mHandler.sendMessageDelayed(Message.obtain(mHandler, TICK_WHAT), mFrequency); // Opens Dialog on click mSetTimer.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { showDialog(NUMBER_DIALOG_ID); } }); }
diff --git a/lab2/src/Main.java b/lab2/src/Main.java index 314b95d..c10344e 100644 --- a/lab2/src/Main.java +++ b/lab2/src/Main.java @@ -1,58 +1,58 @@ import java.util.ArrayList; import java.util.Iterator; public class Main { public static void main(String [ ] args) { boolean showItemsets = true; boolean showRules = true; boolean aprioriSkyLine = true; String fileName = "data/out1.csv"; - if(args.length == 1){ + if(args.length >= 1){ fileName = args[0]; } ArrayList<Vector> vecList = null; vecList = MyParser.parseSparseVectorCSV(fileName); double minSupport = 0.1; - if(args.length == 2){ + if(args.length >= 2){ minSupport = Double.parseDouble(args[1]); } else{ System.out.println("No argument for minimum support found, using "+minSupport+" as value."); } double minConfidence = 0.1; - if(args.length == 3){ + if(args.length >= 3){ minConfidence = Double.parseDouble(args[2]); } else{ System.out.println("No argument for minimum confidence found, using "+minConfidence+" as value."); } ArrayList<Vector> apriOut = Apriori.AprMainLoop(vecList, minSupport, aprioriSkyLine); ArrayList<AssociationRule> rules = genRules.genRulesMainLoop(apriOut, vecList, minConfidence);; for(int i = 0; i < apriOut.size(); i++) { if(showItemsets) { System.out.println("itemset:" + apriOut.get(i).toString() + " Support = " +apriOut.get(i).support); } } for(int i = 0; i < rules.size(); i++) { if(showRules) { System.out.println(" Rule:" + rules.get(i).toString()); } } } }
false
true
public static void main(String [ ] args) { boolean showItemsets = true; boolean showRules = true; boolean aprioriSkyLine = true; String fileName = "data/out1.csv"; if(args.length == 1){ fileName = args[0]; } ArrayList<Vector> vecList = null; vecList = MyParser.parseSparseVectorCSV(fileName); double minSupport = 0.1; if(args.length == 2){ minSupport = Double.parseDouble(args[1]); } else{ System.out.println("No argument for minimum support found, using "+minSupport+" as value."); } double minConfidence = 0.1; if(args.length == 3){ minConfidence = Double.parseDouble(args[2]); } else{ System.out.println("No argument for minimum confidence found, using "+minConfidence+" as value."); } ArrayList<Vector> apriOut = Apriori.AprMainLoop(vecList, minSupport, aprioriSkyLine); ArrayList<AssociationRule> rules = genRules.genRulesMainLoop(apriOut, vecList, minConfidence);; for(int i = 0; i < apriOut.size(); i++) { if(showItemsets) { System.out.println("itemset:" + apriOut.get(i).toString() + " Support = " +apriOut.get(i).support); } } for(int i = 0; i < rules.size(); i++) { if(showRules) { System.out.println(" Rule:" + rules.get(i).toString()); } } }
public static void main(String [ ] args) { boolean showItemsets = true; boolean showRules = true; boolean aprioriSkyLine = true; String fileName = "data/out1.csv"; if(args.length >= 1){ fileName = args[0]; } ArrayList<Vector> vecList = null; vecList = MyParser.parseSparseVectorCSV(fileName); double minSupport = 0.1; if(args.length >= 2){ minSupport = Double.parseDouble(args[1]); } else{ System.out.println("No argument for minimum support found, using "+minSupport+" as value."); } double minConfidence = 0.1; if(args.length >= 3){ minConfidence = Double.parseDouble(args[2]); } else{ System.out.println("No argument for minimum confidence found, using "+minConfidence+" as value."); } ArrayList<Vector> apriOut = Apriori.AprMainLoop(vecList, minSupport, aprioriSkyLine); ArrayList<AssociationRule> rules = genRules.genRulesMainLoop(apriOut, vecList, minConfidence);; for(int i = 0; i < apriOut.size(); i++) { if(showItemsets) { System.out.println("itemset:" + apriOut.get(i).toString() + " Support = " +apriOut.get(i).support); } } for(int i = 0; i < rules.size(); i++) { if(showRules) { System.out.println(" Rule:" + rules.get(i).toString()); } } }
diff --git a/impl/src/main/java/org/jboss/webbeans/bean/proxy/ClientProxyProvider.java b/impl/src/main/java/org/jboss/webbeans/bean/proxy/ClientProxyProvider.java index 8f5981bb1..078ad3137 100644 --- a/impl/src/main/java/org/jboss/webbeans/bean/proxy/ClientProxyProvider.java +++ b/impl/src/main/java/org/jboss/webbeans/bean/proxy/ClientProxyProvider.java @@ -1,142 +1,142 @@ /* * JBoss, Home of Professional Open Source * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * 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.jboss.webbeans.bean.proxy; import java.io.Serializable; import java.lang.reflect.Type; import java.util.LinkedHashSet; import java.util.Set; import java.util.concurrent.Callable; import javassist.util.proxy.ProxyFactory; import javax.enterprise.inject.spi.Bean; import org.jboss.webbeans.BeanManagerImpl; import org.jboss.webbeans.DefinitionException; import org.jboss.webbeans.util.Proxies; import org.jboss.webbeans.util.collections.ConcurrentCache; /** * A proxy pool for holding scope adaptors (client proxies) * * @author Nicklas Karlsson * * @see org.jboss.webbeans.bean.proxy.ProxyMethodHandler */ public class ClientProxyProvider { private static final long serialVersionUID = 9029999149357529341L; /** * A container/cache for previously created proxies * * @author Nicklas Karlsson */ private final ConcurrentCache<Bean<? extends Object>, Object> pool; /** * Constructor */ public ClientProxyProvider() { this.pool = new ConcurrentCache<Bean<? extends Object>, Object>(); } /** * Creates a Javassist scope adaptor (client proxy) for a bean * * Creates a Javassist proxy factory. Gets the type info. Sets the interfaces * and superclass to the factory. Hooks in the MethodHandler and creates the * proxy. * * @param bean The bean to proxy * @param beanIndex The index to the bean in the manager bean list * @return A Javassist proxy * @throws InstantiationException When the proxy couldn't be created * @throws IllegalAccessException When the proxy couldn't be created */ private static <T> T createClientProxy(Bean<T> bean, BeanManagerImpl manager, int beanIndex) throws RuntimeException { try { ClientProxyMethodHandler proxyMethodHandler = new ClientProxyMethodHandler(bean, manager, beanIndex); Set<Type> classes = new LinkedHashSet<Type>(bean.getTypes()); + //classes.add(ClientProxyInstance.class); classes.add(Serializable.class); - classes.add(ClientProxyInstance.class); ProxyFactory proxyFactory = Proxies.getProxyFactory(classes); proxyFactory.setHandler(proxyMethodHandler); Class<?> clazz = proxyFactory.createClass(); @SuppressWarnings("unchecked") T instance = (T) clazz.newInstance(); return instance; } catch (InstantiationException e) { throw new RuntimeException("Could not instantiate client proxy for " + bean, e); } catch (IllegalAccessException e) { throw new RuntimeException("Could not access bean correctly when creating client proxy for " + bean, e); } } /** * Gets a client proxy for a bean * * Looks for a proxy in the pool. If not found, one is created and added to * the pool if the create argument is true. * * @param bean The bean to get a proxy to * @return the client proxy for the bean */ public <T> T getClientProxy(final BeanManagerImpl manager, final Bean<T> bean) { T instance = pool.putIfAbsent(bean, new Callable<T>() { public T call() throws Exception { int beanIndex = manager.getBeans().indexOf(bean); if (beanIndex < 0) { throw new DefinitionException(bean + " is not known to the manager"); } return createClientProxy(bean, manager, beanIndex); } }); // TODO Break circular injection. Can we somehow support both? //((ClientProxyInstance) instance).touch(Marker.INSTANCE); return instance; } /** * Gets a string representation * * @return The string representation */ @Override public String toString() { return "Proxy pool with " + pool.size() + " proxies"; } }
false
true
private static <T> T createClientProxy(Bean<T> bean, BeanManagerImpl manager, int beanIndex) throws RuntimeException { try { ClientProxyMethodHandler proxyMethodHandler = new ClientProxyMethodHandler(bean, manager, beanIndex); Set<Type> classes = new LinkedHashSet<Type>(bean.getTypes()); classes.add(Serializable.class); classes.add(ClientProxyInstance.class); ProxyFactory proxyFactory = Proxies.getProxyFactory(classes); proxyFactory.setHandler(proxyMethodHandler); Class<?> clazz = proxyFactory.createClass(); @SuppressWarnings("unchecked") T instance = (T) clazz.newInstance(); return instance; } catch (InstantiationException e) { throw new RuntimeException("Could not instantiate client proxy for " + bean, e); } catch (IllegalAccessException e) { throw new RuntimeException("Could not access bean correctly when creating client proxy for " + bean, e); } }
private static <T> T createClientProxy(Bean<T> bean, BeanManagerImpl manager, int beanIndex) throws RuntimeException { try { ClientProxyMethodHandler proxyMethodHandler = new ClientProxyMethodHandler(bean, manager, beanIndex); Set<Type> classes = new LinkedHashSet<Type>(bean.getTypes()); //classes.add(ClientProxyInstance.class); classes.add(Serializable.class); ProxyFactory proxyFactory = Proxies.getProxyFactory(classes); proxyFactory.setHandler(proxyMethodHandler); Class<?> clazz = proxyFactory.createClass(); @SuppressWarnings("unchecked") T instance = (T) clazz.newInstance(); return instance; } catch (InstantiationException e) { throw new RuntimeException("Could not instantiate client proxy for " + bean, e); } catch (IllegalAccessException e) { throw new RuntimeException("Could not access bean correctly when creating client proxy for " + bean, e); } }
diff --git a/src/org/python/core/PyModule.java b/src/org/python/core/PyModule.java index 5ccef86c..643f3087 100644 --- a/src/org/python/core/PyModule.java +++ b/src/org/python/core/PyModule.java @@ -1,182 +1,185 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; import org.python.expose.ExposedDelete; import org.python.expose.ExposedGet; import org.python.expose.ExposedMethod; import org.python.expose.ExposedNew; import org.python.expose.ExposedSet; import org.python.expose.ExposedType; /** * The Python Module object. * */ @ExposedType(name = "module") public class PyModule extends PyObject { private final PyObject moduleDoc = new PyString( "module(name[, doc])\n" + "\n" + "Create a module object.\n" + "The name must be a string; the optional doc argument can have any type."); /** The module's mutable dictionary */ @ExposedGet public PyObject __dict__; public PyModule() { super(); } public PyModule(PyType subType) { super(subType); } public PyModule(PyType subType, String name) { super(subType); module___init__(new PyString(name), Py.None); } public PyModule(String name) { this(name, null); } public PyModule(String name, PyObject dict) { super(); __dict__ = dict; module___init__(new PyString(name), Py.None); } @ExposedNew @ExposedMethod final void module___init__(PyObject[] args, String[] keywords) { ArgParser ap = new ArgParser("__init__", args, keywords, new String[] {"name", "doc"}); PyObject name = ap.getPyObject(0); PyObject docs = ap.getPyObject(1, Py.None); module___init__(name, docs); } private void module___init__(PyObject name, PyObject doc) { ensureDict(); __dict__.__setitem__("__name__", name); __dict__.__setitem__("__doc__", doc); } public PyObject fastGetDict() { return __dict__; } public PyObject getDict() { return __dict__; } @ExposedSet(name = "__dict__") public void setDict(PyObject newDict) { throw Py.TypeError("readonly attribute"); } @ExposedDelete(name = "__dict__") public void delDict() { throw Py.TypeError("readonly attribute"); } protected PyObject impAttr(String name) { + if (__dict__ == null) { + return null; + } PyObject path = __dict__.__finditem__("__path__"); PyObject pyName = __dict__.__finditem__("__name__"); if (path == null || pyName == null) { return null; } PyObject attr = null; String fullName = (pyName.__str__().toString() + '.' + name).intern(); if (path == Py.None) { // XXX: disabled //attr = imp.loadFromClassLoader(fullName, // Py.getSystemState().getClassLoader()); } else if (path instanceof PyList) { attr = imp.find_module(name, fullName, (PyList)path); } else { throw Py.TypeError("__path__ must be list or None"); } if (attr == null) { attr = PySystemState.packageManager.lookupName(fullName); } if (attr != null) { // Allow a package component to change its own meaning PyObject found = Py.getSystemState().modules.__finditem__(fullName); if (found != null) { attr = found; } __dict__.__setitem__(name, attr); return attr; } return null; } @Override public PyObject __findattr_ex__(String name) { PyObject attr=super.__findattr_ex__(name); if (attr!=null) return attr; return impAttr(name); } public void __setattr__(String name, PyObject value) { module___setattr__(name, value); } @ExposedMethod final void module___setattr__(String name, PyObject value) { if (name != "__dict__") { ensureDict(); } super.__setattr__(name, value); } public void __delattr__(String name) { module___delattr__(name); } @ExposedMethod final void module___delattr__(String name) { super.__delattr__(name); } public String toString() { return module_toString(); } @ExposedMethod(names = {"__repr__"}) final String module_toString() { PyObject name = null; PyObject filename = null; if (__dict__ != null) { name = __dict__.__finditem__("__name__"); filename = __dict__.__finditem__("__file__"); } if (name == null) { name = new PyString("?"); } if (filename == null) { return String.format("<module '%s' (built-in)>", name); } return String.format("<module '%s' from '%s'>", name, filename); } public PyObject __dir__() { if (__dict__ == null) { throw Py.TypeError("module.__dict__ is not a dictionary"); } return __dict__.invoke("keys"); } private void ensureDict() { if (__dict__ == null) { __dict__ = new PyStringMap(); } } }
true
true
protected PyObject impAttr(String name) { PyObject path = __dict__.__finditem__("__path__"); PyObject pyName = __dict__.__finditem__("__name__"); if (path == null || pyName == null) { return null; } PyObject attr = null; String fullName = (pyName.__str__().toString() + '.' + name).intern(); if (path == Py.None) { // XXX: disabled //attr = imp.loadFromClassLoader(fullName, // Py.getSystemState().getClassLoader()); } else if (path instanceof PyList) { attr = imp.find_module(name, fullName, (PyList)path); } else { throw Py.TypeError("__path__ must be list or None"); } if (attr == null) { attr = PySystemState.packageManager.lookupName(fullName); } if (attr != null) { // Allow a package component to change its own meaning PyObject found = Py.getSystemState().modules.__finditem__(fullName); if (found != null) { attr = found; } __dict__.__setitem__(name, attr); return attr; } return null; }
protected PyObject impAttr(String name) { if (__dict__ == null) { return null; } PyObject path = __dict__.__finditem__("__path__"); PyObject pyName = __dict__.__finditem__("__name__"); if (path == null || pyName == null) { return null; } PyObject attr = null; String fullName = (pyName.__str__().toString() + '.' + name).intern(); if (path == Py.None) { // XXX: disabled //attr = imp.loadFromClassLoader(fullName, // Py.getSystemState().getClassLoader()); } else if (path instanceof PyList) { attr = imp.find_module(name, fullName, (PyList)path); } else { throw Py.TypeError("__path__ must be list or None"); } if (attr == null) { attr = PySystemState.packageManager.lookupName(fullName); } if (attr != null) { // Allow a package component to change its own meaning PyObject found = Py.getSystemState().modules.__finditem__(fullName); if (found != null) { attr = found; } __dict__.__setitem__(name, attr); return attr; } return null; }
diff --git a/src/community/web2/core/src/test/java/org/geoserver/web/wicket/EnvelopePanelTest.java b/src/community/web2/core/src/test/java/org/geoserver/web/wicket/EnvelopePanelTest.java index 0fbae959a7..ad60f93b5d 100644 --- a/src/community/web2/core/src/test/java/org/geoserver/web/wicket/EnvelopePanelTest.java +++ b/src/community/web2/core/src/test/java/org/geoserver/web/wicket/EnvelopePanelTest.java @@ -1,51 +1,51 @@ package org.geoserver.web.wicket; import org.apache.wicket.Component; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.util.tester.FormTester; import org.geoserver.web.FormTestPage; import org.geoserver.web.GeoServerWicketTestSupport; import org.geotools.geometry.jts.ReferencedEnvelope; import org.geotools.referencing.crs.DefaultGeographicCRS; import com.vividsolutions.jts.geom.Envelope; public class EnvelopePanelTest extends GeoServerWicketTestSupport { ReferencedEnvelope e; @Override protected void setUpInternal() throws Exception { super.setUpInternal(); e = new ReferencedEnvelope(-180,180,-90,90, DefaultGeographicCRS.WGS84); tester.startPage(new FormTestPage(new FormTestPage.ComponentBuilder() { public Component buildComponent(String id) { return new EnvelopePanel(id, e); } })); } public void test() throws Exception { tester.assertComponent( "form", Form.class ); FormTester ft = tester.newFormTester( "form"); - assertEquals( "-180", ft.getTextComponentValue( "content:minX") ); - assertEquals( "-90", ft.getTextComponentValue( "content:minY") ); - assertEquals( "180", ft.getTextComponentValue( "content:maxX") ); - assertEquals( "90", ft.getTextComponentValue( "content:maxY") ); + assertEquals( "-180", ft.getTextComponentValue( "panel:minX") ); + assertEquals( "-90", ft.getTextComponentValue( "panel:minY") ); + assertEquals( "180", ft.getTextComponentValue( "panel:maxX") ); + assertEquals( "90", ft.getTextComponentValue( "panel:maxY") ); - EnvelopePanel ep = (EnvelopePanel) tester.getComponentFromLastRenderedPage("form:content"); + EnvelopePanel ep = (EnvelopePanel) tester.getComponentFromLastRenderedPage("form:panel"); assertEquals( e, ep.getModelObject() ); - ft.setValue( "content:minX", "-2"); - ft.setValue( "content:minY", "-2"); - ft.setValue( "content:maxX", "2"); - ft.setValue( "content:maxY", "2"); + ft.setValue( "panel:minX", "-2"); + ft.setValue( "panel:minY", "-2"); + ft.setValue( "panel:maxX", "2"); + ft.setValue( "panel:maxY", "2"); ft.submit(); assertEquals( new Envelope(-2,2,-2,2), ep.getModelObject() ); } }
false
true
public void test() throws Exception { tester.assertComponent( "form", Form.class ); FormTester ft = tester.newFormTester( "form"); assertEquals( "-180", ft.getTextComponentValue( "content:minX") ); assertEquals( "-90", ft.getTextComponentValue( "content:minY") ); assertEquals( "180", ft.getTextComponentValue( "content:maxX") ); assertEquals( "90", ft.getTextComponentValue( "content:maxY") ); EnvelopePanel ep = (EnvelopePanel) tester.getComponentFromLastRenderedPage("form:content"); assertEquals( e, ep.getModelObject() ); ft.setValue( "content:minX", "-2"); ft.setValue( "content:minY", "-2"); ft.setValue( "content:maxX", "2"); ft.setValue( "content:maxY", "2"); ft.submit(); assertEquals( new Envelope(-2,2,-2,2), ep.getModelObject() ); }
public void test() throws Exception { tester.assertComponent( "form", Form.class ); FormTester ft = tester.newFormTester( "form"); assertEquals( "-180", ft.getTextComponentValue( "panel:minX") ); assertEquals( "-90", ft.getTextComponentValue( "panel:minY") ); assertEquals( "180", ft.getTextComponentValue( "panel:maxX") ); assertEquals( "90", ft.getTextComponentValue( "panel:maxY") ); EnvelopePanel ep = (EnvelopePanel) tester.getComponentFromLastRenderedPage("form:panel"); assertEquals( e, ep.getModelObject() ); ft.setValue( "panel:minX", "-2"); ft.setValue( "panel:minY", "-2"); ft.setValue( "panel:maxX", "2"); ft.setValue( "panel:maxY", "2"); ft.submit(); assertEquals( new Envelope(-2,2,-2,2), ep.getModelObject() ); }
diff --git a/AStar/AStar.java b/AStar/AStar.java index f74709a..aaa9f72 100644 --- a/AStar/AStar.java +++ b/AStar/AStar.java @@ -1,166 +1,166 @@ package AStar; import java.util.ArrayList; import java.util.Comparator; import java.util.PriorityQueue; import java.util.Collections; import AStar.ISearchNode; /** * Uses the A* Algorithm to find the shortest path from * an initial to a goal node. * */ public class AStar { // Amount of debug output 0,1,2 private int verbose = 0; // The maximum number of completed nodes. After that number the algorithm returns null. // If negative, the search will run until the goal node is found. private int maxSteps = -1; //number of search steps the AStar will perform before null is returned private int numSearchSteps; public ISearchNode bestNodeAfterSearch; public AStar() { } /** * Returns the shortest Path from a start node to an end node according to * the A* heuristics (h must not overestimate). initialNode and last found node included. */ public ArrayList<ISearchNode> shortestPath(ISearchNode initialNode, IGoalNode goalNode) { //perform search and save the ISearchNode endNode = this.search(initialNode, goalNode); if(endNode == null) return null; //return shortest path according to AStar heuristics return AStar.path(endNode); } /** * @param initialNode start of the search * @param goalNode end of the search * @return goal node from which you can reconstruct the path */ public ISearchNode search(ISearchNode initialNode, IGoalNode goalNode) { - PriorityQueue<ISearchNode> openSet = new PriorityQueue<ISearchNode>(); + PriorityQueue<ISearchNode> openSet = new PriorityQueue<ISearchNode>(1000, new SearchNodeComparator()); openSet.add(initialNode); ArrayList<ISearchNode> closedSet = new ArrayList<ISearchNode>(); // current iteration of the search this.numSearchSteps = 0; while(openSet.size() > 0 && (maxSteps < 0 || this.numSearchSteps < maxSteps)) { //get element with the least sum of costs from the initial node //and heuristic costs to the goal ISearchNode currentNode = openSet.poll(); //debug output according to verbose System.out.println((verbose>1 ? "Open set: " + openSet.toString() + "\n" : "") + (verbose>0 ? "Current node: "+currentNode.toString()+"\n": "") + (verbose>1 ? "Closed set: " + closedSet.toString() : "")); if(goalNode.inGoal(currentNode)) { //we know the shortest path to the goal node, done this.bestNodeAfterSearch = currentNode; return currentNode; } //get successor nodes ArrayList<ISearchNode> successorNodes = currentNode.getSuccessors(); for(ISearchNode successorNode : successorNodes) { boolean inOpenSet; if(closedSet.contains(successorNode)) continue; /* Special rule for nodes that are generated within other nodes: * We need to ensure that we use the node and * its g value from the openSet if its already discovered */ ISearchNode discSuccessorNode = getNode(openSet, successorNode); if(discSuccessorNode != null) { successorNode = discSuccessorNode; inOpenSet = true; } else { inOpenSet = false; } //compute tentativeG double tentativeG = currentNode.g() + currentNode.c(successorNode); //node was already discovered and this path is worse than the last one if(inOpenSet && tentativeG >= successorNode.g()) continue; successorNode.setParent(currentNode); if(inOpenSet) { // if successorNode is already in data structure it has to be inserted again to // regain the order openSet.remove(successorNode); successorNode.setG(tentativeG); openSet.add(successorNode); } else { successorNode.setG(tentativeG); openSet.add(successorNode); } } closedSet.add(currentNode); this.numSearchSteps += 1; } this.bestNodeAfterSearch = Collections.min(closedSet, new SearchNodeComparator()); return null; } /** * returns path from the earliest ancestor to the node in the argument * if the parents are set via AStar search, it will return the path found. * This is the shortest shortest path, if the heuristic h does not overestimate * the true remaining costs * @param node node from which the parents are to be found. Parents of the node should * have been properly set in preprocessing (f.e. AStar.search) * @return path to the node in the argument */ public static ArrayList<ISearchNode> path(ISearchNode node) { ArrayList<ISearchNode> path = new ArrayList<ISearchNode>(); path.add(node); ISearchNode currentNode = node; while(currentNode.getParent() != null) { ISearchNode parent = currentNode.getParent(); path.add(0, parent); currentNode = parent; } return path; } public int numSearchSteps() { return this.numSearchSteps; } public ISearchNode bestNodeAfterSearch() { return this.bestNodeAfterSearch; } public void setMaxSteps(int maxSteps) { this.maxSteps = maxSteps; } static class SearchNodeComparator implements Comparator<ISearchNode> { public int compare(ISearchNode node1, ISearchNode node2) { return Double.compare(node1.f(), node2.f()); } } /** * returns the element from a PriorityQueue of ISearchNodes * @param queue queue to search in * @param searchedNode node we search * @return node from the queue */ private static ISearchNode getNode(PriorityQueue<ISearchNode> queue, ISearchNode searchedNode) { for(ISearchNode openSearchNode : queue) { if(openSearchNode.equals(searchedNode)) { return openSearchNode; } } return null; } }
true
true
public ISearchNode search(ISearchNode initialNode, IGoalNode goalNode) { PriorityQueue<ISearchNode> openSet = new PriorityQueue<ISearchNode>(); openSet.add(initialNode); ArrayList<ISearchNode> closedSet = new ArrayList<ISearchNode>(); // current iteration of the search this.numSearchSteps = 0; while(openSet.size() > 0 && (maxSteps < 0 || this.numSearchSteps < maxSteps)) { //get element with the least sum of costs from the initial node //and heuristic costs to the goal ISearchNode currentNode = openSet.poll(); //debug output according to verbose System.out.println((verbose>1 ? "Open set: " + openSet.toString() + "\n" : "") + (verbose>0 ? "Current node: "+currentNode.toString()+"\n": "") + (verbose>1 ? "Closed set: " + closedSet.toString() : "")); if(goalNode.inGoal(currentNode)) { //we know the shortest path to the goal node, done this.bestNodeAfterSearch = currentNode; return currentNode; } //get successor nodes ArrayList<ISearchNode> successorNodes = currentNode.getSuccessors(); for(ISearchNode successorNode : successorNodes) { boolean inOpenSet; if(closedSet.contains(successorNode)) continue; /* Special rule for nodes that are generated within other nodes: * We need to ensure that we use the node and * its g value from the openSet if its already discovered */ ISearchNode discSuccessorNode = getNode(openSet, successorNode); if(discSuccessorNode != null) { successorNode = discSuccessorNode; inOpenSet = true; } else { inOpenSet = false; } //compute tentativeG double tentativeG = currentNode.g() + currentNode.c(successorNode); //node was already discovered and this path is worse than the last one if(inOpenSet && tentativeG >= successorNode.g()) continue; successorNode.setParent(currentNode); if(inOpenSet) { // if successorNode is already in data structure it has to be inserted again to // regain the order openSet.remove(successorNode); successorNode.setG(tentativeG); openSet.add(successorNode); } else { successorNode.setG(tentativeG); openSet.add(successorNode); } } closedSet.add(currentNode); this.numSearchSteps += 1; } this.bestNodeAfterSearch = Collections.min(closedSet, new SearchNodeComparator()); return null; }
public ISearchNode search(ISearchNode initialNode, IGoalNode goalNode) { PriorityQueue<ISearchNode> openSet = new PriorityQueue<ISearchNode>(1000, new SearchNodeComparator()); openSet.add(initialNode); ArrayList<ISearchNode> closedSet = new ArrayList<ISearchNode>(); // current iteration of the search this.numSearchSteps = 0; while(openSet.size() > 0 && (maxSteps < 0 || this.numSearchSteps < maxSteps)) { //get element with the least sum of costs from the initial node //and heuristic costs to the goal ISearchNode currentNode = openSet.poll(); //debug output according to verbose System.out.println((verbose>1 ? "Open set: " + openSet.toString() + "\n" : "") + (verbose>0 ? "Current node: "+currentNode.toString()+"\n": "") + (verbose>1 ? "Closed set: " + closedSet.toString() : "")); if(goalNode.inGoal(currentNode)) { //we know the shortest path to the goal node, done this.bestNodeAfterSearch = currentNode; return currentNode; } //get successor nodes ArrayList<ISearchNode> successorNodes = currentNode.getSuccessors(); for(ISearchNode successorNode : successorNodes) { boolean inOpenSet; if(closedSet.contains(successorNode)) continue; /* Special rule for nodes that are generated within other nodes: * We need to ensure that we use the node and * its g value from the openSet if its already discovered */ ISearchNode discSuccessorNode = getNode(openSet, successorNode); if(discSuccessorNode != null) { successorNode = discSuccessorNode; inOpenSet = true; } else { inOpenSet = false; } //compute tentativeG double tentativeG = currentNode.g() + currentNode.c(successorNode); //node was already discovered and this path is worse than the last one if(inOpenSet && tentativeG >= successorNode.g()) continue; successorNode.setParent(currentNode); if(inOpenSet) { // if successorNode is already in data structure it has to be inserted again to // regain the order openSet.remove(successorNode); successorNode.setG(tentativeG); openSet.add(successorNode); } else { successorNode.setG(tentativeG); openSet.add(successorNode); } } closedSet.add(currentNode); this.numSearchSteps += 1; } this.bestNodeAfterSearch = Collections.min(closedSet, new SearchNodeComparator()); return null; }
diff --git a/imap2/src/com/android/imap2/Imap2SyncService.java b/imap2/src/com/android/imap2/Imap2SyncService.java index 8f069d9c2..82a5ffa95 100644 --- a/imap2/src/com/android/imap2/Imap2SyncService.java +++ b/imap2/src/com/android/imap2/Imap2SyncService.java @@ -1,2469 +1,2469 @@ /* Copyright (C) 2012 The Android Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.imap2; import android.content.ContentProviderOperation; import android.content.ContentProviderOperation.Builder; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.OperationApplicationException; import android.database.Cursor; import android.net.TrafficStats; import android.net.Uri; import android.os.Bundle; import android.os.RemoteException; import android.util.Log; import com.android.emailcommon.Logging; import com.android.emailcommon.TrafficFlags; import com.android.emailcommon.internet.MimeUtility; import com.android.emailcommon.internet.Rfc822Output; import com.android.emailcommon.mail.Address; import com.android.emailcommon.mail.CertificateValidationException; import com.android.emailcommon.mail.MessagingException; import com.android.emailcommon.provider.Account; import com.android.emailcommon.provider.EmailContent; import com.android.emailcommon.provider.EmailContent.AccountColumns; import com.android.emailcommon.provider.EmailContent.Attachment; import com.android.emailcommon.provider.EmailContent.Body; import com.android.emailcommon.provider.EmailContent.MailboxColumns; import com.android.emailcommon.provider.EmailContent.Message; import com.android.emailcommon.provider.EmailContent.MessageColumns; import com.android.emailcommon.provider.EmailContent.SyncColumns; import com.android.emailcommon.provider.HostAuth; import com.android.emailcommon.provider.Mailbox; import com.android.emailcommon.provider.MailboxUtilities; import com.android.emailcommon.service.EmailServiceProxy; import com.android.emailcommon.service.EmailServiceStatus; import com.android.emailcommon.service.SearchParams; import com.android.emailcommon.service.SyncWindow; import com.android.emailcommon.utility.CountingOutputStream; import com.android.emailcommon.utility.EOLConvertingOutputStream; import com.android.emailcommon.utility.SSLUtils; import com.android.emailcommon.utility.TextUtilities; import com.android.emailcommon.utility.Utility; import com.android.emailsync.AbstractSyncService; import com.android.emailsync.PartRequest; import com.android.emailsync.Request; import com.android.emailsync.SyncManager; import com.android.imap2.smtp.SmtpSender; import com.android.mail.providers.UIProvider; import com.beetstra.jutf7.CharsetProvider; import com.google.common.annotations.VisibleForTesting; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.net.SocketException; import java.net.SocketTimeoutException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLException; import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocket; public class Imap2SyncService extends AbstractSyncService { private static final String IMAP_OK = "OK"; private static final SimpleDateFormat GMAIL_INTERNALDATE_FORMAT = new SimpleDateFormat("EEE, dd MMM yy HH:mm:ss z"); private static final String IMAP_ERR = "ERR"; private static final String IMAP_NO = "NO"; private static final String IMAP_BAD = "BAD"; private static final SimpleDateFormat IMAP_DATE_FORMAT = new SimpleDateFormat("dd-MMM-yyyy"); private static final SimpleDateFormat INTERNALDATE_FORMAT = new SimpleDateFormat("dd-MMM-yy HH:mm:ss z"); private static final Charset MODIFIED_UTF_7_CHARSET = new CharsetProvider().charsetForName("X-RFC-3501"); public static final String IMAP_DELETED_MESSAGES_FOLDER_NAME = "AndroidMail Trash"; public static final String GMAIL_TRASH_FOLDER = "[Gmail]/Trash"; private static Pattern IMAP_RESPONSE_PATTERN = Pattern.compile("\\*(\\s(\\d+))?\\s(\\w+).*"); private static final int HEADER_BATCH_COUNT = 20; private static final int SECONDS = 1000; private static final int MINS = 60*SECONDS; private static final int IDLE_ASLEEP_MILLIS = 11*MINS; private static final int IDLE_FALLBACK_SYNC_INTERVAL = 10; private static final int SOCKET_CONNECT_TIMEOUT = 10*SECONDS; private static final int SOCKET_TIMEOUT = 20*SECONDS; private static final int SEARCH_TIMEOUT = 60*SECONDS; private static final int AUTOMATIC_SYNC_WINDOW_MAX_MESSAGES = 250; private static final int AUTOMATIC_SYNC_WINDOW_LARGE_MAILBOX = 1000; private ContentResolver mResolver; private int mWriterTag = 1; private boolean mIsGmail = false; private boolean mIsIdle = false; private int mLastExists = -1; private ArrayList<String> mImapResponse = null; private String mImapResult; private String mImapErrorLine = null; private String mImapSuccessLine = null; private Socket mSocket = null; private boolean mStop = false; public int mServiceResult = 0; private boolean mIsServiceRequestPending = false; private final String[] MAILBOX_SERVER_ID_ARGS = new String[2]; public Imap2SyncService() { this("Imap2 Validation"); } private final ArrayList<Integer> SERVER_DELETES = new ArrayList<Integer>(); private static final String INBOX_SERVER_NAME = "Inbox"; // Per RFC3501 private BufferedWriter mWriter; private ImapInputStream mReader; private HostAuth mHostAuth; private String mPrefix; private long mTrashMailboxId = Mailbox.NO_MAILBOX; private long mAccountId; private final ArrayList<Long> mUpdatedIds = new ArrayList<Long>(); private final ArrayList<Long> mDeletedIds = new ArrayList<Long>(); private final Stack<Integer> mDeletes = new Stack<Integer>(); private final Stack<Integer> mReadUpdates = new Stack<Integer>(); private final Stack<Integer> mUnreadUpdates = new Stack<Integer>(); private final Stack<Integer> mFlaggedUpdates = new Stack<Integer>(); private final Stack<Integer> mUnflaggedUpdates = new Stack<Integer>(); public Imap2SyncService(Context _context, Mailbox _mailbox) { super(_context, _mailbox); mResolver = _context.getContentResolver(); if (mAccount != null) { mAccountId = mAccount.mId; } MAILBOX_SERVER_ID_ARGS[0] = Long.toString(mMailboxId); } private Imap2SyncService(String prefix) { super(prefix); } public Imap2SyncService(Context _context, Account _account) { this("Imap2 Account"); mContext = _context; mResolver = _context.getContentResolver(); mAccount = _account; mAccountId = _account.mId; mHostAuth = HostAuth.restoreHostAuthWithId(_context, mAccount.mHostAuthKeyRecv); mPrefix = mHostAuth.mDomain; mTrashMailboxId = Mailbox.findMailboxOfType(_context, _account.mId, Mailbox.TYPE_TRASH); } @Override public boolean alarm() { // See if we've got anything to do... Cursor updates = getUpdatesCursor(); Cursor deletes = getDeletesCursor(); try { if (mRequestQueue.isEmpty() && updates == null && deletes == null) { userLog("Ping: nothing to do"); } else { int cnt = mRequestQueue.size(); if (updates != null) { cnt += updates.getCount(); } if (deletes != null) { cnt += deletes.getCount(); } userLog("Ping: " + cnt + " tasks"); ping(); } } finally { if (updates != null) { updates.close(); } if (deletes != null) { deletes.close(); } } return true; } @Override public void reset() { // TODO Auto-generated method stub } public void addRequest(Request req) { super.addRequest(req); if (req instanceof PartRequest) { userLog("Request for attachment " + ((PartRequest)req).mAttachment.mId); } ping(); } @Override public Bundle validateAccount(HostAuth hostAuth, Context context) { Bundle bundle = new Bundle(); int resultCode = MessagingException.IOERROR; Connection conn = connectAndLogin(hostAuth, "main"); if (conn.status == EXIT_DONE) { resultCode = MessagingException.NO_ERROR; } else if (conn.status == EXIT_LOGIN_FAILURE) { resultCode = MessagingException.AUTHENTICATION_FAILED; } bundle.putInt(EmailServiceProxy.VALIDATE_BUNDLE_RESULT_CODE, resultCode); return bundle; } public void loadFolderList() throws IOException { HostAuth hostAuth = HostAuth.restoreHostAuthWithId(mContext, mAccount.mHostAuthKeyRecv); if (hostAuth == null) return; Connection conn = connectAndLogin(hostAuth, "folderList"); if (conn.status == EXIT_DONE) { setConnection(conn); readFolderList(); conn.socket.close(); } } private void setConnection(Connection conn) { mConnection = conn; mWriter = conn.writer; mReader = conn.reader; mSocket = conn.socket; } @Override public void resetCalendarSyncKey() { // Not used by Imap2 } public void ping() { mIsServiceRequestPending = true; Imap2SyncManager.runAwake(mMailbox.mId); if (mSocket != null) { try { if (mIsIdle) { userLog("breakIdle; sending DONE..."); mWriter.write("DONE\r\n"); mWriter.flush(); } } catch (SocketException e) { } catch (IOException e) { } } } public void stop () { if (mSocket != null) try { if (mIsIdle) ping(); mSocket.close(); } catch (IOException e) { } mStop = true; } public String writeCommand (Writer out, String cmd) throws IOException { Integer t = mWriterTag++; String tag = "@@a" + t + ' '; if (!cmd.startsWith("login")) { userLog(tag + cmd); } out.write(tag); out.write(cmd); out.write("\r\n"); out.flush(); return tag; } private void writeContinuation(Writer out, String cmd) { try { out.write(cmd); out.write("\r\n"); out.flush(); userLog(cmd); } catch (IOException e) { userLog("IOException in writeCommand"); } } private long readLong (String str, int idx) { char ch = str.charAt(idx); long num = 0; while (ch >= '0' && ch <= '9') { num = (num * 10) + (ch - '0'); ch = str.charAt(++idx); } return num; } private void readUntagged(String str) { // Skip the "* " Parser p = new Parser(str, 2); String type = p.parseAtom(); int val = -1; if (type != null) { char c = type.charAt(0); if (c >= '0' && c <= '9') try { val = Integer.parseInt(type); type = p.parseAtom(); if (p != null) { if (type.toLowerCase().equals("exists")) mLastExists = val; } } catch (NumberFormatException e) { } else if (mMailbox != null && (mMailbox.mSyncKey == null || mMailbox.mSyncKey == "0")) { str = str.toLowerCase(); int idx = str.indexOf("uidvalidity"); if (idx > 0) { // 12 = length of "uidvalidity" + 1 long num = readLong(str, idx + 12); mMailbox.mSyncKey = Long.toString(num); ContentValues cv = new ContentValues(); cv.put(MailboxColumns.SYNC_KEY, mMailbox.mSyncKey); mContext.getContentResolver().update( ContentUris.withAppendedId(Mailbox.CONTENT_URI, mMailbox.mId), cv, null, null); } } } userLog("Untagged: " + type); } private boolean caseInsensitiveStartsWith(String str, String tag) { return str.toLowerCase().startsWith(tag.toLowerCase()); } private String readResponse (ImapInputStream r, String tag) throws IOException { return readResponse(r, tag, null); } private String readResponse (ImapInputStream r, String tag, String command) throws IOException { mImapResult = IMAP_ERR; String str = null; if (command != null) mImapResponse = new ArrayList<String>(); while (true) { str = r.readLine(); userLog("< " + str); if (caseInsensitiveStartsWith(str, tag)) { // This is the response from the command named 'tag' Parser p = new Parser(str, tag.length() - 1); mImapResult = p.parseAtom(); break; } else if (str.charAt(0) == '*') { if (command != null) { Matcher m = IMAP_RESPONSE_PATTERN.matcher(str); if (m.matches() && m.group(3).equals(command)) { mImapResponse.add(str); } else readUntagged(str); } else readUntagged(str); } else if (str.charAt(0) == '+') { mImapResult = str; return str; } else if (!mImapResponse.isEmpty()) { // Continuation with string literal, perhaps? int off = mImapResponse.size() - 1; mImapResponse.set(off, mImapResponse.get(off) + "\r\n" + str); } } if (mImapResult.equals(IMAP_OK)) { mImapSuccessLine = str; } else { userLog("$$$ Error result = " + mImapResult); mImapErrorLine = str; } return mImapResult; } String parseRecipientList (String str) { if (str == null) return null; ArrayList<Address> list = new ArrayList<Address>(); String r; Parser p = new Parser(str); while ((r = p.parseList()) != null) { Parser rp = new Parser(r); String displayName = rp.parseString(); rp.parseString(); String emailAddress = rp.parseString() + "@" + rp.parseString(); list.add(new Address(emailAddress, displayName)); } return Address.pack(list.toArray(new Address[list.size()])); } String parseRecipients (Parser p, Message msg) { msg.mFrom = parseRecipientList(p.parseListOrNil()); @SuppressWarnings("unused") String senderList = parseRecipientList(p.parseListOrNil()); msg.mReplyTo = parseRecipientList(p.parseListOrNil()); msg.mTo = parseRecipientList(p.parseListOrNil()); msg.mCc = parseRecipientList(p.parseListOrNil()); msg.mBcc = parseRecipientList(p.parseListOrNil()); return Address.toFriendly(Address.unpack(msg.mFrom)); } private Message createMessage (String str, long mailboxId) { Parser p = new Parser(str, str.indexOf('(') + 1); Date date = null; String subject = null; String sender = null; boolean read = false; int flag = 0; String flags = null; int uid = 0; Message msg = new Message(); msg.mMailboxKey = mailboxId; try { while (true) { String atm = p.parseAtom(); // Not sure if this case is possible if (atm == null) break; if (atm.equalsIgnoreCase("UID")) { uid = p.parseInteger(); //userLog("UID=" + uid); } else if (atm.equalsIgnoreCase("ENVELOPE")) { String envelope = p.parseList(); Parser ep = new Parser(envelope); ep.skipWhite(); //date = parseDate(ep.parseString()); ep.parseString(); subject = ep.parseString(); sender = parseRecipients(ep, msg); } else if (atm.equalsIgnoreCase("FLAGS")) { flags = p.parseList().toLowerCase(); if (flags.indexOf("\\seen") >=0) read = true; if (flags.indexOf("\\flagged") >=0) flag = 1; } else if (atm.equalsIgnoreCase("BODYSTRUCTURE")) { msg.mSyncData = p.parseList(); } else if (atm.equalsIgnoreCase("INTERNALDATE")) { date = parseInternaldate(p.parseString()); } } } catch (Exception e) { // Parsing error here. We've got one known one from EON // in which BODYSTRUCTURE is ( "MIXED" (....) ) if (sender == null) sender = "Unknown sender"; if (subject == null) subject = "No subject"; e.printStackTrace(); } if (subject != null && subject.startsWith("=?")) subject = MimeUtility.decode(subject); msg.mSubject = subject; //msg.bodyId = 0; //msg.parts = parts.toString(); msg.mAccountKey = mAccountId; msg.mFlagLoaded = Message.FLAG_LOADED_UNLOADED; msg.mFlags = flag; if (read) msg.mFlagRead = true; msg.mTimeStamp = ((date != null) ? date : new Date()).getTime(); msg.mServerId = Long.toString(uid); // If we're not storing to the same mailbox (search), save away our mailbox name if (mailboxId != mMailboxId) { msg.mProtocolSearchInfo = mMailboxName; } return msg; } private Date parseInternaldate (String str) { if (str != null) { SimpleDateFormat f = INTERNALDATE_FORMAT; if (str.charAt(3) == ',') f = GMAIL_INTERNALDATE_FORMAT; try { return f.parse(str); } catch (ParseException e) { userLog("Unparseable date: " + str); } } return new Date(); } private long getIdForUid(int uid) { // TODO: Rename this MAILBOX_SERVER_ID_ARGS[1] = Integer.toString(uid); Cursor c = mResolver.query(Message.CONTENT_URI, Message.ID_COLUMN_PROJECTION, MessageColumns.MAILBOX_KEY + "=? AND " + SyncColumns.SERVER_ID + "=?", MAILBOX_SERVER_ID_ARGS, null); try { if (c != null && c.moveToFirst()) { return c.getLong(Message.ID_COLUMNS_ID_COLUMN); } } finally { if (c != null) { c.close(); } } return Message.NO_MESSAGE; } private void processDelete(int uid) { SERVER_DELETES.clear(); SERVER_DELETES.add(uid); processServerDeletes(SERVER_DELETES); } /** * Handle a single untagged line * TODO: Perhaps batch operations for multiple lines into a single transaction */ private boolean handleUntagged (String line) { line = line.toLowerCase(); Matcher m = IMAP_RESPONSE_PATTERN.matcher(line); boolean res = false; if (m.matches()) { // What kind of thing is this? String type = m.group(3); if (type.equals("fetch") || type.equals("expunge")) { // This is a flag change or an expunge. First, find the UID int uid = 0; // TODO Get rid of hack to avoid uid... int uidPos = line.indexOf("uid"); if (uidPos > 0) { Parser p = new Parser(line, uidPos + 3); uid = p.parseInteger(); } if (uid == 0) { // This will be very inefficient // Have to 1) break idle, 2) query the server for uid return false; } long id = getIdForUid(uid); if (id == Message.NO_MESSAGE) { // Nothing to do; log userLog("? No message found for uid " + uid); return true; } if (type.equals("fetch")) { if (line.indexOf("\\deleted") > 0) { processDelete(uid); } else { boolean read = line.indexOf("\\seen") > 0; boolean flagged = line.indexOf("\\flagged") > 0; // TODO: Reuse ContentValues values = new ContentValues(); values.put(MessageColumns.FLAG_READ, read); values.put(MessageColumns.FLAG_FAVORITE, flagged); mResolver.update(ContentUris.withAppendedId(Message.SYNCED_CONTENT_URI, id), values, null, null); } userLog("<<< FLAGS " + uid); } else { userLog("<<< EXPUNGE " + uid); processDelete(uid); } } else if (type.equals("exists")) { int num = Integer.parseInt(m.group(2)); if (mIsGmail && (num == mLastExists)) { userLog("Gmail: nothing new..."); return false; } else if (mIsGmail) mLastExists = num; res = true; userLog("<<< EXISTS tag; new SEARCH"); } } return res; } /** * Prepends the folder name with the given prefix and UTF-7 encodes it. */ private String encodeFolderName(String name) { // do NOT add the prefix to the special name "INBOX" if ("inbox".equalsIgnoreCase(name)) return name; // Prepend prefix if (mPrefix != null) { name = mPrefix + name; } // TODO bypass the conversion if name doesn't have special char. ByteBuffer bb = MODIFIED_UTF_7_CHARSET.encode(name); byte[] b = new byte[bb.limit()]; bb.get(b); return Utility.fromAscii(b); } /** * UTF-7 decodes the folder name and removes the given path prefix. */ static String decodeFolderName(String name, String prefix) { // TODO bypass the conversion if name doesn't have special char. String folder; folder = MODIFIED_UTF_7_CHARSET.decode(ByteBuffer.wrap(Utility.toAscii(name))).toString(); if ((prefix != null) && folder.startsWith(prefix)) { folder = folder.substring(prefix.length()); } return folder; } private Cursor getUpdatesCursor() { Cursor c = mResolver.query(Message.UPDATED_CONTENT_URI, UPDATE_DELETE_PROJECTION, MessageColumns.MAILBOX_KEY + '=' + mMailbox.mId, null, null); if (c == null || c.getCount() == 0) { c.close(); return null; } return c; } private static final String[] UPDATE_DELETE_PROJECTION = new String[] {MessageColumns.ID, SyncColumns.SERVER_ID, MessageColumns.MAILBOX_KEY, MessageColumns.FLAG_READ, MessageColumns.FLAG_FAVORITE}; private static final int UPDATE_DELETE_ID_COLUMN = 0; private static final int UPDATE_DELETE_SERVER_ID_COLUMN = 1; private static final int UPDATE_DELETE_MAILBOX_KEY_COLUMN = 2; private static final int UPDATE_DELETE_READ_COLUMN = 3; private static final int UPDATE_DELETE_FAVORITE_COLUMN = 4; private Cursor getDeletesCursor() { Cursor c = mResolver.query(Message.DELETED_CONTENT_URI, UPDATE_DELETE_PROJECTION, MessageColumns.MAILBOX_KEY + '=' + mMailbox.mId, null, null); if (c == null || c.getCount() == 0) { c.close(); return null; } return c; } private void handleLocalDeletes() throws IOException { Cursor c = getDeletesCursor(); if (c == null) return; mDeletes.clear(); mDeletedIds.clear(); try { while (c.moveToNext()) { long id = c.getLong(UPDATE_DELETE_ID_COLUMN); mDeletes.add(c.getInt(UPDATE_DELETE_SERVER_ID_COLUMN)); mDeletedIds.add(id); } sendUpdate(mDeletes, "+FLAGS (\\Deleted)"); String tag = writeCommand(mConnection.writer, "expunge"); readResponse(mConnection.reader, tag, "expunge"); // Delete the deletions now (we must go deeper!) ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); for (long id: mDeletedIds) { ops.add(ContentProviderOperation.newDelete( ContentUris.withAppendedId( Message.DELETED_CONTENT_URI, id)).build()); } applyBatch(ops); } finally { c.close(); } } private void handleLocalUpdates() throws IOException { Cursor updatesCursor = getUpdatesCursor(); if (updatesCursor == null) return; mUpdatedIds.clear(); mReadUpdates.clear(); mUnreadUpdates.clear(); mFlaggedUpdates.clear(); mUnflaggedUpdates.clear(); try { while (updatesCursor.moveToNext()) { long id = updatesCursor.getLong(UPDATE_DELETE_ID_COLUMN); // Keep going if there's no serverId int serverId = updatesCursor.getInt(UPDATE_DELETE_SERVER_ID_COLUMN); if (serverId == 0) { continue; } // Say we've handled this update mUpdatedIds.add(id); // We have the id of the changed item. But first, we have to find out its current // state, since the updated table saves the opriginal state Cursor currentCursor = mResolver.query( ContentUris.withAppendedId(Message.CONTENT_URI, id), UPDATE_DELETE_PROJECTION, null, null, null); try { // If this item no longer exists (shouldn't be possible), just move along if (!currentCursor.moveToFirst()) { continue; } boolean flagChange = false; boolean readChange = false; long mailboxId = currentCursor.getLong(UPDATE_DELETE_MAILBOX_KEY_COLUMN); // If the message is now in the trash folder, it has been deleted by the user if (mailboxId != updatesCursor.getLong(UPDATE_DELETE_MAILBOX_KEY_COLUMN)) { // The message has been moved to another mailbox Mailbox newMailbox = Mailbox.restoreMailboxWithId(mContext, mailboxId); if (newMailbox == null) { continue; } copyMessage(serverId, newMailbox); } // We can only send flag changes to the server in 12.0 or later int flag = currentCursor.getInt(UPDATE_DELETE_FAVORITE_COLUMN); if (flag != updatesCursor.getInt(UPDATE_DELETE_FAVORITE_COLUMN)) { flagChange = true; } int read = currentCursor.getInt(UPDATE_DELETE_READ_COLUMN); if (read != updatesCursor.getInt(UPDATE_DELETE_READ_COLUMN)) { readChange = true; } if (!flagChange && !readChange) { // In this case, we've got nothing to send to the server continue; } Integer update = serverId; if (readChange) { if (read == 1) { mReadUpdates.add(update); } else { mUnreadUpdates.add(update); } } if (flagChange) { if (flag == 1) { mFlaggedUpdates.add(update); } else { mUnflaggedUpdates.add(update); } } } finally { currentCursor.close(); } } } finally { updatesCursor.close(); } if (!mUpdatedIds.isEmpty()) { sendUpdate(mReadUpdates, "+FLAGS (\\Seen)"); sendUpdate(mUnreadUpdates, "-FLAGS (\\Seen)"); sendUpdate(mFlaggedUpdates, "+FLAGS (\\Flagged)"); sendUpdate(mUnflaggedUpdates, "-FLAGS (\\Flagged)"); // Delete the updates now ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); for (Long id: mUpdatedIds) { ops.add(ContentProviderOperation.newDelete( ContentUris.withAppendedId(Message.UPDATED_CONTENT_URI, id)).build()); } applyBatch(ops); } } private void sendUpdate(Stack<Integer> updates, String command) throws IOException { // First, generate the appropriate String while (!updates.isEmpty()) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < HEADER_BATCH_COUNT && !updates.empty(); i++) { Integer update = updates.pop(); if (i != 0) { sb.append(','); } sb.append(update); } String tag = writeCommand(mConnection.writer, "uid store " + sb.toString() + " " + command); if (!readResponse(mConnection.reader, tag, "STORE").equals(IMAP_OK)) { errorLog("Server flag update failed?"); return; } } } private void copyMessage(int serverId, Mailbox mailbox) throws IOException { String tag = writeCommand(mConnection.writer, "uid copy " + serverId + " \"" + encodeFolderName(mailbox.mServerId) + "\""); if (readResponse(mConnection.reader, tag, "COPY").equals(IMAP_OK)) { tag = writeCommand(mConnection.writer, "uid store " + serverId + " +FLAGS(\\Deleted)"); if (readResponse(mConnection.reader, tag, "STORE").equals(IMAP_OK)) { tag = writeCommand(mConnection.writer, "expunge"); readResponse(mConnection.reader, tag, "expunge"); } } else { errorLog("Server copy failed?"); } } private void saveNewMessages (ArrayList<Message> msgList) { // Get the ids of updated messages in this mailbox (usually there won't be any) Cursor c = getUpdatesCursor(); ArrayList<Integer> updatedIds = new ArrayList<Integer>(); boolean newUpdates = false; if (c != null) { try { if (c.moveToFirst()) { do { updatedIds.add(c.getInt(UPDATE_DELETE_SERVER_ID_COLUMN)); newUpdates = true; } while (c.moveToNext()); } } finally { c.close(); } } ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); for (Message msg: msgList) { // If the message is updated, make sure it's not deleted (we don't want to reload it) if (newUpdates && updatedIds.contains(msg.mServerId)) { Message currentMsg = Message.restoreMessageWithId(mContext, msg.mId); if (currentMsg.mMailboxKey == mTrashMailboxId) { userLog("PHEW! Didn't save deleted message with uid: " + msg.mServerId); continue; } } // Add the CPO's for this message msg.addSaveOps(ops); } // Commit these messages applyBatch(ops); } private String readTextPart (ImapInputStream in, String tag, Attachment att, boolean lastPart) throws IOException { String res = in.readLine(); int bstart = res.indexOf("body["); if (bstart < 0) bstart = res.indexOf("BODY["); if (bstart < 0) return ""; int bend = res.indexOf(']', bstart); if (bend < 0) return ""; //String charset = getCharset(thisLoc); boolean qp = att.mEncoding.equalsIgnoreCase("quoted-printable"); int br = res.indexOf('{'); if (br > 0) { Parser p = new Parser(res, br + 1); int length = p.parseInteger(); int len = length; byte[] buf = new byte[len]; int offs = 0; while (len > 0) { int rd = in.read(buf, offs, len); offs += rd; len -= rd; } if (qp) { length = QuotedPrintable.decode(buf, length); } if (lastPart) { String line = in.readLine(); if (!line.endsWith(")")) { userLog("Bad text part?"); throw new IOException(); } line = in.readLine(); if (!line.startsWith(tag)) { userLog("Bad text part?"); throw new IOException(); } } return new String(buf, 0, length, Charset.forName("UTF8")); } else { return ""; } } private BodyThread mBodyThread; private Connection mConnection; private void parseBodystructure (Message msg, Parser p, String level, int cnt, ArrayList<Attachment> viewables, ArrayList<Attachment> attachments) { if (p.peekChar() == '(') { // Multipart variant while (true) { String ps = p.parseList(); if (ps == null) break; parseBodystructure(msg, new Parser(ps), level + ((level.length() > 0) ? '.' : "") + cnt, 1, viewables, attachments); cnt++; } // Multipart type (MIXED/ALTERNATIVE/RELATED) String mp = p.parseString(); userLog("Multipart: " + mp); } else { boolean attachment = true; String fileName = ""; // Here's an actual part... // mime type String type = p.parseString().toLowerCase(); // mime subtype String sub = p.parseString().toLowerCase(); // parameter list or NIL String paramList = p.parseList(); if (paramList == null) p.parseAtom(); else { Parser pp = new Parser(paramList); String param; while ((param = pp.parseString()) != null) { String val = pp.parseString(); if (param.equalsIgnoreCase("name")) { fileName = val; } else if (param.equalsIgnoreCase("charset")) { // TODO: Do we need to handle this? } } } // contentId String contentId = p.parseString(); if (contentId != null) { // Must remove the angle-bracket pair contentId = contentId.substring(1, contentId.length() - 1); fileName = ""; } // contentName p.parseString(); // encoding String encoding = p.parseString().toLowerCase(); // length Integer length = p.parseInteger(); String lvl = level.length() > 0 ? level : String.valueOf(cnt); // body MD5 p.parseStringOrAtom(); // disposition paramList = p.parseList(); if (paramList != null) { //A parenthesized list, consisting of a disposition type //string, followed by a parenthesized list of disposition //attribute/value pairs as defined in [DISPOSITION]. Parser pp = new Parser(paramList); String param; while ((param = pp.parseString()) != null) { String val = pp.parseString(); if (param.equalsIgnoreCase("name") || param.equalsIgnoreCase("filename")) { fileName = val; } } } // Don't waste time with Microsoft foolishness if (!sub.equals("ms-tnef")) { Attachment att = new Attachment(); att.mLocation = lvl; att.mMimeType = type + "/" + sub; att.mSize = length; att.mFileName = fileName; att.mEncoding = encoding; att.mContentId = contentId; // TODO: charset? if ((!type.startsWith("text")) && attachment) { //msg.encoding |= Email.ENCODING_HAS_ATTACHMENTS; attachments.add(att); } else { viewables.add(att); } userLog("Part " + lvl + ": " + type + "/" + sub); } } } private void fetchMessageData(Connection conn, Cursor c) throws IOException { for (;;) { try { if (c == null) { c = mResolver.query(Message.CONTENT_URI, Message.CONTENT_PROJECTION, MessageColumns.FLAG_LOADED + "=" + Message.FLAG_LOADED_UNLOADED, null, MessageColumns.TIMESTAMP + " desc"); if (c == null || c.getCount() == 0) { return; } } while (c.moveToNext()) { // Parse the message's bodystructure Message msg = new Message(); msg.restore(c); ArrayList<Attachment> viewables = new ArrayList<Attachment>(); ArrayList<Attachment> attachments = new ArrayList<Attachment>(); parseBodystructure(msg, new Parser(msg.mSyncData), "", 1, viewables, attachments); ContentValues values = new ContentValues(); values.put(MessageColumns.FLAG_LOADED, Message.FLAG_LOADED_COMPLETE); // Save the attachments... for (Attachment att: attachments) { att.mAccountKey = mAccountId; att.mMessageKey = msg.mId; att.save(mContext); } // Whether or not we have attachments values.put(MessageColumns.FLAG_ATTACHMENT, !attachments.isEmpty()); // Get the viewables Attachment textViewable = null; for (Attachment viewable: viewables) { String mimeType = viewable.mMimeType; if ("text/html".equalsIgnoreCase(mimeType)) { textViewable = viewable; } else if ("text/plain".equalsIgnoreCase(mimeType) && textViewable == null) { textViewable = viewable; } } if (textViewable != null) { // For now, just get single viewable String tag = writeCommand(conn.writer, "uid fetch " + msg.mServerId + " body.peek[" + textViewable.mLocation + "]<0.200000>"); String text = readTextPart(conn.reader, tag, textViewable, true); userLog("Viewable " + textViewable.mMimeType + ", len = " + text.length()); // Save it away Body body = new Body(); if (textViewable.mMimeType.equalsIgnoreCase("text/html")) { body.mHtmlContent = text; } else { body.mTextContent = text; } body.mMessageKey = msg.mId; body.save(mContext); values.put(MessageColumns.SNIPPET, TextUtilities.makeSnippetFromHtmlText(text)); } else { userLog("No viewable?"); values.putNull(MessageColumns.SNIPPET); } mResolver.update(ContentUris.withAppendedId( Message.CONTENT_URI, msg.mId), values, null, null); } } finally { if (c != null) { c.close(); c = null; } } } } /** * Class that loads message bodies in its own thread */ private class BodyThread extends Thread { final Connection mConnection; final Cursor mCursor; BodyThread(Connection conn, Cursor cursor) { super(); mConnection = conn; mCursor = cursor; } public void run() { try { fetchMessageData(mConnection, mCursor); } catch (IOException e) { userLog("IOException in body thread; closing..."); } finally { mConnection.close(); mBodyThread = null; } } void close() { mConnection.close(); } } private void fetchMessageData () throws IOException { // If we're already loading messages on another thread, there's nothing to do if (mBodyThread != null) { return; } HostAuth hostAuth = HostAuth.restoreHostAuthWithId(mContext, mAccount.mHostAuthKeyRecv); if (hostAuth == null) return; // Find messages to load, if any final Cursor unloaded = mResolver.query(Message.CONTENT_URI, Message.CONTENT_PROJECTION, MessageColumns.FLAG_LOADED + "=" + Message.FLAG_LOADED_UNLOADED, null, MessageColumns.TIMESTAMP + " desc"); int cnt = unloaded.getCount(); // If there aren't any, we're done if (cnt > 0) { userLog("Found " + unloaded.getCount() + " messages requiring fetch"); // If we have more than one, try a second thread // Some servers may not allow this, so we fall back to loading text on the main thread if (cnt > 1) { final Connection conn = connectAndLogin(hostAuth, "body"); if (conn.status == EXIT_DONE) { mBodyThread = new BodyThread(conn, unloaded); mBodyThread.start(); userLog("***** Starting mBodyThread " + mBodyThread.getId()); } else { fetchMessageData(mConnection, unloaded); } } else { fetchMessageData(mConnection, unloaded); } } } void readFolderList () throws IOException { String tag = writeCommand(mWriter, "list \"\" *"); String line; char dchar = '/'; userLog("Loading folder list..."); ArrayList<String> parentList = new ArrayList<String>(); ArrayList<Mailbox> mailboxList = new ArrayList<Mailbox>(); while (true) { line = mReader.readLine(); userLog(line); if (line.startsWith(tag)) { // Done reading folder list break; } else { Parser p = new Parser(line, 2); String cmd = p.parseAtom(); if (cmd.equalsIgnoreCase("list")) { @SuppressWarnings("unused") String props = p.parseListOrNil(); String delim = p.parseString(); if (delim == null) delim = "~"; if (delim.length() == 1) dchar = delim.charAt(0); String serverId = p.parseStringOrAtom(); int lastDelim = serverId.lastIndexOf(delim); String displayName; String parentName; if (lastDelim > 0) { displayName = serverId.substring(lastDelim + 1); parentName = serverId.substring(0, lastDelim); } else { displayName = serverId; parentName = null; } Mailbox m = new Mailbox(); - m.mDisplayName = displayName; + m.mDisplayName = decodeFolderName(displayName, null); m.mAccountKey = mAccountId; - m.mServerId = serverId; + m.mServerId = decodeFolderName(serverId, null); if (parentName != null && !parentList.contains(parentName)) { parentList.add(parentName); } m.mFlagVisible = true; m.mParentServerId = parentName; m.mDelimiter = dchar; m.mSyncInterval = Mailbox.CHECK_INTERVAL_NEVER; mailboxList.add(m); } else { // WTF } } } // TODO: Use narrower projection Cursor c = mResolver.query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION, Mailbox.ACCOUNT_KEY + "=?", new String[] {Long.toString(mAccountId)}, MailboxColumns.SERVER_ID + " asc"); if (c == null) return; int cnt = c.getCount(); String[] serverIds = new String[cnt]; long[] uidvals = new long[cnt]; long[] ids = new long[cnt]; int i = 0; try { if (c.moveToFirst()) { // Get arrays of information about existing mailboxes in account do { serverIds[i] = c.getString(Mailbox.CONTENT_SERVER_ID_COLUMN); uidvals[i] = c.getLong(Mailbox.CONTENT_SYNC_KEY_COLUMN); ids[i] = c.getLong(Mailbox.CONTENT_ID_COLUMN); i++; } while (c.moveToNext()); } } finally { c.close(); } ArrayList<Mailbox> addList = new ArrayList<Mailbox>(); for (Mailbox m: mailboxList) { int loc = Arrays.binarySearch(serverIds, m.mServerId); if (loc >= 0) { // It exists if (uidvals[loc] == 0) { // Good enough; a match that we've never visited! // Mark this as touched (-1)... uidvals[loc] = -1; } else { // Ok, now we need to see if this is the SAME mailbox... // For now, assume it is; move on // TODO: There's a problem if you've 1) visited this box and 2) another box now // has its name, but how likely is that?? uidvals[loc] = -1; } } else { // We don't know about this mailbox, so we'll add it... // BUT must see if it's a rename of one we've visited! addList.add(m); } } // TODO: Flush this list every N (100?) in case there are zillions ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); try { for (i = 0; i < cnt; i++) { String name = serverIds[i]; long uidval = uidvals[i]; // -1 means matched; ignore // 0 means unmatched and never before seen // > 0 means unmatched and HAS been seen. must find mWriter why // TODO: Get rid of "Outbox" if (uidval == 0 && !name.equals("Outbox") && !name.equalsIgnoreCase(INBOX_SERVER_NAME)) { // Ok, here's one we've never visited and it's not in the new list ops.add(ContentProviderOperation.newDelete(ContentUris.withAppendedId( Mailbox.CONTENT_URI, ids[i])).build()); userLog("Deleting unseen mailbox; no match: " + name); } else if (uidval > 0 && !name.equalsIgnoreCase(INBOX_SERVER_NAME)) { boolean found = false; for (Mailbox m : addList) { tag = writeCommand(mWriter, "status \"" + m.mServerId + "\" (UIDVALIDITY)"); if (readResponse(mReader, tag, "STATUS").equals(IMAP_OK)) { String str = mImapResponse.get(0).toLowerCase(); int idx = str.indexOf("uidvalidity"); long num = readLong(str, idx + 12); if (uidval == num) { // try { // // This is a renamed mailbox... // c = Mailbox.getCursorWhere(mDatabase, "account=" + mAccount.id + " and serverName=?", name); // if (c != null && c.moveToFirst()) { // Mailbox existing = Mailbox.restoreFromCursor(c); // userLog("Renaming existing mailbox: " + existing.mServerId + " to: " + m.mServerId); // existing.mDisplayName = m.mDisplayName; // existing.mServerId = m.mServerId; // m.mHierarchicalName = m.mServerId; // existing.mParentServerId = m.mParentServerId; // existing.mFlags = m.mFlags; // existing.save(mDatabase); // // Mark this so that we don't save it below // m.mServerId = null; // } // } finally { // if (c != null) { // c.close(); // } // } found = true; break; } } } if (!found) { // There's no current mailbox with this uidval, so delete. ops.add(ContentProviderOperation.newDelete(ContentUris.withAppendedId( Mailbox.CONTENT_URI, ids[i])).build()); userLog("Deleting uidval mailbox; no match: " + name); } } } for (Mailbox m : addList) { String serverId = m.mServerId; if (serverId == null) continue; if (!serverId.equalsIgnoreCase(INBOX_SERVER_NAME) && !serverId.equalsIgnoreCase("Outbox")) { m.mHierarchicalName = m.mServerId; //*** For now, use Mail. We need a way to select the others... m.mType = Mailbox.TYPE_MAIL; ops.add(ContentProviderOperation.newInsert( Mailbox.CONTENT_URI).withValues(m.toContentValues()).build()); userLog("Adding new mailbox: " + m.mServerId); } } applyBatch(ops); // Fixup parent stuff, flags... MailboxUtilities.fixupUninitializedParentKeys(mContext, Mailbox.ACCOUNT_KEY + "=" + mAccountId); } finally { SyncManager.kick("folder list"); } } public int getDepth (String name, char delim) { int depth = 0; int last = -1; while (true) { last = name.indexOf(delim, last + 1); if (last < 0) return depth; depth++; } } private static final int BATCH_SIZE = 100; private void applyBatch(ArrayList<ContentProviderOperation> ops) { try { int len = ops.size(); if (len == 0) { return; } else if (len < BATCH_SIZE) { mResolver.applyBatch(EmailContent.AUTHORITY, ops); } else { ArrayList<ContentProviderOperation> batchOps = new ArrayList<ContentProviderOperation>(); for (int i = 0; i < len; i+=BATCH_SIZE) { batchOps.clear(); for (int j = 0; (j < BATCH_SIZE) && ((i+j) < len); j++) { batchOps.add(ops.get(i+j)); } mResolver.applyBatch(EmailContent.AUTHORITY, batchOps); } } } catch (RemoteException e) { // Nothing to be done } catch (OperationApplicationException e) { // These operations are legal; this can't really happen } } private void processServerDeletes(ArrayList<Integer> deleteList) { int cnt = deleteList.size(); if (cnt > 0) { ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); for (int i = 0; i < cnt; i++) { MAILBOX_SERVER_ID_ARGS[1] = Long.toString(deleteList.get(i)); Builder b = ContentProviderOperation.newDelete( Message.SELECTED_MESSAGE_CONTENT_URI); b.withSelection(MessageColumns.MAILBOX_KEY + "=? AND " + SyncColumns.SERVER_ID + "=?", MAILBOX_SERVER_ID_ARGS); ops.add(b.build()); } applyBatch(ops); } } private void processIntegers(ArrayList<Integer> deleteList, ContentValues values) { int cnt = deleteList.size(); if (cnt > 0) { ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); for (int i = 0; i < cnt; i++) { MAILBOX_SERVER_ID_ARGS[1] = Long.toString(deleteList.get(i)); Builder b = ContentProviderOperation.newUpdate( Message.SELECTED_MESSAGE_CONTENT_URI); b.withSelection(MessageColumns.MAILBOX_KEY + "=? AND " + SyncColumns.SERVER_ID + "=?", MAILBOX_SERVER_ID_ARGS); b.withValues(values); ops.add(b.build()); } applyBatch(ops); } } private static class Reconciled { ArrayList<Integer> insert; ArrayList<Integer> delete; Reconciled (ArrayList<Integer> ins, ArrayList<Integer> del) { insert = ins; delete = del; } } // Arrays must be sorted beforehand public Reconciled reconcile (String name, int[] deviceList, int[] serverList) { ArrayList<Integer> loadList = new ArrayList<Integer>(); ArrayList<Integer> deleteList = new ArrayList<Integer>(); int soff = 0; int doff = 0; int scnt = serverList.length; int dcnt = deviceList.length; while (scnt > 0 || dcnt > 0) { if (scnt == 0) { for (; dcnt > 0; dcnt--) deleteList.add(deviceList[doff++]); break; } else if (dcnt == 0) { for (; scnt > 0; scnt--) loadList.add(serverList[soff++]); break; } int s = serverList[soff++]; int d = deviceList[doff++]; scnt--; dcnt--; if (s == d) { continue; } else if (s > d) { deleteList.add(d); scnt++; soff--; } else if (d > s) { loadList.add(s); dcnt++; doff--; } } userLog("Reconciler " + name + "-> Insert: " + loadList.size() + ", Delete: " + deleteList.size()); return new Reconciled(loadList, deleteList); } private static final String[] UID_PROJECTION = new String[] {SyncColumns.SERVER_ID}; public int[] getUidList (String andClause) { int offs = 0; String ac = MessageColumns.MAILBOX_KEY + "=?"; if (andClause != null) { ac = ac + andClause; } Cursor c = mResolver.query(Message.CONTENT_URI, UID_PROJECTION, ac, new String[] {Long.toString(mMailboxId)}, SyncColumns.SERVER_ID); if (c != null) { try { int[] uids = new int[c.getCount()]; if (c.moveToFirst()) { do { uids[offs++] = c.getInt(0); } while (c.moveToNext()); return uids; } } finally { c.close(); } } return new int[0]; } public int[] getUnreadUidList () { return getUidList(" and " + Message.FLAG_READ + "=0"); } public int[] getFlaggedUidList () { return getUidList(" and " + Message.FLAG_FAVORITE + "!=0"); } private void reconcileState(int[] deviceList, String since, String flag, String search, String column, boolean sense) throws IOException { int[] serverList; Parser p; String msgs; String tag = writeCommand(mWriter, "uid search undeleted " + search + " since " + since); if (readResponse(mReader, tag, "SEARCH").equals(IMAP_OK)) { if (mImapResponse.isEmpty()) { serverList = new int[0]; } else { msgs = mImapResponse.get(0); p = new Parser(msgs, 8); serverList = p.gatherInts(); Arrays.sort(serverList); } Reconciled r = reconcile(flag, deviceList, serverList); ContentValues values = new ContentValues(); values.put(column, sense); processIntegers(r.delete, values); values.put(column, !sense); processIntegers(r.insert, values); } } private ArrayList<String> getTokens(String str) { ArrayList<String> tokens = new ArrayList<String>(); Parser p = new Parser(str); while(true) { String capa = p.parseAtom(); if (capa == null) { break; } tokens.add(capa); } return tokens; } /** * Convenience class to hold state for a single IMAP connection */ public static class Connection { Socket socket; int status; String reason; ImapInputStream reader; BufferedWriter writer; void close() { try { socket.close(); } catch (IOException e) { // It's all good } } } private String mUserAgent; private Connection connectAndLogin(HostAuth hostAuth, String name) { return connectAndLogin(hostAuth, name, null); } private Connection connectAndLogin(HostAuth hostAuth, String name, Socket tlsSocket) { Connection conn = new Connection(); Socket socket; try { if (tlsSocket != null) { // Start secure connection on top of existing one boolean trust = (hostAuth.mFlags & HostAuth.FLAG_TRUST_ALL) != 0; socket = SSLUtils.getSSLSocketFactory(mContext, hostAuth, trust) .createSocket(tlsSocket, hostAuth.mAddress, hostAuth.mPort, true); } else { socket = getSocket(hostAuth); } socket.setSoTimeout(SOCKET_TIMEOUT); userLog(">>> IMAP CONNECTION SUCCESSFUL: " + name + ((socket != null) ? " [STARTTLS]" : "")); ImapInputStream reader = new ImapInputStream(socket.getInputStream()); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter( socket.getOutputStream())); // Get welcome string if (tlsSocket == null) { reader.readLine(); } String tag = writeCommand(writer, "CAPABILITY"); if (readResponse(reader, tag, "CAPABILITY").equals(IMAP_OK)) { // If CAPABILITY if (!mImapResponse.isEmpty()) { String capa = mImapResponse.get(0).toLowerCase(); ArrayList<String> tokens = getTokens(capa); if (tokens.contains("starttls") && tlsSocket == null && ((hostAuth.mFlags & HostAuth.FLAG_SSL) == 0)) { userLog("[Use STARTTLS]"); tag = writeCommand(writer, "STARTTLS"); readResponse(reader, tag, "STARTTLS"); return connectAndLogin(hostAuth, name, socket); } if (tokens.contains("id")) { String hostAddress = hostAuth.mAddress; // Never send ID to *.secureserver.net // Hackish, yes, but we've been doing this for years... :-( if (!hostAddress.toLowerCase().endsWith(".secureserver.net")) { // Assign user-agent string (for RFC2971 ID command) if (mUserAgent == null) { mUserAgent = ImapId.getImapId(mContext, hostAuth.mLogin, hostAddress, null); } tag = writeCommand(writer, "ID (" + mUserAgent + ")"); // We learn nothing useful from the response readResponse(reader, tag); } } } } tag = writeCommand(writer, "login " + hostAuth.mLogin + ' ' + hostAuth.mPassword); if (!IMAP_OK.equals(readResponse(reader, tag))) { if (IMAP_NO.equals(mImapResult)) { int alertPos = mImapErrorLine.indexOf("[ALERT]"); if (alertPos > 0) { conn.reason = mImapErrorLine.substring(alertPos + 7); } } conn.status = EXIT_LOGIN_FAILURE; } else { conn.socket = socket; conn.reader = reader; conn.writer = writer; conn.status = EXIT_DONE; userLog(">>> LOGGED IN: " + name); if (mMailboxName != null) { tag = writeCommand(conn.writer, "select \"" + encodeFolderName(mMailboxName) + '\"'); if (!readResponse(conn.reader, tag).equals(IMAP_OK)) { // Select failed userLog("Select failed?"); conn.status = EXIT_EXCEPTION; } else { userLog(">>> SELECTED"); } } } } catch (CertificateValidationException e) { conn.status = EXIT_LOGIN_FAILURE; } catch (IOException e) { conn.status = EXIT_IO_ERROR; } return conn; } private void setMailboxSyncStatus(long id, int status) { ContentValues values = new ContentValues(); values.put(Mailbox.UI_SYNC_STATUS, status); // Make sure we're always showing a "success" value. A failure wouldn't get set here, but // rather via SyncService.done() values.put(Mailbox.UI_LAST_SYNC_RESULT, Mailbox.LAST_SYNC_RESULT_SUCCESS); mResolver.update(ContentUris.withAppendedId(Mailbox.CONTENT_URI, id), values, null, null); } /** * Reset the sync interval for this mailbox (account if it's Inbox) */ private void resetSyncInterval(int minutes) { ContentValues values = new ContentValues(); Uri uri; if (mMailbox.mType == Mailbox.TYPE_INBOX) { values.put(AccountColumns.SYNC_INTERVAL, minutes); uri = ContentUris.withAppendedId(Account.CONTENT_URI, mAccountId); } else { values.put(MailboxColumns.SYNC_INTERVAL, minutes); uri = ContentUris.withAppendedId(Mailbox.CONTENT_URI, mMailboxId); } // Reset this so that we won't loop mMailbox.mSyncInterval = minutes; // Update the mailbox/account with new sync interval mResolver.update(uri, values, null, null); } private void idle() throws IOException { mIsIdle = true; mThread.setName(mMailboxName + ":IDLE[" + mAccount.mDisplayName + "]"); userLog("Entering idle..."); String tag = writeCommand(mWriter, "idle"); try { while (true) { String resp = mReader.readLine(); if (resp.startsWith("+")) break; // Remember to handle untagged responses here (sigh, and elsewhere) if (resp.startsWith("* ")) handleUntagged(resp); else { userLog("Error in IDLE response: " + resp); if (resp.contains(IMAP_BAD)) { // Fatal error (server doesn't support this command) userLog("IDLE not supported; falling back to scheduled sync"); resetSyncInterval(IDLE_FALLBACK_SYNC_INTERVAL); } return; } } // Server has accepted IDLE long idleStartTime = System.currentTimeMillis(); // Let the socket time out a minute after we expect to terminate it ourselves mSocket.setSoTimeout(IDLE_ASLEEP_MILLIS + (1*MINS)); // Say we're no longer syncing (turn off indeterminate progress in the UI) setMailboxSyncStatus(mMailboxId, UIProvider.SyncStatus.NO_SYNC); // Set an alarm for one minute before our timeout our expected IDLE time Imap2SyncManager.runAsleep(mMailboxId, IDLE_ASLEEP_MILLIS); while (true) { String line = null; try { line = mReader.readLine(); userLog(line); } catch (SocketTimeoutException e) { userLog("Socket timeout"); } finally { Imap2SyncManager.runAwake(mMailboxId); // Say we're syncing again setMailboxSyncStatus(mMailboxId, UIProvider.SyncStatus.BACKGROUND_SYNC); } if (line == null || line.startsWith("* ")) { boolean finish = (line == null) ? true : handleUntagged(line); if (!finish) { long timeSinceIdle = System.currentTimeMillis() - idleStartTime; // If we're nearing the end of IDLE time, let's just reset the IDLE while // we've got the processor awake if (timeSinceIdle > IDLE_ASLEEP_MILLIS - (2*MINS)) { userLog("Time to reset IDLE..."); finish = true; } } if (finish) { mWriter.write("DONE\r\n"); mWriter.flush(); } } else if (line.startsWith(tag)) { Parser p = new Parser(line, tag.length() - 1); mImapResult = p.parseAtom(); mIsIdle = false; break; } } } finally { // We might have left IDLE due to an exception if (mSocket != null) { // Reset the standard timeout mSocket.setSoTimeout(SOCKET_TIMEOUT); } mIsIdle = false; mThread.setName(mMailboxName + "[" + mAccount.mDisplayName + "]"); } } private void doUpload(long messageId, String mailboxServerId) throws IOException, MessagingException { ContentValues values = new ContentValues(); CountingOutputStream out = new CountingOutputStream(); EOLConvertingOutputStream eolOut = new EOLConvertingOutputStream(out); Rfc822Output.writeTo(mContext, messageId, eolOut, false /* do not use smart reply */, false /* do not send BCC */); eolOut.flush(); long len = out.getCount(); try { String tag = writeCommand(mWriter, "append \"" + encodeFolderName(mailboxServerId) + "\" (\\seen) {" + len + '}'); String line = mReader.readLine(); if (line.startsWith("+")) { userLog("append response: " + line); eolOut = new EOLConvertingOutputStream(mSocket.getOutputStream()); Rfc822Output.writeTo(mContext, messageId, eolOut, false /* do not use smart reply */, false /* do not send BCC */); eolOut.flush(); mWriter.write("\r\n"); mWriter.flush(); if (readResponse(mConnection.reader, tag).equals(IMAP_OK)) { int serverId = 0; String lc = mImapSuccessLine.toLowerCase(); int appendUid = lc.indexOf("appenduid"); if (appendUid > 0) { Parser p = new Parser(lc, appendUid + 11); // UIDVALIDITY (we don't need it) p.parseInteger(); serverId = p.parseInteger(); } values.put(SyncColumns.SERVER_ID, serverId); mResolver.update(ContentUris.withAppendedId(Message.CONTENT_URI, messageId), values, null, null); } else { userLog("Append failed: " + mImapErrorLine); } } else { userLog("Append failed: " + line); } } catch (Exception e) { e.printStackTrace(); } } private void processUploads() { Mailbox sentMailbox = Mailbox.restoreMailboxOfType(mContext, mAccountId, Mailbox.TYPE_SENT); if (sentMailbox == null) { // Nothing to do this time around; we'll check each time through the sync loop return; } Cursor c = mResolver.query(Message.CONTENT_URI, Message.ID_COLUMN_PROJECTION, MessageColumns.MAILBOX_KEY + "=? AND " + SyncColumns.SERVER_ID + " is null", new String[] {Long.toString(sentMailbox.mId)}, null); if (c != null) { String sentMailboxServerId = sentMailbox.mServerId; try { // Upload these messages while (c.moveToNext()) { try { doUpload(c.getLong(Message.ID_COLUMNS_ID_COLUMN), sentMailboxServerId); } catch (IOException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } } } finally { c.close(); } } } private int[] getServerIds(String since) throws IOException { String tag = writeCommand(mWriter, "uid search undeleted since " + since); if (!readResponse(mReader, tag, "SEARCH").equals(IMAP_OK)) { userLog("$$$ WHOA! Search failed? "); return null; } userLog(">>> SEARCH RESULT"); String msgs; Parser p; if (mImapResponse.isEmpty()) { return new int[0]; } else { msgs = mImapResponse.get(0); // Length of "* search" p = new Parser(msgs, 8); return p.gatherInts(); } } static private final int[] AUTO_WINDOW_VALUES = new int[] { SyncWindow.SYNC_WINDOW_ALL, SyncWindow.SYNC_WINDOW_1_MONTH, SyncWindow.SYNC_WINDOW_2_WEEKS, SyncWindow.SYNC_WINDOW_1_WEEK, SyncWindow.SYNC_WINDOW_3_DAYS}; /** * Determine a sync window for this mailbox by trying different possibilities from among the * allowed values (in AUTO_WINDOW_VALUES). We start testing with "all" unless there are more * than AUTOMATIC_SYNC_WINDOW_LARGE_MAILBOX messages (we really don't want to load that many); * otherwise, we start with one month. We'll pick any value that has fewer than * AUTOMATIC_SYNC_WINDOW_MAX_MESSAGES messages (arbitrary, but reasonable) * @return a reasonable sync window for this mailbox * @throws IOException */ private int getAutoSyncWindow() throws IOException { int i = (mLastExists > AUTOMATIC_SYNC_WINDOW_LARGE_MAILBOX) ? 1 : 0; for (; i < AUTO_WINDOW_VALUES.length; i++) { int window = AUTO_WINDOW_VALUES[i]; long days = SyncWindow.toDays(window); Date date = new Date(System.currentTimeMillis() - (days*DAYS)); String since = IMAP_DATE_FORMAT.format(date); int msgCount = getServerIds(since).length; if (msgCount < AUTOMATIC_SYNC_WINDOW_MAX_MESSAGES) { userLog("getAutoSyncWindow returns " + days + " days."); return window; } } userLog("getAutoSyncWindow returns 1 day."); return SyncWindow.SYNC_WINDOW_1_DAY; } /** * Process our list of requested attachment loads * @throws IOException */ private void processRequests() throws IOException { while (!mRequestQueue.isEmpty()) { Request req = mRequestQueue.peek(); // Our two request types are PartRequest (loading attachment) and // MeetingResponseRequest (respond to a meeting request) if (req instanceof PartRequest) { TrafficStats.setThreadStatsTag( TrafficFlags.getAttachmentFlags(mContext, mAccount)); new AttachmentLoader(this, (PartRequest)req).loadAttachment(mConnection); TrafficStats.setThreadStatsTag( TrafficFlags.getSyncFlags(mContext, mAccount)); } // If there's an exception handling the request, we'll throw it // Otherwise, we remove the request mRequestQueue.remove(); } } private void loadMessages(ArrayList<Integer> loadList, long mailboxId) throws IOException { int idx= 1; boolean loadedSome = false; int cnt = loadList.size(); while (idx <= cnt) { ArrayList<Message> tmsgList = new ArrayList<Message> (); int tcnt = 0; StringBuilder tsb = new StringBuilder("uid fetch "); for (tcnt = 0; tcnt < HEADER_BATCH_COUNT && idx <= cnt; tcnt++, idx++) { // Load most recent first if (tcnt > 0) tsb.append(','); tsb.append(loadList.get(cnt - idx)); } tsb.append(" (uid internaldate flags envelope bodystructure)"); String tag = writeCommand(mWriter, tsb.toString()); if (readResponse(mReader, tag, "FETCH").equals(IMAP_OK)) { // Create message and store for (int j = 0; j < tcnt; j++) { Message msg = createMessage(mImapResponse.get(j), mailboxId); tmsgList.add(msg); } saveNewMessages(tmsgList); } fetchMessageData(); loadedSome = true; } // TODO: Use loader to watch for changes on unloaded body cursor if (!loadedSome) { fetchMessageData(); } } private void sync () throws IOException { mThread = Thread.currentThread(); HostAuth hostAuth = HostAuth.restoreHostAuthWithId(mContext, mAccount.mHostAuthKeyRecv); if (hostAuth == null) return; Connection conn = connectAndLogin(hostAuth, "main"); if (conn.status != EXIT_DONE) { mExitStatus = conn.status; mExitReason = conn.reason; return; } setConnection(conn); // The account might have changed!! //*** Determine how to often to do this if (mMailboxName.equalsIgnoreCase("inbox")) { long startTime = System.currentTimeMillis(); readFolderList(); userLog("Folder list processed in " + (System.currentTimeMillis() - startTime) + "ms"); } while (!mStop) { try { while (!mStop) { mIsServiceRequestPending = false; // Now, handle various requests processRequests(); // We'll use 14 days as the "default" long days = 14; int lookback = mMailbox.mSyncLookback; if (mMailbox.mType == Mailbox.TYPE_INBOX) { lookback = mAccount.mSyncLookback; } if (lookback == SyncWindow.SYNC_WINDOW_AUTO) { if (mLastExists >= 0) { ContentValues values = new ContentValues(); lookback = getAutoSyncWindow(); Uri uri; if (mMailbox.mType == Mailbox.TYPE_INBOX) { values.put(AccountColumns.SYNC_LOOKBACK, lookback); uri = ContentUris.withAppendedId(Account.CONTENT_URI, mAccountId); } else { values.put(MailboxColumns.SYNC_LOOKBACK, lookback); uri = ContentUris.withAppendedId(Mailbox.CONTENT_URI, mMailboxId); } mResolver.update(uri, values, null, null); } } if (lookback != SyncWindow.SYNC_WINDOW_UNKNOWN) { days = SyncWindow.toDays(lookback); } Date date = new Date(System.currentTimeMillis() - (days*DAYS)); String since = IMAP_DATE_FORMAT.format(date); int[] serverList = getServerIds(since); if (serverList == null) { // Do backoff; hope it works next time. Should never happen mExitStatus = EXIT_IO_ERROR; return; } Arrays.sort(serverList); int[] deviceList = getUidList(null); Reconciled r = reconcile("MESSAGES", deviceList, serverList); ArrayList<Integer> loadList = r.insert; ArrayList<Integer> deleteList = r.delete; serverList = null; deviceList = null; // We load message headers in batches loadMessages(loadList, mMailboxId); // Reflect server deletions on device; do them all at once processServerDeletes(deleteList); handleLocalUpdates(); handleLocalDeletes(); reconcileState(getUnreadUidList(), since, "UNREAD", "unseen", MessageColumns.FLAG_READ, true); reconcileState(getFlaggedUidList(), since, "FLAGGED", "flagged", MessageColumns.FLAG_FAVORITE, false); processUploads(); // We're done if not pushing... if (mMailbox.mSyncInterval != Mailbox.CHECK_INTERVAL_PUSH) { mExitStatus = EXIT_DONE; return; } // If new requests have come in, process them if (mIsServiceRequestPending) continue; idle(); } } finally { if (mConnection != null) { try { // Try to logout readResponse(mReader, writeCommand(mWriter, "logout")); mConnection.close(); } catch (IOException e) { // We're leaving anyway } } } } } private void sendMail() { long sentMailboxId = Mailbox.findMailboxOfType(mContext, mAccountId, Mailbox.TYPE_SENT); if (sentMailboxId == Mailbox.NO_MAILBOX) { // The user must choose a sent mailbox mResolver.update( ContentUris.withAppendedId(EmailContent.PICK_SENT_FOLDER_URI, mAccountId), new ContentValues(), null, null); } Account account = Account.restoreAccountWithId(mContext, mAccountId); if (account == null) { return; } TrafficStats.setThreadStatsTag(TrafficFlags.getSmtpFlags(mContext, account)); // 1. Loop through all messages in the account's outbox long outboxId = Mailbox.findMailboxOfType(mContext, account.mId, Mailbox.TYPE_OUTBOX); if (outboxId == Mailbox.NO_MAILBOX) { return; } Cursor c = mResolver.query(Message.CONTENT_URI, Message.ID_COLUMN_PROJECTION, Message.MAILBOX_KEY + "=?", new String[] { Long.toString(outboxId) }, null); ContentValues values = new ContentValues(); values.put(MessageColumns.MAILBOX_KEY, sentMailboxId); try { // 2. exit early if (c.getCount() <= 0) { return; } SmtpSender sender = new SmtpSender(mContext, account, mUserLog); // 3. loop through the available messages and send them while (c.moveToNext()) { long messageId = -1; try { messageId = c.getLong(Message.ID_COLUMNS_ID_COLUMN); // Don't send messages with unloaded attachments if (Utility.hasUnloadedAttachments(mContext, messageId)) { userLog("Can't send #" + messageId + "; unloaded attachments"); continue; } sender.sendMessage(messageId); // Move to sent folder mResolver.update(ContentUris.withAppendedId(Message.CONTENT_URI, messageId), values, null, null); } catch (MessagingException me) { continue; } } } finally { c.close(); } } @Override public void run() { try { TAG = Thread.currentThread().getName(); // Check for Outbox (special "sync") and stopped if (mMailbox.mType == Mailbox.TYPE_OUTBOX) { sendMail(); mExitStatus = EXIT_DONE; return; } else if (mStop) { return; } if ((mMailbox == null) || (mAccount == null)) { return; } else { int trafficFlags = TrafficFlags.getSyncFlags(mContext, mAccount); TrafficStats.setThreadStatsTag(trafficFlags | TrafficFlags.DATA_EMAIL); // We loop because someone might have put a request in while we were syncing // and we've missed that opportunity... do { if (mRequestTime != 0) { userLog("Looping for user request..."); mRequestTime = 0; } if (mSyncReason >= Imap2SyncManager.SYNC_CALLBACK_START) { try { Imap2SyncManager.callback().syncMailboxStatus(mMailboxId, EmailServiceStatus.IN_PROGRESS, 0); } catch (RemoteException e1) { // Don't care if this fails } } sync(); } while (mRequestTime != 0); } } catch (IOException e) { String message = e.getMessage(); userLog("Caught IOException: ", (message == null) ? "No message" : message); mExitStatus = EXIT_IO_ERROR; } catch (Exception e) { userLog("Uncaught exception in Imap2SyncService", e); } finally { int status; Imap2SyncManager.done(this); if (!mStop) { userLog("Sync finished"); switch (mExitStatus) { case EXIT_IO_ERROR: status = EmailServiceStatus.CONNECTION_ERROR; break; case EXIT_DONE: status = EmailServiceStatus.SUCCESS; ContentValues cv = new ContentValues(); cv.put(Mailbox.SYNC_TIME, System.currentTimeMillis()); String s = "S" + mSyncReason + ':' + status + ':' + mChangeCount; cv.put(Mailbox.SYNC_STATUS, s); mContext.getContentResolver().update( ContentUris.withAppendedId(Mailbox.CONTENT_URI, mMailboxId), cv, null, null); break; case EXIT_LOGIN_FAILURE: status = EmailServiceStatus.LOGIN_FAILED; break; default: status = EmailServiceStatus.REMOTE_EXCEPTION; errorLog("Sync ended due to an exception."); break; } } else { userLog("Stopped sync finished."); status = EmailServiceStatus.SUCCESS; } // Send a callback (doesn't matter how the sync was started) try { // Unless the user specifically asked for a sync, we don't want to report // connection issues, as they are likely to be transient. In this case, we // simply report success, so that the progress indicator terminates without // putting up an error banner //*** if (mSyncReason != Imap2SyncManager.SYNC_UI_REQUEST && status == EmailServiceStatus.CONNECTION_ERROR) { status = EmailServiceStatus.SUCCESS; } Imap2SyncManager.callback().syncMailboxStatus(mMailboxId, status, 0); } catch (RemoteException e1) { // Don't care if this fails } // Make sure we close our body thread (if any) if (mBodyThread != null) { mBodyThread.close(); } // Make sure ExchangeService knows about this Imap2SyncManager.kick("sync finished"); } } private Socket getSocket(HostAuth hostAuth) throws CertificateValidationException, IOException { Socket socket; try { boolean ssl = (hostAuth.mFlags & HostAuth.FLAG_SSL) != 0; boolean trust = (hostAuth.mFlags & HostAuth.FLAG_TRUST_ALL) != 0; SocketAddress socketAddress = new InetSocketAddress(hostAuth.mAddress, hostAuth.mPort); if (ssl) { socket = SSLUtils.getSSLSocketFactory(mContext, hostAuth, trust).createSocket(); } else { socket = new Socket(); } socket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); // After the socket connects to an SSL server, confirm that the hostname is as expected if (ssl && !trust) { verifyHostname(socket, hostAuth.mAddress); } } catch (SSLException e) { errorLog(e.toString()); throw new CertificateValidationException(e.getMessage(), e); } return socket; } /** * Lightweight version of SSLCertificateSocketFactory.verifyHostname, which provides this * service but is not in the public API. * * Verify the hostname of the certificate used by the other end of a * connected socket. You MUST call this if you did not supply a hostname * to SSLCertificateSocketFactory.createSocket(). It is harmless to call this method * redundantly if the hostname has already been verified. * * <p>Wildcard certificates are allowed to verify any matching hostname, * so "foo.bar.example.com" is verified if the peer has a certificate * for "*.example.com". * * @param socket An SSL socket which has been connected to a server * @param hostname The expected hostname of the remote server * @throws IOException if something goes wrong handshaking with the server * @throws SSLPeerUnverifiedException if the server cannot prove its identity */ private void verifyHostname(Socket socket, String hostname) throws IOException { // The code at the start of OpenSSLSocketImpl.startHandshake() // ensures that the call is idempotent, so we can safely call it. SSLSocket ssl = (SSLSocket) socket; ssl.startHandshake(); SSLSession session = ssl.getSession(); if (session == null) { throw new SSLException("Cannot verify SSL socket without session"); } // TODO: Instead of reporting the name of the server we think we're connecting to, // we should be reporting the bad name in the certificate. Unfortunately this is buried // in the verifier code and is not available in the verifier API, and extracting the // CN & alts is beyond the scope of this patch. if (!HttpsURLConnection.getDefaultHostnameVerifier().verify(hostname, session)) { throw new SSLPeerUnverifiedException( "Certificate hostname not useable for server: " + hostname); } } /** * Cache search results by account; this allows for "load more" support without having to * redo the search (which can be quite slow). */ private static final HashMap<Long, Integer[]> sSearchResults = new HashMap<Long, Integer[]>(); @VisibleForTesting protected static boolean isAsciiString(String str) { int len = str.length(); for (int i = 0; i < len; i++) { char c = str.charAt(i); if (c >= 128) return false; } return true; } /** * Wrapper for a search result with possible exception (to be sent back to the UI) */ private static class SearchResult { Integer[] uids; Exception exception; SearchResult(Integer[] _uids, Exception _exception) { uids = _uids; exception = _exception; } } private SearchResult getSearchResults(SearchParams searchParams) { String filter = searchParams.mFilter; // All servers MUST accept US-ASCII, so we'll send this as the CHARSET unless we're really // dealing with a string that contains non-ascii characters String charset = "US-ASCII"; if (!isAsciiString(filter)) { charset = "UTF-8"; } List<String> commands = new ArrayList<String>(); // This is the length of the string in octets (bytes), formatted as a string literal {n} String octetLength = "{" + filter.getBytes().length + "}"; // Break the command up into pieces ending with the string literal length commands.add("UID SEARCH CHARSET " + charset + " OR FROM " + octetLength); commands.add(filter + " (OR TO " + octetLength); commands.add(filter + " (OR CC " + octetLength); commands.add(filter + " (OR SUBJECT " + octetLength); commands.add(filter + " BODY " + octetLength); commands.add(filter + ")))"); Exception exception = null; try { int len = commands.size(); String tag = null; for (int i = 0; i < len; i++) { String command = commands.get(i); if (i == 0) { mSocket.setSoTimeout(SEARCH_TIMEOUT); tag = writeCommand(mWriter, command); } else { writeContinuation(mWriter, command); } if (readResponse(mReader, tag, "SEARCH").equals(IMAP_OK)) { // Done String msgs = mImapResponse.get(0); Parser p = new Parser(msgs, 8); Integer[] serverList = p.gatherIntegers(); Arrays.sort(serverList, Collections.reverseOrder()); return new SearchResult(serverList, null); } else if (mImapResult.startsWith("+")){ continue; } else { errorLog("Server doesn't understand complex SEARCH?"); break; } } } catch (SocketTimeoutException e) { exception = e; errorLog("Search timed out"); } catch (IOException e) { exception = e; errorLog("Search IOException"); } return new SearchResult(new Integer[0], exception); } public int searchMailbox(final Context context, long accountId, SearchParams searchParams, final long destMailboxId) throws IOException { final Account account = Account.restoreAccountWithId(context, accountId); final Mailbox mailbox = Mailbox.restoreMailboxWithId(context, searchParams.mMailboxId); final Mailbox destMailbox = Mailbox.restoreMailboxWithId(context, destMailboxId); if (account == null || mailbox == null || destMailbox == null) { Log.d(Logging.LOG_TAG, "Attempted search for " + searchParams + " but account or mailbox information was missing"); return 0; } HostAuth hostAuth = HostAuth.restoreHostAuthWithId(context, account.mHostAuthKeyRecv); if (hostAuth == null) { } Connection conn = connectAndLogin(hostAuth, "search"); if (conn.status != EXIT_DONE) { mExitStatus = conn.status; return 0; } try { setConnection(conn); Integer[] sortedUids = null; if (searchParams.mOffset == 0) { SearchResult result = getSearchResults(searchParams); if (result.exception == null) { sortedUids = result.uids; sSearchResults.put(accountId, sortedUids); } else { throw new IOException(); } } else { sortedUids = sSearchResults.get(accountId); } final int numSearchResults = sortedUids.length; final int numToLoad = Math.min(numSearchResults - searchParams.mOffset, searchParams.mLimit); if (numToLoad <= 0) { return 0; } final ArrayList<Integer> loadList = new ArrayList<Integer>(); for (int i = searchParams.mOffset; i < numToLoad + searchParams.mOffset; i++) { loadList.add(sortedUids[i]); } try { loadMessages(loadList, destMailboxId); } catch (IOException e) { // TODO: How do we handle this? return 0; } return sortedUids.length; } finally { if (mSocket != null) { try { // Try to logout readResponse(mReader, writeCommand(mWriter, "logout")); mSocket.close(); } catch (IOException e) { // We're leaving anyway } } } } }
false
true
void readFolderList () throws IOException { String tag = writeCommand(mWriter, "list \"\" *"); String line; char dchar = '/'; userLog("Loading folder list..."); ArrayList<String> parentList = new ArrayList<String>(); ArrayList<Mailbox> mailboxList = new ArrayList<Mailbox>(); while (true) { line = mReader.readLine(); userLog(line); if (line.startsWith(tag)) { // Done reading folder list break; } else { Parser p = new Parser(line, 2); String cmd = p.parseAtom(); if (cmd.equalsIgnoreCase("list")) { @SuppressWarnings("unused") String props = p.parseListOrNil(); String delim = p.parseString(); if (delim == null) delim = "~"; if (delim.length() == 1) dchar = delim.charAt(0); String serverId = p.parseStringOrAtom(); int lastDelim = serverId.lastIndexOf(delim); String displayName; String parentName; if (lastDelim > 0) { displayName = serverId.substring(lastDelim + 1); parentName = serverId.substring(0, lastDelim); } else { displayName = serverId; parentName = null; } Mailbox m = new Mailbox(); m.mDisplayName = displayName; m.mAccountKey = mAccountId; m.mServerId = serverId; if (parentName != null && !parentList.contains(parentName)) { parentList.add(parentName); } m.mFlagVisible = true; m.mParentServerId = parentName; m.mDelimiter = dchar; m.mSyncInterval = Mailbox.CHECK_INTERVAL_NEVER; mailboxList.add(m); } else { // WTF } } } // TODO: Use narrower projection Cursor c = mResolver.query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION, Mailbox.ACCOUNT_KEY + "=?", new String[] {Long.toString(mAccountId)}, MailboxColumns.SERVER_ID + " asc"); if (c == null) return; int cnt = c.getCount(); String[] serverIds = new String[cnt]; long[] uidvals = new long[cnt]; long[] ids = new long[cnt]; int i = 0; try { if (c.moveToFirst()) { // Get arrays of information about existing mailboxes in account do { serverIds[i] = c.getString(Mailbox.CONTENT_SERVER_ID_COLUMN); uidvals[i] = c.getLong(Mailbox.CONTENT_SYNC_KEY_COLUMN); ids[i] = c.getLong(Mailbox.CONTENT_ID_COLUMN); i++; } while (c.moveToNext()); } } finally { c.close(); } ArrayList<Mailbox> addList = new ArrayList<Mailbox>(); for (Mailbox m: mailboxList) { int loc = Arrays.binarySearch(serverIds, m.mServerId); if (loc >= 0) { // It exists if (uidvals[loc] == 0) { // Good enough; a match that we've never visited! // Mark this as touched (-1)... uidvals[loc] = -1; } else { // Ok, now we need to see if this is the SAME mailbox... // For now, assume it is; move on // TODO: There's a problem if you've 1) visited this box and 2) another box now // has its name, but how likely is that?? uidvals[loc] = -1; } } else { // We don't know about this mailbox, so we'll add it... // BUT must see if it's a rename of one we've visited! addList.add(m); } } // TODO: Flush this list every N (100?) in case there are zillions ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); try { for (i = 0; i < cnt; i++) { String name = serverIds[i]; long uidval = uidvals[i]; // -1 means matched; ignore // 0 means unmatched and never before seen // > 0 means unmatched and HAS been seen. must find mWriter why // TODO: Get rid of "Outbox" if (uidval == 0 && !name.equals("Outbox") && !name.equalsIgnoreCase(INBOX_SERVER_NAME)) { // Ok, here's one we've never visited and it's not in the new list ops.add(ContentProviderOperation.newDelete(ContentUris.withAppendedId( Mailbox.CONTENT_URI, ids[i])).build()); userLog("Deleting unseen mailbox; no match: " + name); } else if (uidval > 0 && !name.equalsIgnoreCase(INBOX_SERVER_NAME)) { boolean found = false; for (Mailbox m : addList) { tag = writeCommand(mWriter, "status \"" + m.mServerId + "\" (UIDVALIDITY)"); if (readResponse(mReader, tag, "STATUS").equals(IMAP_OK)) { String str = mImapResponse.get(0).toLowerCase(); int idx = str.indexOf("uidvalidity"); long num = readLong(str, idx + 12); if (uidval == num) { // try { // // This is a renamed mailbox... // c = Mailbox.getCursorWhere(mDatabase, "account=" + mAccount.id + " and serverName=?", name); // if (c != null && c.moveToFirst()) { // Mailbox existing = Mailbox.restoreFromCursor(c); // userLog("Renaming existing mailbox: " + existing.mServerId + " to: " + m.mServerId); // existing.mDisplayName = m.mDisplayName; // existing.mServerId = m.mServerId; // m.mHierarchicalName = m.mServerId; // existing.mParentServerId = m.mParentServerId; // existing.mFlags = m.mFlags; // existing.save(mDatabase); // // Mark this so that we don't save it below // m.mServerId = null; // } // } finally { // if (c != null) { // c.close(); // } // } found = true; break; } } } if (!found) { // There's no current mailbox with this uidval, so delete. ops.add(ContentProviderOperation.newDelete(ContentUris.withAppendedId( Mailbox.CONTENT_URI, ids[i])).build()); userLog("Deleting uidval mailbox; no match: " + name); } } } for (Mailbox m : addList) { String serverId = m.mServerId; if (serverId == null) continue; if (!serverId.equalsIgnoreCase(INBOX_SERVER_NAME) && !serverId.equalsIgnoreCase("Outbox")) { m.mHierarchicalName = m.mServerId; //*** For now, use Mail. We need a way to select the others... m.mType = Mailbox.TYPE_MAIL; ops.add(ContentProviderOperation.newInsert( Mailbox.CONTENT_URI).withValues(m.toContentValues()).build()); userLog("Adding new mailbox: " + m.mServerId); } } applyBatch(ops); // Fixup parent stuff, flags... MailboxUtilities.fixupUninitializedParentKeys(mContext, Mailbox.ACCOUNT_KEY + "=" + mAccountId); } finally { SyncManager.kick("folder list"); } }
void readFolderList () throws IOException { String tag = writeCommand(mWriter, "list \"\" *"); String line; char dchar = '/'; userLog("Loading folder list..."); ArrayList<String> parentList = new ArrayList<String>(); ArrayList<Mailbox> mailboxList = new ArrayList<Mailbox>(); while (true) { line = mReader.readLine(); userLog(line); if (line.startsWith(tag)) { // Done reading folder list break; } else { Parser p = new Parser(line, 2); String cmd = p.parseAtom(); if (cmd.equalsIgnoreCase("list")) { @SuppressWarnings("unused") String props = p.parseListOrNil(); String delim = p.parseString(); if (delim == null) delim = "~"; if (delim.length() == 1) dchar = delim.charAt(0); String serverId = p.parseStringOrAtom(); int lastDelim = serverId.lastIndexOf(delim); String displayName; String parentName; if (lastDelim > 0) { displayName = serverId.substring(lastDelim + 1); parentName = serverId.substring(0, lastDelim); } else { displayName = serverId; parentName = null; } Mailbox m = new Mailbox(); m.mDisplayName = decodeFolderName(displayName, null); m.mAccountKey = mAccountId; m.mServerId = decodeFolderName(serverId, null); if (parentName != null && !parentList.contains(parentName)) { parentList.add(parentName); } m.mFlagVisible = true; m.mParentServerId = parentName; m.mDelimiter = dchar; m.mSyncInterval = Mailbox.CHECK_INTERVAL_NEVER; mailboxList.add(m); } else { // WTF } } } // TODO: Use narrower projection Cursor c = mResolver.query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION, Mailbox.ACCOUNT_KEY + "=?", new String[] {Long.toString(mAccountId)}, MailboxColumns.SERVER_ID + " asc"); if (c == null) return; int cnt = c.getCount(); String[] serverIds = new String[cnt]; long[] uidvals = new long[cnt]; long[] ids = new long[cnt]; int i = 0; try { if (c.moveToFirst()) { // Get arrays of information about existing mailboxes in account do { serverIds[i] = c.getString(Mailbox.CONTENT_SERVER_ID_COLUMN); uidvals[i] = c.getLong(Mailbox.CONTENT_SYNC_KEY_COLUMN); ids[i] = c.getLong(Mailbox.CONTENT_ID_COLUMN); i++; } while (c.moveToNext()); } } finally { c.close(); } ArrayList<Mailbox> addList = new ArrayList<Mailbox>(); for (Mailbox m: mailboxList) { int loc = Arrays.binarySearch(serverIds, m.mServerId); if (loc >= 0) { // It exists if (uidvals[loc] == 0) { // Good enough; a match that we've never visited! // Mark this as touched (-1)... uidvals[loc] = -1; } else { // Ok, now we need to see if this is the SAME mailbox... // For now, assume it is; move on // TODO: There's a problem if you've 1) visited this box and 2) another box now // has its name, but how likely is that?? uidvals[loc] = -1; } } else { // We don't know about this mailbox, so we'll add it... // BUT must see if it's a rename of one we've visited! addList.add(m); } } // TODO: Flush this list every N (100?) in case there are zillions ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); try { for (i = 0; i < cnt; i++) { String name = serverIds[i]; long uidval = uidvals[i]; // -1 means matched; ignore // 0 means unmatched and never before seen // > 0 means unmatched and HAS been seen. must find mWriter why // TODO: Get rid of "Outbox" if (uidval == 0 && !name.equals("Outbox") && !name.equalsIgnoreCase(INBOX_SERVER_NAME)) { // Ok, here's one we've never visited and it's not in the new list ops.add(ContentProviderOperation.newDelete(ContentUris.withAppendedId( Mailbox.CONTENT_URI, ids[i])).build()); userLog("Deleting unseen mailbox; no match: " + name); } else if (uidval > 0 && !name.equalsIgnoreCase(INBOX_SERVER_NAME)) { boolean found = false; for (Mailbox m : addList) { tag = writeCommand(mWriter, "status \"" + m.mServerId + "\" (UIDVALIDITY)"); if (readResponse(mReader, tag, "STATUS").equals(IMAP_OK)) { String str = mImapResponse.get(0).toLowerCase(); int idx = str.indexOf("uidvalidity"); long num = readLong(str, idx + 12); if (uidval == num) { // try { // // This is a renamed mailbox... // c = Mailbox.getCursorWhere(mDatabase, "account=" + mAccount.id + " and serverName=?", name); // if (c != null && c.moveToFirst()) { // Mailbox existing = Mailbox.restoreFromCursor(c); // userLog("Renaming existing mailbox: " + existing.mServerId + " to: " + m.mServerId); // existing.mDisplayName = m.mDisplayName; // existing.mServerId = m.mServerId; // m.mHierarchicalName = m.mServerId; // existing.mParentServerId = m.mParentServerId; // existing.mFlags = m.mFlags; // existing.save(mDatabase); // // Mark this so that we don't save it below // m.mServerId = null; // } // } finally { // if (c != null) { // c.close(); // } // } found = true; break; } } } if (!found) { // There's no current mailbox with this uidval, so delete. ops.add(ContentProviderOperation.newDelete(ContentUris.withAppendedId( Mailbox.CONTENT_URI, ids[i])).build()); userLog("Deleting uidval mailbox; no match: " + name); } } } for (Mailbox m : addList) { String serverId = m.mServerId; if (serverId == null) continue; if (!serverId.equalsIgnoreCase(INBOX_SERVER_NAME) && !serverId.equalsIgnoreCase("Outbox")) { m.mHierarchicalName = m.mServerId; //*** For now, use Mail. We need a way to select the others... m.mType = Mailbox.TYPE_MAIL; ops.add(ContentProviderOperation.newInsert( Mailbox.CONTENT_URI).withValues(m.toContentValues()).build()); userLog("Adding new mailbox: " + m.mServerId); } } applyBatch(ops); // Fixup parent stuff, flags... MailboxUtilities.fixupUninitializedParentKeys(mContext, Mailbox.ACCOUNT_KEY + "=" + mAccountId); } finally { SyncManager.kick("folder list"); } }
diff --git a/src/examples/simple/src/main/java/org/apache/accumulo/examples/simple/isolation/InterferenceTest.java b/src/examples/simple/src/main/java/org/apache/accumulo/examples/simple/isolation/InterferenceTest.java index b9bee2133..e569b27eb 100644 --- a/src/examples/simple/src/main/java/org/apache/accumulo/examples/simple/isolation/InterferenceTest.java +++ b/src/examples/simple/src/main/java/org/apache/accumulo/examples/simple/isolation/InterferenceTest.java @@ -1,176 +1,176 @@ /* * 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.accumulo.examples.simple.isolation; import java.util.HashSet; import java.util.Map.Entry; import org.apache.accumulo.core.Constants; import org.apache.accumulo.core.client.BatchWriter; import org.apache.accumulo.core.client.Connector; import org.apache.accumulo.core.client.IsolatedScanner; import org.apache.accumulo.core.client.MutationsRejectedException; import org.apache.accumulo.core.client.Scanner; import org.apache.accumulo.core.client.ZooKeeperInstance; import org.apache.accumulo.core.data.ByteSequence; import org.apache.accumulo.core.data.Key; import org.apache.accumulo.core.data.Mutation; import org.apache.accumulo.core.data.Value; import org.apache.hadoop.io.Text; import org.apache.log4j.Logger; /** * This example shows how a concurrent reader and writer can interfere with each other. It creates two threads that run forever reading and writing to the same * table. * * When the example is run with isolation enabled, no interference will be observed. * * When the example is run with out isolation, the reader will see partial mutations of a row. * */ public class InterferenceTest { private static final int NUM_ROWS = 500; private static final int NUM_COLUMNS = 113; // scanner batches 1000 by default, so make num columns not a multiple of 10 private static long iterations; private static final Logger log = Logger.getLogger(InterferenceTest.class); static class Writer implements Runnable { private BatchWriter bw; Writer(BatchWriter bw) { this.bw = bw; } @Override public void run() { int row = 0; int value = 0; for (long i = 0; i < iterations; i++) { Mutation m = new Mutation(new Text(String.format("%03d", row))); row = (row + 1) % NUM_ROWS; for (int cq = 0; cq < NUM_COLUMNS; cq++) m.put(new Text("000"), new Text(String.format("%04d", cq)), new Value(("" + value).getBytes())); value++; try { bw.addMutation(m); } catch (MutationsRejectedException e) { e.printStackTrace(); System.exit(-1); } } try { bw.close(); } catch (MutationsRejectedException e) { log.error(e, e); } } } static class Reader implements Runnable { private Scanner scanner; volatile boolean stop = false; Reader(Scanner scanner) { this.scanner = scanner; } @Override public void run() { - while (stop) { + while (!stop) { ByteSequence row = null; int count = 0; // all columns in a row should have the same value, // use this hash set to track that HashSet<String> values = new HashSet<String>(); for (Entry<Key,Value> entry : scanner) { if (row == null) row = entry.getKey().getRowData(); if (!row.equals(entry.getKey().getRowData())) { if (count != NUM_COLUMNS) System.err.println("ERROR Did not see " + NUM_COLUMNS + " columns in row " + row); if (values.size() > 1) System.err.println("ERROR Columns in row " + row + " had multiple values " + values); row = entry.getKey().getRowData(); count = 0; values.clear(); } count++; values.add(entry.getValue().toString()); } if (count > 0 && count != NUM_COLUMNS) System.err.println("ERROR Did not see " + NUM_COLUMNS + " columns in row " + row); if (values.size() > 1) System.err.println("ERROR Columns in row " + row + " had multiple values " + values); } } public void stopNow() { stop = true; } } public static void main(String[] args) throws Exception { if (args.length != 7) { System.out.println("Usage : " + InterferenceTest.class.getName() + " <instance name> <zookeepers> <user> <password> <table> <iterations> true|false"); System.out.println(" The last argument determines if scans should be isolated. When false, expect to see errors"); return; } ZooKeeperInstance zki = new ZooKeeperInstance(args[0], args[1]); Connector conn = zki.getConnector(args[2], args[3].getBytes()); String table = args[4]; iterations = Long.parseLong(args[5]); if (iterations < 1) iterations = Long.MAX_VALUE; if (!conn.tableOperations().exists(table)) conn.tableOperations().create(table); Thread writer = new Thread(new Writer(conn.createBatchWriter(table, 10000000, 60000l, 3))); writer.start(); Reader r; if (Boolean.parseBoolean(args[6])) r = new Reader(new IsolatedScanner(conn.createScanner(table, Constants.NO_AUTHS))); else r = new Reader(conn.createScanner(table, Constants.NO_AUTHS)); Thread reader; reader = new Thread(r); reader.start(); writer.join(); r.stopNow(); reader.join(); System.out.println("finished"); } }
true
true
public void run() { while (stop) { ByteSequence row = null; int count = 0; // all columns in a row should have the same value, // use this hash set to track that HashSet<String> values = new HashSet<String>(); for (Entry<Key,Value> entry : scanner) { if (row == null) row = entry.getKey().getRowData(); if (!row.equals(entry.getKey().getRowData())) { if (count != NUM_COLUMNS) System.err.println("ERROR Did not see " + NUM_COLUMNS + " columns in row " + row); if (values.size() > 1) System.err.println("ERROR Columns in row " + row + " had multiple values " + values); row = entry.getKey().getRowData(); count = 0; values.clear(); } count++; values.add(entry.getValue().toString()); } if (count > 0 && count != NUM_COLUMNS) System.err.println("ERROR Did not see " + NUM_COLUMNS + " columns in row " + row); if (values.size() > 1) System.err.println("ERROR Columns in row " + row + " had multiple values " + values); } }
public void run() { while (!stop) { ByteSequence row = null; int count = 0; // all columns in a row should have the same value, // use this hash set to track that HashSet<String> values = new HashSet<String>(); for (Entry<Key,Value> entry : scanner) { if (row == null) row = entry.getKey().getRowData(); if (!row.equals(entry.getKey().getRowData())) { if (count != NUM_COLUMNS) System.err.println("ERROR Did not see " + NUM_COLUMNS + " columns in row " + row); if (values.size() > 1) System.err.println("ERROR Columns in row " + row + " had multiple values " + values); row = entry.getKey().getRowData(); count = 0; values.clear(); } count++; values.add(entry.getValue().toString()); } if (count > 0 && count != NUM_COLUMNS) System.err.println("ERROR Did not see " + NUM_COLUMNS + " columns in row " + row); if (values.size() > 1) System.err.println("ERROR Columns in row " + row + " had multiple values " + values); } }
diff --git a/server/src/main/java/com/metamx/druid/master/SegmentReplicantLookup.java b/server/src/main/java/com/metamx/druid/master/SegmentReplicantLookup.java index 41553b4f7c..560787247f 100644 --- a/server/src/main/java/com/metamx/druid/master/SegmentReplicantLookup.java +++ b/server/src/main/java/com/metamx/druid/master/SegmentReplicantLookup.java @@ -1,107 +1,107 @@ /* * Druid - a distributed column store. * Copyright (C) 2012 Metamarkets Group 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package com.metamx.druid.master; import com.google.common.collect.HashBasedTable; import com.google.common.collect.Maps; import com.google.common.collect.MinMaxPriorityQueue; import com.google.common.collect.Table; import com.metamx.druid.client.DataSegment; import com.metamx.druid.client.DruidServer; import java.util.Map; /** * A lookup for the number of replicants of a given segment for a certain tier. */ public class SegmentReplicantLookup { public static SegmentReplicantLookup make(DruidCluster cluster) { final Table<String, String, Integer> segmentsInCluster = HashBasedTable.create(); final Table<String, String, Integer> loadingSegments = HashBasedTable.create(); for (MinMaxPriorityQueue<ServerHolder> serversByType : cluster.getSortedServersByTier()) { for (ServerHolder serverHolder : serversByType) { DruidServer server = serverHolder.getServer(); for (DataSegment segment : server.getSegments().values()) { Integer numReplicants = segmentsInCluster.get(segment.getIdentifier(), server.getTier()); if (numReplicants == null) { numReplicants = 0; } segmentsInCluster.put(segment.getIdentifier(), server.getTier(), ++numReplicants); } // Also account for queued segments for (DataSegment segment : serverHolder.getPeon().getSegmentsToLoad()) { - Integer numReplicants = segmentsInCluster.get(segment.getIdentifier(), server.getTier()); + Integer numReplicants = loadingSegments.get(segment.getIdentifier(), server.getTier()); if (numReplicants == null) { numReplicants = 0; } loadingSegments.put(segment.getIdentifier(), server.getTier(), ++numReplicants); } } } return new SegmentReplicantLookup(segmentsInCluster, loadingSegments); } private final Table<String, String, Integer> segmentsInCluster; private final Table<String, String, Integer> loadingSegments; private SegmentReplicantLookup( Table<String, String, Integer> segmentsInCluster, Table<String, String, Integer> loadingSegments ) { this.segmentsInCluster = segmentsInCluster; this.loadingSegments = loadingSegments; } public Map<String, Integer> getClusterTiers(String segmentId) { Map<String, Integer> retVal = segmentsInCluster.row(segmentId); return (retVal == null) ? Maps.<String, Integer>newHashMap() : retVal; } public Map<String, Integer> getLoadingTiers(String segmentId) { Map<String, Integer> retVal = loadingSegments.row(segmentId); return (retVal == null) ? Maps.<String, Integer>newHashMap() : retVal; } public int getClusterReplicants(String segmentId, String tier) { Integer retVal = segmentsInCluster.get(segmentId, tier); return (retVal == null) ? 0 : retVal; } public int getLoadingReplicants(String segmentId, String tier) { Integer retVal = loadingSegments.get(segmentId, tier); return (retVal == null) ? 0 : retVal; } public int getTotalReplicants(String segmentId, String tier) { return getClusterReplicants(segmentId, tier) + getLoadingReplicants(segmentId, tier); } }
true
true
public static SegmentReplicantLookup make(DruidCluster cluster) { final Table<String, String, Integer> segmentsInCluster = HashBasedTable.create(); final Table<String, String, Integer> loadingSegments = HashBasedTable.create(); for (MinMaxPriorityQueue<ServerHolder> serversByType : cluster.getSortedServersByTier()) { for (ServerHolder serverHolder : serversByType) { DruidServer server = serverHolder.getServer(); for (DataSegment segment : server.getSegments().values()) { Integer numReplicants = segmentsInCluster.get(segment.getIdentifier(), server.getTier()); if (numReplicants == null) { numReplicants = 0; } segmentsInCluster.put(segment.getIdentifier(), server.getTier(), ++numReplicants); } // Also account for queued segments for (DataSegment segment : serverHolder.getPeon().getSegmentsToLoad()) { Integer numReplicants = segmentsInCluster.get(segment.getIdentifier(), server.getTier()); if (numReplicants == null) { numReplicants = 0; } loadingSegments.put(segment.getIdentifier(), server.getTier(), ++numReplicants); } } } return new SegmentReplicantLookup(segmentsInCluster, loadingSegments); }
public static SegmentReplicantLookup make(DruidCluster cluster) { final Table<String, String, Integer> segmentsInCluster = HashBasedTable.create(); final Table<String, String, Integer> loadingSegments = HashBasedTable.create(); for (MinMaxPriorityQueue<ServerHolder> serversByType : cluster.getSortedServersByTier()) { for (ServerHolder serverHolder : serversByType) { DruidServer server = serverHolder.getServer(); for (DataSegment segment : server.getSegments().values()) { Integer numReplicants = segmentsInCluster.get(segment.getIdentifier(), server.getTier()); if (numReplicants == null) { numReplicants = 0; } segmentsInCluster.put(segment.getIdentifier(), server.getTier(), ++numReplicants); } // Also account for queued segments for (DataSegment segment : serverHolder.getPeon().getSegmentsToLoad()) { Integer numReplicants = loadingSegments.get(segment.getIdentifier(), server.getTier()); if (numReplicants == null) { numReplicants = 0; } loadingSegments.put(segment.getIdentifier(), server.getTier(), ++numReplicants); } } } return new SegmentReplicantLookup(segmentsInCluster, loadingSegments); }
diff --git a/Jabref_Beta_2_7_Docear/src/java/net/sf/jabref/plugin/PluginCore.java b/Jabref_Beta_2_7_Docear/src/java/net/sf/jabref/plugin/PluginCore.java index 3065f4470..3bae5d0d8 100644 --- a/Jabref_Beta_2_7_Docear/src/java/net/sf/jabref/plugin/PluginCore.java +++ b/Jabref_Beta_2_7_Docear/src/java/net/sf/jabref/plugin/PluginCore.java @@ -1,190 +1,191 @@ package net.sf.jabref.plugin; import java.io.File; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import net.sf.jabref.Globals; import net.sf.jabref.plugin.util.Util; import org.java.plugin.ObjectFactory; import org.java.plugin.PluginManager; import org.java.plugin.PluginManager.PluginLocation; import org.java.plugin.boot.DefaultPluginsCollector; import org.java.plugin.registry.PluginDescriptor; import org.java.plugin.standard.StandardPluginLocation; import org.java.plugin.util.ExtendedProperties; /** * Helper class for the plug-in system. Helps to retrieve the singleton instance * of the PluginManager, which then can be used to access all the plug-ins * registered. * * For an example how this is done see * {@link net.sf.jabref.export.layout.LayoutEntry#getLayoutFormatterFromPlugins(String)} * * The PluginCore relies on the generated class * {@link net.sf.jabref.plugin.core.JabRefPlugin} in the sub-package "core" for * finding the plugins and their extension. * * @author Christopher Oezbek */ public class PluginCore { static PluginManager singleton; static File userPluginDir = new File(System.getProperty("user.home")+"/.jabref/plugins"); static PluginLocation getLocationInsideJar(String context, String manifest) { URL jar = PluginCore.class .getResource(Util.joinPath(context, manifest)); if (jar == null) { return null; } String protocol = jar.getProtocol().toLowerCase(); try { if (protocol.startsWith("jar")) { return new StandardPluginLocation(new URL(jar.toExternalForm() .replaceFirst("!(.*?)$", Util.joinPath("!", context))), jar); } else if (protocol.startsWith("file")) { File f = new File(jar.toURI()); return new StandardPluginLocation(f.getParentFile(), manifest); } } catch (URISyntaxException e) { return null; } catch (MalformedURLException e) { return null; } return null; } static PluginManager initialize() { // We do not want info messages from JPF. Logger.getLogger("org.java.plugin").setLevel(Level.WARNING); Logger log = Logger.getLogger(PluginCore.class.getName()); ObjectFactory objectFactory = ObjectFactory.newInstance(); PluginManager result = objectFactory.createManager(); /* * Now find plug-ins! Check directories and jar. */ try { DefaultPluginsCollector collector = new DefaultPluginsCollector(); ExtendedProperties ep = new ExtendedProperties(); List<File> directoriesToSearch = new LinkedList<File>(); directoriesToSearch.add(new File("./src/plugins")); directoriesToSearch.add(new File("./plugins")); directoriesToSearch.add(userPluginDir); try { File parent = new File(PluginCore.class.getProtectionDomain() .getCodeSource().getLocation().toURI()).getParentFile(); if (!parent.getCanonicalFile().equals( new File(".").getCanonicalFile())) { directoriesToSearch.add(new File(parent, "/src/plugins")); directoriesToSearch.add(new File(parent, "/plugins")); } } catch (Exception e) { // no problem, we just use paths relative to current dir. } StringBuilder sb = new StringBuilder(); for (File directory : directoriesToSearch) { // We don't want warnings if the default plug-in paths don't // exist, we do that below if (directory.exists()) { if (sb.length() > 0) sb.append(','); sb.append(directory.getPath()); } } ep.setProperty("org.java.plugin.boot.pluginsRepositories", sb .toString()); collector.configure(ep); Collection<PluginLocation> plugins = collector .collectPluginLocations(); /** * I know the following is really, really ugly, but I have found no * way to automatically discover multiple plugin.xmls in JARs */ String[] jarLocationsToSearch = new String[] { "/plugins/net.sf.jabref.core/", "/plugins/net.sf.jabref.export.misq/"}; // Collection locations for (String jarLocation : jarLocationsToSearch) { PluginLocation location = getLocationInsideJar(jarLocation, "plugin.xml"); if (location != null) plugins.add(location); } if (plugins.size() <= 0) { log .warning(Globals .lang("No plugins were found in the following folders:") + "\n " + Util.join(directoriesToSearch .toArray(new String[directoriesToSearch.size()]), "\n ", 0, directoriesToSearch.size()) + "\n" + Globals.lang("and inside the JabRef-jar:") + "\n " + Util.join(jarLocationsToSearch, "\n ", 0, jarLocationsToSearch.length) + "\n" + Globals .lang("At least the plug-in 'net.sf.jabref.core' should be there.")); } else { result.publishPlugins(plugins.toArray(new PluginLocation[] {})); Collection<PluginDescriptor> descs = result.getRegistry() .getPluginDescriptors(); sb = new StringBuilder(); sb.append(Globals.lang("Found %0 plugin(s)", String .valueOf(descs.size())) + ":\n"); for (PluginDescriptor p : result.getRegistry() .getPluginDescriptors()) { sb.append(" - ").append(p.getId()).append(" (").append( p.getLocation()).append(")\n"); } log.info(sb.toString()); } } catch (Exception e) { + //DOCEAR changed from severe to warning log - .severe(Globals + .warning(Globals .lang("Error in starting plug-in system. Starting without, but some functionality may be missing.") + "\n" + e.getLocalizedMessage()); } return result; } public static PluginManager getManager() { if (singleton == null) { singleton = PluginCore.initialize(); } return singleton; } }
false
true
static PluginManager initialize() { // We do not want info messages from JPF. Logger.getLogger("org.java.plugin").setLevel(Level.WARNING); Logger log = Logger.getLogger(PluginCore.class.getName()); ObjectFactory objectFactory = ObjectFactory.newInstance(); PluginManager result = objectFactory.createManager(); /* * Now find plug-ins! Check directories and jar. */ try { DefaultPluginsCollector collector = new DefaultPluginsCollector(); ExtendedProperties ep = new ExtendedProperties(); List<File> directoriesToSearch = new LinkedList<File>(); directoriesToSearch.add(new File("./src/plugins")); directoriesToSearch.add(new File("./plugins")); directoriesToSearch.add(userPluginDir); try { File parent = new File(PluginCore.class.getProtectionDomain() .getCodeSource().getLocation().toURI()).getParentFile(); if (!parent.getCanonicalFile().equals( new File(".").getCanonicalFile())) { directoriesToSearch.add(new File(parent, "/src/plugins")); directoriesToSearch.add(new File(parent, "/plugins")); } } catch (Exception e) { // no problem, we just use paths relative to current dir. } StringBuilder sb = new StringBuilder(); for (File directory : directoriesToSearch) { // We don't want warnings if the default plug-in paths don't // exist, we do that below if (directory.exists()) { if (sb.length() > 0) sb.append(','); sb.append(directory.getPath()); } } ep.setProperty("org.java.plugin.boot.pluginsRepositories", sb .toString()); collector.configure(ep); Collection<PluginLocation> plugins = collector .collectPluginLocations(); /** * I know the following is really, really ugly, but I have found no * way to automatically discover multiple plugin.xmls in JARs */ String[] jarLocationsToSearch = new String[] { "/plugins/net.sf.jabref.core/", "/plugins/net.sf.jabref.export.misq/"}; // Collection locations for (String jarLocation : jarLocationsToSearch) { PluginLocation location = getLocationInsideJar(jarLocation, "plugin.xml"); if (location != null) plugins.add(location); } if (plugins.size() <= 0) { log .warning(Globals .lang("No plugins were found in the following folders:") + "\n " + Util.join(directoriesToSearch .toArray(new String[directoriesToSearch.size()]), "\n ", 0, directoriesToSearch.size()) + "\n" + Globals.lang("and inside the JabRef-jar:") + "\n " + Util.join(jarLocationsToSearch, "\n ", 0, jarLocationsToSearch.length) + "\n" + Globals .lang("At least the plug-in 'net.sf.jabref.core' should be there.")); } else { result.publishPlugins(plugins.toArray(new PluginLocation[] {})); Collection<PluginDescriptor> descs = result.getRegistry() .getPluginDescriptors(); sb = new StringBuilder(); sb.append(Globals.lang("Found %0 plugin(s)", String .valueOf(descs.size())) + ":\n"); for (PluginDescriptor p : result.getRegistry() .getPluginDescriptors()) { sb.append(" - ").append(p.getId()).append(" (").append( p.getLocation()).append(")\n"); } log.info(sb.toString()); } } catch (Exception e) { log .severe(Globals .lang("Error in starting plug-in system. Starting without, but some functionality may be missing.") + "\n" + e.getLocalizedMessage()); } return result; }
static PluginManager initialize() { // We do not want info messages from JPF. Logger.getLogger("org.java.plugin").setLevel(Level.WARNING); Logger log = Logger.getLogger(PluginCore.class.getName()); ObjectFactory objectFactory = ObjectFactory.newInstance(); PluginManager result = objectFactory.createManager(); /* * Now find plug-ins! Check directories and jar. */ try { DefaultPluginsCollector collector = new DefaultPluginsCollector(); ExtendedProperties ep = new ExtendedProperties(); List<File> directoriesToSearch = new LinkedList<File>(); directoriesToSearch.add(new File("./src/plugins")); directoriesToSearch.add(new File("./plugins")); directoriesToSearch.add(userPluginDir); try { File parent = new File(PluginCore.class.getProtectionDomain() .getCodeSource().getLocation().toURI()).getParentFile(); if (!parent.getCanonicalFile().equals( new File(".").getCanonicalFile())) { directoriesToSearch.add(new File(parent, "/src/plugins")); directoriesToSearch.add(new File(parent, "/plugins")); } } catch (Exception e) { // no problem, we just use paths relative to current dir. } StringBuilder sb = new StringBuilder(); for (File directory : directoriesToSearch) { // We don't want warnings if the default plug-in paths don't // exist, we do that below if (directory.exists()) { if (sb.length() > 0) sb.append(','); sb.append(directory.getPath()); } } ep.setProperty("org.java.plugin.boot.pluginsRepositories", sb .toString()); collector.configure(ep); Collection<PluginLocation> plugins = collector .collectPluginLocations(); /** * I know the following is really, really ugly, but I have found no * way to automatically discover multiple plugin.xmls in JARs */ String[] jarLocationsToSearch = new String[] { "/plugins/net.sf.jabref.core/", "/plugins/net.sf.jabref.export.misq/"}; // Collection locations for (String jarLocation : jarLocationsToSearch) { PluginLocation location = getLocationInsideJar(jarLocation, "plugin.xml"); if (location != null) plugins.add(location); } if (plugins.size() <= 0) { log .warning(Globals .lang("No plugins were found in the following folders:") + "\n " + Util.join(directoriesToSearch .toArray(new String[directoriesToSearch.size()]), "\n ", 0, directoriesToSearch.size()) + "\n" + Globals.lang("and inside the JabRef-jar:") + "\n " + Util.join(jarLocationsToSearch, "\n ", 0, jarLocationsToSearch.length) + "\n" + Globals .lang("At least the plug-in 'net.sf.jabref.core' should be there.")); } else { result.publishPlugins(plugins.toArray(new PluginLocation[] {})); Collection<PluginDescriptor> descs = result.getRegistry() .getPluginDescriptors(); sb = new StringBuilder(); sb.append(Globals.lang("Found %0 plugin(s)", String .valueOf(descs.size())) + ":\n"); for (PluginDescriptor p : result.getRegistry() .getPluginDescriptors()) { sb.append(" - ").append(p.getId()).append(" (").append( p.getLocation()).append(")\n"); } log.info(sb.toString()); } } catch (Exception e) { //DOCEAR changed from severe to warning log .warning(Globals .lang("Error in starting plug-in system. Starting without, but some functionality may be missing.") + "\n" + e.getLocalizedMessage()); } return result; }
diff --git a/geogebra/geogebra3D/euclidian3D/DrawVector3D.java b/geogebra/geogebra3D/euclidian3D/DrawVector3D.java index 5a34af105..64246deb7 100644 --- a/geogebra/geogebra3D/euclidian3D/DrawVector3D.java +++ b/geogebra/geogebra3D/euclidian3D/DrawVector3D.java @@ -1,88 +1,93 @@ package geogebra3D.euclidian3D; import geogebra.Matrix.GgbVector; import geogebra.main.Application; import geogebra3D.euclidian3D.opengl.Brush; import geogebra3D.euclidian3D.opengl.Renderer; import geogebra3D.kernel3D.GeoCoordSys1D; import geogebra3D.kernel3D.GeoVector3D; public class DrawVector3D extends Drawable3DCurves { /** gl index of the geometry */ private int geometryIndex = -1; public DrawVector3D(EuclidianView3D a_view3D, GeoVector3D a_vector3D) { super(a_view3D, a_vector3D); } ///////////////////////////////////////// // DRAWING GEOMETRIES public void drawGeometry(Renderer renderer) { double t = getGeoElement().getLineThickness(); renderer.setThickness(t); renderer.setArrowType(Renderer.ARROW_TYPE_SIMPLE); renderer.setArrowLength(10*t); renderer.setArrowWidth(5*t); //renderer.drawSegment(); renderer.getGeometryManager().draw(geometryIndex); renderer.setArrowType(Renderer.ARROW_TYPE_NONE); } protected void updateForItSelf(){ GeoVector3D geo = ((GeoVector3D) getGeoElement()); geo.updateStartPointPosition(); Renderer renderer = getView3D().getRenderer(); renderer.getGeometryManager().remove(geometryIndex); - GgbVector p1 = geo.getStartPoint().getInhomCoords(); + GgbVector p1; + if (geo.getStartPoint()==null){ + p1 = new GgbVector(4); + p1.setW(1); + }else + p1 = geo.getStartPoint().getInhomCoords(); GgbVector p2 = (GgbVector) p1.add(geo.getCoords()); float thickness = (float) (Brush.LINE3D_THICKNESS*getGeoElement().getLineThickness()/getView3D().getScale()); Brush brush = renderer.getGeometryManager().getBrush(); brush.setArrowType(Brush.ARROW_TYPE_SIMPLE); brush.setThickness(getGeoElement().getLineThickness(),(float) getView3D().getScale()); brush.start(8); brush.setAffineTexture(0.5f, 0.125f); brush.segment(p1,p2); brush.setArrowType(Brush.ARROW_TYPE_NONE); geometryIndex = brush.end(); } protected void updateForView(){ updateForItSelf(); } public int getPickOrder() { return DRAW_PICK_ORDER_1D; } }
true
true
protected void updateForItSelf(){ GeoVector3D geo = ((GeoVector3D) getGeoElement()); geo.updateStartPointPosition(); Renderer renderer = getView3D().getRenderer(); renderer.getGeometryManager().remove(geometryIndex); GgbVector p1 = geo.getStartPoint().getInhomCoords(); GgbVector p2 = (GgbVector) p1.add(geo.getCoords()); float thickness = (float) (Brush.LINE3D_THICKNESS*getGeoElement().getLineThickness()/getView3D().getScale()); Brush brush = renderer.getGeometryManager().getBrush(); brush.setArrowType(Brush.ARROW_TYPE_SIMPLE); brush.setThickness(getGeoElement().getLineThickness(),(float) getView3D().getScale()); brush.start(8); brush.setAffineTexture(0.5f, 0.125f); brush.segment(p1,p2); brush.setArrowType(Brush.ARROW_TYPE_NONE); geometryIndex = brush.end(); }
protected void updateForItSelf(){ GeoVector3D geo = ((GeoVector3D) getGeoElement()); geo.updateStartPointPosition(); Renderer renderer = getView3D().getRenderer(); renderer.getGeometryManager().remove(geometryIndex); GgbVector p1; if (geo.getStartPoint()==null){ p1 = new GgbVector(4); p1.setW(1); }else p1 = geo.getStartPoint().getInhomCoords(); GgbVector p2 = (GgbVector) p1.add(geo.getCoords()); float thickness = (float) (Brush.LINE3D_THICKNESS*getGeoElement().getLineThickness()/getView3D().getScale()); Brush brush = renderer.getGeometryManager().getBrush(); brush.setArrowType(Brush.ARROW_TYPE_SIMPLE); brush.setThickness(getGeoElement().getLineThickness(),(float) getView3D().getScale()); brush.start(8); brush.setAffineTexture(0.5f, 0.125f); brush.segment(p1,p2); brush.setArrowType(Brush.ARROW_TYPE_NONE); geometryIndex = brush.end(); }
diff --git a/grails/src/commons/org/codehaus/groovy/grails/commons/GrailsResourceLoader.java b/grails/src/commons/org/codehaus/groovy/grails/commons/GrailsResourceLoader.java index 47fdb6428..169b4b65b 100644 --- a/grails/src/commons/org/codehaus/groovy/grails/commons/GrailsResourceLoader.java +++ b/grails/src/commons/org/codehaus/groovy/grails/commons/GrailsResourceLoader.java @@ -1,91 +1,91 @@ /* Copyright 2004-2005 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.grails.commons; import groovy.lang.GroovyResourceLoader; import org.springframework.core.io.Resource; import org.codehaus.groovy.grails.exceptions.GrailsConfigurationException; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.HashMap; /** * A GroovyResourceLoader that loads groovy files using Spring's IO abstraction * * @author Graeme Rocher * @since 22-Feb-2006 */ public class GrailsResourceLoader implements GroovyResourceLoader { private Resource[] resources; private List loadedResources = new ArrayList(); private Map classToResource = new HashMap(); public GrailsResourceLoader(Resource[] resources) { this.resources = resources; } public List getLoadedResources() { return loadedResources; } public void setResources(Resource[] resources) { this.resources = resources; } public URL loadGroovySource(String className) throws MalformedURLException { if(className == null) return null; String groovyFile = className.replace('.', '/') + ".groovy"; Resource foundResource = null; for (int i = 0; resources != null && i < resources.length; i++) { if (resources[i].getFilename().equals(groovyFile)) { if (foundResource == null) { foundResource = resources[i]; } else { try { - throw new IllegalArgumentException("Found two identical classes at [" + resources[i].getFile().getAbsolutePath()+ "] and [" + foundResource.getFile().getAbsolutePath() + "] whilst attempting to load [" + className + "]. Please check remove one to avoid duplicates."); + throw new IllegalArgumentException("Found two identical classes at [" + resources[i].getFile().getAbsolutePath()+ "] and [" + foundResource.getFile().getAbsolutePath() + "] whilst attempting to load [" + className + "]. Please remove one to avoid duplicates."); } catch (IOException e) { throw new GrailsConfigurationException("I/O error whilst attempting to load class " + className, e); } } } } try { if (foundResource != null) { loadedResources.add(foundResource); classToResource.put(className, foundResource); return foundResource.getURL(); } else { return null; } } catch (IOException e) { throw new RuntimeException(e); } } /** * Returns the Grails resource for the given class or null if it is not a Grails resource * * @param theClass The class * @return The Resource or null */ public Resource getResourceForClass(Class theClass) { return (Resource)classToResource.get(theClass.getName()); } }
true
true
public URL loadGroovySource(String className) throws MalformedURLException { if(className == null) return null; String groovyFile = className.replace('.', '/') + ".groovy"; Resource foundResource = null; for (int i = 0; resources != null && i < resources.length; i++) { if (resources[i].getFilename().equals(groovyFile)) { if (foundResource == null) { foundResource = resources[i]; } else { try { throw new IllegalArgumentException("Found two identical classes at [" + resources[i].getFile().getAbsolutePath()+ "] and [" + foundResource.getFile().getAbsolutePath() + "] whilst attempting to load [" + className + "]. Please check remove one to avoid duplicates."); } catch (IOException e) { throw new GrailsConfigurationException("I/O error whilst attempting to load class " + className, e); } } } } try { if (foundResource != null) { loadedResources.add(foundResource); classToResource.put(className, foundResource); return foundResource.getURL(); } else { return null; } } catch (IOException e) { throw new RuntimeException(e); } }
public URL loadGroovySource(String className) throws MalformedURLException { if(className == null) return null; String groovyFile = className.replace('.', '/') + ".groovy"; Resource foundResource = null; for (int i = 0; resources != null && i < resources.length; i++) { if (resources[i].getFilename().equals(groovyFile)) { if (foundResource == null) { foundResource = resources[i]; } else { try { throw new IllegalArgumentException("Found two identical classes at [" + resources[i].getFile().getAbsolutePath()+ "] and [" + foundResource.getFile().getAbsolutePath() + "] whilst attempting to load [" + className + "]. Please remove one to avoid duplicates."); } catch (IOException e) { throw new GrailsConfigurationException("I/O error whilst attempting to load class " + className, e); } } } } try { if (foundResource != null) { loadedResources.add(foundResource); classToResource.put(className, foundResource); return foundResource.getURL(); } else { return null; } } catch (IOException e) { throw new RuntimeException(e); } }
diff --git a/src/main/java/org/atlasapi/equiv/generators/FilmEquivalenceGenerator.java b/src/main/java/org/atlasapi/equiv/generators/FilmEquivalenceGenerator.java index 054f63c5f..f267ef678 100644 --- a/src/main/java/org/atlasapi/equiv/generators/FilmEquivalenceGenerator.java +++ b/src/main/java/org/atlasapi/equiv/generators/FilmEquivalenceGenerator.java @@ -1,103 +1,103 @@ package org.atlasapi.equiv.generators; import static com.google.common.collect.Iterables.filter; import java.util.List; import org.atlasapi.application.ApplicationConfiguration; import org.atlasapi.equiv.results.description.ResultDescription; import org.atlasapi.equiv.results.scores.DefaultScoredEquivalents; import org.atlasapi.equiv.results.scores.DefaultScoredEquivalents.ScoredEquivalentsBuilder; import org.atlasapi.equiv.results.scores.Score; import org.atlasapi.equiv.results.scores.ScoredEquivalents; import org.atlasapi.media.entity.Film; import org.atlasapi.media.entity.Identified; import org.atlasapi.media.entity.Publisher; import org.atlasapi.persistence.content.SearchResolver; import org.atlasapi.search.model.SearchQuery; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.metabroadcast.common.query.Selection; public class FilmEquivalenceGenerator implements ContentEquivalenceGenerator<Film> { private static final ApplicationConfiguration config = new ApplicationConfiguration(ImmutableSet.of(Publisher.PREVIEW_NETWORKS), null); private static final float TITLE_WEIGHTING = 1.0f; private static final float BROADCAST_WEIGHTING = 0.0f; private static final float CATCHUP_WEIGHTING = 0.0f; private final SearchResolver searchResolver; public FilmEquivalenceGenerator(SearchResolver searchResolver) { this.searchResolver = searchResolver; } @Override public ScoredEquivalents<Film> generate(Film film, ResultDescription desc) { ScoredEquivalentsBuilder<Film> scores = DefaultScoredEquivalents.<Film> fromSource("Film"); desc.startStage("Film equivalence generator"); if (film.getYear() == null || Strings.isNullOrEmpty(film.getTitle())) { - desc.appendText("Can't continue: year '%s', title '%'", film.getYear(), film.getTitle()).finishStage(); + desc.appendText("Can't continue: year '%s', title '%s'", film.getYear(), film.getTitle()).finishStage(); return scores.build(); } else { desc.appendText("Using year %s, title %s", film.getYear(), film.getTitle()); } List<Identified> possibleEquivalentFilms = searchResolver.search(new SearchQuery(film.getTitle(), Selection.ALL, ImmutableList.of(Publisher.PREVIEW_NETWORKS), TITLE_WEIGHTING, BROADCAST_WEIGHTING, CATCHUP_WEIGHTING), config); Iterable<Film> foundFilms = filter(possibleEquivalentFilms, Film.class); desc.appendText("Found %s films through title search", Iterables.size(foundFilms)); for (Film equivFilm : foundFilms) { if(sameYear(film, equivFilm)) { Score score = Score.valueOf(titleMatch(film, equivFilm)); desc.appendText("%s (%s) scored %s", equivFilm.getTitle(), equivFilm.getCanonicalUri(), score); scores.addEquivalent(equivFilm, score); } else { desc.appendText("%s (%s) ignored. Wrong year %s", equivFilm.getTitle(), equivFilm.getCanonicalUri(), equivFilm.getYear()); scores.addEquivalent(equivFilm, Score.valueOf(0.0)); } } desc.finishStage(); return scores.build(); } private double titleMatch(Film film, Film equivFilm) { return match(removeThe(alphaNumeric(film.getTitle())), removeThe(alphaNumeric(equivFilm.getTitle()))); } public double match(String subjectTitle, String equivalentTitle) { double commonPrefix = commonPrefixLength(subjectTitle, equivalentTitle); double difference = Math.abs(equivalentTitle.length() - commonPrefix) / equivalentTitle.length(); return commonPrefix / (subjectTitle.length() / 1.0) - difference; } private String removeThe(String title) { if(title.startsWith("the")) { return title.substring(3); } return title; } private String alphaNumeric(String title) { return title.replaceAll("[^\\d\\w]", "").toLowerCase(); } private double commonPrefixLength(String t1, String t2) { int i = 0; for (; i < Math.min(t1.length(), t2.length()) && t1.charAt(i) == t2.charAt(i); i++) { } return i; } private boolean sameYear(Film film, Film equivFilm) { return film.getYear().equals(equivFilm.getYear()); } }
true
true
public ScoredEquivalents<Film> generate(Film film, ResultDescription desc) { ScoredEquivalentsBuilder<Film> scores = DefaultScoredEquivalents.<Film> fromSource("Film"); desc.startStage("Film equivalence generator"); if (film.getYear() == null || Strings.isNullOrEmpty(film.getTitle())) { desc.appendText("Can't continue: year '%s', title '%'", film.getYear(), film.getTitle()).finishStage(); return scores.build(); } else { desc.appendText("Using year %s, title %s", film.getYear(), film.getTitle()); } List<Identified> possibleEquivalentFilms = searchResolver.search(new SearchQuery(film.getTitle(), Selection.ALL, ImmutableList.of(Publisher.PREVIEW_NETWORKS), TITLE_WEIGHTING, BROADCAST_WEIGHTING, CATCHUP_WEIGHTING), config); Iterable<Film> foundFilms = filter(possibleEquivalentFilms, Film.class); desc.appendText("Found %s films through title search", Iterables.size(foundFilms)); for (Film equivFilm : foundFilms) { if(sameYear(film, equivFilm)) { Score score = Score.valueOf(titleMatch(film, equivFilm)); desc.appendText("%s (%s) scored %s", equivFilm.getTitle(), equivFilm.getCanonicalUri(), score); scores.addEquivalent(equivFilm, score); } else { desc.appendText("%s (%s) ignored. Wrong year %s", equivFilm.getTitle(), equivFilm.getCanonicalUri(), equivFilm.getYear()); scores.addEquivalent(equivFilm, Score.valueOf(0.0)); } } desc.finishStage(); return scores.build(); }
public ScoredEquivalents<Film> generate(Film film, ResultDescription desc) { ScoredEquivalentsBuilder<Film> scores = DefaultScoredEquivalents.<Film> fromSource("Film"); desc.startStage("Film equivalence generator"); if (film.getYear() == null || Strings.isNullOrEmpty(film.getTitle())) { desc.appendText("Can't continue: year '%s', title '%s'", film.getYear(), film.getTitle()).finishStage(); return scores.build(); } else { desc.appendText("Using year %s, title %s", film.getYear(), film.getTitle()); } List<Identified> possibleEquivalentFilms = searchResolver.search(new SearchQuery(film.getTitle(), Selection.ALL, ImmutableList.of(Publisher.PREVIEW_NETWORKS), TITLE_WEIGHTING, BROADCAST_WEIGHTING, CATCHUP_WEIGHTING), config); Iterable<Film> foundFilms = filter(possibleEquivalentFilms, Film.class); desc.appendText("Found %s films through title search", Iterables.size(foundFilms)); for (Film equivFilm : foundFilms) { if(sameYear(film, equivFilm)) { Score score = Score.valueOf(titleMatch(film, equivFilm)); desc.appendText("%s (%s) scored %s", equivFilm.getTitle(), equivFilm.getCanonicalUri(), score); scores.addEquivalent(equivFilm, score); } else { desc.appendText("%s (%s) ignored. Wrong year %s", equivFilm.getTitle(), equivFilm.getCanonicalUri(), equivFilm.getYear()); scores.addEquivalent(equivFilm, Score.valueOf(0.0)); } } desc.finishStage(); return scores.build(); }
diff --git a/Seng271_LudoGame/src/LudoGame.java b/Seng271_LudoGame/src/LudoGame.java index a339bec..b3d084c 100644 --- a/Seng271_LudoGame/src/LudoGame.java +++ b/Seng271_LudoGame/src/LudoGame.java @@ -1,165 +1,165 @@ import java.awt.Dimension; import java.awt.Point; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.*; /** * This is the main runner class for the Ludo Game. It currently prints the * board background image, and adds the pawns to the board. * * @author Daniel Faulkner */ public class LudoGame extends JPanel { // The height and width of the application private final static int APPHEIGHT = 540; private final static int APPWIDTH = 750; // The offsets from the walls of the window private final static int BOARDLEFTOFFSET = 5; private final static int BOARDTOPOFFSET = 5; // The grids on the game board are 48 pixels across private final static int GRIDSIZE = 48; // There are 11x11 grids (including ones the pawns can't occupy) private final static int GRIDNUM = 11; // This 2D array holds the top left point of each matching grid spot // TODO This should probably be removed once the Fields are implemented private final static Point[][] THEGRID = new Point[GRIDNUM][GRIDNUM]; // The grid offsets for putting pawns in the correct home field private final static int LEFT = 1, RIGHT = 8; private final static int TOP = 1, BOTTOM = 8; // The array lists to keep track of the pawns in the game private final ArrayList<Pawn> bluePawns = new ArrayList<Pawn>(); private final ArrayList<Pawn> redPawns = new ArrayList<Pawn>(); private final ArrayList<Pawn> greenPawns = new ArrayList<Pawn>(); private final ArrayList<Pawn> yellowPawns = new ArrayList<Pawn>(); // The swing panel for layered objects private JLayeredPane boardPane; /** * Constructor for the game board. Adds layered images and game pieces. */ public LudoGame() { setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); - final ImageIcon boardBackground = createImageIcon("src\\game_board.png"); - final ImageIcon bluePawnImg = createImageIcon("src\\blue_pawn.png"); - final ImageIcon redPawnImg = createImageIcon("src\\red_pawn.png"); - final ImageIcon greenPawnImg = createImageIcon("src\\green_pawn.png"); - final ImageIcon yellowPawnImg = createImageIcon("src\\yellow_pawn.png"); + final ImageIcon boardBackground = createImageIcon("src/game_board.png"); + final ImageIcon bluePawnImg = createImageIcon("src/blue_pawn.png"); + final ImageIcon redPawnImg = createImageIcon("src/red_pawn.png"); + final ImageIcon greenPawnImg = createImageIcon("src/green_pawn.png"); + final ImageIcon yellowPawnImg = createImageIcon("src/yellow_pawn.png"); setupTheGrid(); boardPane = new JLayeredPane(); boardPane.setPreferredSize(new Dimension(APPWIDTH, APPHEIGHT)); JLabel board = new JLabel(boardBackground); boardPane.add(board, new Integer(0)); Dimension boardSize = board.getPreferredSize(); board.setBounds(BOARDLEFTOFFSET, BOARDTOPOFFSET, boardSize.width, boardSize.height); addPawns(bluePawnImg, bluePawns, LEFT, TOP); addPawns(redPawnImg, redPawns, LEFT, BOTTOM); addPawns(yellowPawnImg, yellowPawns, RIGHT, TOP); addPawns(greenPawnImg, greenPawns, RIGHT, BOTTOM); add(boardPane); } /** * Sets up the 2D array that holds the 11 x 11 grid imagining of the board * and assigns each location the relevant Point of the top left corner (for * a Point p, p.x and p.y give you the x and y coordinates of that point, * respectively). */ private void setupTheGrid() { for (int i = 0; i < GRIDNUM; i++) { for (int j = 0; j < GRIDNUM; j++) { THEGRID[i][j] = new Point(i * GRIDSIZE, j * GRIDSIZE); } } } /** * Adds a player's 4 pawns to the game board in the grid spot corresponding * with the home field (once that's implemented). * * @param imgSrc * the pawn's image * @param pawnList * the list to add the pawn to after putting on board * @param homeFieldX * the home field positioning (LEFT or RIGHT) * @param homeFieldY * the home field positioning (TOP or BOTTOM) */ private void addPawns(final ImageIcon imgSrc, final ArrayList<Pawn> pawnList, final int homeFieldX, final int homeFieldY) { for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { JLabel jl = new JLabel(imgSrc); boardPane.add(jl, new Integer(1)); Dimension size = jl.getPreferredSize(); jl.setBounds( BOARDLEFTOFFSET + (THEGRID[i % 2 + homeFieldX][j % 2 + homeFieldY].x), BOARDTOPOFFSET + THEGRID[i % 2 + homeFieldX][j % 2 + homeFieldY].y, size.width, size.height); Pawn p = new Pawn(jl, jl.getLocation()); bluePawns.add(p); } } } /** * Loads the image from the specified path. * * @param src * the path of the image file * @return an ImageIcon (or null, if the image is not found) */ private ImageIcon createImageIcon(final String src) { try { BufferedImage bluePawn = ImageIO.read(new File(src)); ImageIcon icon = new ImageIcon(bluePawn); return icon; } catch (IOException ioe) { ioe.printStackTrace(); return null; } } /** * Creates the general GUI frames and call the LudoGame constructor. */ private static void createGUI() { JFrame frame = new JFrame("Ludo Game"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JComponent contentPane = new LudoGame(); contentPane.setOpaque(true); frame.setContentPane(contentPane); frame.pack(); frame.setVisible(true); } /** * The entry point for the program. Kicks things off by creating the GUI. * * @param args */ public static void main(String[] args) { createGUI(); } }
true
true
public LudoGame() { setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); final ImageIcon boardBackground = createImageIcon("src\\game_board.png"); final ImageIcon bluePawnImg = createImageIcon("src\\blue_pawn.png"); final ImageIcon redPawnImg = createImageIcon("src\\red_pawn.png"); final ImageIcon greenPawnImg = createImageIcon("src\\green_pawn.png"); final ImageIcon yellowPawnImg = createImageIcon("src\\yellow_pawn.png"); setupTheGrid(); boardPane = new JLayeredPane(); boardPane.setPreferredSize(new Dimension(APPWIDTH, APPHEIGHT)); JLabel board = new JLabel(boardBackground); boardPane.add(board, new Integer(0)); Dimension boardSize = board.getPreferredSize(); board.setBounds(BOARDLEFTOFFSET, BOARDTOPOFFSET, boardSize.width, boardSize.height); addPawns(bluePawnImg, bluePawns, LEFT, TOP); addPawns(redPawnImg, redPawns, LEFT, BOTTOM); addPawns(yellowPawnImg, yellowPawns, RIGHT, TOP); addPawns(greenPawnImg, greenPawns, RIGHT, BOTTOM); add(boardPane); }
public LudoGame() { setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); final ImageIcon boardBackground = createImageIcon("src/game_board.png"); final ImageIcon bluePawnImg = createImageIcon("src/blue_pawn.png"); final ImageIcon redPawnImg = createImageIcon("src/red_pawn.png"); final ImageIcon greenPawnImg = createImageIcon("src/green_pawn.png"); final ImageIcon yellowPawnImg = createImageIcon("src/yellow_pawn.png"); setupTheGrid(); boardPane = new JLayeredPane(); boardPane.setPreferredSize(new Dimension(APPWIDTH, APPHEIGHT)); JLabel board = new JLabel(boardBackground); boardPane.add(board, new Integer(0)); Dimension boardSize = board.getPreferredSize(); board.setBounds(BOARDLEFTOFFSET, BOARDTOPOFFSET, boardSize.width, boardSize.height); addPawns(bluePawnImg, bluePawns, LEFT, TOP); addPawns(redPawnImg, redPawns, LEFT, BOTTOM); addPawns(yellowPawnImg, yellowPawns, RIGHT, TOP); addPawns(greenPawnImg, greenPawns, RIGHT, BOTTOM); add(boardPane); }
diff --git a/alitheia/db/src/eu/sqooss/impl/service/DBActivator.java b/alitheia/db/src/eu/sqooss/impl/service/DBActivator.java index 26ad0939..f0dc1b5c 100644 --- a/alitheia/db/src/eu/sqooss/impl/service/DBActivator.java +++ b/alitheia/db/src/eu/sqooss/impl/service/DBActivator.java @@ -1,55 +1,55 @@ /* * This file is part of the Alitheia system, developed by the SQO-OSS * consortium as part of the IST FP6 SQO-OSS project, number 033331. * * Copyright 2007 by the SQO-OSS consortium members <[email protected]> * * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package eu.sqooss.impl.service; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; import eu.sqooss.impl.service.db.DBServiceImpl; public class DBActivator implements BundleActivator { private ServiceRegistration registration; public void start(BundleContext bc) throws Exception { registration = bc.registerService(DBServiceImpl.class.getName(), - new DBServiceImpl(), null); + new DBServiceImpl(bc), null); } public void stop(BundleContext bc) throws Exception { registration.unregister(); } } // vi: ai nosi sw=4 ts=4 expandtab
true
true
public void start(BundleContext bc) throws Exception { registration = bc.registerService(DBServiceImpl.class.getName(), new DBServiceImpl(), null); }
public void start(BundleContext bc) throws Exception { registration = bc.registerService(DBServiceImpl.class.getName(), new DBServiceImpl(bc), null); }
diff --git a/src/com/fsck/k9/mail/store/WebDavStore.java b/src/com/fsck/k9/mail/store/WebDavStore.java index df1f0a3..4deb228 100644 --- a/src/com/fsck/k9/mail/store/WebDavStore.java +++ b/src/com/fsck/k9/mail/store/WebDavStore.java @@ -1,2665 +1,2666 @@ package com.fsck.k9.mail.store; import android.util.Log; import com.fsck.k9.Account; import com.fsck.k9.K9; import com.fsck.k9.Utility; import com.fsck.k9.mail.*; import com.fsck.k9.mail.Folder.OpenMode; import com.fsck.k9.mail.internet.MimeMessage; import com.fsck.k9.mail.transport.EOLConvertingOutputStream; import com.fsck.k9.mail.transport.TrustedSocketFactory; import org.apache.http.*; import org.apache.http.auth.AuthScope; import org.apache.http.auth.Credentials; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CookieStore; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.HttpContext; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; import javax.net.ssl.SSLException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.io.*; import java.net.URI; import java.net.URISyntaxException; import java.net.URLDecoder; import java.net.URLEncoder; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Stack; import java.util.zip.GZIPInputStream; /** * <pre> * Uses WebDAV formatted HTTP calls to an MS Exchange server to fetch emails * and email information. This has only been tested on an MS Exchange * Server 2003. It uses Form-Based authentication and requires that * Outlook Web Access be enabled on the server. * </pre> */ public class WebDavStore extends Store { public static final int CONNECTION_SECURITY_NONE = 0; public static final int CONNECTION_SECURITY_TLS_OPTIONAL = 1; public static final int CONNECTION_SECURITY_TLS_REQUIRED = 2; public static final int CONNECTION_SECURITY_SSL_REQUIRED = 3; public static final int CONNECTION_SECURITY_SSL_OPTIONAL = 4; private static final Flag[] PERMANENT_FLAGS = { Flag.DELETED, Flag.SEEN, Flag.ANSWERED }; private int mConnectionSecurity; private String mUsername; /* Stores the username for authentications */ private String alias; private String mPassword; /* Stores the password for authentications */ private String mUrl; /* Stores the base URL for the server */ private String mHost; /* Stores the host name for the server */ private String mPath; /* Stores the path for the server */ private String mAuthPath; /* Stores the path off of the server to post data to for form based authentication */ private String mMailboxPath; /* Stores the user specified path to the mailbox */ private URI mUri; /* Stores the Uniform Resource Indicator with all connection info */ private String mRedirectUrl; private String mAuthString; private static String DAV_MAIL_SEND_FOLDER = "##DavMailSubmissionURI##"; private static String DAV_MAIL_TMP_FOLDER = "drafts"; private CookieStore mAuthCookies; /* Stores cookies from authentication */ private boolean mAuthenticated = false; /* Stores authentication state */ private long mLastAuth = -1; /* Stores the timestamp of last auth */ private long mAuthTimeout = 5 * 60; private HashMap<String, WebDavFolder> mFolderList = new HashMap<String, WebDavFolder>(); private boolean mSecure; private WebDavHttpClient mHttpClient = null; /** * webdav://user:password@server:port CONNECTION_SECURITY_NONE * webdav+tls://user:password@server:port CONNECTION_SECURITY_TLS_OPTIONAL * webdav+tls+://user:password@server:port CONNECTION_SECURITY_TLS_REQUIRED * webdav+ssl+://user:password@server:port CONNECTION_SECURITY_SSL_REQUIRED * webdav+ssl://user:password@server:port CONNECTION_SECURITY_SSL_OPTIONAL */ public WebDavStore(Account account) throws MessagingException { super(account); try { mUri = new URI(mAccount.getStoreUri()); } catch (URISyntaxException use) { throw new MessagingException("Invalid WebDavStore URI", use); } String scheme = mUri.getScheme(); if (scheme.equals("webdav")) { mConnectionSecurity = CONNECTION_SECURITY_NONE; } else if (scheme.equals("webdav+ssl")) { mConnectionSecurity = CONNECTION_SECURITY_SSL_OPTIONAL; } else if (scheme.equals("webdav+ssl+")) { mConnectionSecurity = CONNECTION_SECURITY_SSL_REQUIRED; } else if (scheme.equals("webdav+tls")) { mConnectionSecurity = CONNECTION_SECURITY_TLS_OPTIONAL; } else if (scheme.equals("webdav+tls+")) { mConnectionSecurity = CONNECTION_SECURITY_TLS_REQUIRED; } else { throw new MessagingException("Unsupported protocol"); } mHost = mUri.getHost(); if (mHost.startsWith("http")) { String[] hostParts = mHost.split("://", 2); if (hostParts.length > 1) { mHost = hostParts[1]; } } String[] pathParts = mUri.getPath().split("\\|"); for (int i = 0, count = pathParts.length; i < count; i++) { if (i == 0) { if (pathParts[0] != null && pathParts[0].length() > 1) { if (!pathParts[0].substring(1).equals("")) { mPath = pathParts[0].substring(1); } else { mPath = ""; } } else { mPath = ""; } } else if (i == 1) { if (pathParts[1] != null && pathParts[1].length() > 1) { mAuthPath = "/" + pathParts[1]; } } else if (i == 2) { if (pathParts[2] != null && pathParts[2].length() > 1) { mMailboxPath = "/" + pathParts[2]; if (mPath == null || mPath.equals("")) { mPath = mMailboxPath; } } } } String path = mPath; if (path.length() > 0 && path.startsWith("/") == false) { path = "/" + mPath; } this.mUrl = getRoot() + path; if (mUri.getUserInfo() != null) { try { String[] userInfoParts = mUri.getUserInfo().split(":"); mUsername = URLDecoder.decode(userInfoParts[0], "UTF-8"); String userParts[] = mUsername.split("/", 2); if (userParts.length > 1) { alias = userParts[1]; } else { alias = mUsername; } if (userInfoParts.length > 1) { mPassword = URLDecoder.decode(userInfoParts[1], "UTF-8"); } } catch (UnsupportedEncodingException enc) { // This shouldn't happen since the encoding is hardcoded to UTF-8 Log.e(K9.LOG_TAG, "Couldn't urldecode username or password.", enc); } } mSecure = mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED; mAuthString = "Basic " + Utility.base64Encode(mUsername + ":" + mPassword); } private String getRoot() { String root; if (mConnectionSecurity == CONNECTION_SECURITY_TLS_REQUIRED || mConnectionSecurity == CONNECTION_SECURITY_SSL_REQUIRED || mConnectionSecurity == CONNECTION_SECURITY_TLS_OPTIONAL || mConnectionSecurity == CONNECTION_SECURITY_SSL_OPTIONAL) { root = "https"; } else { root = "http"; } root += "://" + mHost + ":" + mUri.getPort(); return root; } @Override public void checkSettings() throws MessagingException { Log.e(K9.LOG_TAG, "WebDavStore.checkSettings() not implemented"); } @Override public Folder[] getPersonalNamespaces() throws MessagingException { ArrayList<Folder> folderList = new ArrayList<Folder>(); HashMap<String, String> headers = new HashMap<String, String>(); DataSet dataset = new DataSet(); String messageBody; String[] folderUrls; int urlLength; /** * We have to check authentication here so we have the proper URL stored */ getHttpClient(); messageBody = getFolderListXml(); headers.put("Brief", "t"); dataset = processRequest(this.mUrl, "SEARCH", messageBody, headers); folderUrls = dataset.getHrefs(); urlLength = folderUrls.length; for (int i = 0; i < urlLength; i++) { // Log.i(K9.LOG_TAG, "folderUrls[" + i + "] = '" + folderUrls[i]); String[] urlParts = folderUrls[i].split("/"); // Log.i(K9.LOG_TAG, "urlParts = " + urlParts); String folderName = urlParts[urlParts.length - 1]; String fullPathName = ""; WebDavFolder wdFolder; if (folderName.equalsIgnoreCase(K9.INBOX)) { folderName = "INBOX"; } else { for (int j = 5, count = urlParts.length; j < count; j++) { if (j != 5) { fullPathName = fullPathName + "/" + urlParts[j]; } else { fullPathName = urlParts[j]; } } try { folderName = java.net.URLDecoder.decode(fullPathName, "UTF-8"); } catch (UnsupportedEncodingException uee) { /** If we don't support UTF-8 there's a problem, don't decode it then */ folderName = fullPathName; } } wdFolder = new WebDavFolder(this, folderName); wdFolder.setUrl(folderUrls[i]); folderList.add(wdFolder); this.mFolderList.put(folderName, wdFolder); } return folderList.toArray(new WebDavFolder[] {}); } @Override public Folder getFolder(String name) throws MessagingException { WebDavFolder folder; if ((folder = this.mFolderList.get(name)) == null) { folder = new WebDavFolder(this, name); } return folder; } public Folder getSendSpoolFolder() throws MessagingException { return getFolder(DAV_MAIL_SEND_FOLDER); } @Override public boolean isMoveCapable() { return true; } @Override public boolean isCopyCapable() { return true; } /*************************************************************** * WebDAV XML Request body retrieval functions */ private String getFolderListXml() { StringBuffer buffer = new StringBuffer(200); buffer.append("<?xml version='1.0' ?>"); buffer.append("<a:searchrequest xmlns:a='DAV:'><a:sql>\r\n"); buffer.append("SELECT \"DAV:uid\", \"DAV:ishidden\"\r\n"); buffer.append(" FROM SCOPE('deep traversal of \""+this.mUrl+"\"')\r\n"); buffer.append(" WHERE \"DAV:ishidden\"=False AND \"DAV:isfolder\"=True\r\n"); buffer.append("</a:sql></a:searchrequest>\r\n"); return buffer.toString(); } private String getMessageCountXml(String messageState) { StringBuffer buffer = new StringBuffer(200); buffer.append("<?xml version='1.0' ?>"); buffer.append("<a:searchrequest xmlns:a='DAV:'><a:sql>\r\n"); buffer.append("SELECT \"DAV:visiblecount\"\r\n"); buffer.append(" FROM \"\"\r\n"); buffer.append(" WHERE \"DAV:ishidden\"=False AND \"DAV:isfolder\"=False AND \"urn:schemas:httpmail:read\"="+messageState+"\r\n"); buffer.append(" GROUP BY \"DAV:ishidden\"\r\n"); buffer.append("</a:sql></a:searchrequest>\r\n"); return buffer.toString(); } private String getMessageEnvelopeXml(String[] uids) { StringBuffer buffer = new StringBuffer(200); buffer.append("<?xml version='1.0' ?>"); buffer.append("<a:searchrequest xmlns:a='DAV:'><a:sql>\r\n"); buffer.append("SELECT \"DAV:uid\", \"DAV:getcontentlength\","); buffer.append(" \"urn:schemas:mailheader:mime-version\","); buffer.append(" \"urn:schemas:mailheader:content-type\","); buffer.append(" \"urn:schemas:mailheader:subject\","); buffer.append(" \"urn:schemas:mailheader:date\","); buffer.append(" \"urn:schemas:mailheader:thread-topic\","); buffer.append(" \"urn:schemas:mailheader:thread-index\","); buffer.append(" \"urn:schemas:mailheader:from\","); buffer.append(" \"urn:schemas:mailheader:to\","); buffer.append(" \"urn:schemas:mailheader:in-reply-to\","); buffer.append(" \"urn:schemas:mailheader:cc\","); buffer.append(" \"urn:schemas:httpmail:read\""); buffer.append(" \r\n"); buffer.append(" FROM \"\"\r\n"); buffer.append(" WHERE \"DAV:ishidden\"=False AND \"DAV:isfolder\"=False AND "); for (int i = 0, count = uids.length; i < count; i++) { if (i != 0) { buffer.append(" OR "); } buffer.append(" \"DAV:uid\"='"+uids[i]+"' "); } buffer.append("\r\n"); buffer.append("</a:sql></a:searchrequest>\r\n"); return buffer.toString(); } private String getMessagesXml() { StringBuffer buffer = new StringBuffer(200); buffer.append("<?xml version='1.0' ?>"); buffer.append("<a:searchrequest xmlns:a='DAV:'><a:sql>\r\n"); buffer.append("SELECT \"DAV:uid\"\r\n"); buffer.append(" FROM \"\"\r\n"); buffer.append(" WHERE \"DAV:ishidden\"=False AND \"DAV:isfolder\"=False\r\n"); buffer.append("</a:sql></a:searchrequest>\r\n"); return buffer.toString(); } private String getMessageUrlsXml(String[] uids) { StringBuffer buffer = new StringBuffer(600); buffer.append("<?xml version='1.0' ?>"); buffer.append("<a:searchrequest xmlns:a='DAV:'><a:sql>\r\n"); buffer.append("SELECT \"urn:schemas:httpmail:read\", \"DAV:uid\"\r\n"); buffer.append(" FROM \"\"\r\n"); buffer.append(" WHERE \"DAV:ishidden\"=False AND \"DAV:isfolder\"=False AND "); for (int i = 0, count = uids.length; i < count; i++) { if (i != 0) { buffer.append(" OR "); } buffer.append(" \"DAV:uid\"='"+uids[i]+"' "); } buffer.append("\r\n"); buffer.append("</a:sql></a:searchrequest>\r\n"); return buffer.toString(); } private String getMessageFlagsXml(String[] uids) throws MessagingException { if (uids.length == 0) { throw new MessagingException("Attempt to get flags on 0 length array for uids"); } StringBuffer buffer = new StringBuffer(200); buffer.append("<?xml version='1.0' ?>"); buffer.append("<a:searchrequest xmlns:a='DAV:'><a:sql>\r\n"); buffer.append("SELECT \"urn:schemas:httpmail:read\", \"DAV:uid\"\r\n"); buffer.append(" FROM \"\"\r\n"); buffer.append(" WHERE \"DAV:ishidden\"=False AND \"DAV:isfolder\"=False AND "); for (int i = 0, count = uids.length; i < count; i++) { if (i != 0) { buffer.append(" OR "); } buffer.append(" \"DAV:uid\"='"+uids[i]+"' "); } buffer.append("\r\n"); buffer.append("</a:sql></a:searchrequest>\r\n"); return buffer.toString(); } private String getMarkMessagesReadXml(String[] urls, boolean read) { StringBuffer buffer = new StringBuffer(600); buffer.append("<?xml version='1.0' ?>\r\n"); buffer.append("<a:propertyupdate xmlns:a='DAV:' xmlns:b='urn:schemas:httpmail:'>\r\n"); buffer.append("<a:target>\r\n"); for (int i = 0, count = urls.length; i < count; i++) { buffer.append(" <a:href>"+urls[i]+"</a:href>\r\n"); } buffer.append("</a:target>\r\n"); buffer.append("<a:set>\r\n"); buffer.append(" <a:prop>\r\n"); buffer.append(" <b:read>" + (read ? "1" : "0") + "</b:read>\r\n"); buffer.append(" </a:prop>\r\n"); buffer.append("</a:set>\r\n"); buffer.append("</a:propertyupdate>\r\n"); return buffer.toString(); } // For flag: // http://www.devnewsgroups.net/group/microsoft.public.exchange.development/topic27175.aspx //"<m:0x10900003>1</m:0x10900003>" & _ private String getMoveOrCopyMessagesReadXml(String[] urls, boolean isMove) { String action = (isMove ? "move" : "copy"); StringBuffer buffer = new StringBuffer(600); buffer.append("<?xml version='1.0' ?>\r\n"); buffer.append("<a:" + action + " xmlns:a='DAV:' xmlns:b='urn:schemas:httpmail:'>\r\n"); buffer.append("<a:target>\r\n"); for (int i = 0, count = urls.length; i < count; i++) { buffer.append(" <a:href>"+urls[i]+"</a:href>\r\n"); } buffer.append("</a:target>\r\n"); buffer.append("</a:" + action + ">\r\n"); return buffer.toString(); } /*************************************************************** * Authentication related methods */ /** * Performs Form Based authentication regardless of the current * authentication state * @throws MessagingException */ public void authenticate() throws MessagingException { try { doFBA(); //this.mAuthCookies = doAuthentication(this.mUsername, this.mPassword, this.mUrl); } catch (IOException ioe) { Log.e(K9.LOG_TAG, "Error during authentication: " + ioe + "\nStack: " + processException(ioe)); throw new MessagingException("Error during authentication", ioe); } if (this.mAuthCookies == null) { this.mAuthenticated = false; } else { this.mAuthenticated = true; this.mLastAuth = System.currentTimeMillis()/1000; } } /** * Determines if a new authentication is needed. * Returns true if new authentication is needed. */ public boolean needAuth() { boolean status = false; long currentTime = -1; if (this.mAuthenticated == false) { status = true; } currentTime = System.currentTimeMillis()/1000; if ((currentTime - this.mLastAuth) > (this.mAuthTimeout)) { status = true; } return status; } public static String getHttpRequestResponse(HttpEntity request, HttpEntity response) throws IllegalStateException, IOException { String responseText = ""; String requestText = ""; if (response != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(WebDavHttpClient.getUngzippedContent(response)), 8192); String tempText = ""; while ((tempText = reader.readLine()) != null) { responseText += tempText; } } if (request != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(WebDavHttpClient.getUngzippedContent(response)), 8192); String tempText = ""; while ((tempText = reader.readLine()) != null) { requestText += tempText; } requestText = requestText.replaceAll("password=.*?&", "password=(omitted)&"); } return "Request: " + requestText + "\n\nResponse: " + responseText; } /** * Performs the Form Based Authentication * Returns the CookieStore object for later use or null * @throws MessagingException */ public void doFBA() throws IOException, MessagingException { /* public CookieStore doAuthentication(String username, String password, String url) throws IOException, MessagingException {*/ String authPath; String url = this.mUrl; String username = this.mUsername; String password = this.mPassword; String[] urlParts = url.split("/"); String finalUrl = ""; String loginUrl = ""; String destinationUrl = ""; if (this.mAuthPath != null && !this.mAuthPath.equals("") && !this.mAuthPath.equals("/")) { authPath = this.mAuthPath; } else { authPath = "/exchweb/bin/auth/owaauth.dll"; } for (int i = 0; i <= 2; i++) { if (i != 0) { finalUrl = finalUrl + "/" + urlParts[i]; } else { finalUrl = urlParts[i]; } } if (finalUrl.equals("")) { throw new MessagingException("doFBA failed, unable to construct URL to post login credentials to."); } loginUrl = finalUrl + authPath; try { /* Browser Client */ WebDavHttpClient httpclient = mHttpClient; /** * This is in a separate block because I really don't like how it's done. * This basically scrapes the OWA login page for the form submission URL. * UGLY!WebDavHttpClient * Added an if-check to see if there's a user supplied authentication path for FBA */ if (this.mAuthPath == null || this.mAuthPath.equals("") || this.mAuthPath.equals("/")) { httpclient.addRequestInterceptor(new HttpRequestInterceptor() { public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { mRedirectUrl = ((HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST)).toURI() + request.getRequestLine().getUri(); } }); HashMap<String, String> headers = new HashMap<String, String>(); InputStream istream = sendRequest(finalUrl, "GET", null, headers, false); if (istream != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(istream), 4096); String tempText = ""; boolean matched = false; while ((tempText = reader.readLine()) != null && !matched) { if (tempText.indexOf(" action") >= 0) { String[] tagParts = tempText.split("\""); if (tagParts[1].lastIndexOf('/') < 0 && mRedirectUrl != null && !mRedirectUrl.equals("")) { /* We have to do a multi-stage substring here because of potential GET parameters */ mRedirectUrl = mRedirectUrl.substring(0, mRedirectUrl.lastIndexOf('?')); mRedirectUrl = mRedirectUrl.substring(0, mRedirectUrl.lastIndexOf('/')); loginUrl = mRedirectUrl + "/" + tagParts[1]; this.mAuthPath = "/" + tagParts[1]; } else { loginUrl = finalUrl + tagParts[1]; this.mAuthPath = "/" + tagParts[1]; } } if (tempText.indexOf("destination") >= 0) { String[] tagParts = tempText.split("value"); if (tagParts[1] != null) { String[] valueParts = tagParts[1].split("\""); destinationUrl = valueParts[1]; matched = true; } } } istream.close(); } } /** Build the POST data to use */ ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>(); pairs.add(new BasicNameValuePair("username", username)); pairs.add(new BasicNameValuePair("password", password)); if (this.mMailboxPath != null && !this.mMailboxPath.equals("")) { pairs.add(new BasicNameValuePair("destination", finalUrl + this.mMailboxPath)); } else if (destinationUrl != null && !destinationUrl.equals("")) { pairs.add(new BasicNameValuePair("destination", destinationUrl)); } else { pairs.add(new BasicNameValuePair("destination", "/")); } pairs.add(new BasicNameValuePair("flags", "0")); pairs.add(new BasicNameValuePair("SubmitCreds", "Log+On")); pairs.add(new BasicNameValuePair("forcedownlevel", "0")); pairs.add(new BasicNameValuePair("trusted", "0")); try { UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(pairs); HashMap<String, String> headers = new HashMap<String, String>(); String tempUrl = ""; InputStream istream = sendRequest(loginUrl, "POST", formEntity, headers, false); /** Get the URL for the mailbox and set it for the store */ if (istream != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(istream), 8192); String tempText = ""; while ((tempText = reader.readLine()) != null) { if (tempText.indexOf("BASE href") >= 0) { String[] tagParts = tempText.split("\""); tempUrl = tagParts[1]; } } } if (this.mMailboxPath != null && !this.mMailboxPath.equals("")) { this.mUrl = finalUrl + "/" + this.mMailboxPath + "/"; } else if (tempUrl.equals("")) { this.mUrl = finalUrl + "/Exchange/" + this.alias + "/"; } else { this.mUrl = tempUrl; } } catch (UnsupportedEncodingException uee) { Log.e(K9.LOG_TAG, "Error encoding POST data for authentication: " + uee + "\nTrace: " + processException(uee)); throw new MessagingException("Error encoding POST data for authentication", uee); } } catch (SSLException e) { throw new CertificateValidationException(e.getMessage(), e); } this.mAuthenticated = true; } public CookieStore getAuthCookies() { return mAuthCookies; } public String getAlias() { return alias; } public String getUrl() { return mUrl; } public WebDavHttpClient getHttpClient() throws MessagingException { SchemeRegistry reg; Scheme s; boolean needAuth = false; if (mHttpClient == null) { mHttpClient = new WebDavHttpClient(); needAuth = true; } reg = mHttpClient.getConnectionManager().getSchemeRegistry(); try { // Log.i(K9.LOG_TAG, "getHttpClient mHost = " + mHost); s = new Scheme("https", new TrustedSocketFactory(mHost, mSecure), 443); } catch (NoSuchAlgorithmException nsa) { Log.e(K9.LOG_TAG, "NoSuchAlgorithmException in getHttpClient: " + nsa); throw new MessagingException("NoSuchAlgorithmException in getHttpClient: " + nsa); } catch (KeyManagementException kme) { Log.e(K9.LOG_TAG, "KeyManagementException in getHttpClient: " + kme); throw new MessagingException("KeyManagementException in getHttpClient: " + kme); } reg.register(s); if (needAuth) { HashMap<String, String> headers = new HashMap<String, String>(); processRequest(this.mUrl, "GET", null, headers, false); } /* if (needAuth()) { if (!checkAuth()) { try { CookieStore cookies = mHttpClient.getCookieStore(); cookies.clear(); mHttpClient.setCookieStore(cookies); cookies = doAuthentication(this.mUsername, this.mPassword, this.mUrl); if (cookies != null) { this.mAuthenticated = true; this.mLastAuth = System.currentTimeMillis()/1000; } mHttpClient.setCookieStore(cookies); } catch (IOException ioe) { Log.e(K9.LOG_TAG, "IOException: " + ioe + "\nTrace: " + processException(ioe)); } } else { Credentials creds = new UsernamePasswordCredentials(mUsername, mPassword); CredentialsProvider credsProvider = mHttpClient.getCredentialsProvider(); credsProvider.setCredentials(new AuthScope(mHost, 80, AuthScope.ANY_REALM), creds); credsProvider.setCredentials(new AuthScope(mHost, 443, AuthScope.ANY_REALM), creds); credsProvider.setCredentials(new AuthScope(mHost, mUri.getPort(), AuthScope.ANY_REALM), creds); mHttpClient.setCredentialsProvider(credsProvider); // Assume we're authenticated and ok here since the checkAuth() was 401 and we've now set the credentials this.mAuthenticated = true; this.mLastAuth = System.currentTimeMillis()/1000; } } */ return mHttpClient; } public WebDavHttpClient getTrustedHttpClient() throws KeyManagementException, NoSuchAlgorithmException { if (mHttpClient == null) { mHttpClient = new WebDavHttpClient(); SchemeRegistry reg = mHttpClient.getConnectionManager().getSchemeRegistry(); Scheme s = new Scheme("https",new TrustedSocketFactory(mHost,mSecure),443); reg.register(s); //Add credentials for NTLM/Digest/Basic Auth Credentials creds = new UsernamePasswordCredentials(mUsername, mPassword); CredentialsProvider credsProvider = mHttpClient.getCredentialsProvider(); // setting AuthScope for 80 and 443, in case we end up getting redirected // from 80 to 443. credsProvider.setCredentials(new AuthScope(mHost, 80, AuthScope.ANY_REALM), creds); credsProvider.setCredentials(new AuthScope(mHost, 443, AuthScope.ANY_REALM), creds); credsProvider.setCredentials(new AuthScope(mHost, mUri.getPort(), AuthScope.ANY_REALM), creds); mHttpClient.setCredentialsProvider(credsProvider); } return mHttpClient; } private InputStream sendRequest(String url, String method, StringEntity messageBody, HashMap<String, String> headers, boolean tryAuth) throws MessagingException { WebDavHttpClient httpclient; InputStream istream = null; if (url == null || method == null) { return istream; } httpclient = getHttpClient(); try { int statusCode = -1; StringEntity messageEntity = null; HttpGeneric httpmethod = new HttpGeneric(url); HttpResponse response; HttpEntity entity; if (messageBody != null) { httpmethod.setEntity(messageBody); } for (String headerName : headers.keySet()) { httpmethod.setHeader(headerName, headers.get(headerName)); } if (mAuthString != null && mAuthenticated) { httpmethod.setHeader("Authorization", mAuthString); } httpmethod.setMethod(method); response = httpclient.executeOverride(httpmethod); statusCode = response.getStatusLine().getStatusCode(); entity = response.getEntity(); if (statusCode == 401) { if (tryAuth) { mAuthenticated = true; sendRequest(url, method, messageBody, headers, false); } else { throw new MessagingException("Invalid username or password for Basic authentication"); } } else if (statusCode == 440) { if (tryAuth) { doFBA(); sendRequest(url, method, messageBody, headers, false); } else { throw new MessagingException("Authentication failure in sendRequest"); } } else if (statusCode < 200 || statusCode >= 300) { throw new IOException("Error with code " + statusCode + " during request processing: "+ response.getStatusLine().toString()); } else { if (tryAuth && mAuthenticated == false) { doFBA(); sendRequest(url, method, messageBody, headers, false); } } if (entity != null) { istream = WebDavHttpClient.getUngzippedContent(entity); } } catch (UnsupportedEncodingException uee) { Log.e(K9.LOG_TAG, "UnsupportedEncodingException: " + uee + "\nTrace: " + processException(uee)); throw new MessagingException("UnsupportedEncodingException", uee); } catch (IOException ioe) { Log.e(K9.LOG_TAG, "IOException: " + ioe + "\nTrace: " + processException(ioe)); throw new MessagingException("IOException", ioe); } return istream; } public String getAuthString() { return mAuthString; } /** * Performs an httprequest to the supplied url using the supplied method. * messageBody and headers are optional as not all requests will need them. * There are two signatures to support calls that don't require parsing of the response. */ private DataSet processRequest(String url, String method, String messageBody, HashMap<String, String> headers) throws MessagingException { return processRequest(url, method, messageBody, headers, true); } private DataSet processRequest(String url, String method, String messageBody, HashMap<String, String> headers, boolean needsParsing) throws MessagingException { DataSet dataset = new DataSet(); if (K9.DEBUG) { Log.v(K9.LOG_TAG, "processRequest url = '" + url + "', method = '" + method + "', messageBody = '" + messageBody + "'"); } if (url == null || method == null) { return dataset; } getHttpClient(); try { StringEntity messageEntity = null; if (messageBody != null) { messageEntity = new StringEntity(messageBody); messageEntity.setContentType("text/xml"); // httpmethod.setEntity(messageEntity); } InputStream istream = sendRequest(url, method, messageEntity, headers, true); if (istream != null && needsParsing) { try { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); WebDavHandler myHandler = new WebDavHandler(); xr.setContentHandler(myHandler); xr.parse(new InputSource(istream)); dataset = myHandler.getDataSet(); } catch (SAXException se) { Log.e(K9.LOG_TAG, "SAXException in processRequest() " + se + "\nTrace: " + processException(se)); throw new MessagingException("SAXException in processRequest() ", se); } catch (ParserConfigurationException pce) { Log.e(K9.LOG_TAG, "ParserConfigurationException in processRequest() " + pce + "\nTrace: " + processException(pce)); throw new MessagingException("ParserConfigurationException in processRequest() ", pce); } istream.close(); } } catch (UnsupportedEncodingException uee) { Log.e(K9.LOG_TAG, "UnsupportedEncodingException: " + uee + "\nTrace: " + processException(uee)); throw new MessagingException("UnsupportedEncodingException in processRequest() ", uee); } catch (IOException ioe) { Log.e(K9.LOG_TAG, "IOException: " + ioe + "\nTrace: " + processException(ioe)); throw new MessagingException("IOException in processRequest() ", ioe); } return dataset; } /** * Returns a string of the stacktrace for a Throwable to allow for easy inline printing of errors. */ private String processException(Throwable t) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); t.printStackTrace(ps); ps.close(); return baos.toString(); } @Override public boolean isSendCapable() { return true; } @Override public void sendMessages(Message[] messages) throws MessagingException { WebDavFolder tmpFolder = (WebDavStore.WebDavFolder)getFolder(DAV_MAIL_TMP_FOLDER); try { tmpFolder.open(OpenMode.READ_WRITE); Message[] retMessages = tmpFolder.appendWebDavMessages(messages); tmpFolder.moveMessages(retMessages, getSendSpoolFolder()); } finally { if (tmpFolder != null) { tmpFolder.close(); } } } /************************************************************************* * Helper and Inner classes */ /** * A WebDav Folder */ class WebDavFolder extends Folder { private String mName; private String mFolderUrl; private boolean mIsOpen = false; private int mMessageCount = 0; private int mUnreadMessageCount = 0; private WebDavStore store; protected WebDavStore getStore() { return store; } public WebDavFolder(WebDavStore nStore, String name) { super(nStore.getAccount()); store = nStore; this.mName = name; if (DAV_MAIL_SEND_FOLDER.equals(name)) { this.mFolderUrl = getUrl() + "/" + name +"/"; } else { String encodedName = ""; try { String[] urlParts = name.split("/"); String url = ""; for (int i = 0, count = urlParts.length; i < count; i++) { if (i != 0) { url = url + "/" + java.net.URLEncoder.encode(urlParts[i], "UTF-8"); } else { url = java.net.URLEncoder.encode(urlParts[i], "UTF-8"); } } encodedName = url; } catch (UnsupportedEncodingException uee) { Log.e(K9.LOG_TAG, "UnsupportedEncodingException URLEncoding folder name, skipping encoded"); encodedName = name; } encodedName = encodedName.replaceAll("\\+", "%20"); /** * In some instances, it is possible that our folder objects have been collected, * but getPersonalNamespaces() isn't called again (ex. Android destroys the email client). * Perform an authentication to get the appropriate URLs in place again */ // TODO: danapple0 - huh? //getHttpClient(); if (encodedName.equals("INBOX")) { encodedName = "Inbox"; } this.mFolderUrl = WebDavStore.this.mUrl; if (WebDavStore.this.mUrl.endsWith("/") == false) { this.mFolderUrl += "/"; } this.mFolderUrl += encodedName; } } public void setUrl(String url) { if (url != null) { this.mFolderUrl = url; } } @Override public void open(OpenMode mode) throws MessagingException { getHttpClient(); this.mIsOpen = true; } @Override public void copyMessages(Message[] messages, Folder folder) throws MessagingException { moveOrCopyMessages(messages, folder.getName(), false); } @Override public void moveMessages(Message[] messages, Folder folder) throws MessagingException { moveOrCopyMessages(messages, folder.getName(), true); } @Override public void delete(Message[] msgs, String trashFolderName) throws MessagingException { moveOrCopyMessages(msgs, trashFolderName, true); } private void moveOrCopyMessages(Message[] messages, String folderName, boolean isMove) throws MessagingException { String[] uids = new String[messages.length]; for (int i = 0, count = messages.length; i < count; i++) { uids[i] = messages[i].getUid(); } String messageBody = ""; HashMap<String, String> headers = new HashMap<String, String>(); HashMap<String, String> uidToUrl = getMessageUrls(uids); String[] urls = new String[uids.length]; for (int i = 0, count = uids.length; i < count; i++) { urls[i] = uidToUrl.get(uids[i]); if (urls[i] == null && messages[i] instanceof WebDavMessage) { WebDavMessage wdMessage = (WebDavMessage)messages[i]; urls[i] = wdMessage.getUrl(); } } messageBody = getMoveOrCopyMessagesReadXml(urls, isMove); WebDavFolder destFolder = (WebDavFolder)store.getFolder(folderName); headers.put("Destination", destFolder.mFolderUrl); headers.put("Brief", "t"); headers.put("If-Match", "*"); String action = (isMove ? "BMOVE" : "BCOPY"); Log.i(K9.LOG_TAG, "Moving " + messages.length + " messages to " + destFolder.mFolderUrl); processRequest(mFolderUrl, action, messageBody, headers, false); } private int getMessageCount(boolean read, CookieStore authCookies) throws MessagingException { String isRead; int messageCount = 0; DataSet dataset = new DataSet(); HashMap<String, String> headers = new HashMap<String, String>(); String messageBody; if (read) { isRead = "True"; } else { isRead = "False"; } messageBody = getMessageCountXml(isRead); headers.put("Brief", "t"); dataset = processRequest(this.mFolderUrl, "SEARCH", messageBody, headers); if (dataset != null) { messageCount = dataset.getMessageCount(); } return messageCount; } @Override public int getMessageCount() throws MessagingException { open(OpenMode.READ_WRITE); this.mMessageCount = getMessageCount(true, WebDavStore.this.mAuthCookies); return this.mMessageCount; } @Override public int getUnreadMessageCount() throws MessagingException { open(OpenMode.READ_WRITE); this.mUnreadMessageCount = getMessageCount(false, WebDavStore.this.mAuthCookies); return this.mUnreadMessageCount; } @Override public boolean isOpen() { return this.mIsOpen; } @Override public OpenMode getMode() throws MessagingException { return OpenMode.READ_WRITE; } @Override public String getName() { return this.mName; } @Override public boolean exists() { return true; } @Override public void close() { this.mMessageCount = 0; this.mUnreadMessageCount = 0; this.mIsOpen = false; } @Override public boolean create(FolderType type) throws MessagingException { return true; } @Override public void delete(boolean recursive) throws MessagingException { throw new Error("WebDavFolder.delete() not implemeneted"); } @Override public Message getMessage(String uid) throws MessagingException { return new WebDavMessage(uid, this); } @Override public Message[] getMessages(int start, int end, MessageRetrievalListener listener) throws MessagingException { ArrayList<Message> messages = new ArrayList<Message>(); String[] uids; DataSet dataset = new DataSet(); HashMap<String, String> headers = new HashMap<String, String>(); int uidsLength = -1; String messageBody; int prevStart = start; /** Reverse the message range since 0 index is newest */ start = this.mMessageCount - end; end = start + (end - prevStart); //end = this.mMessageCount - prevStart; if (start < 0 || end < 0 || end < start) { throw new MessagingException(String.format("Invalid message set %d %d", start, end)); } if (start == 0 && end < 10) { end = 10; } /** Verify authentication */ messageBody = getMessagesXml(); headers.put("Brief", "t"); headers.put("Range", "rows=" + start + "-" + end); dataset = processRequest(this.mFolderUrl, "SEARCH", messageBody, headers); uids = dataset.getUids(); HashMap<String, String> uidToUrl = dataset.getUidToUrl(); uidsLength = uids.length; for (int i = 0; i < uidsLength; i++) { if (listener != null) { listener.messageStarted(uids[i], i, uidsLength); } WebDavMessage message = new WebDavMessage(uids[i], this); message.setUrl(uidToUrl.get(uids[i])); messages.add(message); if (listener != null) { listener.messageFinished(message, i, uidsLength); } } return messages.toArray(new Message[] {}); } @Override public Message[] getMessages(MessageRetrievalListener listener) throws MessagingException { return getMessages(null, listener); } @Override public Message[] getMessages(String[] uids, MessageRetrievalListener listener) throws MessagingException { ArrayList<Message> messageList = new ArrayList<Message>(); Message[] messages; if (uids == null || uids.length == 0) { return messageList.toArray(new Message[] {}); } for (int i = 0, count = uids.length; i < count; i++) { if (listener != null) { listener.messageStarted(uids[i], i, count); } WebDavMessage message = new WebDavMessage(uids[i], this); messageList.add(message); if (listener != null) { listener.messageFinished(message, i, count); } } messages = messageList.toArray(new Message[] {}); return messages; } private HashMap<String, String> getMessageUrls(String[] uids) throws MessagingException { HashMap<String, String> uidToUrl = new HashMap<String, String>(); HashMap<String, String> headers = new HashMap<String, String>(); DataSet dataset = new DataSet(); String messageBody; /** Retrieve and parse the XML entity for our messages */ messageBody = getMessageUrlsXml(uids); headers.put("Brief", "t"); dataset = processRequest(this.mFolderUrl, "SEARCH", messageBody, headers); uidToUrl = dataset.getUidToUrl(); return uidToUrl; } @Override public void fetch(Message[] messages, FetchProfile fp, MessageRetrievalListener listener) throws MessagingException { if (messages == null || messages.length == 0) { return; } /** * Fetch message envelope information for the array */ if (fp.contains(FetchProfile.Item.ENVELOPE)) { fetchEnvelope(messages, listener); } /** * Fetch message flag info for the array */ if (fp.contains(FetchProfile.Item.FLAGS)) { fetchFlags(messages, listener); } if (fp.contains(FetchProfile.Item.BODY_SANE)) { fetchMessages(messages, listener, FETCH_BODY_SANE_SUGGESTED_SIZE / 76); } if (fp.contains(FetchProfile.Item.BODY)) { fetchMessages(messages, listener, -1); } // if (fp.contains(FetchProfile.Item.STRUCTURE)) { // for (int i = 0, count = messages.length; i < count; i++) { // if (!(messages[i] instanceof WebDavMessage)) { // throw new MessagingException("WebDavStore fetch called with non-WebDavMessage"); // } // WebDavMessage wdMessage = (WebDavMessage) messages[i]; // // if (listener != null) { // listener.messageStarted(wdMessage.getUid(), i, count); // } // // wdMessage.setBody(null); // // if (listener != null) { // listener.messageFinished(wdMessage, i, count); // } // } // } } /** * Fetches the full messages or up to lines lines and passes them to the message parser. */ private void fetchMessages(Message[] messages, MessageRetrievalListener listener, int lines) throws MessagingException { WebDavHttpClient httpclient; httpclient = getHttpClient(); /** * We can't hand off to processRequest() since we need the stream to parse. */ for (int i = 0, count = messages.length; i < count; i++) { WebDavMessage wdMessage; int statusCode = 0; if (!(messages[i] instanceof WebDavMessage)) { throw new MessagingException("WebDavStore fetch called with non-WebDavMessage"); } wdMessage = (WebDavMessage) messages[i]; if (listener != null) { listener.messageStarted(wdMessage.getUid(), i, count); } /** * If fetch is called outside of the initial list (ie, a locally stored * message), it may not have a URL associated. Verify and fix that */ if (wdMessage.getUrl().equals("")) { wdMessage.setUrl(getMessageUrls(new String[] {wdMessage.getUid()}).get(wdMessage.getUid())); Log.i(K9.LOG_TAG, "Fetching messages with UID = '" + wdMessage.getUid() + "', URL = '" + wdMessage.getUrl() + "'"); if (wdMessage.getUrl().equals("")) { throw new MessagingException("Unable to get URL for message"); } } try { Log.i(K9.LOG_TAG, "Fetching message with UID = '" + wdMessage.getUid() + "', URL = '" + wdMessage.getUrl() + "'"); HttpGet httpget = new HttpGet(new URI(wdMessage.getUrl())); HttpResponse response; HttpEntity entity; httpget.setHeader("translate", "f"); if (mAuthString != null && mAuthenticated) { httpget.setHeader("Authorization", mAuthString); } response = httpclient.executeOverride(httpget); statusCode = response.getStatusLine().getStatusCode(); entity = response.getEntity(); if (statusCode < 200 || statusCode > 300) { throw new IOException("Error during with code " + statusCode + " during fetch: " + response.getStatusLine().toString()); } if (entity != null) { InputStream istream = null; StringBuffer buffer = new StringBuffer(); String tempText = ""; String resultText = ""; BufferedReader reader; int currentLines = 0; istream = WebDavHttpClient.getUngzippedContent(entity); if (lines != -1) { reader = new BufferedReader(new InputStreamReader(istream), 8192); while ((tempText = reader.readLine()) != null && (currentLines < lines)) { buffer.append(tempText+"\r\n"); currentLines++; } istream.close(); resultText = buffer.toString(); istream = new ByteArrayInputStream(resultText.getBytes("UTF-8")); } wdMessage.parse(istream); } } catch (IllegalArgumentException iae) { Log.e(K9.LOG_TAG, "IllegalArgumentException caught " + iae + "\nTrace: " + processException(iae)); throw new MessagingException("IllegalArgumentException caught", iae); } catch (URISyntaxException use) { Log.e(K9.LOG_TAG, "URISyntaxException caught " + use + "\nTrace: " + processException(use)); throw new MessagingException("URISyntaxException caught", use); } catch (IOException ioe) { Log.e(K9.LOG_TAG, "Non-success response code loading message, response code was " + statusCode + "\nURL: " + wdMessage.getUrl() + "\nError: " + ioe.getMessage() + "\nTrace: " + processException(ioe)); throw new MessagingException("Failure code " + statusCode, ioe); } if (listener != null) { listener.messageFinished(wdMessage, i, count); } } } /** * Fetches and sets the message flags for the supplied messages. * The idea is to have this be recursive so that we do a series of medium calls * instead of one large massive call or a large number of smaller calls. */ private void fetchFlags(Message[] startMessages, MessageRetrievalListener listener) throws MessagingException { HashMap<String, Boolean> uidToReadStatus = new HashMap<String, Boolean>(); HashMap<String, String> headers = new HashMap<String, String>(); DataSet dataset = new DataSet(); String messageBody = ""; Message[] messages = new Message[20]; String[] uids; if (startMessages == null || startMessages.length == 0) { return; } if (startMessages.length > 20) { Message[] newMessages = new Message[startMessages.length - 20]; for (int i = 0, count = startMessages.length; i < count; i++) { if (i < 20) { messages[i] = startMessages[i]; } else { newMessages[i - 20] = startMessages[i]; } } fetchFlags(newMessages, listener); } else { messages = startMessages; } uids = new String[messages.length]; for (int i = 0, count = messages.length; i < count; i++) { uids[i] = messages[i].getUid(); } messageBody = getMessageFlagsXml(uids); headers.put("Brief", "t"); dataset = processRequest(this.mFolderUrl, "SEARCH", messageBody, headers); if (dataset == null) { throw new MessagingException("Data Set from request was null"); } uidToReadStatus = dataset.getUidToRead(); for (int i = 0, count = messages.length; i < count; i++) { if (!(messages[i] instanceof WebDavMessage)) { throw new MessagingException("WebDavStore fetch called with non-WebDavMessage"); } WebDavMessage wdMessage = (WebDavMessage) messages[i]; if (listener != null) { listener.messageStarted(messages[i].getUid(), i, count); } wdMessage.setFlagInternal(Flag.SEEN, uidToReadStatus.get(wdMessage.getUid())); if (listener != null) { listener.messageFinished(messages[i], i, count); } } } /** * Fetches and parses the message envelopes for the supplied messages. * The idea is to have this be recursive so that we do a series of medium calls * instead of one large massive call or a large number of smaller calls. * Call it a happy balance */ private void fetchEnvelope(Message[] startMessages, MessageRetrievalListener listener) throws MessagingException { HashMap<String, ParsedMessageEnvelope> envelopes = new HashMap<String, ParsedMessageEnvelope>(); HashMap<String, String> headers = new HashMap<String, String>(); DataSet dataset = new DataSet(); String messageBody = ""; String[] uids; Message[] messages = new Message[10]; if (startMessages == null || startMessages.length == 0) { return; } if (startMessages.length > 10) { Message[] newMessages = new Message[startMessages.length - 10]; for (int i = 0, count = startMessages.length; i < count; i++) { if (i < 10) { messages[i] = startMessages[i]; } else { newMessages[i - 10] = startMessages[i]; } } fetchEnvelope(newMessages, listener); } else { messages = startMessages; } uids = new String[messages.length]; for (int i = 0, count = messages.length; i < count; i++) { uids[i] = messages[i].getUid(); } messageBody = getMessageEnvelopeXml(uids); headers.put("Brief", "t"); dataset = processRequest(this.mFolderUrl, "SEARCH", messageBody, headers); envelopes = dataset.getMessageEnvelopes(); int count = messages.length; for (int i = messages.length - 1; i >= 0; i--) { if (!(messages[i] instanceof WebDavMessage)) { throw new MessagingException("WebDavStore fetch called with non-WebDavMessage"); } WebDavMessage wdMessage = (WebDavMessage) messages[i]; if (listener != null) { listener.messageStarted(messages[i].getUid(), i, count); } wdMessage.setNewHeaders(envelopes.get(wdMessage.getUid())); wdMessage.setFlagInternal(Flag.SEEN, envelopes.get(wdMessage.getUid()).getReadStatus()); if (listener != null) { listener.messageFinished(messages[i], i, count); } } } @Override public Flag[] getPermanentFlags() throws MessagingException { return PERMANENT_FLAGS; } @Override public void setFlags(Message[] messages, Flag[] flags, boolean value) throws MessagingException { String[] uids = new String[messages.length]; for (int i = 0, count = messages.length; i < count; i++) { uids[i] = messages[i].getUid(); } for (int i = 0, count = flags.length; i < count; i++) { Flag flag = flags[i]; if (flag == Flag.SEEN) { markServerMessagesRead(uids, value); } else if (flag == Flag.DELETED) { deleteServerMessages(uids); } } } private void markServerMessagesRead(String[] uids, boolean read) throws MessagingException { String messageBody = ""; HashMap<String, String> headers = new HashMap<String, String>(); HashMap<String, String> uidToUrl = getMessageUrls(uids); DataSet dataset = new DataSet(); String[] urls = new String[uids.length]; for (int i = 0, count = uids.length; i < count; i++) { urls[i] = uidToUrl.get(uids[i]); } messageBody = getMarkMessagesReadXml(urls, read); headers.put("Brief", "t"); headers.put("If-Match", "*"); processRequest(this.mFolderUrl, "BPROPPATCH", messageBody, headers, false); } private void deleteServerMessages(String[] uids) throws MessagingException { HashMap<String, String> uidToUrl = getMessageUrls(uids); String[] urls = new String[uids.length]; for (int i = 0, count = uids.length; i < count; i++) { HashMap<String, String> headers = new HashMap<String, String>(); String uid = uids[i]; String url = uidToUrl.get(uid); String destinationUrl = generateDeleteUrl(url); /** * If the destination is the same as the origin, assume delete forever */ if (destinationUrl.equals(url)) { headers.put("Brief", "t"); processRequest(url, "DELETE", null, headers, false); } else { headers.put("Destination", generateDeleteUrl(url)); headers.put("Brief", "t"); processRequest(url, "MOVE", null, headers, false); } } } private String generateDeleteUrl(String startUrl) { String[] urlParts = startUrl.split("/"); String filename = urlParts[urlParts.length - 1]; String finalUrl = WebDavStore.this.mUrl + "Deleted%20Items/" + filename; return finalUrl; } @Override public void appendMessages(Message[] messages) throws MessagingException { appendWebDavMessages(messages); } public Message[] appendWebDavMessages(Message[] messages) throws MessagingException { Message[] retMessages = new Message[messages.length]; int ind = 0; WebDavHttpClient httpclient = getHttpClient(); for (Message message : messages) { HttpGeneric httpmethod; HttpResponse response; StringEntity bodyEntity; int statusCode; try { String subject; try { subject = message.getSubject(); } catch (MessagingException e) { Log.e(K9.LOG_TAG, "MessagingException while retrieving Subject: " + e); subject = ""; } ByteArrayOutputStream out; try { out = new ByteArrayOutputStream(message.getSize()); } catch (MessagingException e) { Log.e(K9.LOG_TAG, "MessagingException while getting size of message: " + e); out = new ByteArrayOutputStream(); } open(OpenMode.READ_WRITE); - message.writeTo( - new EOLConvertingOutputStream( - new BufferedOutputStream(out, 1024))); + EOLConvertingOutputStream msgOut = new EOLConvertingOutputStream( + new BufferedOutputStream(out, 1024)); + message.writeTo(msgOut); + msgOut.flush(); bodyEntity = new StringEntity(out.toString(), "UTF-8"); bodyEntity.setContentType("message/rfc822"); String messageURL = mFolderUrl; if (messageURL.endsWith("/") == false) { messageURL += "/"; } messageURL += URLEncoder.encode(message.getUid() + ":" + System.currentTimeMillis() + ".eml"); Log.i(K9.LOG_TAG, "Uploading message as " + messageURL); httpmethod = new HttpGeneric(messageURL); httpmethod.setMethod("PUT"); httpmethod.setEntity(bodyEntity); String mAuthString = getAuthString(); if (mAuthString != null) { httpmethod.setHeader("Authorization", mAuthString); } response = httpclient.executeOverride(httpmethod); statusCode = response.getStatusLine().getStatusCode(); if (statusCode < 200 || statusCode > 300) { throw new IOException("Error with status code " + statusCode + " while sending/appending message. Response = " + response.getStatusLine().toString() + " for message " + messageURL); } WebDavMessage retMessage = new WebDavMessage(message.getUid(), this); retMessage.setUrl(messageURL); retMessages[ind++] = retMessage; } catch (Exception e) { throw new MessagingException("Unable to append", e); } } return retMessages; } @Override public boolean equals(Object o) { return false; } public String getUidFromMessageId(Message message) throws MessagingException { Log.e(K9.LOG_TAG, "Unimplemented method getUidFromMessageId in WebDavStore.WebDavFolder could lead to duplicate messages " + " being uploaded to the Sent folder"); return null; } public void setFlags(Flag[] flags, boolean value) throws MessagingException { Log.e(K9.LOG_TAG, "Unimplemented method setFlags(Flag[], boolean) breaks markAllMessagesAsRead and EmptyTrash"); // Try to make this efficient by not retrieving all of the messages return; } } /** * A WebDav Message */ class WebDavMessage extends MimeMessage { private String mUrl = ""; WebDavMessage(String uid, Folder folder) throws MessagingException { this.mUid = uid; this.mFolder = folder; } public void setUrl(String url) { //TODO: This is a not as ugly hack (ie, it will actually work) //XXX: prevent URLs from getting to us that are broken if (!(url.toLowerCase().contains("http"))) { if (!(url.startsWith("/"))) { url = "/" + url; } url = WebDavStore.this.mUrl + this.mFolder + url; } String[] urlParts = url.split("/"); int length = urlParts.length; String end = urlParts[length - 1]; this.mUrl = ""; url = ""; /** * We have to decode, then encode the URL because Exchange likes to * not properly encode all characters */ try { end = java.net.URLDecoder.decode(end, "UTF-8"); end = java.net.URLEncoder.encode(end, "UTF-8"); end = end.replaceAll("\\+", "%20"); } catch (UnsupportedEncodingException uee) { Log.e(K9.LOG_TAG, "UnsupportedEncodingException caught in setUrl: " + uee + "\nTrace: " + processException(uee)); } catch (IllegalArgumentException iae) { Log.e(K9.LOG_TAG, "IllegalArgumentException caught in setUrl: " + iae + "\nTrace: " + processException(iae)); } for (int i = 0; i < length - 1; i++) { if (i != 0) { url = url + "/" + urlParts[i]; } else { url = urlParts[i]; } } url = url + "/" + end; this.mUrl = url; } public String getUrl() { return this.mUrl; } public void setSize(int size) { this.mSize = size; } public void parse(InputStream in) throws IOException, MessagingException { super.parse(in); } public void setFlagInternal(Flag flag, boolean set) throws MessagingException { super.setFlag(flag, set); } public void setNewHeaders(ParsedMessageEnvelope envelope) throws MessagingException { String[] headers = envelope.getHeaderList(); HashMap<String, String> messageHeaders = envelope.getMessageHeaders(); for (int i = 0, count = headers.length; i < count; i++) { String headerValue = messageHeaders.get(headers[i]); if (headers[i].equals("Content-Length")) { int size = Integer.parseInt(messageHeaders.get(headers[i])); this.setSize(size); } if (headerValue != null && !headerValue.equals("")) { this.addHeader(headers[i], headerValue); } } } @Override public void delete(String trashFolderName) throws MessagingException { WebDavFolder wdFolder = (WebDavFolder)getFolder(); Log.i(K9.LOG_TAG, "Deleting message by moving to " + trashFolderName); wdFolder.moveMessages(new Message[] { this }, wdFolder.getStore().getFolder(trashFolderName)); } @Override public void setFlag(Flag flag, boolean set) throws MessagingException { super.setFlag(flag, set); mFolder.setFlags(new Message[] { this }, new Flag[] { flag }, set); } } /** * XML Parsing Handler * Can handle all XML handling needs */ public class WebDavHandler extends DefaultHandler { private DataSet mDataSet = new DataSet(); private Stack<String> mOpenTags = new Stack<String>(); public DataSet getDataSet() { return this.mDataSet; } @Override public void startDocument() throws SAXException { this.mDataSet = new DataSet(); } @Override public void endDocument() throws SAXException { /* Do nothing */ } @Override public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { mOpenTags.push(localName); } @Override public void endElement(String namespaceURI, String localName, String qName) { mOpenTags.pop(); /** Reset the hash temp variables */ if (localName.equals("response")) { this.mDataSet.finish(); } } @Override public void characters(char ch[], int start, int length) { String value = new String(ch, start, length); mDataSet.addValue(value, mOpenTags.peek()); } } /** * Data set for a single E-Mail message's required headers (the envelope) * Only provides accessor methods to the stored data. All processing should be * done elsewhere. This is done rather than having multiple hashmaps * associating UIDs to values */ public class ParsedMessageEnvelope { /** * Holds the mappings from the name returned from Exchange to the MIME format header name */ private final HashMap<String, String> mHeaderMappings = new HashMap<String, String>() { { put("mime-version", "MIME-Version"); put("content-type", "Content-Type"); put("subject", "Subject"); put("date", "Date"); put("thread-topic", "Thread-Topic"); put("thread-index", "Thread-Index"); put("from", "From"); put("to", "To"); put("in-reply-to", "In-Reply-To"); put("cc", "Cc"); put("getcontentlength", "Content-Length"); } }; private boolean mReadStatus = false; private String mUid = ""; private HashMap<String, String> mMessageHeaders = new HashMap<String, String>(); private ArrayList<String> mHeaders = new ArrayList<String>(); public void addHeader(String field, String value) { String headerName = mHeaderMappings.get(field); //Log.i(K9.LOG_TAG, "header " + headerName + " = '" + value + "'"); if (headerName != null) { this.mMessageHeaders.put(mHeaderMappings.get(field), value); this.mHeaders.add(mHeaderMappings.get(field)); } } public HashMap<String, String> getMessageHeaders() { return this.mMessageHeaders; } public String[] getHeaderList() { return this.mHeaders.toArray(new String[] {}); } public void setReadStatus(boolean status) { this.mReadStatus = status; } public boolean getReadStatus() { return this.mReadStatus; } public void setUid(String uid) { if (uid != null) { this.mUid = uid; } } public String getUid() { return this.mUid; } } /** * Dataset for all XML parses. * Data is stored in a single format inside the class and is formatted appropriately depending on the accessor calls made. */ public class DataSet { private HashMap<String, HashMap> mData = new HashMap<String, HashMap>(); private HashMap<String, String> mLostData = new HashMap<String, String>(); private String mUid = ""; private HashMap<String, String> mTempData = new HashMap<String, String>(); public void addValue(String value, String tagName) { if (tagName.equals("uid")) { mUid = value; } if (mTempData.containsKey(tagName)) { mTempData.put(tagName, mTempData.get(tagName) + value); } else { mTempData.put(tagName, value); } } public void finish() { if (mUid != null && mTempData != null) { mData.put(mUid, mTempData); } else if (mTempData != null) { /* Lost Data are for requests that don't include a message UID. * These requests should only have a depth of one for the response so it will never get stomped over. */ mLostData = mTempData; String visibleCount = mLostData.get("visiblecount"); } mUid = ""; mTempData = new HashMap<String, String>(); } /** * Returns a hashmap of Message UID => Message Url */ public HashMap<String, String> getUidToUrl() { HashMap<String, String> uidToUrl = new HashMap<String, String>(); for (String uid : mData.keySet()) { HashMap<String, String> data = mData.get(uid); String value = data.get("href"); if (value != null && !value.equals("")) { uidToUrl.put(uid, value); } } return uidToUrl; } /** * Returns a hashmap of Message UID => Read Status */ public HashMap<String, Boolean> getUidToRead() { HashMap<String, Boolean> uidToRead = new HashMap<String, Boolean>(); for (String uid : mData.keySet()) { HashMap<String, String> data = mData.get(uid); String readStatus = data.get("read"); if (readStatus != null && !readStatus.equals("")) { Boolean value = readStatus.equals("0") ? false : true; uidToRead.put(uid, value); } } return uidToRead; } /** * Returns an array of all hrefs (urls) that were received */ public String[] getHrefs() { ArrayList<String> hrefs = new ArrayList<String>(); for (String uid : mData.keySet()) { HashMap<String, String> data = mData.get(uid); String href = data.get("href"); hrefs.add(href); } return hrefs.toArray(new String[] {}); } /** * Return an array of all Message UIDs that were received */ public String[] getUids() { ArrayList<String> uids = new ArrayList<String>(); for (String uid : mData.keySet()) { uids.add(uid); } return uids.toArray(new String[] {}); } /** * Returns the message count as it was retrieved */ public int getMessageCount() { int messageCount = -1; for (String uid : mData.keySet()) { HashMap<String, String> data = mData.get(uid); String count = data.get("visiblecount"); if (count != null && !count.equals("")) { messageCount = Integer.parseInt(count); } } return messageCount; } /** * Returns a HashMap of message UID => ParsedMessageEnvelope */ public HashMap<String, ParsedMessageEnvelope> getMessageEnvelopes() { HashMap<String, ParsedMessageEnvelope> envelopes = new HashMap<String, ParsedMessageEnvelope>(); for (String uid : mData.keySet()) { ParsedMessageEnvelope envelope = new ParsedMessageEnvelope(); HashMap<String, String> data = mData.get(uid); if (data != null) { for (String header : data.keySet()) { if (header.equals("read")) { String read = data.get(header); Boolean readStatus = read.equals("0") ? false : true; envelope.setReadStatus(readStatus); } else if (header.equals("date")) { /** * Exchange doesn't give us rfc822 dates like it claims. The date is in the format: * yyyy-MM-dd'T'HH:mm:ss.SSS<Single digit representation of timezone, so far, all instances are Z> */ String date = data.get(header); date = date.substring(0, date.length() - 1); DateFormat dfInput = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS"); DateFormat dfOutput = new SimpleDateFormat("EEE, d MMM yy HH:mm:ss Z"); String tempDate = ""; try { Date parsedDate = dfInput.parse(date); tempDate = dfOutput.format(parsedDate); } catch (java.text.ParseException pe) { Log.e(K9.LOG_TAG, "Error parsing date: "+ pe + "\nTrace: " + processException(pe)); } envelope.addHeader(header, tempDate); } else { envelope.addHeader(header, data.get(header)); } } } if (envelope != null) { envelopes.put(uid, envelope); } } return envelopes; } } /** * New HTTP Method that allows changing of the method and generic handling * Needed for WebDAV custom methods such as SEARCH and PROPFIND */ public class HttpGeneric extends HttpEntityEnclosingRequestBase { public String METHOD_NAME = "POST"; public HttpGeneric() { super(); } public HttpGeneric(final URI uri) { super(); setURI(uri); } /** * @throws IllegalArgumentException if the uri is invalid. */ public HttpGeneric(final String uri) { super(); if (K9.DEBUG) { Log.v(K9.LOG_TAG, "Starting uri = '" + uri + "'"); } String[] urlParts = uri.split("/"); int length = urlParts.length; String end = urlParts[length - 1]; String url = ""; /** * We have to decode, then encode the URL because Exchange likes to * not properly encode all characters */ try { if (length > 3) { end = java.net.URLDecoder.decode(end, "UTF-8"); end = java.net.URLEncoder.encode(end, "UTF-8"); end = end.replaceAll("\\+", "%20"); } } catch (UnsupportedEncodingException uee) { Log.e(K9.LOG_TAG, "UnsupportedEncodingException caught in HttpGeneric(String uri): " + uee + "\nTrace: " + processException(uee)); } catch (IllegalArgumentException iae) { Log.e(K9.LOG_TAG, "IllegalArgumentException caught in HttpGeneric(String uri): " + iae + "\nTrace: " + processException(iae)); } for (int i = 0; i < length - 1; i++) { if (i != 0) { url = url + "/" + urlParts[i]; } else { url = urlParts[i]; } } if (K9.DEBUG) { Log.v(K9.LOG_TAG, "url = '" + url + "' length = " + url.length() + ", end = '" + end + "' length = " + end.length()); } url = url + "/" + end; Log.i(K9.LOG_TAG, "url = " + url); setURI(URI.create(url)); } @Override public String getMethod() { return METHOD_NAME; } public void setMethod(String method) { if (method != null) { METHOD_NAME = method; } } } public static class WebDavHttpClient extends DefaultHttpClient { /* * 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. */ public static void modifyRequestToAcceptGzipResponse(HttpRequest request) { Log.i(K9.LOG_TAG, "Requesting gzipped data"); request.addHeader("Accept-Encoding", "gzip"); } public static InputStream getUngzippedContent(HttpEntity entity) throws IOException { InputStream responseStream = entity.getContent(); if (responseStream == null) return responseStream; Header header = entity.getContentEncoding(); if (header == null) return responseStream; String contentEncoding = header.getValue(); if (contentEncoding == null) return responseStream; if (contentEncoding.contains("gzip")) { Log.i(K9.LOG_TAG, "Response is gzipped"); responseStream = new GZIPInputStream(responseStream); } return responseStream; } public HttpResponse executeOverride(HttpUriRequest request) throws IOException { modifyRequestToAcceptGzipResponse(request); return super.execute(request); } } }
true
true
public void doFBA() throws IOException, MessagingException { /* public CookieStore doAuthentication(String username, String password, String url) throws IOException, MessagingException {*/ String authPath; String url = this.mUrl; String username = this.mUsername; String password = this.mPassword; String[] urlParts = url.split("/"); String finalUrl = ""; String loginUrl = ""; String destinationUrl = ""; if (this.mAuthPath != null && !this.mAuthPath.equals("") && !this.mAuthPath.equals("/")) { authPath = this.mAuthPath; } else { authPath = "/exchweb/bin/auth/owaauth.dll"; } for (int i = 0; i <= 2; i++) { if (i != 0) { finalUrl = finalUrl + "/" + urlParts[i]; } else { finalUrl = urlParts[i]; } } if (finalUrl.equals("")) { throw new MessagingException("doFBA failed, unable to construct URL to post login credentials to."); } loginUrl = finalUrl + authPath; try { /* Browser Client */ WebDavHttpClient httpclient = mHttpClient; /** * This is in a separate block because I really don't like how it's done. * This basically scrapes the OWA login page for the form submission URL. * UGLY!WebDavHttpClient * Added an if-check to see if there's a user supplied authentication path for FBA */ if (this.mAuthPath == null || this.mAuthPath.equals("") || this.mAuthPath.equals("/")) { httpclient.addRequestInterceptor(new HttpRequestInterceptor() { public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { mRedirectUrl = ((HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST)).toURI() + request.getRequestLine().getUri(); } }); HashMap<String, String> headers = new HashMap<String, String>(); InputStream istream = sendRequest(finalUrl, "GET", null, headers, false); if (istream != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(istream), 4096); String tempText = ""; boolean matched = false; while ((tempText = reader.readLine()) != null && !matched) { if (tempText.indexOf(" action") >= 0) { String[] tagParts = tempText.split("\""); if (tagParts[1].lastIndexOf('/') < 0 && mRedirectUrl != null && !mRedirectUrl.equals("")) { /* We have to do a multi-stage substring here because of potential GET parameters */ mRedirectUrl = mRedirectUrl.substring(0, mRedirectUrl.lastIndexOf('?')); mRedirectUrl = mRedirectUrl.substring(0, mRedirectUrl.lastIndexOf('/')); loginUrl = mRedirectUrl + "/" + tagParts[1]; this.mAuthPath = "/" + tagParts[1]; } else { loginUrl = finalUrl + tagParts[1]; this.mAuthPath = "/" + tagParts[1]; } } if (tempText.indexOf("destination") >= 0) { String[] tagParts = tempText.split("value"); if (tagParts[1] != null) { String[] valueParts = tagParts[1].split("\""); destinationUrl = valueParts[1]; matched = true; } } } istream.close(); } } /** Build the POST data to use */ ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>(); pairs.add(new BasicNameValuePair("username", username)); pairs.add(new BasicNameValuePair("password", password)); if (this.mMailboxPath != null && !this.mMailboxPath.equals("")) { pairs.add(new BasicNameValuePair("destination", finalUrl + this.mMailboxPath)); } else if (destinationUrl != null && !destinationUrl.equals("")) { pairs.add(new BasicNameValuePair("destination", destinationUrl)); } else { pairs.add(new BasicNameValuePair("destination", "/")); } pairs.add(new BasicNameValuePair("flags", "0")); pairs.add(new BasicNameValuePair("SubmitCreds", "Log+On")); pairs.add(new BasicNameValuePair("forcedownlevel", "0")); pairs.add(new BasicNameValuePair("trusted", "0")); try { UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(pairs); HashMap<String, String> headers = new HashMap<String, String>(); String tempUrl = ""; InputStream istream = sendRequest(loginUrl, "POST", formEntity, headers, false); /** Get the URL for the mailbox and set it for the store */ if (istream != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(istream), 8192); String tempText = ""; while ((tempText = reader.readLine()) != null) { if (tempText.indexOf("BASE href") >= 0) { String[] tagParts = tempText.split("\""); tempUrl = tagParts[1]; } } } if (this.mMailboxPath != null && !this.mMailboxPath.equals("")) { this.mUrl = finalUrl + "/" + this.mMailboxPath + "/"; } else if (tempUrl.equals("")) { this.mUrl = finalUrl + "/Exchange/" + this.alias + "/"; } else { this.mUrl = tempUrl; } } catch (UnsupportedEncodingException uee) { Log.e(K9.LOG_TAG, "Error encoding POST data for authentication: " + uee + "\nTrace: " + processException(uee)); throw new MessagingException("Error encoding POST data for authentication", uee); } } catch (SSLException e) { throw new CertificateValidationException(e.getMessage(), e); } this.mAuthenticated = true; } public CookieStore getAuthCookies() { return mAuthCookies; } public String getAlias() { return alias; } public String getUrl() { return mUrl; } public WebDavHttpClient getHttpClient() throws MessagingException { SchemeRegistry reg; Scheme s; boolean needAuth = false; if (mHttpClient == null) { mHttpClient = new WebDavHttpClient(); needAuth = true; } reg = mHttpClient.getConnectionManager().getSchemeRegistry(); try { // Log.i(K9.LOG_TAG, "getHttpClient mHost = " + mHost); s = new Scheme("https", new TrustedSocketFactory(mHost, mSecure), 443); } catch (NoSuchAlgorithmException nsa) { Log.e(K9.LOG_TAG, "NoSuchAlgorithmException in getHttpClient: " + nsa); throw new MessagingException("NoSuchAlgorithmException in getHttpClient: " + nsa); } catch (KeyManagementException kme) { Log.e(K9.LOG_TAG, "KeyManagementException in getHttpClient: " + kme); throw new MessagingException("KeyManagementException in getHttpClient: " + kme); } reg.register(s); if (needAuth) { HashMap<String, String> headers = new HashMap<String, String>(); processRequest(this.mUrl, "GET", null, headers, false); } /* if (needAuth()) { if (!checkAuth()) { try { CookieStore cookies = mHttpClient.getCookieStore(); cookies.clear(); mHttpClient.setCookieStore(cookies); cookies = doAuthentication(this.mUsername, this.mPassword, this.mUrl); if (cookies != null) { this.mAuthenticated = true; this.mLastAuth = System.currentTimeMillis()/1000; } mHttpClient.setCookieStore(cookies); } catch (IOException ioe) { Log.e(K9.LOG_TAG, "IOException: " + ioe + "\nTrace: " + processException(ioe)); } } else { Credentials creds = new UsernamePasswordCredentials(mUsername, mPassword); CredentialsProvider credsProvider = mHttpClient.getCredentialsProvider(); credsProvider.setCredentials(new AuthScope(mHost, 80, AuthScope.ANY_REALM), creds); credsProvider.setCredentials(new AuthScope(mHost, 443, AuthScope.ANY_REALM), creds); credsProvider.setCredentials(new AuthScope(mHost, mUri.getPort(), AuthScope.ANY_REALM), creds); mHttpClient.setCredentialsProvider(credsProvider); // Assume we're authenticated and ok here since the checkAuth() was 401 and we've now set the credentials this.mAuthenticated = true; this.mLastAuth = System.currentTimeMillis()/1000; } } */ return mHttpClient; } public WebDavHttpClient getTrustedHttpClient() throws KeyManagementException, NoSuchAlgorithmException { if (mHttpClient == null) { mHttpClient = new WebDavHttpClient(); SchemeRegistry reg = mHttpClient.getConnectionManager().getSchemeRegistry(); Scheme s = new Scheme("https",new TrustedSocketFactory(mHost,mSecure),443); reg.register(s); //Add credentials for NTLM/Digest/Basic Auth Credentials creds = new UsernamePasswordCredentials(mUsername, mPassword); CredentialsProvider credsProvider = mHttpClient.getCredentialsProvider(); // setting AuthScope for 80 and 443, in case we end up getting redirected // from 80 to 443. credsProvider.setCredentials(new AuthScope(mHost, 80, AuthScope.ANY_REALM), creds); credsProvider.setCredentials(new AuthScope(mHost, 443, AuthScope.ANY_REALM), creds); credsProvider.setCredentials(new AuthScope(mHost, mUri.getPort(), AuthScope.ANY_REALM), creds); mHttpClient.setCredentialsProvider(credsProvider); } return mHttpClient; } private InputStream sendRequest(String url, String method, StringEntity messageBody, HashMap<String, String> headers, boolean tryAuth) throws MessagingException { WebDavHttpClient httpclient; InputStream istream = null; if (url == null || method == null) { return istream; } httpclient = getHttpClient(); try { int statusCode = -1; StringEntity messageEntity = null; HttpGeneric httpmethod = new HttpGeneric(url); HttpResponse response; HttpEntity entity; if (messageBody != null) { httpmethod.setEntity(messageBody); } for (String headerName : headers.keySet()) { httpmethod.setHeader(headerName, headers.get(headerName)); } if (mAuthString != null && mAuthenticated) { httpmethod.setHeader("Authorization", mAuthString); } httpmethod.setMethod(method); response = httpclient.executeOverride(httpmethod); statusCode = response.getStatusLine().getStatusCode(); entity = response.getEntity(); if (statusCode == 401) { if (tryAuth) { mAuthenticated = true; sendRequest(url, method, messageBody, headers, false); } else { throw new MessagingException("Invalid username or password for Basic authentication"); } } else if (statusCode == 440) { if (tryAuth) { doFBA(); sendRequest(url, method, messageBody, headers, false); } else { throw new MessagingException("Authentication failure in sendRequest"); } } else if (statusCode < 200 || statusCode >= 300) { throw new IOException("Error with code " + statusCode + " during request processing: "+ response.getStatusLine().toString()); } else { if (tryAuth && mAuthenticated == false) { doFBA(); sendRequest(url, method, messageBody, headers, false); } } if (entity != null) { istream = WebDavHttpClient.getUngzippedContent(entity); } } catch (UnsupportedEncodingException uee) { Log.e(K9.LOG_TAG, "UnsupportedEncodingException: " + uee + "\nTrace: " + processException(uee)); throw new MessagingException("UnsupportedEncodingException", uee); } catch (IOException ioe) { Log.e(K9.LOG_TAG, "IOException: " + ioe + "\nTrace: " + processException(ioe)); throw new MessagingException("IOException", ioe); } return istream; } public String getAuthString() { return mAuthString; } /** * Performs an httprequest to the supplied url using the supplied method. * messageBody and headers are optional as not all requests will need them. * There are two signatures to support calls that don't require parsing of the response. */ private DataSet processRequest(String url, String method, String messageBody, HashMap<String, String> headers) throws MessagingException { return processRequest(url, method, messageBody, headers, true); } private DataSet processRequest(String url, String method, String messageBody, HashMap<String, String> headers, boolean needsParsing) throws MessagingException { DataSet dataset = new DataSet(); if (K9.DEBUG) { Log.v(K9.LOG_TAG, "processRequest url = '" + url + "', method = '" + method + "', messageBody = '" + messageBody + "'"); } if (url == null || method == null) { return dataset; } getHttpClient(); try { StringEntity messageEntity = null; if (messageBody != null) { messageEntity = new StringEntity(messageBody); messageEntity.setContentType("text/xml"); // httpmethod.setEntity(messageEntity); } InputStream istream = sendRequest(url, method, messageEntity, headers, true); if (istream != null && needsParsing) { try { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); WebDavHandler myHandler = new WebDavHandler(); xr.setContentHandler(myHandler); xr.parse(new InputSource(istream)); dataset = myHandler.getDataSet(); } catch (SAXException se) { Log.e(K9.LOG_TAG, "SAXException in processRequest() " + se + "\nTrace: " + processException(se)); throw new MessagingException("SAXException in processRequest() ", se); } catch (ParserConfigurationException pce) { Log.e(K9.LOG_TAG, "ParserConfigurationException in processRequest() " + pce + "\nTrace: " + processException(pce)); throw new MessagingException("ParserConfigurationException in processRequest() ", pce); } istream.close(); } } catch (UnsupportedEncodingException uee) { Log.e(K9.LOG_TAG, "UnsupportedEncodingException: " + uee + "\nTrace: " + processException(uee)); throw new MessagingException("UnsupportedEncodingException in processRequest() ", uee); } catch (IOException ioe) { Log.e(K9.LOG_TAG, "IOException: " + ioe + "\nTrace: " + processException(ioe)); throw new MessagingException("IOException in processRequest() ", ioe); } return dataset; } /** * Returns a string of the stacktrace for a Throwable to allow for easy inline printing of errors. */ private String processException(Throwable t) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); t.printStackTrace(ps); ps.close(); return baos.toString(); } @Override public boolean isSendCapable() { return true; } @Override public void sendMessages(Message[] messages) throws MessagingException { WebDavFolder tmpFolder = (WebDavStore.WebDavFolder)getFolder(DAV_MAIL_TMP_FOLDER); try { tmpFolder.open(OpenMode.READ_WRITE); Message[] retMessages = tmpFolder.appendWebDavMessages(messages); tmpFolder.moveMessages(retMessages, getSendSpoolFolder()); } finally { if (tmpFolder != null) { tmpFolder.close(); } } } /************************************************************************* * Helper and Inner classes */ /** * A WebDav Folder */ class WebDavFolder extends Folder { private String mName; private String mFolderUrl; private boolean mIsOpen = false; private int mMessageCount = 0; private int mUnreadMessageCount = 0; private WebDavStore store; protected WebDavStore getStore() { return store; } public WebDavFolder(WebDavStore nStore, String name) { super(nStore.getAccount()); store = nStore; this.mName = name; if (DAV_MAIL_SEND_FOLDER.equals(name)) { this.mFolderUrl = getUrl() + "/" + name +"/"; } else { String encodedName = ""; try { String[] urlParts = name.split("/"); String url = ""; for (int i = 0, count = urlParts.length; i < count; i++) { if (i != 0) { url = url + "/" + java.net.URLEncoder.encode(urlParts[i], "UTF-8"); } else { url = java.net.URLEncoder.encode(urlParts[i], "UTF-8"); } } encodedName = url; } catch (UnsupportedEncodingException uee) { Log.e(K9.LOG_TAG, "UnsupportedEncodingException URLEncoding folder name, skipping encoded"); encodedName = name; } encodedName = encodedName.replaceAll("\\+", "%20"); /** * In some instances, it is possible that our folder objects have been collected, * but getPersonalNamespaces() isn't called again (ex. Android destroys the email client). * Perform an authentication to get the appropriate URLs in place again */ // TODO: danapple0 - huh? //getHttpClient(); if (encodedName.equals("INBOX")) { encodedName = "Inbox"; } this.mFolderUrl = WebDavStore.this.mUrl; if (WebDavStore.this.mUrl.endsWith("/") == false) { this.mFolderUrl += "/"; } this.mFolderUrl += encodedName; } } public void setUrl(String url) { if (url != null) { this.mFolderUrl = url; } } @Override public void open(OpenMode mode) throws MessagingException { getHttpClient(); this.mIsOpen = true; } @Override public void copyMessages(Message[] messages, Folder folder) throws MessagingException { moveOrCopyMessages(messages, folder.getName(), false); } @Override public void moveMessages(Message[] messages, Folder folder) throws MessagingException { moveOrCopyMessages(messages, folder.getName(), true); } @Override public void delete(Message[] msgs, String trashFolderName) throws MessagingException { moveOrCopyMessages(msgs, trashFolderName, true); } private void moveOrCopyMessages(Message[] messages, String folderName, boolean isMove) throws MessagingException { String[] uids = new String[messages.length]; for (int i = 0, count = messages.length; i < count; i++) { uids[i] = messages[i].getUid(); } String messageBody = ""; HashMap<String, String> headers = new HashMap<String, String>(); HashMap<String, String> uidToUrl = getMessageUrls(uids); String[] urls = new String[uids.length]; for (int i = 0, count = uids.length; i < count; i++) { urls[i] = uidToUrl.get(uids[i]); if (urls[i] == null && messages[i] instanceof WebDavMessage) { WebDavMessage wdMessage = (WebDavMessage)messages[i]; urls[i] = wdMessage.getUrl(); } } messageBody = getMoveOrCopyMessagesReadXml(urls, isMove); WebDavFolder destFolder = (WebDavFolder)store.getFolder(folderName); headers.put("Destination", destFolder.mFolderUrl); headers.put("Brief", "t"); headers.put("If-Match", "*"); String action = (isMove ? "BMOVE" : "BCOPY"); Log.i(K9.LOG_TAG, "Moving " + messages.length + " messages to " + destFolder.mFolderUrl); processRequest(mFolderUrl, action, messageBody, headers, false); } private int getMessageCount(boolean read, CookieStore authCookies) throws MessagingException { String isRead; int messageCount = 0; DataSet dataset = new DataSet(); HashMap<String, String> headers = new HashMap<String, String>(); String messageBody; if (read) { isRead = "True"; } else { isRead = "False"; } messageBody = getMessageCountXml(isRead); headers.put("Brief", "t"); dataset = processRequest(this.mFolderUrl, "SEARCH", messageBody, headers); if (dataset != null) { messageCount = dataset.getMessageCount(); } return messageCount; } @Override public int getMessageCount() throws MessagingException { open(OpenMode.READ_WRITE); this.mMessageCount = getMessageCount(true, WebDavStore.this.mAuthCookies); return this.mMessageCount; } @Override public int getUnreadMessageCount() throws MessagingException { open(OpenMode.READ_WRITE); this.mUnreadMessageCount = getMessageCount(false, WebDavStore.this.mAuthCookies); return this.mUnreadMessageCount; } @Override public boolean isOpen() { return this.mIsOpen; } @Override public OpenMode getMode() throws MessagingException { return OpenMode.READ_WRITE; } @Override public String getName() { return this.mName; } @Override public boolean exists() { return true; } @Override public void close() { this.mMessageCount = 0; this.mUnreadMessageCount = 0; this.mIsOpen = false; } @Override public boolean create(FolderType type) throws MessagingException { return true; } @Override public void delete(boolean recursive) throws MessagingException { throw new Error("WebDavFolder.delete() not implemeneted"); } @Override public Message getMessage(String uid) throws MessagingException { return new WebDavMessage(uid, this); } @Override public Message[] getMessages(int start, int end, MessageRetrievalListener listener) throws MessagingException { ArrayList<Message> messages = new ArrayList<Message>(); String[] uids; DataSet dataset = new DataSet(); HashMap<String, String> headers = new HashMap<String, String>(); int uidsLength = -1; String messageBody; int prevStart = start; /** Reverse the message range since 0 index is newest */ start = this.mMessageCount - end; end = start + (end - prevStart); //end = this.mMessageCount - prevStart; if (start < 0 || end < 0 || end < start) { throw new MessagingException(String.format("Invalid message set %d %d", start, end)); } if (start == 0 && end < 10) { end = 10; } /** Verify authentication */ messageBody = getMessagesXml(); headers.put("Brief", "t"); headers.put("Range", "rows=" + start + "-" + end); dataset = processRequest(this.mFolderUrl, "SEARCH", messageBody, headers); uids = dataset.getUids(); HashMap<String, String> uidToUrl = dataset.getUidToUrl(); uidsLength = uids.length; for (int i = 0; i < uidsLength; i++) { if (listener != null) { listener.messageStarted(uids[i], i, uidsLength); } WebDavMessage message = new WebDavMessage(uids[i], this); message.setUrl(uidToUrl.get(uids[i])); messages.add(message); if (listener != null) { listener.messageFinished(message, i, uidsLength); } } return messages.toArray(new Message[] {}); } @Override public Message[] getMessages(MessageRetrievalListener listener) throws MessagingException { return getMessages(null, listener); } @Override public Message[] getMessages(String[] uids, MessageRetrievalListener listener) throws MessagingException { ArrayList<Message> messageList = new ArrayList<Message>(); Message[] messages; if (uids == null || uids.length == 0) { return messageList.toArray(new Message[] {}); } for (int i = 0, count = uids.length; i < count; i++) { if (listener != null) { listener.messageStarted(uids[i], i, count); } WebDavMessage message = new WebDavMessage(uids[i], this); messageList.add(message); if (listener != null) { listener.messageFinished(message, i, count); } } messages = messageList.toArray(new Message[] {}); return messages; } private HashMap<String, String> getMessageUrls(String[] uids) throws MessagingException { HashMap<String, String> uidToUrl = new HashMap<String, String>(); HashMap<String, String> headers = new HashMap<String, String>(); DataSet dataset = new DataSet(); String messageBody; /** Retrieve and parse the XML entity for our messages */ messageBody = getMessageUrlsXml(uids); headers.put("Brief", "t"); dataset = processRequest(this.mFolderUrl, "SEARCH", messageBody, headers); uidToUrl = dataset.getUidToUrl(); return uidToUrl; } @Override public void fetch(Message[] messages, FetchProfile fp, MessageRetrievalListener listener) throws MessagingException { if (messages == null || messages.length == 0) { return; } /** * Fetch message envelope information for the array */ if (fp.contains(FetchProfile.Item.ENVELOPE)) { fetchEnvelope(messages, listener); } /** * Fetch message flag info for the array */ if (fp.contains(FetchProfile.Item.FLAGS)) { fetchFlags(messages, listener); } if (fp.contains(FetchProfile.Item.BODY_SANE)) { fetchMessages(messages, listener, FETCH_BODY_SANE_SUGGESTED_SIZE / 76); } if (fp.contains(FetchProfile.Item.BODY)) { fetchMessages(messages, listener, -1); } // if (fp.contains(FetchProfile.Item.STRUCTURE)) { // for (int i = 0, count = messages.length; i < count; i++) { // if (!(messages[i] instanceof WebDavMessage)) { // throw new MessagingException("WebDavStore fetch called with non-WebDavMessage"); // } // WebDavMessage wdMessage = (WebDavMessage) messages[i]; // // if (listener != null) { // listener.messageStarted(wdMessage.getUid(), i, count); // } // // wdMessage.setBody(null); // // if (listener != null) { // listener.messageFinished(wdMessage, i, count); // } // } // } } /** * Fetches the full messages or up to lines lines and passes them to the message parser. */ private void fetchMessages(Message[] messages, MessageRetrievalListener listener, int lines) throws MessagingException { WebDavHttpClient httpclient; httpclient = getHttpClient(); /** * We can't hand off to processRequest() since we need the stream to parse. */ for (int i = 0, count = messages.length; i < count; i++) { WebDavMessage wdMessage; int statusCode = 0; if (!(messages[i] instanceof WebDavMessage)) { throw new MessagingException("WebDavStore fetch called with non-WebDavMessage"); } wdMessage = (WebDavMessage) messages[i]; if (listener != null) { listener.messageStarted(wdMessage.getUid(), i, count); } /** * If fetch is called outside of the initial list (ie, a locally stored * message), it may not have a URL associated. Verify and fix that */ if (wdMessage.getUrl().equals("")) { wdMessage.setUrl(getMessageUrls(new String[] {wdMessage.getUid()}).get(wdMessage.getUid())); Log.i(K9.LOG_TAG, "Fetching messages with UID = '" + wdMessage.getUid() + "', URL = '" + wdMessage.getUrl() + "'"); if (wdMessage.getUrl().equals("")) { throw new MessagingException("Unable to get URL for message"); } } try { Log.i(K9.LOG_TAG, "Fetching message with UID = '" + wdMessage.getUid() + "', URL = '" + wdMessage.getUrl() + "'"); HttpGet httpget = new HttpGet(new URI(wdMessage.getUrl())); HttpResponse response; HttpEntity entity; httpget.setHeader("translate", "f"); if (mAuthString != null && mAuthenticated) { httpget.setHeader("Authorization", mAuthString); } response = httpclient.executeOverride(httpget); statusCode = response.getStatusLine().getStatusCode(); entity = response.getEntity(); if (statusCode < 200 || statusCode > 300) { throw new IOException("Error during with code " + statusCode + " during fetch: " + response.getStatusLine().toString()); } if (entity != null) { InputStream istream = null; StringBuffer buffer = new StringBuffer(); String tempText = ""; String resultText = ""; BufferedReader reader; int currentLines = 0; istream = WebDavHttpClient.getUngzippedContent(entity); if (lines != -1) { reader = new BufferedReader(new InputStreamReader(istream), 8192); while ((tempText = reader.readLine()) != null && (currentLines < lines)) { buffer.append(tempText+"\r\n"); currentLines++; } istream.close(); resultText = buffer.toString(); istream = new ByteArrayInputStream(resultText.getBytes("UTF-8")); } wdMessage.parse(istream); } } catch (IllegalArgumentException iae) { Log.e(K9.LOG_TAG, "IllegalArgumentException caught " + iae + "\nTrace: " + processException(iae)); throw new MessagingException("IllegalArgumentException caught", iae); } catch (URISyntaxException use) { Log.e(K9.LOG_TAG, "URISyntaxException caught " + use + "\nTrace: " + processException(use)); throw new MessagingException("URISyntaxException caught", use); } catch (IOException ioe) { Log.e(K9.LOG_TAG, "Non-success response code loading message, response code was " + statusCode + "\nURL: " + wdMessage.getUrl() + "\nError: " + ioe.getMessage() + "\nTrace: " + processException(ioe)); throw new MessagingException("Failure code " + statusCode, ioe); } if (listener != null) { listener.messageFinished(wdMessage, i, count); } } } /** * Fetches and sets the message flags for the supplied messages. * The idea is to have this be recursive so that we do a series of medium calls * instead of one large massive call or a large number of smaller calls. */ private void fetchFlags(Message[] startMessages, MessageRetrievalListener listener) throws MessagingException { HashMap<String, Boolean> uidToReadStatus = new HashMap<String, Boolean>(); HashMap<String, String> headers = new HashMap<String, String>(); DataSet dataset = new DataSet(); String messageBody = ""; Message[] messages = new Message[20]; String[] uids; if (startMessages == null || startMessages.length == 0) { return; } if (startMessages.length > 20) { Message[] newMessages = new Message[startMessages.length - 20]; for (int i = 0, count = startMessages.length; i < count; i++) { if (i < 20) { messages[i] = startMessages[i]; } else { newMessages[i - 20] = startMessages[i]; } } fetchFlags(newMessages, listener); } else { messages = startMessages; } uids = new String[messages.length]; for (int i = 0, count = messages.length; i < count; i++) { uids[i] = messages[i].getUid(); } messageBody = getMessageFlagsXml(uids); headers.put("Brief", "t"); dataset = processRequest(this.mFolderUrl, "SEARCH", messageBody, headers); if (dataset == null) { throw new MessagingException("Data Set from request was null"); } uidToReadStatus = dataset.getUidToRead(); for (int i = 0, count = messages.length; i < count; i++) { if (!(messages[i] instanceof WebDavMessage)) { throw new MessagingException("WebDavStore fetch called with non-WebDavMessage"); } WebDavMessage wdMessage = (WebDavMessage) messages[i]; if (listener != null) { listener.messageStarted(messages[i].getUid(), i, count); } wdMessage.setFlagInternal(Flag.SEEN, uidToReadStatus.get(wdMessage.getUid())); if (listener != null) { listener.messageFinished(messages[i], i, count); } } } /** * Fetches and parses the message envelopes for the supplied messages. * The idea is to have this be recursive so that we do a series of medium calls * instead of one large massive call or a large number of smaller calls. * Call it a happy balance */ private void fetchEnvelope(Message[] startMessages, MessageRetrievalListener listener) throws MessagingException { HashMap<String, ParsedMessageEnvelope> envelopes = new HashMap<String, ParsedMessageEnvelope>(); HashMap<String, String> headers = new HashMap<String, String>(); DataSet dataset = new DataSet(); String messageBody = ""; String[] uids; Message[] messages = new Message[10]; if (startMessages == null || startMessages.length == 0) { return; } if (startMessages.length > 10) { Message[] newMessages = new Message[startMessages.length - 10]; for (int i = 0, count = startMessages.length; i < count; i++) { if (i < 10) { messages[i] = startMessages[i]; } else { newMessages[i - 10] = startMessages[i]; } } fetchEnvelope(newMessages, listener); } else { messages = startMessages; } uids = new String[messages.length]; for (int i = 0, count = messages.length; i < count; i++) { uids[i] = messages[i].getUid(); } messageBody = getMessageEnvelopeXml(uids); headers.put("Brief", "t"); dataset = processRequest(this.mFolderUrl, "SEARCH", messageBody, headers); envelopes = dataset.getMessageEnvelopes(); int count = messages.length; for (int i = messages.length - 1; i >= 0; i--) { if (!(messages[i] instanceof WebDavMessage)) { throw new MessagingException("WebDavStore fetch called with non-WebDavMessage"); } WebDavMessage wdMessage = (WebDavMessage) messages[i]; if (listener != null) { listener.messageStarted(messages[i].getUid(), i, count); } wdMessage.setNewHeaders(envelopes.get(wdMessage.getUid())); wdMessage.setFlagInternal(Flag.SEEN, envelopes.get(wdMessage.getUid()).getReadStatus()); if (listener != null) { listener.messageFinished(messages[i], i, count); } } } @Override public Flag[] getPermanentFlags() throws MessagingException { return PERMANENT_FLAGS; } @Override public void setFlags(Message[] messages, Flag[] flags, boolean value) throws MessagingException { String[] uids = new String[messages.length]; for (int i = 0, count = messages.length; i < count; i++) { uids[i] = messages[i].getUid(); } for (int i = 0, count = flags.length; i < count; i++) { Flag flag = flags[i]; if (flag == Flag.SEEN) { markServerMessagesRead(uids, value); } else if (flag == Flag.DELETED) { deleteServerMessages(uids); } } } private void markServerMessagesRead(String[] uids, boolean read) throws MessagingException { String messageBody = ""; HashMap<String, String> headers = new HashMap<String, String>(); HashMap<String, String> uidToUrl = getMessageUrls(uids); DataSet dataset = new DataSet(); String[] urls = new String[uids.length]; for (int i = 0, count = uids.length; i < count; i++) { urls[i] = uidToUrl.get(uids[i]); } messageBody = getMarkMessagesReadXml(urls, read); headers.put("Brief", "t"); headers.put("If-Match", "*"); processRequest(this.mFolderUrl, "BPROPPATCH", messageBody, headers, false); } private void deleteServerMessages(String[] uids) throws MessagingException { HashMap<String, String> uidToUrl = getMessageUrls(uids); String[] urls = new String[uids.length]; for (int i = 0, count = uids.length; i < count; i++) { HashMap<String, String> headers = new HashMap<String, String>(); String uid = uids[i]; String url = uidToUrl.get(uid); String destinationUrl = generateDeleteUrl(url); /** * If the destination is the same as the origin, assume delete forever */ if (destinationUrl.equals(url)) { headers.put("Brief", "t"); processRequest(url, "DELETE", null, headers, false); } else { headers.put("Destination", generateDeleteUrl(url)); headers.put("Brief", "t"); processRequest(url, "MOVE", null, headers, false); } } } private String generateDeleteUrl(String startUrl) { String[] urlParts = startUrl.split("/"); String filename = urlParts[urlParts.length - 1]; String finalUrl = WebDavStore.this.mUrl + "Deleted%20Items/" + filename; return finalUrl; } @Override public void appendMessages(Message[] messages) throws MessagingException { appendWebDavMessages(messages); } public Message[] appendWebDavMessages(Message[] messages) throws MessagingException { Message[] retMessages = new Message[messages.length]; int ind = 0; WebDavHttpClient httpclient = getHttpClient(); for (Message message : messages) { HttpGeneric httpmethod; HttpResponse response; StringEntity bodyEntity; int statusCode; try { String subject; try { subject = message.getSubject(); } catch (MessagingException e) { Log.e(K9.LOG_TAG, "MessagingException while retrieving Subject: " + e); subject = ""; } ByteArrayOutputStream out; try { out = new ByteArrayOutputStream(message.getSize()); } catch (MessagingException e) { Log.e(K9.LOG_TAG, "MessagingException while getting size of message: " + e); out = new ByteArrayOutputStream(); } open(OpenMode.READ_WRITE); message.writeTo( new EOLConvertingOutputStream( new BufferedOutputStream(out, 1024))); bodyEntity = new StringEntity(out.toString(), "UTF-8"); bodyEntity.setContentType("message/rfc822"); String messageURL = mFolderUrl; if (messageURL.endsWith("/") == false) { messageURL += "/"; } messageURL += URLEncoder.encode(message.getUid() + ":" + System.currentTimeMillis() + ".eml"); Log.i(K9.LOG_TAG, "Uploading message as " + messageURL); httpmethod = new HttpGeneric(messageURL); httpmethod.setMethod("PUT"); httpmethod.setEntity(bodyEntity); String mAuthString = getAuthString(); if (mAuthString != null) { httpmethod.setHeader("Authorization", mAuthString); } response = httpclient.executeOverride(httpmethod); statusCode = response.getStatusLine().getStatusCode(); if (statusCode < 200 || statusCode > 300) { throw new IOException("Error with status code " + statusCode + " while sending/appending message. Response = " + response.getStatusLine().toString() + " for message " + messageURL); } WebDavMessage retMessage = new WebDavMessage(message.getUid(), this); retMessage.setUrl(messageURL); retMessages[ind++] = retMessage; } catch (Exception e) { throw new MessagingException("Unable to append", e); } } return retMessages; } @Override public boolean equals(Object o) { return false; } public String getUidFromMessageId(Message message) throws MessagingException { Log.e(K9.LOG_TAG, "Unimplemented method getUidFromMessageId in WebDavStore.WebDavFolder could lead to duplicate messages " + " being uploaded to the Sent folder"); return null; } public void setFlags(Flag[] flags, boolean value) throws MessagingException { Log.e(K9.LOG_TAG, "Unimplemented method setFlags(Flag[], boolean) breaks markAllMessagesAsRead and EmptyTrash"); // Try to make this efficient by not retrieving all of the messages return; } } /** * A WebDav Message */ class WebDavMessage extends MimeMessage { private String mUrl = ""; WebDavMessage(String uid, Folder folder) throws MessagingException { this.mUid = uid; this.mFolder = folder; } public void setUrl(String url) { //TODO: This is a not as ugly hack (ie, it will actually work) //XXX: prevent URLs from getting to us that are broken if (!(url.toLowerCase().contains("http"))) { if (!(url.startsWith("/"))) { url = "/" + url; } url = WebDavStore.this.mUrl + this.mFolder + url; } String[] urlParts = url.split("/"); int length = urlParts.length; String end = urlParts[length - 1]; this.mUrl = ""; url = ""; /** * We have to decode, then encode the URL because Exchange likes to * not properly encode all characters */ try { end = java.net.URLDecoder.decode(end, "UTF-8"); end = java.net.URLEncoder.encode(end, "UTF-8"); end = end.replaceAll("\\+", "%20"); } catch (UnsupportedEncodingException uee) { Log.e(K9.LOG_TAG, "UnsupportedEncodingException caught in setUrl: " + uee + "\nTrace: " + processException(uee)); } catch (IllegalArgumentException iae) { Log.e(K9.LOG_TAG, "IllegalArgumentException caught in setUrl: " + iae + "\nTrace: " + processException(iae)); } for (int i = 0; i < length - 1; i++) { if (i != 0) { url = url + "/" + urlParts[i]; } else { url = urlParts[i]; } } url = url + "/" + end; this.mUrl = url; } public String getUrl() { return this.mUrl; } public void setSize(int size) { this.mSize = size; } public void parse(InputStream in) throws IOException, MessagingException { super.parse(in); } public void setFlagInternal(Flag flag, boolean set) throws MessagingException { super.setFlag(flag, set); } public void setNewHeaders(ParsedMessageEnvelope envelope) throws MessagingException { String[] headers = envelope.getHeaderList(); HashMap<String, String> messageHeaders = envelope.getMessageHeaders(); for (int i = 0, count = headers.length; i < count; i++) { String headerValue = messageHeaders.get(headers[i]); if (headers[i].equals("Content-Length")) { int size = Integer.parseInt(messageHeaders.get(headers[i])); this.setSize(size); } if (headerValue != null && !headerValue.equals("")) { this.addHeader(headers[i], headerValue); } } } @Override public void delete(String trashFolderName) throws MessagingException { WebDavFolder wdFolder = (WebDavFolder)getFolder(); Log.i(K9.LOG_TAG, "Deleting message by moving to " + trashFolderName); wdFolder.moveMessages(new Message[] { this }, wdFolder.getStore().getFolder(trashFolderName)); } @Override public void setFlag(Flag flag, boolean set) throws MessagingException { super.setFlag(flag, set); mFolder.setFlags(new Message[] { this }, new Flag[] { flag }, set); } } /** * XML Parsing Handler * Can handle all XML handling needs */ public class WebDavHandler extends DefaultHandler { private DataSet mDataSet = new DataSet(); private Stack<String> mOpenTags = new Stack<String>(); public DataSet getDataSet() { return this.mDataSet; } @Override public void startDocument() throws SAXException { this.mDataSet = new DataSet(); } @Override public void endDocument() throws SAXException { /* Do nothing */ } @Override public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { mOpenTags.push(localName); } @Override public void endElement(String namespaceURI, String localName, String qName) { mOpenTags.pop(); /** Reset the hash temp variables */ if (localName.equals("response")) { this.mDataSet.finish(); } } @Override public void characters(char ch[], int start, int length) { String value = new String(ch, start, length); mDataSet.addValue(value, mOpenTags.peek()); } } /** * Data set for a single E-Mail message's required headers (the envelope) * Only provides accessor methods to the stored data. All processing should be * done elsewhere. This is done rather than having multiple hashmaps * associating UIDs to values */ public class ParsedMessageEnvelope { /** * Holds the mappings from the name returned from Exchange to the MIME format header name */ private final HashMap<String, String> mHeaderMappings = new HashMap<String, String>() { { put("mime-version", "MIME-Version"); put("content-type", "Content-Type"); put("subject", "Subject"); put("date", "Date"); put("thread-topic", "Thread-Topic"); put("thread-index", "Thread-Index"); put("from", "From"); put("to", "To"); put("in-reply-to", "In-Reply-To"); put("cc", "Cc"); put("getcontentlength", "Content-Length"); } }; private boolean mReadStatus = false; private String mUid = ""; private HashMap<String, String> mMessageHeaders = new HashMap<String, String>(); private ArrayList<String> mHeaders = new ArrayList<String>(); public void addHeader(String field, String value) { String headerName = mHeaderMappings.get(field); //Log.i(K9.LOG_TAG, "header " + headerName + " = '" + value + "'"); if (headerName != null) { this.mMessageHeaders.put(mHeaderMappings.get(field), value); this.mHeaders.add(mHeaderMappings.get(field)); } } public HashMap<String, String> getMessageHeaders() { return this.mMessageHeaders; } public String[] getHeaderList() { return this.mHeaders.toArray(new String[] {}); } public void setReadStatus(boolean status) { this.mReadStatus = status; } public boolean getReadStatus() { return this.mReadStatus; } public void setUid(String uid) { if (uid != null) { this.mUid = uid; } } public String getUid() { return this.mUid; } } /** * Dataset for all XML parses. * Data is stored in a single format inside the class and is formatted appropriately depending on the accessor calls made. */ public class DataSet { private HashMap<String, HashMap> mData = new HashMap<String, HashMap>(); private HashMap<String, String> mLostData = new HashMap<String, String>(); private String mUid = ""; private HashMap<String, String> mTempData = new HashMap<String, String>(); public void addValue(String value, String tagName) { if (tagName.equals("uid")) { mUid = value; } if (mTempData.containsKey(tagName)) { mTempData.put(tagName, mTempData.get(tagName) + value); } else { mTempData.put(tagName, value); } } public void finish() { if (mUid != null && mTempData != null) { mData.put(mUid, mTempData); } else if (mTempData != null) { /* Lost Data are for requests that don't include a message UID. * These requests should only have a depth of one for the response so it will never get stomped over. */ mLostData = mTempData; String visibleCount = mLostData.get("visiblecount"); } mUid = ""; mTempData = new HashMap<String, String>(); } /** * Returns a hashmap of Message UID => Message Url */ public HashMap<String, String> getUidToUrl() { HashMap<String, String> uidToUrl = new HashMap<String, String>(); for (String uid : mData.keySet()) { HashMap<String, String> data = mData.get(uid); String value = data.get("href"); if (value != null && !value.equals("")) { uidToUrl.put(uid, value); } } return uidToUrl; } /** * Returns a hashmap of Message UID => Read Status */ public HashMap<String, Boolean> getUidToRead() { HashMap<String, Boolean> uidToRead = new HashMap<String, Boolean>(); for (String uid : mData.keySet()) { HashMap<String, String> data = mData.get(uid); String readStatus = data.get("read"); if (readStatus != null && !readStatus.equals("")) { Boolean value = readStatus.equals("0") ? false : true; uidToRead.put(uid, value); } } return uidToRead; } /** * Returns an array of all hrefs (urls) that were received */ public String[] getHrefs() { ArrayList<String> hrefs = new ArrayList<String>(); for (String uid : mData.keySet()) { HashMap<String, String> data = mData.get(uid); String href = data.get("href"); hrefs.add(href); } return hrefs.toArray(new String[] {}); } /** * Return an array of all Message UIDs that were received */ public String[] getUids() { ArrayList<String> uids = new ArrayList<String>(); for (String uid : mData.keySet()) { uids.add(uid); } return uids.toArray(new String[] {}); } /** * Returns the message count as it was retrieved */ public int getMessageCount() { int messageCount = -1; for (String uid : mData.keySet()) { HashMap<String, String> data = mData.get(uid); String count = data.get("visiblecount"); if (count != null && !count.equals("")) { messageCount = Integer.parseInt(count); } } return messageCount; } /** * Returns a HashMap of message UID => ParsedMessageEnvelope */ public HashMap<String, ParsedMessageEnvelope> getMessageEnvelopes() { HashMap<String, ParsedMessageEnvelope> envelopes = new HashMap<String, ParsedMessageEnvelope>(); for (String uid : mData.keySet()) { ParsedMessageEnvelope envelope = new ParsedMessageEnvelope(); HashMap<String, String> data = mData.get(uid); if (data != null) { for (String header : data.keySet()) { if (header.equals("read")) { String read = data.get(header); Boolean readStatus = read.equals("0") ? false : true; envelope.setReadStatus(readStatus); } else if (header.equals("date")) { /** * Exchange doesn't give us rfc822 dates like it claims. The date is in the format: * yyyy-MM-dd'T'HH:mm:ss.SSS<Single digit representation of timezone, so far, all instances are Z> */ String date = data.get(header); date = date.substring(0, date.length() - 1); DateFormat dfInput = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS"); DateFormat dfOutput = new SimpleDateFormat("EEE, d MMM yy HH:mm:ss Z"); String tempDate = ""; try { Date parsedDate = dfInput.parse(date); tempDate = dfOutput.format(parsedDate); } catch (java.text.ParseException pe) { Log.e(K9.LOG_TAG, "Error parsing date: "+ pe + "\nTrace: " + processException(pe)); } envelope.addHeader(header, tempDate); } else { envelope.addHeader(header, data.get(header)); } } } if (envelope != null) { envelopes.put(uid, envelope); } } return envelopes; } } /** * New HTTP Method that allows changing of the method and generic handling * Needed for WebDAV custom methods such as SEARCH and PROPFIND */ public class HttpGeneric extends HttpEntityEnclosingRequestBase { public String METHOD_NAME = "POST"; public HttpGeneric() { super(); } public HttpGeneric(final URI uri) { super(); setURI(uri); } /** * @throws IllegalArgumentException if the uri is invalid. */ public HttpGeneric(final String uri) { super(); if (K9.DEBUG) { Log.v(K9.LOG_TAG, "Starting uri = '" + uri + "'"); } String[] urlParts = uri.split("/"); int length = urlParts.length; String end = urlParts[length - 1]; String url = ""; /** * We have to decode, then encode the URL because Exchange likes to * not properly encode all characters */ try { if (length > 3) { end = java.net.URLDecoder.decode(end, "UTF-8"); end = java.net.URLEncoder.encode(end, "UTF-8"); end = end.replaceAll("\\+", "%20"); } } catch (UnsupportedEncodingException uee) { Log.e(K9.LOG_TAG, "UnsupportedEncodingException caught in HttpGeneric(String uri): " + uee + "\nTrace: " + processException(uee)); } catch (IllegalArgumentException iae) { Log.e(K9.LOG_TAG, "IllegalArgumentException caught in HttpGeneric(String uri): " + iae + "\nTrace: " + processException(iae)); } for (int i = 0; i < length - 1; i++) { if (i != 0) { url = url + "/" + urlParts[i]; } else { url = urlParts[i]; } } if (K9.DEBUG) { Log.v(K9.LOG_TAG, "url = '" + url + "' length = " + url.length() + ", end = '" + end + "' length = " + end.length()); } url = url + "/" + end; Log.i(K9.LOG_TAG, "url = " + url); setURI(URI.create(url)); } @Override public String getMethod() { return METHOD_NAME; } public void setMethod(String method) { if (method != null) { METHOD_NAME = method; } } } public static class WebDavHttpClient extends DefaultHttpClient { /* * 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. */ public static void modifyRequestToAcceptGzipResponse(HttpRequest request) { Log.i(K9.LOG_TAG, "Requesting gzipped data"); request.addHeader("Accept-Encoding", "gzip"); } public static InputStream getUngzippedContent(HttpEntity entity) throws IOException { InputStream responseStream = entity.getContent(); if (responseStream == null) return responseStream; Header header = entity.getContentEncoding(); if (header == null) return responseStream; String contentEncoding = header.getValue(); if (contentEncoding == null) return responseStream; if (contentEncoding.contains("gzip")) { Log.i(K9.LOG_TAG, "Response is gzipped"); responseStream = new GZIPInputStream(responseStream); } return responseStream; } public HttpResponse executeOverride(HttpUriRequest request) throws IOException { modifyRequestToAcceptGzipResponse(request); return super.execute(request); } } }
public void doFBA() throws IOException, MessagingException { /* public CookieStore doAuthentication(String username, String password, String url) throws IOException, MessagingException {*/ String authPath; String url = this.mUrl; String username = this.mUsername; String password = this.mPassword; String[] urlParts = url.split("/"); String finalUrl = ""; String loginUrl = ""; String destinationUrl = ""; if (this.mAuthPath != null && !this.mAuthPath.equals("") && !this.mAuthPath.equals("/")) { authPath = this.mAuthPath; } else { authPath = "/exchweb/bin/auth/owaauth.dll"; } for (int i = 0; i <= 2; i++) { if (i != 0) { finalUrl = finalUrl + "/" + urlParts[i]; } else { finalUrl = urlParts[i]; } } if (finalUrl.equals("")) { throw new MessagingException("doFBA failed, unable to construct URL to post login credentials to."); } loginUrl = finalUrl + authPath; try { /* Browser Client */ WebDavHttpClient httpclient = mHttpClient; /** * This is in a separate block because I really don't like how it's done. * This basically scrapes the OWA login page for the form submission URL. * UGLY!WebDavHttpClient * Added an if-check to see if there's a user supplied authentication path for FBA */ if (this.mAuthPath == null || this.mAuthPath.equals("") || this.mAuthPath.equals("/")) { httpclient.addRequestInterceptor(new HttpRequestInterceptor() { public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { mRedirectUrl = ((HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST)).toURI() + request.getRequestLine().getUri(); } }); HashMap<String, String> headers = new HashMap<String, String>(); InputStream istream = sendRequest(finalUrl, "GET", null, headers, false); if (istream != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(istream), 4096); String tempText = ""; boolean matched = false; while ((tempText = reader.readLine()) != null && !matched) { if (tempText.indexOf(" action") >= 0) { String[] tagParts = tempText.split("\""); if (tagParts[1].lastIndexOf('/') < 0 && mRedirectUrl != null && !mRedirectUrl.equals("")) { /* We have to do a multi-stage substring here because of potential GET parameters */ mRedirectUrl = mRedirectUrl.substring(0, mRedirectUrl.lastIndexOf('?')); mRedirectUrl = mRedirectUrl.substring(0, mRedirectUrl.lastIndexOf('/')); loginUrl = mRedirectUrl + "/" + tagParts[1]; this.mAuthPath = "/" + tagParts[1]; } else { loginUrl = finalUrl + tagParts[1]; this.mAuthPath = "/" + tagParts[1]; } } if (tempText.indexOf("destination") >= 0) { String[] tagParts = tempText.split("value"); if (tagParts[1] != null) { String[] valueParts = tagParts[1].split("\""); destinationUrl = valueParts[1]; matched = true; } } } istream.close(); } } /** Build the POST data to use */ ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>(); pairs.add(new BasicNameValuePair("username", username)); pairs.add(new BasicNameValuePair("password", password)); if (this.mMailboxPath != null && !this.mMailboxPath.equals("")) { pairs.add(new BasicNameValuePair("destination", finalUrl + this.mMailboxPath)); } else if (destinationUrl != null && !destinationUrl.equals("")) { pairs.add(new BasicNameValuePair("destination", destinationUrl)); } else { pairs.add(new BasicNameValuePair("destination", "/")); } pairs.add(new BasicNameValuePair("flags", "0")); pairs.add(new BasicNameValuePair("SubmitCreds", "Log+On")); pairs.add(new BasicNameValuePair("forcedownlevel", "0")); pairs.add(new BasicNameValuePair("trusted", "0")); try { UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(pairs); HashMap<String, String> headers = new HashMap<String, String>(); String tempUrl = ""; InputStream istream = sendRequest(loginUrl, "POST", formEntity, headers, false); /** Get the URL for the mailbox and set it for the store */ if (istream != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(istream), 8192); String tempText = ""; while ((tempText = reader.readLine()) != null) { if (tempText.indexOf("BASE href") >= 0) { String[] tagParts = tempText.split("\""); tempUrl = tagParts[1]; } } } if (this.mMailboxPath != null && !this.mMailboxPath.equals("")) { this.mUrl = finalUrl + "/" + this.mMailboxPath + "/"; } else if (tempUrl.equals("")) { this.mUrl = finalUrl + "/Exchange/" + this.alias + "/"; } else { this.mUrl = tempUrl; } } catch (UnsupportedEncodingException uee) { Log.e(K9.LOG_TAG, "Error encoding POST data for authentication: " + uee + "\nTrace: " + processException(uee)); throw new MessagingException("Error encoding POST data for authentication", uee); } } catch (SSLException e) { throw new CertificateValidationException(e.getMessage(), e); } this.mAuthenticated = true; } public CookieStore getAuthCookies() { return mAuthCookies; } public String getAlias() { return alias; } public String getUrl() { return mUrl; } public WebDavHttpClient getHttpClient() throws MessagingException { SchemeRegistry reg; Scheme s; boolean needAuth = false; if (mHttpClient == null) { mHttpClient = new WebDavHttpClient(); needAuth = true; } reg = mHttpClient.getConnectionManager().getSchemeRegistry(); try { // Log.i(K9.LOG_TAG, "getHttpClient mHost = " + mHost); s = new Scheme("https", new TrustedSocketFactory(mHost, mSecure), 443); } catch (NoSuchAlgorithmException nsa) { Log.e(K9.LOG_TAG, "NoSuchAlgorithmException in getHttpClient: " + nsa); throw new MessagingException("NoSuchAlgorithmException in getHttpClient: " + nsa); } catch (KeyManagementException kme) { Log.e(K9.LOG_TAG, "KeyManagementException in getHttpClient: " + kme); throw new MessagingException("KeyManagementException in getHttpClient: " + kme); } reg.register(s); if (needAuth) { HashMap<String, String> headers = new HashMap<String, String>(); processRequest(this.mUrl, "GET", null, headers, false); } /* if (needAuth()) { if (!checkAuth()) { try { CookieStore cookies = mHttpClient.getCookieStore(); cookies.clear(); mHttpClient.setCookieStore(cookies); cookies = doAuthentication(this.mUsername, this.mPassword, this.mUrl); if (cookies != null) { this.mAuthenticated = true; this.mLastAuth = System.currentTimeMillis()/1000; } mHttpClient.setCookieStore(cookies); } catch (IOException ioe) { Log.e(K9.LOG_TAG, "IOException: " + ioe + "\nTrace: " + processException(ioe)); } } else { Credentials creds = new UsernamePasswordCredentials(mUsername, mPassword); CredentialsProvider credsProvider = mHttpClient.getCredentialsProvider(); credsProvider.setCredentials(new AuthScope(mHost, 80, AuthScope.ANY_REALM), creds); credsProvider.setCredentials(new AuthScope(mHost, 443, AuthScope.ANY_REALM), creds); credsProvider.setCredentials(new AuthScope(mHost, mUri.getPort(), AuthScope.ANY_REALM), creds); mHttpClient.setCredentialsProvider(credsProvider); // Assume we're authenticated and ok here since the checkAuth() was 401 and we've now set the credentials this.mAuthenticated = true; this.mLastAuth = System.currentTimeMillis()/1000; } } */ return mHttpClient; } public WebDavHttpClient getTrustedHttpClient() throws KeyManagementException, NoSuchAlgorithmException { if (mHttpClient == null) { mHttpClient = new WebDavHttpClient(); SchemeRegistry reg = mHttpClient.getConnectionManager().getSchemeRegistry(); Scheme s = new Scheme("https",new TrustedSocketFactory(mHost,mSecure),443); reg.register(s); //Add credentials for NTLM/Digest/Basic Auth Credentials creds = new UsernamePasswordCredentials(mUsername, mPassword); CredentialsProvider credsProvider = mHttpClient.getCredentialsProvider(); // setting AuthScope for 80 and 443, in case we end up getting redirected // from 80 to 443. credsProvider.setCredentials(new AuthScope(mHost, 80, AuthScope.ANY_REALM), creds); credsProvider.setCredentials(new AuthScope(mHost, 443, AuthScope.ANY_REALM), creds); credsProvider.setCredentials(new AuthScope(mHost, mUri.getPort(), AuthScope.ANY_REALM), creds); mHttpClient.setCredentialsProvider(credsProvider); } return mHttpClient; } private InputStream sendRequest(String url, String method, StringEntity messageBody, HashMap<String, String> headers, boolean tryAuth) throws MessagingException { WebDavHttpClient httpclient; InputStream istream = null; if (url == null || method == null) { return istream; } httpclient = getHttpClient(); try { int statusCode = -1; StringEntity messageEntity = null; HttpGeneric httpmethod = new HttpGeneric(url); HttpResponse response; HttpEntity entity; if (messageBody != null) { httpmethod.setEntity(messageBody); } for (String headerName : headers.keySet()) { httpmethod.setHeader(headerName, headers.get(headerName)); } if (mAuthString != null && mAuthenticated) { httpmethod.setHeader("Authorization", mAuthString); } httpmethod.setMethod(method); response = httpclient.executeOverride(httpmethod); statusCode = response.getStatusLine().getStatusCode(); entity = response.getEntity(); if (statusCode == 401) { if (tryAuth) { mAuthenticated = true; sendRequest(url, method, messageBody, headers, false); } else { throw new MessagingException("Invalid username or password for Basic authentication"); } } else if (statusCode == 440) { if (tryAuth) { doFBA(); sendRequest(url, method, messageBody, headers, false); } else { throw new MessagingException("Authentication failure in sendRequest"); } } else if (statusCode < 200 || statusCode >= 300) { throw new IOException("Error with code " + statusCode + " during request processing: "+ response.getStatusLine().toString()); } else { if (tryAuth && mAuthenticated == false) { doFBA(); sendRequest(url, method, messageBody, headers, false); } } if (entity != null) { istream = WebDavHttpClient.getUngzippedContent(entity); } } catch (UnsupportedEncodingException uee) { Log.e(K9.LOG_TAG, "UnsupportedEncodingException: " + uee + "\nTrace: " + processException(uee)); throw new MessagingException("UnsupportedEncodingException", uee); } catch (IOException ioe) { Log.e(K9.LOG_TAG, "IOException: " + ioe + "\nTrace: " + processException(ioe)); throw new MessagingException("IOException", ioe); } return istream; } public String getAuthString() { return mAuthString; } /** * Performs an httprequest to the supplied url using the supplied method. * messageBody and headers are optional as not all requests will need them. * There are two signatures to support calls that don't require parsing of the response. */ private DataSet processRequest(String url, String method, String messageBody, HashMap<String, String> headers) throws MessagingException { return processRequest(url, method, messageBody, headers, true); } private DataSet processRequest(String url, String method, String messageBody, HashMap<String, String> headers, boolean needsParsing) throws MessagingException { DataSet dataset = new DataSet(); if (K9.DEBUG) { Log.v(K9.LOG_TAG, "processRequest url = '" + url + "', method = '" + method + "', messageBody = '" + messageBody + "'"); } if (url == null || method == null) { return dataset; } getHttpClient(); try { StringEntity messageEntity = null; if (messageBody != null) { messageEntity = new StringEntity(messageBody); messageEntity.setContentType("text/xml"); // httpmethod.setEntity(messageEntity); } InputStream istream = sendRequest(url, method, messageEntity, headers, true); if (istream != null && needsParsing) { try { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); WebDavHandler myHandler = new WebDavHandler(); xr.setContentHandler(myHandler); xr.parse(new InputSource(istream)); dataset = myHandler.getDataSet(); } catch (SAXException se) { Log.e(K9.LOG_TAG, "SAXException in processRequest() " + se + "\nTrace: " + processException(se)); throw new MessagingException("SAXException in processRequest() ", se); } catch (ParserConfigurationException pce) { Log.e(K9.LOG_TAG, "ParserConfigurationException in processRequest() " + pce + "\nTrace: " + processException(pce)); throw new MessagingException("ParserConfigurationException in processRequest() ", pce); } istream.close(); } } catch (UnsupportedEncodingException uee) { Log.e(K9.LOG_TAG, "UnsupportedEncodingException: " + uee + "\nTrace: " + processException(uee)); throw new MessagingException("UnsupportedEncodingException in processRequest() ", uee); } catch (IOException ioe) { Log.e(K9.LOG_TAG, "IOException: " + ioe + "\nTrace: " + processException(ioe)); throw new MessagingException("IOException in processRequest() ", ioe); } return dataset; } /** * Returns a string of the stacktrace for a Throwable to allow for easy inline printing of errors. */ private String processException(Throwable t) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); t.printStackTrace(ps); ps.close(); return baos.toString(); } @Override public boolean isSendCapable() { return true; } @Override public void sendMessages(Message[] messages) throws MessagingException { WebDavFolder tmpFolder = (WebDavStore.WebDavFolder)getFolder(DAV_MAIL_TMP_FOLDER); try { tmpFolder.open(OpenMode.READ_WRITE); Message[] retMessages = tmpFolder.appendWebDavMessages(messages); tmpFolder.moveMessages(retMessages, getSendSpoolFolder()); } finally { if (tmpFolder != null) { tmpFolder.close(); } } } /************************************************************************* * Helper and Inner classes */ /** * A WebDav Folder */ class WebDavFolder extends Folder { private String mName; private String mFolderUrl; private boolean mIsOpen = false; private int mMessageCount = 0; private int mUnreadMessageCount = 0; private WebDavStore store; protected WebDavStore getStore() { return store; } public WebDavFolder(WebDavStore nStore, String name) { super(nStore.getAccount()); store = nStore; this.mName = name; if (DAV_MAIL_SEND_FOLDER.equals(name)) { this.mFolderUrl = getUrl() + "/" + name +"/"; } else { String encodedName = ""; try { String[] urlParts = name.split("/"); String url = ""; for (int i = 0, count = urlParts.length; i < count; i++) { if (i != 0) { url = url + "/" + java.net.URLEncoder.encode(urlParts[i], "UTF-8"); } else { url = java.net.URLEncoder.encode(urlParts[i], "UTF-8"); } } encodedName = url; } catch (UnsupportedEncodingException uee) { Log.e(K9.LOG_TAG, "UnsupportedEncodingException URLEncoding folder name, skipping encoded"); encodedName = name; } encodedName = encodedName.replaceAll("\\+", "%20"); /** * In some instances, it is possible that our folder objects have been collected, * but getPersonalNamespaces() isn't called again (ex. Android destroys the email client). * Perform an authentication to get the appropriate URLs in place again */ // TODO: danapple0 - huh? //getHttpClient(); if (encodedName.equals("INBOX")) { encodedName = "Inbox"; } this.mFolderUrl = WebDavStore.this.mUrl; if (WebDavStore.this.mUrl.endsWith("/") == false) { this.mFolderUrl += "/"; } this.mFolderUrl += encodedName; } } public void setUrl(String url) { if (url != null) { this.mFolderUrl = url; } } @Override public void open(OpenMode mode) throws MessagingException { getHttpClient(); this.mIsOpen = true; } @Override public void copyMessages(Message[] messages, Folder folder) throws MessagingException { moveOrCopyMessages(messages, folder.getName(), false); } @Override public void moveMessages(Message[] messages, Folder folder) throws MessagingException { moveOrCopyMessages(messages, folder.getName(), true); } @Override public void delete(Message[] msgs, String trashFolderName) throws MessagingException { moveOrCopyMessages(msgs, trashFolderName, true); } private void moveOrCopyMessages(Message[] messages, String folderName, boolean isMove) throws MessagingException { String[] uids = new String[messages.length]; for (int i = 0, count = messages.length; i < count; i++) { uids[i] = messages[i].getUid(); } String messageBody = ""; HashMap<String, String> headers = new HashMap<String, String>(); HashMap<String, String> uidToUrl = getMessageUrls(uids); String[] urls = new String[uids.length]; for (int i = 0, count = uids.length; i < count; i++) { urls[i] = uidToUrl.get(uids[i]); if (urls[i] == null && messages[i] instanceof WebDavMessage) { WebDavMessage wdMessage = (WebDavMessage)messages[i]; urls[i] = wdMessage.getUrl(); } } messageBody = getMoveOrCopyMessagesReadXml(urls, isMove); WebDavFolder destFolder = (WebDavFolder)store.getFolder(folderName); headers.put("Destination", destFolder.mFolderUrl); headers.put("Brief", "t"); headers.put("If-Match", "*"); String action = (isMove ? "BMOVE" : "BCOPY"); Log.i(K9.LOG_TAG, "Moving " + messages.length + " messages to " + destFolder.mFolderUrl); processRequest(mFolderUrl, action, messageBody, headers, false); } private int getMessageCount(boolean read, CookieStore authCookies) throws MessagingException { String isRead; int messageCount = 0; DataSet dataset = new DataSet(); HashMap<String, String> headers = new HashMap<String, String>(); String messageBody; if (read) { isRead = "True"; } else { isRead = "False"; } messageBody = getMessageCountXml(isRead); headers.put("Brief", "t"); dataset = processRequest(this.mFolderUrl, "SEARCH", messageBody, headers); if (dataset != null) { messageCount = dataset.getMessageCount(); } return messageCount; } @Override public int getMessageCount() throws MessagingException { open(OpenMode.READ_WRITE); this.mMessageCount = getMessageCount(true, WebDavStore.this.mAuthCookies); return this.mMessageCount; } @Override public int getUnreadMessageCount() throws MessagingException { open(OpenMode.READ_WRITE); this.mUnreadMessageCount = getMessageCount(false, WebDavStore.this.mAuthCookies); return this.mUnreadMessageCount; } @Override public boolean isOpen() { return this.mIsOpen; } @Override public OpenMode getMode() throws MessagingException { return OpenMode.READ_WRITE; } @Override public String getName() { return this.mName; } @Override public boolean exists() { return true; } @Override public void close() { this.mMessageCount = 0; this.mUnreadMessageCount = 0; this.mIsOpen = false; } @Override public boolean create(FolderType type) throws MessagingException { return true; } @Override public void delete(boolean recursive) throws MessagingException { throw new Error("WebDavFolder.delete() not implemeneted"); } @Override public Message getMessage(String uid) throws MessagingException { return new WebDavMessage(uid, this); } @Override public Message[] getMessages(int start, int end, MessageRetrievalListener listener) throws MessagingException { ArrayList<Message> messages = new ArrayList<Message>(); String[] uids; DataSet dataset = new DataSet(); HashMap<String, String> headers = new HashMap<String, String>(); int uidsLength = -1; String messageBody; int prevStart = start; /** Reverse the message range since 0 index is newest */ start = this.mMessageCount - end; end = start + (end - prevStart); //end = this.mMessageCount - prevStart; if (start < 0 || end < 0 || end < start) { throw new MessagingException(String.format("Invalid message set %d %d", start, end)); } if (start == 0 && end < 10) { end = 10; } /** Verify authentication */ messageBody = getMessagesXml(); headers.put("Brief", "t"); headers.put("Range", "rows=" + start + "-" + end); dataset = processRequest(this.mFolderUrl, "SEARCH", messageBody, headers); uids = dataset.getUids(); HashMap<String, String> uidToUrl = dataset.getUidToUrl(); uidsLength = uids.length; for (int i = 0; i < uidsLength; i++) { if (listener != null) { listener.messageStarted(uids[i], i, uidsLength); } WebDavMessage message = new WebDavMessage(uids[i], this); message.setUrl(uidToUrl.get(uids[i])); messages.add(message); if (listener != null) { listener.messageFinished(message, i, uidsLength); } } return messages.toArray(new Message[] {}); } @Override public Message[] getMessages(MessageRetrievalListener listener) throws MessagingException { return getMessages(null, listener); } @Override public Message[] getMessages(String[] uids, MessageRetrievalListener listener) throws MessagingException { ArrayList<Message> messageList = new ArrayList<Message>(); Message[] messages; if (uids == null || uids.length == 0) { return messageList.toArray(new Message[] {}); } for (int i = 0, count = uids.length; i < count; i++) { if (listener != null) { listener.messageStarted(uids[i], i, count); } WebDavMessage message = new WebDavMessage(uids[i], this); messageList.add(message); if (listener != null) { listener.messageFinished(message, i, count); } } messages = messageList.toArray(new Message[] {}); return messages; } private HashMap<String, String> getMessageUrls(String[] uids) throws MessagingException { HashMap<String, String> uidToUrl = new HashMap<String, String>(); HashMap<String, String> headers = new HashMap<String, String>(); DataSet dataset = new DataSet(); String messageBody; /** Retrieve and parse the XML entity for our messages */ messageBody = getMessageUrlsXml(uids); headers.put("Brief", "t"); dataset = processRequest(this.mFolderUrl, "SEARCH", messageBody, headers); uidToUrl = dataset.getUidToUrl(); return uidToUrl; } @Override public void fetch(Message[] messages, FetchProfile fp, MessageRetrievalListener listener) throws MessagingException { if (messages == null || messages.length == 0) { return; } /** * Fetch message envelope information for the array */ if (fp.contains(FetchProfile.Item.ENVELOPE)) { fetchEnvelope(messages, listener); } /** * Fetch message flag info for the array */ if (fp.contains(FetchProfile.Item.FLAGS)) { fetchFlags(messages, listener); } if (fp.contains(FetchProfile.Item.BODY_SANE)) { fetchMessages(messages, listener, FETCH_BODY_SANE_SUGGESTED_SIZE / 76); } if (fp.contains(FetchProfile.Item.BODY)) { fetchMessages(messages, listener, -1); } // if (fp.contains(FetchProfile.Item.STRUCTURE)) { // for (int i = 0, count = messages.length; i < count; i++) { // if (!(messages[i] instanceof WebDavMessage)) { // throw new MessagingException("WebDavStore fetch called with non-WebDavMessage"); // } // WebDavMessage wdMessage = (WebDavMessage) messages[i]; // // if (listener != null) { // listener.messageStarted(wdMessage.getUid(), i, count); // } // // wdMessage.setBody(null); // // if (listener != null) { // listener.messageFinished(wdMessage, i, count); // } // } // } } /** * Fetches the full messages or up to lines lines and passes them to the message parser. */ private void fetchMessages(Message[] messages, MessageRetrievalListener listener, int lines) throws MessagingException { WebDavHttpClient httpclient; httpclient = getHttpClient(); /** * We can't hand off to processRequest() since we need the stream to parse. */ for (int i = 0, count = messages.length; i < count; i++) { WebDavMessage wdMessage; int statusCode = 0; if (!(messages[i] instanceof WebDavMessage)) { throw new MessagingException("WebDavStore fetch called with non-WebDavMessage"); } wdMessage = (WebDavMessage) messages[i]; if (listener != null) { listener.messageStarted(wdMessage.getUid(), i, count); } /** * If fetch is called outside of the initial list (ie, a locally stored * message), it may not have a URL associated. Verify and fix that */ if (wdMessage.getUrl().equals("")) { wdMessage.setUrl(getMessageUrls(new String[] {wdMessage.getUid()}).get(wdMessage.getUid())); Log.i(K9.LOG_TAG, "Fetching messages with UID = '" + wdMessage.getUid() + "', URL = '" + wdMessage.getUrl() + "'"); if (wdMessage.getUrl().equals("")) { throw new MessagingException("Unable to get URL for message"); } } try { Log.i(K9.LOG_TAG, "Fetching message with UID = '" + wdMessage.getUid() + "', URL = '" + wdMessage.getUrl() + "'"); HttpGet httpget = new HttpGet(new URI(wdMessage.getUrl())); HttpResponse response; HttpEntity entity; httpget.setHeader("translate", "f"); if (mAuthString != null && mAuthenticated) { httpget.setHeader("Authorization", mAuthString); } response = httpclient.executeOverride(httpget); statusCode = response.getStatusLine().getStatusCode(); entity = response.getEntity(); if (statusCode < 200 || statusCode > 300) { throw new IOException("Error during with code " + statusCode + " during fetch: " + response.getStatusLine().toString()); } if (entity != null) { InputStream istream = null; StringBuffer buffer = new StringBuffer(); String tempText = ""; String resultText = ""; BufferedReader reader; int currentLines = 0; istream = WebDavHttpClient.getUngzippedContent(entity); if (lines != -1) { reader = new BufferedReader(new InputStreamReader(istream), 8192); while ((tempText = reader.readLine()) != null && (currentLines < lines)) { buffer.append(tempText+"\r\n"); currentLines++; } istream.close(); resultText = buffer.toString(); istream = new ByteArrayInputStream(resultText.getBytes("UTF-8")); } wdMessage.parse(istream); } } catch (IllegalArgumentException iae) { Log.e(K9.LOG_TAG, "IllegalArgumentException caught " + iae + "\nTrace: " + processException(iae)); throw new MessagingException("IllegalArgumentException caught", iae); } catch (URISyntaxException use) { Log.e(K9.LOG_TAG, "URISyntaxException caught " + use + "\nTrace: " + processException(use)); throw new MessagingException("URISyntaxException caught", use); } catch (IOException ioe) { Log.e(K9.LOG_TAG, "Non-success response code loading message, response code was " + statusCode + "\nURL: " + wdMessage.getUrl() + "\nError: " + ioe.getMessage() + "\nTrace: " + processException(ioe)); throw new MessagingException("Failure code " + statusCode, ioe); } if (listener != null) { listener.messageFinished(wdMessage, i, count); } } } /** * Fetches and sets the message flags for the supplied messages. * The idea is to have this be recursive so that we do a series of medium calls * instead of one large massive call or a large number of smaller calls. */ private void fetchFlags(Message[] startMessages, MessageRetrievalListener listener) throws MessagingException { HashMap<String, Boolean> uidToReadStatus = new HashMap<String, Boolean>(); HashMap<String, String> headers = new HashMap<String, String>(); DataSet dataset = new DataSet(); String messageBody = ""; Message[] messages = new Message[20]; String[] uids; if (startMessages == null || startMessages.length == 0) { return; } if (startMessages.length > 20) { Message[] newMessages = new Message[startMessages.length - 20]; for (int i = 0, count = startMessages.length; i < count; i++) { if (i < 20) { messages[i] = startMessages[i]; } else { newMessages[i - 20] = startMessages[i]; } } fetchFlags(newMessages, listener); } else { messages = startMessages; } uids = new String[messages.length]; for (int i = 0, count = messages.length; i < count; i++) { uids[i] = messages[i].getUid(); } messageBody = getMessageFlagsXml(uids); headers.put("Brief", "t"); dataset = processRequest(this.mFolderUrl, "SEARCH", messageBody, headers); if (dataset == null) { throw new MessagingException("Data Set from request was null"); } uidToReadStatus = dataset.getUidToRead(); for (int i = 0, count = messages.length; i < count; i++) { if (!(messages[i] instanceof WebDavMessage)) { throw new MessagingException("WebDavStore fetch called with non-WebDavMessage"); } WebDavMessage wdMessage = (WebDavMessage) messages[i]; if (listener != null) { listener.messageStarted(messages[i].getUid(), i, count); } wdMessage.setFlagInternal(Flag.SEEN, uidToReadStatus.get(wdMessage.getUid())); if (listener != null) { listener.messageFinished(messages[i], i, count); } } } /** * Fetches and parses the message envelopes for the supplied messages. * The idea is to have this be recursive so that we do a series of medium calls * instead of one large massive call or a large number of smaller calls. * Call it a happy balance */ private void fetchEnvelope(Message[] startMessages, MessageRetrievalListener listener) throws MessagingException { HashMap<String, ParsedMessageEnvelope> envelopes = new HashMap<String, ParsedMessageEnvelope>(); HashMap<String, String> headers = new HashMap<String, String>(); DataSet dataset = new DataSet(); String messageBody = ""; String[] uids; Message[] messages = new Message[10]; if (startMessages == null || startMessages.length == 0) { return; } if (startMessages.length > 10) { Message[] newMessages = new Message[startMessages.length - 10]; for (int i = 0, count = startMessages.length; i < count; i++) { if (i < 10) { messages[i] = startMessages[i]; } else { newMessages[i - 10] = startMessages[i]; } } fetchEnvelope(newMessages, listener); } else { messages = startMessages; } uids = new String[messages.length]; for (int i = 0, count = messages.length; i < count; i++) { uids[i] = messages[i].getUid(); } messageBody = getMessageEnvelopeXml(uids); headers.put("Brief", "t"); dataset = processRequest(this.mFolderUrl, "SEARCH", messageBody, headers); envelopes = dataset.getMessageEnvelopes(); int count = messages.length; for (int i = messages.length - 1; i >= 0; i--) { if (!(messages[i] instanceof WebDavMessage)) { throw new MessagingException("WebDavStore fetch called with non-WebDavMessage"); } WebDavMessage wdMessage = (WebDavMessage) messages[i]; if (listener != null) { listener.messageStarted(messages[i].getUid(), i, count); } wdMessage.setNewHeaders(envelopes.get(wdMessage.getUid())); wdMessage.setFlagInternal(Flag.SEEN, envelopes.get(wdMessage.getUid()).getReadStatus()); if (listener != null) { listener.messageFinished(messages[i], i, count); } } } @Override public Flag[] getPermanentFlags() throws MessagingException { return PERMANENT_FLAGS; } @Override public void setFlags(Message[] messages, Flag[] flags, boolean value) throws MessagingException { String[] uids = new String[messages.length]; for (int i = 0, count = messages.length; i < count; i++) { uids[i] = messages[i].getUid(); } for (int i = 0, count = flags.length; i < count; i++) { Flag flag = flags[i]; if (flag == Flag.SEEN) { markServerMessagesRead(uids, value); } else if (flag == Flag.DELETED) { deleteServerMessages(uids); } } } private void markServerMessagesRead(String[] uids, boolean read) throws MessagingException { String messageBody = ""; HashMap<String, String> headers = new HashMap<String, String>(); HashMap<String, String> uidToUrl = getMessageUrls(uids); DataSet dataset = new DataSet(); String[] urls = new String[uids.length]; for (int i = 0, count = uids.length; i < count; i++) { urls[i] = uidToUrl.get(uids[i]); } messageBody = getMarkMessagesReadXml(urls, read); headers.put("Brief", "t"); headers.put("If-Match", "*"); processRequest(this.mFolderUrl, "BPROPPATCH", messageBody, headers, false); } private void deleteServerMessages(String[] uids) throws MessagingException { HashMap<String, String> uidToUrl = getMessageUrls(uids); String[] urls = new String[uids.length]; for (int i = 0, count = uids.length; i < count; i++) { HashMap<String, String> headers = new HashMap<String, String>(); String uid = uids[i]; String url = uidToUrl.get(uid); String destinationUrl = generateDeleteUrl(url); /** * If the destination is the same as the origin, assume delete forever */ if (destinationUrl.equals(url)) { headers.put("Brief", "t"); processRequest(url, "DELETE", null, headers, false); } else { headers.put("Destination", generateDeleteUrl(url)); headers.put("Brief", "t"); processRequest(url, "MOVE", null, headers, false); } } } private String generateDeleteUrl(String startUrl) { String[] urlParts = startUrl.split("/"); String filename = urlParts[urlParts.length - 1]; String finalUrl = WebDavStore.this.mUrl + "Deleted%20Items/" + filename; return finalUrl; } @Override public void appendMessages(Message[] messages) throws MessagingException { appendWebDavMessages(messages); } public Message[] appendWebDavMessages(Message[] messages) throws MessagingException { Message[] retMessages = new Message[messages.length]; int ind = 0; WebDavHttpClient httpclient = getHttpClient(); for (Message message : messages) { HttpGeneric httpmethod; HttpResponse response; StringEntity bodyEntity; int statusCode; try { String subject; try { subject = message.getSubject(); } catch (MessagingException e) { Log.e(K9.LOG_TAG, "MessagingException while retrieving Subject: " + e); subject = ""; } ByteArrayOutputStream out; try { out = new ByteArrayOutputStream(message.getSize()); } catch (MessagingException e) { Log.e(K9.LOG_TAG, "MessagingException while getting size of message: " + e); out = new ByteArrayOutputStream(); } open(OpenMode.READ_WRITE); EOLConvertingOutputStream msgOut = new EOLConvertingOutputStream( new BufferedOutputStream(out, 1024)); message.writeTo(msgOut); msgOut.flush(); bodyEntity = new StringEntity(out.toString(), "UTF-8"); bodyEntity.setContentType("message/rfc822"); String messageURL = mFolderUrl; if (messageURL.endsWith("/") == false) { messageURL += "/"; } messageURL += URLEncoder.encode(message.getUid() + ":" + System.currentTimeMillis() + ".eml"); Log.i(K9.LOG_TAG, "Uploading message as " + messageURL); httpmethod = new HttpGeneric(messageURL); httpmethod.setMethod("PUT"); httpmethod.setEntity(bodyEntity); String mAuthString = getAuthString(); if (mAuthString != null) { httpmethod.setHeader("Authorization", mAuthString); } response = httpclient.executeOverride(httpmethod); statusCode = response.getStatusLine().getStatusCode(); if (statusCode < 200 || statusCode > 300) { throw new IOException("Error with status code " + statusCode + " while sending/appending message. Response = " + response.getStatusLine().toString() + " for message " + messageURL); } WebDavMessage retMessage = new WebDavMessage(message.getUid(), this); retMessage.setUrl(messageURL); retMessages[ind++] = retMessage; } catch (Exception e) { throw new MessagingException("Unable to append", e); } } return retMessages; } @Override public boolean equals(Object o) { return false; } public String getUidFromMessageId(Message message) throws MessagingException { Log.e(K9.LOG_TAG, "Unimplemented method getUidFromMessageId in WebDavStore.WebDavFolder could lead to duplicate messages " + " being uploaded to the Sent folder"); return null; } public void setFlags(Flag[] flags, boolean value) throws MessagingException { Log.e(K9.LOG_TAG, "Unimplemented method setFlags(Flag[], boolean) breaks markAllMessagesAsRead and EmptyTrash"); // Try to make this efficient by not retrieving all of the messages return; } } /** * A WebDav Message */ class WebDavMessage extends MimeMessage { private String mUrl = ""; WebDavMessage(String uid, Folder folder) throws MessagingException { this.mUid = uid; this.mFolder = folder; } public void setUrl(String url) { //TODO: This is a not as ugly hack (ie, it will actually work) //XXX: prevent URLs from getting to us that are broken if (!(url.toLowerCase().contains("http"))) { if (!(url.startsWith("/"))) { url = "/" + url; } url = WebDavStore.this.mUrl + this.mFolder + url; } String[] urlParts = url.split("/"); int length = urlParts.length; String end = urlParts[length - 1]; this.mUrl = ""; url = ""; /** * We have to decode, then encode the URL because Exchange likes to * not properly encode all characters */ try { end = java.net.URLDecoder.decode(end, "UTF-8"); end = java.net.URLEncoder.encode(end, "UTF-8"); end = end.replaceAll("\\+", "%20"); } catch (UnsupportedEncodingException uee) { Log.e(K9.LOG_TAG, "UnsupportedEncodingException caught in setUrl: " + uee + "\nTrace: " + processException(uee)); } catch (IllegalArgumentException iae) { Log.e(K9.LOG_TAG, "IllegalArgumentException caught in setUrl: " + iae + "\nTrace: " + processException(iae)); } for (int i = 0; i < length - 1; i++) { if (i != 0) { url = url + "/" + urlParts[i]; } else { url = urlParts[i]; } } url = url + "/" + end; this.mUrl = url; } public String getUrl() { return this.mUrl; } public void setSize(int size) { this.mSize = size; } public void parse(InputStream in) throws IOException, MessagingException { super.parse(in); } public void setFlagInternal(Flag flag, boolean set) throws MessagingException { super.setFlag(flag, set); } public void setNewHeaders(ParsedMessageEnvelope envelope) throws MessagingException { String[] headers = envelope.getHeaderList(); HashMap<String, String> messageHeaders = envelope.getMessageHeaders(); for (int i = 0, count = headers.length; i < count; i++) { String headerValue = messageHeaders.get(headers[i]); if (headers[i].equals("Content-Length")) { int size = Integer.parseInt(messageHeaders.get(headers[i])); this.setSize(size); } if (headerValue != null && !headerValue.equals("")) { this.addHeader(headers[i], headerValue); } } } @Override public void delete(String trashFolderName) throws MessagingException { WebDavFolder wdFolder = (WebDavFolder)getFolder(); Log.i(K9.LOG_TAG, "Deleting message by moving to " + trashFolderName); wdFolder.moveMessages(new Message[] { this }, wdFolder.getStore().getFolder(trashFolderName)); } @Override public void setFlag(Flag flag, boolean set) throws MessagingException { super.setFlag(flag, set); mFolder.setFlags(new Message[] { this }, new Flag[] { flag }, set); } } /** * XML Parsing Handler * Can handle all XML handling needs */ public class WebDavHandler extends DefaultHandler { private DataSet mDataSet = new DataSet(); private Stack<String> mOpenTags = new Stack<String>(); public DataSet getDataSet() { return this.mDataSet; } @Override public void startDocument() throws SAXException { this.mDataSet = new DataSet(); } @Override public void endDocument() throws SAXException { /* Do nothing */ } @Override public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { mOpenTags.push(localName); } @Override public void endElement(String namespaceURI, String localName, String qName) { mOpenTags.pop(); /** Reset the hash temp variables */ if (localName.equals("response")) { this.mDataSet.finish(); } } @Override public void characters(char ch[], int start, int length) { String value = new String(ch, start, length); mDataSet.addValue(value, mOpenTags.peek()); } } /** * Data set for a single E-Mail message's required headers (the envelope) * Only provides accessor methods to the stored data. All processing should be * done elsewhere. This is done rather than having multiple hashmaps * associating UIDs to values */ public class ParsedMessageEnvelope { /** * Holds the mappings from the name returned from Exchange to the MIME format header name */ private final HashMap<String, String> mHeaderMappings = new HashMap<String, String>() { { put("mime-version", "MIME-Version"); put("content-type", "Content-Type"); put("subject", "Subject"); put("date", "Date"); put("thread-topic", "Thread-Topic"); put("thread-index", "Thread-Index"); put("from", "From"); put("to", "To"); put("in-reply-to", "In-Reply-To"); put("cc", "Cc"); put("getcontentlength", "Content-Length"); } }; private boolean mReadStatus = false; private String mUid = ""; private HashMap<String, String> mMessageHeaders = new HashMap<String, String>(); private ArrayList<String> mHeaders = new ArrayList<String>(); public void addHeader(String field, String value) { String headerName = mHeaderMappings.get(field); //Log.i(K9.LOG_TAG, "header " + headerName + " = '" + value + "'"); if (headerName != null) { this.mMessageHeaders.put(mHeaderMappings.get(field), value); this.mHeaders.add(mHeaderMappings.get(field)); } } public HashMap<String, String> getMessageHeaders() { return this.mMessageHeaders; } public String[] getHeaderList() { return this.mHeaders.toArray(new String[] {}); } public void setReadStatus(boolean status) { this.mReadStatus = status; } public boolean getReadStatus() { return this.mReadStatus; } public void setUid(String uid) { if (uid != null) { this.mUid = uid; } } public String getUid() { return this.mUid; } } /** * Dataset for all XML parses. * Data is stored in a single format inside the class and is formatted appropriately depending on the accessor calls made. */ public class DataSet { private HashMap<String, HashMap> mData = new HashMap<String, HashMap>(); private HashMap<String, String> mLostData = new HashMap<String, String>(); private String mUid = ""; private HashMap<String, String> mTempData = new HashMap<String, String>(); public void addValue(String value, String tagName) { if (tagName.equals("uid")) { mUid = value; } if (mTempData.containsKey(tagName)) { mTempData.put(tagName, mTempData.get(tagName) + value); } else { mTempData.put(tagName, value); } } public void finish() { if (mUid != null && mTempData != null) { mData.put(mUid, mTempData); } else if (mTempData != null) { /* Lost Data are for requests that don't include a message UID. * These requests should only have a depth of one for the response so it will never get stomped over. */ mLostData = mTempData; String visibleCount = mLostData.get("visiblecount"); } mUid = ""; mTempData = new HashMap<String, String>(); } /** * Returns a hashmap of Message UID => Message Url */ public HashMap<String, String> getUidToUrl() { HashMap<String, String> uidToUrl = new HashMap<String, String>(); for (String uid : mData.keySet()) { HashMap<String, String> data = mData.get(uid); String value = data.get("href"); if (value != null && !value.equals("")) { uidToUrl.put(uid, value); } } return uidToUrl; } /** * Returns a hashmap of Message UID => Read Status */ public HashMap<String, Boolean> getUidToRead() { HashMap<String, Boolean> uidToRead = new HashMap<String, Boolean>(); for (String uid : mData.keySet()) { HashMap<String, String> data = mData.get(uid); String readStatus = data.get("read"); if (readStatus != null && !readStatus.equals("")) { Boolean value = readStatus.equals("0") ? false : true; uidToRead.put(uid, value); } } return uidToRead; } /** * Returns an array of all hrefs (urls) that were received */ public String[] getHrefs() { ArrayList<String> hrefs = new ArrayList<String>(); for (String uid : mData.keySet()) { HashMap<String, String> data = mData.get(uid); String href = data.get("href"); hrefs.add(href); } return hrefs.toArray(new String[] {}); } /** * Return an array of all Message UIDs that were received */ public String[] getUids() { ArrayList<String> uids = new ArrayList<String>(); for (String uid : mData.keySet()) { uids.add(uid); } return uids.toArray(new String[] {}); } /** * Returns the message count as it was retrieved */ public int getMessageCount() { int messageCount = -1; for (String uid : mData.keySet()) { HashMap<String, String> data = mData.get(uid); String count = data.get("visiblecount"); if (count != null && !count.equals("")) { messageCount = Integer.parseInt(count); } } return messageCount; } /** * Returns a HashMap of message UID => ParsedMessageEnvelope */ public HashMap<String, ParsedMessageEnvelope> getMessageEnvelopes() { HashMap<String, ParsedMessageEnvelope> envelopes = new HashMap<String, ParsedMessageEnvelope>(); for (String uid : mData.keySet()) { ParsedMessageEnvelope envelope = new ParsedMessageEnvelope(); HashMap<String, String> data = mData.get(uid); if (data != null) { for (String header : data.keySet()) { if (header.equals("read")) { String read = data.get(header); Boolean readStatus = read.equals("0") ? false : true; envelope.setReadStatus(readStatus); } else if (header.equals("date")) { /** * Exchange doesn't give us rfc822 dates like it claims. The date is in the format: * yyyy-MM-dd'T'HH:mm:ss.SSS<Single digit representation of timezone, so far, all instances are Z> */ String date = data.get(header); date = date.substring(0, date.length() - 1); DateFormat dfInput = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS"); DateFormat dfOutput = new SimpleDateFormat("EEE, d MMM yy HH:mm:ss Z"); String tempDate = ""; try { Date parsedDate = dfInput.parse(date); tempDate = dfOutput.format(parsedDate); } catch (java.text.ParseException pe) { Log.e(K9.LOG_TAG, "Error parsing date: "+ pe + "\nTrace: " + processException(pe)); } envelope.addHeader(header, tempDate); } else { envelope.addHeader(header, data.get(header)); } } } if (envelope != null) { envelopes.put(uid, envelope); } } return envelopes; } } /** * New HTTP Method that allows changing of the method and generic handling * Needed for WebDAV custom methods such as SEARCH and PROPFIND */ public class HttpGeneric extends HttpEntityEnclosingRequestBase { public String METHOD_NAME = "POST"; public HttpGeneric() { super(); } public HttpGeneric(final URI uri) { super(); setURI(uri); } /** * @throws IllegalArgumentException if the uri is invalid. */ public HttpGeneric(final String uri) { super(); if (K9.DEBUG) { Log.v(K9.LOG_TAG, "Starting uri = '" + uri + "'"); } String[] urlParts = uri.split("/"); int length = urlParts.length; String end = urlParts[length - 1]; String url = ""; /** * We have to decode, then encode the URL because Exchange likes to * not properly encode all characters */ try { if (length > 3) { end = java.net.URLDecoder.decode(end, "UTF-8"); end = java.net.URLEncoder.encode(end, "UTF-8"); end = end.replaceAll("\\+", "%20"); } } catch (UnsupportedEncodingException uee) { Log.e(K9.LOG_TAG, "UnsupportedEncodingException caught in HttpGeneric(String uri): " + uee + "\nTrace: " + processException(uee)); } catch (IllegalArgumentException iae) { Log.e(K9.LOG_TAG, "IllegalArgumentException caught in HttpGeneric(String uri): " + iae + "\nTrace: " + processException(iae)); } for (int i = 0; i < length - 1; i++) { if (i != 0) { url = url + "/" + urlParts[i]; } else { url = urlParts[i]; } } if (K9.DEBUG) { Log.v(K9.LOG_TAG, "url = '" + url + "' length = " + url.length() + ", end = '" + end + "' length = " + end.length()); } url = url + "/" + end; Log.i(K9.LOG_TAG, "url = " + url); setURI(URI.create(url)); } @Override public String getMethod() { return METHOD_NAME; } public void setMethod(String method) { if (method != null) { METHOD_NAME = method; } } } public static class WebDavHttpClient extends DefaultHttpClient { /* * 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. */ public static void modifyRequestToAcceptGzipResponse(HttpRequest request) { Log.i(K9.LOG_TAG, "Requesting gzipped data"); request.addHeader("Accept-Encoding", "gzip"); } public static InputStream getUngzippedContent(HttpEntity entity) throws IOException { InputStream responseStream = entity.getContent(); if (responseStream == null) return responseStream; Header header = entity.getContentEncoding(); if (header == null) return responseStream; String contentEncoding = header.getValue(); if (contentEncoding == null) return responseStream; if (contentEncoding.contains("gzip")) { Log.i(K9.LOG_TAG, "Response is gzipped"); responseStream = new GZIPInputStream(responseStream); } return responseStream; } public HttpResponse executeOverride(HttpUriRequest request) throws IOException { modifyRequestToAcceptGzipResponse(request); return super.execute(request); } } }
diff --git a/generic.sesam/search-command-config/src/main/java/no/sesat/search/mode/config/SolrCommandConfig.java b/generic.sesam/search-command-config/src/main/java/no/sesat/search/mode/config/SolrCommandConfig.java index 8b3054f33..a8a13a55d 100644 --- a/generic.sesam/search-command-config/src/main/java/no/sesat/search/mode/config/SolrCommandConfig.java +++ b/generic.sesam/search-command-config/src/main/java/no/sesat/search/mode/config/SolrCommandConfig.java @@ -1,233 +1,233 @@ /* Copyright (2008-2009) Schibsted ASA * This file is part of SESAT. * * SESAT is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SESAT is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with SESAT. If not, see <http://www.gnu.org/licenses/>. * AbstractXmlSearchConfiguration.java * * Created on June 12, 2006, 10:58 AM * */ package no.sesat.search.mode.config; import java.util.Collections; import java.util.HashMap; import java.util.Map; import no.sesat.search.mode.SearchModeFactory.Context; import no.sesat.search.mode.config.CommandConfig.Controller; import no.sesat.search.result.Navigator; import org.w3c.dom.Element; /** Searching against a Solr index using the Solrj client. * * @version $Id$ */ @Controller("SolrSearchCommand") public class SolrCommandConfig extends CommandConfig implements FacetedCommandConfig { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- private String serverUrl = ""; private String filteringQuery = ""; private final Map<String,String> sort = new HashMap<String,String>(); private Integer timeout = Integer.MAX_VALUE; private final Map<String, Navigator> facets = new HashMap<String,Navigator>(); private String facetToolkit; private String queryType = null; // Static -------------------------------------------------------- // Constructors -------------------------------------------------- // Public -------------------------------------------------------- /** * Getter for property serverUrl. * The value returned is the key used * to look up the real value via SiteConfiguration(via in configuration.properties) * * @return Value of property serverUrl. */ public String getServerUrl() { return this.serverUrl; } /** * @see #getServerUrl() * @param serverUrl New value of property serverUrl. */ public void setServerUrl(final String serverUrl) { this.serverUrl = serverUrl; } /** The filter query. * Used like an additional filter to narrow the query down. * @see org.apache.solr.client.solrj.SolrQuery#setFilterQueries(String...) * * TODO change bean property from String to String[] to support multiple filtering queries. * * @return */ public String getFilteringQuery(){ return filteringQuery; } /** @see #getFilteringQuery() * * @param filteringQuery */ public void setFilteringQuery(final String filteringQuery){ this.filteringQuery = filteringQuery; } /** Sets the qt parameter in turn choosing a query handler. * {@link http://wiki.apache.org/solr/CoreQueryParameters} * * @return */ public String getQueryType(){ return queryType; } /** @see #getQueryType() * * @param filteringQuery */ public void setQueryType(final String queryType){ this.queryType = queryType; } /** @see #setFieldFilters(java.lang.String[]) * * @return Value of map property sort. */ public Map<String,String> getSortMap() { return Collections.unmodifiableMap(sort); } public void clearSort(){ sort.clear(); } /** * Syntax: sort="fieldName1 asc, fieldName2 desc" * * Just "fieldName1" will presume ascending (asc) order. * * @param sortFields Array of sort fields. */ public void setSort(final String[] sortFields) { for (String string : sortFields) { setSort(string); } } /** Specified in milliseconds. * Default is Integer.MAX_VALUE. * * Only actived when root log4j logger is set to INFO or higher. * Rationale here is that we don't want timeouts in debugging environments. * @param integer */ public void setTimeout(final Integer integer){ timeout = integer; } /** @see #setTimeout(java.lang.Integer) * * @return */ public int getTimeout(){ return timeout; } /** * * @return */ @Override public Map<String, Navigator> getFacets() { return facets; } /** * * @param navigatorKey * @return */ @Override public Navigator getFacet(final String navigatorKey) { return facets.get(navigatorKey); } public String getFacetToolkit() { return facetToolkit; } public void setFacetToolkit(final String toolkit){ this.facetToolkit = toolkit; } @Override public SearchConfiguration readSearchConfiguration( final Element element, final SearchConfiguration inherit, final Context context) { if(null!=inherit && inherit instanceof SolrCommandConfig){ sort.putAll(((SolrCommandConfig)inherit).getSortMap()); } - ModesSearchConfigurationDeserializer.readSearchConfiguration(this, element, inherit); + super.readSearchConfiguration(element, inherit, context); if (element.hasAttribute("sort")) { if (element.getAttribute("sort").length() == 0) { clearSort(); } } FacetedSearchConfigurationDeserializer.readNavigators(element, this, inherit, facets); return this; } // Z implementation ---------------------------------------------- // Y overrides --------------------------------------------------- // Package protected --------------------------------------------- // Protected ----------------------------------------------------- // Private ------------------------------------------------------- private void setSort(final String sortFieldAndOrder) { final String parsed[] = sortFieldAndOrder.trim().split(" "); final String field = parsed[0].trim(); sort.put(field, (parsed.length > 1) ? parsed[1].trim() : "asc"); } // Inner classes ------------------------------------------------- }
true
true
public SearchConfiguration readSearchConfiguration( final Element element, final SearchConfiguration inherit, final Context context) { if(null!=inherit && inherit instanceof SolrCommandConfig){ sort.putAll(((SolrCommandConfig)inherit).getSortMap()); } ModesSearchConfigurationDeserializer.readSearchConfiguration(this, element, inherit); if (element.hasAttribute("sort")) { if (element.getAttribute("sort").length() == 0) { clearSort(); } } FacetedSearchConfigurationDeserializer.readNavigators(element, this, inherit, facets); return this; }
public SearchConfiguration readSearchConfiguration( final Element element, final SearchConfiguration inherit, final Context context) { if(null!=inherit && inherit instanceof SolrCommandConfig){ sort.putAll(((SolrCommandConfig)inherit).getSortMap()); } super.readSearchConfiguration(element, inherit, context); if (element.hasAttribute("sort")) { if (element.getAttribute("sort").length() == 0) { clearSort(); } } FacetedSearchConfigurationDeserializer.readNavigators(element, this, inherit, facets); return this; }
diff --git a/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/c/embedded/CEmbeddedBackend.java b/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/c/embedded/CEmbeddedBackend.java index 0df05423d..492b2991b 100644 --- a/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/c/embedded/CEmbeddedBackend.java +++ b/eclipse/plugins/net.sf.orcc.backends/src/net/sf/orcc/backends/c/embedded/CEmbeddedBackend.java @@ -1,173 +1,173 @@ /* * Copyright (c) 2009, IETR/INSA of Rennes * 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 IETR/INSA of Rennes nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ package net.sf.orcc.backends.c.embedded; import java.io.File; import java.util.List; import net.sf.orcc.backends.AbstractBackend; import net.sf.orcc.backends.StandardPrinter; import net.sf.orcc.backends.c.CExpressionPrinter; import net.sf.orcc.backends.c.CTypePrinter; import net.sf.orcc.df.Actor; import net.sf.orcc.df.Network; import net.sf.orcc.df.transform.Instantiator; import net.sf.orcc.df.transform.NetworkFlattener; import net.sf.orcc.moc.MoC; import net.sf.orcc.moc.SDFMoC; import net.sf.orcc.tools.classifier.Classifier; import net.sf.orcc.util.OrccLogger; import org.eclipse.core.resources.IFile; /** * C backend targetting embedded systems * * @author mpelcat */ public class CEmbeddedBackend extends AbstractBackend { @Override protected void doInitializeOptions() { // Set Algo, Code, Code/src and Code/IDL directory File algoDir = new File(path + "/Algo"); File codeDir = new File(path + "/Code"); File srcDir = new File(path + "/Code/src"); File idlDir = new File(path + "/Code/IDL"); // If directories don't exist, create them if (!algoDir.exists()) { algoDir.mkdirs(); } if (!codeDir.exists()) { codeDir.mkdirs(); } if (!srcDir.exists()) { srcDir.mkdirs(); } if (!idlDir.exists()) { idlDir.mkdirs(); } } @Override protected void doTransformActor(Actor actor) { } @Override protected void doVtlCodeGeneration(List<IFile> files) { // do not generate an embedded C VTL } @Override protected void doXdfCodeGeneration(Network network) { // Transform all actors of the network transformActors(network.getAllActors()); printActors(network.getAllActors()); StandardPrinter printer = new StandardPrinter( "net/sf/orcc/backends/c/embedded/Network.stg"); printer.setTypePrinter(new CTypePrinter()); printer.setExpressionPrinter(new CExpressionPrinter()); // instantiate and flattens network new Instantiator(false, fifoSize).doSwitch(network); new NetworkFlattener().doSwitch(network); // This call is needed to associate instances to network vertices network.computeTemplateMaps(); // The classification gives production and consumption information from // the graph - OrccLogger.trace("Starting classification of actors... "); + OrccLogger.traceln("Starting classification of actors... "); new Classifier().doSwitch(network); OrccLogger.traceln("done"); // Check that all actors have SDF MoC // or CSDF (converted to SDF) boolean isSDF = true; for (Actor actor : network.getAllActors()) { MoC moc = actor.getMoC(); if (moc.isSDF()) { // This is what we want, do nothing } else { if (moc.isCSDF()) { // TODO CSDF actor will be converted into SDF } else { // Actor is neither SDF nor CSDF. Cannot use the backend isSDF = false; } } } // Print actors if (isSDF) { SDFMoC moc = (SDFMoC) network.getAllActors().get(0).getMoC(); moc.toString(); OrccLogger.traceln("Printing network..."); printer.print("./Algo/" + network.getName() + ".graphml", path, network); } else { OrccLogger .traceln("The network is not SDF. Other models are not yet supported."); } } /** * Instead of printing actors' instances like in the C backend, we wish to * print actors and reference them from the network generated code. */ @Override protected boolean printActor(Actor actor) { boolean result = false; // print IDL StandardPrinter printerIDL = new StandardPrinter( "net/sf/orcc/backends/c/embedded/ActorIDL.stg", false); printerIDL.setExpressionPrinter(new CExpressionPrinter()); printerIDL.setTypePrinter(new CTypePrinter()); result = printerIDL.print("./Code/IDL/" + actor.getSimpleName() + ".idl", path, actor); // Print C code StandardPrinter printerC = new StandardPrinter( "net/sf/orcc/backends/c/embedded/ActorC.stg", false); printerC.setExpressionPrinter(new CExpressionPrinter()); printerC.setTypePrinter(new CTypePrinter()); result |= printerC.print("./Code/src/" + actor.getSimpleName() + ".c", path, actor); return result; } }
true
true
protected void doXdfCodeGeneration(Network network) { // Transform all actors of the network transformActors(network.getAllActors()); printActors(network.getAllActors()); StandardPrinter printer = new StandardPrinter( "net/sf/orcc/backends/c/embedded/Network.stg"); printer.setTypePrinter(new CTypePrinter()); printer.setExpressionPrinter(new CExpressionPrinter()); // instantiate and flattens network new Instantiator(false, fifoSize).doSwitch(network); new NetworkFlattener().doSwitch(network); // This call is needed to associate instances to network vertices network.computeTemplateMaps(); // The classification gives production and consumption information from // the graph OrccLogger.trace("Starting classification of actors... "); new Classifier().doSwitch(network); OrccLogger.traceln("done"); // Check that all actors have SDF MoC // or CSDF (converted to SDF) boolean isSDF = true; for (Actor actor : network.getAllActors()) { MoC moc = actor.getMoC(); if (moc.isSDF()) { // This is what we want, do nothing } else { if (moc.isCSDF()) { // TODO CSDF actor will be converted into SDF } else { // Actor is neither SDF nor CSDF. Cannot use the backend isSDF = false; } } } // Print actors if (isSDF) { SDFMoC moc = (SDFMoC) network.getAllActors().get(0).getMoC(); moc.toString(); OrccLogger.traceln("Printing network..."); printer.print("./Algo/" + network.getName() + ".graphml", path, network); } else { OrccLogger .traceln("The network is not SDF. Other models are not yet supported."); } }
protected void doXdfCodeGeneration(Network network) { // Transform all actors of the network transformActors(network.getAllActors()); printActors(network.getAllActors()); StandardPrinter printer = new StandardPrinter( "net/sf/orcc/backends/c/embedded/Network.stg"); printer.setTypePrinter(new CTypePrinter()); printer.setExpressionPrinter(new CExpressionPrinter()); // instantiate and flattens network new Instantiator(false, fifoSize).doSwitch(network); new NetworkFlattener().doSwitch(network); // This call is needed to associate instances to network vertices network.computeTemplateMaps(); // The classification gives production and consumption information from // the graph OrccLogger.traceln("Starting classification of actors... "); new Classifier().doSwitch(network); OrccLogger.traceln("done"); // Check that all actors have SDF MoC // or CSDF (converted to SDF) boolean isSDF = true; for (Actor actor : network.getAllActors()) { MoC moc = actor.getMoC(); if (moc.isSDF()) { // This is what we want, do nothing } else { if (moc.isCSDF()) { // TODO CSDF actor will be converted into SDF } else { // Actor is neither SDF nor CSDF. Cannot use the backend isSDF = false; } } } // Print actors if (isSDF) { SDFMoC moc = (SDFMoC) network.getAllActors().get(0).getMoC(); moc.toString(); OrccLogger.traceln("Printing network..."); printer.print("./Algo/" + network.getName() + ".graphml", path, network); } else { OrccLogger .traceln("The network is not SDF. Other models are not yet supported."); } }
diff --git a/src/edu/gatech/oad/antlab/person/Person2.java b/src/edu/gatech/oad/antlab/person/Person2.java index 108e9b4..fadcc34 100644 --- a/src/edu/gatech/oad/antlab/person/Person2.java +++ b/src/edu/gatech/oad/antlab/person/Person2.java @@ -1,63 +1,63 @@ package edu.gatech.oad.antlab.person; /** * A simple class for person 2 * returns their name and a * modified string * * @author Vraj Patel * @version 1.1 */ public class Person2 { /** Holds the persons real name */ private String name; /** * The constructor, takes in the persons * name * @param pname the person's real name */ public Person2(String pname) { name = pname; } /** * This method should take the string * input and return its characters in * random order. * given "gtg123b" it should return * something like "g3tb1g2". * * @param input the string to be modified * @return the modified string */ private String calc(String input) { //Person 2 put your implementation here char[] charArray = input.toCharArray(); int shuffle = input.length(); for (int i = 0; i < shuffle; i++) { int index1 = (int) (Math.random() * charArray.length); int index2 = (int) (Math.random() * charArray.length); - char temp1 = turtle[index1]; - char temp2 = turtle[index2]; + char temp1 = charArray[index1]; + char temp2 = charArray[index2]; charArray[index2] = temp1; charArray[index1] = temp2; } String newString = new String(charArray); return newString; } /** * Return a string rep of this object * that varies with an input string * * @param input the varying string * @return the string representing the * object */ public String toString(String input) { return name + calc(input); } }
true
true
private String calc(String input) { //Person 2 put your implementation here char[] charArray = input.toCharArray(); int shuffle = input.length(); for (int i = 0; i < shuffle; i++) { int index1 = (int) (Math.random() * charArray.length); int index2 = (int) (Math.random() * charArray.length); char temp1 = turtle[index1]; char temp2 = turtle[index2]; charArray[index2] = temp1; charArray[index1] = temp2; } String newString = new String(charArray); return newString; }
private String calc(String input) { //Person 2 put your implementation here char[] charArray = input.toCharArray(); int shuffle = input.length(); for (int i = 0; i < shuffle; i++) { int index1 = (int) (Math.random() * charArray.length); int index2 = (int) (Math.random() * charArray.length); char temp1 = charArray[index1]; char temp2 = charArray[index2]; charArray[index2] = temp1; charArray[index1] = temp2; } String newString = new String(charArray); return newString; }
diff --git a/src/org/joval/plugin/RemotePlugin.java b/src/org/joval/plugin/RemotePlugin.java index 1d969723..a02b3b1d 100755 --- a/src/org/joval/plugin/RemotePlugin.java +++ b/src/org/joval/plugin/RemotePlugin.java @@ -1,193 +1,193 @@ // Copyright (C) 2011 jOVAL.org. All rights reserved. // This software is licensed under the AGPL 3.0 license available at http://www.joval.org/agpl_v3.txt package org.joval.plugin; import java.io.File; import java.io.IOException; import java.net.UnknownHostException; import java.util.List; import java.util.logging.Level; import org.vngx.jsch.exception.JSchException; import org.joval.discovery.SessionFactory; import org.joval.identity.Credential; import org.joval.intf.di.IJovaldiConfiguration; import org.joval.intf.identity.ICredential; import org.joval.intf.identity.ILocked; import org.joval.intf.system.IBaseSession; import org.joval.intf.system.IEnvironment; import org.joval.intf.system.ISession; import org.joval.intf.windows.system.IWindowsSession; import org.joval.os.embedded.system.IosSession; import org.joval.os.unix.remote.system.UnixSession; import org.joval.os.windows.identity.WindowsCredential; import org.joval.oval.di.BasePlugin; import org.joval.ssh.identity.SshCredential; import org.joval.ssh.system.SshSession; import org.joval.util.JOVALSystem; /** * Implementation of an IJovaldiPlugin for the Windows operating system. * * @author David A. Solin * @version %I% %G% */ public class RemotePlugin extends BasePlugin { private String hostname; private ICredential cred; private SessionFactory sessionFactory; /** * Create a plugin solely for test evaluation. */ public RemotePlugin() { super(); } // Implement IJovaldiPlugin public void setDataDirectory(File dir) { try { sessionFactory = new SessionFactory(dir); } catch (IOException e) { JOVALSystem.getLogger().log(Level.WARNING, e.getMessage(), e); } } /** * Create a plugin for data retrieval and test evaluation. * * A note about the redirect64 setting: If true, then registry and filesystem redirection will be active for 64-bit * machines. This means that redirected assets (files, registry entries) will appear to be in their 32-bit locations. * Hence, if you intend to run tests that specifically look for assets in their REAL 64-bit locations this should be set * to false. If you intend to run tests that were designed for 32-bit Windows systems, then set this parameter to true. */ public boolean configure(String[] args, IJovaldiConfiguration jDIconfig) { if (jDIconfig.printingHelp()) return true; String hostname = null; boolean redirect64 = true; String domain=null, username=null, password=null, passphrase=null, rootPassword=null; File privateKey = null; for (int i=0; i < args.length; i++) { if (args[i].equals("-hostname")) { hostname = args[++i]; } else if (args[i].equals("-domain")) { domain = args[++i]; } else if (args[i].equals("-username")) { username = args[++i]; } else if (args[i].equals("-password")) { password = args[++i]; } else if (args[i].equals("-privateKey")) { privateKey = new File(args[++i]); } else if (args[i].equals("-passphrase")) { passphrase = args[++i]; } else if (args[i].equals("-rootPassword")) { rootPassword = args[++i]; } else if (args[i].equals("-redirect64")) { redirect64 = "true".equals(args[++i]); } } // // Configure for analysis only. // if (jDIconfig.getSystemCharacteristicsInputFile() != null && hostname == null) { session = null; return true; // // Configure for both scanning and analysis. // } else if (hostname != null) { try { IBaseSession base = sessionFactory.createSession(hostname); ICredential cred = null; if (base instanceof ILocked) { if (username == null) { err = getMessage("ERROR_USERNAME"); return false; } else if (privateKey == null && password == null) { err = getMessage("ERROR_PASSWORD"); return false; } else if (privateKey != null && !privateKey.isFile()) { err = getMessage("ERROR_PRIVATE_KEY", privateKey.getPath()); return false; } switch (base.getType()) { case WINDOWS: if (domain == null) { domain = hostname; } cred = new WindowsCredential(domain, username, password); break; case SSH: if (privateKey != null) { try { cred = new SshCredential(username, privateKey, passphrase, rootPassword); } catch (JSchException e) { err = getMessage("ERROR_PRIVATE_KEY", e.getMessage()); return false; } } else if (rootPassword != null) { cred = new SshCredential(username, password, rootPassword); } else { cred = new Credential(username, password); } break; } if (!((ILocked)base).unlock(cred)) { err = getMessage("ERROR_LOCK", cred.getClass().getName(), session.getClass().getName()); return false; } } switch (base.getType()) { case WINDOWS: - session = (IWindowsSession)session; + session = (IWindowsSession)base; break; case UNIX: base.disconnect(); UnixSession us = new UnixSession(new SshSession(hostname)); us.unlock(cred); session = us; break; case CISCO_IOS: base.disconnect(); IosSession is = new IosSession(new SshSession(hostname)); is.unlock(cred); session = is; break; default: System.out.println("DAS: screwed: " + base.getType()); break; } if (session instanceof ILocked) { ((ILocked)session).unlock(cred); } } catch (Exception e) { err = e.getMessage(); return false; } if (session.getType() == IBaseSession.Type.WINDOWS) { ((IWindowsSession)session).set64BitRedirect(redirect64); } return true; } else { err = getMessage("ERROR_HOSTNAME"); return false; } } }
true
true
public boolean configure(String[] args, IJovaldiConfiguration jDIconfig) { if (jDIconfig.printingHelp()) return true; String hostname = null; boolean redirect64 = true; String domain=null, username=null, password=null, passphrase=null, rootPassword=null; File privateKey = null; for (int i=0; i < args.length; i++) { if (args[i].equals("-hostname")) { hostname = args[++i]; } else if (args[i].equals("-domain")) { domain = args[++i]; } else if (args[i].equals("-username")) { username = args[++i]; } else if (args[i].equals("-password")) { password = args[++i]; } else if (args[i].equals("-privateKey")) { privateKey = new File(args[++i]); } else if (args[i].equals("-passphrase")) { passphrase = args[++i]; } else if (args[i].equals("-rootPassword")) { rootPassword = args[++i]; } else if (args[i].equals("-redirect64")) { redirect64 = "true".equals(args[++i]); } } // // Configure for analysis only. // if (jDIconfig.getSystemCharacteristicsInputFile() != null && hostname == null) { session = null; return true; // // Configure for both scanning and analysis. // } else if (hostname != null) { try { IBaseSession base = sessionFactory.createSession(hostname); ICredential cred = null; if (base instanceof ILocked) { if (username == null) { err = getMessage("ERROR_USERNAME"); return false; } else if (privateKey == null && password == null) { err = getMessage("ERROR_PASSWORD"); return false; } else if (privateKey != null && !privateKey.isFile()) { err = getMessage("ERROR_PRIVATE_KEY", privateKey.getPath()); return false; } switch (base.getType()) { case WINDOWS: if (domain == null) { domain = hostname; } cred = new WindowsCredential(domain, username, password); break; case SSH: if (privateKey != null) { try { cred = new SshCredential(username, privateKey, passphrase, rootPassword); } catch (JSchException e) { err = getMessage("ERROR_PRIVATE_KEY", e.getMessage()); return false; } } else if (rootPassword != null) { cred = new SshCredential(username, password, rootPassword); } else { cred = new Credential(username, password); } break; } if (!((ILocked)base).unlock(cred)) { err = getMessage("ERROR_LOCK", cred.getClass().getName(), session.getClass().getName()); return false; } } switch (base.getType()) { case WINDOWS: session = (IWindowsSession)session; break; case UNIX: base.disconnect(); UnixSession us = new UnixSession(new SshSession(hostname)); us.unlock(cred); session = us; break; case CISCO_IOS: base.disconnect(); IosSession is = new IosSession(new SshSession(hostname)); is.unlock(cred); session = is; break; default: System.out.println("DAS: screwed: " + base.getType()); break; } if (session instanceof ILocked) { ((ILocked)session).unlock(cred); } } catch (Exception e) { err = e.getMessage(); return false; } if (session.getType() == IBaseSession.Type.WINDOWS) { ((IWindowsSession)session).set64BitRedirect(redirect64); } return true; } else { err = getMessage("ERROR_HOSTNAME"); return false; } }
public boolean configure(String[] args, IJovaldiConfiguration jDIconfig) { if (jDIconfig.printingHelp()) return true; String hostname = null; boolean redirect64 = true; String domain=null, username=null, password=null, passphrase=null, rootPassword=null; File privateKey = null; for (int i=0; i < args.length; i++) { if (args[i].equals("-hostname")) { hostname = args[++i]; } else if (args[i].equals("-domain")) { domain = args[++i]; } else if (args[i].equals("-username")) { username = args[++i]; } else if (args[i].equals("-password")) { password = args[++i]; } else if (args[i].equals("-privateKey")) { privateKey = new File(args[++i]); } else if (args[i].equals("-passphrase")) { passphrase = args[++i]; } else if (args[i].equals("-rootPassword")) { rootPassword = args[++i]; } else if (args[i].equals("-redirect64")) { redirect64 = "true".equals(args[++i]); } } // // Configure for analysis only. // if (jDIconfig.getSystemCharacteristicsInputFile() != null && hostname == null) { session = null; return true; // // Configure for both scanning and analysis. // } else if (hostname != null) { try { IBaseSession base = sessionFactory.createSession(hostname); ICredential cred = null; if (base instanceof ILocked) { if (username == null) { err = getMessage("ERROR_USERNAME"); return false; } else if (privateKey == null && password == null) { err = getMessage("ERROR_PASSWORD"); return false; } else if (privateKey != null && !privateKey.isFile()) { err = getMessage("ERROR_PRIVATE_KEY", privateKey.getPath()); return false; } switch (base.getType()) { case WINDOWS: if (domain == null) { domain = hostname; } cred = new WindowsCredential(domain, username, password); break; case SSH: if (privateKey != null) { try { cred = new SshCredential(username, privateKey, passphrase, rootPassword); } catch (JSchException e) { err = getMessage("ERROR_PRIVATE_KEY", e.getMessage()); return false; } } else if (rootPassword != null) { cred = new SshCredential(username, password, rootPassword); } else { cred = new Credential(username, password); } break; } if (!((ILocked)base).unlock(cred)) { err = getMessage("ERROR_LOCK", cred.getClass().getName(), session.getClass().getName()); return false; } } switch (base.getType()) { case WINDOWS: session = (IWindowsSession)base; break; case UNIX: base.disconnect(); UnixSession us = new UnixSession(new SshSession(hostname)); us.unlock(cred); session = us; break; case CISCO_IOS: base.disconnect(); IosSession is = new IosSession(new SshSession(hostname)); is.unlock(cred); session = is; break; default: System.out.println("DAS: screwed: " + base.getType()); break; } if (session instanceof ILocked) { ((ILocked)session).unlock(cred); } } catch (Exception e) { err = e.getMessage(); return false; } if (session.getType() == IBaseSession.Type.WINDOWS) { ((IWindowsSession)session).set64BitRedirect(redirect64); } return true; } else { err = getMessage("ERROR_HOSTNAME"); return false; } }
diff --git a/src/main/java/loci/maven/plugin/cppwrap/CppWrapMojo.java b/src/main/java/loci/maven/plugin/cppwrap/CppWrapMojo.java index a062d8c..4c4216c 100644 --- a/src/main/java/loci/maven/plugin/cppwrap/CppWrapMojo.java +++ b/src/main/java/loci/maven/plugin/cppwrap/CppWrapMojo.java @@ -1,266 +1,266 @@ // // CppWrapMojo.java // /* C++ Wrapper Maven plugin for generating C++ proxy classes for a Java library. Copyright (c) 2011, UW-Madison LOCI 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 UW-Madison LOCI 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 HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package loci.maven.plugin.cppwrap; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Set; import loci.jar2lib.Jar2Lib; import loci.jar2lib.VelocityException; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.project.MavenProject; /** * Goal which creates a C++ project wrapping a Maven Java project. * * Portions of this mojo were adapted from exec-maven-plugin's ExecJavaMojo. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="http://dev.loci.wisc.edu/trac/software/browser/trunk/projects/cppwrap-maven-plugin/src/main/java/loci/maven/plugin/cppwrap/CppWrapMojo.java">Trac</a>, * <a href="http://dev.loci.wisc.edu/svn/software/trunk/projects/cppwrap-maven-plugin/src/main/java/loci/maven/plugin/cppwrap/CppWrapMojo.java">SVN</a></dd></dl> * * @author Curtis Rueden * * @goal wrap */ public class CppWrapMojo extends AbstractMojo { /** * The Maven project to wrap. * * @parameter expression="${project}" * @required * @readonly */ private MavenProject project; /** * Additional dependencies to wrap as part of the C++ project. * * For example, if a project human:body:jar:1.0 depends on projects * human:head:jar:1.0, human:arms:jar:1.0 and human:legs:jar:1.0, * and you wish to wrap human and head, but not arms or legs, * you could specify human:head:jar:1.0 as an extra artifact here. * * @parameter expression="${cppwrap.libraries}" */ private String[] libraries; /** * Path to conflicts list of Java constants to rename, * to avoid name collisions. * * @parameter expression="${cppwrap.conflictsFile}" * default-value="src/main/cppwrap/conflicts.txt" */ private File conflictsFile; /** * Path to header file to prepend to each C++ source file. * * @parameter expression="${cppwrap.headerFile}" * default-value="LICENSE.txt" */ private File headerFile; /** * Path to folder containing additional C++ source code. * * Each .cpp file in the folder should contain a main method. * These files will then be compiled as part of the build process, * as individual executables. * * @parameter expression="${cppwrap.sourceDir}" * default-value="src/main/cppwrap" */ private File sourceDir; /** * Path to output folder for C++ project. * * @parameter expression="${cppwrap.outputDir}" * default-value="target/cppwrap" */ private File outputDir; /** * Path to a text file listing core Java classes to be ensured * proxied. * * @parameter expression="${cppwrap.coreFile}" * default-value="src/main/cppwrap/core.txt" */ private File coreFile; /** * Path to text file, the contents of which will be * appended to resulting CMakeLists.txt for this project. * * @parameter expression="${cppwrap.extrasFile}" * default-value="src/main/cppwrap/extras.txt" */ private File extrasFile; @Override public void execute() throws MojoExecutionException { final String artifactId = project.getArtifactId(); final String projectId = artifactId.replaceAll("[^\\w\\-]", "_"); final String projectName = project.getName(); final List<String> libraryJars = getLibraryJars(); final List<String> classpathJars = getClasspathJars(); final String conflictsPath = conflictsFile.exists() ? conflictsFile.getPath() : null; final String headerPath = headerFile.exists() ? headerFile.getPath() : null; final String sourcePath = sourceDir.isDirectory() ? sourceDir.getPath() : null; final String outputPath = outputDir.getPath(); final String extrasPath = extrasFile.exists() ? extrasFile.getPath() : null; final String corePath = coreFile.exists() ? coreFile.getPath() : null; final Jar2Lib jar2lib = new Jar2Lib() { @Override protected void log(String message) { getLog().info(message); } }; jar2lib.setProjectId(projectId); jar2lib.setProjectName(projectName); jar2lib.setLibraryJars(libraryJars); jar2lib.setClasspathJars(classpathJars); jar2lib.setConflictsPath(conflictsPath); jar2lib.setHeaderPath(headerPath); jar2lib.setSourcePath(sourcePath); jar2lib.setOutputPath(outputPath); jar2lib.setExtrasPath(extrasPath); jar2lib.setCorePath(corePath); try { jar2lib.execute(); } catch (IOException e) { throw new MojoExecutionException("Error invoking jar2lib", e); } catch (VelocityException e) { throw new MojoExecutionException("Error invoking jar2lib", e); } } private List<String> getLibraryJars() throws MojoExecutionException { final List<String> jars = new ArrayList<String>(); // add project artifacts final File projectArtifact = project.getArtifact().getFile(); if (projectArtifact == null || !projectArtifact.exists()) { throw new MojoExecutionException("Must execute package target first " + "(e.g., mvn package cppwrap:wrap)."); } jars.add(projectArtifact.getPath()); // add explicitly enumerated dependencies if (libraries != null) { @SuppressWarnings("unchecked") final Artifact[] artifacts = - (Artifact[]) project.getDependencyArtifacts().toArray(new Artifact[0]); + (Artifact[]) project.getDependencyArtifacts().toArray(new Artifact[0]); ArrayList<String> libs = new ArrayList<String>(Arrays.asList(libraries)); Arrays.sort(artifacts, new ArtComparator()); Collections.sort(libs); int libIndex = 0; int artIndex = 0; boolean done = artIndex == artifacts.length; while (!done) { if(libs.get(libIndex).compareTo(artifacts[artIndex].getId()) == 0) { File artifactFile = artifacts[artIndex].getFile(); if (!artifactFile.exists()) { throw new MojoExecutionException("Artifact not found: " + artifactFile); } jars.add(artifactFile.getPath()); libIndex++; } else { artIndex++; } if(artIndex == artifacts.length) { throw new MojoExecutionException("Invalid library dependency: " + libs.get(libIndex)); } done = libIndex == libraries.length; } } return jars; } private List<String> getClasspathJars() { final List<String> jars = new ArrayList<String>(); // add project runtime dependencies @SuppressWarnings("unchecked") final Set<Artifact> artifacts = project.getDependencyArtifacts(); for (final Artifact classPathElement : artifacts) { jars.add(classPathElement.getFile().getPath()); } return jars; } private class ArtComparator implements Comparator { public int compare (Object obj1, Object obj2) { Artifact art1 = (Artifact)obj1; Artifact art2 = (Artifact)obj2; return art1.getId().compareTo(art2.getId()); } } }
true
true
private List<String> getLibraryJars() throws MojoExecutionException { final List<String> jars = new ArrayList<String>(); // add project artifacts final File projectArtifact = project.getArtifact().getFile(); if (projectArtifact == null || !projectArtifact.exists()) { throw new MojoExecutionException("Must execute package target first " + "(e.g., mvn package cppwrap:wrap)."); } jars.add(projectArtifact.getPath()); // add explicitly enumerated dependencies if (libraries != null) { @SuppressWarnings("unchecked") final Artifact[] artifacts = (Artifact[]) project.getDependencyArtifacts().toArray(new Artifact[0]); ArrayList<String> libs = new ArrayList<String>(Arrays.asList(libraries)); Arrays.sort(artifacts, new ArtComparator()); Collections.sort(libs); int libIndex = 0; int artIndex = 0; boolean done = artIndex == artifacts.length; while (!done) { if(libs.get(libIndex).compareTo(artifacts[artIndex].getId()) == 0) { File artifactFile = artifacts[artIndex].getFile(); if (!artifactFile.exists()) { throw new MojoExecutionException("Artifact not found: " + artifactFile); } jars.add(artifactFile.getPath()); libIndex++; } else { artIndex++; } if(artIndex == artifacts.length) { throw new MojoExecutionException("Invalid library dependency: " + libs.get(libIndex)); } done = libIndex == libraries.length; } } return jars; }
private List<String> getLibraryJars() throws MojoExecutionException { final List<String> jars = new ArrayList<String>(); // add project artifacts final File projectArtifact = project.getArtifact().getFile(); if (projectArtifact == null || !projectArtifact.exists()) { throw new MojoExecutionException("Must execute package target first " + "(e.g., mvn package cppwrap:wrap)."); } jars.add(projectArtifact.getPath()); // add explicitly enumerated dependencies if (libraries != null) { @SuppressWarnings("unchecked") final Artifact[] artifacts = (Artifact[]) project.getDependencyArtifacts().toArray(new Artifact[0]); ArrayList<String> libs = new ArrayList<String>(Arrays.asList(libraries)); Arrays.sort(artifacts, new ArtComparator()); Collections.sort(libs); int libIndex = 0; int artIndex = 0; boolean done = artIndex == artifacts.length; while (!done) { if(libs.get(libIndex).compareTo(artifacts[artIndex].getId()) == 0) { File artifactFile = artifacts[artIndex].getFile(); if (!artifactFile.exists()) { throw new MojoExecutionException("Artifact not found: " + artifactFile); } jars.add(artifactFile.getPath()); libIndex++; } else { artIndex++; } if(artIndex == artifacts.length) { throw new MojoExecutionException("Invalid library dependency: " + libs.get(libIndex)); } done = libIndex == libraries.length; } } return jars; }
diff --git a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/ContainerValueCollection.java b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/ContainerValueCollection.java index 09f7944be..cf1947908 100644 --- a/activemq-core/src/main/java/org/apache/activemq/kaha/impl/ContainerValueCollection.java +++ b/activemq-core/src/main/java/org/apache/activemq/kaha/impl/ContainerValueCollection.java @@ -1,138 +1,138 @@ /** * * Copyright 2005-2006 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.activemq.kaha.impl; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; /** * Values collection for the MapContainer * * @version $Revision: 1.2 $ */ class ContainerValueCollection extends ContainerCollectionSupport implements Collection{ ContainerValueCollection(MapContainerImpl container){ super(container); } public boolean contains(Object o){ return container.containsValue(o); } public Iterator iterator(){ LinkedList list=container.getItemList(); list = (LinkedList) list.clone(); return new ContainerValueCollectionIterator(container,list.iterator()); } public Object[] toArray(){ Object[] result = null; List list = container.getItemList(); synchronized(list){ result = new Object[list.size()]; int count = 0; for(Iterator i=list.iterator();i.hasNext();){ LocatableItem item=(LocatableItem) i.next(); Object value=container.getValue(item); result[count++] = value; } } return result; } public Object[] toArray(Object[] result){ List list=container.getItemList(); synchronized(list){ - if(result.length<list.size()){ + if(result.length<=list.size()){ int count=0; result=(Object[]) java.lang.reflect.Array.newInstance(result.getClass().getComponentType(),list.size()); for(Iterator i=list.iterator();i.hasNext();){ LocatableItem item=(LocatableItem) i.next(); Object value=container.getValue(item); result[count++]=value; } } } return result; } public boolean add(Object o){ throw new UnsupportedOperationException("Can't add an object here"); } public boolean remove(Object o){ return container.removeValue(o); } public boolean containsAll(Collection c){ boolean result = !c.isEmpty(); for (Iterator i = c.iterator(); i.hasNext(); ){ if (!contains(i.next())){ result = false; break; } } return result; } public boolean addAll(Collection c){ throw new UnsupportedOperationException("Can't add everything here!"); } public boolean removeAll(Collection c){ boolean result = true; for (Iterator i = c.iterator(); i.hasNext(); ){ Object obj = i.next(); result&=remove(obj); } return result; } public boolean retainAll(Collection c){ List tmpList = new ArrayList(); for (Iterator i = c.iterator(); i.hasNext(); ){ Object o = i.next(); if (!contains(o)){ tmpList.add(o); } } for(Iterator i = tmpList.iterator(); i.hasNext();){ remove(i.next()); } return !tmpList.isEmpty(); } public void clear(){ container.clear(); } }
true
true
public Object[] toArray(Object[] result){ List list=container.getItemList(); synchronized(list){ if(result.length<list.size()){ int count=0; result=(Object[]) java.lang.reflect.Array.newInstance(result.getClass().getComponentType(),list.size()); for(Iterator i=list.iterator();i.hasNext();){ LocatableItem item=(LocatableItem) i.next(); Object value=container.getValue(item); result[count++]=value; } } } return result; }
public Object[] toArray(Object[] result){ List list=container.getItemList(); synchronized(list){ if(result.length<=list.size()){ int count=0; result=(Object[]) java.lang.reflect.Array.newInstance(result.getClass().getComponentType(),list.size()); for(Iterator i=list.iterator();i.hasNext();){ LocatableItem item=(LocatableItem) i.next(); Object value=container.getValue(item); result[count++]=value; } } } return result; }
diff --git a/us7638/client/src/main/java/com/funambol/client/test/media/MediaRobot.java b/us7638/client/src/main/java/com/funambol/client/test/media/MediaRobot.java index 8c901023..9d6ab7cc 100755 --- a/us7638/client/src/main/java/com/funambol/client/test/media/MediaRobot.java +++ b/us7638/client/src/main/java/com/funambol/client/test/media/MediaRobot.java @@ -1,357 +1,357 @@ /* * Funambol is a mobile platform developed by Funambol, Inc. * Copyright (C) 2010 Funambol, Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by * the Free Software Foundation with the addition of the following permission * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 Affero General Public License * along with this program; if not, see http://www.gnu.org/licenses or write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA. * * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite * 305, Redwood City, CA 94063, USA, or at email address [email protected]. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License * version 3, these Appropriate Legal Notices must retain the display of the * "Powered by Funambol" logo. If the display of the logo is not reasonably * feasible for technical reasons, the Appropriate Legal Notices must display * the words "Powered by Funambol". */ package com.funambol.client.test.media; import com.funambol.client.source.AppSyncSource; import com.funambol.client.source.AppSyncSourceManager; import com.funambol.client.test.BasicScriptRunner; import com.funambol.client.test.Robot; import com.funambol.client.test.util.TestFileManager; import com.funambol.client.test.basic.BasicUserCommands; import com.funambol.sapisync.SapiSyncHandler; import com.funambol.sapisync.source.JSONFileObject; import com.funambol.sapisync.source.JSONSyncItem; import com.funambol.sapisync.source.JSONSyncSource; import com.funambol.sync.SyncConfig; import com.funambol.sync.SyncItem; import com.funambol.sync.SyncSource; import com.funambol.util.Log; import com.funambol.util.StringUtil; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.json.me.JSONArray; import org.json.me.JSONException; import org.json.me.JSONObject; public abstract class MediaRobot extends Robot { private static final String TAG_LOG = "MediaRobot"; protected AppSyncSourceManager appSourceManager; protected TestFileManager fileManager; protected SapiSyncHandler sapiSyncHandler = null; public MediaRobot(AppSyncSourceManager appSourceManager, TestFileManager fileManager) { this.appSourceManager = appSourceManager; this.fileManager = fileManager; } public MediaRobot(TestFileManager fileManager) { this.fileManager = fileManager; } public void addMedia(String type, String filename) throws Throwable { SyncSource source = getAppSyncSource(type).getSyncSource(); assertTrue(source instanceof JSONSyncSource, "Sync source format not supported"); getMediaFile(filename, ((JSONSyncSource) source).getDownloadOutputStream(filename, -1, false, false)); } public abstract void deleteMedia(String type, String filename) throws Throwable; public abstract void deleteAllMedia(String type) throws Throwable; /** * Add a media to the server. Media content is read based on specified * file name (a file in application's assets or an online resource). * * @param type sync source type * @param filename a relative path to the resource. BaseUrl parameter on test * configuration defines if the resource is a local file or is * an URL. In both cases, file is copied locally and then * uploaded to the server. * @throws Throwable */ public void addMediaOnServer(String type, String filename) throws Throwable { //make file available on local storage ByteArrayOutputStream os = new ByteArrayOutputStream(); String contentType = getMediaFile(filename, os); byte[] fileContent = os.toByteArray(); int size = fileContent.length; InputStream is = new ByteArrayInputStream(fileContent); addMediaOnServerFromStream(type, filename, is, size, contentType); } /** * Add a media to the server. Media content is read from a stream. * * @param type sync source type * @param itemName name of the item to add * @param contentStream stream to the content of the item * @param contentSize size of the item * @param contentType mimetype of the content to add * * @throws JSONException */ protected void addMediaOnServerFromStream( String type, String itemName, InputStream contentStream, long contentSize, String contentType) throws JSONException { // Prepare json item to upload JSONFileObject jsonFileObject = new JSONFileObject(); jsonFileObject.setName(itemName); jsonFileObject.setSize(contentSize); jsonFileObject.setCreationdate(System.currentTimeMillis()); jsonFileObject.setLastModifiedDate(System.currentTimeMillis()); jsonFileObject.setMimetype(contentType); MediaSyncItem item = new MediaSyncItem("fake_key", "fake_type", SyncItem.STATE_NEW, null, jsonFileObject, contentStream, contentSize); SapiSyncHandler sapiHandler = getSapiSyncHandler(); sapiHandler.login(null); sapiHandler.uploadItem(item, getRemoteUri(type), null); sapiHandler.logout(); } public void deleteMediaOnServer(String type, String filename) throws Throwable { SapiSyncHandler sapiHandler = getSapiSyncHandler(); String itemId = findMediaOnServer(type, filename); sapiHandler.login(null); sapiHandler.deleteItem(itemId, getRemoteUri(type), getDataTag(type)); sapiHandler.logout(); } private String findMediaOnServer(String type, String filename) throws Throwable { SapiSyncHandler sapiHandler = getSapiSyncHandler(); sapiHandler.login(null); try { SapiSyncHandler.FullSet itemsSet = sapiHandler.getItems( getRemoteUri(type), getDataTag(type), null, null, null, null); JSONArray items = itemsSet.items; for (int i = 0; i < items.length(); ++i) { JSONObject item = items.getJSONObject(i); String aFilename = item.getString("name"); if (filename.equals(aFilename)) { String id = item.getString("id"); return id; } } } finally { sapiHandler.logout(); } return null; } public void deleteAllMediaOnServer(String type) throws Throwable { SapiSyncHandler sapiHandler = getSapiSyncHandler(); sapiHandler.login(null); sapiHandler.deleteAllItems(getRemoteUri(type)); sapiHandler.logout(); } /** * Fill the server with some data in order to leave only specified quota * free. * Is free user quota is less that the required size, no action is * performed. * * @param type * @param byteToLeaveFree amount of byte to leave free on server * @throws Throwable */ public void leaveFreeServerQuota(String type, long byteToLeaveFree) throws Throwable { // get free quota for the current user SapiSyncHandler sapiHandler = getSapiSyncHandler(); - sapiHandler.logout(); + sapiHandler.login(null); long availableSpace = sapiHandler .getUserAvailableServerQuota(getRemoteUri(type)); //calculate server space to fill long spaceToFill = availableSpace - byteToLeaveFree; if (spaceToFill > 0) { if (Log.isLoggable(Log.DEBUG)) { Log.debug(TAG_LOG, "Available user quota is " + availableSpace + ", creating a fake file of bytes " + spaceToFill); } String extension; String mimetype; if (BasicUserCommands.SOURCE_NAME_PICTURES.equals(type)) { extension = ".jpg"; mimetype = "image/jpeg"; } else if (BasicUserCommands.SOURCE_NAME_VIDEOS.equals(type)) { extension = ".avi"; mimetype = "video/avi"; } else { extension = ".txt"; mimetype = "application/*"; } //create a fake file and fill it File tempFile = createFileWithSizeOnDevice(spaceToFill); FileInputStream fis = new FileInputStream(tempFile); if (tempFile != null ) addMediaOnServerFromStream(getRemoteUri(type), "fillspaceitem" + extension, fis, spaceToFill, mimetype); } else { if (Log.isLoggable(Log.DEBUG)) { Log.debug(TAG_LOG, "Available user quota is " + availableSpace + ", less that the required. Nothing to do."); } } sapiHandler.logout(); } protected AppSyncSourceManager getAppSyncSourceManager() { return appSourceManager; } /** * Returns the AppSyncSource related to the given data type * * @param type * @return */ protected AppSyncSource getAppSyncSource(String type) { if (StringUtil.equalsIgnoreCase(BasicUserCommands.SOURCE_NAME_PICTURES, type)) { return getAppSyncSourceManager().getSource( AppSyncSourceManager.PICTURES_ID); } else if (StringUtil.equalsIgnoreCase( BasicUserCommands.SOURCE_NAME_VIDEOS, type)) { return getAppSyncSourceManager().getSource( AppSyncSourceManager.VIDEOS_ID); } else { throw new IllegalArgumentException("Invalid type: " + type); } } /** * Returns the SAPI data tag related to the given data type. * * @param type * @return */ private String getRemoteUri(String type) { return getAppSyncSource(type).getSyncSource().getConfig() .getRemoteUri(); } private String getDataTag(String type) { SyncSource src = getAppSyncSource(type).getSyncSource(); String dataTag = null; if (src instanceof JSONSyncSource) { JSONSyncSource jsonSyncSource = (JSONSyncSource) src; dataTag = jsonSyncSource.getDataTag(); } return dataTag; } private SapiSyncHandler getSapiSyncHandler() { if (sapiSyncHandler == null) { SyncConfig syncConfig = getSyncConfig(); sapiSyncHandler = new SapiSyncHandler( StringUtil.extractAddressFromUrl(syncConfig.getSyncUrl()), syncConfig.getUserName(), syncConfig.getPassword()); } return sapiSyncHandler; } /** * This is used to override the item input stream */ private class MediaSyncItem extends JSONSyncItem { private InputStream stream; private long size; public MediaSyncItem(String key, String type, char state, String parent, JSONFileObject jsonFileObject, InputStream stream, long size) throws JSONException { super(key, type, state, parent, jsonFileObject); this.stream = stream; this.size = size; } public InputStream getInputStream() throws IOException { return stream; } public long getObjectSize() { return size; } } protected String getMediaFile(String filename, OutputStream output) throws Throwable { String baseUrl = BasicScriptRunner.getBaseUrl(); String url = baseUrl + "/" + filename; return fileManager.getFile(url, output); } protected abstract void fillLocalStorage(); protected abstract void restoreLocalStorage(); public abstract void checkMediaCount(String type, int count) throws Throwable; protected abstract SyncConfig getSyncConfig(); /** * Creates a temporary file of specified size * * @param byteSize size of the file * @return name of the file created * @throws IOException */ protected abstract File createFileWithSizeOnDevice(long byteSize) throws IOException; }
true
true
public void leaveFreeServerQuota(String type, long byteToLeaveFree) throws Throwable { // get free quota for the current user SapiSyncHandler sapiHandler = getSapiSyncHandler(); sapiHandler.logout(); long availableSpace = sapiHandler .getUserAvailableServerQuota(getRemoteUri(type)); //calculate server space to fill long spaceToFill = availableSpace - byteToLeaveFree; if (spaceToFill > 0) { if (Log.isLoggable(Log.DEBUG)) { Log.debug(TAG_LOG, "Available user quota is " + availableSpace + ", creating a fake file of bytes " + spaceToFill); } String extension; String mimetype; if (BasicUserCommands.SOURCE_NAME_PICTURES.equals(type)) { extension = ".jpg"; mimetype = "image/jpeg"; } else if (BasicUserCommands.SOURCE_NAME_VIDEOS.equals(type)) { extension = ".avi"; mimetype = "video/avi"; } else { extension = ".txt"; mimetype = "application/*"; } //create a fake file and fill it File tempFile = createFileWithSizeOnDevice(spaceToFill); FileInputStream fis = new FileInputStream(tempFile); if (tempFile != null ) addMediaOnServerFromStream(getRemoteUri(type), "fillspaceitem" + extension, fis, spaceToFill, mimetype); } else { if (Log.isLoggable(Log.DEBUG)) { Log.debug(TAG_LOG, "Available user quota is " + availableSpace + ", less that the required. Nothing to do."); } } sapiHandler.logout(); }
public void leaveFreeServerQuota(String type, long byteToLeaveFree) throws Throwable { // get free quota for the current user SapiSyncHandler sapiHandler = getSapiSyncHandler(); sapiHandler.login(null); long availableSpace = sapiHandler .getUserAvailableServerQuota(getRemoteUri(type)); //calculate server space to fill long spaceToFill = availableSpace - byteToLeaveFree; if (spaceToFill > 0) { if (Log.isLoggable(Log.DEBUG)) { Log.debug(TAG_LOG, "Available user quota is " + availableSpace + ", creating a fake file of bytes " + spaceToFill); } String extension; String mimetype; if (BasicUserCommands.SOURCE_NAME_PICTURES.equals(type)) { extension = ".jpg"; mimetype = "image/jpeg"; } else if (BasicUserCommands.SOURCE_NAME_VIDEOS.equals(type)) { extension = ".avi"; mimetype = "video/avi"; } else { extension = ".txt"; mimetype = "application/*"; } //create a fake file and fill it File tempFile = createFileWithSizeOnDevice(spaceToFill); FileInputStream fis = new FileInputStream(tempFile); if (tempFile != null ) addMediaOnServerFromStream(getRemoteUri(type), "fillspaceitem" + extension, fis, spaceToFill, mimetype); } else { if (Log.isLoggable(Log.DEBUG)) { Log.debug(TAG_LOG, "Available user quota is " + availableSpace + ", less that the required. Nothing to do."); } } sapiHandler.logout(); }
diff --git a/src/main/java/org/apache/hadoop/hive/ql/udf/generic/UDFSplitWithLimit.java b/src/main/java/org/apache/hadoop/hive/ql/udf/generic/UDFSplitWithLimit.java index b3634e1..5bda5f5 100644 --- a/src/main/java/org/apache/hadoop/hive/ql/udf/generic/UDFSplitWithLimit.java +++ b/src/main/java/org/apache/hadoop/hive/ql/udf/generic/UDFSplitWithLimit.java @@ -1,163 +1,163 @@ /** * 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.hive.ql.udf.generic; import java.util.ArrayList; import org.apache.hadoop.hive.ql.exec.Description; import org.apache.hadoop.hive.ql.exec.UDFArgumentException; import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorConverters; import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory; import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory; import org.apache.hadoop.io.Text; import java.util.regex.Pattern; import org.apache.hadoop.io.IntWritable; import java.io.PrintWriter; import java.io.StringWriter; /** * GenericUDFSplit. * */ @Description(name = "split", value = "_FUNC_(str, regex, [limit]) - Splits str around occurances that match " + "regex", extended = "Example:\n" + " > SELECT _FUNC_('oneAtwoBthreeC', '[ABC]', 2) FROM src LIMIT 1;\n" + " [\"one\", \"two\" \n" + " Note: setting limit to 0 will cause trailing empty/null entries to be truncated (which is earlier behavior" + " when \"limit\" was not available as third parameter)") public class UDFSplitWithLimit extends GenericUDF { private ObjectInspectorConverters.Converter[] converters; @Override public ObjectInspector initialize(ObjectInspector[] arguments) throws UDFArgumentException { if ( arguments.length < 2 || arguments.length > 3) { throw new UDFArgumentLengthException( "The function SPLIT(s, regexp) takes either 2 (without limit) or 3 (with limit) arguments."); } converters = new ObjectInspectorConverters.Converter[arguments.length]; for (int i = 0; i < arguments.length; i++) { converters[i] = ObjectInspectorConverters.getConverter(arguments[i], PrimitiveObjectInspectorFactory.writableStringObjectInspector); } return ObjectInspectorFactory .getStandardListObjectInspector(PrimitiveObjectInspectorFactory .writableStringObjectInspector); } @Override public Object evaluate(DeferredObject[] arguments) throws HiveException { try { if (arguments[0].get() == null || arguments[1].get() == null) { return null; } Text s = (Text) converters[0].convert(arguments[0].get()); Text regex = (Text) converters[1].convert(arguments[1].get()); int limit = Integer.MAX_VALUE; if (arguments.length>=3) { limit = Integer.parseInt(((Text)(converters[2]).convert(arguments[2].get())).toString()); } ArrayList<Text> result = new ArrayList<Text>(); for (String str : split(s.toString(),regex.toString(), limit)) { result.add(new Text(str)); } return result; } catch (Exception e) { System.err.println(toString(e)); throw new HiveException(toString(e)); } } private static String toString(Exception e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); return e.getMessage() + ": " + sw.toString(); } /** * The String.split() method has a strange behavior for the case of truncating * strings containing null/empty split entries at the end: I have fixed this * behavior, thus requiring this split() method to be included within this UDF * to override /replace the standard String.split() */ public static String[] split(String str, String regex, int limit) { /* fastpath if the regex is a (1)one-char String and this character is not one of the RegEx's meta characters ".$|()[{^?*+\\", or (2)two-char String and the first char is the backslash and the second is not the ascii digit or ascii letter. */ char ch = 0; if (((regex.length() == 1 && ".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) || (regex.length() == 2 && regex.charAt(0) == '\\' && (((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 && ((ch-'a')|('z'-ch)) < 0 && ((ch-'A')|('Z'-ch)) < 0)) && (ch < Character.MIN_HIGH_SURROGATE || ch > Character.MAX_LOW_SURROGATE)) { int off = 0; int next = 0; boolean limited = limit > 0; ArrayList<String> list = new ArrayList(); while ((next = str.indexOf(ch, off)) != -1) { - if (!limited || list.size() < limit - 1) { + if (!limited || list.size() < limit) { list.add(str.substring(off, next)); off = next + 1; } else { // last one - //assert (list.size() == limit - 1); - list.add(str.substring(off, regex.length())); - off = regex.length(); + // //assert (list.size() == limit - 1); + // list.add(str.substring(off, off+)); + // off = regex.length(); break; } } // If no match was found, return this if (off == 0) return new String[]{str}; // Add remaining segment if (!limited || list.size() < limit) - // Here is the "strange" truncation behavior that is being modified -// list.add(str.substring(off, regex.length())); +// list.add(str.substring(off, regex.length())); list.add(str.substring(off)); // Construct result int resultSize = list.size(); + // Here is the "strange" truncation behavior that is being modified if (limit == 0) while (resultSize > 0 && list.get(resultSize - 1).length() == 0) resultSize--; String[] result = new String[resultSize]; return list.subList(0, resultSize).toArray(result); } return Pattern.compile(regex).split(str, limit); } @Override public String getDisplayString(String[] children) { return "split(" + children[0] + ", " + children[1] + (children.length>2 ? (","+children[2]) : "") + ")"; } }
false
true
public static String[] split(String str, String regex, int limit) { /* fastpath if the regex is a (1)one-char String and this character is not one of the RegEx's meta characters ".$|()[{^?*+\\", or (2)two-char String and the first char is the backslash and the second is not the ascii digit or ascii letter. */ char ch = 0; if (((regex.length() == 1 && ".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) || (regex.length() == 2 && regex.charAt(0) == '\\' && (((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 && ((ch-'a')|('z'-ch)) < 0 && ((ch-'A')|('Z'-ch)) < 0)) && (ch < Character.MIN_HIGH_SURROGATE || ch > Character.MAX_LOW_SURROGATE)) { int off = 0; int next = 0; boolean limited = limit > 0; ArrayList<String> list = new ArrayList(); while ((next = str.indexOf(ch, off)) != -1) { if (!limited || list.size() < limit - 1) { list.add(str.substring(off, next)); off = next + 1; } else { // last one //assert (list.size() == limit - 1); list.add(str.substring(off, regex.length())); off = regex.length(); break; } } // If no match was found, return this if (off == 0) return new String[]{str}; // Add remaining segment if (!limited || list.size() < limit) // Here is the "strange" truncation behavior that is being modified // list.add(str.substring(off, regex.length())); list.add(str.substring(off)); // Construct result int resultSize = list.size(); if (limit == 0) while (resultSize > 0 && list.get(resultSize - 1).length() == 0) resultSize--; String[] result = new String[resultSize]; return list.subList(0, resultSize).toArray(result); } return Pattern.compile(regex).split(str, limit); }
public static String[] split(String str, String regex, int limit) { /* fastpath if the regex is a (1)one-char String and this character is not one of the RegEx's meta characters ".$|()[{^?*+\\", or (2)two-char String and the first char is the backslash and the second is not the ascii digit or ascii letter. */ char ch = 0; if (((regex.length() == 1 && ".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) || (regex.length() == 2 && regex.charAt(0) == '\\' && (((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 && ((ch-'a')|('z'-ch)) < 0 && ((ch-'A')|('Z'-ch)) < 0)) && (ch < Character.MIN_HIGH_SURROGATE || ch > Character.MAX_LOW_SURROGATE)) { int off = 0; int next = 0; boolean limited = limit > 0; ArrayList<String> list = new ArrayList(); while ((next = str.indexOf(ch, off)) != -1) { if (!limited || list.size() < limit) { list.add(str.substring(off, next)); off = next + 1; } else { // last one // //assert (list.size() == limit - 1); // list.add(str.substring(off, off+)); // off = regex.length(); break; } } // If no match was found, return this if (off == 0) return new String[]{str}; // Add remaining segment if (!limited || list.size() < limit) // list.add(str.substring(off, regex.length())); list.add(str.substring(off)); // Construct result int resultSize = list.size(); // Here is the "strange" truncation behavior that is being modified if (limit == 0) while (resultSize > 0 && list.get(resultSize - 1).length() == 0) resultSize--; String[] result = new String[resultSize]; return list.subList(0, resultSize).toArray(result); } return Pattern.compile(regex).split(str, limit); }
diff --git a/PullPit/src/kea/kme/pullpit/server/podio/ArrayParser.java b/PullPit/src/kea/kme/pullpit/server/podio/ArrayParser.java index c8aa1c0..32c5f24 100644 --- a/PullPit/src/kea/kme/pullpit/server/podio/ArrayParser.java +++ b/PullPit/src/kea/kme/pullpit/server/podio/ArrayParser.java @@ -1,95 +1,101 @@ package kea.kme.pullpit.server.podio; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.logging.Logger; import kea.kme.pullpit.server.podio.enums.App; import com.podio.item.FieldValuesView; import com.podio.item.ItemBadge; import com.podio.item.ItemsResponse; public class ArrayParser { private static ArrayParser arrayParser; private static final Logger log = Logger.getLogger(ArrayParser.class.getName()); private ArrayParser() { } public static ArrayParser getInstance() { if (arrayParser == null) arrayParser = new ArrayParser(); return arrayParser; } public ArrayList<?> parseArray(App app, ItemsResponse ir) { switch (app.appName) { case "Bands" : return parseBands(ir); } return null; } protected ArrayList<PodioBand> parseBands(ItemsResponse ir) { ArrayList<PodioBand> bands = new ArrayList<PodioBand>(); List<ItemBadge> items = ir.getItems(); for (ItemBadge ib : items) { int itemID = ib.getId(); String name = null; String country = null; int agentID = 0; int promoID = 0; + PodioAgent[] agents = {new PodioAgent(0,0)}; Timestamp time = null; SimpleDateFormat formatter, FORMATTER; formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); String dateString = ib.getCurrentRevision().getCreatedOn().toString(); Date date; try { date = formatter.parse(dateString); FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); time = Timestamp.valueOf(FORMATTER.format(date)); } catch (ParseException e) { log.warning("Could not parse! " + e.getMessage()); } for (FieldValuesView fvw : ib.getFields()) { switch (fvw.getLabel()) { case "Navn": name = (String) fvw.getValues().get(0).get("value"); break; case "Land": country = (String) fvw.getValues().get(0).get("value"); break; case "Agent": - @SuppressWarnings("unchecked") + int noOfAgents = fvw.getValues().size(); + agents = new PodioAgent[noOfAgents]; + for (int i = 0; i < noOfAgents; i++) { + @SuppressWarnings("unchecked") HashMap<String, Object> agentMap = (HashMap<String, Object>) fvw - .getValues().get(0).get("value"); + .getValues().get(i).get("value"); agentID = (Integer) agentMap.get("profile_id"); + agents[i] = new PodioAgent(itemID, agentID); + } break; case "SBP-Promoter": @SuppressWarnings("unchecked") HashMap<String, Object> promoMap = (HashMap<String, Object>) fvw .getValues().get(0).get("value"); promoID = (Integer) promoMap.get("user_id"); } } - bands.add(new PodioBand(itemID, name, country, promoID, time, new PodioAgent(itemID, agentID))); + bands.add(new PodioBand(itemID, name, country, promoID, time, agents)); } return bands; } public ArrayList<PodioVenue> parseVenues(ItemsResponse ir) { // TODO Auto-generated method stub return null; } public ArrayList<PodioShow> parseShows(ItemsResponse ir) { // TODO Auto-generated method stub return null; } }
false
true
protected ArrayList<PodioBand> parseBands(ItemsResponse ir) { ArrayList<PodioBand> bands = new ArrayList<PodioBand>(); List<ItemBadge> items = ir.getItems(); for (ItemBadge ib : items) { int itemID = ib.getId(); String name = null; String country = null; int agentID = 0; int promoID = 0; Timestamp time = null; SimpleDateFormat formatter, FORMATTER; formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); String dateString = ib.getCurrentRevision().getCreatedOn().toString(); Date date; try { date = formatter.parse(dateString); FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); time = Timestamp.valueOf(FORMATTER.format(date)); } catch (ParseException e) { log.warning("Could not parse! " + e.getMessage()); } for (FieldValuesView fvw : ib.getFields()) { switch (fvw.getLabel()) { case "Navn": name = (String) fvw.getValues().get(0).get("value"); break; case "Land": country = (String) fvw.getValues().get(0).get("value"); break; case "Agent": @SuppressWarnings("unchecked") HashMap<String, Object> agentMap = (HashMap<String, Object>) fvw .getValues().get(0).get("value"); agentID = (Integer) agentMap.get("profile_id"); break; case "SBP-Promoter": @SuppressWarnings("unchecked") HashMap<String, Object> promoMap = (HashMap<String, Object>) fvw .getValues().get(0).get("value"); promoID = (Integer) promoMap.get("user_id"); } } bands.add(new PodioBand(itemID, name, country, promoID, time, new PodioAgent(itemID, agentID))); } return bands; }
protected ArrayList<PodioBand> parseBands(ItemsResponse ir) { ArrayList<PodioBand> bands = new ArrayList<PodioBand>(); List<ItemBadge> items = ir.getItems(); for (ItemBadge ib : items) { int itemID = ib.getId(); String name = null; String country = null; int agentID = 0; int promoID = 0; PodioAgent[] agents = {new PodioAgent(0,0)}; Timestamp time = null; SimpleDateFormat formatter, FORMATTER; formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); String dateString = ib.getCurrentRevision().getCreatedOn().toString(); Date date; try { date = formatter.parse(dateString); FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); time = Timestamp.valueOf(FORMATTER.format(date)); } catch (ParseException e) { log.warning("Could not parse! " + e.getMessage()); } for (FieldValuesView fvw : ib.getFields()) { switch (fvw.getLabel()) { case "Navn": name = (String) fvw.getValues().get(0).get("value"); break; case "Land": country = (String) fvw.getValues().get(0).get("value"); break; case "Agent": int noOfAgents = fvw.getValues().size(); agents = new PodioAgent[noOfAgents]; for (int i = 0; i < noOfAgents; i++) { @SuppressWarnings("unchecked") HashMap<String, Object> agentMap = (HashMap<String, Object>) fvw .getValues().get(i).get("value"); agentID = (Integer) agentMap.get("profile_id"); agents[i] = new PodioAgent(itemID, agentID); } break; case "SBP-Promoter": @SuppressWarnings("unchecked") HashMap<String, Object> promoMap = (HashMap<String, Object>) fvw .getValues().get(0).get("value"); promoID = (Integer) promoMap.get("user_id"); } } bands.add(new PodioBand(itemID, name, country, promoID, time, agents)); } return bands; }
diff --git a/org.eclipse.mylyn.monitor.tests/src/org/eclipse/mylyn/monitor/reports/tests/ContextParsingTest.java b/org.eclipse.mylyn.monitor.tests/src/org/eclipse/mylyn/monitor/reports/tests/ContextParsingTest.java index cdb41dd4..bc11961e 100644 --- a/org.eclipse.mylyn.monitor.tests/src/org/eclipse/mylyn/monitor/reports/tests/ContextParsingTest.java +++ b/org.eclipse.mylyn.monitor.tests/src/org/eclipse/mylyn/monitor/reports/tests/ContextParsingTest.java @@ -1,99 +1,99 @@ /******************************************************************************* * 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.monitor.reports.tests; import java.io.File; import java.util.List; import junit.framework.TestCase; import org.eclipse.core.runtime.Path; import org.eclipse.mylar.core.IMylarElement; import org.eclipse.mylar.core.InteractionEvent; import org.eclipse.mylar.internal.core.MylarContext; import org.eclipse.mylar.internal.core.ScalingFactor; import org.eclipse.mylar.internal.core.ScalingFactors; import org.eclipse.mylar.internal.monitor.InteractionEventLogger; import org.eclipse.mylar.internal.monitor.monitors.SelectionMonitor; import org.eclipse.mylar.monitor.tests.MylarMonitorTestsPlugin; /** * @author Mik Kersten */ public class ContextParsingTest extends TestCase { private static final String PATH_USAGE_FILE = "testdata/usage-parsing.zip"; private List<InteractionEvent> events; @Override protected void setUp() throws Exception { super.setUp(); File file; if (MylarMonitorTestsPlugin.getDefault() != null) { file = FileTool.getFileInPlugin(MylarMonitorTestsPlugin.getDefault(), new Path(PATH_USAGE_FILE)); } else { file = new File(PATH_USAGE_FILE); } InteractionEventLogger logger = new InteractionEventLogger(file); events = logger.getHistoryFromFile(file); } @Override protected void tearDown() throws Exception { super.tearDown(); events.clear(); } public void testOriginIdValidity() { for (InteractionEvent event : events) { if (event.isValidStructureHandle()) { assertFalse(event.getStructureHandle().equals("null")); } } } public void testHistoryParsingWithDecayReset() { ScalingFactors scalingFactors = new ScalingFactors(); // scalingFactors.setDecay(new ScalingFactor("decay", .05f)); MylarContext context = new MylarContext("test", scalingFactors); int numEvents = 0; for (InteractionEvent event : events) { if (SelectionMonitor.isValidStructureHandle(event)) { InteractionEvent newEvent = InteractionEvent.makeCopy(event, 1f); context.parseEvent(newEvent); if (SelectionMonitor.isValidStructureHandle(event) && event.getKind().equals(InteractionEvent.Kind.SELECTION)) { IMylarElement element = context.parseEvent(event); // reset decay if not selected if (element.getInterest().getValue() < 0) { float decayOffset = (-1) * (element.getInterest().getValue()) + 1; element = context.parseEvent(new InteractionEvent(InteractionEvent.Kind.MANIPULATION, event.getContentType(), event.getStructureHandle(), "test-decay", decayOffset)); } assertTrue("should be positive: " + element.getInterest().getValue(), element.getInterest().getValue() >= 0); - System.err.println(">>> " + element.getInterest().getValue() + ", handle: " - + element.getHandleIdentifier()); +// System.err.println(">>> " + element.getInterest().getValue() + ", handle: " +// + element.getHandleIdentifier()); numEvents++; } } } } public void testScalingVactorSet() { ScalingFactors scalingFactors = new ScalingFactors(); scalingFactors.setDecay(new ScalingFactor("decay", 0f)); MylarContext context = new MylarContext("test", scalingFactors); assertEquals(0f, context.getScalingFactors().getDecay().getValue()); } }
true
true
public void testHistoryParsingWithDecayReset() { ScalingFactors scalingFactors = new ScalingFactors(); // scalingFactors.setDecay(new ScalingFactor("decay", .05f)); MylarContext context = new MylarContext("test", scalingFactors); int numEvents = 0; for (InteractionEvent event : events) { if (SelectionMonitor.isValidStructureHandle(event)) { InteractionEvent newEvent = InteractionEvent.makeCopy(event, 1f); context.parseEvent(newEvent); if (SelectionMonitor.isValidStructureHandle(event) && event.getKind().equals(InteractionEvent.Kind.SELECTION)) { IMylarElement element = context.parseEvent(event); // reset decay if not selected if (element.getInterest().getValue() < 0) { float decayOffset = (-1) * (element.getInterest().getValue()) + 1; element = context.parseEvent(new InteractionEvent(InteractionEvent.Kind.MANIPULATION, event.getContentType(), event.getStructureHandle(), "test-decay", decayOffset)); } assertTrue("should be positive: " + element.getInterest().getValue(), element.getInterest().getValue() >= 0); System.err.println(">>> " + element.getInterest().getValue() + ", handle: " + element.getHandleIdentifier()); numEvents++; } } } }
public void testHistoryParsingWithDecayReset() { ScalingFactors scalingFactors = new ScalingFactors(); // scalingFactors.setDecay(new ScalingFactor("decay", .05f)); MylarContext context = new MylarContext("test", scalingFactors); int numEvents = 0; for (InteractionEvent event : events) { if (SelectionMonitor.isValidStructureHandle(event)) { InteractionEvent newEvent = InteractionEvent.makeCopy(event, 1f); context.parseEvent(newEvent); if (SelectionMonitor.isValidStructureHandle(event) && event.getKind().equals(InteractionEvent.Kind.SELECTION)) { IMylarElement element = context.parseEvent(event); // reset decay if not selected if (element.getInterest().getValue() < 0) { float decayOffset = (-1) * (element.getInterest().getValue()) + 1; element = context.parseEvent(new InteractionEvent(InteractionEvent.Kind.MANIPULATION, event.getContentType(), event.getStructureHandle(), "test-decay", decayOffset)); } assertTrue("should be positive: " + element.getInterest().getValue(), element.getInterest().getValue() >= 0); // System.err.println(">>> " + element.getInterest().getValue() + ", handle: " // + element.getHandleIdentifier()); numEvents++; } } } }
diff --git a/gdx/src/com/badlogic/gdx/utils/GdxNativesLoader.java b/gdx/src/com/badlogic/gdx/utils/GdxNativesLoader.java index eecc74646..273e7e29b 100644 --- a/gdx/src/com/badlogic/gdx/utils/GdxNativesLoader.java +++ b/gdx/src/com/badlogic/gdx/utils/GdxNativesLoader.java @@ -1,122 +1,122 @@ /******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.utils; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.CRC32; import com.badlogic.gdx.Version; public class GdxNativesLoader { static public boolean disableNativesLoading = false; static private boolean nativesLoaded = false; static public boolean isWindows = System.getProperty("os.name").contains("Windows"); static public boolean isLinux = System.getProperty("os.name").contains("Linux"); static public boolean isMac = System.getProperty("os.name").contains("Mac"); static public boolean is64Bit = System.getProperty("os.arch").equals("amd64"); static public File nativesDir = new File(System.getProperty("java.io.tmpdir") + "/libgdx/" + crc("gdx.dll")); static public String path; static private String crc (String nativeFile) { InputStream input = GdxNativesLoader.class.getResourceAsStream("/" + nativeFile); if (input == null) return Version.VERSION; // fallback CRC32 crc = new CRC32(); byte[] buffer = new byte[4096]; try { while (true) { int length = input.read(buffer); if (length == -1) break; crc.update(buffer, 0, length); } } catch (Exception ex) { try { input.close(); } catch (Exception ignored) { } } return Long.toString(crc.getValue()); } static public boolean loadLibrary (String nativeFile32, String nativeFile64) { path = extractLibrary(nativeFile32, nativeFile64); if (path != null) System.load(path); return path != null; } static public String extractLibrary (String native32, String native64) { String nativeFileName = is64Bit ? native64 : native32; File nativeFile = new File(nativesDir, nativeFileName); try { // Extract native from classpath to temp dir. InputStream input = GdxNativesLoader.class.getResourceAsStream("/" + nativeFileName); if (input == null) return null; nativesDir.mkdirs(); FileOutputStream output = new FileOutputStream(nativeFile); byte[] buffer = new byte[4096]; while (true) { int length = input.read(buffer); if (length == -1) break; output.write(buffer, 0, length); } input.close(); output.close(); } catch (IOException ex) { } return nativeFile.exists() ? nativeFile.getAbsolutePath() : null; } /** Loads the libgdx native libraries. */ static public void load () { if (disableNativesLoading) { System.out .println("So you don't like our native lib loading? Good, you are on your own now. We don't give support from here on out"); return; } if (nativesLoaded) return; String vm = System.getProperty("java.vm.name"); if (vm == null || !vm.contains("Dalvik")) { if (isWindows) { - nativesLoaded = loadLibrary("gdx.dll", "gdx-64.dll"); + nativesLoaded = loadLibrary("gdx.dll", "gdx64.dll"); } else if (isMac) { nativesLoaded = loadLibrary("libgdx.dylib", "libgdx.dylib"); if (!nativesLoaded) { // Find the lib for applets, since System.loadLibrary looks for jnilib, not dylib. File file = new File(System.getProperty("java.library.path"), "libgdx.dylib"); if (file.exists()) { System.load(file.getAbsolutePath()); nativesLoaded = true; } } } else if (isLinux) { - nativesLoaded = loadLibrary("libgdx.so", "libgdx-64.so"); + nativesLoaded = loadLibrary("libgdx.so", "libgdx64.so"); } if (nativesLoaded) return; } if (!is64Bit || isMac) { System.loadLibrary("gdx"); } else { - System.loadLibrary("gdx-64"); + System.loadLibrary("gdx64"); } nativesLoaded = true; } }
false
true
static public void load () { if (disableNativesLoading) { System.out .println("So you don't like our native lib loading? Good, you are on your own now. We don't give support from here on out"); return; } if (nativesLoaded) return; String vm = System.getProperty("java.vm.name"); if (vm == null || !vm.contains("Dalvik")) { if (isWindows) { nativesLoaded = loadLibrary("gdx.dll", "gdx-64.dll"); } else if (isMac) { nativesLoaded = loadLibrary("libgdx.dylib", "libgdx.dylib"); if (!nativesLoaded) { // Find the lib for applets, since System.loadLibrary looks for jnilib, not dylib. File file = new File(System.getProperty("java.library.path"), "libgdx.dylib"); if (file.exists()) { System.load(file.getAbsolutePath()); nativesLoaded = true; } } } else if (isLinux) { nativesLoaded = loadLibrary("libgdx.so", "libgdx-64.so"); } if (nativesLoaded) return; } if (!is64Bit || isMac) { System.loadLibrary("gdx"); } else { System.loadLibrary("gdx-64"); } nativesLoaded = true; }
static public void load () { if (disableNativesLoading) { System.out .println("So you don't like our native lib loading? Good, you are on your own now. We don't give support from here on out"); return; } if (nativesLoaded) return; String vm = System.getProperty("java.vm.name"); if (vm == null || !vm.contains("Dalvik")) { if (isWindows) { nativesLoaded = loadLibrary("gdx.dll", "gdx64.dll"); } else if (isMac) { nativesLoaded = loadLibrary("libgdx.dylib", "libgdx.dylib"); if (!nativesLoaded) { // Find the lib for applets, since System.loadLibrary looks for jnilib, not dylib. File file = new File(System.getProperty("java.library.path"), "libgdx.dylib"); if (file.exists()) { System.load(file.getAbsolutePath()); nativesLoaded = true; } } } else if (isLinux) { nativesLoaded = loadLibrary("libgdx.so", "libgdx64.so"); } if (nativesLoaded) return; } if (!is64Bit || isMac) { System.loadLibrary("gdx"); } else { System.loadLibrary("gdx64"); } nativesLoaded = true; }
diff --git a/src/uk/me/parabola/mkgmap/osmstyle/StyledConverter.java b/src/uk/me/parabola/mkgmap/osmstyle/StyledConverter.java index 1bffe6c2..aa5bab1a 100644 --- a/src/uk/me/parabola/mkgmap/osmstyle/StyledConverter.java +++ b/src/uk/me/parabola/mkgmap/osmstyle/StyledConverter.java @@ -1,938 +1,938 @@ /* * Copyright (C) 2007 Steve Ratcliffe * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * * Author: Steve Ratcliffe * Create date: Feb 17, 2008 */ package uk.me.parabola.mkgmap.osmstyle; import java.util.ArrayList; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import uk.me.parabola.imgfmt.app.Area; import uk.me.parabola.imgfmt.app.Coord; import uk.me.parabola.imgfmt.app.CoordNode; import uk.me.parabola.imgfmt.app.Exit; import uk.me.parabola.log.Logger; import uk.me.parabola.mkgmap.general.AreaClipper; import uk.me.parabola.mkgmap.general.Clipper; import uk.me.parabola.mkgmap.general.LineAdder; import uk.me.parabola.mkgmap.general.LineClipper; import uk.me.parabola.mkgmap.general.MapCollector; import uk.me.parabola.mkgmap.general.MapElement; import uk.me.parabola.mkgmap.general.MapExitPoint; import uk.me.parabola.mkgmap.general.MapLine; import uk.me.parabola.mkgmap.general.MapPoint; import uk.me.parabola.mkgmap.general.MapRoad; import uk.me.parabola.mkgmap.general.MapShape; import uk.me.parabola.mkgmap.general.RoadNetwork; import uk.me.parabola.mkgmap.reader.osm.Element; import uk.me.parabola.mkgmap.reader.osm.GType; import uk.me.parabola.mkgmap.reader.osm.Node; import uk.me.parabola.mkgmap.reader.osm.OsmConverter; import uk.me.parabola.mkgmap.reader.osm.Relation; import uk.me.parabola.mkgmap.reader.osm.RestrictionRelation; import uk.me.parabola.mkgmap.reader.osm.Rule; import uk.me.parabola.mkgmap.reader.osm.Style; import uk.me.parabola.mkgmap.reader.osm.Way; /** * Convert from OSM to the mkgmap intermediate format using a style. * A style is a collection of files that describe the mappings to be used * when converting. * * @author Steve Ratcliffe */ public class StyledConverter implements OsmConverter { private static final Logger log = Logger.getLogger(StyledConverter.class); private final String[] nameTagList; private final MapCollector collector; private Clipper clipper = Clipper.NULL_CLIPPER; private Area bbox; private Set<Coord> boundaryCoords = new HashSet<Coord>(); // restrictions associates lists of turn restrictions with the // Coord corresponding to the restrictions' 'via' node private final Map<Coord, List<RestrictionRelation>> restrictions = new IdentityHashMap<Coord, List<RestrictionRelation>>(); // originalWay associates Ways that have been created due to // splitting or clipping with the Ways that they were derived // from private final Map<Way, Way> originalWay = new HashMap<Way, Way>(); // limit arc lengths to what can currently be handled by RouteArc private final int MAX_ARC_LENGTH = 75000; private final int MAX_POINTS_IN_WAY = 200; private final int MAX_NODES_IN_WAY = 16; private final double MIN_DISTANCE_BETWEEN_NODES = 5.5; // nodeIdMap maps a Coord into a nodeId private final Map<Coord, Integer> nodeIdMap = new IdentityHashMap<Coord, Integer>(); private int nextNodeId = 1; private final Rule wayRules; private final Rule nodeRules; private final Rule relationRules; private boolean ignoreMaxspeeds; class AccessMapping { private final String type; private final int index; AccessMapping(String type, int index) { this.type = type; this.index = index; } } private final AccessMapping[] accessMap = { new AccessMapping("access", RoadNetwork.NO_MAX), // must be first in list new AccessMapping("bicycle", RoadNetwork.NO_BIKE), new AccessMapping("foot", RoadNetwork.NO_FOOT), new AccessMapping("hgv", RoadNetwork.NO_TRUCK), new AccessMapping("motorcar", RoadNetwork.NO_CAR), new AccessMapping("motorcycle", RoadNetwork.NO_CAR), new AccessMapping("psv", RoadNetwork.NO_BUS), new AccessMapping("taxi", RoadNetwork.NO_TAXI), new AccessMapping("emergency", RoadNetwork.NO_EMERGENCY), new AccessMapping("delivery", RoadNetwork.NO_DELIVERY), new AccessMapping("goods", RoadNetwork.NO_DELIVERY), }; private LineAdder lineAdder = new LineAdder() { public void add(MapLine element) { if (element instanceof MapRoad) collector.addRoad((MapRoad) element); else collector.addLine(element); } }; public StyledConverter(Style style, MapCollector collector, Properties props) { this.collector = collector; nameTagList = style.getNameTagList(); wayRules = style.getWayRules(); nodeRules = style.getNodeRules(); relationRules = style.getRelationRules(); ignoreMaxspeeds = props.getProperty("ignore-maxspeeds") != null; LineAdder overlayAdder = style.getOverlays(lineAdder); if (overlayAdder != null) lineAdder = overlayAdder; } /** * This takes the way and works out what kind of map feature it is and makes * the relevant call to the mapper callback. * <p> * As a few examples we might want to check for the 'highway' tag, work out * if it is an area of a park etc. * * @param way The OSM way. */ public void convertWay(Way way) { if (way.getPoints().size() < 2) return; preConvertRules(way); GType foundType = wayRules.resolveType(way); if (foundType == null) return; postConvertRules(way, foundType); if (foundType.getFeatureKind() == GType.POLYLINE) { if(foundType.isRoad()) addRoad(way, foundType); else addLine(way, foundType); } else addShape(way, foundType); } /** * Takes a node (that has its own identity) and converts it from the OSM * type to the Garmin map type. * * @param node The node to convert. */ public void convertNode(Node node) { preConvertRules(node); GType foundType = nodeRules.resolveType(node); if (foundType == null) return; postConvertRules(node, foundType); addPoint(node, foundType); } /** * Rules to run before converting the element. */ private void preConvertRules(Element el) { if (nameTagList == null) return; for (String t : nameTagList) { String val = el.getTag(t); if (val != null) { el.addTag("name", val); break; } } } /** * Built in rules to run after converting the element. */ private void postConvertRules(Element el, GType type) { // Set the name from the 'name' tag or failing that from // the default_name. el.setName(el.getTag("name")); if (el.getName() == null) el.setName(type.getDefaultName()); } /** * Set the bounding box for this map. This should be set before any other * elements are converted if you want to use it. All elements that are added * are clipped to this box, new points are added as needed at the boundry. * * If a node or a way falls completely outside the boundry then it would be * ommited. This would not normally happen in the way this option is typically * used however. * * @param bbox The bounding area. */ public void setBoundingBox(Area bbox) { this.clipper = new AreaClipper(bbox); this.bbox = bbox; } /** * Run the rules for this relation. As this is not an end object, then * the only useful rules are action rules that set tags on the contained * ways or nodes. Every rule should probably start with 'type=".."'. * * @param relation The relation to convert. */ public void convertRelation(Relation relation) { // Relations never resolve to a GType and so we ignore the return // value. relationRules.resolveType(relation); if(relation instanceof RestrictionRelation) { RestrictionRelation rr = (RestrictionRelation)relation; if(rr.isValid()) { List<RestrictionRelation> lrr = restrictions.get(rr.getViaCoord()); if(lrr == null) { lrr = new ArrayList<RestrictionRelation>(); restrictions.put(rr.getViaCoord(), lrr); } lrr.add(rr); } } } private void addLine(Way way, GType gt) { MapLine line = new MapLine(); elementSetup(line, gt, way); line.setPoints(way.getPoints()); if (way.isBoolTag("oneway")) line.setDirection(true); clipper.clipLine(line, lineAdder); } private void addShape(Way way, GType gt) { MapShape shape = new MapShape(); elementSetup(shape, gt, way); shape.setPoints(way.getPoints()); clipper.clipShape(shape, collector); GType pointType = nodeRules.resolveType(way); if(pointType != null) shape.setPoiType(pointType.getType()); } private void addPoint(Node node, GType gt) { if (!clipper.contains(node.getLocation())) return; // to handle exit points we use a subclass of MapPoint // to carry some extra info (a reference to the // motorway associated with the exit) MapPoint mp; int type = gt.getType(); if(type >= 0x2000 && type < 0x2800) { String ref = node.getTag(Exit.TAG_ROAD_REF); String id = node.getTag("osm:id"); if(ref != null) { String to = node.getTag(Exit.TAG_TO); MapExitPoint mep = new MapExitPoint(ref, to); String fd = node.getTag(Exit.TAG_FACILITY); if(fd != null) mep.setFacilityDescription(fd); if(id != null) mep.setOSMId(id); mp = mep; } else { mp = new MapPoint(); log.warn("Motorway exit " + node.getName() + " (OSM id " + id + ") located at " + node.getLocation().toDegreeString() + " has no motorway! (either make the exit share a node with the motorway or specify the motorway ref with a " + Exit.TAG_ROAD_REF + " tag)"); } } else { mp = new MapPoint(); } elementSetup(mp, gt, node); mp.setLocation(node.getLocation()); collector.addPoint(mp); } private String combineRefs(Element element) { String ref = element.getTag("ref"); String int_ref = element.getTag("int_ref"); if(int_ref != null) { if(ref == null) ref = int_ref; else ref += ";" + int_ref; } String nat_ref = element.getTag("nat_ref"); if(nat_ref != null) { if(ref == null) ref = nat_ref; else ref += ";" + nat_ref; } String reg_ref = element.getTag("reg_ref"); if(reg_ref != null) { if(ref == null) ref = reg_ref; else ref += ";" + reg_ref; } return ref; } private void elementSetup(MapElement ms, GType gt, Element element) { String name = element.getName(); String refs = combineRefs(element); if(name == null && refs != null) { // use first ref as name name = refs.split(";")[0].trim(); } if(name != null) ms.setName(name); if(refs != null) ms.setRef(refs); ms.setType(gt.getType()); ms.setMinResolution(gt.getMinResolution()); ms.setMaxResolution(gt.getMaxResolution()); // Now try to get some address info for POIs String city = element.getTag("addr:city"); String zip = element.getTag("addr:postcode"); String street = element.getTag("addr:street"); String houseNumber = element.getTag("addr:housenumber"); String phone = element.getTag("phone"); String isIn = element.getTag("is_in"); String country = element.getTag("is_in:country"); String region = element.getTag("is_in:county"); if(country != null) country = element.getTag("addr:country"); if(zip == null) zip = element.getTag("openGeoDB:postal_codes"); if(city == null) city = element.getTag("openGeoDB:sort_name"); if(city != null) ms.setCity(city); if(zip != null) ms.setZip(zip); if(street != null) ms.setStreet(street); if(houseNumber != null) ms.setHouseNumber(houseNumber); if(isIn != null) ms.setIsIn(isIn); if(phone != null) ms.setPhone(phone); if(country != null) ms.setCountry(country); if(region != null) ms.setRegion(region); } void addRoad(Way way, GType gt) { if("roundabout".equals(way.getTag("junction"))) { String frigFactorTag = way.getTag("mkgmap:frig_roundabout"); if(frigFactorTag != null) { // do special roundabout frigging to make gps // routing prompt use the correct exit number double frigFactor = 0.25; // default try { frigFactor = Double.parseDouble(frigFactorTag); } catch (NumberFormatException nfe) { // relax, tag was probably not a number anyway } frigRoundabout(way, frigFactor); } } // if there is a bounding box, clip the way with it List<Way> clippedWays = null; if(bbox != null) { List<List<Coord>> lineSegs = LineClipper.clip(bbox, way.getPoints()); boundaryCoords = new HashSet<Coord>(); if (lineSegs != null) { clippedWays = new ArrayList<Way>(); for (List<Coord> lco : lineSegs) { Way nWay = new Way(way.getId()); nWay.setName(way.getName()); nWay.copyTags(way); for(Coord co : lco) { nWay.addPoint(co); if(co.getHighwayCount() == 0) { boundaryCoords.add(co); co.incHighwayCount(); } } clippedWays.add(nWay); // associate the original Way // to the new Way Way origWay = originalWay.get(way); if(origWay == null) origWay = way; originalWay.put(nWay, origWay); } } } if(clippedWays != null) { for(Way cw : clippedWays) { while(cw.getPoints().size() > MAX_POINTS_IN_WAY) { Way tail = splitWayAt(cw, MAX_POINTS_IN_WAY - 1); addRoadAfterSplittingLoops(cw, gt); cw = tail; } addRoadAfterSplittingLoops(cw, gt); } } else { // no bounding box or way was not clipped while(way.getPoints().size() > MAX_POINTS_IN_WAY) { Way tail = splitWayAt(way, MAX_POINTS_IN_WAY - 1); addRoadAfterSplittingLoops(way, gt); way = tail; } addRoadAfterSplittingLoops(way, gt); } } void addRoadAfterSplittingLoops(Way way, GType gt) { // check if the way is a loop or intersects with itself boolean wayWasSplit = true; // aka rescan required while(wayWasSplit) { List<Coord> wayPoints = way.getPoints(); int numPointsInWay = wayPoints.size(); wayWasSplit = false; // assume way won't be split // check each point in the way to see if it is the same // point as a following point in the way (actually the // same object not just the same coordinates) for(int p1I = 0; !wayWasSplit && p1I < (numPointsInWay - 1); p1I++) { Coord p1 = wayPoints.get(p1I); for(int p2I = p1I + 1; !wayWasSplit && p2I < numPointsInWay; p2I++) { if(p1 == wayPoints.get(p2I)) { // way is a loop or intersects itself // attempt to split it into two ways // start at point before intersection point // check that splitting there will not produce // a zero length arc - if it does try the // previous point(s) int splitI = p2I - 1; while(splitI > p1I && p1.equals(wayPoints.get(splitI))) --splitI; if(splitI == p1I) { log.warn("Looped way " + getDebugName(way) + " has zero length arc - deleting node[" + p2I + "] to remove it"); wayPoints.remove(p2I); // next point to inspect has same index --p2I; // but number of points has reduced --numPointsInWay; } else { // split the way before the second point log.info("Splitting looped way " + getDebugName(way) + " at node[" + splitI + "] - it has " + (numPointsInWay - splitI - 1 ) + " following segment(s)."); Way loopTail = splitWayAt(way, splitI); // recursively check (shortened) head for // more loops addRoadAfterSplittingLoops(way, gt); // now process the tail of the way way = loopTail; wayWasSplit = true; } } } } if(!wayWasSplit) { // no split required so make road from way addRoadWithoutLoops(way, gt); } } } String getDebugName(Way way) { String name = way.getName(); if(name == null) name = way.getTag("ref"); if(name == null) name = ""; else name += " "; return name + "(OSM id " + way.getId() + ")"; } void addRoadWithoutLoops(Way way, GType gt) { List<Integer> nodeIndices = new ArrayList<Integer>(); List<Coord> points = way.getPoints(); Way trailingWay = null; String debugWayName = getDebugName(way); // make sure the way has nodes at each end points.get(0).incHighwayCount(); points.get(points.size() - 1).incHighwayCount(); // collect the Way's nodes and also split the way if any // inter-node arc length becomes excessive double arcLength = 0; for(int i = 0; i < points.size(); ++i) { Coord p = points.get(i); // check if we should split the way at this point to limit // the arc length between nodes if((i + 1) < points.size()) { double d = p.distance(points.get(i + 1)); if(d > MAX_ARC_LENGTH) { - double fraction = MAX_ARC_LENGTH / d; + double fraction = 0.99 * MAX_ARC_LENGTH / d; Coord extrap = p.makeBetweenPoint(points.get(i + 1), fraction); extrap.incHighwayCount(); points.add(i + 1, extrap); double newD = p.distance(extrap); log.warn("Way " + debugWayName + " contains a segment that is " + (int)d + "m long so I am adding a point to reduce its length to " + (int)newD + "m"); d = newD; } if((arcLength + d) > MAX_ARC_LENGTH) { assert i > 0; trailingWay = splitWayAt(way, i); // this will have truncated the current Way's // points so the loop will now terminate log.warn("Splitting way " + debugWayName + " at " + points.get(i).toDegreeString() + " to limit arc length to " + (long)arcLength + "m"); } else { if(p.getHighwayCount() > 1) // point is a node so zero arc length arcLength = 0; arcLength += d; } } if(p.getHighwayCount() > 1) { // this point is a node connecting highways Integer nodeId = nodeIdMap.get(p); if(nodeId == null) { // assign a node id nodeIdMap.put(p, nextNodeId++); } nodeIndices.add(i); if((i + 1) < points.size() && nodeIndices.size() == MAX_NODES_IN_WAY) { // this isn't the last point in the way so split // it here to avoid exceeding the max nodes in way // limit trailingWay = splitWayAt(way, i); // this will have truncated the current Way's // points so the loop will now terminate log.info("Splitting way " + debugWayName + " at " + points.get(i).toDegreeString() + " as it has at least " + MAX_NODES_IN_WAY + " nodes"); } } } MapLine line = new MapLine(); elementSetup(line, gt, way); line.setPoints(points); MapRoad road = new MapRoad(way.getId(), line); // set road parameters. road.setRoadClass(gt.getRoadClass()); if (way.isBoolTag("oneway")) { road.setDirection(true); road.setOneway(); } int speedIdx = -1; if(!ignoreMaxspeeds) { // maxspeed attribute overrides default for road type String maxSpeed = way.getTag("maxspeed"); if(maxSpeed != null) { speedIdx = getSpeedIdx(maxSpeed); log.info(debugWayName + " maxspeed=" + maxSpeed + ", speedIndex=" + speedIdx); } } road.setSpeed(speedIdx >= 0? speedIdx : gt.getRoadSpeed()); boolean[] noAccess = new boolean[RoadNetwork.NO_MAX]; String highwayType = way.getTag("highway"); if(highwayType == null) { // it's a routable way but not a highway (e.g. a ferry) // use the value of the route tag as the highwayType for // the purpose of testing for access restrictions highwayType = way.getTag("route"); } for (AccessMapping anAccessMap : accessMap) { int index = anAccessMap.index; String type = anAccessMap.type; String accessTagValue = way.getTag(type); if (accessTagValue == null) continue; if (accessExplicitlyDenied(accessTagValue)) { if (index == RoadNetwork.NO_MAX) { // everything is denied access for (int j = 1; j < accessMap.length; ++j) noAccess[accessMap[j].index] = true; } else { // just the specific vehicle class is denied // access noAccess[index] = true; } log.info(type + " is not allowed in " + highwayType + " " + debugWayName); } else if (accessExplicitlyAllowed(accessTagValue)) { if (index == RoadNetwork.NO_MAX) { // everything is allowed access for (int j = 1; j < accessMap.length; ++j) noAccess[accessMap[j].index] = false; } else { // just the specific vehicle class is allowed // access noAccess[index] = false; } log.info(type + " is allowed in " + highwayType + " " + debugWayName); } else if (accessTagValue.equalsIgnoreCase("destination")) { if (type.equals("motorcar") || type.equals("motorcycle")) { road.setNoThroughRouting(); } else if (type.equals("access")) { log.warn("access=destination only affects routing for cars in " + highwayType + " " + debugWayName); road.setNoThroughRouting(); } else { log.warn(type + "=destination ignored in " + highwayType + " " + debugWayName); } } else if (accessTagValue.equalsIgnoreCase("unknown")) { // implicitly allow access } else { log.warn("Ignoring unsupported access tag value " + type + "=" + accessTagValue + " in " + highwayType + " " + debugWayName); } } road.setAccess(noAccess); if(way.isBoolTag("toll")) road.setToll(); Way origWay = originalWay.get(way); if(origWay == null) origWay = way; int numNodes = nodeIndices.size(); road.setNumNodes(numNodes); if(numNodes > 0) { // replace Coords that are nodes with CoordNodes boolean hasInternalNodes = false; CoordNode lastCoordNode = null; List<RestrictionRelation> lastRestrictions = null; for(int i = 0; i < numNodes; ++i) { int n = nodeIndices.get(i); if(n > 0 && n < points.size() - 1) hasInternalNodes = true; Coord coord = points.get(n); Integer nodeId = nodeIdMap.get(coord); boolean boundary = boundaryCoords.contains(coord); if(boundary) { log.info("Way " + debugWayName + "'s point #" + n + " at " + points.get(n).toDegreeString() + " is a boundary node"); } CoordNode thisCoordNode = new CoordNode(coord.getLatitude(), coord.getLongitude(), nodeId, boundary); points.set(n, thisCoordNode); // see if this node plays a role in any turn // restrictions if(lastRestrictions != null) { // the previous node was the location of one or // more restrictions for(RestrictionRelation rr : lastRestrictions) { if(rr.getToWay().equals(origWay)) { rr.setToNode(thisCoordNode); } else if(rr.getFromWay().equals(origWay)) { rr.setFromNode(thisCoordNode); } else { rr.addOtherNode(thisCoordNode); } } } List<RestrictionRelation> theseRestrictions = restrictions.get(coord); if(theseRestrictions != null) { // this node is the location of one or more // restrictions for(RestrictionRelation rr : theseRestrictions) { rr.setViaNode(thisCoordNode); if(rr.getToWay().equals(origWay)) { if(lastCoordNode != null) rr.setToNode(lastCoordNode); } else if(rr.getFromWay().equals(origWay)) { if(lastCoordNode != null) rr.setFromNode(lastCoordNode); } else if(lastCoordNode != null) { rr.addOtherNode(lastCoordNode); } } } lastRestrictions = theseRestrictions; lastCoordNode = thisCoordNode; } road.setStartsWithNode(nodeIndices.get(0) == 0); road.setInternalNodes(hasInternalNodes); } lineAdder.add(road); if(trailingWay != null) addRoadWithoutLoops(trailingWay, gt); } // split a Way at the specified point and return the new Way (the // original Way is truncated) Way splitWayAt(Way way, int index) { Way trailingWay = new Way(way.getId()); List<Coord> wayPoints = way.getPoints(); int numPointsInWay = wayPoints.size(); for(int i = index; i < numPointsInWay; ++i) trailingWay.addPoint(wayPoints.get(i)); // ensure split point becomes a node wayPoints.get(index).incHighwayCount(); // copy the way's name and tags to the new way trailingWay.setName(way.getName()); trailingWay.copyTags(way); // remove the points after the split from the original way // it's probably more efficient to remove from the end first for(int i = numPointsInWay - 1; i > index; --i) wayPoints.remove(i); // associate the original Way to the new Way Way origWay = originalWay.get(way); if(origWay == null) origWay = way; originalWay.put(trailingWay, origWay); return trailingWay; } // function to add points between adjacent nodes in a roundabout // to make gps use correct exit number in routing instructions void frigRoundabout(Way way, double frigFactor) { List<Coord> wayPoints = way.getPoints(); int origNumPoints = wayPoints.size(); if(origNumPoints < 3) { // forget it! return; } int[] highWayCounts = new int[origNumPoints]; int middleLat = 0; int middleLon = 0; highWayCounts[0] = wayPoints.get(0).getHighwayCount(); for(int i = 1; i < origNumPoints; ++i) { Coord p = wayPoints.get(i); middleLat += p.getLatitude(); middleLon += p.getLongitude(); highWayCounts[i] = p.getHighwayCount(); } middleLat /= origNumPoints - 1; middleLon /= origNumPoints - 1; Coord middleCoord = new Coord(middleLat, middleLon); // account for fact that roundabout joins itself --highWayCounts[0]; --highWayCounts[origNumPoints - 1]; for(int i = origNumPoints - 2; i >= 0; --i) { Coord p1 = wayPoints.get(i); Coord p2 = wayPoints.get(i + 1); if(highWayCounts[i] > 1 && highWayCounts[i + 1] > 1) { // both points will be nodes so insert a new point // between them that (approximately) falls on the // roundabout's perimeter int newLat = (p1.getLatitude() + p2.getLatitude()) / 2; int newLon = (p1.getLongitude() + p2.getLongitude()) / 2; // new point has to be "outside" of existing line // joining p1 and p2 - how far outside is determined // by the ratio of the distance between p1 and p2 // compared to the distance of p1 from the "middle" of // the roundabout (aka, the approx radius of the // roundabout) - the higher the value of frigFactor, // the further out the point will be double scale = 1 + frigFactor * p1.distance(p2) / p1.distance(middleCoord); newLat = (int)((newLat - middleLat) * scale) + middleLat; newLon = (int)((newLon - middleLon) * scale) + middleLon; Coord newPoint = new Coord(newLat, newLon); double d1 = p1.distance(newPoint); double d2 = p2.distance(newPoint); double maxDistance = 100; if(d1 >= MIN_DISTANCE_BETWEEN_NODES && d1 <= maxDistance && d2 >= MIN_DISTANCE_BETWEEN_NODES && d2 <= maxDistance) { newPoint.incHighwayCount(); wayPoints.add(i + 1, newPoint); } } } } int getSpeedIdx(String tag) { double kmh; double factor = 1.0; String speedTag = tag.toLowerCase().trim(); if(speedTag.matches(".*mph")) // Check if it is a limit in mph { speedTag = speedTag.replaceFirst("mph", ""); factor = 1.61; } else speedTag = speedTag.replaceFirst("kmh", ""); // get rid of kmh just in case try { kmh = Integer.parseInt(speedTag) * factor; } catch (Exception e) { return -1; } if(kmh > 110) return 7; if(kmh > 90) return 6; if(kmh > 80) return 5; if(kmh > 60) return 4; if(kmh > 40) return 3; if(kmh > 20) return 2; if(kmh > 10) return 1; else return 0; } protected boolean accessExplicitlyAllowed(String val) { if (val == null) return false; return (val.equalsIgnoreCase("yes") || val.equalsIgnoreCase("designated") || val.equalsIgnoreCase("permissive")); } protected boolean accessExplicitlyDenied(String val) { if (val == null) return false; return (val.equalsIgnoreCase("no") || val.equalsIgnoreCase("private")); } }
true
true
void addRoadWithoutLoops(Way way, GType gt) { List<Integer> nodeIndices = new ArrayList<Integer>(); List<Coord> points = way.getPoints(); Way trailingWay = null; String debugWayName = getDebugName(way); // make sure the way has nodes at each end points.get(0).incHighwayCount(); points.get(points.size() - 1).incHighwayCount(); // collect the Way's nodes and also split the way if any // inter-node arc length becomes excessive double arcLength = 0; for(int i = 0; i < points.size(); ++i) { Coord p = points.get(i); // check if we should split the way at this point to limit // the arc length between nodes if((i + 1) < points.size()) { double d = p.distance(points.get(i + 1)); if(d > MAX_ARC_LENGTH) { double fraction = MAX_ARC_LENGTH / d; Coord extrap = p.makeBetweenPoint(points.get(i + 1), fraction); extrap.incHighwayCount(); points.add(i + 1, extrap); double newD = p.distance(extrap); log.warn("Way " + debugWayName + " contains a segment that is " + (int)d + "m long so I am adding a point to reduce its length to " + (int)newD + "m"); d = newD; } if((arcLength + d) > MAX_ARC_LENGTH) { assert i > 0; trailingWay = splitWayAt(way, i); // this will have truncated the current Way's // points so the loop will now terminate log.warn("Splitting way " + debugWayName + " at " + points.get(i).toDegreeString() + " to limit arc length to " + (long)arcLength + "m"); } else { if(p.getHighwayCount() > 1) // point is a node so zero arc length arcLength = 0; arcLength += d; } } if(p.getHighwayCount() > 1) { // this point is a node connecting highways Integer nodeId = nodeIdMap.get(p); if(nodeId == null) { // assign a node id nodeIdMap.put(p, nextNodeId++); } nodeIndices.add(i); if((i + 1) < points.size() && nodeIndices.size() == MAX_NODES_IN_WAY) { // this isn't the last point in the way so split // it here to avoid exceeding the max nodes in way // limit trailingWay = splitWayAt(way, i); // this will have truncated the current Way's // points so the loop will now terminate log.info("Splitting way " + debugWayName + " at " + points.get(i).toDegreeString() + " as it has at least " + MAX_NODES_IN_WAY + " nodes"); } } } MapLine line = new MapLine(); elementSetup(line, gt, way); line.setPoints(points); MapRoad road = new MapRoad(way.getId(), line); // set road parameters. road.setRoadClass(gt.getRoadClass()); if (way.isBoolTag("oneway")) { road.setDirection(true); road.setOneway(); } int speedIdx = -1; if(!ignoreMaxspeeds) { // maxspeed attribute overrides default for road type String maxSpeed = way.getTag("maxspeed"); if(maxSpeed != null) { speedIdx = getSpeedIdx(maxSpeed); log.info(debugWayName + " maxspeed=" + maxSpeed + ", speedIndex=" + speedIdx); } } road.setSpeed(speedIdx >= 0? speedIdx : gt.getRoadSpeed()); boolean[] noAccess = new boolean[RoadNetwork.NO_MAX]; String highwayType = way.getTag("highway"); if(highwayType == null) { // it's a routable way but not a highway (e.g. a ferry) // use the value of the route tag as the highwayType for // the purpose of testing for access restrictions highwayType = way.getTag("route"); } for (AccessMapping anAccessMap : accessMap) { int index = anAccessMap.index; String type = anAccessMap.type; String accessTagValue = way.getTag(type); if (accessTagValue == null) continue; if (accessExplicitlyDenied(accessTagValue)) { if (index == RoadNetwork.NO_MAX) { // everything is denied access for (int j = 1; j < accessMap.length; ++j) noAccess[accessMap[j].index] = true; } else { // just the specific vehicle class is denied // access noAccess[index] = true; } log.info(type + " is not allowed in " + highwayType + " " + debugWayName); } else if (accessExplicitlyAllowed(accessTagValue)) { if (index == RoadNetwork.NO_MAX) { // everything is allowed access for (int j = 1; j < accessMap.length; ++j) noAccess[accessMap[j].index] = false; } else { // just the specific vehicle class is allowed // access noAccess[index] = false; } log.info(type + " is allowed in " + highwayType + " " + debugWayName); } else if (accessTagValue.equalsIgnoreCase("destination")) { if (type.equals("motorcar") || type.equals("motorcycle")) { road.setNoThroughRouting(); } else if (type.equals("access")) { log.warn("access=destination only affects routing for cars in " + highwayType + " " + debugWayName); road.setNoThroughRouting(); } else { log.warn(type + "=destination ignored in " + highwayType + " " + debugWayName); } } else if (accessTagValue.equalsIgnoreCase("unknown")) { // implicitly allow access } else { log.warn("Ignoring unsupported access tag value " + type + "=" + accessTagValue + " in " + highwayType + " " + debugWayName); } } road.setAccess(noAccess); if(way.isBoolTag("toll")) road.setToll(); Way origWay = originalWay.get(way); if(origWay == null) origWay = way; int numNodes = nodeIndices.size(); road.setNumNodes(numNodes); if(numNodes > 0) { // replace Coords that are nodes with CoordNodes boolean hasInternalNodes = false; CoordNode lastCoordNode = null; List<RestrictionRelation> lastRestrictions = null; for(int i = 0; i < numNodes; ++i) { int n = nodeIndices.get(i); if(n > 0 && n < points.size() - 1) hasInternalNodes = true; Coord coord = points.get(n); Integer nodeId = nodeIdMap.get(coord); boolean boundary = boundaryCoords.contains(coord); if(boundary) { log.info("Way " + debugWayName + "'s point #" + n + " at " + points.get(n).toDegreeString() + " is a boundary node"); } CoordNode thisCoordNode = new CoordNode(coord.getLatitude(), coord.getLongitude(), nodeId, boundary); points.set(n, thisCoordNode); // see if this node plays a role in any turn // restrictions if(lastRestrictions != null) { // the previous node was the location of one or // more restrictions for(RestrictionRelation rr : lastRestrictions) { if(rr.getToWay().equals(origWay)) { rr.setToNode(thisCoordNode); } else if(rr.getFromWay().equals(origWay)) { rr.setFromNode(thisCoordNode); } else { rr.addOtherNode(thisCoordNode); } } } List<RestrictionRelation> theseRestrictions = restrictions.get(coord); if(theseRestrictions != null) { // this node is the location of one or more // restrictions for(RestrictionRelation rr : theseRestrictions) { rr.setViaNode(thisCoordNode); if(rr.getToWay().equals(origWay)) { if(lastCoordNode != null) rr.setToNode(lastCoordNode); } else if(rr.getFromWay().equals(origWay)) { if(lastCoordNode != null) rr.setFromNode(lastCoordNode); } else if(lastCoordNode != null) { rr.addOtherNode(lastCoordNode); } } } lastRestrictions = theseRestrictions; lastCoordNode = thisCoordNode; } road.setStartsWithNode(nodeIndices.get(0) == 0); road.setInternalNodes(hasInternalNodes); } lineAdder.add(road); if(trailingWay != null) addRoadWithoutLoops(trailingWay, gt); }
void addRoadWithoutLoops(Way way, GType gt) { List<Integer> nodeIndices = new ArrayList<Integer>(); List<Coord> points = way.getPoints(); Way trailingWay = null; String debugWayName = getDebugName(way); // make sure the way has nodes at each end points.get(0).incHighwayCount(); points.get(points.size() - 1).incHighwayCount(); // collect the Way's nodes and also split the way if any // inter-node arc length becomes excessive double arcLength = 0; for(int i = 0; i < points.size(); ++i) { Coord p = points.get(i); // check if we should split the way at this point to limit // the arc length between nodes if((i + 1) < points.size()) { double d = p.distance(points.get(i + 1)); if(d > MAX_ARC_LENGTH) { double fraction = 0.99 * MAX_ARC_LENGTH / d; Coord extrap = p.makeBetweenPoint(points.get(i + 1), fraction); extrap.incHighwayCount(); points.add(i + 1, extrap); double newD = p.distance(extrap); log.warn("Way " + debugWayName + " contains a segment that is " + (int)d + "m long so I am adding a point to reduce its length to " + (int)newD + "m"); d = newD; } if((arcLength + d) > MAX_ARC_LENGTH) { assert i > 0; trailingWay = splitWayAt(way, i); // this will have truncated the current Way's // points so the loop will now terminate log.warn("Splitting way " + debugWayName + " at " + points.get(i).toDegreeString() + " to limit arc length to " + (long)arcLength + "m"); } else { if(p.getHighwayCount() > 1) // point is a node so zero arc length arcLength = 0; arcLength += d; } } if(p.getHighwayCount() > 1) { // this point is a node connecting highways Integer nodeId = nodeIdMap.get(p); if(nodeId == null) { // assign a node id nodeIdMap.put(p, nextNodeId++); } nodeIndices.add(i); if((i + 1) < points.size() && nodeIndices.size() == MAX_NODES_IN_WAY) { // this isn't the last point in the way so split // it here to avoid exceeding the max nodes in way // limit trailingWay = splitWayAt(way, i); // this will have truncated the current Way's // points so the loop will now terminate log.info("Splitting way " + debugWayName + " at " + points.get(i).toDegreeString() + " as it has at least " + MAX_NODES_IN_WAY + " nodes"); } } } MapLine line = new MapLine(); elementSetup(line, gt, way); line.setPoints(points); MapRoad road = new MapRoad(way.getId(), line); // set road parameters. road.setRoadClass(gt.getRoadClass()); if (way.isBoolTag("oneway")) { road.setDirection(true); road.setOneway(); } int speedIdx = -1; if(!ignoreMaxspeeds) { // maxspeed attribute overrides default for road type String maxSpeed = way.getTag("maxspeed"); if(maxSpeed != null) { speedIdx = getSpeedIdx(maxSpeed); log.info(debugWayName + " maxspeed=" + maxSpeed + ", speedIndex=" + speedIdx); } } road.setSpeed(speedIdx >= 0? speedIdx : gt.getRoadSpeed()); boolean[] noAccess = new boolean[RoadNetwork.NO_MAX]; String highwayType = way.getTag("highway"); if(highwayType == null) { // it's a routable way but not a highway (e.g. a ferry) // use the value of the route tag as the highwayType for // the purpose of testing for access restrictions highwayType = way.getTag("route"); } for (AccessMapping anAccessMap : accessMap) { int index = anAccessMap.index; String type = anAccessMap.type; String accessTagValue = way.getTag(type); if (accessTagValue == null) continue; if (accessExplicitlyDenied(accessTagValue)) { if (index == RoadNetwork.NO_MAX) { // everything is denied access for (int j = 1; j < accessMap.length; ++j) noAccess[accessMap[j].index] = true; } else { // just the specific vehicle class is denied // access noAccess[index] = true; } log.info(type + " is not allowed in " + highwayType + " " + debugWayName); } else if (accessExplicitlyAllowed(accessTagValue)) { if (index == RoadNetwork.NO_MAX) { // everything is allowed access for (int j = 1; j < accessMap.length; ++j) noAccess[accessMap[j].index] = false; } else { // just the specific vehicle class is allowed // access noAccess[index] = false; } log.info(type + " is allowed in " + highwayType + " " + debugWayName); } else if (accessTagValue.equalsIgnoreCase("destination")) { if (type.equals("motorcar") || type.equals("motorcycle")) { road.setNoThroughRouting(); } else if (type.equals("access")) { log.warn("access=destination only affects routing for cars in " + highwayType + " " + debugWayName); road.setNoThroughRouting(); } else { log.warn(type + "=destination ignored in " + highwayType + " " + debugWayName); } } else if (accessTagValue.equalsIgnoreCase("unknown")) { // implicitly allow access } else { log.warn("Ignoring unsupported access tag value " + type + "=" + accessTagValue + " in " + highwayType + " " + debugWayName); } } road.setAccess(noAccess); if(way.isBoolTag("toll")) road.setToll(); Way origWay = originalWay.get(way); if(origWay == null) origWay = way; int numNodes = nodeIndices.size(); road.setNumNodes(numNodes); if(numNodes > 0) { // replace Coords that are nodes with CoordNodes boolean hasInternalNodes = false; CoordNode lastCoordNode = null; List<RestrictionRelation> lastRestrictions = null; for(int i = 0; i < numNodes; ++i) { int n = nodeIndices.get(i); if(n > 0 && n < points.size() - 1) hasInternalNodes = true; Coord coord = points.get(n); Integer nodeId = nodeIdMap.get(coord); boolean boundary = boundaryCoords.contains(coord); if(boundary) { log.info("Way " + debugWayName + "'s point #" + n + " at " + points.get(n).toDegreeString() + " is a boundary node"); } CoordNode thisCoordNode = new CoordNode(coord.getLatitude(), coord.getLongitude(), nodeId, boundary); points.set(n, thisCoordNode); // see if this node plays a role in any turn // restrictions if(lastRestrictions != null) { // the previous node was the location of one or // more restrictions for(RestrictionRelation rr : lastRestrictions) { if(rr.getToWay().equals(origWay)) { rr.setToNode(thisCoordNode); } else if(rr.getFromWay().equals(origWay)) { rr.setFromNode(thisCoordNode); } else { rr.addOtherNode(thisCoordNode); } } } List<RestrictionRelation> theseRestrictions = restrictions.get(coord); if(theseRestrictions != null) { // this node is the location of one or more // restrictions for(RestrictionRelation rr : theseRestrictions) { rr.setViaNode(thisCoordNode); if(rr.getToWay().equals(origWay)) { if(lastCoordNode != null) rr.setToNode(lastCoordNode); } else if(rr.getFromWay().equals(origWay)) { if(lastCoordNode != null) rr.setFromNode(lastCoordNode); } else if(lastCoordNode != null) { rr.addOtherNode(lastCoordNode); } } } lastRestrictions = theseRestrictions; lastCoordNode = thisCoordNode; } road.setStartsWithNode(nodeIndices.get(0) == 0); road.setInternalNodes(hasInternalNodes); } lineAdder.add(road); if(trailingWay != null) addRoadWithoutLoops(trailingWay, gt); }
diff --git a/core/src/test/java/org/apache/commons/vfs2/test/LastModifiedTests.java b/core/src/test/java/org/apache/commons/vfs2/test/LastModifiedTests.java index a0428157..acd7f5f8 100644 --- a/core/src/test/java/org/apache/commons/vfs2/test/LastModifiedTests.java +++ b/core/src/test/java/org/apache/commons/vfs2/test/LastModifiedTests.java @@ -1,111 +1,115 @@ /* * 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.commons.vfs2.test; import junit.framework.AssertionFailedError; import org.apache.commons.vfs2.Capability; import org.apache.commons.vfs2.FileObject; /** * Test cases for getting and setting file last modified time. * * @author <a href="mailto:[email protected]">Adam Murdoch</a> */ public class LastModifiedTests extends AbstractProviderTestCase { /** * Returns the capabilities required by the tests of this test case. */ @Override protected Capability[] getRequiredCaps() { return new Capability[]{ Capability.GET_LAST_MODIFIED }; } /** * Tests getting the last modified time of a file. */ public void testGetLastModified() throws Exception { // Try a file. final FileObject file = getReadFolder().resolveFile("file1.txt"); file.getContent().getLastModifiedTime(); // TODO - switch this on // Try a folder //final FileObject folder = getReadFolder().resolveFile( "dir1" ); //folder.getContent().getLastModifiedTime(); } /** * Tests setting the last modified time of file. */ public void testSetLastModified() throws Exception { final long now = System.currentTimeMillis(); if (getReadFolder().getFileSystem().hasCapability(Capability.SET_LAST_MODIFIED_FILE)) { // Try a file final FileObject file = getReadFolder().resolveFile("file1.txt"); file.getContent().setLastModifiedTime(now); + final double lastModTimeAccuracy = file.getFileSystem().getLastModTimeAccuracy(); + final long lastModifiedTime = file.getContent().getLastModifiedTime(); try { - assertEquals("Check 1", now, file.getContent().getLastModifiedTime(), file.getFileSystem().getLastModTimeAccuracy()); + assertEquals("Check 1", now, lastModifiedTime, lastModTimeAccuracy); } catch (AssertionFailedError e) { // on linux ext3 the above check is not necessarily true - if (file.getFileSystem().getLastModTimeAccuracy() < 1000L) + if (lastModTimeAccuracy < 1000L) { - assertEquals("Check 2", now, file.getContent().getLastModifiedTime(), 1000L); + assertEquals("Check 2", now, lastModifiedTime, 1000L); } else { throw e; } } } if (getReadFolder().getFileSystem().hasCapability(Capability.SET_LAST_MODIFIED_FOLDER)) { // Try a folder final FileObject folder = getReadFolder().resolveFile("dir1"); folder.getContent().setLastModifiedTime(now); + final double lastModTimeAccuracy = folder.getFileSystem().getLastModTimeAccuracy(); + final long lastModifiedTime = folder.getContent().getLastModifiedTime(); try { - assertEquals("Check 3", now, folder.getContent().getLastModifiedTime(), folder.getFileSystem().getLastModTimeAccuracy()); + assertEquals("Check 3", now, lastModifiedTime, lastModTimeAccuracy); } catch (AssertionFailedError e) { // on linux ext3 the above check is not necessarily true - if (folder.getFileSystem().getLastModTimeAccuracy() < 1000L) + if (lastModTimeAccuracy < 1000L) { - assertEquals("Check 4", now, folder.getContent().getLastModifiedTime(), 1000L); + assertEquals("Check 4", now, lastModifiedTime, 1000L); } else { throw e; } } } } }
false
true
public void testSetLastModified() throws Exception { final long now = System.currentTimeMillis(); if (getReadFolder().getFileSystem().hasCapability(Capability.SET_LAST_MODIFIED_FILE)) { // Try a file final FileObject file = getReadFolder().resolveFile("file1.txt"); file.getContent().setLastModifiedTime(now); try { assertEquals("Check 1", now, file.getContent().getLastModifiedTime(), file.getFileSystem().getLastModTimeAccuracy()); } catch (AssertionFailedError e) { // on linux ext3 the above check is not necessarily true if (file.getFileSystem().getLastModTimeAccuracy() < 1000L) { assertEquals("Check 2", now, file.getContent().getLastModifiedTime(), 1000L); } else { throw e; } } } if (getReadFolder().getFileSystem().hasCapability(Capability.SET_LAST_MODIFIED_FOLDER)) { // Try a folder final FileObject folder = getReadFolder().resolveFile("dir1"); folder.getContent().setLastModifiedTime(now); try { assertEquals("Check 3", now, folder.getContent().getLastModifiedTime(), folder.getFileSystem().getLastModTimeAccuracy()); } catch (AssertionFailedError e) { // on linux ext3 the above check is not necessarily true if (folder.getFileSystem().getLastModTimeAccuracy() < 1000L) { assertEquals("Check 4", now, folder.getContent().getLastModifiedTime(), 1000L); } else { throw e; } } } }
public void testSetLastModified() throws Exception { final long now = System.currentTimeMillis(); if (getReadFolder().getFileSystem().hasCapability(Capability.SET_LAST_MODIFIED_FILE)) { // Try a file final FileObject file = getReadFolder().resolveFile("file1.txt"); file.getContent().setLastModifiedTime(now); final double lastModTimeAccuracy = file.getFileSystem().getLastModTimeAccuracy(); final long lastModifiedTime = file.getContent().getLastModifiedTime(); try { assertEquals("Check 1", now, lastModifiedTime, lastModTimeAccuracy); } catch (AssertionFailedError e) { // on linux ext3 the above check is not necessarily true if (lastModTimeAccuracy < 1000L) { assertEquals("Check 2", now, lastModifiedTime, 1000L); } else { throw e; } } } if (getReadFolder().getFileSystem().hasCapability(Capability.SET_LAST_MODIFIED_FOLDER)) { // Try a folder final FileObject folder = getReadFolder().resolveFile("dir1"); folder.getContent().setLastModifiedTime(now); final double lastModTimeAccuracy = folder.getFileSystem().getLastModTimeAccuracy(); final long lastModifiedTime = folder.getContent().getLastModifiedTime(); try { assertEquals("Check 3", now, lastModifiedTime, lastModTimeAccuracy); } catch (AssertionFailedError e) { // on linux ext3 the above check is not necessarily true if (lastModTimeAccuracy < 1000L) { assertEquals("Check 4", now, lastModifiedTime, 1000L); } else { throw e; } } } }
diff --git a/src/test/java/com/github/detro/rps/http/test/RouterTest.java b/src/test/java/com/github/detro/rps/http/test/RouterTest.java index 8d1e6a3..6f365fc 100644 --- a/src/test/java/com/github/detro/rps/http/test/RouterTest.java +++ b/src/test/java/com/github/detro/rps/http/test/RouterTest.java @@ -1,150 +1,150 @@ package com.github.detro.rps.http.test; import com.github.detro.rps.Match; import com.github.detro.rps.Weapons; import com.github.detro.rps.http.Router; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.PutMethod; import org.openqa.selenium.net.PortProber; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.testng.Assert.*; // TODO Definitely needs more tests public class RouterTest { private static final int PORT = PortProber.findFreePort(); private static final Router ROUTER = new Router(); private static final String BASEURL = "http://localhost:" + PORT + Router.API_PATH; @BeforeClass public static void startRouter() { ROUTER.listen(PORT); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } @Test public void shouldReturnListOfAllAvailableWeapons() { HttpClient client = new HttpClient(); GetMethod getWeapons = new GetMethod(BASEURL + "/weapons"); try { // execute and check status code int statusCode = client.executeMethod(getWeapons); assertEquals(statusCode, 200); // check response body String body = new String(getWeapons.getResponseBody()); assertTrue(body.startsWith("[")); assertTrue(body.endsWith("]")); for (int i = 0, ilen = Weapons.weaponsAmount(); i < ilen; ++i) { assertTrue(body.contains(Weapons.getName(i))); } } catch (IOException ioe) { fail(); } finally { getWeapons.releaseConnection(); } } @Test public void shouldAllowToPlayAMatch() { HttpClient client1 = new HttpClient(); HttpClient client2 = new HttpClient(); PostMethod createMatch = null; PutMethod joinMatch = null; PutMethod setWeapon = null; PutMethod restartMatch = null; GetMethod getMatchInfo = null; String body; JsonObject jsonBody; String matchId; // Create a Match try { // First Player creates the match createMatch = new PostMethod(BASEURL + "/match"); createMatch.setParameter("kind", "pvp"); assertEquals(client1.executeMethod(createMatch), 200); // Extract Match ID from response body body = new String(createMatch.getResponseBody()); jsonBody = new JsonParser().parse(body).getAsJsonObject(); assertTrue(jsonBody.isJsonObject()); assertTrue(jsonBody.has("id")); assertTrue(jsonBody.get("id").isJsonPrimitive()); assertNotNull(jsonBody.get("id")); matchId = jsonBody.get("id").getAsString(); // First Player joins the match joinMatch = new PutMethod(BASEURL + "/match/" + matchId); joinMatch.setQueryString(new NameValuePair[] { new NameValuePair("action", "join")}); assertEquals(client1.executeMethod(joinMatch), 200); // Second Player joins the match assertEquals(client2.executeMethod(joinMatch), 200); // First and Second Player set the same weapon setWeapon = new PutMethod(BASEURL + "/match/" + matchId); setWeapon.setQueryString(new NameValuePair[] { new NameValuePair("action", "weapon"), - new NameValuePair("weaponid", "1") + new NameValuePair("weaponId", "1") }); assertEquals(client1.executeMethod(setWeapon), 200); assertEquals(client2.executeMethod(setWeapon), 200); // Check Match is has now been played getMatchInfo = new GetMethod(BASEURL + "/match/" + matchId); assertEquals(client1.executeMethod(getMatchInfo), 200); body = new String(getMatchInfo.getResponseBody()); jsonBody = new JsonParser().parse(body).getAsJsonObject(); // Extract the Match status assertTrue(jsonBody.has("status")); assertTrue(jsonBody.get("status").isJsonPrimitive()); assertEquals(jsonBody.get("status").getAsInt(), Match.PLAYED); // Extract the Match result assertTrue(jsonBody.has("result")); assertTrue(jsonBody.get("result").isJsonPrimitive()); assertEquals(jsonBody.get("result").getAsString(), "draw"); // Reset the Match restartMatch = new PutMethod(BASEURL + "/match/" + matchId); restartMatch.setQueryString(new NameValuePair[]{new NameValuePair("action", "restart")}); assertEquals(client2.executeMethod(restartMatch), 200); // Check Match is has now been reset getMatchInfo = new GetMethod(BASEURL + "/match/" + matchId); assertEquals(client2.executeMethod(getMatchInfo), 200); body = new String(getMatchInfo.getResponseBody()); // Extract the Match status jsonBody = new JsonParser().parse(body).getAsJsonObject(); assertTrue(jsonBody.has("status")); assertTrue(jsonBody.get("status").isJsonPrimitive()); assertEquals(jsonBody.get("status").getAsInt(), Match.WAITING_PLAYERS_WEAPONS); } catch (IOException ioe) { fail(); } finally { if (createMatch != null) createMatch.releaseConnection(); if (joinMatch != null) joinMatch.releaseConnection(); if (setWeapon != null) setWeapon.releaseConnection(); if (restartMatch != null) restartMatch.releaseConnection(); if (getMatchInfo != null) getMatchInfo.releaseConnection(); } } }
true
true
public void shouldAllowToPlayAMatch() { HttpClient client1 = new HttpClient(); HttpClient client2 = new HttpClient(); PostMethod createMatch = null; PutMethod joinMatch = null; PutMethod setWeapon = null; PutMethod restartMatch = null; GetMethod getMatchInfo = null; String body; JsonObject jsonBody; String matchId; // Create a Match try { // First Player creates the match createMatch = new PostMethod(BASEURL + "/match"); createMatch.setParameter("kind", "pvp"); assertEquals(client1.executeMethod(createMatch), 200); // Extract Match ID from response body body = new String(createMatch.getResponseBody()); jsonBody = new JsonParser().parse(body).getAsJsonObject(); assertTrue(jsonBody.isJsonObject()); assertTrue(jsonBody.has("id")); assertTrue(jsonBody.get("id").isJsonPrimitive()); assertNotNull(jsonBody.get("id")); matchId = jsonBody.get("id").getAsString(); // First Player joins the match joinMatch = new PutMethod(BASEURL + "/match/" + matchId); joinMatch.setQueryString(new NameValuePair[] { new NameValuePair("action", "join")}); assertEquals(client1.executeMethod(joinMatch), 200); // Second Player joins the match assertEquals(client2.executeMethod(joinMatch), 200); // First and Second Player set the same weapon setWeapon = new PutMethod(BASEURL + "/match/" + matchId); setWeapon.setQueryString(new NameValuePair[] { new NameValuePair("action", "weapon"), new NameValuePair("weaponid", "1") }); assertEquals(client1.executeMethod(setWeapon), 200); assertEquals(client2.executeMethod(setWeapon), 200); // Check Match is has now been played getMatchInfo = new GetMethod(BASEURL + "/match/" + matchId); assertEquals(client1.executeMethod(getMatchInfo), 200); body = new String(getMatchInfo.getResponseBody()); jsonBody = new JsonParser().parse(body).getAsJsonObject(); // Extract the Match status assertTrue(jsonBody.has("status")); assertTrue(jsonBody.get("status").isJsonPrimitive()); assertEquals(jsonBody.get("status").getAsInt(), Match.PLAYED); // Extract the Match result assertTrue(jsonBody.has("result")); assertTrue(jsonBody.get("result").isJsonPrimitive()); assertEquals(jsonBody.get("result").getAsString(), "draw"); // Reset the Match restartMatch = new PutMethod(BASEURL + "/match/" + matchId); restartMatch.setQueryString(new NameValuePair[]{new NameValuePair("action", "restart")}); assertEquals(client2.executeMethod(restartMatch), 200); // Check Match is has now been reset getMatchInfo = new GetMethod(BASEURL + "/match/" + matchId); assertEquals(client2.executeMethod(getMatchInfo), 200); body = new String(getMatchInfo.getResponseBody()); // Extract the Match status jsonBody = new JsonParser().parse(body).getAsJsonObject(); assertTrue(jsonBody.has("status")); assertTrue(jsonBody.get("status").isJsonPrimitive()); assertEquals(jsonBody.get("status").getAsInt(), Match.WAITING_PLAYERS_WEAPONS); } catch (IOException ioe) { fail(); } finally { if (createMatch != null) createMatch.releaseConnection(); if (joinMatch != null) joinMatch.releaseConnection(); if (setWeapon != null) setWeapon.releaseConnection(); if (restartMatch != null) restartMatch.releaseConnection(); if (getMatchInfo != null) getMatchInfo.releaseConnection(); } }
public void shouldAllowToPlayAMatch() { HttpClient client1 = new HttpClient(); HttpClient client2 = new HttpClient(); PostMethod createMatch = null; PutMethod joinMatch = null; PutMethod setWeapon = null; PutMethod restartMatch = null; GetMethod getMatchInfo = null; String body; JsonObject jsonBody; String matchId; // Create a Match try { // First Player creates the match createMatch = new PostMethod(BASEURL + "/match"); createMatch.setParameter("kind", "pvp"); assertEquals(client1.executeMethod(createMatch), 200); // Extract Match ID from response body body = new String(createMatch.getResponseBody()); jsonBody = new JsonParser().parse(body).getAsJsonObject(); assertTrue(jsonBody.isJsonObject()); assertTrue(jsonBody.has("id")); assertTrue(jsonBody.get("id").isJsonPrimitive()); assertNotNull(jsonBody.get("id")); matchId = jsonBody.get("id").getAsString(); // First Player joins the match joinMatch = new PutMethod(BASEURL + "/match/" + matchId); joinMatch.setQueryString(new NameValuePair[] { new NameValuePair("action", "join")}); assertEquals(client1.executeMethod(joinMatch), 200); // Second Player joins the match assertEquals(client2.executeMethod(joinMatch), 200); // First and Second Player set the same weapon setWeapon = new PutMethod(BASEURL + "/match/" + matchId); setWeapon.setQueryString(new NameValuePair[] { new NameValuePair("action", "weapon"), new NameValuePair("weaponId", "1") }); assertEquals(client1.executeMethod(setWeapon), 200); assertEquals(client2.executeMethod(setWeapon), 200); // Check Match is has now been played getMatchInfo = new GetMethod(BASEURL + "/match/" + matchId); assertEquals(client1.executeMethod(getMatchInfo), 200); body = new String(getMatchInfo.getResponseBody()); jsonBody = new JsonParser().parse(body).getAsJsonObject(); // Extract the Match status assertTrue(jsonBody.has("status")); assertTrue(jsonBody.get("status").isJsonPrimitive()); assertEquals(jsonBody.get("status").getAsInt(), Match.PLAYED); // Extract the Match result assertTrue(jsonBody.has("result")); assertTrue(jsonBody.get("result").isJsonPrimitive()); assertEquals(jsonBody.get("result").getAsString(), "draw"); // Reset the Match restartMatch = new PutMethod(BASEURL + "/match/" + matchId); restartMatch.setQueryString(new NameValuePair[]{new NameValuePair("action", "restart")}); assertEquals(client2.executeMethod(restartMatch), 200); // Check Match is has now been reset getMatchInfo = new GetMethod(BASEURL + "/match/" + matchId); assertEquals(client2.executeMethod(getMatchInfo), 200); body = new String(getMatchInfo.getResponseBody()); // Extract the Match status jsonBody = new JsonParser().parse(body).getAsJsonObject(); assertTrue(jsonBody.has("status")); assertTrue(jsonBody.get("status").isJsonPrimitive()); assertEquals(jsonBody.get("status").getAsInt(), Match.WAITING_PLAYERS_WEAPONS); } catch (IOException ioe) { fail(); } finally { if (createMatch != null) createMatch.releaseConnection(); if (joinMatch != null) joinMatch.releaseConnection(); if (setWeapon != null) setWeapon.releaseConnection(); if (restartMatch != null) restartMatch.releaseConnection(); if (getMatchInfo != null) getMatchInfo.releaseConnection(); } }
diff --git a/src/VASSAL/chat/ui/SimpleStatusControlsInitializer.java b/src/VASSAL/chat/ui/SimpleStatusControlsInitializer.java index 2c35b3a4..b5ac6182 100644 --- a/src/VASSAL/chat/ui/SimpleStatusControlsInitializer.java +++ b/src/VASSAL/chat/ui/SimpleStatusControlsInitializer.java @@ -1,91 +1,91 @@ /* * * Copyright (c) 2000-2007 by Rodney Kinney * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License (LGPL) as published by the Free Software Foundation. * * 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, copies are available * at http://www.opensource.org. */ package VASSAL.chat.ui; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URL; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JOptionPane; import VASSAL.chat.ChatServerConnection; import VASSAL.chat.Player; import VASSAL.chat.SimplePlayer; import VASSAL.chat.SimpleStatus; import VASSAL.i18n.Resources; public class SimpleStatusControlsInitializer implements ChatControlsInitializer { private ChatServerConnection client; private JButton lookingBox; private JButton awayButton; public SimpleStatusControlsInitializer(ChatServerConnection client) { super(); this.client = client; } public void initializeControls(final ChatServerControls controls) { lookingBox = new JButton(Resources.getString("Chat.looking_for_a_game")); //$NON-NLS-1$ lookingBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { if (client != null) { Player p = client.getUserInfo(); SimpleStatus s = (SimpleStatus) p.getStatus(); - s = new SimpleStatus(!s.isLooking(),s.isAway(),s.getProfile()); + s = new SimpleStatus(!s.isLooking(),s.isAway(),s.getProfile(), s.getClient(), s.getIp(), s.getModuleVersion(), s.getCrc()); client.setUserInfo(new SimplePlayer(p.getId(),p.getName(),s)); } } }); lookingBox.setSize(lookingBox.getMinimumSize()); URL imageURL = getClass().getResource("/images/playerLooking.gif"); //$NON-NLS-1$ if (imageURL != null) { lookingBox.setToolTipText(lookingBox.getText()); lookingBox.setText(""); //$NON-NLS-1$ lookingBox.setIcon(new ImageIcon(imageURL)); } awayButton = new JButton(Resources.getString("Chat.away_from_keyboard")); //$NON-NLS-1$ awayButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { if (client != null) { Player p = client.getUserInfo(); SimpleStatus s = (SimpleStatus) p.getStatus(); - s = new SimpleStatus(s.isLooking(),true,s.getProfile()); + s = new SimpleStatus(s.isLooking(),true,s.getProfile(), s.getClient(), s.getIp(), s.getModuleVersion(), s.getCrc()); client.setUserInfo(new SimplePlayer(p.getId(),p.getName(),s)); JOptionPane.showMessageDialog(controls.getRoomTree(), Resources.getString("Chat.im_back"), Resources.getString("Chat.away_from_keyboard"), JOptionPane.PLAIN_MESSAGE); //$NON-NLS-1$ //$NON-NLS-2$ s = (SimpleStatus) p.getStatus(); - s = new SimpleStatus(s.isLooking(),false ,s.getProfile()); + s = new SimpleStatus(s.isLooking(),false ,s.getProfile(), s.getClient(), s.getIp(), s.getModuleVersion(), s.getCrc()); client.setUserInfo(new SimplePlayer(p.getId(),p.getName(),s)); } } }); imageURL = getClass().getResource("/images/playerAway.gif"); //$NON-NLS-1$ if (imageURL != null) { awayButton.setToolTipText(awayButton.getText()); awayButton.setText(""); //$NON-NLS-1$ awayButton.setIcon(new ImageIcon(imageURL)); } controls.getToolbar().add(lookingBox); controls.getToolbar().add(awayButton); } public void uninitializeControls(ChatServerControls controls) { controls.getToolbar().remove(lookingBox); controls.getToolbar().remove(awayButton); } }
false
true
public void initializeControls(final ChatServerControls controls) { lookingBox = new JButton(Resources.getString("Chat.looking_for_a_game")); //$NON-NLS-1$ lookingBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { if (client != null) { Player p = client.getUserInfo(); SimpleStatus s = (SimpleStatus) p.getStatus(); s = new SimpleStatus(!s.isLooking(),s.isAway(),s.getProfile()); client.setUserInfo(new SimplePlayer(p.getId(),p.getName(),s)); } } }); lookingBox.setSize(lookingBox.getMinimumSize()); URL imageURL = getClass().getResource("/images/playerLooking.gif"); //$NON-NLS-1$ if (imageURL != null) { lookingBox.setToolTipText(lookingBox.getText()); lookingBox.setText(""); //$NON-NLS-1$ lookingBox.setIcon(new ImageIcon(imageURL)); } awayButton = new JButton(Resources.getString("Chat.away_from_keyboard")); //$NON-NLS-1$ awayButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { if (client != null) { Player p = client.getUserInfo(); SimpleStatus s = (SimpleStatus) p.getStatus(); s = new SimpleStatus(s.isLooking(),true,s.getProfile()); client.setUserInfo(new SimplePlayer(p.getId(),p.getName(),s)); JOptionPane.showMessageDialog(controls.getRoomTree(), Resources.getString("Chat.im_back"), Resources.getString("Chat.away_from_keyboard"), JOptionPane.PLAIN_MESSAGE); //$NON-NLS-1$ //$NON-NLS-2$ s = (SimpleStatus) p.getStatus(); s = new SimpleStatus(s.isLooking(),false ,s.getProfile()); client.setUserInfo(new SimplePlayer(p.getId(),p.getName(),s)); } } }); imageURL = getClass().getResource("/images/playerAway.gif"); //$NON-NLS-1$ if (imageURL != null) { awayButton.setToolTipText(awayButton.getText()); awayButton.setText(""); //$NON-NLS-1$ awayButton.setIcon(new ImageIcon(imageURL)); } controls.getToolbar().add(lookingBox); controls.getToolbar().add(awayButton); }
public void initializeControls(final ChatServerControls controls) { lookingBox = new JButton(Resources.getString("Chat.looking_for_a_game")); //$NON-NLS-1$ lookingBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { if (client != null) { Player p = client.getUserInfo(); SimpleStatus s = (SimpleStatus) p.getStatus(); s = new SimpleStatus(!s.isLooking(),s.isAway(),s.getProfile(), s.getClient(), s.getIp(), s.getModuleVersion(), s.getCrc()); client.setUserInfo(new SimplePlayer(p.getId(),p.getName(),s)); } } }); lookingBox.setSize(lookingBox.getMinimumSize()); URL imageURL = getClass().getResource("/images/playerLooking.gif"); //$NON-NLS-1$ if (imageURL != null) { lookingBox.setToolTipText(lookingBox.getText()); lookingBox.setText(""); //$NON-NLS-1$ lookingBox.setIcon(new ImageIcon(imageURL)); } awayButton = new JButton(Resources.getString("Chat.away_from_keyboard")); //$NON-NLS-1$ awayButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { if (client != null) { Player p = client.getUserInfo(); SimpleStatus s = (SimpleStatus) p.getStatus(); s = new SimpleStatus(s.isLooking(),true,s.getProfile(), s.getClient(), s.getIp(), s.getModuleVersion(), s.getCrc()); client.setUserInfo(new SimplePlayer(p.getId(),p.getName(),s)); JOptionPane.showMessageDialog(controls.getRoomTree(), Resources.getString("Chat.im_back"), Resources.getString("Chat.away_from_keyboard"), JOptionPane.PLAIN_MESSAGE); //$NON-NLS-1$ //$NON-NLS-2$ s = (SimpleStatus) p.getStatus(); s = new SimpleStatus(s.isLooking(),false ,s.getProfile(), s.getClient(), s.getIp(), s.getModuleVersion(), s.getCrc()); client.setUserInfo(new SimplePlayer(p.getId(),p.getName(),s)); } } }); imageURL = getClass().getResource("/images/playerAway.gif"); //$NON-NLS-1$ if (imageURL != null) { awayButton.setToolTipText(awayButton.getText()); awayButton.setText(""); //$NON-NLS-1$ awayButton.setIcon(new ImageIcon(imageURL)); } controls.getToolbar().add(lookingBox); controls.getToolbar().add(awayButton); }
diff --git a/packetcable/src/main/java/org/opendaylight/controller/protocol_plugin/packetcable/internal/FlowConverter.java b/packetcable/src/main/java/org/opendaylight/controller/protocol_plugin/packetcable/internal/FlowConverter.java index 49b7872..a5d9da6 100644 --- a/packetcable/src/main/java/org/opendaylight/controller/protocol_plugin/packetcable/internal/FlowConverter.java +++ b/packetcable/src/main/java/org/opendaylight/controller/protocol_plugin/packetcable/internal/FlowConverter.java @@ -1,1005 +1,1007 @@ /* @header@ */ package org.opendaylight.controller.protocol_plugin.packetcable.internal; import java.math.BigInteger; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.opendaylight.controller.sal.action.Action; import org.opendaylight.controller.sal.action.ActionType; import org.opendaylight.controller.sal.action.Controller; import org.opendaylight.controller.sal.action.Drop; import org.opendaylight.controller.sal.action.Flood; import org.opendaylight.controller.sal.action.FloodAll; import org.opendaylight.controller.sal.action.HwPath; import org.opendaylight.controller.sal.action.Loopback; import org.opendaylight.controller.sal.action.Output; import org.opendaylight.controller.sal.action.PopVlan; import org.opendaylight.controller.sal.action.SetDlDst; import org.opendaylight.controller.sal.action.SetDlSrc; import org.opendaylight.controller.sal.action.SetNwDst; import org.opendaylight.controller.sal.action.SetNwSrc; import org.opendaylight.controller.sal.action.SetNwTos; import org.opendaylight.controller.sal.action.SetTpDst; import org.opendaylight.controller.sal.action.SetTpSrc; import org.opendaylight.controller.sal.action.SetVlanId; import org.opendaylight.controller.sal.action.SetVlanPcp; import org.opendaylight.controller.sal.action.SwPath; import org.opendaylight.controller.sal.core.Node; import org.opendaylight.controller.sal.core.NodeConnector; import org.opendaylight.controller.sal.flowprogrammer.Flow; import org.opendaylight.controller.sal.match.Match; import org.opendaylight.controller.sal.match.MatchField; import org.opendaylight.controller.sal.match.MatchType; import org.opendaylight.controller.sal.utils.NetUtils; import org.opendaylight.controller.sal.utils.NodeConnectorCreator; /** import org.opendaylight.controller.protocol_plugin.openflow.vendorextension.v6extension.V6FlowMod; import org.opendaylight.controller.protocol_plugin.openflow.vendorextension.v6extension.V6Match; import org.openflow.protocol.OFFlowMod; import org.openflow.protocol.OFMatch; import org.openflow.protocol.OFMessage; import org.openflow.protocol.OFPacketOut; import org.openflow.protocol.OFPort; import org.openflow.protocol.OFVendor; import org.openflow.protocol.action.OFAction; import org.openflow.protocol.action.OFActionDataLayer; import org.openflow.protocol.action.OFActionDataLayerDestination; import org.openflow.protocol.action.OFActionDataLayerSource; import org.openflow.protocol.action.OFActionNetworkLayerAddress; import org.openflow.protocol.action.OFActionNetworkLayerDestination; import org.openflow.protocol.action.OFActionNetworkLayerSource; import org.openflow.protocol.action.OFActionNetworkTypeOfService; import org.openflow.protocol.action.OFActionOutput; import org.openflow.protocol.action.OFActionStripVirtualLan; import org.openflow.protocol.action.OFActionTransportLayer; import org.openflow.protocol.action.OFActionTransportLayerDestination; import org.openflow.protocol.action.OFActionTransportLayerSource; import org.openflow.protocol.action.OFActionVirtualLanIdentifier; import org.openflow.protocol.action.OFActionVirtualLanPriorityCodePoint; import org.openflow.util.U16; import org.openflow.util.U32; */ import org.pcmm.PCMMGlobalConfig; import org.pcmm.gates.IAMID; import org.pcmm.gates.IClassifier; import org.pcmm.gates.IExtendedClassifier; import org.pcmm.gates.IGateSpec; import org.pcmm.gates.IGateSpec.DSCPTOS; import org.pcmm.gates.IGateSpec.Direction; import org.pcmm.gates.IPCMMGate; import org.pcmm.gates.ISubscriberID; import org.pcmm.gates.ITrafficProfile; import org.pcmm.gates.ITransactionID; import org.pcmm.gates.IGateID; import org.pcmm.gates.impl.GateID; import org.pcmm.gates.impl.AMID; import org.pcmm.gates.impl.BestEffortService; import org.pcmm.gates.impl.Classifier; import org.pcmm.gates.impl.ExtendedClassifier; import org.pcmm.gates.impl.DOCSISServiceClassNameTrafficProfile; import org.pcmm.gates.impl.GateSpec; import org.pcmm.gates.impl.PCMMGateReq; import org.pcmm.gates.impl.SubscriberID; import org.pcmm.gates.impl.TransactionID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Utility class for converting a SAL Flow into the PCMM service flow and vice-versa */ public class FlowConverter { protected static final Logger logger = LoggerFactory .getLogger(FlowConverter.class); /* * The value 0xffff (OFP_VLAN_NONE) is used to indicate * that no VLAN ID is set for OF Flow. */ private static final short OFP_VLAN_NONE = (short) 0xffff; private Flow flow; // SAL Flow // private OFMatch ofMatch; // OF 1.0 match or OF 1.0 + IPv6 extension match // private List<OFAction> actionsList; // OF 1.0 actions private int actionsLength; private boolean isIPv6; /* public FlowConverter(OFMatch ofMatch, List<OFAction> actionsList) { // this.ofMatch = ofMatch; this.actionsList = actionsList; this.actionsLength = 0; this.flow = null; // this.isIPv6 = ofMatch instanceof V6Match; } */ public FlowConverter(Flow flow) { // this.ofMatch = null; // this.actionsList = null; this.actionsLength = 0; this.flow = flow; this.isIPv6 = flow.isIPv6(); } // public void dump(Flow flow) { public void dump() { logger.info("SAL Flow IPv6 : {}", flow.isIPv6()); logger.info("SAL Flow Actions : {}", flow.getActions()); logger.info("SAL Flow Priority: {}", flow.getPriority()); logger.info("SAL Flow Id: {}", flow.getId()); logger.info("SAL Flow Idle Timeout: {}", flow.getIdleTimeout()); logger.info("SAL Flow Hard Timeout: {}", flow.getHardTimeout()); } public void dumpAction() { logger.info("SAL Flow Actions:"); Iterator<Action> actionIter = flow.getActions().iterator(); while (actionIter.hasNext()) { Action action = actionIter.next(); switch (action.getType()) { case DROP: logger.info("drop"); break; case LOOPBACK: logger.info("loopback"); break; case FLOOD: logger.info("flood"); break; case FLOOD_ALL: logger.info("floodAll"); break; case CONTROLLER: logger.info("controller"); break; case INTERFACE: logger.info("interface"); break; case SW_PATH: logger.info("software path"); break; case HW_PATH: logger.info("harware path"); break; case OUTPUT: logger.info("output"); break; case ENQUEUE: logger.info("enqueue"); break; case SET_DL_SRC: logger.info("setDlSrc"); break; case SET_DL_DST: logger.info("setDlDst"); break; case SET_VLAN_ID: logger.info("setVlan"); break; case SET_VLAN_PCP: logger.info("setVlanPcp"); break; case SET_VLAN_CFI: logger.info("setVlanCif"); break; case POP_VLAN: logger.info("stripVlan"); break; case PUSH_VLAN: logger.info("pushVlan"); break; case SET_DL_TYPE: logger.info("setDlType"); break; case SET_NW_SRC: logger.info("setNwSrc"); break; case SET_NW_DST: logger.info("setNwDst"); break; case SET_NW_TOS: logger.info("setNwTos"); break; case SET_TP_SRC: logger.info("setTpSrc"); break; case SET_TP_DST: logger.info("setTpDst"); break; case SET_NEXT_HOP: logger.info("setNextHop"); break; default: logger.info("Unknown"); break; } } } /** * Returns the match in Gate Control message * * @return */ // public OFMatch getOFMatch() { public IPCMMGate getServiceFlow() { IPCMMGate gate = new PCMMGateReq(); // ITransactionID trID = new TransactionID(); IAMID amid = new AMID(); ISubscriberID subscriberID = new SubscriberID(); IGateSpec gateSpec = new GateSpec(); IClassifier classifier = new Classifier(); IExtendedClassifier eclassifier = new ExtendedClassifier(); InetAddress defaultmask = null; /* Constrain priority to 64 to 128 as per spec */ byte pri = (byte) (flow.getPriority() & 0xFFFF); if ((pri < 64) || (pri > 128)) eclassifier.setPriority((byte) 64); else eclassifier.setPriority(pri); int TrafficRate = 0; if (pri == 100) TrafficRate = PCMMGlobalConfig.DefaultBestEffortTrafficRate; else TrafficRate = PCMMGlobalConfig.DefaultLowBestEffortTrafficRate; logger.info("FlowConverter Flow Id: {}", flow.getId()); logger.info("FlowConverter Priority: {}",pri); logger.info("FlowConverter Traffic Rate: {}",TrafficRate); ITrafficProfile trafficProfile = new BestEffortService( (byte) 7); //BestEffortService.DEFAULT_ENVELOP); ((BestEffortService) trafficProfile).getAuthorizedEnvelop() .setTrafficPriority(BestEffortService.DEFAULT_TRAFFIC_PRIORITY); ((BestEffortService) trafficProfile).getAuthorizedEnvelop() .setMaximumTrafficBurst( BestEffortService.DEFAULT_MAX_TRAFFIC_BURST); ((BestEffortService) trafficProfile).getAuthorizedEnvelop() .setRequestTransmissionPolicy( PCMMGlobalConfig.BETransmissionPolicy); ((BestEffortService) trafficProfile).getAuthorizedEnvelop() .setMaximumSustainedTrafficRate( TrafficRate); ((BestEffortService) trafficProfile).getReservedEnvelop() .setTrafficPriority(BestEffortService.DEFAULT_TRAFFIC_PRIORITY); ((BestEffortService) trafficProfile).getReservedEnvelop() .setMaximumTrafficBurst( BestEffortService.DEFAULT_MAX_TRAFFIC_BURST); ((BestEffortService) trafficProfile).getReservedEnvelop() .setRequestTransmissionPolicy( PCMMGlobalConfig.BETransmissionPolicy); ((BestEffortService) trafficProfile).getReservedEnvelop() .setMaximumSustainedTrafficRate( TrafficRate); ((BestEffortService) trafficProfile).getCommittedEnvelop() .setTrafficPriority(BestEffortService.DEFAULT_TRAFFIC_PRIORITY); ((BestEffortService) trafficProfile).getCommittedEnvelop() .setMaximumTrafficBurst( BestEffortService.DEFAULT_MAX_TRAFFIC_BURST); ((BestEffortService) trafficProfile).getCommittedEnvelop() .setRequestTransmissionPolicy( PCMMGlobalConfig.BETransmissionPolicy); ((BestEffortService) trafficProfile).getCommittedEnvelop() .setMaximumSustainedTrafficRate( TrafficRate); amid.setApplicationType((short) 1); amid.setApplicationMgrTag((short) 1); gateSpec.setDirection(Direction.UPSTREAM); gateSpec.setDSCP_TOSOverwrite(DSCPTOS.OVERRIDE); gateSpec.setTimerT1(PCMMGlobalConfig.GateT1); gateSpec.setTimerT2(PCMMGlobalConfig.GateT2); gateSpec.setTimerT3(PCMMGlobalConfig.GateT3); gateSpec.setTimerT4(PCMMGlobalConfig.GateT4); try { InetAddress subIP = InetAddress .getByName(PCMMGlobalConfig.SubscriberID); subscriberID.setSourceIPAddress(subIP); } catch (UnknownHostException unae) { logger.error("Error getByName" + unae.getMessage()); } Match match = flow.getMatch(); if (match.isPresent(MatchType.IN_PORT)) { short port = (Short) ((NodeConnector) match.getField( MatchType.IN_PORT).getValue()).getID(); if (!isIPv6) { logger.info("Flow : In Port: {}", port); } else { logger.info("Flow V6 : In Port: {}", port); } } if (match.isPresent(MatchType.DL_SRC)) { byte[] srcMac = (byte[]) match.getField(MatchType.DL_SRC) .getValue(); if (!isIPv6) { logger.info("Flow : Data Layer Src MAC: {}", srcMac); } else { logger.info("Flow V6 : Data Layer Src MAC: {}", srcMac); } } if (match.isPresent(MatchType.DL_DST)) { byte[] dstMac = (byte[]) match.getField(MatchType.DL_DST) .getValue(); if (!isIPv6) { logger.info("Flow : Data Layer Dst MAC: {}", dstMac); } else { logger.info("Flow V6 : Data Layer Dst MAC: {}", dstMac); } } if (match.isPresent(MatchType.DL_VLAN)) { short vlan = (Short) match.getField(MatchType.DL_VLAN) .getValue(); if (vlan == MatchType.DL_VLAN_NONE) { vlan = OFP_VLAN_NONE; } if (!isIPv6) { logger.info("Flow : Data Layer Vlan: {}", vlan); } else { logger.info("Flow V6 : Data Layer Vlan: {}", vlan); } } if (match.isPresent(MatchType.DL_VLAN_PR)) { byte vlanPr = (Byte) match.getField(MatchType.DL_VLAN_PR) .getValue(); if (!isIPv6) { logger.info("Flow : Data Layer Vlan Priority: {}", vlanPr); } else { logger.info("Flow : Data Layer Vlan Priority: {}", vlanPr); } } if (match.isPresent(MatchType.DL_TYPE)) { short ethType = (Short) match.getField(MatchType.DL_TYPE) .getValue(); if (!isIPv6) { logger.info("Flow : Data Layer Eth Type: {}", ethType); } else { logger.info("Flow V6: Data Layer Eth Type: {}", ethType); } } if (match.isPresent(MatchType.NW_TOS)) { byte tos = (Byte) match.getField(MatchType.NW_TOS).getValue(); byte dscp = (byte) (tos << 2); if (!isIPv6) { logger.info("Flow : Network TOS : {}", tos); logger.info("Flow : Network DSCP : {}", dscp); // XXX - hook me up gateSpec.setDSCP_TOSOverwrite(DSCPTOS.OVERRIDE); } else { logger.info("Flow V6 : Network TOS : {}", tos); logger.info("Flow V6 : Network DSCP : {}", dscp); } } if (match.isPresent(MatchType.NW_PROTO)) { byte proto = (Byte) match.getField(MatchType.NW_PROTO) .getValue(); if (!isIPv6) { logger.info("Flow : Network Protocol : {}", proto); switch (proto) { case 6: - classifier.setProtocol(IClassifier.Protocol.TCP); + eclassifier.setProtocol(IClassifier.Protocol.TCP); break; case 17: - classifier.setProtocol(IClassifier.Protocol.UDP); + eclassifier.setProtocol(IClassifier.Protocol.UDP); break; case 0: default: - classifier.setProtocol(IClassifier.Protocol.NONE); + eclassifier.setProtocol(IClassifier.Protocol.NONE); break; } } else { logger.info("Flow V6 : Network Protocol : {}", proto); } } if (match.isPresent(MatchType.NW_SRC)) { InetAddress address = (InetAddress) match.getField(MatchType.NW_SRC).getValue(); InetAddress mask = (InetAddress) match.getField(MatchType.NW_SRC).getMask(); try { defaultmask = InetAddress.getByName("0.0.0.0"); } catch (UnknownHostException unae) { System.out.println("Error getByName" + unae.getMessage()); } if (!isIPv6) { int maskLength = (mask == null) ? 32 : NetUtils.getSubnetMaskLength(mask); logger.info("Flow : Network Address Src : {} Mask : {}", address, mask); eclassifier.setSourceIPAddress(address); if (mask == null) eclassifier.setIPSourceMask(defaultmask); else eclassifier.setIPSourceMask(mask); + //eclassifier.setIPSourceMask(defaultmask); } else { logger.info("Flow V6 : Network Address Src : {} Mask : {}", address, mask); } } if (match.isPresent(MatchType.NW_DST)) { InetAddress address = (InetAddress) match.getField(MatchType.NW_DST).getValue(); InetAddress mask = (InetAddress) match.getField(MatchType.NW_DST).getMask(); // InetAddress defaultmask; try { defaultmask = InetAddress.getByName("0.0.0.0"); } catch (UnknownHostException unae) { System.out.println("Error getByName" + unae.getMessage()); } if (!isIPv6) { int maskLength = (mask == null) ? 32 : NetUtils.getSubnetMaskLength(mask); logger.info("Flow : Network Address Dst : {} Mask : {}", address, mask); eclassifier.setDestinationIPAddress(address); if (mask == null) eclassifier.setIPDestinationMask(defaultmask); else eclassifier.setIPDestinationMask(mask); + //eclassifier.setIPDestinationMask(defaultmask); } else { logger.info("Flow V6 : Network Address Dst : {} Mask : {}", address, mask); } } if (match.isPresent(MatchType.TP_SRC)) { short port = (Short) match.getField(MatchType.TP_SRC) .getValue(); if (!isIPv6) { logger.info("Flow : Network Transport Port Src : {} ", port); eclassifier.setSourcePortStart(port); eclassifier.setSourcePortEnd(port); } else { logger.info("Flow V6 : Network Transport Port Src : {} ", port); } } if (match.isPresent(MatchType.TP_DST)) { short port = (Short) match.getField(MatchType.TP_DST) .getValue(); if (!isIPv6) { logger.info("Flow : Network Transport Port Dst : {} ", port); eclassifier.setDestinationPortStart(port); eclassifier.setDestinationPortEnd(port); } else { logger.info("Flow V6: Network Transport Port Dst : {} ", port); } } if (!isIPv6) { } logger.info("SAL Match: {} ", flow.getMatch()); eclassifier.setClassifierID((short) 0x01); /* eclassifier.setClassifierID((short) (_classifierID == 0 ? Math .random() * hashCode() : _classifierID)); */ eclassifier.setAction((byte) 0x00); eclassifier.setActivationState((byte) 0x01); //gate.setTransactionID(trID); gate.setAMID(amid); gate.setSubscriberID(subscriberID); gate.setGateSpec(gateSpec); gate.setTrafficProfile(trafficProfile); gate.setClassifier(eclassifier); return gate; } /** * Returns the list of actions in OF 1.0 form * * @return public List<OFAction> getOFActions() { if (this.actionsList == null) { actionsList = new ArrayList<OFAction>(); for (Action action : flow.getActions()) { if (action.getType() == ActionType.OUTPUT) { Output a = (Output) action; OFActionOutput ofAction = new OFActionOutput(); ofAction.setMaxLength((short) 0xffff); ofAction.setPort(PortConverter.toOFPort(a.getPort())); actionsList.add(ofAction); actionsLength += OFActionOutput.MINIMUM_LENGTH; continue; } if (action.getType() == ActionType.DROP) { continue; } if (action.getType() == ActionType.LOOPBACK) { OFActionOutput ofAction = new OFActionOutput(); ofAction.setPort(OFPort.OFPP_IN_PORT.getValue()); actionsList.add(ofAction); actionsLength += OFActionOutput.MINIMUM_LENGTH; continue; } if (action.getType() == ActionType.FLOOD) { OFActionOutput ofAction = new OFActionOutput(); ofAction.setPort(OFPort.OFPP_FLOOD.getValue()); actionsList.add(ofAction); actionsLength += OFActionOutput.MINIMUM_LENGTH; continue; } if (action.getType() == ActionType.FLOOD_ALL) { OFActionOutput ofAction = new OFActionOutput(); ofAction.setPort(OFPort.OFPP_ALL.getValue()); actionsList.add(ofAction); actionsLength += OFActionOutput.MINIMUM_LENGTH; continue; } if (action.getType() == ActionType.CONTROLLER) { OFActionOutput ofAction = new OFActionOutput(); ofAction.setPort(OFPort.OFPP_CONTROLLER.getValue()); // We want the whole frame hitting the match be sent to the // controller ofAction.setMaxLength((short) 0xffff); actionsList.add(ofAction); actionsLength += OFActionOutput.MINIMUM_LENGTH; continue; } if (action.getType() == ActionType.SW_PATH) { OFActionOutput ofAction = new OFActionOutput(); ofAction.setPort(OFPort.OFPP_LOCAL.getValue()); actionsList.add(ofAction); actionsLength += OFActionOutput.MINIMUM_LENGTH; continue; } if (action.getType() == ActionType.HW_PATH) { OFActionOutput ofAction = new OFActionOutput(); ofAction.setPort(OFPort.OFPP_NORMAL.getValue()); actionsList.add(ofAction); actionsLength += OFActionOutput.MINIMUM_LENGTH; continue; } if (action.getType() == ActionType.SET_VLAN_ID) { SetVlanId a = (SetVlanId) action; OFActionVirtualLanIdentifier ofAction = new OFActionVirtualLanIdentifier(); ofAction.setVirtualLanIdentifier((short) a.getVlanId()); actionsList.add(ofAction); actionsLength += OFActionVirtualLanIdentifier.MINIMUM_LENGTH; continue; } if (action.getType() == ActionType.SET_VLAN_PCP) { SetVlanPcp a = (SetVlanPcp) action; OFActionVirtualLanPriorityCodePoint ofAction = new OFActionVirtualLanPriorityCodePoint(); ofAction.setVirtualLanPriorityCodePoint(Integer.valueOf( a.getPcp()).byteValue()); actionsList.add(ofAction); actionsLength += OFActionVirtualLanPriorityCodePoint.MINIMUM_LENGTH; continue; } if (action.getType() == ActionType.POP_VLAN) { OFActionStripVirtualLan ofAction = new OFActionStripVirtualLan(); actionsList.add(ofAction); actionsLength += OFActionStripVirtualLan.MINIMUM_LENGTH; continue; } if (action.getType() == ActionType.SET_DL_SRC) { SetDlSrc a = (SetDlSrc) action; OFActionDataLayerSource ofAction = new OFActionDataLayerSource(); ofAction.setDataLayerAddress(a.getDlAddress()); actionsList.add(ofAction); actionsLength += OFActionDataLayer.MINIMUM_LENGTH; continue; } if (action.getType() == ActionType.SET_DL_DST) { SetDlDst a = (SetDlDst) action; OFActionDataLayerDestination ofAction = new OFActionDataLayerDestination(); ofAction.setDataLayerAddress(a.getDlAddress()); actionsList.add(ofAction); actionsLength += OFActionDataLayer.MINIMUM_LENGTH; continue; } if (action.getType() == ActionType.SET_NW_SRC) { SetNwSrc a = (SetNwSrc) action; OFActionNetworkLayerSource ofAction = new OFActionNetworkLayerSource(); ofAction.setNetworkAddress(NetUtils.byteArray4ToInt(a .getAddress().getAddress())); actionsList.add(ofAction); actionsLength += OFActionNetworkLayerAddress.MINIMUM_LENGTH; continue; } if (action.getType() == ActionType.SET_NW_DST) { SetNwDst a = (SetNwDst) action; OFActionNetworkLayerDestination ofAction = new OFActionNetworkLayerDestination(); ofAction.setNetworkAddress(NetUtils.byteArray4ToInt(a .getAddress().getAddress())); actionsList.add(ofAction); actionsLength += OFActionNetworkLayerAddress.MINIMUM_LENGTH; continue; } if (action.getType() == ActionType.SET_NW_TOS) { SetNwTos a = (SetNwTos) action; OFActionNetworkTypeOfService ofAction = new OFActionNetworkTypeOfService(); ofAction.setNetworkTypeOfService(Integer.valueOf( a.getNwTos()).byteValue()); actionsList.add(ofAction); actionsLength += OFActionNetworkTypeOfService.MINIMUM_LENGTH; continue; } if (action.getType() == ActionType.SET_TP_SRC) { SetTpSrc a = (SetTpSrc) action; OFActionTransportLayerSource ofAction = new OFActionTransportLayerSource(); ofAction.setTransportPort(Integer.valueOf(a.getPort()) .shortValue()); actionsList.add(ofAction); actionsLength += OFActionTransportLayer.MINIMUM_LENGTH; continue; } if (action.getType() == ActionType.SET_TP_DST) { SetTpDst a = (SetTpDst) action; OFActionTransportLayerDestination ofAction = new OFActionTransportLayerDestination(); ofAction.setTransportPort(Integer.valueOf(a.getPort()) .shortValue()); actionsList.add(ofAction); actionsLength += OFActionTransportLayer.MINIMUM_LENGTH; continue; } if (action.getType() == ActionType.SET_NEXT_HOP) { logger.info("Unsupported action: {}", action); continue; } } } logger.info("SAL Actions: {} Openflow Actions: {}", flow.getActions(), actionsList); return actionsList; } */ /** * Utility to convert a SAL flow to an OF 1.0 (OFFlowMod) or to an OF 1.0 + * IPv6 extension (V6FlowMod) Flow modifier Message * * @param sw * @param command * @param port * @return public OFMessage getOFFlowMod(short command, OFPort port) { OFMessage fm = (isIPv6) ? new V6FlowMod() : new OFFlowMod(); if (this.ofMatch == null) { getOFMatch(); } if (this.actionsList == null) { getOFActions(); } if (!isIPv6) { ((OFFlowMod) fm).setMatch(this.ofMatch); ((OFFlowMod) fm).setActions(this.actionsList); ((OFFlowMod) fm).setPriority(flow.getPriority()); ((OFFlowMod) fm).setCookie(flow.getId()); ((OFFlowMod) fm).setBufferId(OFPacketOut.BUFFER_ID_NONE); ((OFFlowMod) fm).setLength(U16.t(OFFlowMod.MINIMUM_LENGTH + actionsLength)); ((OFFlowMod) fm).setIdleTimeout(flow.getIdleTimeout()); ((OFFlowMod) fm).setHardTimeout(flow.getHardTimeout()); ((OFFlowMod) fm).setCommand(command); if (port != null) { ((OFFlowMod) fm).setOutPort(port); } if (command == OFFlowMod.OFPFC_ADD || command == OFFlowMod.OFPFC_MODIFY || command == OFFlowMod.OFPFC_MODIFY_STRICT) { if (flow.getIdleTimeout() != 0 || flow.getHardTimeout() != 0) { // Instruct switch to let controller know when flow expires ((OFFlowMod) fm).setFlags((short) 1); } } } else { ((V6FlowMod) fm).setVendor(); ((V6FlowMod) fm).setMatch((V6Match) ofMatch); ((V6FlowMod) fm).setActions(this.actionsList); ((V6FlowMod) fm).setPriority(flow.getPriority()); ((V6FlowMod) fm).setCookie(flow.getId()); ((V6FlowMod) fm).setLength(U16.t(OFVendor.MINIMUM_LENGTH + ((V6Match) ofMatch).getIPv6ExtMinHdrLen() + ((V6Match) ofMatch).getIPv6MatchLen() + ((V6Match) ofMatch).getPadSize() + actionsLength)); ((V6FlowMod) fm).setIdleTimeout(flow.getIdleTimeout()); ((V6FlowMod) fm).setHardTimeout(flow.getHardTimeout()); ((V6FlowMod) fm).setCommand(command); if (port != null) { ((V6FlowMod) fm).setOutPort(port); } if (command == OFFlowMod.OFPFC_ADD || command == OFFlowMod.OFPFC_MODIFY || command == OFFlowMod.OFPFC_MODIFY_STRICT) { if (flow.getIdleTimeout() != 0 || flow.getHardTimeout() != 0) { // Instruct switch to let controller know when flow expires ((V6FlowMod) fm).setFlags((short) 1); } } } logger.info("Openflow Match: {} Openflow Actions: {}", ofMatch, actionsList); logger.info("Openflow Mod Message: {}", fm); return fm; } */ /* * Installed flow may not have a Match defined like in case of a * drop all flow public Flow getFlow(Node node) { if (this.flow == null) { Match salMatch = new Match(); if (ofMatch != null) { if (!isIPv6) { // Compute OF1.0 Match if (ofMatch.getInputPort() != 0 && ofMatch.getInputPort() != OFPort.OFPP_LOCAL.getValue()) { salMatch.setField(new MatchField(MatchType.IN_PORT, NodeConnectorCreator.createNodeConnector( ofMatch.getInputPort(), node))); } if (ofMatch.getDataLayerSource() != null && !NetUtils .isZeroMAC(ofMatch.getDataLayerSource())) { byte srcMac[] = ofMatch.getDataLayerSource(); salMatch.setField(new MatchField(MatchType.DL_SRC, srcMac.clone())); } if (ofMatch.getDataLayerDestination() != null && !NetUtils.isZeroMAC(ofMatch .getDataLayerDestination())) { byte dstMac[] = ofMatch.getDataLayerDestination(); salMatch.setField(new MatchField(MatchType.DL_DST, dstMac.clone())); } if (ofMatch.getDataLayerType() != 0) { salMatch.setField(new MatchField(MatchType.DL_TYPE, ofMatch.getDataLayerType())); } short vlan = ofMatch.getDataLayerVirtualLan(); if (vlan != 0) { if (vlan == OFP_VLAN_NONE) { vlan = MatchType.DL_VLAN_NONE; } salMatch.setField(new MatchField(MatchType.DL_VLAN, vlan)); } if (ofMatch.getDataLayerVirtualLanPriorityCodePoint() != 0) { salMatch.setField(MatchType.DL_VLAN_PR, ofMatch .getDataLayerVirtualLanPriorityCodePoint()); } if (ofMatch.getNetworkSource() != 0) { salMatch.setField(MatchType.NW_SRC, NetUtils .getInetAddress(ofMatch.getNetworkSource()), NetUtils.getInetNetworkMask( ofMatch.getNetworkSourceMaskLen(), false)); } if (ofMatch.getNetworkDestination() != 0) { salMatch.setField(MatchType.NW_DST, NetUtils.getInetAddress(ofMatch .getNetworkDestination()), NetUtils.getInetNetworkMask( ofMatch.getNetworkDestinationMaskLen(), false)); } if (ofMatch.getNetworkTypeOfService() != 0) { int dscp = NetUtils.getUnsignedByte(ofMatch .getNetworkTypeOfService()); byte tos = (byte) (dscp >> 2); salMatch.setField(MatchType.NW_TOS, tos); } if (ofMatch.getNetworkProtocol() != 0) { salMatch.setField(MatchType.NW_PROTO, ofMatch.getNetworkProtocol()); } if (ofMatch.getTransportSource() != 0) { salMatch.setField(MatchType.TP_SRC, ofMatch.getTransportSource()); } if (ofMatch.getTransportDestination() != 0) { salMatch.setField(MatchType.TP_DST, ofMatch.getTransportDestination()); } } else { // Compute OF1.0 + IPv6 extensions Match V6Match v6Match = (V6Match) ofMatch; if (v6Match.getInputPort() != 0 && v6Match.getInputPort() != OFPort.OFPP_LOCAL.getValue()) { // Mask on input port is not defined salMatch.setField(new MatchField(MatchType.IN_PORT, NodeConnectorCreator.createOFNodeConnector( v6Match.getInputPort(), node))); } if (v6Match.getDataLayerSource() != null && !NetUtils .isZeroMAC(ofMatch.getDataLayerSource())) { byte srcMac[] = v6Match.getDataLayerSource(); salMatch.setField(new MatchField(MatchType.DL_SRC, srcMac.clone())); } if (v6Match.getDataLayerDestination() != null && !NetUtils.isZeroMAC(ofMatch .getDataLayerDestination())) { byte dstMac[] = v6Match.getDataLayerDestination(); salMatch.setField(new MatchField(MatchType.DL_DST, dstMac.clone())); } if (v6Match.getDataLayerType() != 0) { salMatch.setField(new MatchField(MatchType.DL_TYPE, v6Match.getDataLayerType())); } short vlan = v6Match.getDataLayerVirtualLan(); if (vlan != 0) { if (vlan == OFP_VLAN_NONE) { vlan = MatchType.DL_VLAN_NONE; } salMatch.setField(new MatchField(MatchType.DL_VLAN, vlan)); } if (v6Match.getDataLayerVirtualLanPriorityCodePoint() != 0) { salMatch.setField(MatchType.DL_VLAN_PR, v6Match .getDataLayerVirtualLanPriorityCodePoint()); } // V6Match may carry IPv4 address if (v6Match.getNetworkSrc() != null) { salMatch.setField(MatchType.NW_SRC, v6Match.getNetworkSrc(), v6Match.getNetworkSourceMask()); } else if (v6Match.getNetworkSource() != 0) { salMatch.setField(MatchType.NW_SRC, NetUtils .getInetAddress(v6Match.getNetworkSource()), NetUtils.getInetNetworkMask( v6Match.getNetworkSourceMaskLen(), false)); } // V6Match may carry IPv4 address if (v6Match.getNetworkDest() != null) { salMatch.setField(MatchType.NW_DST, v6Match.getNetworkDest(), v6Match.getNetworkDestinationMask()); } else if (v6Match.getNetworkDestination() != 0) { salMatch.setField(MatchType.NW_DST, NetUtils.getInetAddress(v6Match .getNetworkDestination()), NetUtils.getInetNetworkMask( v6Match.getNetworkDestinationMaskLen(), false)); } if (v6Match.getNetworkTypeOfService() != 0) { int dscp = NetUtils.getUnsignedByte(v6Match .getNetworkTypeOfService()); byte tos = (byte) (dscp >> 2); salMatch.setField(MatchType.NW_TOS, tos); } if (v6Match.getNetworkProtocol() != 0) { salMatch.setField(MatchType.NW_PROTO, v6Match.getNetworkProtocol()); } if (v6Match.getTransportSource() != 0) { salMatch.setField(MatchType.TP_SRC, (v6Match.getTransportSource())); } if (v6Match.getTransportDestination() != 0) { salMatch.setField(MatchType.TP_DST, (v6Match.getTransportDestination())); } } } // Convert actions Action salAction = null; List<Action> salActionList = new ArrayList<Action>(); if (actionsList == null) { salActionList.add(new Drop()); } else { for (OFAction ofAction : actionsList) { if (ofAction instanceof OFActionOutput) { short ofPort = ((OFActionOutput) ofAction).getPort(); if (ofPort == OFPort.OFPP_CONTROLLER.getValue()) { salAction = new Controller(); } else if (ofPort == OFPort.OFPP_NONE.getValue()) { salAction = new Drop(); } else if (ofPort == OFPort.OFPP_IN_PORT.getValue()) { salAction = new Loopback(); } else if (ofPort == OFPort.OFPP_FLOOD.getValue()) { salAction = new Flood(); } else if (ofPort == OFPort.OFPP_ALL.getValue()) { salAction = new FloodAll(); } else if (ofPort == OFPort.OFPP_LOCAL.getValue()) { salAction = new SwPath(); } else if (ofPort == OFPort.OFPP_NORMAL.getValue()) { salAction = new HwPath(); } else if (ofPort == OFPort.OFPP_TABLE.getValue()) { salAction = new HwPath(); // TODO: we do not handle // table in sal for now } else { salAction = new Output( NodeConnectorCreator.createOFNodeConnector( ofPort, node)); } } else if (ofAction instanceof OFActionVirtualLanIdentifier) { salAction = new SetVlanId( ((OFActionVirtualLanIdentifier) ofAction) .getVirtualLanIdentifier()); } else if (ofAction instanceof OFActionStripVirtualLan) { salAction = new PopVlan(); } else if (ofAction instanceof OFActionVirtualLanPriorityCodePoint) { salAction = new SetVlanPcp( ((OFActionVirtualLanPriorityCodePoint) ofAction) .getVirtualLanPriorityCodePoint()); } else if (ofAction instanceof OFActionDataLayerSource) { salAction = new SetDlSrc( ((OFActionDataLayerSource) ofAction) .getDataLayerAddress().clone()); } else if (ofAction instanceof OFActionDataLayerDestination) { salAction = new SetDlDst( ((OFActionDataLayerDestination) ofAction) .getDataLayerAddress().clone()); } else if (ofAction instanceof OFActionNetworkLayerSource) { byte addr[] = BigInteger.valueOf( ((OFActionNetworkLayerSource) ofAction) .getNetworkAddress()).toByteArray(); InetAddress ip = null; try { ip = InetAddress.getByAddress(addr); } catch (UnknownHostException e) { logger.error("", e); } salAction = new SetNwSrc(ip); } else if (ofAction instanceof OFActionNetworkLayerDestination) { byte addr[] = BigInteger.valueOf( ((OFActionNetworkLayerDestination) ofAction) .getNetworkAddress()).toByteArray(); InetAddress ip = null; try { ip = InetAddress.getByAddress(addr); } catch (UnknownHostException e) { logger.error("", e); } salAction = new SetNwDst(ip); } else if (ofAction instanceof OFActionNetworkTypeOfService) { salAction = new SetNwTos( ((OFActionNetworkTypeOfService) ofAction) .getNetworkTypeOfService()); } else if (ofAction instanceof OFActionTransportLayerSource) { Short port = ((OFActionTransportLayerSource) ofAction) .getTransportPort(); int intPort = NetUtils.getUnsignedShort(port); salAction = new SetTpSrc(intPort); } else if (ofAction instanceof OFActionTransportLayerDestination) { Short port = ((OFActionTransportLayerDestination) ofAction) .getTransportPort(); int intPort = NetUtils.getUnsignedShort(port); salAction = new SetTpDst(intPort); } salActionList.add(salAction); } } // Create Flow flow = new Flow(salMatch, salActionList); } logger.info("Openflow Match: {} Openflow Actions: {}", ofMatch, actionsList); logger.info("SAL Flow: {}", flow); return flow; } */ }
false
true
public IPCMMGate getServiceFlow() { IPCMMGate gate = new PCMMGateReq(); // ITransactionID trID = new TransactionID(); IAMID amid = new AMID(); ISubscriberID subscriberID = new SubscriberID(); IGateSpec gateSpec = new GateSpec(); IClassifier classifier = new Classifier(); IExtendedClassifier eclassifier = new ExtendedClassifier(); InetAddress defaultmask = null; /* Constrain priority to 64 to 128 as per spec */ byte pri = (byte) (flow.getPriority() & 0xFFFF); if ((pri < 64) || (pri > 128)) eclassifier.setPriority((byte) 64); else eclassifier.setPriority(pri); int TrafficRate = 0; if (pri == 100) TrafficRate = PCMMGlobalConfig.DefaultBestEffortTrafficRate; else TrafficRate = PCMMGlobalConfig.DefaultLowBestEffortTrafficRate; logger.info("FlowConverter Flow Id: {}", flow.getId()); logger.info("FlowConverter Priority: {}",pri); logger.info("FlowConverter Traffic Rate: {}",TrafficRate); ITrafficProfile trafficProfile = new BestEffortService( (byte) 7); //BestEffortService.DEFAULT_ENVELOP); ((BestEffortService) trafficProfile).getAuthorizedEnvelop() .setTrafficPriority(BestEffortService.DEFAULT_TRAFFIC_PRIORITY); ((BestEffortService) trafficProfile).getAuthorizedEnvelop() .setMaximumTrafficBurst( BestEffortService.DEFAULT_MAX_TRAFFIC_BURST); ((BestEffortService) trafficProfile).getAuthorizedEnvelop() .setRequestTransmissionPolicy( PCMMGlobalConfig.BETransmissionPolicy); ((BestEffortService) trafficProfile).getAuthorizedEnvelop() .setMaximumSustainedTrafficRate( TrafficRate); ((BestEffortService) trafficProfile).getReservedEnvelop() .setTrafficPriority(BestEffortService.DEFAULT_TRAFFIC_PRIORITY); ((BestEffortService) trafficProfile).getReservedEnvelop() .setMaximumTrafficBurst( BestEffortService.DEFAULT_MAX_TRAFFIC_BURST); ((BestEffortService) trafficProfile).getReservedEnvelop() .setRequestTransmissionPolicy( PCMMGlobalConfig.BETransmissionPolicy); ((BestEffortService) trafficProfile).getReservedEnvelop() .setMaximumSustainedTrafficRate( TrafficRate); ((BestEffortService) trafficProfile).getCommittedEnvelop() .setTrafficPriority(BestEffortService.DEFAULT_TRAFFIC_PRIORITY); ((BestEffortService) trafficProfile).getCommittedEnvelop() .setMaximumTrafficBurst( BestEffortService.DEFAULT_MAX_TRAFFIC_BURST); ((BestEffortService) trafficProfile).getCommittedEnvelop() .setRequestTransmissionPolicy( PCMMGlobalConfig.BETransmissionPolicy); ((BestEffortService) trafficProfile).getCommittedEnvelop() .setMaximumSustainedTrafficRate( TrafficRate); amid.setApplicationType((short) 1); amid.setApplicationMgrTag((short) 1); gateSpec.setDirection(Direction.UPSTREAM); gateSpec.setDSCP_TOSOverwrite(DSCPTOS.OVERRIDE); gateSpec.setTimerT1(PCMMGlobalConfig.GateT1); gateSpec.setTimerT2(PCMMGlobalConfig.GateT2); gateSpec.setTimerT3(PCMMGlobalConfig.GateT3); gateSpec.setTimerT4(PCMMGlobalConfig.GateT4); try { InetAddress subIP = InetAddress .getByName(PCMMGlobalConfig.SubscriberID); subscriberID.setSourceIPAddress(subIP); } catch (UnknownHostException unae) { logger.error("Error getByName" + unae.getMessage()); } Match match = flow.getMatch(); if (match.isPresent(MatchType.IN_PORT)) { short port = (Short) ((NodeConnector) match.getField( MatchType.IN_PORT).getValue()).getID(); if (!isIPv6) { logger.info("Flow : In Port: {}", port); } else { logger.info("Flow V6 : In Port: {}", port); } } if (match.isPresent(MatchType.DL_SRC)) { byte[] srcMac = (byte[]) match.getField(MatchType.DL_SRC) .getValue(); if (!isIPv6) { logger.info("Flow : Data Layer Src MAC: {}", srcMac); } else { logger.info("Flow V6 : Data Layer Src MAC: {}", srcMac); } } if (match.isPresent(MatchType.DL_DST)) { byte[] dstMac = (byte[]) match.getField(MatchType.DL_DST) .getValue(); if (!isIPv6) { logger.info("Flow : Data Layer Dst MAC: {}", dstMac); } else { logger.info("Flow V6 : Data Layer Dst MAC: {}", dstMac); } } if (match.isPresent(MatchType.DL_VLAN)) { short vlan = (Short) match.getField(MatchType.DL_VLAN) .getValue(); if (vlan == MatchType.DL_VLAN_NONE) { vlan = OFP_VLAN_NONE; } if (!isIPv6) { logger.info("Flow : Data Layer Vlan: {}", vlan); } else { logger.info("Flow V6 : Data Layer Vlan: {}", vlan); } } if (match.isPresent(MatchType.DL_VLAN_PR)) { byte vlanPr = (Byte) match.getField(MatchType.DL_VLAN_PR) .getValue(); if (!isIPv6) { logger.info("Flow : Data Layer Vlan Priority: {}", vlanPr); } else { logger.info("Flow : Data Layer Vlan Priority: {}", vlanPr); } } if (match.isPresent(MatchType.DL_TYPE)) { short ethType = (Short) match.getField(MatchType.DL_TYPE) .getValue(); if (!isIPv6) { logger.info("Flow : Data Layer Eth Type: {}", ethType); } else { logger.info("Flow V6: Data Layer Eth Type: {}", ethType); } } if (match.isPresent(MatchType.NW_TOS)) { byte tos = (Byte) match.getField(MatchType.NW_TOS).getValue(); byte dscp = (byte) (tos << 2); if (!isIPv6) { logger.info("Flow : Network TOS : {}", tos); logger.info("Flow : Network DSCP : {}", dscp); // XXX - hook me up gateSpec.setDSCP_TOSOverwrite(DSCPTOS.OVERRIDE); } else { logger.info("Flow V6 : Network TOS : {}", tos); logger.info("Flow V6 : Network DSCP : {}", dscp); } } if (match.isPresent(MatchType.NW_PROTO)) { byte proto = (Byte) match.getField(MatchType.NW_PROTO) .getValue(); if (!isIPv6) { logger.info("Flow : Network Protocol : {}", proto); switch (proto) { case 6: classifier.setProtocol(IClassifier.Protocol.TCP); break; case 17: classifier.setProtocol(IClassifier.Protocol.UDP); break; case 0: default: classifier.setProtocol(IClassifier.Protocol.NONE); break; } } else { logger.info("Flow V6 : Network Protocol : {}", proto); } } if (match.isPresent(MatchType.NW_SRC)) { InetAddress address = (InetAddress) match.getField(MatchType.NW_SRC).getValue(); InetAddress mask = (InetAddress) match.getField(MatchType.NW_SRC).getMask(); try { defaultmask = InetAddress.getByName("0.0.0.0"); } catch (UnknownHostException unae) { System.out.println("Error getByName" + unae.getMessage()); } if (!isIPv6) { int maskLength = (mask == null) ? 32 : NetUtils.getSubnetMaskLength(mask); logger.info("Flow : Network Address Src : {} Mask : {}", address, mask); eclassifier.setSourceIPAddress(address); if (mask == null) eclassifier.setIPSourceMask(defaultmask); else eclassifier.setIPSourceMask(mask); } else { logger.info("Flow V6 : Network Address Src : {} Mask : {}", address, mask); } } if (match.isPresent(MatchType.NW_DST)) { InetAddress address = (InetAddress) match.getField(MatchType.NW_DST).getValue(); InetAddress mask = (InetAddress) match.getField(MatchType.NW_DST).getMask(); // InetAddress defaultmask; try { defaultmask = InetAddress.getByName("0.0.0.0"); } catch (UnknownHostException unae) { System.out.println("Error getByName" + unae.getMessage()); } if (!isIPv6) { int maskLength = (mask == null) ? 32 : NetUtils.getSubnetMaskLength(mask); logger.info("Flow : Network Address Dst : {} Mask : {}", address, mask); eclassifier.setDestinationIPAddress(address); if (mask == null) eclassifier.setIPDestinationMask(defaultmask); else eclassifier.setIPDestinationMask(mask); } else { logger.info("Flow V6 : Network Address Dst : {} Mask : {}", address, mask); } } if (match.isPresent(MatchType.TP_SRC)) { short port = (Short) match.getField(MatchType.TP_SRC) .getValue(); if (!isIPv6) { logger.info("Flow : Network Transport Port Src : {} ", port); eclassifier.setSourcePortStart(port); eclassifier.setSourcePortEnd(port); } else { logger.info("Flow V6 : Network Transport Port Src : {} ", port); } } if (match.isPresent(MatchType.TP_DST)) { short port = (Short) match.getField(MatchType.TP_DST) .getValue(); if (!isIPv6) { logger.info("Flow : Network Transport Port Dst : {} ", port); eclassifier.setDestinationPortStart(port); eclassifier.setDestinationPortEnd(port); } else { logger.info("Flow V6: Network Transport Port Dst : {} ", port); } } if (!isIPv6) { } logger.info("SAL Match: {} ", flow.getMatch()); eclassifier.setClassifierID((short) 0x01); /* eclassifier.setClassifierID((short) (_classifierID == 0 ? Math .random() * hashCode() : _classifierID)); */ eclassifier.setAction((byte) 0x00); eclassifier.setActivationState((byte) 0x01); //gate.setTransactionID(trID); gate.setAMID(amid); gate.setSubscriberID(subscriberID); gate.setGateSpec(gateSpec); gate.setTrafficProfile(trafficProfile); gate.setClassifier(eclassifier); return gate; }
public IPCMMGate getServiceFlow() { IPCMMGate gate = new PCMMGateReq(); // ITransactionID trID = new TransactionID(); IAMID amid = new AMID(); ISubscriberID subscriberID = new SubscriberID(); IGateSpec gateSpec = new GateSpec(); IClassifier classifier = new Classifier(); IExtendedClassifier eclassifier = new ExtendedClassifier(); InetAddress defaultmask = null; /* Constrain priority to 64 to 128 as per spec */ byte pri = (byte) (flow.getPriority() & 0xFFFF); if ((pri < 64) || (pri > 128)) eclassifier.setPriority((byte) 64); else eclassifier.setPriority(pri); int TrafficRate = 0; if (pri == 100) TrafficRate = PCMMGlobalConfig.DefaultBestEffortTrafficRate; else TrafficRate = PCMMGlobalConfig.DefaultLowBestEffortTrafficRate; logger.info("FlowConverter Flow Id: {}", flow.getId()); logger.info("FlowConverter Priority: {}",pri); logger.info("FlowConverter Traffic Rate: {}",TrafficRate); ITrafficProfile trafficProfile = new BestEffortService( (byte) 7); //BestEffortService.DEFAULT_ENVELOP); ((BestEffortService) trafficProfile).getAuthorizedEnvelop() .setTrafficPriority(BestEffortService.DEFAULT_TRAFFIC_PRIORITY); ((BestEffortService) trafficProfile).getAuthorizedEnvelop() .setMaximumTrafficBurst( BestEffortService.DEFAULT_MAX_TRAFFIC_BURST); ((BestEffortService) trafficProfile).getAuthorizedEnvelop() .setRequestTransmissionPolicy( PCMMGlobalConfig.BETransmissionPolicy); ((BestEffortService) trafficProfile).getAuthorizedEnvelop() .setMaximumSustainedTrafficRate( TrafficRate); ((BestEffortService) trafficProfile).getReservedEnvelop() .setTrafficPriority(BestEffortService.DEFAULT_TRAFFIC_PRIORITY); ((BestEffortService) trafficProfile).getReservedEnvelop() .setMaximumTrafficBurst( BestEffortService.DEFAULT_MAX_TRAFFIC_BURST); ((BestEffortService) trafficProfile).getReservedEnvelop() .setRequestTransmissionPolicy( PCMMGlobalConfig.BETransmissionPolicy); ((BestEffortService) trafficProfile).getReservedEnvelop() .setMaximumSustainedTrafficRate( TrafficRate); ((BestEffortService) trafficProfile).getCommittedEnvelop() .setTrafficPriority(BestEffortService.DEFAULT_TRAFFIC_PRIORITY); ((BestEffortService) trafficProfile).getCommittedEnvelop() .setMaximumTrafficBurst( BestEffortService.DEFAULT_MAX_TRAFFIC_BURST); ((BestEffortService) trafficProfile).getCommittedEnvelop() .setRequestTransmissionPolicy( PCMMGlobalConfig.BETransmissionPolicy); ((BestEffortService) trafficProfile).getCommittedEnvelop() .setMaximumSustainedTrafficRate( TrafficRate); amid.setApplicationType((short) 1); amid.setApplicationMgrTag((short) 1); gateSpec.setDirection(Direction.UPSTREAM); gateSpec.setDSCP_TOSOverwrite(DSCPTOS.OVERRIDE); gateSpec.setTimerT1(PCMMGlobalConfig.GateT1); gateSpec.setTimerT2(PCMMGlobalConfig.GateT2); gateSpec.setTimerT3(PCMMGlobalConfig.GateT3); gateSpec.setTimerT4(PCMMGlobalConfig.GateT4); try { InetAddress subIP = InetAddress .getByName(PCMMGlobalConfig.SubscriberID); subscriberID.setSourceIPAddress(subIP); } catch (UnknownHostException unae) { logger.error("Error getByName" + unae.getMessage()); } Match match = flow.getMatch(); if (match.isPresent(MatchType.IN_PORT)) { short port = (Short) ((NodeConnector) match.getField( MatchType.IN_PORT).getValue()).getID(); if (!isIPv6) { logger.info("Flow : In Port: {}", port); } else { logger.info("Flow V6 : In Port: {}", port); } } if (match.isPresent(MatchType.DL_SRC)) { byte[] srcMac = (byte[]) match.getField(MatchType.DL_SRC) .getValue(); if (!isIPv6) { logger.info("Flow : Data Layer Src MAC: {}", srcMac); } else { logger.info("Flow V6 : Data Layer Src MAC: {}", srcMac); } } if (match.isPresent(MatchType.DL_DST)) { byte[] dstMac = (byte[]) match.getField(MatchType.DL_DST) .getValue(); if (!isIPv6) { logger.info("Flow : Data Layer Dst MAC: {}", dstMac); } else { logger.info("Flow V6 : Data Layer Dst MAC: {}", dstMac); } } if (match.isPresent(MatchType.DL_VLAN)) { short vlan = (Short) match.getField(MatchType.DL_VLAN) .getValue(); if (vlan == MatchType.DL_VLAN_NONE) { vlan = OFP_VLAN_NONE; } if (!isIPv6) { logger.info("Flow : Data Layer Vlan: {}", vlan); } else { logger.info("Flow V6 : Data Layer Vlan: {}", vlan); } } if (match.isPresent(MatchType.DL_VLAN_PR)) { byte vlanPr = (Byte) match.getField(MatchType.DL_VLAN_PR) .getValue(); if (!isIPv6) { logger.info("Flow : Data Layer Vlan Priority: {}", vlanPr); } else { logger.info("Flow : Data Layer Vlan Priority: {}", vlanPr); } } if (match.isPresent(MatchType.DL_TYPE)) { short ethType = (Short) match.getField(MatchType.DL_TYPE) .getValue(); if (!isIPv6) { logger.info("Flow : Data Layer Eth Type: {}", ethType); } else { logger.info("Flow V6: Data Layer Eth Type: {}", ethType); } } if (match.isPresent(MatchType.NW_TOS)) { byte tos = (Byte) match.getField(MatchType.NW_TOS).getValue(); byte dscp = (byte) (tos << 2); if (!isIPv6) { logger.info("Flow : Network TOS : {}", tos); logger.info("Flow : Network DSCP : {}", dscp); // XXX - hook me up gateSpec.setDSCP_TOSOverwrite(DSCPTOS.OVERRIDE); } else { logger.info("Flow V6 : Network TOS : {}", tos); logger.info("Flow V6 : Network DSCP : {}", dscp); } } if (match.isPresent(MatchType.NW_PROTO)) { byte proto = (Byte) match.getField(MatchType.NW_PROTO) .getValue(); if (!isIPv6) { logger.info("Flow : Network Protocol : {}", proto); switch (proto) { case 6: eclassifier.setProtocol(IClassifier.Protocol.TCP); break; case 17: eclassifier.setProtocol(IClassifier.Protocol.UDP); break; case 0: default: eclassifier.setProtocol(IClassifier.Protocol.NONE); break; } } else { logger.info("Flow V6 : Network Protocol : {}", proto); } } if (match.isPresent(MatchType.NW_SRC)) { InetAddress address = (InetAddress) match.getField(MatchType.NW_SRC).getValue(); InetAddress mask = (InetAddress) match.getField(MatchType.NW_SRC).getMask(); try { defaultmask = InetAddress.getByName("0.0.0.0"); } catch (UnknownHostException unae) { System.out.println("Error getByName" + unae.getMessage()); } if (!isIPv6) { int maskLength = (mask == null) ? 32 : NetUtils.getSubnetMaskLength(mask); logger.info("Flow : Network Address Src : {} Mask : {}", address, mask); eclassifier.setSourceIPAddress(address); if (mask == null) eclassifier.setIPSourceMask(defaultmask); else eclassifier.setIPSourceMask(mask); //eclassifier.setIPSourceMask(defaultmask); } else { logger.info("Flow V6 : Network Address Src : {} Mask : {}", address, mask); } } if (match.isPresent(MatchType.NW_DST)) { InetAddress address = (InetAddress) match.getField(MatchType.NW_DST).getValue(); InetAddress mask = (InetAddress) match.getField(MatchType.NW_DST).getMask(); // InetAddress defaultmask; try { defaultmask = InetAddress.getByName("0.0.0.0"); } catch (UnknownHostException unae) { System.out.println("Error getByName" + unae.getMessage()); } if (!isIPv6) { int maskLength = (mask == null) ? 32 : NetUtils.getSubnetMaskLength(mask); logger.info("Flow : Network Address Dst : {} Mask : {}", address, mask); eclassifier.setDestinationIPAddress(address); if (mask == null) eclassifier.setIPDestinationMask(defaultmask); else eclassifier.setIPDestinationMask(mask); //eclassifier.setIPDestinationMask(defaultmask); } else { logger.info("Flow V6 : Network Address Dst : {} Mask : {}", address, mask); } } if (match.isPresent(MatchType.TP_SRC)) { short port = (Short) match.getField(MatchType.TP_SRC) .getValue(); if (!isIPv6) { logger.info("Flow : Network Transport Port Src : {} ", port); eclassifier.setSourcePortStart(port); eclassifier.setSourcePortEnd(port); } else { logger.info("Flow V6 : Network Transport Port Src : {} ", port); } } if (match.isPresent(MatchType.TP_DST)) { short port = (Short) match.getField(MatchType.TP_DST) .getValue(); if (!isIPv6) { logger.info("Flow : Network Transport Port Dst : {} ", port); eclassifier.setDestinationPortStart(port); eclassifier.setDestinationPortEnd(port); } else { logger.info("Flow V6: Network Transport Port Dst : {} ", port); } } if (!isIPv6) { } logger.info("SAL Match: {} ", flow.getMatch()); eclassifier.setClassifierID((short) 0x01); /* eclassifier.setClassifierID((short) (_classifierID == 0 ? Math .random() * hashCode() : _classifierID)); */ eclassifier.setAction((byte) 0x00); eclassifier.setActivationState((byte) 0x01); //gate.setTransactionID(trID); gate.setAMID(amid); gate.setSubscriberID(subscriberID); gate.setGateSpec(gateSpec); gate.setTrafficProfile(trafficProfile); gate.setClassifier(eclassifier); return gate; }
diff --git a/src/org/newdawn/slick/opengl/PNGImageData.java b/src/org/newdawn/slick/opengl/PNGImageData.java index 1ec7e41..4d3cafe 100644 --- a/src/org/newdawn/slick/opengl/PNGImageData.java +++ b/src/org/newdawn/slick/opengl/PNGImageData.java @@ -1,787 +1,791 @@ package org.newdawn.slick.opengl; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.zip.CRC32; import java.util.zip.DataFormatException; import java.util.zip.Inflater; import org.lwjgl.BufferUtils; /** * The PNG imge data source that is pure java reading PNGs * * @author Matthias Mann (original code) */ public class PNGImageData implements LoadableImageData { /** The valid signature of a PNG */ private static final byte[] SIGNATURE = {(byte)137, 80, 78, 71, 13, 10, 26, 10}; /** The header chunk identifer */ private static final int IHDR = 0x49484452; /** The palette chunk identifer */ private static final int PLTE = 0x504C5445; /** The transparency chunk identifier */ private static final int tRNS = 0x74524E53; /** The data chunk identifier */ private static final int IDAT = 0x49444154; /** The end chunk identifier */ private static final int IEND = 0x49454E44; /** Color type for greyscale images */ private static final byte COLOR_GREYSCALE = 0; /** Color type for true colour images */ private static final byte COLOR_TRUECOLOR = 2; /** Color type for indexed palette images */ private static final byte COLOR_INDEXED = 3; /** Color type for greyscale images with alpha */ private static final byte COLOR_GREYALPHA = 4; /** Color type for true colour images with alpha */ private static final byte COLOR_TRUEALPHA = 6; /** The stream we're going to read from */ private InputStream input; /** The CRC for the current chunk */ private final CRC32 crc; /** The buffer we'll use as temporary storage */ private final byte[] buffer; /** The length of the current chunk in bytes */ private int chunkLength; /** The ID of the current chunk */ private int chunkType; /** The number of bytes remaining in the current chunk */ private int chunkRemaining; /** The width of the image read */ private int width; /** The height of the image read */ private int height; /** The type of colours in the PNG data */ private int colorType; /** The number of bytes per pixel */ private int bytesPerPixel; /** The palette data that has been read - RGB only */ private byte[] palette; /** The palette data thats be read from alpha channel */ private byte[] paletteA; /** The transparent pixel description */ private byte[] transPixel; /** The bit depth of the image */ private int bitDepth; /** The width of the texture to be generated */ private int texWidth; /** The height of the texture to be generated */ private int texHeight; /** The scratch buffer used to store the image data */ private ByteBuffer scratch; /** * Create a new PNG image data that can read image data from PNG formated files */ public PNGImageData() { this.crc = new CRC32(); this.buffer = new byte[4096]; } /** * Initialise the PNG data header fields from the input stream * * @param input The input stream to read from * @throws IOException Indicates a failure to read appropriate data from the stream */ private void init(InputStream input) throws IOException { this.input = input; int read = input.read(buffer, 0, SIGNATURE.length); if(read != SIGNATURE.length || !checkSignatur(buffer)) { throw new IOException("Not a valid PNG file"); } openChunk(IHDR); readIHDR(); closeChunk(); searchIDAT: for(;;) { openChunk(); switch (chunkType) { case IDAT: break searchIDAT; case PLTE: readPLTE(); break; case tRNS: readtRNS(); break; } closeChunk(); } } /** * @see org.newdawn.slick.opengl.ImageData#getHeight() */ public int getHeight() { return height; } /** * @see org.newdawn.slick.opengl.ImageData#getWidth() */ public int getWidth() { return width; } /** * Check if this PNG has a an alpha channel * * @return True if the PNG has an alpha channel */ public boolean hasAlpha() { return colorType == COLOR_TRUEALPHA || paletteA != null || transPixel != null; } /** * Check if the PNG is RGB formatted * * @return True if the PNG is RGB formatted */ public boolean isRGB() { return colorType == COLOR_TRUEALPHA || colorType == COLOR_TRUECOLOR || colorType == COLOR_INDEXED; } /** * Decode a PNG into a data buffer * * @param buffer The buffer to read the data into * @param stride The image stride to read (i.e. the number of bytes to skip each line) * @param flip True if the PNG should be flipped * @throws IOException Indicates a failure to read the PNG either invalid data or * not enough room in the buffer */ private void decode(ByteBuffer buffer, int stride, boolean flip) throws IOException { final int offset = buffer.position(); byte[] curLine = new byte[width*bytesPerPixel+1]; byte[] prevLine = new byte[width*bytesPerPixel+1]; final Inflater inflater = new Inflater(); try { for(int yIndex=0 ; yIndex<height ; yIndex++) { int y = yIndex; if (flip) { y = height - 1 - yIndex; } readChunkUnzip(inflater, curLine, 0, curLine.length); unfilter(curLine, prevLine); buffer.position(offset + y*stride); switch (colorType) { case COLOR_TRUECOLOR: case COLOR_TRUEALPHA: copy(buffer, curLine); break; case COLOR_INDEXED: copyExpand(buffer, curLine); break; default: throw new UnsupportedOperationException("Not yet implemented"); } byte[] tmp = curLine; curLine = prevLine; prevLine = tmp; } } finally { inflater.end(); } bitDepth = hasAlpha() ? 32 : 24; } /** * Copy some data into the given byte buffer expanding the * data based on indexing the palette * * @param buffer The buffer to write into * @param curLine The current line of data to copy */ private void copyExpand(ByteBuffer buffer, byte[] curLine) { for (int i=1;i<curLine.length;i++) { int v = curLine[i] & 255; int index = v * 3; for (int j=0;j<3;j++) { buffer.put(palette[index+j]); } if (hasAlpha()) { if (paletteA != null) { buffer.put(paletteA[v]); } else { buffer.put((byte) 255); } } } } /** * Copy the data given directly into the byte buffer (skipping * the filter byte); * * @param buffer The buffer to write into * @param curLine The current line to copy into the buffer */ private void copy(ByteBuffer buffer, byte[] curLine) { buffer.put(curLine, 1, curLine.length-1); } /** * Unfilter the data, i.e. convert it back to it's original form * * @param curLine The line of data just read * @param prevLine The line before * @throws IOException Indicates a failure to unfilter the data due to an unknown * filter type */ private void unfilter(byte[] curLine, byte[] prevLine) throws IOException { switch (curLine[0]) { case 0: // none break; case 1: unfilterSub(curLine); break; case 2: unfilterUp(curLine, prevLine); break; case 3: unfilterAverage(curLine, prevLine); break; case 4: unfilterPaeth(curLine, prevLine); break; default: throw new IOException("invalide filter type in scanline: " + curLine[0]); } } /** * Sub unfilter * {@url http://libpng.nigilist.ru/pub/png/spec/1.2/PNG-Filters.html} * * @param curLine The line of data to be unfiltered */ private void unfilterSub(byte[] curLine) { final int bpp = this.bytesPerPixel; final int lineSize = width*bpp; for(int i=bpp+1 ; i<=lineSize ; ++i) { curLine[i] += curLine[i-bpp]; } } /** * Up unfilter * {@url http://libpng.nigilist.ru/pub/png/spec/1.2/PNG-Filters.html} * * @param prevLine The line of data read before the current * @param curLine The line of data to be unfiltered */ private void unfilterUp(byte[] curLine, byte[] prevLine) { final int bpp = this.bytesPerPixel; final int lineSize = width*bpp; for(int i=1 ; i<=lineSize ; ++i) { curLine[i] += prevLine[i]; } } /** * Average unfilter * {@url http://libpng.nigilist.ru/pub/png/spec/1.2/PNG-Filters.html} * * @param prevLine The line of data read before the current * @param curLine The line of data to be unfiltered */ private void unfilterAverage(byte[] curLine, byte[] prevLine) { final int bpp = this.bytesPerPixel; final int lineSize = width*bpp; int i; for(i=1 ; i<=bpp ; ++i) { curLine[i] += (byte)((prevLine[i] & 0xFF) >>> 1); } for(; i<=lineSize ; ++i) { curLine[i] += (byte)(((prevLine[i] & 0xFF) + (curLine[i - bpp] & 0xFF)) >>> 1); } } /** * Paeth unfilter * {@url http://libpng.nigilist.ru/pub/png/spec/1.2/PNG-Filters.html} * * @param prevLine The line of data read before the current * @param curLine The line of data to be unfiltered */ private void unfilterPaeth(byte[] curLine, byte[] prevLine) { final int bpp = this.bytesPerPixel; final int lineSize = width*bpp; int i; for(i=1 ; i<=bpp ; ++i) { curLine[i] += prevLine[i]; } for(; i<=lineSize ; ++i) { int a = curLine[i - bpp] & 255; int b = prevLine[i] & 255; int c = prevLine[i - bpp] & 255; int p = a + b - c; int pa = p - a; if(pa < 0) pa = -pa; int pb = p - b; if(pb < 0) pb = -pb; int pc = p - c; if(pc < 0) pc = -pc; if(pa<=pb && pa<=pc) c = a; else if(pb<=pc) c = b; curLine[i] += (byte)c; } } /** * Read the header of the PNG * * @throws IOException Indicates a failure to read the header */ private void readIHDR() throws IOException { checkChunkLength(13); readChunk(buffer, 0, 13); width = readInt(buffer, 0); height = readInt(buffer, 4); if(buffer[8] != 8) { throw new IOException("Unsupported bit depth"); } colorType = buffer[9] & 255; switch (colorType) { case COLOR_GREYSCALE: bytesPerPixel = 1; break; case COLOR_TRUECOLOR: bytesPerPixel = 3; break; case COLOR_TRUEALPHA: bytesPerPixel = 4; break; case COLOR_INDEXED: bytesPerPixel = 1; break; default: throw new IOException("unsupported color format"); } if(buffer[10] != 0) { throw new IOException("unsupported compression method"); } if(buffer[11] != 0) { throw new IOException("unsupported filtering method"); } if(buffer[12] != 0) { throw new IOException("unsupported interlace method"); } } /** * Read the palette chunk * * @throws IOException Indicates a failure to fully read the chunk */ private void readPLTE() throws IOException { int paletteEntries = chunkLength / 3; if(paletteEntries < 1 || paletteEntries > 256 || (chunkLength % 3) != 0) { throw new IOException("PLTE chunk has wrong length"); } palette = new byte[paletteEntries*3]; readChunk(palette, 0, palette.length); } /** * Read the transparency chunk * * @throws IOException Indicates a failure to fully read the chunk */ private void readtRNS() throws IOException { switch (colorType) { case COLOR_GREYSCALE: checkChunkLength(2); transPixel = new byte[2]; readChunk(transPixel, 0, 2); break; case COLOR_TRUECOLOR: checkChunkLength(6); transPixel = new byte[6]; readChunk(transPixel, 0, 6); break; case COLOR_INDEXED: if(palette == null) { throw new IOException("tRNS chunk without PLTE chunk"); } paletteA = new byte[palette.length/3]; // initialise default palette values for (int i=0;i<paletteA.length;i++) { paletteA[i] = (byte) 255; } readChunk(paletteA, 0, paletteA.length); break; default: // just ignore it } } /** * Close the current chunk, skip the remaining data * * @throws IOException Indicates a failure to read off redundant data */ private void closeChunk() throws IOException { if(chunkRemaining > 0) { // just skip the rest and the CRC input.skip(chunkRemaining+4); } else { readFully(buffer, 0, 4); int expectedCrc = readInt(buffer, 0); int computedCrc = (int)crc.getValue(); if(computedCrc != expectedCrc) { throw new IOException("Invalid CRC"); } } chunkRemaining = 0; chunkLength = 0; chunkType = 0; } /** * Open the next chunk, determine the type and setup the internal state * * @throws IOException Indicates a failure to determine chunk information from the stream */ private void openChunk() throws IOException { readFully(buffer, 0, 8); chunkLength = readInt(buffer, 0); chunkType = readInt(buffer, 4); chunkRemaining = chunkLength; crc.reset(); crc.update(buffer, 4, 4); // only chunkType } /** * Open a chunk of an expected type * * @param expected The expected type of the next chunk * @throws IOException Indicate a failure to read data or a different chunk on the stream */ private void openChunk(int expected) throws IOException { openChunk(); if(chunkType != expected) { throw new IOException("Expected chunk: " + Integer.toHexString(expected)); } } /** * Check the current chunk has the correct size * * @param expected The expected size of the chunk * @throws IOException Indicate an invalid size */ private void checkChunkLength(int expected) throws IOException { if(chunkLength != expected) { throw new IOException("Chunk has wrong size"); } } /** * Read some data from the current chunk * * @param buffer The buffer to read into * @param offset The offset into the buffer to read into * @param length The amount of data to read * @return The number of bytes read from the chunk * @throws IOException Indicate a failure to read the appropriate data from the chunk */ private int readChunk(byte[] buffer, int offset, int length) throws IOException { if(length > chunkRemaining) { length = chunkRemaining; } readFully(buffer, offset, length); crc.update(buffer, offset, length); chunkRemaining -= length; return length; } /** * Refill the inflating stream with data from the stream * * @param inflater The inflater to fill * @throws IOException Indicates there is no more data left or invalid data has been found on * the stream. */ private void refillInflater(Inflater inflater) throws IOException { while(chunkRemaining == 0) { closeChunk(); openChunk(IDAT); } int read = readChunk(buffer, 0, buffer.length); inflater.setInput(buffer, 0, read); } /** * Read a chunk from the inflater * * @param inflater The inflater to read the data from * @param buffer The buffer to write into * @param offset The offset into the buffer at which to start writing * @param length The number of bytes to read * @throws IOException Indicates a failure to read the complete chunk */ private void readChunkUnzip(Inflater inflater, byte[] buffer, int offset, int length) throws IOException { try { do { int read = inflater.inflate(buffer, offset, length); if(read <= 0) { if(inflater.finished()) { throw new EOFException(); } if(inflater.needsInput()) { refillInflater(inflater); } else { throw new IOException("Can't inflate " + length + " bytes"); } } else { offset += read; length -= read; } } while(length > 0); } catch (DataFormatException ex) { IOException io = new IOException("inflate error"); io.initCause(ex); throw io; } } /** * Read a complete buffer of data from the input stream * * @param buffer The buffer to read into * @param offset The offset to start copying into * @param length The length of bytes to read * @throws IOException Indicates a failure to access the data */ private void readFully(byte[] buffer, int offset, int length) throws IOException { do { int read = input.read(buffer, offset, length); if(read < 0) { throw new EOFException(); } offset += read; length -= read; } while(length > 0); } /** * Read an int from a buffer * * @param buffer The buffer to read from * @param offset The offset into the buffer to read from * @return The int read interpreted in big endian */ private int readInt(byte[] buffer, int offset) { return ((buffer[offset ] ) << 24) | ((buffer[offset+1] & 255) << 16) | ((buffer[offset+2] & 255) << 8) | ((buffer[offset+3] & 255) ); } /** * Check the signature of the PNG to confirm it's a PNG * * @param buffer The buffer to read from * @return True if the PNG signature is correct */ private boolean checkSignatur(byte[] buffer) { for(int i=0 ; i<SIGNATURE.length ; i++) { if(buffer[i] != SIGNATURE[i]) { return false; } } return true; } /** * @see org.newdawn.slick.opengl.ImageData#getDepth() */ public int getDepth() { return bitDepth; } /** * @see org.newdawn.slick.opengl.ImageData#getImageBufferData() */ public ByteBuffer getImageBufferData() { return scratch; } /** * @see org.newdawn.slick.opengl.ImageData#getTexHeight() */ public int getTexHeight() { return texHeight; } /** * @see org.newdawn.slick.opengl.ImageData#getTexWidth() */ public int getTexWidth() { return texWidth; } /** * @see org.newdawn.slick.opengl.LoadableImageData#loadImage(java.io.InputStream) */ public ByteBuffer loadImage(InputStream fis) throws IOException { return loadImage(fis, false, null); } /** * @see org.newdawn.slick.opengl.LoadableImageData#loadImage(java.io.InputStream, boolean, int[]) */ public ByteBuffer loadImage(InputStream fis, boolean flipped, int[] transparent) throws IOException { return loadImage(fis, flipped, false, transparent); } /** * @see org.newdawn.slick.opengl.LoadableImageData#loadImage(java.io.InputStream, boolean, boolean, int[]) */ public ByteBuffer loadImage(InputStream fis, boolean flipped, boolean forceAlpha, int[] transparent) throws IOException { if (transparent != null) { forceAlpha = true; } init(fis); if (!isRGB()) { throw new IOException("Only RGB formatted images are supported by the PNGLoader"); } texWidth = get2Fold(width); texHeight = get2Fold(height); int perPixel = hasAlpha() ? 4 : 3; // Get a pointer to the image memory scratch = BufferUtils.createByteBuffer(texWidth * texHeight * perPixel); decode(scratch, texWidth * perPixel, flipped); if (height < texHeight-1) { int topOffset = (texHeight-1) * (texWidth*perPixel); int bottomOffset = (height-1) * (texWidth*perPixel); for (int x=0;x<texWidth;x++) { for (int i=0;i<perPixel;i++) { scratch.put(topOffset+x+i, scratch.get(x+i)); scratch.put(bottomOffset+(texWidth*perPixel)+x+i, scratch.get(bottomOffset+x+i)); } } } if (width < texWidth-1) { for (int y=0;y<texHeight;y++) { for (int i=0;i<perPixel;i++) { scratch.put(((y+1)*(texWidth*perPixel))-perPixel+i, scratch.get(y*(texWidth*perPixel)+i)); scratch.put((y*(texWidth*perPixel))+(width*perPixel)+i, scratch.get((y*(texWidth*perPixel))+((width-1)*perPixel)+i)); } } } if (!hasAlpha() && forceAlpha) { ByteBuffer temp = BufferUtils.createByteBuffer(texWidth * texHeight * 4); for (int x=0;x<texWidth;x++) { for (int y=0;y<texHeight;y++) { int srcOffset = (y*3)+(x*texHeight*3); int dstOffset = (y*4)+(x*texHeight*4); temp.put(dstOffset, scratch.get(srcOffset)); temp.put(dstOffset+1, scratch.get(srcOffset+1)); temp.put(dstOffset+2, scratch.get(srcOffset+2)); - temp.put(dstOffset+3, (byte) 255); + if ((x < getHeight()) && (y < getWidth())) { + temp.put(dstOffset+3, (byte) 255); + } else { + temp.put(dstOffset+3, (byte) 0); + } } } colorType = COLOR_TRUEALPHA; bitDepth = 32; scratch = temp; } if (transparent != null) { for (int i=0;i<texWidth*texHeight*4;i+=4) { boolean match = true; for (int c=0;c<3;c++) { if (toInt(scratch.get(i+c)) != transparent[c]) { match = false; } } if (match) { scratch.put(i+3, (byte) 0); } } } scratch.position(0); return scratch; } /** * Safe convert byte to int * * @param b The byte to convert * @return The converted byte */ private int toInt(byte b) { if (b < 0) { return 256+b; } return b; } /** * Get the closest greater power of 2 to the fold number * * @param fold The target number * @return The power of 2 */ private int get2Fold(int fold) { int ret = 2; while (ret < fold) { ret *= 2; } return ret; } /** * @see org.newdawn.slick.opengl.LoadableImageData#configureEdging(boolean) */ public void configureEdging(boolean edging) { } }
true
true
public ByteBuffer loadImage(InputStream fis, boolean flipped, boolean forceAlpha, int[] transparent) throws IOException { if (transparent != null) { forceAlpha = true; } init(fis); if (!isRGB()) { throw new IOException("Only RGB formatted images are supported by the PNGLoader"); } texWidth = get2Fold(width); texHeight = get2Fold(height); int perPixel = hasAlpha() ? 4 : 3; // Get a pointer to the image memory scratch = BufferUtils.createByteBuffer(texWidth * texHeight * perPixel); decode(scratch, texWidth * perPixel, flipped); if (height < texHeight-1) { int topOffset = (texHeight-1) * (texWidth*perPixel); int bottomOffset = (height-1) * (texWidth*perPixel); for (int x=0;x<texWidth;x++) { for (int i=0;i<perPixel;i++) { scratch.put(topOffset+x+i, scratch.get(x+i)); scratch.put(bottomOffset+(texWidth*perPixel)+x+i, scratch.get(bottomOffset+x+i)); } } } if (width < texWidth-1) { for (int y=0;y<texHeight;y++) { for (int i=0;i<perPixel;i++) { scratch.put(((y+1)*(texWidth*perPixel))-perPixel+i, scratch.get(y*(texWidth*perPixel)+i)); scratch.put((y*(texWidth*perPixel))+(width*perPixel)+i, scratch.get((y*(texWidth*perPixel))+((width-1)*perPixel)+i)); } } } if (!hasAlpha() && forceAlpha) { ByteBuffer temp = BufferUtils.createByteBuffer(texWidth * texHeight * 4); for (int x=0;x<texWidth;x++) { for (int y=0;y<texHeight;y++) { int srcOffset = (y*3)+(x*texHeight*3); int dstOffset = (y*4)+(x*texHeight*4); temp.put(dstOffset, scratch.get(srcOffset)); temp.put(dstOffset+1, scratch.get(srcOffset+1)); temp.put(dstOffset+2, scratch.get(srcOffset+2)); temp.put(dstOffset+3, (byte) 255); } } colorType = COLOR_TRUEALPHA; bitDepth = 32; scratch = temp; } if (transparent != null) { for (int i=0;i<texWidth*texHeight*4;i+=4) { boolean match = true; for (int c=0;c<3;c++) { if (toInt(scratch.get(i+c)) != transparent[c]) { match = false; } } if (match) { scratch.put(i+3, (byte) 0); } } } scratch.position(0); return scratch; }
public ByteBuffer loadImage(InputStream fis, boolean flipped, boolean forceAlpha, int[] transparent) throws IOException { if (transparent != null) { forceAlpha = true; } init(fis); if (!isRGB()) { throw new IOException("Only RGB formatted images are supported by the PNGLoader"); } texWidth = get2Fold(width); texHeight = get2Fold(height); int perPixel = hasAlpha() ? 4 : 3; // Get a pointer to the image memory scratch = BufferUtils.createByteBuffer(texWidth * texHeight * perPixel); decode(scratch, texWidth * perPixel, flipped); if (height < texHeight-1) { int topOffset = (texHeight-1) * (texWidth*perPixel); int bottomOffset = (height-1) * (texWidth*perPixel); for (int x=0;x<texWidth;x++) { for (int i=0;i<perPixel;i++) { scratch.put(topOffset+x+i, scratch.get(x+i)); scratch.put(bottomOffset+(texWidth*perPixel)+x+i, scratch.get(bottomOffset+x+i)); } } } if (width < texWidth-1) { for (int y=0;y<texHeight;y++) { for (int i=0;i<perPixel;i++) { scratch.put(((y+1)*(texWidth*perPixel))-perPixel+i, scratch.get(y*(texWidth*perPixel)+i)); scratch.put((y*(texWidth*perPixel))+(width*perPixel)+i, scratch.get((y*(texWidth*perPixel))+((width-1)*perPixel)+i)); } } } if (!hasAlpha() && forceAlpha) { ByteBuffer temp = BufferUtils.createByteBuffer(texWidth * texHeight * 4); for (int x=0;x<texWidth;x++) { for (int y=0;y<texHeight;y++) { int srcOffset = (y*3)+(x*texHeight*3); int dstOffset = (y*4)+(x*texHeight*4); temp.put(dstOffset, scratch.get(srcOffset)); temp.put(dstOffset+1, scratch.get(srcOffset+1)); temp.put(dstOffset+2, scratch.get(srcOffset+2)); if ((x < getHeight()) && (y < getWidth())) { temp.put(dstOffset+3, (byte) 255); } else { temp.put(dstOffset+3, (byte) 0); } } } colorType = COLOR_TRUEALPHA; bitDepth = 32; scratch = temp; } if (transparent != null) { for (int i=0;i<texWidth*texHeight*4;i+=4) { boolean match = true; for (int c=0;c<3;c++) { if (toInt(scratch.get(i+c)) != transparent[c]) { match = false; } } if (match) { scratch.put(i+3, (byte) 0); } } } scratch.position(0); return scratch; }
diff --git a/Exploratory/TEB2FMI/ac.soton.fmusim.codegen/src/ac/soton/fmusim/codegen/FMUTranslator.java b/Exploratory/TEB2FMI/ac.soton.fmusim.codegen/src/ac/soton/fmusim/codegen/FMUTranslator.java index e018e0f..f4634a2 100644 --- a/Exploratory/TEB2FMI/ac.soton.fmusim.codegen/src/ac/soton/fmusim/codegen/FMUTranslator.java +++ b/Exploratory/TEB2FMI/ac.soton.fmusim.codegen/src/ac/soton/fmusim/codegen/FMUTranslator.java @@ -1,648 +1,648 @@ package ac.soton.fmusim.codegen; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.Map; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import org.eclipse.cdt.core.model.CModelException; import org.eclipse.cdt.core.model.CoreModel; import org.eclipse.cdt.core.model.ICProject; import org.eclipse.cdt.core.model.IPathEntry; import org.eclipse.cdt.core.model.ISourceEntry; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.common.util.TreeIterator; 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.eclipse.emf.ecore.xmi.impl.XMLResourceFactoryImpl; import org.eclipse.jface.viewers.IStructuredSelection; import org.eventb.codegen.il1.Declaration; import org.eventb.codegen.il1.Il1Factory; import org.eventb.codegen.il1.Program; import org.eventb.codegen.il1.Protected; import org.eventb.codegen.il1.Subroutine; import org.eventb.codegen.il1.impl.Il1PackageImpl; import org.eventb.codegen.il1.translator.AbstractTranslateEventBToTarget; import org.eventb.codegen.il1.translator.ClassHeaderInformation; import org.eventb.codegen.il1.translator.IL1TranslationManager; import org.eventb.codegen.il1.translator.IL1TranslationUnhandledTypeException; import org.eventb.codegen.il1.translator.TargetLanguage; import org.eventb.codegen.il1.translator.provider.ITranslationRule; import org.eventb.codegen.tasking.RMLDataStruct; import org.eventb.codegen.tasking.RelevantMachineLoader; import org.eventb.codegen.tasking.TaskingTranslationException; import org.eventb.codegen.tasking.TaskingTranslationManager; import org.eventb.codegen.tasking.TaskingTranslationUnhandledTypeException; import org.eventb.codegen.tasking.utils.CodeGenTaskingUtils; import org.eventb.core.ast.ITypeEnvironment; import org.eventb.core.ast.Type; import org.eventb.core.basis.ContextRoot; import org.eventb.core.basis.MachineRoot; import org.eventb.emf.core.machine.Machine; import org.eventb.emf.core.machine.Variable; import org.osgi.service.prefs.BackingStoreException; import org.rodinp.core.IRodinDB; import org.rodinp.core.IRodinFile; import org.rodinp.core.IRodinProject; import org.rodinp.core.RodinCore; import org.rodinp.core.RodinDBException; import FmiModel.BooleanType; import FmiModel.CoSimulationType; import FmiModel.DocumentRoot; import FmiModel.FmiModelDescriptionType; import FmiModel.FmiModelFactory; import FmiModel.FmiScalarVariable; import FmiModel.IntegerType; import FmiModel.ModelVariablesType; import FmiModel.RealType1; import FmiModel.StringType; import ac.soton.composition.core.basis.ComposedMachineRoot; import ac.soton.compositionmodel.core.compositionmodel.ComposedMachine; // This class is the entry point for the translation proper. // UNLIKE the existing C code generator, it does not extend AbstractProgramIL1Translator. // It is not related to the extensibility mechanism implemented by Chris, i.e. does not // use an extension point. However, protected objects, and those nested within, do use it. @SuppressWarnings("restriction") public class FMUTranslator extends AbstractTranslateEventBToTarget { public static final String REAL = "Real"; public static final String STRING = "String"; public static final String BOOLEAN = "Boolean"; public static final String INTEGER = "Integer"; public static String COMMON_HEADER_PARTIAL = "Common"; public static String COMMON_HEADER_FULL = COMMON_HEADER_PARTIAL + ".h"; // The target source folder for the translation - static to enable the IL1 // C translator to reference it public static IFolder targetSourceFolder = null; private static TaskingTranslationManager taskingTranslationManager = null; private static TargetLanguage targetLanguage = new TargetLanguage("FMI_C"); private static ArrayList<DocumentRoot> docRootList = new ArrayList<DocumentRoot>(); private Protected currentProtected; // Keep a local count here value references of variable arrays. // This is reset to zero for each machine. private int realVariableCount = 0; private int stringVariableCount = 0; private int integerVariableCount = 0; private int boolVariableCount = 0; private IProject targetProject = null; // Translate the selected Composed Machine/Event-B Machine to FMU(s) public void translateToFMU(IStructuredSelection s) throws TaskingTranslationException, BackingStoreException, CoreException, IOException, URISyntaxException, IL1TranslationUnhandledTypeException { this.setSelection(s); // Initialise the tasking translation manager Il1PackageImpl.init(); Il1Factory factory = Il1Factory.eINSTANCE; taskingTranslationManager = new TaskingTranslationManager(factory); // Generate an IL1 program using existing stage 1 code generator. Program program = translateEventBToIL1(s); // Create a target Directory createTargetProject(taskingTranslationManager); // From the program, we can create the modelDescription file createModelDescriptionFile(program); // we can generate the FMU from the IL1program. translateIL1ToFMU(program); // reflect the changes in the model, back to the workspace. updateResources(); } private void createTargetProject(TaskingTranslationManager taskingTranslationManager) throws CoreException, TaskingTranslationException { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); targetProject = root.getProject(TaskingTranslationManager.getProject() .getName() + "Targetx"); if (!targetProject.exists()) { targetProject.create(null); targetProject.open(null); if (!targetProject.hasNature("org.eclipse.cdt.core.cnature")) { IProjectDescription description = targetProject.getDescription(); String[] natures = description.getNatureIds(); String[] newNatures = new String[natures.length + 1]; System.arraycopy(natures, 0, newNatures, 0, natures.length); newNatures[natures.length] = "org.eclipse.cdt.core.cnature"; // We can put these back in if we decide to do managed builds etc. // newNatures[natures.length + 1] = "org.eclipse.cdt.managedbuilder.core.managedBuildNature"; // newNatures[natures.length + 2] = "org.eclipse.cdt.managedbuilder.core.ScannerConfigNature"; description.setNatureIds(newNatures); targetProject.setDescription(description, null); } } // create C source folder in the project called "src" for generated source // and external for inherited code createCSourceFolder(targetProject, "src"); createCSourceFolder(targetProject, "external"); } private void createCSourceFolder(IProject targetProject, String newDirectoryName) throws CoreException, CModelException { // obtain a model,project and folder CoreModel cModel = CoreModel.getDefault(); ICProject cProject = cModel.create(targetProject); // This is where this 'important' target source directory is created!!! targetSourceFolder = targetProject.getFolder(newDirectoryName); targetSourceFolder.create(true, true, null); // create a new sourceEntry (i.e. identifies this folder as a C source folder) ISourceEntry newSourceEntry = CoreModel .newSourceEntry(targetSourceFolder.getFullPath()); // now add it to the cProject info, by creating a new list of entries. IPathEntry[] existingPathEntries = cProject.getRawPathEntries(); List<IPathEntry> newEntries = new ArrayList<IPathEntry>( existingPathEntries.length); // add existingPathEntries to newEntries newEntries.addAll(Arrays.asList(existingPathEntries)); // add the new sourceEntry newEntries.add(newSourceEntry); // set the pathEntry values in the project cProject.setRawPathEntries( newEntries.toArray(new IPathEntry[newEntries.size()]), null); } private void createModelDescriptionFile(Program program) throws IOException, TaskingTranslationException, CModelException, CoreException { ArrayList<Machine> fmuMachineList = taskingTranslationManager .getFMUMachineList(); for (Machine fmuMachine : fmuMachineList) { // Reset the value reference array indices for each machine. realVariableCount = 0; stringVariableCount = 0; integerVariableCount = 0; boolVariableCount = 0; // Each fmuMachine will have its own DocumentRoot DocumentRoot docRoot = FmiModelFactory.eINSTANCE .createDocumentRoot(); // add this machine documentroot to the list docRootList.add(docRoot); // set various values FmiModelDescriptionType descriptionType = FmiModelFactory.eINSTANCE .createFmiModelDescriptionType(); docRoot.setFmiModelDescription(descriptionType); descriptionType.setFmiVersion("2.0"); descriptionType.setGenerationTool("EB2FMU"); descriptionType.setAuthor("University of Southampton"); XMLGregorianCalendar xmlGC = makeDate(); descriptionType.setGenerationDateAndTime(xmlGC); descriptionType.setGuid("GUID_" + fmuMachine.getName() + "_" + xmlGC.toXMLFormat()); descriptionType.setModelName(fmuMachine.getName()); // This is a co-simulation CoSimulationType coSimType = FmiModelFactory.eINSTANCE .createCoSimulationType(); descriptionType.getCoSimulation().add(coSimType); // This is where we store the FMI scalar variables ModelVariablesType modelVarsType = FmiModelFactory.eINSTANCE .createModelVariablesType(); descriptionType.setModelVariables(modelVarsType); // Get the root so we can obtain the type environment IRodinDB rodinDB = RodinCore.getRodinDB(); IRodinProject rodinProject = rodinDB.getRodinProject(program .getProjectName()); - IRodinFile mchFile = rodinProject.getRodinFile(fmuMachine + IRodinFile mchFile = rodinProject.getRodinFile(fmuMachine.getName() + ".bum"); MachineRoot root = (MachineRoot) mchFile.getRoot(); EList<Variable> variableList = fmuMachine.getVariables(); // get the FMI type from the type environment ITypeEnvironment typeEnv = taskingTranslationManager .getTypeEnvironment(root); // Iterate through the machine's variables and generate FMIScalar // values for (Variable var : variableList) { variableToFMIScalar(modelVarsType, typeEnv, var); } // create a descriptions folder. String fileName = fmuMachine.getName() + "." + FmiModelFactory.eINSTANCE.getEPackage().getName().toLowerCase(); File newFile = createNewFile(fileName, "descriptions"); String netUri = newFile.toURI().toString(); URI emfURI = URI.createURI(netUri); ResourceSet resSet = new ResourceSetImpl(); Resource resource = resSet.createResource(emfURI); resource.getContents().add(docRoot); resource.save(Collections.EMPTY_MAP); }// end of foreach machine }// end of createModelDescriptionFile(...); // create a new file, with fileName, in the named subFolder of 'the' targetProject. private File createNewFile(String fileName, String subFolderName) throws CoreException, IOException { IFolder newFolder = targetProject.getFolder(subFolderName); if (!newFolder.exists()) { newFolder.create(true, true, null); } // construct the new fileName for the model description String directoryPath = newFolder.getRawLocation().toString() + File.separatorChar; // construct the new fileName path for the model description String fPathName = directoryPath + fileName; File newFile = new File(fPathName); boolean success = newFile.createNewFile(); // force creation of a new file if (!success) { newFile.delete(); newFile.createNewFile(); } return newFile; } // The method populates the ModelVariables segment with scalar // variables, generated from the variable's type etc. private void variableToFMIScalar(ModelVariablesType modelVarsType, ITypeEnvironment typeEnv, Variable var) { Type type = typeEnv.getType(var.getName()); // Create and set an fmiScalar value for each variable FmiScalarVariable scalar = FmiModelFactory.eINSTANCE .createFmiScalarVariable(); modelVarsType.getScalarVariable().add(scalar); scalar.setName(var.getName()); String typeString = getFMITypeString(type); // Add a type if it is an integer if (typeString.equals(INTEGER)) { scalar.setValueReference(integerVariableCount); integerVariableCount++; IntegerType integerType = FmiModelFactory.eINSTANCE .createIntegerType(); scalar.setInteger(integerType); } // else if it is a real else if (typeString.equals(REAL)) { scalar.setValueReference(realVariableCount); realVariableCount++; RealType1 realType = FmiModelFactory.eINSTANCE.createRealType1(); scalar.setReal(realType); } // elseif it is a string else if (typeString.equals(STRING)) { scalar.setValueReference(stringVariableCount); stringVariableCount++; StringType stringType = FmiModelFactory.eINSTANCE .createStringType(); scalar.setString(stringType); } // elsif it is a boolean else if (typeString.equals(BOOLEAN)) { scalar.setValueReference(boolVariableCount); boolVariableCount++; BooleanType boolType = FmiModelFactory.eINSTANCE .createBooleanType(); scalar.setBoolean(boolType); } } public static String getFMIType(Type type) throws TaskingTranslationException { String fmiTypeName = null; String typeAsString = type.toString(); if (typeAsString.equalsIgnoreCase(CodeGenTaskingUtils.INT_SYMBOL)) { fmiTypeName = INTEGER; } else if (typeAsString .equalsIgnoreCase(CodeGenTaskingUtils.BOOL_SYMBOL)) { fmiTypeName = BOOLEAN; } else if (typeAsString.equalsIgnoreCase(STRING)) { fmiTypeName = STRING; } else if (typeAsString.equalsIgnoreCase(REAL)) { fmiTypeName = REAL; } if (fmiTypeName == null) { throw new TaskingTranslationException("FMI Type not found for: " + type.toString()); } else { return fmiTypeName; } } private XMLGregorianCalendar makeDate() { DatatypeFactory df = null; Date date = new Date(); try { df = DatatypeFactory.newInstance(); } catch (DatatypeConfigurationException dce) { throw new IllegalStateException( "Exception while obtaining DatatypeFactory instance", dce); } GregorianCalendar gc = new GregorianCalendar(); gc.setTimeInMillis(date.getTime()); XMLGregorianCalendar xmlGC = df.newXMLGregorianCalendar(gc); return xmlGC; } // This method translates Event-B models into an IL1 program private static Program translateEventBToIL1(IStructuredSelection s) throws TaskingTranslationException, BackingStoreException, CoreException, IOException, URISyntaxException { Object[] list = s.toArray(); // load all the machines into a pre-prepared structure. RMLDataStruct relevantMachines = RelevantMachineLoader .getAllRelevantMachines(list); list = relevantMachines.machines; ArrayList<ComposedMachine> composedMachines = relevantMachines.composedMachines; Map<String, String> composedEvents = relevantMachines.composedEvents; ArrayList<String> composedMachineNames = relevantMachines.composedMachineNames; IFile target = null; // Get target's location from the list which is derived from the // structured selection. for (Object obj : list) { if (obj instanceof MachineRoot) { target = ((MachineRoot) obj).getResource(); break; } else if (obj instanceof ContextRoot) { target = ((ContextRoot) obj).getResource(); break; } else if (obj instanceof ComposedMachineRoot) { target = ((ComposedMachineRoot) obj).getResource(); break; } } storeProject(target.getProject(), taskingTranslationManager); Program program = taskingTranslationManager.translateToIL1Entry(list, composedMachines, composedEvents, composedMachineNames, relevantMachines); // We delete the temporary subroutines EList<Protected> protectedList = program.getProtected(); for (Protected prot : protectedList) { EList<Subroutine> subroutineList = prot.getSubroutines(); List<Subroutine> tmpSubroutine = new ArrayList<Subroutine>(); for (Subroutine subroutine : subroutineList) { if (!subroutine.isTemporary()) { tmpSubroutine.add(subroutine); } } if (tmpSubroutine.size() != subroutineList.size()) { subroutineList.clear(); subroutineList.addAll(tmpSubroutine); } } saveBaseProgram(program, targetFile(target)); return program; } // This method is equivalent to CProgramIL1Translator, tailored for // use with FMI translation. private void translateIL1ToFMU(Program program) throws IL1TranslationUnhandledTypeException, RodinDBException, TaskingTranslationUnhandledTypeException { // Now to the code generation IL1TranslationManager il1TranslationManager = new IL1TranslationManager(); boolean hasBool = false; TreeIterator<EObject> programContentList = program.eAllContents(); while (programContentList.hasNext()) { EObject obj = programContentList.next(); if (obj instanceof Declaration) { Declaration decl = (Declaration) obj; if (decl.getType().equals(CodeGenTaskingUtils.BOOL_SYMBOL)) { hasBool = true; break; } } } // If we have any boolean variable then add the BOOL definitions if (hasBool) { // Output OpenMP blocking il1TranslationManager.addIncludeStatement("typedef int BOOL;"); il1TranslationManager.addIncludeStatement("#define TRUE 1"); il1TranslationManager.addIncludeStatement("#define FALSE 0"); } ArrayList<String> code = null; // Translation Rules Map<IProject, List<ITranslationRule>> translationRules = loadTranslatorRules(); il1TranslationManager.setTranslatorRules(translationRules); // Types Rules Map<IProject, List<ITranslationRule>> translationTypeRules = loadTranslatorTypeRules(); il1TranslationManager.setTranslatorTypeRules(translationTypeRules); String parentDirectoryPath = getFilePathFromSelected(); if (parentDirectoryPath != null) { // make the file system ready. String newDirectoryPath = FMUTranslator.targetSourceFolder.getRawLocation().toString() + File.separatorChar; ArrayList<ClassHeaderInformation> headerInfo = il1TranslationManager .getClassHeaderInformation(); EList<Protected> protectedList = program.getProtected(); // for each protected object for (Protected p : protectedList) { code = il1TranslationManager.translateIL1ElementToCode(p, getTargetLanguage()); code.add(0, "#include \"" + COMMON_HEADER_FULL + "\""); code.add("// EndProtected"); currentProtected = p; saveToFile(code, headerInfo, program, newDirectoryPath, il1TranslationManager); } } System.out.println(); } // Create the file associated with the output // The sourceRes is the container of the MainClass // element that we want to transform protected static String targetFile(IFile source) throws URISyntaxException { java.net.URI location = source.getLocationURI(); IPath p = new Path(location.getPath()); IPath newPath = p.removeFileExtension(); String path = newPath + ".il1"; return path; } protected static void saveBaseProgram(Program program, String filename) throws IOException { URI uri = URI.createFileURI(filename); Resource outResource = new XMLResourceFactoryImpl().createResource(uri); outResource.getContents().add(program); outResource.save(null); } private static void storeProject(IProject project, TaskingTranslationManager translationManager) { translationManager.setProject(project); } @Override protected TargetLanguage getTargetLanguage() { return targetLanguage; } @Override protected ArrayList<String> formatCode(ArrayList<String> code, IL1TranslationManager translationManager) { // TODO Auto-generated method stub return null; } // We override the saveToFile since we do not need to write tasks for FMU's // only protected objects. We also want to save the 'protected object' // code from shared machines since they map to the FMUs. We store the // 'protected object' code in a field, temporarily, in TranslateIL1ToFMU, // then call the saveToFile, and make use of it there rather than pass it // as a parameter. @Override protected void saveToFile(ArrayList<String> codeToSave, ArrayList<ClassHeaderInformation> headerInformation, Program program, String directoryName, IL1TranslationManager translationManager) { ArrayList<String> globalDecls = new ArrayList<String>(); for (int lineNumber = 0; lineNumber < codeToSave.size(); lineNumber++) { ArrayList<String> protectedCode = new ArrayList<String>(); // In the original code (the default C code) we used lineNumber + 1. // For FMUs we use lineNumber, to pick up the 'include "common.h"' // statement. lineNumber = getCodeBlock(codeToSave, lineNumber, "// EndProtected", protectedCode); // Get the protected name String name = currentProtected.getMachineName(); saveToFileHelper(protectedCode, name + ".c", directoryName); } // Generate the header files. // Each protected file just includes "common.h" which includes the other // files. generateHeaders(headerInformation, directoryName, translationManager, globalDecls); } private void generateHeaders( ArrayList<ClassHeaderInformation> headerInformation, String directoryName, IL1TranslationManager translationManager, ArrayList<String> globalDecls) { // Now sort out header files // For common header ClassHeaderInformation common = new ClassHeaderInformation(); common.className = COMMON_HEADER_PARTIAL; // wont use initial now, will add headers manually, then add common // class for compiler specific code common.functionDeclarations.addAll(translationManager .getIncludeStatements()); // Add any global declarations common.functionDeclarations.addAll(globalDecls); // Add the header files to include in the initial data for (ClassHeaderInformation c : headerInformation) { String headerName = c.className + ".h"; if (!headerName.equalsIgnoreCase("common.h")) { common.functionDeclarations.add("#include \"" + headerName + "\""); } } headerInformation.add(common); if (translationManager.getCompilerDependentExecutableCodeBlock().size() > 0) { ArrayList<String> commonCode = new ArrayList<String>(); // commonCode.add(codeGenerateTimestamp); commonCode.add("#include \"" + COMMON_HEADER_FULL + "\""); commonCode.addAll(formatCode(translationManager .getCompilerDependentExecutableCodeBlock(), translationManager)); this.saveToFileHelper(commonCode, "Common.c", directoryName); } // Save the header files for (ClassHeaderInformation c : headerInformation) { String headerName = c.className; String headerPreBlock = c.className.toUpperCase() + "_H"; ArrayList<String> headerCode = new ArrayList<String>(); // headerCode.add(codeGenerateTimestamp); headerCode.add("#ifndef " + headerPreBlock); headerCode.add("#define " + headerPreBlock); for (String i : c.functionDeclarations) { headerCode.add(i); } headerCode.add("#endif"); headerCode.add(""); // blank line this.saveToFileHelper(headerCode, headerName + ".h", directoryName); } } protected int getCodeBlock(ArrayList<String> codeIn, int startIdx, String endStatement, ArrayList<String> codeOut) { int endIdx = startIdx; for (int i = startIdx; i < codeIn.size() && !codeIn.get(i).equals(endStatement); i++, endIdx++) { codeOut.add(codeIn.get(i)); } return endIdx; } protected String getName(ArrayList<String> codeIn, String lhs) { // Find first occurence of the lhs string // As the first lines may be include / import statements for (String s : codeIn) { if (s.startsWith(lhs)) { return s.split(lhs)[1].trim(); } } return ""; // something went wrong } public static String getFMITypeString(Type type) { String fmiTypeName = null; String typeAsString = type.toString(); if (typeAsString.equalsIgnoreCase(CodeGenTaskingUtils.INT_SYMBOL)) { fmiTypeName = INTEGER; } else if (typeAsString .equalsIgnoreCase(CodeGenTaskingUtils.BOOL_SYMBOL)) { fmiTypeName = FMUTranslator.BOOLEAN; } else if (typeAsString.equalsIgnoreCase(STRING)) { fmiTypeName = STRING; } else if (typeAsString.equalsIgnoreCase(REAL)) { fmiTypeName = REAL; } return fmiTypeName; } }
true
true
private void createModelDescriptionFile(Program program) throws IOException, TaskingTranslationException, CModelException, CoreException { ArrayList<Machine> fmuMachineList = taskingTranslationManager .getFMUMachineList(); for (Machine fmuMachine : fmuMachineList) { // Reset the value reference array indices for each machine. realVariableCount = 0; stringVariableCount = 0; integerVariableCount = 0; boolVariableCount = 0; // Each fmuMachine will have its own DocumentRoot DocumentRoot docRoot = FmiModelFactory.eINSTANCE .createDocumentRoot(); // add this machine documentroot to the list docRootList.add(docRoot); // set various values FmiModelDescriptionType descriptionType = FmiModelFactory.eINSTANCE .createFmiModelDescriptionType(); docRoot.setFmiModelDescription(descriptionType); descriptionType.setFmiVersion("2.0"); descriptionType.setGenerationTool("EB2FMU"); descriptionType.setAuthor("University of Southampton"); XMLGregorianCalendar xmlGC = makeDate(); descriptionType.setGenerationDateAndTime(xmlGC); descriptionType.setGuid("GUID_" + fmuMachine.getName() + "_" + xmlGC.toXMLFormat()); descriptionType.setModelName(fmuMachine.getName()); // This is a co-simulation CoSimulationType coSimType = FmiModelFactory.eINSTANCE .createCoSimulationType(); descriptionType.getCoSimulation().add(coSimType); // This is where we store the FMI scalar variables ModelVariablesType modelVarsType = FmiModelFactory.eINSTANCE .createModelVariablesType(); descriptionType.setModelVariables(modelVarsType); // Get the root so we can obtain the type environment IRodinDB rodinDB = RodinCore.getRodinDB(); IRodinProject rodinProject = rodinDB.getRodinProject(program .getProjectName()); IRodinFile mchFile = rodinProject.getRodinFile(fmuMachine + ".bum"); MachineRoot root = (MachineRoot) mchFile.getRoot(); EList<Variable> variableList = fmuMachine.getVariables(); // get the FMI type from the type environment ITypeEnvironment typeEnv = taskingTranslationManager .getTypeEnvironment(root); // Iterate through the machine's variables and generate FMIScalar // values for (Variable var : variableList) { variableToFMIScalar(modelVarsType, typeEnv, var); } // create a descriptions folder. String fileName = fmuMachine.getName() + "." + FmiModelFactory.eINSTANCE.getEPackage().getName().toLowerCase(); File newFile = createNewFile(fileName, "descriptions"); String netUri = newFile.toURI().toString(); URI emfURI = URI.createURI(netUri); ResourceSet resSet = new ResourceSetImpl(); Resource resource = resSet.createResource(emfURI); resource.getContents().add(docRoot); resource.save(Collections.EMPTY_MAP); }// end of foreach machine }// end of createModelDescriptionFile(...);
private void createModelDescriptionFile(Program program) throws IOException, TaskingTranslationException, CModelException, CoreException { ArrayList<Machine> fmuMachineList = taskingTranslationManager .getFMUMachineList(); for (Machine fmuMachine : fmuMachineList) { // Reset the value reference array indices for each machine. realVariableCount = 0; stringVariableCount = 0; integerVariableCount = 0; boolVariableCount = 0; // Each fmuMachine will have its own DocumentRoot DocumentRoot docRoot = FmiModelFactory.eINSTANCE .createDocumentRoot(); // add this machine documentroot to the list docRootList.add(docRoot); // set various values FmiModelDescriptionType descriptionType = FmiModelFactory.eINSTANCE .createFmiModelDescriptionType(); docRoot.setFmiModelDescription(descriptionType); descriptionType.setFmiVersion("2.0"); descriptionType.setGenerationTool("EB2FMU"); descriptionType.setAuthor("University of Southampton"); XMLGregorianCalendar xmlGC = makeDate(); descriptionType.setGenerationDateAndTime(xmlGC); descriptionType.setGuid("GUID_" + fmuMachine.getName() + "_" + xmlGC.toXMLFormat()); descriptionType.setModelName(fmuMachine.getName()); // This is a co-simulation CoSimulationType coSimType = FmiModelFactory.eINSTANCE .createCoSimulationType(); descriptionType.getCoSimulation().add(coSimType); // This is where we store the FMI scalar variables ModelVariablesType modelVarsType = FmiModelFactory.eINSTANCE .createModelVariablesType(); descriptionType.setModelVariables(modelVarsType); // Get the root so we can obtain the type environment IRodinDB rodinDB = RodinCore.getRodinDB(); IRodinProject rodinProject = rodinDB.getRodinProject(program .getProjectName()); IRodinFile mchFile = rodinProject.getRodinFile(fmuMachine.getName() + ".bum"); MachineRoot root = (MachineRoot) mchFile.getRoot(); EList<Variable> variableList = fmuMachine.getVariables(); // get the FMI type from the type environment ITypeEnvironment typeEnv = taskingTranslationManager .getTypeEnvironment(root); // Iterate through the machine's variables and generate FMIScalar // values for (Variable var : variableList) { variableToFMIScalar(modelVarsType, typeEnv, var); } // create a descriptions folder. String fileName = fmuMachine.getName() + "." + FmiModelFactory.eINSTANCE.getEPackage().getName().toLowerCase(); File newFile = createNewFile(fileName, "descriptions"); String netUri = newFile.toURI().toString(); URI emfURI = URI.createURI(netUri); ResourceSet resSet = new ResourceSetImpl(); Resource resource = resSet.createResource(emfURI); resource.getContents().add(docRoot); resource.save(Collections.EMPTY_MAP); }// end of foreach machine }// end of createModelDescriptionFile(...);
diff --git a/org.eclipse.mylyn.java.ui/src/org/eclipse/mylyn/java/MylarChangeSetManager.java b/org.eclipse.mylyn.java.ui/src/org/eclipse/mylyn/java/MylarChangeSetManager.java index c50c5100f..0465753fc 100644 --- a/org.eclipse.mylyn.java.ui/src/org/eclipse/mylyn/java/MylarChangeSetManager.java +++ b/org.eclipse.mylyn.java.ui/src/org/eclipse/mylyn/java/MylarChangeSetManager.java @@ -1,150 +1,149 @@ /******************************************************************************* * Copyright (c) 2004 - 2005 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.java; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.core.resources.IResource; import org.eclipse.mylar.core.IMylarContext; import org.eclipse.mylar.core.IMylarContextListener; import org.eclipse.mylar.core.IMylarElement; import org.eclipse.mylar.core.IMylarStructureBridge; import org.eclipse.mylar.core.MylarPlugin; import org.eclipse.mylar.ide.MylarIdePlugin; import org.eclipse.mylar.tasklist.ITask; import org.eclipse.mylar.tasklist.MylarTasklistPlugin; import org.eclipse.team.core.TeamException; import org.eclipse.team.internal.ccvs.ui.CVSUIPlugin; import org.eclipse.team.internal.core.subscribers.SubscriberChangeSetCollector; /** * @author Mik Kersten */ public class MylarChangeSetManager implements IMylarContextListener { private SubscriberChangeSetCollector collector; private Map<ITask, TaskContextChangeSet> changeSets = new HashMap<ITask, TaskContextChangeSet>(); public MylarChangeSetManager() { this.collector = CVSUIPlugin.getPlugin().getChangeSetManager(); } public IResource[] getResources(ITask task) { TaskContextChangeSet changeSet = changeSets.get(task); if (changeSet != null) { return changeSet.getResources(); } else { return null; } } public void contextActivated(IMylarContext context) { try { ITask task = getTask(context); if (task == null) { MylarPlugin.log("could not resolve task for context", this); } else if (!changeSets.containsKey(task)) { TaskContextChangeSet changeSet = new TaskContextChangeSet(task, collector); changeSet.add(changeSet.getResources()); changeSets.put(task, changeSet); if (!collector.contains(changeSet)) collector.add(changeSet); } } catch (Exception e) { MylarPlugin.fail(e, "could not update change set", false); } } public void contextDeactivated(IMylarContext context) { // TODO: support multiple tasks for (ITask task : changeSets.keySet()) { collector.remove(changeSets.get(task)); } changeSets.clear(); } public List<TaskContextChangeSet> getChangeSets() { return new ArrayList<TaskContextChangeSet>(changeSets.values()); } private ITask getTask(IMylarContext context) { List<ITask> activeTasks = MylarTasklistPlugin.getTaskListManager().getTaskList().getActiveTasks(); // TODO: support multiple tasks if (activeTasks.size() > 0) { return activeTasks.get(0); } else { return null; } } public void presentationSettingsChanging(UpdateKind kind) { // TODO Auto-generated method stub } public void presentationSettingsChanged(UpdateKind kind) { // TODO Auto-generated method stub } public void interestChanged(IMylarElement element) { - System.err.println(">>> " + element); IMylarStructureBridge bridge = MylarPlugin.getDefault().getStructureBridge(element.getContentType()); if (bridge.isDocument(element.getHandleIdentifier())) { IResource resource = MylarIdePlugin.getDefault().getResourceForElement(element); if (resource != null) { for (TaskContextChangeSet changeSet: getChangeSets()) { if (!changeSet.contains(resource)) { try { if (element.getInterest().isInteresting()) { changeSet.add(new IResource[] { resource }); } else { changeSet.remove(resource); } } catch (TeamException e) { MylarPlugin.fail(e, "could not add resource to change set", false); } } } } } } public void interestChanged(List<IMylarElement> elements) { for (IMylarElement element : elements) { interestChanged(element); } } public void nodeDeleted(IMylarElement node) { // ignore } public void landmarkAdded(IMylarElement node) { // TODO Auto-generated method stub } public void landmarkRemoved(IMylarElement node) { // TODO Auto-generated method stub } public void edgesChanged(IMylarElement node) { // TODO Auto-generated method stub } }
true
true
public void interestChanged(IMylarElement element) { System.err.println(">>> " + element); IMylarStructureBridge bridge = MylarPlugin.getDefault().getStructureBridge(element.getContentType()); if (bridge.isDocument(element.getHandleIdentifier())) { IResource resource = MylarIdePlugin.getDefault().getResourceForElement(element); if (resource != null) { for (TaskContextChangeSet changeSet: getChangeSets()) { if (!changeSet.contains(resource)) { try { if (element.getInterest().isInteresting()) { changeSet.add(new IResource[] { resource }); } else { changeSet.remove(resource); } } catch (TeamException e) { MylarPlugin.fail(e, "could not add resource to change set", false); } } } } } }
public void interestChanged(IMylarElement element) { IMylarStructureBridge bridge = MylarPlugin.getDefault().getStructureBridge(element.getContentType()); if (bridge.isDocument(element.getHandleIdentifier())) { IResource resource = MylarIdePlugin.getDefault().getResourceForElement(element); if (resource != null) { for (TaskContextChangeSet changeSet: getChangeSets()) { if (!changeSet.contains(resource)) { try { if (element.getInterest().isInteresting()) { changeSet.add(new IResource[] { resource }); } else { changeSet.remove(resource); } } catch (TeamException e) { MylarPlugin.fail(e, "could not add resource to change set", false); } } } } } }
diff --git a/src/org/geworkbench/bison/datastructure/complex/panels/CSPanel.java b/src/org/geworkbench/bison/datastructure/complex/panels/CSPanel.java index e3ddb3ae..59f4c8d9 100755 --- a/src/org/geworkbench/bison/datastructure/complex/panels/CSPanel.java +++ b/src/org/geworkbench/bison/datastructure/complex/panels/CSPanel.java @@ -1,401 +1,401 @@ package org.geworkbench.bison.datastructure.complex.panels; import org.geworkbench.bison.datastructure.properties.DSNamed; /** * This class has a really odd design. Until we could get rid of it in the * future, this just describes as it is now: * * 1. It is basically a CSItemList<T>; * 2. It contains a DSItemList<DSPanel> called subPanels; * 3. There are in fact two different kinds of CSPanel: * (a) the special one (called 'selection panel'): its label is "Selection" and its subPanels are empty * (b) the 'regular' ones: its subPanel always contains one special CSPanel (the 'selection panel') besides other DSPanel's * * activeSubset() creates another even more special kind of CSPanel. See mode detail in activeSubset's comments. * * CSItemList is already convolved and dangerous; CSPanel makes it worse. * Whenever possible, use CSItemList instead of CSPanel; java.util.ArrayList instead of CSItemList. * * $Id$ */ public class CSPanel <T extends DSNamed> extends CSItemList<T> implements DSPanel<T> { private static final long serialVersionUID = 8634609117930075231L; private String label = ""; private String subLabel = ""; private boolean active = false; private int serial = 0; /** * Used in the implementation of the <code>Identifiable</code> interface. */ private String panelId = null; /** * Used in the implementation of the <code>Describable</code> interface. */ private String description = null; /** * The subPanels */ private DSItemList<DSPanel<T>> subPanels = new CSItemList<DSPanel<T>>(); /** * The manually selected items */ protected DSPanel<T> selection;// selected markerset // TODO - watkin - revisit the concept of the "selection" panel private CSPanel(boolean selection) { label = "Selection"; } /** * Constructs a new CSPanel. */ public CSPanel() { selection = new CSPanel<T>(true); subPanels.add(selection); } /** * Constructs a new CSPanel with the specified label. * * @param label the label for this CSPanel. */ public CSPanel(String label) { this.label = label; selection = new CSPanel<T>(true); subPanels.add(selection); } /** * Constructs a new CSPanel with the specified label and sublabel. * * @param label the label for this CSPanel. * @param subLabel the sublabel for this CSPanel. */ public CSPanel(String label, String subLabel) { this.label = label; this.subLabel = subLabel; selection = new CSPanel<T>(true); subPanels.add(selection); } /** * Creates a CSPanel from an existing panel. * * @param panel the panel from which to create this CSPanel. */ public CSPanel(DSPanel<T> panel) { setLabel(panel.getLabel()); setSubLabel(panel.getSubLabel()); addAll(panel); setActive(true); } @Override public int size() { int n = super.size(); for (DSPanel<T> panel : subPanels) { if (panel.isActive()) { n += panel.size(); } } return n; } public T getProperItem(int index) { return super.get(index); } public int getNumberOfProperItems() { return super.size(); } /** * Gets the item from by index. * * @param index the index of the item * @return the item, or <code>null</code> if not found. */ @Override public T get(int index) { int n = super.size(); if (index < n) { return super.get(index); } else { index -= n; for (DSPanel<T> panel : subPanels) { if (panel.isActive()) { int size = panel.size(); if (index < size) { return panel.get(index); } else { index -= size; } } } throw new IndexOutOfBoundsException("Index out of bounds: " + index); } } @Override public int indexOf(Object item) { int index = super.indexOf(item); if (index != -1) { return index; } else { int offset = super.size(); for (DSPanel<T> panel : subPanels) { if (panel.isActive()) { index = panel.indexOf(item); if (index != -1) { return index + offset; } else { offset += panel.size(); } } } return -1; } } public boolean isBoundary(int index) { int n = super.size(); if (index < n) { return false; } else { index -= n; for (DSPanel<T> panel : subPanels) { if (panel.isActive()) { int size = panel.size(); if (index == size - 1) { return true; } else { if (index > size) { index -= size; } else { return false; } } } } return false; } } /** * Gets the label for this panel. * * @return label the label for this panel. */ public String getLabel() { return label; } /** * Clears all data from this panel and all sub-panels. */ @Override public void clear() { super.clear(); subPanels.clear(); } /** * Sets the label for this panel. * * @param label the new label for this panel. */ public void setLabel(String label) { this.label = new String(label); } /** * Get all sub-panels for this panel. * * @return */ public DSItemList<DSPanel<T>> panels() { return subPanels; } /** * Get the panel that contains the given item. * * @param item the item for which to search. * @return the panel in which the item resides, or <code>null</code> if the item was not found. */ public DSPanel<T> getPanel(T item) { for (DSPanel<T> panel : subPanels) { if (panel.contains(item)) { return panel; } } return null; } /** * Gets the special 'selection' panel. * * @return the selection panel. */ public DSPanel<T> getSelection() { return selection; } /** * Gets the sub-label for this panel. * * @return the sub-label for this panel. */ public String getSubLabel() { return subLabel; } /** * Sets the sub-label for this panel. * * @param label the new sub-label. */ public void setSubLabel(String label) { subLabel = new String(label); } /** * Sets this <code>Panel</code> to be 'Active' or 'Inactive'. * * @param flag activation state of this panel: <code>true</code> for 'Active', <code>false</code> for 'Inactive'. */ public void setActive(boolean flag) { active = flag; } /** * Obtains the activation state of this <code>Panel</code> * * @return activation state either <code>true</code> for 'Active', * <code>false</code> for 'Inactive'. */ public boolean isActive() { return active; } /** * Gets the <code>String</code> representation of this <code>Panel</code>. * * @return <code>String</code> representation of this <code>Panel</code>. */ public String toString() { return label + " [" + size() + "]"; } /** * Two panels are equal if their labels are identical. * * @param o object with which to compare. * @return <code>true</code> if the object is a {@link DSPanel} and its label is the same as this panel's label. */ @SuppressWarnings("unchecked") public boolean equals(Object o) { if (o instanceof DSPanel && this.getLabel() != null && this.getSubLabel() != null) { return (this.getLabel().equalsIgnoreCase(((DSPanel<T>) o).getLabel()) && this.getSubLabel().equalsIgnoreCase(((DSPanel<T>) o).getSubLabel())); } return false; } @Override public int hashCode() { return getLabel().hashCode(); } /** * Returns the ID for this panel. * * @return the ID of the panel. */ public String getID() { return panelId; } /** * Sets the ID of this panel * * @param id the new ID. */ public void setID(String id) { panelId = id; } /** * Adds a description to this panel. * * @param description the new description to add. */ public void setDescription(String description) { this.description = description; } /** * Gets all descriptions for the panel. * * @return the array of descriptions. */ public String getDescription() { return description; } /** * Gets the index of this object in its ordered container. * * @return the serial (or index) of this object. */ public int getSerial() { return serial; } /** * Sets the index of this object in its ordered container. * * @param i the new serial (or index). */ public void setSerial(int i) { serial = i; } /** * Gets all the active sub-panels of the panel. * * @return the active panels contained by this panel. */ public DSPanel<T> activeSubset() { /* * I simplified the code based on the existing behavior, which may not * be completely intentional in the first place: activePanels returned * from this method is really different from those constructed * otherwise, summarized in the class comment I wrote. It has subPanels, * but the subPanels does not contains selection panel. However, I have * to leave the behavior as it is because other code, e.g. ANOVA * analysis, depends on the current behavior to work correctly. */ CSPanel<T> activePanels = new CSPanel<T>(label); // Include selection if it is activated if (selection.isActive()) { activePanels.selection = selection; } /* * The original 'selection panel' is removed. It seems obvious that we * should use the constructor that does not create 'selection panel', * CSPanel(true). Unfortunately, some other code, at least * AnnotationPanel2.java depends (incorrectly) on that fact that * 'selection' has been initialized for this CSPanel (not the new * activePanels we are constructing here). */ - activePanels.panels().remove(0); + activePanels.panels().remove(selection); activePanels.setActive(true); for (DSPanel<T> panel : subPanels) { if (panel.isActive()) activePanels.panels().add(panel); } return activePanels; } }
true
true
public DSPanel<T> activeSubset() { /* * I simplified the code based on the existing behavior, which may not * be completely intentional in the first place: activePanels returned * from this method is really different from those constructed * otherwise, summarized in the class comment I wrote. It has subPanels, * but the subPanels does not contains selection panel. However, I have * to leave the behavior as it is because other code, e.g. ANOVA * analysis, depends on the current behavior to work correctly. */ CSPanel<T> activePanels = new CSPanel<T>(label); // Include selection if it is activated if (selection.isActive()) { activePanels.selection = selection; } /* * The original 'selection panel' is removed. It seems obvious that we * should use the constructor that does not create 'selection panel', * CSPanel(true). Unfortunately, some other code, at least * AnnotationPanel2.java depends (incorrectly) on that fact that * 'selection' has been initialized for this CSPanel (not the new * activePanels we are constructing here). */ activePanels.panels().remove(0); activePanels.setActive(true); for (DSPanel<T> panel : subPanels) { if (panel.isActive()) activePanels.panels().add(panel); } return activePanels; }
public DSPanel<T> activeSubset() { /* * I simplified the code based on the existing behavior, which may not * be completely intentional in the first place: activePanels returned * from this method is really different from those constructed * otherwise, summarized in the class comment I wrote. It has subPanels, * but the subPanels does not contains selection panel. However, I have * to leave the behavior as it is because other code, e.g. ANOVA * analysis, depends on the current behavior to work correctly. */ CSPanel<T> activePanels = new CSPanel<T>(label); // Include selection if it is activated if (selection.isActive()) { activePanels.selection = selection; } /* * The original 'selection panel' is removed. It seems obvious that we * should use the constructor that does not create 'selection panel', * CSPanel(true). Unfortunately, some other code, at least * AnnotationPanel2.java depends (incorrectly) on that fact that * 'selection' has been initialized for this CSPanel (not the new * activePanels we are constructing here). */ activePanels.panels().remove(selection); activePanels.setActive(true); for (DSPanel<T> panel : subPanels) { if (panel.isActive()) activePanels.panels().add(panel); } return activePanels; }
diff --git a/core/src/main/java/org/seventyeight/web/actions/AbstractUploadAction.java b/core/src/main/java/org/seventyeight/web/actions/AbstractUploadAction.java index 03a2f87..e4f8e19 100644 --- a/core/src/main/java/org/seventyeight/web/actions/AbstractUploadAction.java +++ b/core/src/main/java/org/seventyeight/web/actions/AbstractUploadAction.java @@ -1,109 +1,109 @@ package org.seventyeight.web.actions; import com.google.gson.JsonObject; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang.math.IEEE754rUtils; import org.apache.log4j.Logger; import org.omg.CosNaming.NamingContextExtPackage.StringNameHelper; import org.seventyeight.database.mongodb.MongoDocument; import org.seventyeight.utils.PostMethod; import org.seventyeight.web.Core; import org.seventyeight.web.model.Action; import org.seventyeight.web.model.Authorizer; import org.seventyeight.web.model.Node; import org.seventyeight.web.servlet.Request; import org.seventyeight.web.servlet.Response; import org.seventyeight.web.utilities.JsonException; import org.seventyeight.web.utilities.JsonUtils; import org.seventyeight.web.utilities.ServletUtils; import java.io.File; import java.util.List; /** * @author cwolfgang */ public abstract class AbstractUploadAction<T extends AbstractUploadAction<T>> extends Action<T> { private static Logger logger = Logger.getLogger( AbstractUploadAction.class ); protected AbstractUploadAction( Node parent, MongoDocument document ) { super( parent, document ); } public abstract File getPath(); public abstract String getRelativePath(); /** * Get the filename for the upload. The filename must not contain the extension. * @param thisFilename The uploaded filename without extension * @return An extensionless filename */ public abstract String getFilename( String thisFilename ); public abstract Authorizer.Authorization getUploadAuthorization(); @PostMethod public void doUpload( Request request, Response response ) throws Exception { request.checkAuthorization( getParent(), getUploadAuthorization() ); logger.debug( "Uploading file" ); //String relativePath = request.getUser().getIdentifier(); File path = new File( getPath(), getRelativePath() ); if( !path.exists() && !path.mkdirs() ) { throw new IllegalStateException( "Unable to create path " + path.toString() ); } List<String> uploadedFilenames = ServletUtils.upload( request, path, true, 1 ); logger.debug( "Filenames: " + uploadedFilenames ); if( uploadedFilenames.size() > 0 ) { String ext = "." + FilenameUtils.getExtension( uploadedFilenames.get( 0 ) ); /* Rename */ - String fname = FilenameUtils.getBaseName( uploadedFilenames.get( 0 ) ); - File f = new File( path, getFilename( fname ) + ext ); + String fname = getFilename( FilenameUtils.getBaseName( uploadedFilenames.get( 0 ) ) ) + ext; + File f = new File( path, fname ); f.delete(); FileUtils.moveFile( new File( path, uploadedFilenames.get( 0 ) ), f ); setExtension( ext ); setFile( new File( getRelativePath(), fname ).toString() ); try { JsonObject json = JsonUtils.getJsonFromRequest( request ); save( request, json ); Core.superSave( this ); } catch( JsonException e ) { logger.warn( "Json is null: " + e.getMessage() ); save( request, null ); Core.superSave( this ); } } else { throw new IllegalStateException( "No file uploaded" ); } response.sendRedirect( "" ); } public void setFile( String file ) { logger.debug( "Setting file to " + file ); document.set( "file", file ); } public void setExtension( String extension ) { document.set( "ext", extension ); } public String getExtension() { return document.get( "ext", "" ); } public void onUpload() { /* Default implementation is a no op, for now. */ } //public abstract boolean allowMultiple(); }
true
true
public void doUpload( Request request, Response response ) throws Exception { request.checkAuthorization( getParent(), getUploadAuthorization() ); logger.debug( "Uploading file" ); //String relativePath = request.getUser().getIdentifier(); File path = new File( getPath(), getRelativePath() ); if( !path.exists() && !path.mkdirs() ) { throw new IllegalStateException( "Unable to create path " + path.toString() ); } List<String> uploadedFilenames = ServletUtils.upload( request, path, true, 1 ); logger.debug( "Filenames: " + uploadedFilenames ); if( uploadedFilenames.size() > 0 ) { String ext = "." + FilenameUtils.getExtension( uploadedFilenames.get( 0 ) ); /* Rename */ String fname = FilenameUtils.getBaseName( uploadedFilenames.get( 0 ) ); File f = new File( path, getFilename( fname ) + ext ); f.delete(); FileUtils.moveFile( new File( path, uploadedFilenames.get( 0 ) ), f ); setExtension( ext ); setFile( new File( getRelativePath(), fname ).toString() ); try { JsonObject json = JsonUtils.getJsonFromRequest( request ); save( request, json ); Core.superSave( this ); } catch( JsonException e ) { logger.warn( "Json is null: " + e.getMessage() ); save( request, null ); Core.superSave( this ); } } else { throw new IllegalStateException( "No file uploaded" ); } response.sendRedirect( "" ); }
public void doUpload( Request request, Response response ) throws Exception { request.checkAuthorization( getParent(), getUploadAuthorization() ); logger.debug( "Uploading file" ); //String relativePath = request.getUser().getIdentifier(); File path = new File( getPath(), getRelativePath() ); if( !path.exists() && !path.mkdirs() ) { throw new IllegalStateException( "Unable to create path " + path.toString() ); } List<String> uploadedFilenames = ServletUtils.upload( request, path, true, 1 ); logger.debug( "Filenames: " + uploadedFilenames ); if( uploadedFilenames.size() > 0 ) { String ext = "." + FilenameUtils.getExtension( uploadedFilenames.get( 0 ) ); /* Rename */ String fname = getFilename( FilenameUtils.getBaseName( uploadedFilenames.get( 0 ) ) ) + ext; File f = new File( path, fname ); f.delete(); FileUtils.moveFile( new File( path, uploadedFilenames.get( 0 ) ), f ); setExtension( ext ); setFile( new File( getRelativePath(), fname ).toString() ); try { JsonObject json = JsonUtils.getJsonFromRequest( request ); save( request, json ); Core.superSave( this ); } catch( JsonException e ) { logger.warn( "Json is null: " + e.getMessage() ); save( request, null ); Core.superSave( this ); } } else { throw new IllegalStateException( "No file uploaded" ); } response.sendRedirect( "" ); }
diff --git a/bundles/org.eclipse.wst.xsd.ui/src-adt-xsd/org/eclipse/wst/xsd/ui/internal/editor/XSDEditorPlugin.java b/bundles/org.eclipse.wst.xsd.ui/src-adt-xsd/org/eclipse/wst/xsd/ui/internal/editor/XSDEditorPlugin.java index e0a601708..573714969 100644 --- a/bundles/org.eclipse.wst.xsd.ui/src-adt-xsd/org/eclipse/wst/xsd/ui/internal/editor/XSDEditorPlugin.java +++ b/bundles/org.eclipse.wst.xsd.ui/src-adt-xsd/org/eclipse/wst/xsd/ui/internal/editor/XSDEditorPlugin.java @@ -1,272 +1,274 @@ /******************************************************************************* * Copyright (c) 2001, 2006 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.xsd.ui.internal.editor; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.plugin.*; import org.eclipse.wst.xsd.ui.internal.common.properties.sections.appinfo.ExtensionsSchemasRegistry; import org.eclipse.core.runtime.Platform; import org.eclipse.emf.edit.ui.provider.ExtendedImageRegistry; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.ImageRegistry; import org.osgi.framework.BundleContext; import java.net.MalformedURLException; import java.net.URL; import java.text.MessageFormat; import java.util.*; public class XSDEditorPlugin extends AbstractUIPlugin { public static final String PLUGIN_ID = "org.eclipse.wst.xsd.ui"; public static final String CONST_XSD_DEFAULT_PREFIX_TEXT = "org.eclipse.wst.xmlschema.xsdDefaultPrefixText"; public static final String CONST_PREFERED_BUILT_IN_TYPES = "org.eclipse.wst.xmlschema.preferedBuiltInTypes"; public static final String CUSTOM_LIST_SEPARATOR = "\n"; public static final String EXTENSIONS_SCHEMAS_EXTENSIONID = "org.eclipse.wst.xsd.ui.ExtensionsSchemasDescription"; public final static String DEFAULT_TARGET_NAMESPACE = "http://www.example.org"; //The shared instance. private static XSDEditorPlugin plugin; //Resource bundle. private ResourceBundle resourceBundle; private ExtensionsSchemasRegistry registry; private XSDEditorConfiguration xsdEditorConfiguration = null; public static final String CONST_USE_SIMPLE_EDIT_MODE = PLUGIN_ID + ".useSimpleEditMode"; public static final String CONST_SHOW_INHERITED_CONTENT = PLUGIN_ID + ".showInheritedContent"; public static final String CONST_XSD_LANGUAGE_QUALIFY = "org.eclipse.wst.xmlschema.xsdQualify"; public static final String CONST_DEFAULT_TARGET_NAMESPACE = "org.eclipse.wst.xmlschema.defaultTargetnamespaceText"; /** * The constructor. */ public XSDEditorPlugin() { super(); plugin = this; } /** * This method is called upon plug-in activation */ public void start(BundleContext context) throws Exception { super.start(context); } /** * This method is called when the plug-in is stopped */ public void stop(BundleContext context) throws Exception { super.stop(context); plugin = null; resourceBundle = null; } /** * Returns the shared instance. */ public static XSDEditorPlugin getDefault() { return plugin; } /** * Returns the string from the plugin's resource bundle, * or 'key' if not found. */ public static String getResourceString(String key) { ResourceBundle bundle = XSDEditorPlugin.getDefault().getResourceBundle(); try { return (bundle != null) ? bundle.getString(key) : key; } catch (MissingResourceException e) { return key; } } public static String getResourceString(String key, Object o) { return getResourceString(key, new Object[] { o}); } public static String getResourceString(String key, Object[] objects) { return MessageFormat.format(getResourceString(key), objects); } public static String getResourceString(String key, Object o1, Object o2) { return getResourceString(key, new Object[] { o1, o2}); } /** * Returns the plugin's resource bundle, */ public ResourceBundle getResourceBundle() { try { if (resourceBundle == null) // resourceBundle = ResourceBundle.getBundle("org.eclipse.wst.xsd.ui.internal.editor.EditorPluginResources"); resourceBundle = Platform.getResourceBundle(getBundle()); } catch (MissingResourceException x) { resourceBundle = null; } return resourceBundle; } /** * Returns an image descriptor for the image file at the given * plug-in relative path. * * @param path the path * @return the image descriptor */ public static ImageDescriptor getImageDescriptor(String path) { return AbstractUIPlugin.imageDescriptorFromPlugin("org.eclipse.wst.xsd.ui", path); } public static ImageDescriptor getImageDescriptor(String name, boolean getBaseURL) { try { URL installURL = getDefault().getBundle().getEntry("/"); //$NON-NLS-1$ String imageString = getBaseURL ? "icons/" + name : name; URL imageURL = new URL(installURL, imageString); return ImageDescriptor.createFromURL(imageURL); } catch (MalformedURLException e) { return null; } } public static XSDEditorPlugin getPlugin() { return plugin; } public static String getXSDString(String key) { return getResourceString(key); } /** * This gets the string resource and does one substitution. */ public String getString(String key, Object s1) { return MessageFormat.format(Platform.getResourceBundle(getBundle()).getString(key), new Object[]{s1}); } public static Image getXSDImage(String iconName) { return getDefault().getImage(iconName); } public Image getImage(String iconName) { ImageRegistry imageRegistry = getImageRegistry(); if (imageRegistry.get(iconName) != null) { return imageRegistry.get(iconName); } else { imageRegistry.put(iconName, ImageDescriptor.createFromFile(getClass(), iconName)); return imageRegistry.get(iconName); } } public URL getBaseURL() { return getDescriptor().getInstallURL(); } public Image getIconImage(String object) { try { return ExtendedImageRegistry.getInstance().getImage(new URL(getBaseURL() + "icons/" + object + ".gif")); } catch (MalformedURLException exception) { System.out.println("Failed to load image for '" + object + "'"); } return null; } public boolean getShowInheritedContent() { return getPreferenceStore().getBoolean(CONST_SHOW_INHERITED_CONTENT); } protected void initializeDefaultPreferences(IPreferenceStore store) { store.setDefault(CONST_SHOW_INHERITED_CONTENT, false); store.setDefault(CONST_XSD_DEFAULT_PREFIX_TEXT, "xsd"); + store.setDefault(CONST_XSD_LANGUAGE_QUALIFY, false); + store.setDefault(CONST_DEFAULT_TARGET_NAMESPACE, DEFAULT_TARGET_NAMESPACE); //Even the last item in the list must contain a trailing List separator store.setDefault(CONST_PREFERED_BUILT_IN_TYPES, "boolean"+ CUSTOM_LIST_SEPARATOR + "date" + CUSTOM_LIST_SEPARATOR + "dateTime" + CUSTOM_LIST_SEPARATOR + "double" + CUSTOM_LIST_SEPARATOR + "float" + CUSTOM_LIST_SEPARATOR + "hexBinary" + CUSTOM_LIST_SEPARATOR + "int" + CUSTOM_LIST_SEPARATOR + "string" + CUSTOM_LIST_SEPARATOR + "time" + CUSTOM_LIST_SEPARATOR); } public ExtensionsSchemasRegistry getExtensionsSchemasRegistry() { if (registry == null) { registry = new ExtensionsSchemasRegistry(EXTENSIONS_SCHEMAS_EXTENSIONID); } return registry; } public XSDEditorConfiguration getXSDEditorConfiguration() { if (xsdEditorConfiguration == null) { xsdEditorConfiguration = new XSDEditorConfiguration(); } return xsdEditorConfiguration; } /** * Get the xml schema default namespace prefix */ public String getXMLSchemaPrefix() { return getPreferenceStore().getString(CONST_XSD_DEFAULT_PREFIX_TEXT); } /** * Get the xml schema default target namespace */ public String getXMLSchemaTargetNamespace() { String targetNamespace = getPreferenceStore().getString(CONST_DEFAULT_TARGET_NAMESPACE); if (!targetNamespace.endsWith("/")) { targetNamespace = targetNamespace + "/"; } return targetNamespace; } /** * Get the xml schema language qualification */ public boolean isQualifyXMLSchemaLanguage() { return getPreferenceStore().getBoolean(CONST_XSD_LANGUAGE_QUALIFY); } public static Shell getShell() { return getPlugin().getWorkbench().getActiveWorkbenchWindow().getShell(); } }
true
true
protected void initializeDefaultPreferences(IPreferenceStore store) { store.setDefault(CONST_SHOW_INHERITED_CONTENT, false); store.setDefault(CONST_XSD_DEFAULT_PREFIX_TEXT, "xsd"); //Even the last item in the list must contain a trailing List separator store.setDefault(CONST_PREFERED_BUILT_IN_TYPES, "boolean"+ CUSTOM_LIST_SEPARATOR + "date" + CUSTOM_LIST_SEPARATOR + "dateTime" + CUSTOM_LIST_SEPARATOR + "double" + CUSTOM_LIST_SEPARATOR + "float" + CUSTOM_LIST_SEPARATOR + "hexBinary" + CUSTOM_LIST_SEPARATOR + "int" + CUSTOM_LIST_SEPARATOR + "string" + CUSTOM_LIST_SEPARATOR + "time" + CUSTOM_LIST_SEPARATOR); }
protected void initializeDefaultPreferences(IPreferenceStore store) { store.setDefault(CONST_SHOW_INHERITED_CONTENT, false); store.setDefault(CONST_XSD_DEFAULT_PREFIX_TEXT, "xsd"); store.setDefault(CONST_XSD_LANGUAGE_QUALIFY, false); store.setDefault(CONST_DEFAULT_TARGET_NAMESPACE, DEFAULT_TARGET_NAMESPACE); //Even the last item in the list must contain a trailing List separator store.setDefault(CONST_PREFERED_BUILT_IN_TYPES, "boolean"+ CUSTOM_LIST_SEPARATOR + "date" + CUSTOM_LIST_SEPARATOR + "dateTime" + CUSTOM_LIST_SEPARATOR + "double" + CUSTOM_LIST_SEPARATOR + "float" + CUSTOM_LIST_SEPARATOR + "hexBinary" + CUSTOM_LIST_SEPARATOR + "int" + CUSTOM_LIST_SEPARATOR + "string" + CUSTOM_LIST_SEPARATOR + "time" + CUSTOM_LIST_SEPARATOR); }
diff --git a/impl/src/main/java/ceylon/modules/jboss/runtime/AbstractJBossRuntime.java b/impl/src/main/java/ceylon/modules/jboss/runtime/AbstractJBossRuntime.java index 71f7205..4f404b9 100644 --- a/impl/src/main/java/ceylon/modules/jboss/runtime/AbstractJBossRuntime.java +++ b/impl/src/main/java/ceylon/modules/jboss/runtime/AbstractJBossRuntime.java @@ -1,128 +1,128 @@ /* * Copyright 2011 Red Hat inc. and third party contributors as noted * by the author tags. * * 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 ceylon.modules.jboss.runtime; import org.jboss.modules.Module; import org.jboss.modules.ModuleIdentifier; import org.jboss.modules.ModuleLoader; import org.jboss.modules.ModuleNotFoundException; import ceylon.modules.CeylonRuntimeException; import ceylon.modules.Configuration; import ceylon.modules.Main; import ceylon.modules.api.runtime.AbstractRuntime; import com.redhat.ceylon.cmr.api.Logger; import com.redhat.ceylon.cmr.api.RepositoryManager; import com.redhat.ceylon.cmr.api.RepositoryManagerBuilder; import com.redhat.ceylon.cmr.ceylon.CeylonUtils; import com.redhat.ceylon.cmr.impl.JULLogger; import com.redhat.ceylon.cmr.spi.ContentTransformer; import com.redhat.ceylon.cmr.spi.MergeStrategy; /** * Abstract Ceylon JBoss Modules runtime. * Useful for potential extension. * * @author <a href="mailto:[email protected]">Ales Justin</a> */ public abstract class AbstractJBossRuntime extends AbstractRuntime { @Override public ClassLoader createClassLoader(String name, String version, Configuration conf) throws Exception { ModuleLoader moduleLoader = createModuleLoader(conf); ModuleIdentifier moduleIdentifier; try{ moduleIdentifier = ModuleIdentifier.fromString(name + ":" + version); }catch(IllegalArgumentException x){ CeylonRuntimeException cre = new CeylonRuntimeException("Invalid module name or version: contains invalid characters"); cre.initCause(x); throw cre; } try { Module module = moduleLoader.loadModule(moduleIdentifier); return SecurityActions.getClassLoader(module); } catch (ModuleNotFoundException e) { - String spec = name; + String spec = e.getMessage().replace(':', '/'); String hint = ""; if (RepositoryManager.DEFAULT_MODULE.equals(name)) { if (version != null) hint = " (default module should not have any version)"; } else if (version != null) { - spec += "/" + version; hint = " (invalid version?)"; } else { + spec = spec.replace("/null", ""); hint = " (missing required version, try " + spec + "/version)"; } final CeylonRuntimeException cre = new CeylonRuntimeException("Could not find module: " + spec + hint); cre.initCause(e); throw cre; } } /** * Get repository extension. * * @param conf the configuration * @return repository extension */ protected RepositoryManager createRepository(Configuration conf) { Logger log = new JULLogger(); final RepositoryManagerBuilder builder = CeylonUtils.repoManager() .systemRepo(conf.systemRepository) .userRepos(conf.repositories) .logger(log) .buildManagerBuilder(); final MergeStrategy ms = getService(MergeStrategy.class, conf); if (ms != null) builder.mergeStrategy(ms); if (conf.cacheContent) builder.cacheContent(); final ContentTransformer ct = getService(ContentTransformer.class, conf); if (ct != null) builder.contentTransformer(ct); return builder.buildRepository(); } /** * Get repository service. * * @param serviceType the service type * @param conf the configuration * @return service instance or null */ protected <T> T getService(Class<T> serviceType, Configuration conf) { try { String impl = conf.impl.get(serviceType.getName()); return (impl != null) ? Main.createInstance(serviceType, impl) : null; } catch (Exception e) { throw new IllegalArgumentException("Cannot instantiate service: " + serviceType.getName(), e); } } /** * Create module loader. * * @param conf the configuration * @return the module loader */ protected abstract ModuleLoader createModuleLoader(Configuration conf); }
false
true
public ClassLoader createClassLoader(String name, String version, Configuration conf) throws Exception { ModuleLoader moduleLoader = createModuleLoader(conf); ModuleIdentifier moduleIdentifier; try{ moduleIdentifier = ModuleIdentifier.fromString(name + ":" + version); }catch(IllegalArgumentException x){ CeylonRuntimeException cre = new CeylonRuntimeException("Invalid module name or version: contains invalid characters"); cre.initCause(x); throw cre; } try { Module module = moduleLoader.loadModule(moduleIdentifier); return SecurityActions.getClassLoader(module); } catch (ModuleNotFoundException e) { String spec = name; String hint = ""; if (RepositoryManager.DEFAULT_MODULE.equals(name)) { if (version != null) hint = " (default module should not have any version)"; } else if (version != null) { spec += "/" + version; hint = " (invalid version?)"; } else { hint = " (missing required version, try " + spec + "/version)"; } final CeylonRuntimeException cre = new CeylonRuntimeException("Could not find module: " + spec + hint); cre.initCause(e); throw cre; } }
public ClassLoader createClassLoader(String name, String version, Configuration conf) throws Exception { ModuleLoader moduleLoader = createModuleLoader(conf); ModuleIdentifier moduleIdentifier; try{ moduleIdentifier = ModuleIdentifier.fromString(name + ":" + version); }catch(IllegalArgumentException x){ CeylonRuntimeException cre = new CeylonRuntimeException("Invalid module name or version: contains invalid characters"); cre.initCause(x); throw cre; } try { Module module = moduleLoader.loadModule(moduleIdentifier); return SecurityActions.getClassLoader(module); } catch (ModuleNotFoundException e) { String spec = e.getMessage().replace(':', '/'); String hint = ""; if (RepositoryManager.DEFAULT_MODULE.equals(name)) { if (version != null) hint = " (default module should not have any version)"; } else if (version != null) { hint = " (invalid version?)"; } else { spec = spec.replace("/null", ""); hint = " (missing required version, try " + spec + "/version)"; } final CeylonRuntimeException cre = new CeylonRuntimeException("Could not find module: " + spec + hint); cre.initCause(e); throw cre; } }
diff --git a/src/test/org/apache/hadoop/util/TestQueueProcessingStatistics.java b/src/test/org/apache/hadoop/util/TestQueueProcessingStatistics.java index 9a404fc29..2c32bf9e2 100644 --- a/src/test/org/apache/hadoop/util/TestQueueProcessingStatistics.java +++ b/src/test/org/apache/hadoop/util/TestQueueProcessingStatistics.java @@ -1,416 +1,424 @@ /** * 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.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.util.QueueProcessingStatistics.State; import org.junit.Before; import org.junit.Test; /** * Standalone unit tests for QueueProcessingStatistics */ public class TestQueueProcessingStatistics extends junit.framework.TestCase { public static final Log testLog = LogFactory.getLog( TestQueueProcessingStatistics.class.getName() + ".testLog"); private UnitQueueProcessingStats qStats = new UnitQueueProcessingStats(); public enum ExpectedLogResult {NONE, EXPECT_END_FIRST_CYCLE, EXPECT_END_SOLE_CYCLE, EXPECT_END_LAST_CYCLE, EXPECT_ERROR, EXPECT_ERROR_WITH_STATUS,} private static final long DEFAULT_CYCLE_DURATION = 25; private static final long DEFAULT_CYCLE_DELAY = 10; //minimum expected duration of each cycle must be >= 0 msec, //ignored if zero. private long cycleDuration = DEFAULT_CYCLE_DURATION; //minimum expected rest time after each cycle must be >= 0 msec, //ignored if zero. private long cycleDelay = DEFAULT_CYCLE_DELAY; @Before public void initialize() { qStats.initialize(); cycleDuration = DEFAULT_CYCLE_DURATION; cycleDelay = DEFAULT_CYCLE_DELAY; assertExpectedValues(false, State.BEGIN_COLLECTING, 0, 0); } /** * Does a set of asserts, appropriate to the current state of qStats. * * Note that any or all of cycleDuration, cycleDelay, and workItemCount * may be zero, which restricts the assertions we can make about the growth * of the qStats values as cycleCount increases. * * @param inCycle - true if believed to be currently in the middle of a cycle, * false if believed to have ended the most recent cycle. * @param state - expected state (ignored if null) * @param workItemCount - expected count (ignored if null) * @param cycleCount - expected count (ignored if null) */ public void assertExpectedValues( boolean inCycle, QueueProcessingStatistics.State state, Integer workItemCount, Integer cycleCount) { //Check implicit arguments assertTrue(cycleDuration >= 0L); assertTrue(cycleDelay >= 0L); //Asserts based on expected values if (state != null) assertEquals(failMsg(), state, qStats.state); if (workItemCount != null) assertEquals(failMsg(), (long) workItemCount, qStats.workItemCount); if (cycleCount != null) assertEquals(failMsg(), (int) cycleCount, qStats.cycleCount); //Asserts based on general principles assertTrue(failMsg(), qStats.startTime >= 0); if (qStats.state != State.BEGIN_COLLECTING) { + /* The following timing calculations don't work in many + * automated test environments (e.g., on heavily loaded servers with + * very unreliable "sleep()" durations), but are useful during + * development work. Commenting them out but leaving them here + * for dev use. + */ + /* assertAlmostEquals(failMsg() + " inCycle=" + inCycle, qStats.startTimeCurrentCycle, qStats.startTime + (cycleDuration + cycleDelay) * (qStats.cycleCount - (inCycle ? 0 : 1))); assertAlmostEquals(failMsg(), qStats.processDuration, cycleDuration * qStats.cycleCount); assertAlmostEquals(failMsg(), qStats.clockDuration, qStats.processDuration + cycleDelay * (qStats.cycleCount - (qStats.cycleCount > 0 ? 1 : 0))); + */ } assertTrue(failMsg(), qStats.workItemCount >= 0); assertTrue(failMsg(), qStats.cycleCount >= 0); //Asserts based on state machine State. switch (qStats.state) { case BEGIN_COLLECTING: assertFalse(failMsg(), inCycle); assertEquals(failMsg(), 0, qStats.startTime); assertEquals(failMsg(), 0, qStats.startTimeCurrentCycle); assertEquals(failMsg(), 0, qStats.processDuration); assertEquals(failMsg(), 0, qStats.clockDuration); assertEquals(failMsg(), 0, qStats.workItemCount); assertEquals(failMsg(), 0, qStats.cycleCount); break; case IN_FIRST_CYCLE: case IN_SOLE_CYCLE: assertTrue(failMsg(), inCycle); assertTrue(failMsg(), qStats.startTime > 0); assertEquals(failMsg(), qStats.startTime, qStats.startTimeCurrentCycle); assertEquals(failMsg(), 0, qStats.processDuration); assertEquals(failMsg(), 0, qStats.clockDuration); assertEquals(failMsg(), 0, qStats.workItemCount); assertEquals(failMsg(), 0, qStats.cycleCount); break; case DONE_FIRST_CYCLE: //Can't make any assertions about "inCycle". //For other qStats values, the general principles are the strongest //assertions that can be made. assertTrue(failMsg(), qStats.startTime > 0); assertTrue(failMsg(), qStats.cycleCount > 0); break; case IN_LAST_CYCLE: assertTrue(failMsg(), inCycle); assertTrue(failMsg(), qStats.startTime > 0); assertTrue(failMsg(), qStats.cycleCount > 0); break; case DONE_COLLECTING: assertFalse(failMsg(), inCycle); assertTrue(failMsg(), qStats.startTime > 0); assertTrue(failMsg(), qStats.cycleCount > 0); break; default: fail(failMsg() + " Reached unallowed state"); break; } } private String failMsg() { return "State=" + qStats.state + " cycleCount=" + qStats.cycleCount; } /** * The cycleDuration and cycleDelay are simulated by sleeping for those * numbers of milliseconds. Since sleep() is inexact, we'll assume it may * vary by +/- 1 msec per call. Since there are two calls per * virtual cycle, the potential error is twice that. And we add 1 to * account for sheer paranoia and the possibility of two consecutive * calls to "now()" occurring across a tick boundary. * We'll use values > 10 for cycleDuration and cycleDelay, * so the error isn't huge, percentage-wise. * * @return - whether the difference between inputs a and b is within * that expected error */ private boolean almostEquals(long a, long b) { long diff = a - b; if (diff < 0) diff = -diff; return diff < 2 * (qStats.cycleCount + 1); } private void assertAlmostEquals(long a, long b) { if (!almostEquals(a, b)) fail("Failed almostEquals test: " + a + ", " + b); } private void assertAlmostEquals(String msg, long a, long b) { if (!almostEquals(a, b)) fail(msg + "; Failed almostEquals test: " + a + ", " + b); } /* * Concrete subclasses of {@link QueueProcessingStatistics} for unit test */ private class UnitQueueProcessingStats extends QueueProcessingStatistics { public boolean triggerPreDetectLastCycle = false; public boolean triggerPostDetectLastCycle = false; public ExpectedLogResult expectedLogResult = ExpectedLogResult.NONE; UnitQueueProcessingStats() { super("UnitTestQueue", "blocks", testLog); } @Override void initialize() { super.initialize(); triggerPreDetectLastCycle = false; triggerPostDetectLastCycle = false; expectedLogResult = ExpectedLogResult.NONE; } // @see org.apache.hadoop.hdfs.server.namenode.FSNamesystem.QueueProcessingStatistics#preCheckIsLastCycle(int) @Override public boolean preCheckIsLastCycle(int maxWorkToProcess) { return triggerPreDetectLastCycle; } // @see org.apache.hadoop.hdfs.server.namenode.FSNamesystem.QueueProcessingStatistics#postCheckIsLastCycle(int) @Override public boolean postCheckIsLastCycle(int workFound) { return triggerPostDetectLastCycle; } // @see org.apache.hadoop.util.QueueProcessingStatistics#logEndFirstCycle() @Override void logEndFirstCycle() { assertTrue(expectedLogResult == ExpectedLogResult.EXPECT_END_FIRST_CYCLE || expectedLogResult == ExpectedLogResult.EXPECT_END_SOLE_CYCLE); super.logEndFirstCycle(); } // @see org.apache.hadoop.util.QueueProcessingStatistics#logEndLastCycle() @Override void logEndLastCycle() { assertTrue(expectedLogResult == ExpectedLogResult.EXPECT_END_LAST_CYCLE || expectedLogResult == ExpectedLogResult.EXPECT_END_SOLE_CYCLE); super.logEndLastCycle(); } // @see org.apache.hadoop.util.QueueProcessingStatistics#logError(String) @Override void logError(String msg) { assertEquals(ExpectedLogResult.EXPECT_ERROR, expectedLogResult); super.logError(msg); } // @see org.apache.hadoop.util.QueueProcessingStatistics#logErrorWithStats(String) @Override void logErrorWithStats(String msg) { assertEquals(ExpectedLogResult.EXPECT_ERROR_WITH_STATUS, expectedLogResult); super.logErrorWithStats(msg); } } /* * Simulate doing a cycle of work * @return - whatever was passed in */ private int simulateWork(int work) throws InterruptedException { Thread.sleep(DEFAULT_CYCLE_DURATION); return work; } /* * Simulate the inter-cycle delay by ... delaying! */ private void simulateIntercycleDelay() throws InterruptedException { Thread.sleep(DEFAULT_CYCLE_DELAY); return; } @Test public void testSingleCyclePreDetect() throws InterruptedException { int workToDo = 8; int maxWorkPerCycle = 10; int workDone = 0; qStats.checkRestart(); assertExpectedValues(false, State.BEGIN_COLLECTING, 0, 0); qStats.triggerPreDetectLastCycle = true; qStats.startCycle(workToDo); assertExpectedValues(true, State.IN_SOLE_CYCLE, 0, 0); workDone = simulateWork(workToDo); qStats.expectedLogResult = ExpectedLogResult.EXPECT_END_SOLE_CYCLE; qStats.endCycle(workDone); assertExpectedValues(false, State.DONE_COLLECTING, 8, 1); } @Test public void testSingleCyclePostDetect() throws InterruptedException { int workToDo = 8; int maxWorkPerCycle = 10; int workDone = 0; qStats.checkRestart(); assertExpectedValues(false, State.BEGIN_COLLECTING, 0, 0); qStats.startCycle(maxWorkPerCycle); assertExpectedValues(true, State.IN_FIRST_CYCLE, 0, 0); workDone = simulateWork(workToDo); qStats.triggerPostDetectLastCycle = true; qStats.expectedLogResult = ExpectedLogResult.EXPECT_END_SOLE_CYCLE; qStats.endCycle(workDone); assertExpectedValues(false, State.DONE_COLLECTING, 8, 1); } @Test public void testMultiCyclePreDetect() throws InterruptedException { int workToDo = 28; int maxWorkPerCycle = 10; int workFound = 0; int workDone = 0; qStats.checkRestart(); assertExpectedValues(false, State.BEGIN_COLLECTING, 0, 0); qStats.startCycle(maxWorkPerCycle); assertExpectedValues(true, State.IN_FIRST_CYCLE, workDone, 0); workFound = simulateWork(maxWorkPerCycle); workDone += workFound; workToDo -= workFound; qStats.expectedLogResult = ExpectedLogResult.EXPECT_END_FIRST_CYCLE; qStats.endCycle(workFound); assertExpectedValues(false, State.DONE_FIRST_CYCLE, 10, 1); qStats.expectedLogResult = ExpectedLogResult.NONE; simulateIntercycleDelay(); qStats.startCycle(maxWorkPerCycle); assertExpectedValues(true, State.DONE_FIRST_CYCLE, workDone, 1); workFound = simulateWork(maxWorkPerCycle); workDone += workFound; workToDo -= workFound; qStats.endCycle(workFound); assertExpectedValues(false, State.DONE_FIRST_CYCLE, 20, 2); simulateIntercycleDelay(); qStats.triggerPreDetectLastCycle = true; qStats.startCycle(maxWorkPerCycle); assertExpectedValues(true, State.IN_LAST_CYCLE, workDone, 2); workFound = simulateWork(workToDo); workDone += workFound; workToDo -= workFound; qStats.expectedLogResult = ExpectedLogResult.EXPECT_END_LAST_CYCLE; qStats.endCycle(workFound); assertExpectedValues(false, State.DONE_COLLECTING, 28, 3); } @Test public void testMultiCyclePostDetect() throws InterruptedException { int workToDo = 28; int maxWorkPerCycle = 10; int workFound = 0; int workDone = 0; qStats.checkRestart(); assertExpectedValues(false, State.BEGIN_COLLECTING, 0, 0); qStats.startCycle(maxWorkPerCycle); assertExpectedValues(true, State.IN_FIRST_CYCLE, workDone, 0); workFound = simulateWork(maxWorkPerCycle); workDone += workFound; workToDo -= workFound; qStats.expectedLogResult = ExpectedLogResult.EXPECT_END_FIRST_CYCLE; qStats.endCycle(workFound); assertExpectedValues(false, State.DONE_FIRST_CYCLE, 10, 1); qStats.expectedLogResult = ExpectedLogResult.NONE; simulateIntercycleDelay(); qStats.startCycle(maxWorkPerCycle); assertExpectedValues(true, State.DONE_FIRST_CYCLE, workDone, 1); workFound = simulateWork(maxWorkPerCycle); workDone += workFound; workToDo -= workFound; qStats.endCycle(workFound); assertExpectedValues(false, State.DONE_FIRST_CYCLE, 20, 2); simulateIntercycleDelay(); qStats.startCycle(maxWorkPerCycle); assertExpectedValues(true, State.DONE_FIRST_CYCLE, workDone, 2); workFound = simulateWork(workToDo); workDone += workFound; workToDo -= workFound; qStats.triggerPostDetectLastCycle = true; qStats.expectedLogResult = ExpectedLogResult.EXPECT_END_LAST_CYCLE; qStats.endCycle(workFound); assertExpectedValues(false, State.DONE_COLLECTING, 28, 3); } @Test public void testRestartIncycle() throws InterruptedException { int workToDo = 28; int maxWorkPerCycle = 10; int workFound = 0; int workDone = 0; qStats.checkRestart(); assertExpectedValues(false, State.BEGIN_COLLECTING, 0, 0); qStats.startCycle(maxWorkPerCycle); assertExpectedValues(true, State.IN_FIRST_CYCLE, workDone, 0); workFound = simulateWork(maxWorkPerCycle); workDone += workFound; workToDo -= workFound; qStats.expectedLogResult = ExpectedLogResult.EXPECT_END_FIRST_CYCLE; qStats.endCycle(workFound); assertExpectedValues(false, State.DONE_FIRST_CYCLE, 10, 1); qStats.expectedLogResult = ExpectedLogResult.EXPECT_ERROR_WITH_STATUS; qStats.checkRestart(); assertExpectedValues(false, State.BEGIN_COLLECTING, 0, 0); } @Test public void testRestartAfter() throws InterruptedException { testSingleCyclePostDetect(); qStats.expectedLogResult = ExpectedLogResult.EXPECT_ERROR; qStats.checkRestart(); assertExpectedValues(false, State.BEGIN_COLLECTING, 0, 0); } }
false
true
public void assertExpectedValues( boolean inCycle, QueueProcessingStatistics.State state, Integer workItemCount, Integer cycleCount) { //Check implicit arguments assertTrue(cycleDuration >= 0L); assertTrue(cycleDelay >= 0L); //Asserts based on expected values if (state != null) assertEquals(failMsg(), state, qStats.state); if (workItemCount != null) assertEquals(failMsg(), (long) workItemCount, qStats.workItemCount); if (cycleCount != null) assertEquals(failMsg(), (int) cycleCount, qStats.cycleCount); //Asserts based on general principles assertTrue(failMsg(), qStats.startTime >= 0); if (qStats.state != State.BEGIN_COLLECTING) { assertAlmostEquals(failMsg() + " inCycle=" + inCycle, qStats.startTimeCurrentCycle, qStats.startTime + (cycleDuration + cycleDelay) * (qStats.cycleCount - (inCycle ? 0 : 1))); assertAlmostEquals(failMsg(), qStats.processDuration, cycleDuration * qStats.cycleCount); assertAlmostEquals(failMsg(), qStats.clockDuration, qStats.processDuration + cycleDelay * (qStats.cycleCount - (qStats.cycleCount > 0 ? 1 : 0))); } assertTrue(failMsg(), qStats.workItemCount >= 0); assertTrue(failMsg(), qStats.cycleCount >= 0); //Asserts based on state machine State. switch (qStats.state) { case BEGIN_COLLECTING: assertFalse(failMsg(), inCycle); assertEquals(failMsg(), 0, qStats.startTime); assertEquals(failMsg(), 0, qStats.startTimeCurrentCycle); assertEquals(failMsg(), 0, qStats.processDuration); assertEquals(failMsg(), 0, qStats.clockDuration); assertEquals(failMsg(), 0, qStats.workItemCount); assertEquals(failMsg(), 0, qStats.cycleCount); break; case IN_FIRST_CYCLE: case IN_SOLE_CYCLE: assertTrue(failMsg(), inCycle); assertTrue(failMsg(), qStats.startTime > 0); assertEquals(failMsg(), qStats.startTime, qStats.startTimeCurrentCycle); assertEquals(failMsg(), 0, qStats.processDuration); assertEquals(failMsg(), 0, qStats.clockDuration); assertEquals(failMsg(), 0, qStats.workItemCount); assertEquals(failMsg(), 0, qStats.cycleCount); break; case DONE_FIRST_CYCLE: //Can't make any assertions about "inCycle". //For other qStats values, the general principles are the strongest //assertions that can be made. assertTrue(failMsg(), qStats.startTime > 0); assertTrue(failMsg(), qStats.cycleCount > 0); break; case IN_LAST_CYCLE: assertTrue(failMsg(), inCycle); assertTrue(failMsg(), qStats.startTime > 0); assertTrue(failMsg(), qStats.cycleCount > 0); break; case DONE_COLLECTING: assertFalse(failMsg(), inCycle); assertTrue(failMsg(), qStats.startTime > 0); assertTrue(failMsg(), qStats.cycleCount > 0); break; default: fail(failMsg() + " Reached unallowed state"); break; } }
public void assertExpectedValues( boolean inCycle, QueueProcessingStatistics.State state, Integer workItemCount, Integer cycleCount) { //Check implicit arguments assertTrue(cycleDuration >= 0L); assertTrue(cycleDelay >= 0L); //Asserts based on expected values if (state != null) assertEquals(failMsg(), state, qStats.state); if (workItemCount != null) assertEquals(failMsg(), (long) workItemCount, qStats.workItemCount); if (cycleCount != null) assertEquals(failMsg(), (int) cycleCount, qStats.cycleCount); //Asserts based on general principles assertTrue(failMsg(), qStats.startTime >= 0); if (qStats.state != State.BEGIN_COLLECTING) { /* The following timing calculations don't work in many * automated test environments (e.g., on heavily loaded servers with * very unreliable "sleep()" durations), but are useful during * development work. Commenting them out but leaving them here * for dev use. */ /* assertAlmostEquals(failMsg() + " inCycle=" + inCycle, qStats.startTimeCurrentCycle, qStats.startTime + (cycleDuration + cycleDelay) * (qStats.cycleCount - (inCycle ? 0 : 1))); assertAlmostEquals(failMsg(), qStats.processDuration, cycleDuration * qStats.cycleCount); assertAlmostEquals(failMsg(), qStats.clockDuration, qStats.processDuration + cycleDelay * (qStats.cycleCount - (qStats.cycleCount > 0 ? 1 : 0))); */ } assertTrue(failMsg(), qStats.workItemCount >= 0); assertTrue(failMsg(), qStats.cycleCount >= 0); //Asserts based on state machine State. switch (qStats.state) { case BEGIN_COLLECTING: assertFalse(failMsg(), inCycle); assertEquals(failMsg(), 0, qStats.startTime); assertEquals(failMsg(), 0, qStats.startTimeCurrentCycle); assertEquals(failMsg(), 0, qStats.processDuration); assertEquals(failMsg(), 0, qStats.clockDuration); assertEquals(failMsg(), 0, qStats.workItemCount); assertEquals(failMsg(), 0, qStats.cycleCount); break; case IN_FIRST_CYCLE: case IN_SOLE_CYCLE: assertTrue(failMsg(), inCycle); assertTrue(failMsg(), qStats.startTime > 0); assertEquals(failMsg(), qStats.startTime, qStats.startTimeCurrentCycle); assertEquals(failMsg(), 0, qStats.processDuration); assertEquals(failMsg(), 0, qStats.clockDuration); assertEquals(failMsg(), 0, qStats.workItemCount); assertEquals(failMsg(), 0, qStats.cycleCount); break; case DONE_FIRST_CYCLE: //Can't make any assertions about "inCycle". //For other qStats values, the general principles are the strongest //assertions that can be made. assertTrue(failMsg(), qStats.startTime > 0); assertTrue(failMsg(), qStats.cycleCount > 0); break; case IN_LAST_CYCLE: assertTrue(failMsg(), inCycle); assertTrue(failMsg(), qStats.startTime > 0); assertTrue(failMsg(), qStats.cycleCount > 0); break; case DONE_COLLECTING: assertFalse(failMsg(), inCycle); assertTrue(failMsg(), qStats.startTime > 0); assertTrue(failMsg(), qStats.cycleCount > 0); break; default: fail(failMsg() + " Reached unallowed state"); break; } }
diff --git a/src/net/rcode/wsclient/WebSocket.java b/src/net/rcode/wsclient/WebSocket.java index 49be52b..8cfd614 100644 --- a/src/net/rcode/wsclient/WebSocket.java +++ b/src/net/rcode/wsclient/WebSocket.java @@ -1,571 +1,571 @@ package net.rcode.wsclient; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.net.Socket; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import javax.net.SocketFactory; /** * Provide an implementation of the HTML5 WebSocket class: * http://dev.w3.org/html5/websockets/ * <p> * Where feasible, we use similar conventions/names here as in the HTML5 spec for * familiarity. This class manages a worker thread which actually performs all of * the connection management. For simplicity, the several events are collapsed * down to a single event handler registration and distinguished with an event code. * <p> * This class implements thewebsocketprotocol-03 * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-03 * * @author stella * */ public class WebSocket { private static final Pattern INVALID_HEADER_NAME_PATTERN=Pattern.compile("[\\r\\n\\:]"); private static final Pattern INVALID_HEADER_VALUE_PATTERN=Pattern.compile("[\\r\\n]"); public static class Event { /** * An EVENT_* constant */ protected int type; /** * The source WebSocket */ protected WebSocket source; /** * Snapshot of the readyState at the time of the event */ protected int readyState=-1; /** * On MESSAGE event types this is the message */ protected Message message; /** * On error event types, this is the error */ protected Throwable error; public int getType() { return type; } public WebSocket getSource() { return source; } public int getReadyState() { return readyState; } public Message getMessage() { return message; } public Throwable getError() { return error; } public String toString() { StringWriter ret=new StringWriter(); String typeName; if (type==EVENT_READYSTATE) typeName="ReadyState"; else if (type==EVENT_MESSAGE) typeName="Message"; else if (type==EVENT_ERROR) typeName="Error"; else typeName=String.valueOf(type); ret.write("<Event "); ret.append(typeName); ret.append(", readyState="); ret.append(String.valueOf(readyState)); ret.append(">\n"); if (type==EVENT_ERROR && error!=null) { PrintWriter pout=new PrintWriter(ret); error.printStackTrace(pout); pout.flush(); } else if (type==EVENT_MESSAGE) { ret.append(message.toString()); } ret.append("</Event>"); return ret.toString(); } } public static interface EventListener { public void handleEvent(Event event); } // -- readyState constants public static final int CONNECTING=0; public static final int OPEN=1; public static final int CLOSING=2; public static final int CLOSED=3; /** * Combines the open and close events and just exposes one * readyState change event */ public static final int EVENT_READYSTATE=0; /** * A message has been received. The message field will be set. */ public static final int EVENT_MESSAGE=1; /** * An error occurred. If this was due to an exception, the event error * field will be set. In general, errors cause the io thread to commence * shutdown. */ public static final int EVENT_ERROR=2; // -- public properties (read-only) private int readyState; private String url; private Map<String, String> requestHeaders=new HashMap<String, String>(); private Map<String, String> responseHeaders; private boolean verifyHandshake=true; // -- public properties (read-write) private NetConfig netConfig=new NetConfig(); private WireProtocol wireProtocol=WireProtocolDraft76.INSTANCE; public synchronized int getReadyState() { return readyState; } protected synchronized void setReadyState(int readyState) { boolean notifyListeners; synchronized(this) { if (readyState!=this.readyState) { this.readyState = readyState; notifyListeners=listeners!=null; this.notifyAll(); } else { notifyListeners=false; } } if (notifyListeners) { Event event=new Event(); event.source=this; event.type=EVENT_READYSTATE; event.readyState=readyState; signalEvent(event); } } public synchronized String getProtocol() { if (responseHeaders==null) return null; return responseHeaders.get("sec-websocket-protocol"); } public synchronized String[] getResponseHeaderNames() { if (responseHeaders==null) return null; return responseHeaders.keySet().toArray(new String[responseHeaders.size()]); } public synchronized String getResponseHeader(String name) { if (responseHeaders==null) return null; return responseHeaders.get(name.toLowerCase()); } public String getUrl() { return url; } public NetConfig getNetConfig() { return netConfig; } public void setNetConfig(NetConfig netConfig) { if (started) throw new IllegalStateException(); this.netConfig = netConfig; } public WireProtocol getWireProtocol() { return wireProtocol; } public void setWireProtocol(WireProtocol wireProtocol) { if (started) throw new IllegalStateException(); this.wireProtocol = wireProtocol; } /** * Use to disable handshake verification. Handshake is still generated per spec but * not verified * @param verifyHandshake */ public void setVerifyHandshake(boolean verifyHandshake) { if (started) throw new IllegalStateException(); this.verifyHandshake = verifyHandshake; } public boolean isVerifyHandshake() { return verifyHandshake; } public void addRequestHeader(String name, String value) { if (started) throw new IllegalStateException(); if (INVALID_HEADER_NAME_PATTERN.matcher(name).find() || INVALID_HEADER_VALUE_PATTERN.matcher(value).find()) throw new IllegalArgumentException(); if (requestHeaders==null) requestHeaders=new HashMap<String, String>(); requestHeaders.put(name, value); } // -- public constructors public WebSocket(String url, String... requestedProtocols) { this.url=url; this.requestedProtocols=requestedProtocols.clone(); } // -- public api /** * Queues a message for sending (puts the message at the tail of the queue) */ public void send(Message message) { transmissionQueue.addTail(message); } /** * Queues a message for immediate transmission (puts it at the head of the * queue). * @param message */ public void sendImmediate(Message message) { transmissionQueue.addHead(message); } public void send(CharSequence message) { send(new Message(message)); } /** * @return the number of messages on the transmission queue */ public int getOutgoingDepth() { return transmissionQueue.getDepth(); } /** * @return the approximate number of bytes queued for transmission (excluding framing) */ public long getOutgoingAmount() { return transmissionQueue.getBytes(); } public void close() { synchronized (this) { if (readyState!=OPEN) { abort(); return; } } wireProtocol.initiateClose(this); } /** * Immediately abort the connection. */ public void abort() { if (socket!=null) { try { socket.close(); // This will stop anything blocked on read or write } catch (IOException e) { // Not much else to do e.printStackTrace(); } socket=null; } Thread localReaderThread=null, localWriterThread=null; synchronized (this) { if (readerThread!=null && readerThread.isAlive()) { readerThread.interrupt(); localReaderThread=readerThread; } if (writerThread!=null && writerThread.isAlive()) { writerThread.interrupt(); localWriterThread=writerThread; } readerThread=null; writerThread=null; } if (localReaderThread!=null) { try { - readerThread.join(); + localReaderThread.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if (localWriterThread!=null) { try { - writerThread.join(); + localWriterThread.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } setReadyState(CLOSED); } public void waitForReadyState(int targetReadyState) throws InterruptedException { synchronized (this) { while (readyState!=targetReadyState) { this.wait(); } } } public synchronized void addListener(EventListener l) { if (dispatchingEvent && listeners!=null) { // Make a defensive copy listeners=new ArrayList<WebSocket.EventListener>(listeners); } if (listeners==null) listeners=new ArrayList<WebSocket.EventListener>(2); listeners.add(l); } public synchronized void removeListener(EventListener l) { if (listeners!=null) { if (dispatchingEvent) listeners=new ArrayList<WebSocket.EventListener>(listeners); listeners.remove(l); } } public synchronized void removeAllListeners() { listeners=null; } /** * The HTML5 implementation presumably starts after the current tick. This base class * has no threading ideas so it has an explicit start() method. If already started * does nothing. Otherwise, starts the processing thread. Environment specific * subclasses will typically integrate with the native message loop to handle this * detail for you. */ public void start() { if (started) return; started=true; readerThread=new Thread("WebSocket read " + url) { public void run() { runReader(); } }; readerThread.start(); } private void startWriter() { writerThread=new Thread("WebSocket write " + url) { public void run() { runWriter(); } }; writerThread.start(); } // -- package private (to protocol implementations) private byte[] closeCookie; protected Map<String, String> getRequestHeaders() { return requestHeaders; } protected String[] getRequestedProtocols() { return requestedProtocols; } protected synchronized void setResponseHeaders(Map<String, String> responseHeaders) { this.responseHeaders = responseHeaders; } protected MessageQueue getTransmissionQueue() { return transmissionQueue; } public synchronized byte[] getCloseCookie() { return closeCookie; } public synchronized void setCloseCookie(byte[] closeCookie) { this.closeCookie = closeCookie; } // -- internal implementation private boolean started; private Thread readerThread, writerThread; private String[] requestedProtocols; private List<EventListener> listeners; private boolean dispatchingEvent; protected final void signalEvent(Event event) { List<EventListener> listenersCopy; synchronized (this) { dispatchingEvent=true; listenersCopy=listeners; } try { if (listenersCopy!=null) { for (int i=0; i<listenersCopy.size(); i++) { dispatchEvent(event, listenersCopy.get(i)); } } } finally { synchronized (this) { dispatchingEvent=false; } } } protected void signalError(Throwable t) { //t.printStackTrace(); Event event=new Event(); event.source=this; event.type=EVENT_ERROR; event.readyState=readyState; event.error=t; signalEvent(event); } protected void signalMessage(Message msg) { Event event=new Event(); event.source=this; event.readyState=readyState; event.type=EVENT_MESSAGE; event.message=msg; signalEvent(event); } /** * Dispatch an event to the given listener. Subclasses can do custom thread * marshalling by overriding this method * @param event * @param l */ protected void dispatchEvent(Event event, EventListener l) { l.handleEvent(event); } // -- IO Management. Everything from here on runs under either the reader or writer thread private URI uri; private String hostName; private int port; private SocketFactory socketFactory; private Socket socket; private DataInputStream in; private DataOutputStream out; private MessageQueue transmissionQueue=new MessageQueue(); private void setupConnection() throws Throwable { uri=new URI(url); // Detect protocol, host, port String hostHeader; String scheme=uri.getScheme(); port=uri.getPort(); hostName=uri.getHost(); if ("ws".equalsIgnoreCase(scheme) || "http".equals(scheme)) { // Default to http if (port<0) port=80; if (port!=80) hostHeader=hostName + ':' + port; else hostHeader=hostName; socketFactory=netConfig.getPlainSocketFactory(); } else if ("wss".equalsIgnoreCase(scheme) || "https".equalsIgnoreCase(scheme)) { // Secure if (port<0) port=443; if (port!=443) hostHeader=hostName + ':' + port; else hostHeader=hostName; socketFactory=netConfig.getSecureSocketFactory(); } else { throw new IllegalArgumentException("Unsupported websocket protocol"); } // Add the host header requestHeaders.put("Host", hostHeader); // Connect the socket socket=socketFactory.createSocket(hostName, port); try { // Buffer the streams to a typical network packet size in=new DataInputStream(new BufferedInputStream(socket.getInputStream(), 1500)); out=new DataOutputStream(new BufferedOutputStream(socket.getOutputStream(), 1500)); } catch (Throwable t) { socket.close(); throw t; } } private void pumpSocketInput() throws Exception { for (;;) { Message message=wireProtocol.readMessage(this, in); if (message==null) break; signalMessage(message); } } private void runReader() { setReadyState(CONNECTING); // Before starting the main loop, we need to resolve the URI try { setupConnection(); wireProtocol.performHandshake(this, uri, in, out); startWriter(); pumpSocketInput(); abort(); } catch (Throwable t) { exceptionalShutdown(t); return; } } private void runWriter() { //System.out.println("Writer starting"); for (;;) { Message next; try { next=transmissionQueue.waitNext(); } catch (InterruptedException e) { // Shutdown break; } try { boolean shouldContinue=wireProtocol.sendMessage(this, out, next); transmissionQueue.remove(next); if (!shouldContinue) break; } catch (Throwable t) { // Replace the message exceptionalShutdown(t); break; } } //System.out.println("Writer exiting"); } /** * Called on exception. Fires events and shuts everything down. */ private void exceptionalShutdown(Throwable t) { signalError(t); abort(); } }
false
true
public void abort() { if (socket!=null) { try { socket.close(); // This will stop anything blocked on read or write } catch (IOException e) { // Not much else to do e.printStackTrace(); } socket=null; } Thread localReaderThread=null, localWriterThread=null; synchronized (this) { if (readerThread!=null && readerThread.isAlive()) { readerThread.interrupt(); localReaderThread=readerThread; } if (writerThread!=null && writerThread.isAlive()) { writerThread.interrupt(); localWriterThread=writerThread; } readerThread=null; writerThread=null; } if (localReaderThread!=null) { try { readerThread.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if (localWriterThread!=null) { try { writerThread.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } setReadyState(CLOSED); }
public void abort() { if (socket!=null) { try { socket.close(); // This will stop anything blocked on read or write } catch (IOException e) { // Not much else to do e.printStackTrace(); } socket=null; } Thread localReaderThread=null, localWriterThread=null; synchronized (this) { if (readerThread!=null && readerThread.isAlive()) { readerThread.interrupt(); localReaderThread=readerThread; } if (writerThread!=null && writerThread.isAlive()) { writerThread.interrupt(); localWriterThread=writerThread; } readerThread=null; writerThread=null; } if (localReaderThread!=null) { try { localReaderThread.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if (localWriterThread!=null) { try { localWriterThread.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } setReadyState(CLOSED); }
diff --git a/src/main/java/org/atlasapi/persistence/CassandraPersistenceModule.java b/src/main/java/org/atlasapi/persistence/CassandraPersistenceModule.java index 370380c9..cba60171 100644 --- a/src/main/java/org/atlasapi/persistence/CassandraPersistenceModule.java +++ b/src/main/java/org/atlasapi/persistence/CassandraPersistenceModule.java @@ -1,23 +1,23 @@ package org.atlasapi.persistence; import com.google.common.base.Splitter; import com.google.common.collect.Lists; import org.atlasapi.persistence.content.cassandra.CassandraContentStore; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** */ @Configuration public class CassandraPersistenceModule { private @Value("${cassandra.seeds}") String seeds; private @Value("${cassandra.port}") int port; private @Value("${cassandra.connectionTimeout}") int connectionTimeout; private @Value("${cassandra.requestTimeout}") int requestTimeout; - private @Bean CassandraContentStore cassandraContentStore() { + public @Bean CassandraContentStore cassandraContentStore() { return new CassandraContentStore(Lists.newArrayList(Splitter.on(',').split(seeds)), port, Runtime.getRuntime().availableProcessors() * 10, connectionTimeout, requestTimeout); } }
true
true
private @Bean CassandraContentStore cassandraContentStore() { return new CassandraContentStore(Lists.newArrayList(Splitter.on(',').split(seeds)), port, Runtime.getRuntime().availableProcessors() * 10, connectionTimeout, requestTimeout); }
public @Bean CassandraContentStore cassandraContentStore() { return new CassandraContentStore(Lists.newArrayList(Splitter.on(',').split(seeds)), port, Runtime.getRuntime().availableProcessors() * 10, connectionTimeout, requestTimeout); }
diff --git a/jetty-io/src/main/java/org/eclipse/jetty/io/nio/SelectorManager.java b/jetty-io/src/main/java/org/eclipse/jetty/io/nio/SelectorManager.java index 1b33306b5..e89ca927e 100644 --- a/jetty-io/src/main/java/org/eclipse/jetty/io/nio/SelectorManager.java +++ b/jetty-io/src/main/java/org/eclipse/jetty/io/nio/SelectorManager.java @@ -1,880 +1,880 @@ // ======================================================================== // Copyright (c) 2004-2009 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // You may elect to redistribute this code under either of these licenses. // ======================================================================== package org.eclipse.jetty.io.nio; import java.io.IOException; import java.nio.channels.CancelledKeyException; import java.nio.channels.SelectableChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import org.eclipse.jetty.io.Connection; import org.eclipse.jetty.io.EndPoint; import org.eclipse.jetty.util.component.AbstractLifeCycle; import org.eclipse.jetty.util.log.Log; import org.eclipse.jetty.util.thread.Timeout; /* ------------------------------------------------------------ */ /** * The Selector Manager manages and number of SelectSets to allow * NIO scheduling to scale to large numbers of connections. * * * */ public abstract class SelectorManager extends AbstractLifeCycle { // TODO Tune these by approx system speed. private static final int __JVMBUG_THRESHHOLD=Integer.getInteger("org.mortbay.io.nio.JVMBUG_THRESHHOLD",512).intValue(); private static final int __MONITOR_PERIOD=Integer.getInteger("org.mortbay.io.nio.MONITOR_PERIOD",1000).intValue(); private static final int __MAX_SELECTS=Integer.getInteger("org.mortbay.io.nio.MAX_SELECTS",15000).intValue(); private static final int __BUSY_PAUSE=Integer.getInteger("org.mortbay.io.nio.BUSY_PAUSE",50).intValue(); private static final int __BUSY_KEY=Integer.getInteger("org.mortbay.io.nio.BUSY_KEY",-1).intValue(); private long _maxIdleTime; private long _lowResourcesConnections; private long _lowResourcesMaxIdleTime; private transient SelectSet[] _selectSet; private int _selectSets=1; private volatile int _set; /* ------------------------------------------------------------ */ /** * @param maxIdleTime The maximum period in milli seconds that a connection may be idle before it is closed. * @see {@link #setLowResourcesMaxIdleTime(long)} */ public void setMaxIdleTime(long maxIdleTime) { _maxIdleTime=maxIdleTime; } /* ------------------------------------------------------------ */ /** * @param selectSets number of select sets to create */ public void setSelectSets(int selectSets) { long lrc = _lowResourcesConnections * _selectSets; _selectSets=selectSets; _lowResourcesConnections=lrc/_selectSets; } /* ------------------------------------------------------------ */ /** * @return */ public long getMaxIdleTime() { return _maxIdleTime; } /* ------------------------------------------------------------ */ /** * @return */ public int getSelectSets() { return _selectSets; } /* ------------------------------------------------------------ */ /** Register a channel * @param channel * @param att Attached Object * @throws IOException */ public void register(SocketChannel channel, Object att) { int s=_set++; s=s%_selectSets; SelectSet[] sets=_selectSet; if (sets!=null) { SelectSet set=sets[s]; set.addChange(channel,att); set.wakeup(); } } /* ------------------------------------------------------------ */ /** Register a serverchannel * @param acceptChannel * @return * @throws IOException */ public void register(ServerSocketChannel acceptChannel) { int s=_set++; s=s%_selectSets; SelectSet set=_selectSet[s]; set.addChange(acceptChannel); set.wakeup(); } /* ------------------------------------------------------------ */ /** * @return the lowResourcesConnections */ public long getLowResourcesConnections() { return _lowResourcesConnections*_selectSets; } /* ------------------------------------------------------------ */ /** * Set the number of connections, which if exceeded places this manager in low resources state. * This is not an exact measure as the connection count is averaged over the select sets. * @param lowResourcesConnections the number of connections * @see {@link #setLowResourcesMaxIdleTime(long)} */ public void setLowResourcesConnections(long lowResourcesConnections) { _lowResourcesConnections=(lowResourcesConnections+_selectSets-1)/_selectSets; } /* ------------------------------------------------------------ */ /** * @return the lowResourcesMaxIdleTime */ public long getLowResourcesMaxIdleTime() { return _lowResourcesMaxIdleTime; } /* ------------------------------------------------------------ */ /** * @param lowResourcesMaxIdleTime the period in ms that a connection is allowed to be idle when this SelectSet has more connections than {@link #getLowResourcesConnections()} * @see {@link #setMaxIdleTime(long)} */ public void setLowResourcesMaxIdleTime(long lowResourcesMaxIdleTime) { _lowResourcesMaxIdleTime=lowResourcesMaxIdleTime; } /* ------------------------------------------------------------ */ /** * @param acceptorID * @throws IOException */ public void doSelect(int acceptorID) throws IOException { SelectSet[] sets= _selectSet; if (sets!=null && sets.length>acceptorID && sets[acceptorID]!=null) sets[acceptorID].doSelect(); } /* ------------------------------------------------------------ */ /** * @param key * @return * @throws IOException */ protected abstract SocketChannel acceptChannel(SelectionKey key) throws IOException; /* ------------------------------------------------------------------------------- */ public abstract boolean dispatch(Runnable task); /* ------------------------------------------------------------ */ /* (non-Javadoc) * @see org.eclipse.component.AbstractLifeCycle#doStart() */ protected void doStart() throws Exception { _selectSet = new SelectSet[_selectSets]; for (int i=0;i<_selectSet.length;i++) _selectSet[i]= new SelectSet(i); super.doStart(); } /* ------------------------------------------------------------------------------- */ protected void doStop() throws Exception { SelectSet[] sets= _selectSet; _selectSet=null; if (sets!=null) { for (SelectSet set : sets) { if (set!=null) set.stop(); } } super.doStop(); } /* ------------------------------------------------------------ */ /** * @param endpoint */ protected abstract void endPointClosed(SelectChannelEndPoint endpoint); /* ------------------------------------------------------------ */ /** * @param endpoint */ protected abstract void endPointOpened(SelectChannelEndPoint endpoint); /* ------------------------------------------------------------------------------- */ protected abstract Connection newConnection(SocketChannel channel, SelectChannelEndPoint endpoint); /* ------------------------------------------------------------ */ /** * @param channel * @param selectSet * @param sKey * @return * @throws IOException */ protected abstract SelectChannelEndPoint newEndPoint(SocketChannel channel, SelectorManager.SelectSet selectSet, SelectionKey sKey) throws IOException; /* ------------------------------------------------------------------------------- */ protected void connectionFailed(SocketChannel channel,Throwable ex,Object attachment) { Log.warn(ex+","+channel+","+attachment); Log.debug(ex); } /* ------------------------------------------------------------------------------- */ public void dump() { for (final SelectSet set :_selectSet) { Thread selecting = set._selecting; Log.info("SelectSet "+set._setID+" : "+selecting); if (selecting!=null) { StackTraceElement[] trace =selecting.getStackTrace(); if (trace!=null) { for (StackTraceElement e : trace) { Log.info("\tat "+e.toString()); } } } set.addChange(new ChangeTask(){ public void run() { set.dump(); } }); } } /* ------------------------------------------------------------------------------- */ /* ------------------------------------------------------------------------------- */ /* ------------------------------------------------------------------------------- */ public class SelectSet { private final int _setID; private final Timeout _idleTimeout; private final Timeout _timeout; private final List<Object>[] _changes; private int _change; private int _nextSet; private Selector _selector; private volatile Thread _selecting; private int _jvmBug; private int _selects; private long _monitorStart; private long _monitorNext; private boolean _pausing; private SelectionKey _busyKey; private int _busyKeyCount; private long _log; private int _paused; private int _jvmFix0; private int _jvmFix1; private int _jvmFix2; /* ------------------------------------------------------------ */ SelectSet(int acceptorID) throws Exception { _setID=acceptorID; _idleTimeout = new Timeout(this); _idleTimeout.setDuration(getMaxIdleTime()); _timeout = new Timeout(this); _timeout.setDuration(0L); _changes = new List[] {new ArrayList(),new ArrayList()}; // create a selector; _selector = Selector.open(); _change=0; _monitorStart=System.currentTimeMillis(); _monitorNext=_monitorStart+__MONITOR_PERIOD; _log=_monitorStart+60000; } /* ------------------------------------------------------------ */ public void addChange(Object point) { synchronized (_changes) { _changes[_change].add(point); } } /* ------------------------------------------------------------ */ public void addChange(SelectableChannel channel, Object att) { if (att==null) addChange(channel); else if (att instanceof EndPoint) addChange(att); else addChange(new ChangeSelectableChannel(channel,att)); } /* ------------------------------------------------------------ */ public void cancelIdle(Timeout.Task task) { task.cancel(); } /* ------------------------------------------------------------ */ /** * Select and dispatch tasks found from changes and the selector. * * @throws IOException */ public void doSelect() throws IOException { try { _selecting=Thread.currentThread(); List<?> changes; final Selector selector; synchronized (_changes) { changes=_changes[_change]; _change=_change==0?1:0; selector=_selector; } // Make any key changes required final int size=changes.size(); for (int i = 0; i < size; i++) { try { Object o = changes.get(i); if (o instanceof EndPoint) { // Update the operations for a key. SelectChannelEndPoint endpoint = (SelectChannelEndPoint)o; endpoint.doUpdateKey(); } else if (o instanceof Runnable) { dispatch((Runnable)o); } else if (o instanceof ChangeSelectableChannel) { // finish accepting/connecting this connection final ChangeSelectableChannel asc = (ChangeSelectableChannel)o; final SelectableChannel channel=asc._channel; final Object att = asc._attachment; if ((channel instanceof SocketChannel) && ((SocketChannel)channel).isConnected()) { SelectionKey key = channel.register(selector,SelectionKey.OP_READ,att); SelectChannelEndPoint endpoint = newEndPoint((SocketChannel)channel,this,key); key.attach(endpoint); endpoint.schedule(); } else if (channel.isOpen()) { channel.register(selector,SelectionKey.OP_CONNECT,att); } } else if (o instanceof SocketChannel) { final SocketChannel channel=(SocketChannel)o; if (channel.isConnected()) { SelectionKey key = channel.register(selector,SelectionKey.OP_READ,null); SelectChannelEndPoint endpoint = newEndPoint(channel,this,key); key.attach(endpoint); endpoint.schedule(); } else if (channel.isOpen()) { channel.register(selector,SelectionKey.OP_CONNECT,null); } } else if (o instanceof ServerSocketChannel) { ServerSocketChannel channel = (ServerSocketChannel)o; channel.register(getSelector(),SelectionKey.OP_ACCEPT); } else if (o instanceof ChangeTask) { ((ChangeTask)o).run(); } else throw new IllegalArgumentException(o.toString()); } - catch (CancelledKeyException e) + catch (Exception e) { if (isRunning()) Log.warn(e); else Log.debug(e); } } changes.clear(); long idle_next; long retry_next; long now=System.currentTimeMillis(); synchronized (this) { _idleTimeout.setNow(now); _timeout.setNow(now); if (_lowResourcesConnections>0 && selector.keys().size()>_lowResourcesConnections) _idleTimeout.setDuration(_lowResourcesMaxIdleTime); else _idleTimeout.setDuration(_maxIdleTime); idle_next=_idleTimeout.getTimeToNext(); retry_next=_timeout.getTimeToNext(); } // workout how low to wait in select long wait = 1000L; // not getMaxIdleTime() as the now value of the idle timers needs to be updated. if (idle_next >= 0 && wait > idle_next) wait = idle_next; if (wait > 0 && retry_next >= 0 && wait > retry_next) wait = retry_next; // Do the select. if (wait > 0) { // If we are in pausing mode if (_pausing) { try { Thread.sleep(__BUSY_PAUSE); // pause to reduce impact of busy loop } catch(InterruptedException e) { Log.ignore(e); } } long before=now; int selected=selector.select(wait); now = System.currentTimeMillis(); _idleTimeout.setNow(now); _timeout.setNow(now); _selects++; // Look for JVM bugs over a monitor period. // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6403933 // http://bugs.sun.com/view_bug.do?bug_id=6693490 if (now>_monitorNext) { _selects=(int)(_selects*__MONITOR_PERIOD/(now-_monitorStart)); _pausing=_selects>__MAX_SELECTS; if (_pausing) _paused++; _selects=0; _jvmBug=0; _monitorStart=now; _monitorNext=now+__MONITOR_PERIOD; } if (now>_log) { if (_paused>0) Log.info(this+" Busy selector - injecting delay "+_paused+" times"); if (_jvmFix2>0) Log.info(this+" JVM BUG(s) - injecting delay"+_jvmFix2+" times"); if (_jvmFix1>0) Log.info(this+" JVM BUG(s) - recreating selector "+_jvmFix1+" times, canceled keys "+_jvmFix0+" times"); else if(Log.isDebugEnabled() && _jvmFix0>0) Log.info(this+" JVM BUG(s) - canceled keys "+_jvmFix0+" times"); _paused=0; _jvmFix2=0; _jvmFix1=0; _jvmFix0=0; _log=now+60000; } // If we see signature of possible JVM bug, increment count. if (selected==0 && wait>10 && (now-before)<(wait/2)) { // Increment bug count and try a work around _jvmBug++; if (_jvmBug>(__JVMBUG_THRESHHOLD)) { try { if (_jvmBug==__JVMBUG_THRESHHOLD+1) _jvmFix2++; Thread.sleep(__BUSY_PAUSE); // pause to avoid busy loop } catch(InterruptedException e) { Log.ignore(e); } } else if (_jvmBug==__JVMBUG_THRESHHOLD) { synchronized (this) { // BLOODY SUN BUG !!! Try refreshing the entire selector. final Selector new_selector = Selector.open(); for (SelectionKey k: selector.keys()) { if (!k.isValid() || k.interestOps()==0) continue; final SelectableChannel channel = k.channel(); final Object attachment = k.attachment(); if (attachment==null) addChange(channel); else addChange(channel,attachment); } _selector.close(); _selector=new_selector; return; } } else if (_jvmBug%32==31) // heuristic attempt to cancel key 31,63,95,... loops { // Cancel keys with 0 interested ops int cancelled=0; for (SelectionKey k: selector.keys()) { if (k.isValid()&&k.interestOps()==0) { k.cancel(); cancelled++; } } if (cancelled>0) _jvmFix0++; return; } } else if (__BUSY_KEY>0 && selected==1 && _selects>__MAX_SELECTS) { // Look for busy key SelectionKey busy = (SelectionKey)selector.selectedKeys().iterator().next(); if (busy==_busyKey) { if (++_busyKeyCount>__BUSY_KEY) { SelectChannelEndPoint endpoint = (SelectChannelEndPoint)busy.attachment(); Log.warn("Busy Key "+busy+" "+endpoint); busy.cancel(); if (endpoint!=null) endpoint.close(); } } else _busyKeyCount=0; _busyKey=busy; } } else { selector.selectNow(); _selects++; } // have we been destroyed while sleeping if (_selector==null || !selector.isOpen()) return; // Look for things to do for (SelectionKey key: selector.selectedKeys()) { try { if (!key.isValid()) { key.cancel(); SelectChannelEndPoint endpoint = (SelectChannelEndPoint)key.attachment(); if (endpoint != null) endpoint.doUpdateKey(); continue; } Object att = key.attachment(); if (att instanceof SelectChannelEndPoint) { ((SelectChannelEndPoint)att).schedule(); } else if (key.isAcceptable()) { SocketChannel channel = acceptChannel(key); if (channel==null) continue; channel.configureBlocking(false); // TODO make it reluctant to leave 0 _nextSet=++_nextSet%_selectSet.length; // Is this for this selectset if (_nextSet==_setID) { // bind connections to this select set. SelectionKey cKey = channel.register(_selectSet[_nextSet].getSelector(), SelectionKey.OP_READ); SelectChannelEndPoint endpoint=newEndPoint(channel,_selectSet[_nextSet],cKey); cKey.attach(endpoint); if (endpoint != null) endpoint.schedule(); } else { // nope - give it to another. _selectSet[_nextSet].addChange(channel); _selectSet[_nextSet].wakeup(); } } else if (key.isConnectable()) { // Complete a connection of a registered channel SocketChannel channel = (SocketChannel)key.channel(); boolean connected=false; try { connected=channel.finishConnect(); } catch(Exception e) { connectionFailed(channel,e,att); } finally { if (connected) { key.interestOps(SelectionKey.OP_READ); SelectChannelEndPoint endpoint = newEndPoint(channel,this,key); key.attach(endpoint); endpoint.schedule(); } else { key.cancel(); } } } else { // Wrap readable registered channel in an endpoint SocketChannel channel = (SocketChannel)key.channel(); SelectChannelEndPoint endpoint = newEndPoint(channel,this,key); key.attach(endpoint); if (key.isReadable()) endpoint.schedule(); } key = null; } catch (CancelledKeyException e) { Log.ignore(e); } catch (Exception e) { if (isRunning()) Log.warn(e); else Log.ignore(e); if (key != null && !(key.channel() instanceof ServerSocketChannel) && key.isValid()) key.cancel(); } } // Everything always handled selector.selectedKeys().clear(); // tick over the timers _idleTimeout.tick(now); _timeout.tick(now); } catch (CancelledKeyException e) { Log.ignore(e); } finally { _selecting=null; } } /* ------------------------------------------------------------ */ public SelectorManager getManager() { return SelectorManager.this; } /* ------------------------------------------------------------ */ public long getNow() { return _idleTimeout.getNow(); } /* ------------------------------------------------------------ */ public void scheduleIdle(Timeout.Task task) { if (_idleTimeout.getDuration() <= 0) return; _idleTimeout.schedule(task); } /* ------------------------------------------------------------ */ public void scheduleTimeout(Timeout.Task task, long timeoutMs) { _timeout.schedule(task, timeoutMs); } /* ------------------------------------------------------------ */ public void cancelTimeout(Timeout.Task task) { task.cancel(); } /* ------------------------------------------------------------ */ public void wakeup() { Selector selector = _selector; if (selector!=null) selector.wakeup(); } /* ------------------------------------------------------------ */ Selector getSelector() { return _selector; } /* ------------------------------------------------------------ */ void stop() throws Exception { boolean selecting=true; while(selecting) { wakeup(); selecting=_selecting!=null; } for (SelectionKey key:_selector.keys()) { if (key==null) continue; Object att=key.attachment(); if (att instanceof EndPoint) { EndPoint endpoint = (EndPoint)att; try { endpoint.close(); } catch(IOException e) { Log.ignore(e); } } } synchronized (this) { selecting=_selecting!=null; while(selecting) { wakeup(); selecting=_selecting!=null; } _idleTimeout.cancelAll(); _timeout.cancelAll(); try { if (_selector != null) _selector.close(); } catch (IOException e) { Log.ignore(e); } _selector=null; } } public void dump() { synchronized (System.err) { Selector selector=_selector; Log.info("SelectSet "+_setID+" "+selector.keys().size()); for (SelectionKey key: selector.keys()) { if (key.isValid()) Log.info(key.channel()+" "+key.interestOps()+" "+key.readyOps()+" "+key.attachment()); else Log.info(key.channel()+" - - "+key.attachment()); } } } } /* ------------------------------------------------------------ */ private static class ChangeSelectableChannel { final SelectableChannel _channel; final Object _attachment; public ChangeSelectableChannel(SelectableChannel channel, Object attachment) { super(); _channel = channel; _attachment = attachment; } } /* ------------------------------------------------------------ */ private interface ChangeTask { public void run(); } }
true
true
public void doSelect() throws IOException { try { _selecting=Thread.currentThread(); List<?> changes; final Selector selector; synchronized (_changes) { changes=_changes[_change]; _change=_change==0?1:0; selector=_selector; } // Make any key changes required final int size=changes.size(); for (int i = 0; i < size; i++) { try { Object o = changes.get(i); if (o instanceof EndPoint) { // Update the operations for a key. SelectChannelEndPoint endpoint = (SelectChannelEndPoint)o; endpoint.doUpdateKey(); } else if (o instanceof Runnable) { dispatch((Runnable)o); } else if (o instanceof ChangeSelectableChannel) { // finish accepting/connecting this connection final ChangeSelectableChannel asc = (ChangeSelectableChannel)o; final SelectableChannel channel=asc._channel; final Object att = asc._attachment; if ((channel instanceof SocketChannel) && ((SocketChannel)channel).isConnected()) { SelectionKey key = channel.register(selector,SelectionKey.OP_READ,att); SelectChannelEndPoint endpoint = newEndPoint((SocketChannel)channel,this,key); key.attach(endpoint); endpoint.schedule(); } else if (channel.isOpen()) { channel.register(selector,SelectionKey.OP_CONNECT,att); } } else if (o instanceof SocketChannel) { final SocketChannel channel=(SocketChannel)o; if (channel.isConnected()) { SelectionKey key = channel.register(selector,SelectionKey.OP_READ,null); SelectChannelEndPoint endpoint = newEndPoint(channel,this,key); key.attach(endpoint); endpoint.schedule(); } else if (channel.isOpen()) { channel.register(selector,SelectionKey.OP_CONNECT,null); } } else if (o instanceof ServerSocketChannel) { ServerSocketChannel channel = (ServerSocketChannel)o; channel.register(getSelector(),SelectionKey.OP_ACCEPT); } else if (o instanceof ChangeTask) { ((ChangeTask)o).run(); } else throw new IllegalArgumentException(o.toString()); } catch (CancelledKeyException e) { if (isRunning()) Log.warn(e); else Log.debug(e); } } changes.clear(); long idle_next; long retry_next; long now=System.currentTimeMillis(); synchronized (this) { _idleTimeout.setNow(now); _timeout.setNow(now); if (_lowResourcesConnections>0 && selector.keys().size()>_lowResourcesConnections) _idleTimeout.setDuration(_lowResourcesMaxIdleTime); else _idleTimeout.setDuration(_maxIdleTime); idle_next=_idleTimeout.getTimeToNext(); retry_next=_timeout.getTimeToNext(); } // workout how low to wait in select long wait = 1000L; // not getMaxIdleTime() as the now value of the idle timers needs to be updated. if (idle_next >= 0 && wait > idle_next) wait = idle_next; if (wait > 0 && retry_next >= 0 && wait > retry_next) wait = retry_next; // Do the select. if (wait > 0) { // If we are in pausing mode if (_pausing) { try { Thread.sleep(__BUSY_PAUSE); // pause to reduce impact of busy loop } catch(InterruptedException e) { Log.ignore(e); } } long before=now; int selected=selector.select(wait); now = System.currentTimeMillis(); _idleTimeout.setNow(now); _timeout.setNow(now); _selects++; // Look for JVM bugs over a monitor period. // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6403933 // http://bugs.sun.com/view_bug.do?bug_id=6693490 if (now>_monitorNext) { _selects=(int)(_selects*__MONITOR_PERIOD/(now-_monitorStart)); _pausing=_selects>__MAX_SELECTS; if (_pausing) _paused++; _selects=0; _jvmBug=0; _monitorStart=now; _monitorNext=now+__MONITOR_PERIOD; } if (now>_log) { if (_paused>0) Log.info(this+" Busy selector - injecting delay "+_paused+" times"); if (_jvmFix2>0) Log.info(this+" JVM BUG(s) - injecting delay"+_jvmFix2+" times"); if (_jvmFix1>0) Log.info(this+" JVM BUG(s) - recreating selector "+_jvmFix1+" times, canceled keys "+_jvmFix0+" times"); else if(Log.isDebugEnabled() && _jvmFix0>0) Log.info(this+" JVM BUG(s) - canceled keys "+_jvmFix0+" times"); _paused=0; _jvmFix2=0; _jvmFix1=0; _jvmFix0=0; _log=now+60000; } // If we see signature of possible JVM bug, increment count. if (selected==0 && wait>10 && (now-before)<(wait/2)) { // Increment bug count and try a work around _jvmBug++; if (_jvmBug>(__JVMBUG_THRESHHOLD)) { try { if (_jvmBug==__JVMBUG_THRESHHOLD+1) _jvmFix2++; Thread.sleep(__BUSY_PAUSE); // pause to avoid busy loop } catch(InterruptedException e) { Log.ignore(e); } } else if (_jvmBug==__JVMBUG_THRESHHOLD) { synchronized (this) { // BLOODY SUN BUG !!! Try refreshing the entire selector. final Selector new_selector = Selector.open(); for (SelectionKey k: selector.keys()) { if (!k.isValid() || k.interestOps()==0) continue; final SelectableChannel channel = k.channel(); final Object attachment = k.attachment(); if (attachment==null) addChange(channel); else addChange(channel,attachment); } _selector.close(); _selector=new_selector; return; } } else if (_jvmBug%32==31) // heuristic attempt to cancel key 31,63,95,... loops { // Cancel keys with 0 interested ops int cancelled=0; for (SelectionKey k: selector.keys()) { if (k.isValid()&&k.interestOps()==0) { k.cancel(); cancelled++; } } if (cancelled>0) _jvmFix0++; return; } } else if (__BUSY_KEY>0 && selected==1 && _selects>__MAX_SELECTS) { // Look for busy key SelectionKey busy = (SelectionKey)selector.selectedKeys().iterator().next(); if (busy==_busyKey) { if (++_busyKeyCount>__BUSY_KEY) { SelectChannelEndPoint endpoint = (SelectChannelEndPoint)busy.attachment(); Log.warn("Busy Key "+busy+" "+endpoint); busy.cancel(); if (endpoint!=null) endpoint.close(); } } else _busyKeyCount=0; _busyKey=busy; } } else { selector.selectNow(); _selects++; } // have we been destroyed while sleeping if (_selector==null || !selector.isOpen()) return; // Look for things to do for (SelectionKey key: selector.selectedKeys()) { try { if (!key.isValid()) { key.cancel(); SelectChannelEndPoint endpoint = (SelectChannelEndPoint)key.attachment(); if (endpoint != null) endpoint.doUpdateKey(); continue; } Object att = key.attachment(); if (att instanceof SelectChannelEndPoint) { ((SelectChannelEndPoint)att).schedule(); } else if (key.isAcceptable()) { SocketChannel channel = acceptChannel(key); if (channel==null) continue; channel.configureBlocking(false); // TODO make it reluctant to leave 0 _nextSet=++_nextSet%_selectSet.length; // Is this for this selectset if (_nextSet==_setID) { // bind connections to this select set. SelectionKey cKey = channel.register(_selectSet[_nextSet].getSelector(), SelectionKey.OP_READ); SelectChannelEndPoint endpoint=newEndPoint(channel,_selectSet[_nextSet],cKey); cKey.attach(endpoint); if (endpoint != null) endpoint.schedule(); } else { // nope - give it to another. _selectSet[_nextSet].addChange(channel); _selectSet[_nextSet].wakeup(); } } else if (key.isConnectable()) { // Complete a connection of a registered channel SocketChannel channel = (SocketChannel)key.channel(); boolean connected=false; try { connected=channel.finishConnect(); } catch(Exception e) { connectionFailed(channel,e,att); } finally { if (connected) { key.interestOps(SelectionKey.OP_READ); SelectChannelEndPoint endpoint = newEndPoint(channel,this,key); key.attach(endpoint); endpoint.schedule(); } else { key.cancel(); } } } else { // Wrap readable registered channel in an endpoint SocketChannel channel = (SocketChannel)key.channel(); SelectChannelEndPoint endpoint = newEndPoint(channel,this,key); key.attach(endpoint); if (key.isReadable()) endpoint.schedule(); } key = null; } catch (CancelledKeyException e) { Log.ignore(e); } catch (Exception e) { if (isRunning()) Log.warn(e); else Log.ignore(e); if (key != null && !(key.channel() instanceof ServerSocketChannel) && key.isValid()) key.cancel(); } } // Everything always handled selector.selectedKeys().clear(); // tick over the timers _idleTimeout.tick(now); _timeout.tick(now); } catch (CancelledKeyException e) { Log.ignore(e); } finally { _selecting=null; } }
public void doSelect() throws IOException { try { _selecting=Thread.currentThread(); List<?> changes; final Selector selector; synchronized (_changes) { changes=_changes[_change]; _change=_change==0?1:0; selector=_selector; } // Make any key changes required final int size=changes.size(); for (int i = 0; i < size; i++) { try { Object o = changes.get(i); if (o instanceof EndPoint) { // Update the operations for a key. SelectChannelEndPoint endpoint = (SelectChannelEndPoint)o; endpoint.doUpdateKey(); } else if (o instanceof Runnable) { dispatch((Runnable)o); } else if (o instanceof ChangeSelectableChannel) { // finish accepting/connecting this connection final ChangeSelectableChannel asc = (ChangeSelectableChannel)o; final SelectableChannel channel=asc._channel; final Object att = asc._attachment; if ((channel instanceof SocketChannel) && ((SocketChannel)channel).isConnected()) { SelectionKey key = channel.register(selector,SelectionKey.OP_READ,att); SelectChannelEndPoint endpoint = newEndPoint((SocketChannel)channel,this,key); key.attach(endpoint); endpoint.schedule(); } else if (channel.isOpen()) { channel.register(selector,SelectionKey.OP_CONNECT,att); } } else if (o instanceof SocketChannel) { final SocketChannel channel=(SocketChannel)o; if (channel.isConnected()) { SelectionKey key = channel.register(selector,SelectionKey.OP_READ,null); SelectChannelEndPoint endpoint = newEndPoint(channel,this,key); key.attach(endpoint); endpoint.schedule(); } else if (channel.isOpen()) { channel.register(selector,SelectionKey.OP_CONNECT,null); } } else if (o instanceof ServerSocketChannel) { ServerSocketChannel channel = (ServerSocketChannel)o; channel.register(getSelector(),SelectionKey.OP_ACCEPT); } else if (o instanceof ChangeTask) { ((ChangeTask)o).run(); } else throw new IllegalArgumentException(o.toString()); } catch (Exception e) { if (isRunning()) Log.warn(e); else Log.debug(e); } } changes.clear(); long idle_next; long retry_next; long now=System.currentTimeMillis(); synchronized (this) { _idleTimeout.setNow(now); _timeout.setNow(now); if (_lowResourcesConnections>0 && selector.keys().size()>_lowResourcesConnections) _idleTimeout.setDuration(_lowResourcesMaxIdleTime); else _idleTimeout.setDuration(_maxIdleTime); idle_next=_idleTimeout.getTimeToNext(); retry_next=_timeout.getTimeToNext(); } // workout how low to wait in select long wait = 1000L; // not getMaxIdleTime() as the now value of the idle timers needs to be updated. if (idle_next >= 0 && wait > idle_next) wait = idle_next; if (wait > 0 && retry_next >= 0 && wait > retry_next) wait = retry_next; // Do the select. if (wait > 0) { // If we are in pausing mode if (_pausing) { try { Thread.sleep(__BUSY_PAUSE); // pause to reduce impact of busy loop } catch(InterruptedException e) { Log.ignore(e); } } long before=now; int selected=selector.select(wait); now = System.currentTimeMillis(); _idleTimeout.setNow(now); _timeout.setNow(now); _selects++; // Look for JVM bugs over a monitor period. // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6403933 // http://bugs.sun.com/view_bug.do?bug_id=6693490 if (now>_monitorNext) { _selects=(int)(_selects*__MONITOR_PERIOD/(now-_monitorStart)); _pausing=_selects>__MAX_SELECTS; if (_pausing) _paused++; _selects=0; _jvmBug=0; _monitorStart=now; _monitorNext=now+__MONITOR_PERIOD; } if (now>_log) { if (_paused>0) Log.info(this+" Busy selector - injecting delay "+_paused+" times"); if (_jvmFix2>0) Log.info(this+" JVM BUG(s) - injecting delay"+_jvmFix2+" times"); if (_jvmFix1>0) Log.info(this+" JVM BUG(s) - recreating selector "+_jvmFix1+" times, canceled keys "+_jvmFix0+" times"); else if(Log.isDebugEnabled() && _jvmFix0>0) Log.info(this+" JVM BUG(s) - canceled keys "+_jvmFix0+" times"); _paused=0; _jvmFix2=0; _jvmFix1=0; _jvmFix0=0; _log=now+60000; } // If we see signature of possible JVM bug, increment count. if (selected==0 && wait>10 && (now-before)<(wait/2)) { // Increment bug count and try a work around _jvmBug++; if (_jvmBug>(__JVMBUG_THRESHHOLD)) { try { if (_jvmBug==__JVMBUG_THRESHHOLD+1) _jvmFix2++; Thread.sleep(__BUSY_PAUSE); // pause to avoid busy loop } catch(InterruptedException e) { Log.ignore(e); } } else if (_jvmBug==__JVMBUG_THRESHHOLD) { synchronized (this) { // BLOODY SUN BUG !!! Try refreshing the entire selector. final Selector new_selector = Selector.open(); for (SelectionKey k: selector.keys()) { if (!k.isValid() || k.interestOps()==0) continue; final SelectableChannel channel = k.channel(); final Object attachment = k.attachment(); if (attachment==null) addChange(channel); else addChange(channel,attachment); } _selector.close(); _selector=new_selector; return; } } else if (_jvmBug%32==31) // heuristic attempt to cancel key 31,63,95,... loops { // Cancel keys with 0 interested ops int cancelled=0; for (SelectionKey k: selector.keys()) { if (k.isValid()&&k.interestOps()==0) { k.cancel(); cancelled++; } } if (cancelled>0) _jvmFix0++; return; } } else if (__BUSY_KEY>0 && selected==1 && _selects>__MAX_SELECTS) { // Look for busy key SelectionKey busy = (SelectionKey)selector.selectedKeys().iterator().next(); if (busy==_busyKey) { if (++_busyKeyCount>__BUSY_KEY) { SelectChannelEndPoint endpoint = (SelectChannelEndPoint)busy.attachment(); Log.warn("Busy Key "+busy+" "+endpoint); busy.cancel(); if (endpoint!=null) endpoint.close(); } } else _busyKeyCount=0; _busyKey=busy; } } else { selector.selectNow(); _selects++; } // have we been destroyed while sleeping if (_selector==null || !selector.isOpen()) return; // Look for things to do for (SelectionKey key: selector.selectedKeys()) { try { if (!key.isValid()) { key.cancel(); SelectChannelEndPoint endpoint = (SelectChannelEndPoint)key.attachment(); if (endpoint != null) endpoint.doUpdateKey(); continue; } Object att = key.attachment(); if (att instanceof SelectChannelEndPoint) { ((SelectChannelEndPoint)att).schedule(); } else if (key.isAcceptable()) { SocketChannel channel = acceptChannel(key); if (channel==null) continue; channel.configureBlocking(false); // TODO make it reluctant to leave 0 _nextSet=++_nextSet%_selectSet.length; // Is this for this selectset if (_nextSet==_setID) { // bind connections to this select set. SelectionKey cKey = channel.register(_selectSet[_nextSet].getSelector(), SelectionKey.OP_READ); SelectChannelEndPoint endpoint=newEndPoint(channel,_selectSet[_nextSet],cKey); cKey.attach(endpoint); if (endpoint != null) endpoint.schedule(); } else { // nope - give it to another. _selectSet[_nextSet].addChange(channel); _selectSet[_nextSet].wakeup(); } } else if (key.isConnectable()) { // Complete a connection of a registered channel SocketChannel channel = (SocketChannel)key.channel(); boolean connected=false; try { connected=channel.finishConnect(); } catch(Exception e) { connectionFailed(channel,e,att); } finally { if (connected) { key.interestOps(SelectionKey.OP_READ); SelectChannelEndPoint endpoint = newEndPoint(channel,this,key); key.attach(endpoint); endpoint.schedule(); } else { key.cancel(); } } } else { // Wrap readable registered channel in an endpoint SocketChannel channel = (SocketChannel)key.channel(); SelectChannelEndPoint endpoint = newEndPoint(channel,this,key); key.attach(endpoint); if (key.isReadable()) endpoint.schedule(); } key = null; } catch (CancelledKeyException e) { Log.ignore(e); } catch (Exception e) { if (isRunning()) Log.warn(e); else Log.ignore(e); if (key != null && !(key.channel() instanceof ServerSocketChannel) && key.isValid()) key.cancel(); } } // Everything always handled selector.selectedKeys().clear(); // tick over the timers _idleTimeout.tick(now); _timeout.tick(now); } catch (CancelledKeyException e) { Log.ignore(e); } finally { _selecting=null; } }
diff --git a/addon-web-selenium/src/main/java/org/springframework/roo/addon/web/selenium/SeleniumOperationsImpl.java b/addon-web-selenium/src/main/java/org/springframework/roo/addon/web/selenium/SeleniumOperationsImpl.java index 1e707a4a3..8b796046e 100644 --- a/addon-web-selenium/src/main/java/org/springframework/roo/addon/web/selenium/SeleniumOperationsImpl.java +++ b/addon-web-selenium/src/main/java/org/springframework/roo/addon/web/selenium/SeleniumOperationsImpl.java @@ -1,348 +1,348 @@ package org.springframework.roo.addon.web.selenium; import java.io.InputStream; import java.math.BigDecimal; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.logging.Logger; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.springframework.roo.addon.web.mvc.controller.details.WebMetadataService; import org.springframework.roo.addon.web.mvc.controller.scaffold.mvc.WebScaffoldMetadata; import org.springframework.roo.addon.web.mvc.jsp.menu.MenuOperations; import org.springframework.roo.classpath.PhysicalTypeIdentifier; import org.springframework.roo.classpath.PhysicalTypeMetadata; import org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails; import org.springframework.roo.classpath.details.FieldMetadata; import org.springframework.roo.classpath.details.FieldMetadataBuilder; import org.springframework.roo.classpath.details.MemberFindingUtils; import org.springframework.roo.classpath.details.annotations.AnnotationAttributeValue; import org.springframework.roo.classpath.details.annotations.AnnotationMetadata; import org.springframework.roo.classpath.operations.DateTime; import org.springframework.roo.classpath.persistence.PersistenceMemberLocator; import org.springframework.roo.classpath.scanner.MemberDetails; import org.springframework.roo.classpath.scanner.MemberDetailsScanner; import org.springframework.roo.metadata.MetadataService; import org.springframework.roo.model.JavaSymbolName; import org.springframework.roo.model.JavaType; import org.springframework.roo.process.manager.FileManager; import org.springframework.roo.project.Path; import org.springframework.roo.project.PathResolver; import org.springframework.roo.project.Plugin; import org.springframework.roo.project.ProjectMetadata; import org.springframework.roo.project.ProjectOperations; import org.springframework.roo.support.logging.HandlerUtils; import org.springframework.roo.support.util.Assert; import org.springframework.roo.support.util.TemplateUtils; import org.springframework.roo.support.util.XmlUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; /** * Provides property file configuration operations. * * @author Stefan Schmidt * @since 1.0 */ @Component @Service public class SeleniumOperationsImpl implements SeleniumOperations { private static final Logger logger = HandlerUtils.getLogger(SeleniumOperationsImpl.class); @Reference private FileManager fileManager; @Reference private MetadataService metadataService; @Reference private MenuOperations menuOperations; @Reference private MemberDetailsScanner memberDetailsScanner; @Reference private ProjectOperations projectOperations; @Reference private WebMetadataService webMetadataService; @Reference private PersistenceMemberLocator persistenceMemberLocator; public boolean isProjectAvailable() { return projectOperations.isProjectAvailable() && fileManager.exists(projectOperations.getPathResolver().getIdentifier(Path.SRC_MAIN_WEBAPP, "WEB-INF/web.xml")); } /** * Creates a new Selenium testcase * * @param controller the JavaType of the controller under test (required) * @param name the name of the test case (optional) */ public void generateTest(JavaType controller, String name, String serverURL) { Assert.notNull(controller, "Controller type required"); String webScaffoldMetadataIdentifier = WebScaffoldMetadata.createIdentifier(controller, Path.SRC_MAIN_JAVA); WebScaffoldMetadata webScaffoldMetadata = (WebScaffoldMetadata) metadataService.get(webScaffoldMetadataIdentifier); Assert.notNull(webScaffoldMetadata, "Web controller '" + controller.getFullyQualifiedTypeName() + "' does not appear to be an automatic, scaffolded controller"); // We abort the creation of a selenium test if the controller does not allow the creation of new instances for the form backing object if (!webScaffoldMetadata.getAnnotationValues().isCreate()) { logger.warning("The controller you specified does not allow the creation of new instances of the form backing object. No Selenium tests created."); return; } if (!serverURL.endsWith("/")) { serverURL = serverURL + "/"; } JavaType formBackingType = webScaffoldMetadata.getAnnotationValues().getFormBackingObject(); String relativeTestFilePath = "selenium/test-" + formBackingType.getSimpleTypeName().toLowerCase() + ".xhtml"; String seleniumPath = projectOperations.getPathResolver().getIdentifier(Path.SRC_MAIN_WEBAPP, relativeTestFilePath); Document document; try { InputStream templateInputStream = TemplateUtils.getTemplate(getClass(), "selenium-template.xhtml"); Assert.notNull(templateInputStream, "Could not acquire selenium.xhtml template"); document = XmlUtils.readXml(templateInputStream); } catch (Exception e) { throw new IllegalStateException(e); } Element root = (Element) document.getLastChild(); if (root == null || !"html".equals(root.getNodeName())) { throw new IllegalArgumentException("Could not parse selenium test case template file!"); } name = (name != null ? name : "Selenium test for " + controller.getSimpleTypeName()); XmlUtils.findRequiredElement("/html/head/title", root).setTextContent(name); XmlUtils.findRequiredElement("/html/body/table/thead/tr/td", root).setTextContent(name); Element tbody = XmlUtils.findRequiredElement("/html/body/table/tbody", root); tbody.appendChild(openCommand(document, serverURL + projectOperations.getProjectMetadata().getProjectName() + "/" + webScaffoldMetadata.getAnnotationValues().getPath() + "?form")); PhysicalTypeMetadata formBackingObjectPhysicalTypeMetadata = (PhysicalTypeMetadata) metadataService.get(PhysicalTypeIdentifier.createIdentifier(formBackingType, Path.SRC_MAIN_JAVA)); Assert.notNull(formBackingObjectPhysicalTypeMetadata, "Unable to obtain physical type metadata for type " + formBackingType.getFullyQualifiedTypeName()); ClassOrInterfaceTypeDetails formBackingClassOrInterfaceDetails = (ClassOrInterfaceTypeDetails) formBackingObjectPhysicalTypeMetadata.getMemberHoldingTypeDetails(); MemberDetails memberDetails = memberDetailsScanner.getMemberDetails(getClass().getName(), formBackingClassOrInterfaceDetails); // Add composite PK identifier fields if needed - for (FieldMetadata field : persistenceMemberLocator.getEmbeddedIdentifierFields(formBackingType)) { + for (FieldMetadata field : persistenceMemberLocator.getEmbeddedIdentifierFields(memberDetails)) { if (!field.getFieldType().isCommonCollectionType() && !isSpecialType(field.getFieldType())) { FieldMetadataBuilder fieldBuilder = new FieldMetadataBuilder(field); fieldBuilder.setFieldName(new JavaSymbolName(field.getFieldName().getSymbolName() + "." + field.getFieldName().getSymbolName())); tbody.appendChild(typeCommand(document, fieldBuilder.build())); } } // Add all other fields List<FieldMetadata> fields = webMetadataService.getScaffoldEligibleFieldMetadata(formBackingType, memberDetails, null); for (FieldMetadata field : fields) { if (!field.getFieldType().isCommonCollectionType() && !isSpecialType(field.getFieldType())) { tbody.appendChild(typeCommand(document, field)); } } tbody.appendChild(clickAndWaitCommand(document, "//input[@id='proceed']")); // Add verifications for all other fields for (FieldMetadata field : fields) { if (!field.getFieldType().isCommonCollectionType() && !isSpecialType(field.getFieldType())) { tbody.appendChild(verifyTextCommand(document, formBackingType, field)); } } fileManager.createOrUpdateTextFileIfRequired(seleniumPath, XmlUtils.nodeToString(document), false); manageTestSuite(relativeTestFilePath, name, serverURL); installMavenPlugin(); } private void manageTestSuite(String testPath, String name, String serverURL) { String relativeTestFilePath = "selenium/test-suite.xhtml"; String seleniumPath = projectOperations.getPathResolver().getIdentifier(Path.SRC_MAIN_WEBAPP, relativeTestFilePath); Document suite; try { if (fileManager.exists(seleniumPath)) { suite = XmlUtils.readXml(fileManager.getInputStream(seleniumPath)); } else { InputStream templateInputStream = TemplateUtils.getTemplate(getClass(), "selenium-test-suite-template.xhtml"); Assert.notNull(templateInputStream, "Could not acquire selenium test suite template"); suite = XmlUtils.readXml(templateInputStream); } } catch (Exception e) { throw new IllegalStateException(e); } ProjectMetadata projectMetadata = projectOperations.getProjectMetadata(); Assert.notNull(projectMetadata, "Unable to obtain project metadata"); Element root = (Element) suite.getLastChild(); XmlUtils.findRequiredElement("/html/head/title", root).setTextContent("Test suite for " + projectMetadata.getProjectName() + "project"); Element tr = suite.createElement("tr"); Element td = suite.createElement("td"); tr.appendChild(td); Element a = suite.createElement("a"); a.setAttribute("href", serverURL + projectMetadata.getProjectName() + "/resources/" + testPath); a.setTextContent(name); td.appendChild(a); XmlUtils.findRequiredElement("/html/body/table", root).appendChild(tr); fileManager.createOrUpdateTextFileIfRequired(seleniumPath, XmlUtils.nodeToString(suite), false); menuOperations.addMenuItem(new JavaSymbolName("SeleniumTests"), new JavaSymbolName("Test"), "Test", "selenium_menu_test_suite", "/resources/" + relativeTestFilePath, "si_"); } private void installMavenPlugin() { PathResolver pathResolver = projectOperations.getPathResolver(); String pom = pathResolver.getIdentifier(Path.ROOT, "/pom.xml"); Document document = XmlUtils.readXml(fileManager.getInputStream(pom)); Element root = (Element) document.getLastChild(); // Stop if the plugin is already installed if (XmlUtils.findFirstElement("/project/build/plugins/plugin[artifactId = 'selenium-maven-plugin']", root) != null) { return; } Element configuration = XmlUtils.getConfiguration(getClass()); Element plugin = XmlUtils.findFirstElement("/configuration/selenium/plugin", configuration); // Now install the plugin itself if (plugin != null) { projectOperations.addBuildPlugin(new Plugin(plugin)); } } private Node clickAndWaitCommand(Document document, String linkTarget) { Node tr = document.createElement("tr"); Node td1 = tr.appendChild(document.createElement("td")); td1.setTextContent("clickAndWait"); Node td2 = tr.appendChild(document.createElement("td")); td2.setTextContent(linkTarget); Node td3 = tr.appendChild(document.createElement("td")); td3.setTextContent(" "); return tr; } private Node typeCommand(Document document, FieldMetadata field) { Node tr = document.createElement("tr"); Node td1 = tr.appendChild(document.createElement("td")); td1.setTextContent("type"); Node td2 = tr.appendChild(document.createElement("td")); td2.setTextContent("_" + field.getFieldName().getSymbolName() + "_id"); Node td3 = tr.appendChild(document.createElement("td")); td3.setTextContent(convertToInitializer(field)); return tr; } private Node verifyTextCommand(Document document, JavaType formBackingType, FieldMetadata field) { Node tr = document.createElement("tr"); Node td1 = tr.appendChild(document.createElement("td")); td1.setTextContent("verifyText"); Node td2 = tr.appendChild(document.createElement("td")); td2.setTextContent(XmlUtils.convertId("_s_" + formBackingType.getFullyQualifiedTypeName() + "_" + field.getFieldName().getSymbolName() + "_" + field.getFieldName().getSymbolName() + "_id")); Node td3 = tr.appendChild(document.createElement("td")); td3.setTextContent(convertToInitializer(field)); return tr; } private String convertToInitializer(FieldMetadata field) { String initializer = " "; short index = 1; AnnotationMetadata min = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.validation.constraints.Min")); if (min != null) { AnnotationAttributeValue<?> value = min.getAttribute(new JavaSymbolName("value")); if (value != null) { index = new Short(value.getValue().toString()); } } if (field.getFieldName().getSymbolName().contains("email") || field.getFieldName().getSymbolName().contains("Email")) { initializer = "[email protected]"; } else if (field.getFieldType().equals(JavaType.STRING_OBJECT)) { initializer = "some" + field.getFieldName().getSymbolNameCapitalisedFirstLetter() + index; } else if (field.getFieldType().equals(new JavaType(Date.class.getName())) || field.getFieldType().equals(new JavaType(Calendar.class.getName()))) { Calendar cal = Calendar.getInstance(); AnnotationMetadata dateTimeFormat = null; String style = null; if (null != (dateTimeFormat = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("org.springframework.format.annotation.DateTimeFormat")))) { AnnotationAttributeValue<?> value = dateTimeFormat.getAttribute(new JavaSymbolName("style")); if (value != null) { style = value.getValue().toString(); } } if (null != MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.validation.constraints.Past"))) { cal.add(Calendar.YEAR, -1); cal.add(Calendar.MONTH, -1); cal.add(Calendar.DAY_OF_MONTH, -1); } else if (null != MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.validation.constraints.Future"))) { cal.add(Calendar.YEAR, +1); cal.add(Calendar.MONTH, +1); cal.add(Calendar.DAY_OF_MONTH, +1); } if (style != null) { if (style.startsWith("-")) { initializer = ((SimpleDateFormat) DateFormat.getTimeInstance(DateTime.parseDateFormat(style.charAt(1)), Locale.getDefault())).format(cal.getTime()); } else if (style.endsWith("-")) { initializer = ((SimpleDateFormat) DateFormat.getDateInstance(DateTime.parseDateFormat(style.charAt(0)), Locale.getDefault())).format(cal.getTime()); } else { initializer = ((SimpleDateFormat) DateFormat.getDateTimeInstance(DateTime.parseDateFormat(style.charAt(0)), DateTime.parseDateFormat(style.charAt(1)), Locale.getDefault())).format(cal.getTime()); } } else { initializer = ((SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault())).format(cal.getTime()); } } else if (field.getFieldType().equals(JavaType.BOOLEAN_OBJECT) || field.getFieldType().equals(JavaType.BOOLEAN_PRIMITIVE)) { initializer = new Boolean(false).toString(); } else if (field.getFieldType().equals(JavaType.INT_OBJECT) || field.getFieldType().equals(JavaType.INT_PRIMITIVE)) { initializer = new Integer(index).toString(); } else if (field.getFieldType().equals(JavaType.DOUBLE_OBJECT) || field.getFieldType().equals(JavaType.DOUBLE_PRIMITIVE)) { initializer = new Double(index).toString(); } else if (field.getFieldType().equals(JavaType.FLOAT_OBJECT) || field.getFieldType().equals(JavaType.FLOAT_PRIMITIVE)) { initializer = new Float(index).toString(); } else if (field.getFieldType().equals(JavaType.LONG_OBJECT) || field.getFieldType().equals(JavaType.LONG_PRIMITIVE)) { initializer = new Long(index).toString(); } else if (field.getFieldType().equals(JavaType.SHORT_OBJECT) || field.getFieldType().equals(JavaType.SHORT_PRIMITIVE)) { initializer = new Short(index).toString(); } else if (field.getFieldType().equals(new JavaType("java.math.BigDecimal"))) { initializer = new BigDecimal(index).toString(); } return initializer; } private Node openCommand(Document document, String linkTarget) { Node tr = document.createElement("tr"); Node td1 = tr.appendChild(document.createElement("td")); td1.setTextContent("open"); Node td2 = tr.appendChild(document.createElement("td")); td2.setTextContent(linkTarget + (linkTarget.contains("?") ? "&" : "?") + "lang=" + Locale.getDefault()); Node td3 = tr.appendChild(document.createElement("td")); td3.setTextContent(" "); return tr; } private boolean isSpecialType(JavaType javaType) { String physicalTypeIdentifier = PhysicalTypeIdentifier.createIdentifier(javaType, Path.SRC_MAIN_JAVA); // We are only interested if the type is part of our application and if no editor exists for it already if (metadataService.get(physicalTypeIdentifier) != null) { return true; } return false; } }
true
true
public void generateTest(JavaType controller, String name, String serverURL) { Assert.notNull(controller, "Controller type required"); String webScaffoldMetadataIdentifier = WebScaffoldMetadata.createIdentifier(controller, Path.SRC_MAIN_JAVA); WebScaffoldMetadata webScaffoldMetadata = (WebScaffoldMetadata) metadataService.get(webScaffoldMetadataIdentifier); Assert.notNull(webScaffoldMetadata, "Web controller '" + controller.getFullyQualifiedTypeName() + "' does not appear to be an automatic, scaffolded controller"); // We abort the creation of a selenium test if the controller does not allow the creation of new instances for the form backing object if (!webScaffoldMetadata.getAnnotationValues().isCreate()) { logger.warning("The controller you specified does not allow the creation of new instances of the form backing object. No Selenium tests created."); return; } if (!serverURL.endsWith("/")) { serverURL = serverURL + "/"; } JavaType formBackingType = webScaffoldMetadata.getAnnotationValues().getFormBackingObject(); String relativeTestFilePath = "selenium/test-" + formBackingType.getSimpleTypeName().toLowerCase() + ".xhtml"; String seleniumPath = projectOperations.getPathResolver().getIdentifier(Path.SRC_MAIN_WEBAPP, relativeTestFilePath); Document document; try { InputStream templateInputStream = TemplateUtils.getTemplate(getClass(), "selenium-template.xhtml"); Assert.notNull(templateInputStream, "Could not acquire selenium.xhtml template"); document = XmlUtils.readXml(templateInputStream); } catch (Exception e) { throw new IllegalStateException(e); } Element root = (Element) document.getLastChild(); if (root == null || !"html".equals(root.getNodeName())) { throw new IllegalArgumentException("Could not parse selenium test case template file!"); } name = (name != null ? name : "Selenium test for " + controller.getSimpleTypeName()); XmlUtils.findRequiredElement("/html/head/title", root).setTextContent(name); XmlUtils.findRequiredElement("/html/body/table/thead/tr/td", root).setTextContent(name); Element tbody = XmlUtils.findRequiredElement("/html/body/table/tbody", root); tbody.appendChild(openCommand(document, serverURL + projectOperations.getProjectMetadata().getProjectName() + "/" + webScaffoldMetadata.getAnnotationValues().getPath() + "?form")); PhysicalTypeMetadata formBackingObjectPhysicalTypeMetadata = (PhysicalTypeMetadata) metadataService.get(PhysicalTypeIdentifier.createIdentifier(formBackingType, Path.SRC_MAIN_JAVA)); Assert.notNull(formBackingObjectPhysicalTypeMetadata, "Unable to obtain physical type metadata for type " + formBackingType.getFullyQualifiedTypeName()); ClassOrInterfaceTypeDetails formBackingClassOrInterfaceDetails = (ClassOrInterfaceTypeDetails) formBackingObjectPhysicalTypeMetadata.getMemberHoldingTypeDetails(); MemberDetails memberDetails = memberDetailsScanner.getMemberDetails(getClass().getName(), formBackingClassOrInterfaceDetails); // Add composite PK identifier fields if needed for (FieldMetadata field : persistenceMemberLocator.getEmbeddedIdentifierFields(formBackingType)) { if (!field.getFieldType().isCommonCollectionType() && !isSpecialType(field.getFieldType())) { FieldMetadataBuilder fieldBuilder = new FieldMetadataBuilder(field); fieldBuilder.setFieldName(new JavaSymbolName(field.getFieldName().getSymbolName() + "." + field.getFieldName().getSymbolName())); tbody.appendChild(typeCommand(document, fieldBuilder.build())); } } // Add all other fields List<FieldMetadata> fields = webMetadataService.getScaffoldEligibleFieldMetadata(formBackingType, memberDetails, null); for (FieldMetadata field : fields) { if (!field.getFieldType().isCommonCollectionType() && !isSpecialType(field.getFieldType())) { tbody.appendChild(typeCommand(document, field)); } } tbody.appendChild(clickAndWaitCommand(document, "//input[@id='proceed']")); // Add verifications for all other fields for (FieldMetadata field : fields) { if (!field.getFieldType().isCommonCollectionType() && !isSpecialType(field.getFieldType())) { tbody.appendChild(verifyTextCommand(document, formBackingType, field)); } } fileManager.createOrUpdateTextFileIfRequired(seleniumPath, XmlUtils.nodeToString(document), false); manageTestSuite(relativeTestFilePath, name, serverURL); installMavenPlugin(); }
public void generateTest(JavaType controller, String name, String serverURL) { Assert.notNull(controller, "Controller type required"); String webScaffoldMetadataIdentifier = WebScaffoldMetadata.createIdentifier(controller, Path.SRC_MAIN_JAVA); WebScaffoldMetadata webScaffoldMetadata = (WebScaffoldMetadata) metadataService.get(webScaffoldMetadataIdentifier); Assert.notNull(webScaffoldMetadata, "Web controller '" + controller.getFullyQualifiedTypeName() + "' does not appear to be an automatic, scaffolded controller"); // We abort the creation of a selenium test if the controller does not allow the creation of new instances for the form backing object if (!webScaffoldMetadata.getAnnotationValues().isCreate()) { logger.warning("The controller you specified does not allow the creation of new instances of the form backing object. No Selenium tests created."); return; } if (!serverURL.endsWith("/")) { serverURL = serverURL + "/"; } JavaType formBackingType = webScaffoldMetadata.getAnnotationValues().getFormBackingObject(); String relativeTestFilePath = "selenium/test-" + formBackingType.getSimpleTypeName().toLowerCase() + ".xhtml"; String seleniumPath = projectOperations.getPathResolver().getIdentifier(Path.SRC_MAIN_WEBAPP, relativeTestFilePath); Document document; try { InputStream templateInputStream = TemplateUtils.getTemplate(getClass(), "selenium-template.xhtml"); Assert.notNull(templateInputStream, "Could not acquire selenium.xhtml template"); document = XmlUtils.readXml(templateInputStream); } catch (Exception e) { throw new IllegalStateException(e); } Element root = (Element) document.getLastChild(); if (root == null || !"html".equals(root.getNodeName())) { throw new IllegalArgumentException("Could not parse selenium test case template file!"); } name = (name != null ? name : "Selenium test for " + controller.getSimpleTypeName()); XmlUtils.findRequiredElement("/html/head/title", root).setTextContent(name); XmlUtils.findRequiredElement("/html/body/table/thead/tr/td", root).setTextContent(name); Element tbody = XmlUtils.findRequiredElement("/html/body/table/tbody", root); tbody.appendChild(openCommand(document, serverURL + projectOperations.getProjectMetadata().getProjectName() + "/" + webScaffoldMetadata.getAnnotationValues().getPath() + "?form")); PhysicalTypeMetadata formBackingObjectPhysicalTypeMetadata = (PhysicalTypeMetadata) metadataService.get(PhysicalTypeIdentifier.createIdentifier(formBackingType, Path.SRC_MAIN_JAVA)); Assert.notNull(formBackingObjectPhysicalTypeMetadata, "Unable to obtain physical type metadata for type " + formBackingType.getFullyQualifiedTypeName()); ClassOrInterfaceTypeDetails formBackingClassOrInterfaceDetails = (ClassOrInterfaceTypeDetails) formBackingObjectPhysicalTypeMetadata.getMemberHoldingTypeDetails(); MemberDetails memberDetails = memberDetailsScanner.getMemberDetails(getClass().getName(), formBackingClassOrInterfaceDetails); // Add composite PK identifier fields if needed for (FieldMetadata field : persistenceMemberLocator.getEmbeddedIdentifierFields(memberDetails)) { if (!field.getFieldType().isCommonCollectionType() && !isSpecialType(field.getFieldType())) { FieldMetadataBuilder fieldBuilder = new FieldMetadataBuilder(field); fieldBuilder.setFieldName(new JavaSymbolName(field.getFieldName().getSymbolName() + "." + field.getFieldName().getSymbolName())); tbody.appendChild(typeCommand(document, fieldBuilder.build())); } } // Add all other fields List<FieldMetadata> fields = webMetadataService.getScaffoldEligibleFieldMetadata(formBackingType, memberDetails, null); for (FieldMetadata field : fields) { if (!field.getFieldType().isCommonCollectionType() && !isSpecialType(field.getFieldType())) { tbody.appendChild(typeCommand(document, field)); } } tbody.appendChild(clickAndWaitCommand(document, "//input[@id='proceed']")); // Add verifications for all other fields for (FieldMetadata field : fields) { if (!field.getFieldType().isCommonCollectionType() && !isSpecialType(field.getFieldType())) { tbody.appendChild(verifyTextCommand(document, formBackingType, field)); } } fileManager.createOrUpdateTextFileIfRequired(seleniumPath, XmlUtils.nodeToString(document), false); manageTestSuite(relativeTestFilePath, name, serverURL); installMavenPlugin(); }
diff --git a/src/test/java/org/atlasapi/beans/JaxbXmlTranslatorTest.java b/src/test/java/org/atlasapi/beans/JaxbXmlTranslatorTest.java index b297e211f..1b4f7d866 100644 --- a/src/test/java/org/atlasapi/beans/JaxbXmlTranslatorTest.java +++ b/src/test/java/org/atlasapi/beans/JaxbXmlTranslatorTest.java @@ -1,120 +1,121 @@ /* 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.beans; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import java.util.Set; import junit.framework.TestCase; import org.atlasapi.media.entity.simple.Broadcast; import org.atlasapi.media.entity.simple.ContentQueryResult; import org.atlasapi.media.entity.simple.Description; import org.atlasapi.media.entity.simple.Item; import org.atlasapi.media.entity.simple.ContentIdentifier.ItemIdentifier; import org.atlasapi.media.entity.simple.Location; import org.atlasapi.media.entity.simple.Playlist; import org.joda.time.DateTime; import com.google.common.collect.ImmutableList; import com.google.common.collect.Sets; import com.metabroadcast.common.servlet.StubHttpServletRequest; import com.metabroadcast.common.servlet.StubHttpServletResponse; /** * @author Robert Chatley ([email protected]) */ public class JaxbXmlTranslatorTest extends TestCase { private StubHttpServletRequest request; private StubHttpServletResponse response; @Override public void setUp() throws Exception { this.request = new StubHttpServletRequest(); this.response = new StubHttpServletResponse(); } public void testCanOutputSimpleItemObjectModelAsXml() throws Exception { Set<Object> graph = Sets.newHashSet(); Item item = new Item(); item.setTitle("Blue Peter"); item.setUri("http://www.bbc.co.uk/programmes/bluepeter"); item.setAliases(Sets.newHashSet("http://www.bbc.co.uk/p/bluepeter")); Location location = new Location(); location.setUri("http://www.bbc.co.uk/bluepeter"); location.setEmbedCode("<object><embed></embed></object>"); item.addLocation(location); DateTime transmitted = new DateTime(1990, 1, 1, 1, 1, 1, 1); item.addBroadcast(new Broadcast("channel", transmitted, transmitted.plusHours(1))); ContentQueryResult result = new ContentQueryResult(); result.add(item); graph.add(result); new JaxbXmlTranslator().writeTo(request, response, graph, AtlasModelType.CONTENT); String output = response.getResponseAsString(); assertThat(output, containsString("<play:item>" + "<uri>http://www.bbc.co.uk/programmes/bluepeter</uri>" + "<aliases>" + "<alias>http://www.bbc.co.uk/p/bluepeter</alias>" + "</aliases>" + "<clips/>" + "<play:genres/>" + "<play:sameAs/>" + "<play:tags/>" + "<title>Blue Peter</title>" + "<play:broadcasts>" + "<play:broadcast>" + "<broadcastDuration>3600</broadcastDuration>" + "<broadcastOn>channel</broadcastOn><transmissionEndTime>1990-01-01T02:01:01.001Z</transmissionEndTime>" + "<transmissionTime>1990-01-01T01:01:01.001Z</transmissionTime>" + "</play:broadcast>" + "</play:broadcasts>" + + "<play:countriesOfOrigin/>" + "<play:locations>" + "<play:location>" + "<available>true</available>" + "<play:availableCountries/>" + "<embedCode>&lt;object&gt;&lt;embed&gt;&lt;/embed&gt;&lt;/object&gt;</embedCode>" + "<uri>http://www.bbc.co.uk/bluepeter</uri>" + "</play:location>" + "</play:locations>" + "<play:people/>" + "</play:item>")); } public void testCanOutputSimpleListObjectModelAsXml() throws Exception { Set<Object> graph = Sets.newHashSet(); Playlist list = new Playlist(); ItemIdentifier item = new ItemIdentifier("http://www.bbc.co.uk/bluepeter"); list.add(item); ContentQueryResult result = new ContentQueryResult(); result.setContents(ImmutableList.<Description>of(list)); graph.add(result); new JaxbXmlTranslator().writeTo(request, response, graph, AtlasModelType.CONTENT); assertThat(response.getResponseAsString(), containsString("<play:item><type>Item</type>" + "<uri>http://www.bbc.co.uk/bluepeter</uri>" + "</play:item>")); } }
true
true
public void testCanOutputSimpleItemObjectModelAsXml() throws Exception { Set<Object> graph = Sets.newHashSet(); Item item = new Item(); item.setTitle("Blue Peter"); item.setUri("http://www.bbc.co.uk/programmes/bluepeter"); item.setAliases(Sets.newHashSet("http://www.bbc.co.uk/p/bluepeter")); Location location = new Location(); location.setUri("http://www.bbc.co.uk/bluepeter"); location.setEmbedCode("<object><embed></embed></object>"); item.addLocation(location); DateTime transmitted = new DateTime(1990, 1, 1, 1, 1, 1, 1); item.addBroadcast(new Broadcast("channel", transmitted, transmitted.plusHours(1))); ContentQueryResult result = new ContentQueryResult(); result.add(item); graph.add(result); new JaxbXmlTranslator().writeTo(request, response, graph, AtlasModelType.CONTENT); String output = response.getResponseAsString(); assertThat(output, containsString("<play:item>" + "<uri>http://www.bbc.co.uk/programmes/bluepeter</uri>" + "<aliases>" + "<alias>http://www.bbc.co.uk/p/bluepeter</alias>" + "</aliases>" + "<clips/>" + "<play:genres/>" + "<play:sameAs/>" + "<play:tags/>" + "<title>Blue Peter</title>" + "<play:broadcasts>" + "<play:broadcast>" + "<broadcastDuration>3600</broadcastDuration>" + "<broadcastOn>channel</broadcastOn><transmissionEndTime>1990-01-01T02:01:01.001Z</transmissionEndTime>" + "<transmissionTime>1990-01-01T01:01:01.001Z</transmissionTime>" + "</play:broadcast>" + "</play:broadcasts>" + "<play:locations>" + "<play:location>" + "<available>true</available>" + "<play:availableCountries/>" + "<embedCode>&lt;object&gt;&lt;embed&gt;&lt;/embed&gt;&lt;/object&gt;</embedCode>" + "<uri>http://www.bbc.co.uk/bluepeter</uri>" + "</play:location>" + "</play:locations>" + "<play:people/>" + "</play:item>")); }
public void testCanOutputSimpleItemObjectModelAsXml() throws Exception { Set<Object> graph = Sets.newHashSet(); Item item = new Item(); item.setTitle("Blue Peter"); item.setUri("http://www.bbc.co.uk/programmes/bluepeter"); item.setAliases(Sets.newHashSet("http://www.bbc.co.uk/p/bluepeter")); Location location = new Location(); location.setUri("http://www.bbc.co.uk/bluepeter"); location.setEmbedCode("<object><embed></embed></object>"); item.addLocation(location); DateTime transmitted = new DateTime(1990, 1, 1, 1, 1, 1, 1); item.addBroadcast(new Broadcast("channel", transmitted, transmitted.plusHours(1))); ContentQueryResult result = new ContentQueryResult(); result.add(item); graph.add(result); new JaxbXmlTranslator().writeTo(request, response, graph, AtlasModelType.CONTENT); String output = response.getResponseAsString(); assertThat(output, containsString("<play:item>" + "<uri>http://www.bbc.co.uk/programmes/bluepeter</uri>" + "<aliases>" + "<alias>http://www.bbc.co.uk/p/bluepeter</alias>" + "</aliases>" + "<clips/>" + "<play:genres/>" + "<play:sameAs/>" + "<play:tags/>" + "<title>Blue Peter</title>" + "<play:broadcasts>" + "<play:broadcast>" + "<broadcastDuration>3600</broadcastDuration>" + "<broadcastOn>channel</broadcastOn><transmissionEndTime>1990-01-01T02:01:01.001Z</transmissionEndTime>" + "<transmissionTime>1990-01-01T01:01:01.001Z</transmissionTime>" + "</play:broadcast>" + "</play:broadcasts>" + "<play:countriesOfOrigin/>" + "<play:locations>" + "<play:location>" + "<available>true</available>" + "<play:availableCountries/>" + "<embedCode>&lt;object&gt;&lt;embed&gt;&lt;/embed&gt;&lt;/object&gt;</embedCode>" + "<uri>http://www.bbc.co.uk/bluepeter</uri>" + "</play:location>" + "</play:locations>" + "<play:people/>" + "</play:item>")); }
diff --git a/shell/core/src/main/java/org/vfsutils/shell/commands/BoxedUnregister.java b/shell/core/src/main/java/org/vfsutils/shell/commands/BoxedUnregister.java index 7faaa60..294f1e4 100644 --- a/shell/core/src/main/java/org/vfsutils/shell/commands/BoxedUnregister.java +++ b/shell/core/src/main/java/org/vfsutils/shell/commands/BoxedUnregister.java @@ -1,34 +1,34 @@ package org.vfsutils.shell.commands; import org.vfsutils.shell.CommandProvider; import org.vfsutils.shell.Engine; /** * Allows unregistering only vfs script commands, not the java class or bsh script * commands * @author kleij - at - users.sourceforge.net * */ public class BoxedUnregister extends Unregister { /** * Only unregister vfs script commands */ protected void unregister(String cmd, CommandProvider command, Engine engine) { if (command instanceof Register.Script) { - if ("vfs".equals(((Register.Script)command).type)) { + if ("vfs".equals(((Register.Script)command).getType())) { super.unregister(cmd, command, engine); } else { engine.error("Can not unregister " + cmd); } } else { engine.error("Can not unregister " + cmd); } } }
true
true
protected void unregister(String cmd, CommandProvider command, Engine engine) { if (command instanceof Register.Script) { if ("vfs".equals(((Register.Script)command).type)) { super.unregister(cmd, command, engine); } else { engine.error("Can not unregister " + cmd); } } else { engine.error("Can not unregister " + cmd); } }
protected void unregister(String cmd, CommandProvider command, Engine engine) { if (command instanceof Register.Script) { if ("vfs".equals(((Register.Script)command).getType())) { super.unregister(cmd, command, engine); } else { engine.error("Can not unregister " + cmd); } } else { engine.error("Can not unregister " + cmd); } }
diff --git a/src/plugin/Stalemate.java b/src/plugin/Stalemate.java index 3e74466..00ee779 100644 --- a/src/plugin/Stalemate.java +++ b/src/plugin/Stalemate.java @@ -1,878 +1,878 @@ package plugin; import java.io.*; import static util.ColorParser.parseColors; import org.bukkit.Location; import org.bukkit.World; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import net.minecraft.server.v1_5_R3.Block; import net.minecraft.server.v1_5_R3.Item; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.Listener; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.java.JavaPlugin; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import amendedclasses.LoggerOutputStream; import controllers.RoundController; import defense.PlayerAI; import defense.Team; import serial.MapArea; import serial.RoundConfiguration; import serial.SerializableItemStack; import soldier.SoldierClass; import java.util.*; public class Stalemate extends JavaPlugin implements Listener { private Map<String, List<ItemStack>> itempacks = new ConcurrentHashMap<String, List<ItemStack>>(); public Map<String, String> settings = new ConcurrentHashMap<String, String>(); private static Stalemate instance; public final Map<String, PlayerAI> aiMap = new ConcurrentHashMap<String, PlayerAI>(); private List<RoundController> rounds = new Vector<RoundController>(); private Map<String, CommandCallback> cmdMap = new ConcurrentHashMap<String, CommandCallback>(); private Map<String, String> helpMap = new ConcurrentHashMap<String, String>(); private Map<String, TrapCallback> trapMap = new ConcurrentHashMap<String, TrapCallback>(); public final Map<Location, String> placedTraps = new ConcurrentHashMap<Location, String>(); public String getSetting(String key, String def) { String val = settings.get(key); if (val == null) val = def; return val; } private static TrapCallback createCallbackFromXML(Element e) { final List<TrapCallback> tasks = new Vector<TrapCallback>(); NodeList stuff = e.getChildNodes(); for (int i = 0; i < stuff.getLength(); i++) { Node n = stuff.item(i); if (!(n instanceof Element)) continue; Element task = (Element) n; String name = task.getNodeName(); switch (name.toLowerCase()) { case "explosion": tasks.add(new ExplosiveTrapCallback(task)); break; case "kill": tasks.add(new KillPlayerCallback(task)); break; case "sleep": tasks.add(new SleepTrapCallback(task)); break; case "command": tasks.add(new CommandTrapCallback(task)); break; default: System.out.println("Trap Callbacks: Unrecognized tag: "+name); } } String reusables = e.getAttribute("reusable"); boolean reusable = true; if (!reusables.equals("true")) { reusable = false; } final boolean reusableF = reusable; return new TrapCallback() { @Override public void onTriggered(Player p, Location loc, RoundController rnd) { for (TrapCallback c : tasks) try { c.onTriggered(p, loc, rnd); } catch (Throwable e) { RuntimeException e1 = new RuntimeException(Stalemate.getInstance().getSetting("trap_exc_msg", "Exception when triggering trap.")); e1.initCause(e); throw e1; } } @Override public boolean isReusable() { return reusableF; } }; } public static Stalemate getInstance() { return instance; } private static class AsyncTask { public long timeToWait; public long lastTimeUpdated; public final Callable<?> call; public AsyncTask(long t, Callable<?> c) { timeToWait = t; call = c; lastTimeUpdated = System.nanoTime()/1000000; } } public Map<String, TrapCallback> getTrapCallbacks() { return trapMap; } private List<AsyncTask> tasks = new Vector<AsyncTask>(); private Thread asyncUpdateThread = new Thread() { public void run() { while (Stalemate.getInstance().isEnabled()) { for (AsyncTask t : tasks) { t.timeToWait += -(t.lastTimeUpdated-(t.lastTimeUpdated = System.nanoTime()/1000000)); if (t.timeToWait <= 0) { tasks.remove(t); try { t.call.call(); } catch (Exception e) { throw new RuntimeException(e); } } } try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } }; public void setTimeout(long timeToWait, Callable<?> callback) { tasks.add(new AsyncTask(timeToWait, callback)); } public Stalemate() { instance = this; } private void join(Team t, Player p) { for (Team tt : Team.list()) { if (Arrays.asList(tt.getPlayers()).contains(p.getName().toUpperCase())) tt.removePlayer(p.getName().toUpperCase()); } t.addPlayer(p.getName()); for (RoundController rc : rounds) { if (rc.getConfig().getParticipatingTeams().contains(t)) { p.teleport(rc.getConfig().getArea().randomLoc()); } } } private void initRound(RoundController rnd) { rounds.add(rnd); rnd.startRound(); } private void placeTrap(String type, Location loc) { for (RoundController rc : rounds) { MapArea a = rc.getConfig().getArea(); if (a.contains(loc)) { rc.placeTrap(type, loc); break; } } } private Set<String> noChange = new HashSet<String>(); private Map<String, List<ItemStack>> itemsAccountableMap = new ConcurrentHashMap<String, List<ItemStack>>(); public void onEnable() { if (getDataFolder().isFile()) getDataFolder().delete(); if (!getDataFolder().exists()) getDataFolder().mkdir(); // TODO: Implement all commands registerCommand(getSetting("help_cmd", "help"), getSetting("help_help", "Shows the help page."), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { for (String key : helpMap.keySet()) { sender.sendMessage(synColor(ChatColor.LIGHT_PURPLE)+"/stalemate "+synColor(ChatColor.RESET)+key.toLowerCase()+" - "+synColor(ChatColor.AQUA)+helpMap.get(key)); } } }); registerCommand(getSetting("remove_trap_cmd", "rtrap"), getSetting("remove_trap_help", "Defuses a trap. Has a chance to fail."), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { if (!(sender instanceof Player)) { sender.sendMessage(parseColors(getSetting("players_only_msg", "Only players may use this command."))); return; } // TODO: Finish } }); registerCommand(getSetting("join_war_cmd", "joinwar"), getSetting("join_war_help", "Joins a war"), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { if (!sender.hasPermission(getSetting("join_war_perm", "stalemate.joinwar"))) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that.</font></xml>"))); return; } if (args.length < 2) { sender.sendMessage(parseColors(getSetting("join_war_syntax", "Syntax: /stalemate "+args[0]+" &lt;teamname&gt;"))); return; } Team t = Team.getTeam(args[1]); Team yours = null; for (Team te : Team.list()) { if (te.containsPlayer(sender.getName().toUpperCase())) { yours = te; } } if (yours == null) { sender.sendMessage(parseColors(getSetting("err_no_team_msg", "<root><font color=\"Red\">Join a team first.</font></root>"))); return; } if (!sender.getName().equalsIgnoreCase(yours.getOwner())) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } for (RoundController rc : rounds) { if (rc.getConfig().getParticipatingTeams().contains(t) && rc.isJoinable()) { rc.getConfig().addTeam(yours); } } } }); registerCommand(getSetting("war_cmd", "war"), getSetting("war_help", "Starts a new war"),new CommandCallback() { @Override public void onCommand(final CommandSender sender, String[] args) { if (!sender.hasPermission(getSetting("war_perm", "stalemate.start"))) { sender.sendMessage(getSetting("no_perm_msg", "<xml><font color=\"Red\"> You do not have permission to do that.</font></xml>")); return; } RoundController rnd = new RoundController(new RoundConfiguration((Location) null, null), new Callable<Object>(){ @Override public Object call() throws Exception { for (RoundController r : rounds) { if (r.getPlayers().contains(sender.getName().toUpperCase())) { for (String p : r.getPlayers()) { List<ItemStack> acct = Stalemate.this.itemsAccountableMap.get(p.toUpperCase()); Player pl = Stalemate.this.getServer().getPlayer(p); Map<Integer, ItemStack> failed = pl.getInventory().removeItem(acct.toArray(new ItemStack[0])); acct.clear(); acct.addAll(failed.values()); noChange.remove(p.toUpperCase()); } break; } } return null; }}); initRound(rnd); Team yours = null; for (Team t : Team.list()) { if (t.containsPlayer(sender.getName())) { yours = t; break; } } if (!yours.getOwner().equalsIgnoreCase(sender.getName())) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } rnd.getConfig().addTeam(yours); } }); registerCommand(getSetting("place_trap_cmd", "ptrap"), getSetting("place_trap_help", "Places a new trap."), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { assert(args.length > 0); if (!sender.hasPermission(getSetting("place_trap_perm", "stalemate.ptrap"))) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } if (!(sender instanceof Player)) { if (args.length < 6) { sender.sendMessage(parseColors(getSetting("syntax_trap_console_msg", "Syntax: stalemate "+args[0]+" <world> <x> <y> <z>"))); return; } World w; int x, y, z; String trapName; try { w = getServer().getWorld(args[1]); if (w == null) { sender.sendMessage(getSetting("invworld_trap_console_msg", "Invalid World.")); return; } x = Integer.parseInt(args[2]); y = Integer.parseInt(args[3]); z = Integer.parseInt(args[4]); trapName = args[5]; } catch (NumberFormatException e) { sender.sendMessage(getSetting("integer_err_console", "Please provide integers for x, y, and z.")); return; } placeTrap(trapName, new Location(w, x, y, z)); sender.sendMessage(getSetting("trap_place_success_msg_console", "Trap Placed.")); } else { if (args.length < 2) { sender.sendMessage(parseColors(getSetting("syntax_trap_player_msg", "Syntax: /stalemate "+args[0]+" <trap_type>"))); return; } Player p = (Player) sender; String trapName = args[1]; if (!trapMap.containsKey(trapName.toUpperCase())) { sender.sendMessage(parseColors(getSetting("no_trap_name", "<xml><font color=\"Purple\">That trap type does not exist!</font></xml>"))); return; } placeTrap(trapName, p.getLocation()); - sender.sendMessage(parseColors(getSetting("trap_place_success_msg", "Trap Placed."))); + sender.sendMessage(parseColors(getSetting("trap_place_success_msg", "<xml>Trap Placed.</xml>"))); } } }); registerCommand(getSetting("join_cmd", "join"), getSetting("join_help", "Joins the team of the specified player."), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { if (!sender.hasPermission(getSetting("join_perm", "stalemate.join"))) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } if (args.length < 2) { sender.sendMessage(parseColors(getSetting("syntax_join_msg", "<xml>/stalemate "+args[0]+" &lt;player&gt; or to create a team: /stalemate "+args[0]+" &lt;teamname&gt;</xml>"))); Team yours = null; for (Team tt : Team.list()) { if (tt.containsPlayer(sender.getName())) { yours = tt; break; } } if (yours != null) sender.sendMessage("Your current team is: "+yours.getName()); else sender.sendMessage("You do not have a team."); return; } Player target = getServer().getPlayer(args[1]); if (!(sender instanceof Player)) { sender.sendMessage(getSetting("players_only_msg", "Only players may execute this command.")); return; } for (Team t : Team.list()) { // TODO: Use linear search or hashing if (Arrays.binarySearch(t.getPlayers(), target.getName().toUpperCase()) > 0) { join(t, (Player) sender); sender.sendMessage(parseColors(getSetting("join_success_msg", "Success."))); return; } } Team x = new Team(args[1]); join(x, (Player) sender); } }); registerCommand(getSetting("leave_cmd", "leave"), getSetting("leave_help", "Leaves the current round."), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { if (!sender.hasPermission(getSetting("leave_perm", "stalemate.leave"))) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } if (!(sender instanceof Player)) { sender.sendMessage(parseColors(getSetting("players_only_msg", "Only players may use this feature."))); return; } for (RoundController rc : rounds) { if (rc.getPlayers().contains(sender.getName().toUpperCase())) { List<Team> teams = rc.getConfig().getParticipatingTeams(); for (Team t : teams) if (t.removePlayer(sender.getName())) break; } } } }); registerCommand(getSetting("class_cmd", "class"), getSetting("class_help", "Changes your class (Gives you a class's items)"), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { if (!(sender instanceof Player)) { sender.sendMessage(parseColors(getSetting("players_only_msg", "<xml>Only players may use this command.</xml>"))); return; } if (!sender.hasPermission(getSetting("class_perm", "stalemate.changeclass"))) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } if (noChange.contains(sender.getName().toUpperCase()) && !sender.hasPermission("stalemate.changeclass.multiple")) { sender.sendMessage(parseColors(getSetting("class_nochange", "<xml>You may not change your class once you have selected it.</xml>"))); return; } if (args.length < 2) { sender.sendMessage(parseColors(getSetting("class_syntax", "<xml>Syntax: /stalemate "+args[0]+" &lt;classname&gt;</xml>"))); return; } SoldierClass s = SoldierClass.fromName(args[1]); if (s == null) { sender.sendMessage(parseColors(getSetting("class_nonexist_msg", "<xml><font color=\"Red\">That class does not exist!</font></xml>"))); return; } if (!sender.hasPermission(s.getPermission())) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "You do not have permission to change to the requested class."))); return; } ItemStack[] give = s.getItems(); List<ItemStack> account = (account=itemsAccountableMap.get(sender.getName().toUpperCase())) == null ? account == itemsAccountableMap.put(sender.getName().toUpperCase(), account = new Vector<ItemStack>()) ? account : account : account; for (ItemStack i : give) account.add(i.clone()); Map<Integer, ItemStack> failed = ((Player) sender).getInventory().addItem(give); account.removeAll(failed.values()); } }); try { onEnable0(); } catch (Throwable e) { getLogger().log(Level.SEVERE, "Unexpected exception while loading Stalemate."); e.printStackTrace(); } asyncUpdateThread.start(); getLogger().info("Wars? Battles? Skirmishes? Fistfights? Air punching? Stalemate loaded!"); } protected static boolean isInRound(Player sender) { // TODO: Finish for (RoundController rc : Stalemate.getInstance().rounds) { if (rc.getPlayers().contains(sender.getName().toUpperCase())) { return true; } } return false; } protected static RoundController getRound(Player sender) { for (RoundController rc : Stalemate.getInstance().rounds) { if (rc.getPlayers().contains(sender.getName().toUpperCase())) return rc; } return null; } public CommandCallback registerCommand(String name, String desc, CommandCallback onCommand) { CommandCallback c = cmdMap.put(name.toUpperCase(), onCommand); helpMap.put(name.toUpperCase(), desc); return c; } public void onDisable() { getLogger().info("Peace! AAAAH!"); Map<String, List<SerializableItemStack>> saveAccount = new HashMap<String, List<SerializableItemStack>>(); for (String s : itemsAccountableMap.keySet()) { List<SerializableItemStack> l = SerializableItemStack.fromList(itemsAccountableMap.get(s)); saveAccount.put(s, l); } try { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File(getDataFolder(), "items.dat"))); oos.writeObject(saveAccount); oos.close(); } catch (IOException e) { e.printStackTrace(); } } private String synColor(ChatColor c) { return ChatColor.COLOR_CHAR+""+c.getChar(); } public boolean onCommand(CommandSender sender, Command cmd, String lbl, String args[]) { if (!cmd.getName().equalsIgnoreCase("stalemate")) return false; if (!sender.hasPermission("stalemate.basic")) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission.</font></xml>"))); return true; } if (args.length == 0) { args = new String[] {"help"}; } String name = args[0]; CommandCallback cb = cmdMap.get(name.toUpperCase()); if (cb == null) { sender.sendMessage(parseColors(getSetting("invalid_cmd_msg", "<xml>Invalid Command. Please type /stalemate "+getSetting("help_cmd", "help")+" for help.</xml>"))); return true; } cb.onCommand(sender, args); return true; } private void generateConfig(File f) throws IOException { // Writing lines to translate CRLF -> LF and LF -> CRLF PrintWriter writer = new PrintWriter(new FileOutputStream(f)); InputStream in = getResource("config.xml"); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String ln; while ((ln = br.readLine()) != null) writer.println(ln); writer.close(); br.close(); } public void onEnable0() throws Throwable { File config = new File(this.getDataFolder(), "config.xml"); if (!config.exists()) { generateConfig(config); } if (!config.isFile()) { boolean success = config.delete(); if (!success) { config.deleteOnExit(); throw new RuntimeException("Failed to create config."); } else { generateConfig(config); } } FileInputStream stream = new FileInputStream(config); // Buffer the file in memory ByteArrayOutputStream b = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int bytesRead; while ((bytesRead = stream.read(buf)) != -1) { b.write(buf, 0, bytesRead); } stream.close(); buf = null; byte[] bytes = b.toByteArray(); b.close(); // Begin parsing DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = dbf.newDocumentBuilder(); Document doc; try { doc = builder.parse(new ByteArrayInputStream(bytes)); } catch (Throwable t) { Throwable exc = new RuntimeException("Config Error: Invalid XML File: config.xml"); exc.initCause(t); throw exc; } Element root = doc.getDocumentElement(); NodeList classes = root.getElementsByTagName("soldiers"); for (int i = 0; i < classes.getLength(); i++) { Node nn = classes.item(i); if (!(nn instanceof Element)) continue; Element section = (Element) nn; // Load item packs NodeList nodes = section.getElementsByTagName("itempack"); for (int j = 0; j < nodes.getLength(); j++) { Node nnn = nodes.item(j); if (!(nnn instanceof Element)) continue; Element pack = (Element) nnn; NodeList items = pack.getElementsByTagName("item"); List<ItemStack> packItems = new Vector<ItemStack>(); for (int k = 0; k < items.getLength(); k++) { Node nnnn = items.item(k); if (!(nnnn instanceof Element)) continue; Element item = (Element) nnnn; String idStr = item.getAttribute("id"); int id = -1; if (idStr.equals("")) { // Fetch according to name attribute String name = item.getAttribute("name"); for (Block block : Block.byId) { if (block == null) continue; if (block.getName().equalsIgnoreCase(name)) { id = block.id; break; } } if (id == -1) { for (Item mcItem : Item.byId) { if (mcItem == null) continue; if (mcItem.getName().equalsIgnoreCase(name)) { id = mcItem.id; break; } } if (id == -1) throw new RuntimeException("Config Error: Non-existent name: "+name); } } else { String name = item.getAttribute("name"); if (!name.equals("")) throw new RuntimeException("Both name and ID specified. Specify one or the other. Name: "+name+" ID: "+idStr); try { id = Integer.parseInt(idStr); } catch (NumberFormatException e) { throw new RuntimeException("Config Error: Expected a number for item ID. Got: "+idStr); } } String dmgStr = item.getAttribute("dmg"); int dmg; if (dmgStr.equals("")) { dmg = 0; } else { try { dmg = Integer.parseInt(dmgStr); } catch (NumberFormatException e) { throw new RuntimeException("Config Error: Expected an integer (-2147483648 -> 2147483647) for item damage. Got: "+dmgStr); } } int num; String numStr = item.getAttribute("num"); if (numStr.equals("")) { num = 1; } else { try { num = Integer.parseInt(numStr); if (num <= 0) throw new NumberFormatException("break"); } catch (NumberFormatException e) { throw new RuntimeException("Config Error: Expected a positive integer for item number. Got: "+numStr); } } ItemStack stack = new ItemStack(id, num, (short) dmg); packItems.add(stack); } if (pack.getAttribute("name").equals("")) throw new RuntimeException("Config Error: Item packs require a name attribute."); itempacks.put(pack.getAttribute("name").toUpperCase(), packItems); } NodeList classList = section.getElementsByTagName("sclass"); for (int j = 0; j < classList.getLength(); j++) { Element classElement = (Element) classList.item(j); String name = classElement.getAttribute("name"); String permission = classElement.getAttribute("permission"); if (permission.equals("")) permission = "stalemate.basic"; NodeList itemList = classElement.getElementsByTagName("item"); List<ItemStack> classItems = new Vector<ItemStack>(); for (int k = 0; k < itemList.getLength(); k++) { Element item = (Element) itemList.item(k); String n = item.getAttribute("name"); String isPackStr = item.getAttribute("isPack").toLowerCase(); boolean isPack; if (isPackStr.equals("")) { isPack = false; } else { try { isPack = Boolean.parseBoolean(isPackStr); } catch (RuntimeException e) { throw new RuntimeException("Config Error: Expected a true/false value for attribute isPack. Got: "+isPackStr); } } if (n.equals("") || !isPack) { // Normal Item Processing String idStr = item.getAttribute("id"); int id = -1; if (!n.equals("")) { if (!idStr.equals("")) throw new RuntimeException("Config Error: Name and ID specified. Please specify one or the other. Name: "+n+" ID: "+idStr); for (Block b1 : Block.byId) { if (b1.getName().equalsIgnoreCase(n)) { id = b1.id; break; } } if (id == -1) throw new RuntimeException("Config Error: Non-existent name: "+n); } else { try { id = Integer.parseInt(idStr); } catch (NumberFormatException e) { throw new RuntimeException("Config Error: ID must be a valid integer. Got: "+idStr); } } int num; String numStr = item.getAttribute("num"); if (numStr.equals("")) { num = 1; } else { try { num = Integer.parseInt(numStr); } catch (NumberFormatException e) { throw new RuntimeException("Config Error: Expected an integer for item amount. Got: "+numStr); } } int dmg; String dmgStr = item.getAttribute("dmg"); if (dmgStr.equals("")) { dmg = 0; } else { try { dmg = Integer.parseInt(dmgStr); } catch (NumberFormatException e) { throw new RuntimeException("Config Error: Expected an integer (-32768 -> 32767) for item damage. Got: "+dmgStr); } } ItemStack stack = new ItemStack(id, num, (short) dmg); classItems.add(stack); } else { // Fetch item pack and add in. if (!itempacks.containsKey(n.toUpperCase())) throw new RuntimeException("Config Error: Non-existent item pack: "+n); classItems.addAll(itempacks.get(n.toUpperCase())); } } new SoldierClass(name, classItems.toArray(new ItemStack[0]), permission); } } // Load Settings NodeList settings = root.getElementsByTagName("settings"); for (int i = 0; i < settings.getLength(); i++) { Node nnnn = settings.item(i); Element section = (Element) nnnn; NodeList tags = section.getElementsByTagName("setting"); for (int j = 0; j < tags.getLength(); j++) { Element setting = (Element) tags.item(j); String name = setting.getAttribute("name"); String value = setting.getAttribute("value"); if (name.equals("")) throw new RuntimeException("Please include a name attribute for all setting tags in config.xml"); this.settings.put(name, value); } } // Load Traps NodeList traps = root.getElementsByTagName("traps"); for (int i = 0; i < traps.getLength(); i++) { Element section = (Element) settings.item(i); NodeList trapList = section.getElementsByTagName("trap"); for (int j = 0; j < trapList.getLength(); j++) { Element trap = (Element) trapList.item(j); String name = trap.getAttribute("name"); if (name.equals("")) throw new RuntimeException("All traps must have a name."); TrapCallback call = createCallbackFromXML(trap); trapMap.put(name.toUpperCase(), call); } } // Load accounts File accountsFile = new File(getDataFolder(), "items.dat"); if (accountsFile.isDirectory()) accountsFile.delete(); if (!accountsFile.exists()) { ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(accountsFile)); out.writeObject(new HashMap<String, List<SerializableItemStack>>()); out.close(); } try { // TODO: Fix race condition, so that checking and opening is atomic ObjectInputStream in = new ObjectInputStream(new FileInputStream(accountsFile)); @SuppressWarnings("unchecked") Map<String, List<SerializableItemStack>> read = (Map<String, List<SerializableItemStack>>) in.readObject(); in.close(); // Begin translation for (String s : read.keySet()) { itemsAccountableMap.put(s, SerializableItemStack.toList(read.get(s))); } } catch (Throwable t) { accountsFile.delete(); ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(accountsFile)); out.writeObject(new HashMap<String, List<SerializableItemStack>>()); out.close(); System.err.println("Please restart the server. A data file has been corrupted."); throw new RuntimeException(t); } } }
true
true
public void onEnable() { if (getDataFolder().isFile()) getDataFolder().delete(); if (!getDataFolder().exists()) getDataFolder().mkdir(); // TODO: Implement all commands registerCommand(getSetting("help_cmd", "help"), getSetting("help_help", "Shows the help page."), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { for (String key : helpMap.keySet()) { sender.sendMessage(synColor(ChatColor.LIGHT_PURPLE)+"/stalemate "+synColor(ChatColor.RESET)+key.toLowerCase()+" - "+synColor(ChatColor.AQUA)+helpMap.get(key)); } } }); registerCommand(getSetting("remove_trap_cmd", "rtrap"), getSetting("remove_trap_help", "Defuses a trap. Has a chance to fail."), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { if (!(sender instanceof Player)) { sender.sendMessage(parseColors(getSetting("players_only_msg", "Only players may use this command."))); return; } // TODO: Finish } }); registerCommand(getSetting("join_war_cmd", "joinwar"), getSetting("join_war_help", "Joins a war"), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { if (!sender.hasPermission(getSetting("join_war_perm", "stalemate.joinwar"))) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that.</font></xml>"))); return; } if (args.length < 2) { sender.sendMessage(parseColors(getSetting("join_war_syntax", "Syntax: /stalemate "+args[0]+" &lt;teamname&gt;"))); return; } Team t = Team.getTeam(args[1]); Team yours = null; for (Team te : Team.list()) { if (te.containsPlayer(sender.getName().toUpperCase())) { yours = te; } } if (yours == null) { sender.sendMessage(parseColors(getSetting("err_no_team_msg", "<root><font color=\"Red\">Join a team first.</font></root>"))); return; } if (!sender.getName().equalsIgnoreCase(yours.getOwner())) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } for (RoundController rc : rounds) { if (rc.getConfig().getParticipatingTeams().contains(t) && rc.isJoinable()) { rc.getConfig().addTeam(yours); } } } }); registerCommand(getSetting("war_cmd", "war"), getSetting("war_help", "Starts a new war"),new CommandCallback() { @Override public void onCommand(final CommandSender sender, String[] args) { if (!sender.hasPermission(getSetting("war_perm", "stalemate.start"))) { sender.sendMessage(getSetting("no_perm_msg", "<xml><font color=\"Red\"> You do not have permission to do that.</font></xml>")); return; } RoundController rnd = new RoundController(new RoundConfiguration((Location) null, null), new Callable<Object>(){ @Override public Object call() throws Exception { for (RoundController r : rounds) { if (r.getPlayers().contains(sender.getName().toUpperCase())) { for (String p : r.getPlayers()) { List<ItemStack> acct = Stalemate.this.itemsAccountableMap.get(p.toUpperCase()); Player pl = Stalemate.this.getServer().getPlayer(p); Map<Integer, ItemStack> failed = pl.getInventory().removeItem(acct.toArray(new ItemStack[0])); acct.clear(); acct.addAll(failed.values()); noChange.remove(p.toUpperCase()); } break; } } return null; }}); initRound(rnd); Team yours = null; for (Team t : Team.list()) { if (t.containsPlayer(sender.getName())) { yours = t; break; } } if (!yours.getOwner().equalsIgnoreCase(sender.getName())) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } rnd.getConfig().addTeam(yours); } }); registerCommand(getSetting("place_trap_cmd", "ptrap"), getSetting("place_trap_help", "Places a new trap."), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { assert(args.length > 0); if (!sender.hasPermission(getSetting("place_trap_perm", "stalemate.ptrap"))) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } if (!(sender instanceof Player)) { if (args.length < 6) { sender.sendMessage(parseColors(getSetting("syntax_trap_console_msg", "Syntax: stalemate "+args[0]+" <world> <x> <y> <z>"))); return; } World w; int x, y, z; String trapName; try { w = getServer().getWorld(args[1]); if (w == null) { sender.sendMessage(getSetting("invworld_trap_console_msg", "Invalid World.")); return; } x = Integer.parseInt(args[2]); y = Integer.parseInt(args[3]); z = Integer.parseInt(args[4]); trapName = args[5]; } catch (NumberFormatException e) { sender.sendMessage(getSetting("integer_err_console", "Please provide integers for x, y, and z.")); return; } placeTrap(trapName, new Location(w, x, y, z)); sender.sendMessage(getSetting("trap_place_success_msg_console", "Trap Placed.")); } else { if (args.length < 2) { sender.sendMessage(parseColors(getSetting("syntax_trap_player_msg", "Syntax: /stalemate "+args[0]+" <trap_type>"))); return; } Player p = (Player) sender; String trapName = args[1]; if (!trapMap.containsKey(trapName.toUpperCase())) { sender.sendMessage(parseColors(getSetting("no_trap_name", "<xml><font color=\"Purple\">That trap type does not exist!</font></xml>"))); return; } placeTrap(trapName, p.getLocation()); sender.sendMessage(parseColors(getSetting("trap_place_success_msg", "Trap Placed."))); } } }); registerCommand(getSetting("join_cmd", "join"), getSetting("join_help", "Joins the team of the specified player."), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { if (!sender.hasPermission(getSetting("join_perm", "stalemate.join"))) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } if (args.length < 2) { sender.sendMessage(parseColors(getSetting("syntax_join_msg", "<xml>/stalemate "+args[0]+" &lt;player&gt; or to create a team: /stalemate "+args[0]+" &lt;teamname&gt;</xml>"))); Team yours = null; for (Team tt : Team.list()) { if (tt.containsPlayer(sender.getName())) { yours = tt; break; } } if (yours != null) sender.sendMessage("Your current team is: "+yours.getName()); else sender.sendMessage("You do not have a team."); return; } Player target = getServer().getPlayer(args[1]); if (!(sender instanceof Player)) { sender.sendMessage(getSetting("players_only_msg", "Only players may execute this command.")); return; } for (Team t : Team.list()) { // TODO: Use linear search or hashing if (Arrays.binarySearch(t.getPlayers(), target.getName().toUpperCase()) > 0) { join(t, (Player) sender); sender.sendMessage(parseColors(getSetting("join_success_msg", "Success."))); return; } } Team x = new Team(args[1]); join(x, (Player) sender); } }); registerCommand(getSetting("leave_cmd", "leave"), getSetting("leave_help", "Leaves the current round."), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { if (!sender.hasPermission(getSetting("leave_perm", "stalemate.leave"))) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } if (!(sender instanceof Player)) { sender.sendMessage(parseColors(getSetting("players_only_msg", "Only players may use this feature."))); return; } for (RoundController rc : rounds) { if (rc.getPlayers().contains(sender.getName().toUpperCase())) { List<Team> teams = rc.getConfig().getParticipatingTeams(); for (Team t : teams) if (t.removePlayer(sender.getName())) break; } } } }); registerCommand(getSetting("class_cmd", "class"), getSetting("class_help", "Changes your class (Gives you a class's items)"), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { if (!(sender instanceof Player)) { sender.sendMessage(parseColors(getSetting("players_only_msg", "<xml>Only players may use this command.</xml>"))); return; } if (!sender.hasPermission(getSetting("class_perm", "stalemate.changeclass"))) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } if (noChange.contains(sender.getName().toUpperCase()) && !sender.hasPermission("stalemate.changeclass.multiple")) { sender.sendMessage(parseColors(getSetting("class_nochange", "<xml>You may not change your class once you have selected it.</xml>"))); return; } if (args.length < 2) { sender.sendMessage(parseColors(getSetting("class_syntax", "<xml>Syntax: /stalemate "+args[0]+" &lt;classname&gt;</xml>"))); return; } SoldierClass s = SoldierClass.fromName(args[1]); if (s == null) { sender.sendMessage(parseColors(getSetting("class_nonexist_msg", "<xml><font color=\"Red\">That class does not exist!</font></xml>"))); return; } if (!sender.hasPermission(s.getPermission())) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "You do not have permission to change to the requested class."))); return; } ItemStack[] give = s.getItems(); List<ItemStack> account = (account=itemsAccountableMap.get(sender.getName().toUpperCase())) == null ? account == itemsAccountableMap.put(sender.getName().toUpperCase(), account = new Vector<ItemStack>()) ? account : account : account; for (ItemStack i : give) account.add(i.clone()); Map<Integer, ItemStack> failed = ((Player) sender).getInventory().addItem(give); account.removeAll(failed.values()); } }); try { onEnable0(); } catch (Throwable e) { getLogger().log(Level.SEVERE, "Unexpected exception while loading Stalemate."); e.printStackTrace(); } asyncUpdateThread.start(); getLogger().info("Wars? Battles? Skirmishes? Fistfights? Air punching? Stalemate loaded!"); }
public void onEnable() { if (getDataFolder().isFile()) getDataFolder().delete(); if (!getDataFolder().exists()) getDataFolder().mkdir(); // TODO: Implement all commands registerCommand(getSetting("help_cmd", "help"), getSetting("help_help", "Shows the help page."), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { for (String key : helpMap.keySet()) { sender.sendMessage(synColor(ChatColor.LIGHT_PURPLE)+"/stalemate "+synColor(ChatColor.RESET)+key.toLowerCase()+" - "+synColor(ChatColor.AQUA)+helpMap.get(key)); } } }); registerCommand(getSetting("remove_trap_cmd", "rtrap"), getSetting("remove_trap_help", "Defuses a trap. Has a chance to fail."), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { if (!(sender instanceof Player)) { sender.sendMessage(parseColors(getSetting("players_only_msg", "Only players may use this command."))); return; } // TODO: Finish } }); registerCommand(getSetting("join_war_cmd", "joinwar"), getSetting("join_war_help", "Joins a war"), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { if (!sender.hasPermission(getSetting("join_war_perm", "stalemate.joinwar"))) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that.</font></xml>"))); return; } if (args.length < 2) { sender.sendMessage(parseColors(getSetting("join_war_syntax", "Syntax: /stalemate "+args[0]+" &lt;teamname&gt;"))); return; } Team t = Team.getTeam(args[1]); Team yours = null; for (Team te : Team.list()) { if (te.containsPlayer(sender.getName().toUpperCase())) { yours = te; } } if (yours == null) { sender.sendMessage(parseColors(getSetting("err_no_team_msg", "<root><font color=\"Red\">Join a team first.</font></root>"))); return; } if (!sender.getName().equalsIgnoreCase(yours.getOwner())) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } for (RoundController rc : rounds) { if (rc.getConfig().getParticipatingTeams().contains(t) && rc.isJoinable()) { rc.getConfig().addTeam(yours); } } } }); registerCommand(getSetting("war_cmd", "war"), getSetting("war_help", "Starts a new war"),new CommandCallback() { @Override public void onCommand(final CommandSender sender, String[] args) { if (!sender.hasPermission(getSetting("war_perm", "stalemate.start"))) { sender.sendMessage(getSetting("no_perm_msg", "<xml><font color=\"Red\"> You do not have permission to do that.</font></xml>")); return; } RoundController rnd = new RoundController(new RoundConfiguration((Location) null, null), new Callable<Object>(){ @Override public Object call() throws Exception { for (RoundController r : rounds) { if (r.getPlayers().contains(sender.getName().toUpperCase())) { for (String p : r.getPlayers()) { List<ItemStack> acct = Stalemate.this.itemsAccountableMap.get(p.toUpperCase()); Player pl = Stalemate.this.getServer().getPlayer(p); Map<Integer, ItemStack> failed = pl.getInventory().removeItem(acct.toArray(new ItemStack[0])); acct.clear(); acct.addAll(failed.values()); noChange.remove(p.toUpperCase()); } break; } } return null; }}); initRound(rnd); Team yours = null; for (Team t : Team.list()) { if (t.containsPlayer(sender.getName())) { yours = t; break; } } if (!yours.getOwner().equalsIgnoreCase(sender.getName())) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } rnd.getConfig().addTeam(yours); } }); registerCommand(getSetting("place_trap_cmd", "ptrap"), getSetting("place_trap_help", "Places a new trap."), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { assert(args.length > 0); if (!sender.hasPermission(getSetting("place_trap_perm", "stalemate.ptrap"))) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } if (!(sender instanceof Player)) { if (args.length < 6) { sender.sendMessage(parseColors(getSetting("syntax_trap_console_msg", "Syntax: stalemate "+args[0]+" <world> <x> <y> <z>"))); return; } World w; int x, y, z; String trapName; try { w = getServer().getWorld(args[1]); if (w == null) { sender.sendMessage(getSetting("invworld_trap_console_msg", "Invalid World.")); return; } x = Integer.parseInt(args[2]); y = Integer.parseInt(args[3]); z = Integer.parseInt(args[4]); trapName = args[5]; } catch (NumberFormatException e) { sender.sendMessage(getSetting("integer_err_console", "Please provide integers for x, y, and z.")); return; } placeTrap(trapName, new Location(w, x, y, z)); sender.sendMessage(getSetting("trap_place_success_msg_console", "Trap Placed.")); } else { if (args.length < 2) { sender.sendMessage(parseColors(getSetting("syntax_trap_player_msg", "Syntax: /stalemate "+args[0]+" <trap_type>"))); return; } Player p = (Player) sender; String trapName = args[1]; if (!trapMap.containsKey(trapName.toUpperCase())) { sender.sendMessage(parseColors(getSetting("no_trap_name", "<xml><font color=\"Purple\">That trap type does not exist!</font></xml>"))); return; } placeTrap(trapName, p.getLocation()); sender.sendMessage(parseColors(getSetting("trap_place_success_msg", "<xml>Trap Placed.</xml>"))); } } }); registerCommand(getSetting("join_cmd", "join"), getSetting("join_help", "Joins the team of the specified player."), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { if (!sender.hasPermission(getSetting("join_perm", "stalemate.join"))) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } if (args.length < 2) { sender.sendMessage(parseColors(getSetting("syntax_join_msg", "<xml>/stalemate "+args[0]+" &lt;player&gt; or to create a team: /stalemate "+args[0]+" &lt;teamname&gt;</xml>"))); Team yours = null; for (Team tt : Team.list()) { if (tt.containsPlayer(sender.getName())) { yours = tt; break; } } if (yours != null) sender.sendMessage("Your current team is: "+yours.getName()); else sender.sendMessage("You do not have a team."); return; } Player target = getServer().getPlayer(args[1]); if (!(sender instanceof Player)) { sender.sendMessage(getSetting("players_only_msg", "Only players may execute this command.")); return; } for (Team t : Team.list()) { // TODO: Use linear search or hashing if (Arrays.binarySearch(t.getPlayers(), target.getName().toUpperCase()) > 0) { join(t, (Player) sender); sender.sendMessage(parseColors(getSetting("join_success_msg", "Success."))); return; } } Team x = new Team(args[1]); join(x, (Player) sender); } }); registerCommand(getSetting("leave_cmd", "leave"), getSetting("leave_help", "Leaves the current round."), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { if (!sender.hasPermission(getSetting("leave_perm", "stalemate.leave"))) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } if (!(sender instanceof Player)) { sender.sendMessage(parseColors(getSetting("players_only_msg", "Only players may use this feature."))); return; } for (RoundController rc : rounds) { if (rc.getPlayers().contains(sender.getName().toUpperCase())) { List<Team> teams = rc.getConfig().getParticipatingTeams(); for (Team t : teams) if (t.removePlayer(sender.getName())) break; } } } }); registerCommand(getSetting("class_cmd", "class"), getSetting("class_help", "Changes your class (Gives you a class's items)"), new CommandCallback() { @Override public void onCommand(CommandSender sender, String[] args) { if (!(sender instanceof Player)) { sender.sendMessage(parseColors(getSetting("players_only_msg", "<xml>Only players may use this command.</xml>"))); return; } if (!sender.hasPermission(getSetting("class_perm", "stalemate.changeclass"))) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "<xml><font color=\"Red\">You do not have permission to do that!</font></xml>"))); return; } if (noChange.contains(sender.getName().toUpperCase()) && !sender.hasPermission("stalemate.changeclass.multiple")) { sender.sendMessage(parseColors(getSetting("class_nochange", "<xml>You may not change your class once you have selected it.</xml>"))); return; } if (args.length < 2) { sender.sendMessage(parseColors(getSetting("class_syntax", "<xml>Syntax: /stalemate "+args[0]+" &lt;classname&gt;</xml>"))); return; } SoldierClass s = SoldierClass.fromName(args[1]); if (s == null) { sender.sendMessage(parseColors(getSetting("class_nonexist_msg", "<xml><font color=\"Red\">That class does not exist!</font></xml>"))); return; } if (!sender.hasPermission(s.getPermission())) { sender.sendMessage(parseColors(getSetting("no_perm_msg", "You do not have permission to change to the requested class."))); return; } ItemStack[] give = s.getItems(); List<ItemStack> account = (account=itemsAccountableMap.get(sender.getName().toUpperCase())) == null ? account == itemsAccountableMap.put(sender.getName().toUpperCase(), account = new Vector<ItemStack>()) ? account : account : account; for (ItemStack i : give) account.add(i.clone()); Map<Integer, ItemStack> failed = ((Player) sender).getInventory().addItem(give); account.removeAll(failed.values()); } }); try { onEnable0(); } catch (Throwable e) { getLogger().log(Level.SEVERE, "Unexpected exception while loading Stalemate."); e.printStackTrace(); } asyncUpdateThread.start(); getLogger().info("Wars? Battles? Skirmishes? Fistfights? Air punching? Stalemate loaded!"); }
diff --git a/src/main/java/nl/mindef/c2sc/nbs/olsr/pud/uplink/server/handlers/impl/WireFormatCheckerImpl.java b/src/main/java/nl/mindef/c2sc/nbs/olsr/pud/uplink/server/handlers/impl/WireFormatCheckerImpl.java index 524c9d3..5c7d32f 100644 --- a/src/main/java/nl/mindef/c2sc/nbs/olsr/pud/uplink/server/handlers/impl/WireFormatCheckerImpl.java +++ b/src/main/java/nl/mindef/c2sc/nbs/olsr/pud/uplink/server/handlers/impl/WireFormatCheckerImpl.java @@ -1,57 +1,57 @@ package nl.mindef.c2sc.nbs.olsr.pud.uplink.server.handlers.impl; import nl.mindef.c2sc.nbs.olsr.pud.uplink.server.dao.domainmodel.Sender; import nl.mindef.c2sc.nbs.olsr.pud.uplink.server.handlers.WireFormatChecker; import nl.mindef.c2sc.nbs.olsr.pud.uplink.server.reportonce.ReportOnce; import nl.mindef.c2sc.nbs.olsr.pud.uplink.server.reportonce.ReportSubject; import org.apache.log4j.Logger; import org.olsr.plugin.pud.ClusterLeader; import org.olsr.plugin.pud.PositionUpdate; import org.olsr.plugin.pud.UplinkMessage; import org.olsr.plugin.pud.WireFormatConstants; import org.springframework.beans.factory.annotation.Required; public class WireFormatCheckerImpl implements WireFormatChecker { private Logger logger = Logger.getLogger(this.getClass().getName()); private ReportOnce reportOnce; /** * @param reportOnce * the reportOnce to set */ @Required public final void setReportOnce(ReportOnce reportOnce) { this.reportOnce = reportOnce; } @Override public boolean checkUplinkMessageWireFormat(Sender sender, UplinkMessage msg) { assert (sender != null); assert (msg != null); int wireFormatVersion = -1; if (msg instanceof ClusterLeader) { wireFormatVersion = ((ClusterLeader) msg).getClusterLeaderVersion(); } else /* if (msg instanceof PositionUpdate) */{ wireFormatVersion = ((PositionUpdate) msg).getPositionUpdateVersion(); } String senderReport = sender.getIp().getHostAddress() + ":" + sender.getPort().toString(); if (wireFormatVersion == WireFormatConstants.VERSION) { if (this.reportOnce.remove(ReportSubject.SENDER_WIRE_FORMAT, senderReport)) { this.logger.error("Received correct version of uplink message from " + senderReport + ", node will no longer be ignored"); } return true; } if (this.reportOnce.add(ReportSubject.SENDER_WIRE_FORMAT, senderReport)) { - this.logger.error("Received uplink message version " + wireFormatVersion + " (expected version " + this.logger.warn("Received uplink message version " + wireFormatVersion + " (expected version " + WireFormatConstants.VERSION + ") from " + senderReport + ", node will be ignored"); } return false; } }
true
true
public boolean checkUplinkMessageWireFormat(Sender sender, UplinkMessage msg) { assert (sender != null); assert (msg != null); int wireFormatVersion = -1; if (msg instanceof ClusterLeader) { wireFormatVersion = ((ClusterLeader) msg).getClusterLeaderVersion(); } else /* if (msg instanceof PositionUpdate) */{ wireFormatVersion = ((PositionUpdate) msg).getPositionUpdateVersion(); } String senderReport = sender.getIp().getHostAddress() + ":" + sender.getPort().toString(); if (wireFormatVersion == WireFormatConstants.VERSION) { if (this.reportOnce.remove(ReportSubject.SENDER_WIRE_FORMAT, senderReport)) { this.logger.error("Received correct version of uplink message from " + senderReport + ", node will no longer be ignored"); } return true; } if (this.reportOnce.add(ReportSubject.SENDER_WIRE_FORMAT, senderReport)) { this.logger.error("Received uplink message version " + wireFormatVersion + " (expected version " + WireFormatConstants.VERSION + ") from " + senderReport + ", node will be ignored"); } return false; }
public boolean checkUplinkMessageWireFormat(Sender sender, UplinkMessage msg) { assert (sender != null); assert (msg != null); int wireFormatVersion = -1; if (msg instanceof ClusterLeader) { wireFormatVersion = ((ClusterLeader) msg).getClusterLeaderVersion(); } else /* if (msg instanceof PositionUpdate) */{ wireFormatVersion = ((PositionUpdate) msg).getPositionUpdateVersion(); } String senderReport = sender.getIp().getHostAddress() + ":" + sender.getPort().toString(); if (wireFormatVersion == WireFormatConstants.VERSION) { if (this.reportOnce.remove(ReportSubject.SENDER_WIRE_FORMAT, senderReport)) { this.logger.error("Received correct version of uplink message from " + senderReport + ", node will no longer be ignored"); } return true; } if (this.reportOnce.add(ReportSubject.SENDER_WIRE_FORMAT, senderReport)) { this.logger.warn("Received uplink message version " + wireFormatVersion + " (expected version " + WireFormatConstants.VERSION + ") from " + senderReport + ", node will be ignored"); } return false; }
diff --git a/org.dawb.common.ui/src/org/dawb/common/ui/plot/roi/data/RectangularROIData.java b/org.dawb.common.ui/src/org/dawb/common/ui/plot/roi/data/RectangularROIData.java index c15d1107..fc44f2b2 100644 --- a/org.dawb.common.ui/src/org/dawb/common/ui/plot/roi/data/RectangularROIData.java +++ b/org.dawb.common.ui/src/org/dawb/common/ui/plot/roi/data/RectangularROIData.java @@ -1,110 +1,111 @@ /* * Copyright 2012 Diamond Light Source 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.dawb.common.ui.plot.roi.data; import uk.ac.diamond.scisoft.analysis.axis.AxisValues; import uk.ac.diamond.scisoft.analysis.dataset.AbstractCompoundDataset; import uk.ac.diamond.scisoft.analysis.dataset.AbstractDataset; import uk.ac.diamond.scisoft.analysis.roi.ROIProfile; import uk.ac.diamond.scisoft.analysis.roi.RectangularROI; /** * Class to aggregate information associated with a ROI */ public class RectangularROIData extends ROIData { /** * Construct new object from given roi and data * @param rroi * @param data */ public RectangularROIData(RectangularROI rroi, AbstractDataset data) { this(rroi, data, null, 1.); } public RectangularROIData(RectangularROI rroi, AbstractDataset data, AbstractDataset mask) { this(rroi, data, mask, 1.); } /** * Construct new object from given roi and data * * @param rroi * @param data * @param subFactor */ public RectangularROIData(RectangularROI rroi, AbstractDataset data, AbstractDataset mask, double subFactor) { super(); setROI(rroi.copy()); roi.downsample(subFactor); - profileData = ROIProfile.box(data, mask, (RectangularROI) roi); + if (data != null) + profileData = ROIProfile.box(data, mask, (RectangularROI) roi); if (profileData != null && profileData[0].getShape()[0] > 1 && profileData[1].getShape()[0] > 1) { AbstractDataset pdata; for (int i = 0; i < 2; i++) { pdata = profileData[i]; if (pdata instanceof AbstractCompoundDataset) // use first element profileData[i] = ((AbstractCompoundDataset) pdata).getElements(0); } Number sum = (Number) profileData[0].sum(); profileSum = sum.doubleValue(); xAxes = new AxisValues[] { null, null }; xAxes[0] = new AxisValues(); xAxes[1] = new AxisValues(); AbstractDataset axis; axis = profileData[0].getIndices().squeeze(); axis.imultiply(subFactor); xAxes[0].setValues(axis); axis = profileData[1].getIndices().squeeze(); axis.imultiply(subFactor); xAxes[1].setValues(axis); } else { setPlot(false); } } /** * Aggregate a copy of ROI data to this object * @param roi * @param profileData * @param axes * @param profileSum */ public RectangularROIData(RectangularROI roi, AbstractDataset[] profileData, AxisValues[] axes, double profileSum) { super(); setROI(roi.copy()); this.profileData = profileData.clone(); for (int i = 0; i < profileData.length; i++) { this.profileData[i] = profileData[i].clone(); } xAxes = axes.clone(); for (int i = 0; i < axes.length; i++) { xAxes[i] = axes[i].clone(); } this.profileSum = profileSum; setPlot(false); } /** * @return linear region of interest */ @Override public RectangularROI getROI() { return (RectangularROI) roi; } }
true
true
public RectangularROIData(RectangularROI rroi, AbstractDataset data, AbstractDataset mask, double subFactor) { super(); setROI(rroi.copy()); roi.downsample(subFactor); profileData = ROIProfile.box(data, mask, (RectangularROI) roi); if (profileData != null && profileData[0].getShape()[0] > 1 && profileData[1].getShape()[0] > 1) { AbstractDataset pdata; for (int i = 0; i < 2; i++) { pdata = profileData[i]; if (pdata instanceof AbstractCompoundDataset) // use first element profileData[i] = ((AbstractCompoundDataset) pdata).getElements(0); } Number sum = (Number) profileData[0].sum(); profileSum = sum.doubleValue(); xAxes = new AxisValues[] { null, null }; xAxes[0] = new AxisValues(); xAxes[1] = new AxisValues(); AbstractDataset axis; axis = profileData[0].getIndices().squeeze(); axis.imultiply(subFactor); xAxes[0].setValues(axis); axis = profileData[1].getIndices().squeeze(); axis.imultiply(subFactor); xAxes[1].setValues(axis); } else { setPlot(false); } }
public RectangularROIData(RectangularROI rroi, AbstractDataset data, AbstractDataset mask, double subFactor) { super(); setROI(rroi.copy()); roi.downsample(subFactor); if (data != null) profileData = ROIProfile.box(data, mask, (RectangularROI) roi); if (profileData != null && profileData[0].getShape()[0] > 1 && profileData[1].getShape()[0] > 1) { AbstractDataset pdata; for (int i = 0; i < 2; i++) { pdata = profileData[i]; if (pdata instanceof AbstractCompoundDataset) // use first element profileData[i] = ((AbstractCompoundDataset) pdata).getElements(0); } Number sum = (Number) profileData[0].sum(); profileSum = sum.doubleValue(); xAxes = new AxisValues[] { null, null }; xAxes[0] = new AxisValues(); xAxes[1] = new AxisValues(); AbstractDataset axis; axis = profileData[0].getIndices().squeeze(); axis.imultiply(subFactor); xAxes[0].setValues(axis); axis = profileData[1].getIndices().squeeze(); axis.imultiply(subFactor); xAxes[1].setValues(axis); } else { setPlot(false); } }
diff --git a/src/main/java/org/bukkit/event/vehicle/VehicleDamageEvent.java b/src/main/java/org/bukkit/event/vehicle/VehicleDamageEvent.java index 044cfe82..0b8c44ad 100644 --- a/src/main/java/org/bukkit/event/vehicle/VehicleDamageEvent.java +++ b/src/main/java/org/bukkit/event/vehicle/VehicleDamageEvent.java @@ -1,48 +1,48 @@ package org.bukkit.event.vehicle; import org.bukkit.entity.Entity; import org.bukkit.entity.Vehicle; import org.bukkit.event.Cancellable; /** * Raised when a vehicle receives damage. * * @author sk89q */ public class VehicleDamageEvent extends VehicleEvent implements Cancellable { private Entity attacker; private int damage; private boolean cancelled; public VehicleDamageEvent(Vehicle vehicle, Entity attacker, int damage) { - super(Type.ENTITY_DAMAGE, vehicle); + super(Type.VEHICLE_DAMAGE, vehicle); this.attacker = attacker; this.damage = damage; } public Entity getAttacker() { return attacker; } public int getDamage() { return damage; } /** * Change the damage. * * @param damage */ public void setDamage(int damage) { this.damage = damage; } public boolean isCancelled() { return cancelled; } public void setCancelled(boolean cancel) { this.cancelled = cancel; } }
true
true
public VehicleDamageEvent(Vehicle vehicle, Entity attacker, int damage) { super(Type.ENTITY_DAMAGE, vehicle); this.attacker = attacker; this.damage = damage; }
public VehicleDamageEvent(Vehicle vehicle, Entity attacker, int damage) { super(Type.VEHICLE_DAMAGE, vehicle); this.attacker = attacker; this.damage = damage; }
diff --git a/src/org/rascalmpl/library/experiments/Compiler/RVM/Interpreter/RVM.java b/src/org/rascalmpl/library/experiments/Compiler/RVM/Interpreter/RVM.java index 88c891a974..010794af95 100644 --- a/src/org/rascalmpl/library/experiments/Compiler/RVM/Interpreter/RVM.java +++ b/src/org/rascalmpl/library/experiments/Compiler/RVM/Interpreter/RVM.java @@ -1,1657 +1,1657 @@ package org.rascalmpl.library.experiments.Compiler.RVM.Interpreter; import java.io.PrintWriter; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Stack; import java.util.regex.Matcher; import org.eclipse.imp.pdb.facts.IBool; import org.eclipse.imp.pdb.facts.IConstructor; import org.eclipse.imp.pdb.facts.IDateTime; import org.eclipse.imp.pdb.facts.IInteger; import org.eclipse.imp.pdb.facts.IList; import org.eclipse.imp.pdb.facts.IListWriter; import org.eclipse.imp.pdb.facts.IMap; import org.eclipse.imp.pdb.facts.IMapWriter; import org.eclipse.imp.pdb.facts.INode; import org.eclipse.imp.pdb.facts.INumber; import org.eclipse.imp.pdb.facts.IRational; import org.eclipse.imp.pdb.facts.IReal; import org.eclipse.imp.pdb.facts.ISet; import org.eclipse.imp.pdb.facts.ISetWriter; import org.eclipse.imp.pdb.facts.ISourceLocation; import org.eclipse.imp.pdb.facts.IString; import org.eclipse.imp.pdb.facts.ITuple; import org.eclipse.imp.pdb.facts.IValue; import org.eclipse.imp.pdb.facts.IValueFactory; import org.eclipse.imp.pdb.facts.type.ITypeVisitor; import org.eclipse.imp.pdb.facts.type.Type; import org.eclipse.imp.pdb.facts.type.TypeFactory; import org.eclipse.imp.pdb.facts.type.TypeStore; import org.rascalmpl.interpreter.IEvaluatorContext; import org.rascalmpl.interpreter.control_exceptions.Throw; import org.rascalmpl.interpreter.types.FunctionType; import org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.Instructions.Opcode; public class RVM { public final IValueFactory vf; private final TypeFactory tf; private final Boolean TRUE; private final Boolean FALSE; private final IBool Rascal_TRUE; private final IBool Rascal_FALSE; private final IString NONE; private final Failure FAILURE = Failure.getInstance(); private boolean debug = true; private boolean listing = false; private boolean finalized = false; private final ArrayList<Function> functionStore; private final Map<String, Integer> functionMap; // Function overloading private final Map<String, Integer> resolver; private final ArrayList<OverloadedFunction> overloadedStore; private final TypeStore typeStore = new TypeStore(); private final Types types; private final ArrayList<Type> constructorStore; private final Map<String, Integer> constructorMap; private IMap grammars; private final Map<IValue, IValue> moduleVariables; PrintWriter stdout; PrintWriter stderr; // Management of active coroutines Stack<Coroutine> activeCoroutines = new Stack<>(); Frame ccf = null; // the start frame (of the coroutine's main function) of the current active coroutine IEvaluatorContext ctx; public RVM(IValueFactory vf, IEvaluatorContext ctx, boolean debug, boolean profile) { super(); this.vf = vf; tf = TypeFactory.getInstance(); this.ctx = ctx; this.stdout = ctx.getStdOut(); this.stderr = ctx.getStdErr(); this.debug = debug; this.finalized = false; this.types = new Types(this.vf); TRUE = true; FALSE = false; Rascal_TRUE = vf.bool(true); Rascal_FALSE = vf.bool(false); NONE = vf.string("$nothing$"); functionStore = new ArrayList<Function>(); constructorStore = new ArrayList<Type>(); functionMap = new HashMap<String, Integer>(); constructorMap = new HashMap<String, Integer>(); resolver = new HashMap<String,Integer>(); overloadedStore = new ArrayList<OverloadedFunction>(); moduleVariables = new HashMap<IValue,IValue>(); MuPrimitive.init(vf, stdout, profile); RascalPrimitive.init(vf, this, profile); Opcode.init(stdout, profile); } public RVM(IValueFactory vf){ this(vf, null, false, false); } public void declare(Function f){ if(functionMap.get(f.getName()) != null){ throw new RuntimeException("PANIC: Double declaration of function: " + f.getName()); } functionMap.put(f.getName(), functionStore.size()); functionStore.add(f); } public void declareConstructor(String name, IConstructor symbol) { Type constr = types.symbolToType(symbol, typeStore); if(constructorMap.get(name) != null) { throw new RuntimeException("PANIC: Double declaration of constructor: " + name); } constructorMap.put(name, constructorStore.size()); constructorStore.add(constr); } public Type symbolToType(IConstructor symbol) { return types.symbolToType(symbol, typeStore); } public void addResolver(IMap resolver) { for(IValue fuid : resolver) { String of = ((IString) fuid).getValue(); int index = ((IInteger) resolver.get(fuid)).intValue(); this.resolver.put(of, index); } } public void fillOverloadedStore(IList overloadedStore) { for(IValue of : overloadedStore) { ITuple ofTuple = (ITuple) of; String scopeIn = ((IString) ofTuple.get(0)).getValue(); if(scopeIn.equals("")) { scopeIn = null; } IList fuids = (IList) ofTuple.get(1); int[] funs = new int[fuids.length()]; int i = 0; for(IValue fuid : fuids) { Integer index = functionMap.get(((IString) fuid).getValue()); if(index == null){ throw new RuntimeException("No definition for " + fuid + " in functionMap"); } funs[i++] = index; } fuids = (IList) ofTuple.get(2); int[] constrs = new int[fuids.length()]; i = 0; for(IValue fuid : fuids) { Integer index = constructorMap.get(((IString) fuid).getValue()); if(index == null){ throw new RuntimeException("No definition for " + fuid + " in constructorMap"); } constrs[i++] = index; } this.overloadedStore.add(new OverloadedFunction(funs, constrs, scopeIn)); } } public void setGrammars(IMap grammer){ this.grammars = grammars; } public IMap getGrammars(){ return grammars; } /** * Narrow an Object as occurring on the RVM runtime stack to an IValue that can be returned. * Note that various non-IValues can occur: * - Coroutine * - Reference * - FunctionInstance * - Object[] (is converted to an IList) * @param result to be returned * @return converted result or an exception */ private IValue narrow(Object result){ if(result instanceof Boolean) { return vf.bool((Boolean) result); } if(result instanceof Integer) { return vf.integer((Integer)result); } if(result instanceof IValue) { return (IValue) result; } if(result instanceof Thrown) { ((Thrown) result).printStackTrace(stdout); return vf.string(((Thrown) result).toString()); } if(result instanceof Object[]) { IListWriter w = vf.listWriter(); Object[] lst = (Object[]) result; for(int i = 0; i < lst.length; i++){ w.append(narrow(lst[i])); } return w.done(); } throw new RuntimeException("PANIC: Cannot convert object back to IValue: " + result); } /** * Represent any object that can occur on the RVM stack stack as string * @param some stack object * @return its string representation */ private String asString(Object o){ if(o == null) return "null"; if(o instanceof Boolean) return ((Boolean) o).toString() + " [Java]"; if(o instanceof Integer) return ((Integer)o).toString() + " [Java]"; if(o instanceof IValue) return ((IValue) o).toString() +" [IValue]"; if(o instanceof Type) return ((Type) o).toString() + " [Type]"; if(o instanceof Object[]){ StringBuilder w = new StringBuilder(); Object[] lst = (Object[]) o; w.append("["); for(int i = 0; i < lst.length; i++){ w.append(asString(lst[i])); if(i < lst.length - 1) w.append(", "); } w.append("]"); return w.toString() + " [Object[]]"; } if(o instanceof Coroutine){ return "Coroutine[" + ((Coroutine)o).frame.function.getName() + "]"; } if(o instanceof Function){ return "Function[" + ((Function)o).getName() + "]"; } if(o instanceof FunctionInstance){ return "Function[" + ((FunctionInstance)o).function.getName() + "]"; } if(o instanceof OverloadedFunctionInstance) { OverloadedFunctionInstance of = (OverloadedFunctionInstance) o; String alts = ""; for(Integer fun : of.functions) { alts = alts + functionStore.get(fun).getName() + "; "; } return "OverloadedFunction[ alts: " + alts + "]"; } if(o instanceof Reference){ Reference ref = (Reference) o; return "Reference[" + ref.stack + ", " + ref.pos + "]"; } if(o instanceof IListWriter){ return "ListWriter[" + ((IListWriter) o).toString() + "]"; } if(o instanceof ISetWriter){ return "SetWriter[" + ((ISetWriter) o).toString() + "]"; } if(o instanceof IMapWriter){ return "MapWriter[" + ((IMapWriter) o).toString() + "]"; } if(o instanceof Matcher){ return "Matcher[" + ((Matcher) o).pattern() + "]"; } if(o instanceof Thrown) { return "THROWN[ " + asString(((Thrown) o).value) + " ]"; } if(o instanceof StringBuilder){ return "StringBuilder[" + ((StringBuilder) o).toString() + "]"; } if(o instanceof HashSet){ return "HashSet[" + ((HashSet) o).toString() + "]"; } throw new RuntimeException("PANIC: asString cannot convert: " + o); } public void finalize(){ // Finalize the instruction generation of all functions, if needed if(!finalized){ finalized = true; for(Function f : functionStore) { f.finalize(functionMap, constructorMap, resolver, listing); } for(OverloadedFunction of : overloadedStore) { of.finalize(functionMap); } } } public String getFunctionName(int n) { for(String fname : functionMap.keySet()) { if(functionMap.get(fname) == n) { return fname; } } throw new RuntimeException("PANIC: undefined function index " + n); } public String getConstructorName(int n) { for(String cname : constructorMap.keySet()) { if(constructorMap.get(cname) == n) { return cname; } } throw new RuntimeException("PANIC: undefined constructor index " + n); } public String getOverloadedFunctionName(int n) { for(String ofname : resolver.keySet()) { if(resolver.get(ofname) == n) { return ofname; } } throw new RuntimeException("PANIC: undefined overloaded function index " + n); } public IValue executeFunction(String uid_func, IValue[] args){ // Assumption here is that the function called is not nested one // and does not use global variables Function func = functionStore.get(functionMap.get(uid_func)); Frame root = new Frame(func.scopeId, null, func.maxstack, func); Frame cf = root; // Pass the program arguments to main for(int i = 0; i < args.length; i++){ cf.stack[i] = args[i]; } Object o = executeProgram(root, cf); if(o instanceof Thrown){ throw (Thrown) o; } return narrow(o); } private Frame pushArguments(Frame cf, Function func, Frame env, IValue[] args) { cf = new Frame(func.scopeId, cf, env, func.maxstack, func); if(func.isVarArgs) { // VarArgs for(int i = 0; i < func.nformals - 2; i++) { cf.stack[i] = args[i]; } Type argTypes = ((FunctionType) func.ftype).getArgumentTypes(); if(args.length == func.nformals && args[func.nformals - 2].getType().isSubtypeOf(argTypes.getFieldType(func.nformals - 2))) { cf.stack[func.nformals - 2] = args[func.nformals - 2]; } else { IListWriter writer = vf.listWriter(); for(int i = func.nformals - 2; i < args.length - 1; i++) { writer.append((IValue) args[i]); } cf.stack[func.nformals - 2] = writer.done(); } cf.stack[func.nformals - 1] = args[args.length - 1]; // Keyword arguments } else { for(int i = 0; i < args.length; i++){ cf.stack[i] = args[i]; } } cf.sp = func.nlocals; return cf; } private String trace = ""; public String getTrace() { return trace; } public void appendToTrace(String trace) { this.trace = this.trace + trace + "\n"; } public IValue executeProgram(String uid_main, IValue[] args) { finalize(); Function main_function = functionStore.get(functionMap.get(uid_main)); if (main_function == null) { throw new RuntimeException("PANIC: No function " + uid_main + " found"); } if (main_function.nformals != 2) { // List of IValues and empty map of keyword parameters throw new RuntimeException("PANIC: function " + uid_main + " should have two arguments"); } Frame root = new Frame(main_function.scopeId, null, main_function.maxstack, main_function); Frame cf = root; cf.stack[0] = vf.list(args); // pass the program argument to main_function as a IList object cf.stack[1] = vf.mapWriter().done(); Object o = executeProgram(root, cf); if(o != null && o instanceof Thrown){ throw (Thrown) o; } IValue res = narrow(o); if(debug) { stdout.println("TRACE:"); stdout.println(getTrace()); } return res; } private Object executeProgram(Frame root, Frame cf) { Object[] stack = cf.stack; // current stack int sp = cf.function.nlocals; // current stack pointer int [] instructions = cf.function.codeblock.getInstructions(); // current instruction sequence int pc = 0; // current program counter int postOp = 0; int pos = 0; ArrayList<Frame> stacktrace; Thrown thrown; int arity; String last_function_name = ""; // Overloading specific Stack<OverloadedFunctionInstanceCall> ocalls = new Stack<OverloadedFunctionInstanceCall>(); OverloadedFunctionInstanceCall c_ofun_call = null; try { NEXT_INSTRUCTION: while (true) { // if(pc < 0 || pc >= instructions.length){ // throw new RuntimeException(cf.function.name + " illegal pc: " + pc); // } int instruction = instructions[pc++]; int op = CodeBlock.fetchOp(instruction); if (debug) { int startpc = pc - 1; if(!last_function_name.equals(cf.function.name)) stdout.printf("[%03d] %s\n", startpc, cf.function.name); for (int i = 0; i < sp; i++) { stdout.println("\t " + (i < cf.function.nlocals ? "*" : " ") + i + ": " + asString(stack[i])); } stdout.printf("%5s %s\n" , "", cf.function.codeblock.toString(startpc)); } Opcode.use(instruction); switch (op) { case Opcode.OP_POP: sp--; continue NEXT_INSTRUCTION; case Opcode.OP_LOADLOC0: if(stack[0] != null){ stack[sp++] = stack[0]; continue NEXT_INSTRUCTION; } pos = 0; postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADLOC1: if(stack[1] != null){ stack[sp++] = stack[1]; continue NEXT_INSTRUCTION; } pos = 1; postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADLOC2: if(stack[2] != null){ stack[sp++] = stack[2]; continue NEXT_INSTRUCTION; } pos = 2; postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADLOC3: if(stack[3] != null){ stack[sp++] = stack[3]; continue NEXT_INSTRUCTION; } pos = 3; postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADLOC4: if(stack[4] != null){ stack[sp++] = stack[4]; continue NEXT_INSTRUCTION; } pos = 4; postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADLOC5: if(stack[5] != null){ stack[sp++] = stack[5]; continue NEXT_INSTRUCTION; } pos = 5; postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADLOC6: if(stack[6] != null){ stack[sp++] = stack[6]; continue NEXT_INSTRUCTION; } pos = 6; postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADLOC7: if(stack[7] != null){ stack[sp++] = stack[7]; continue NEXT_INSTRUCTION; } pos = 7; postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADLOC8: if(stack[8] != null){ stack[sp++] = stack[8]; continue NEXT_INSTRUCTION; } pos = 8; postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADLOC9: if(stack[9] != null){ stack[sp++] = stack[9]; continue NEXT_INSTRUCTION; } pos = 9; postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADLOC: pos = CodeBlock.fetchArg1(instruction); Object rval = stack[pos]; if(rval != null){ stack[sp++] = rval; continue NEXT_INSTRUCTION; } postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADBOOL: stack[sp++] = CodeBlock.fetchArg1(instruction) == 1 ? true : false; continue NEXT_INSTRUCTION; case Opcode.OP_LOADINT: stack[sp++] = CodeBlock.fetchArg1(instruction); continue NEXT_INSTRUCTION; case Opcode.OP_LOADCON: stack[sp++] = cf.function.constantStore[CodeBlock.fetchArg1(instruction)]; continue NEXT_INSTRUCTION; case Opcode.OP_LOADLOCREF: stack[sp++] = new Reference(stack, CodeBlock.fetchArg1(instruction)); continue NEXT_INSTRUCTION; case Opcode.OP_CALLMUPRIM: MuPrimitive muprim = MuPrimitive.fromInteger(CodeBlock.fetchArg1(instruction)); sp = muprim.invoke(stack, sp, CodeBlock.fetchArg2(instruction)); continue NEXT_INSTRUCTION; case Opcode.OP_JMP: pc = CodeBlock.fetchArg1(instruction); continue NEXT_INSTRUCTION; case Opcode.OP_JMPTRUE: if (stack[sp - 1].equals(TRUE) || stack[sp - 1].equals(Rascal_TRUE)) { pc = CodeBlock.fetchArg1(instruction); } sp--; continue NEXT_INSTRUCTION; case Opcode.OP_JMPFALSE: if (stack[sp - 1].equals(FALSE) || stack[sp - 1].equals(Rascal_FALSE)) { pc = CodeBlock.fetchArg1(instruction); } sp--; continue NEXT_INSTRUCTION; case Opcode.OP_TYPESWITCH: IValue val = (IValue) stack[--sp]; Type t = null; if(val instanceof IConstructor) { t = ((IConstructor) val).getConstructorType(); } else { t = val.getType(); } int labelIndex = ToplevelType.getToplevelTypeAsInt(t); IList labels = (IList) cf.function.constantStore[CodeBlock.fetchArg1(instruction)]; pc = ((IInteger) labels.get(labelIndex)).intValue(); continue NEXT_INSTRUCTION; case Opcode.OP_JMPINDEXED: labelIndex = ((IInteger) stack[--sp]).intValue(); labels = (IList) cf.function.constantStore[CodeBlock.fetchArg1(instruction)]; pc = ((IInteger) labels.get(labelIndex)).intValue(); continue NEXT_INSTRUCTION; case Opcode.OP_LOADTYPE: stack[sp++] = cf.function.typeConstantStore[CodeBlock.fetchArg1(instruction)]; continue NEXT_INSTRUCTION; case Opcode.OP_LOADLOCDEREF: { Reference ref = (Reference) stack[CodeBlock.fetchArg1(instruction)]; stack[sp++] = ref.stack[ref.pos]; continue NEXT_INSTRUCTION; } case Opcode.OP_STORELOC: { stack[CodeBlock.fetchArg1(instruction)] = stack[sp - 1]; continue NEXT_INSTRUCTION; } case Opcode.OP_UNWRAPTHROWN: { stack[CodeBlock.fetchArg1(instruction)] = ((Thrown) stack[--sp]).value; continue NEXT_INSTRUCTION; } case Opcode.OP_STORELOCDEREF: Reference ref = (Reference) stack[CodeBlock.fetchArg1(instruction)]; ref.stack[ref.pos] = stack[sp - 1]; // TODO: We need to re-consider how to guarantee safe use of both Java objects and IValues continue NEXT_INSTRUCTION; case Opcode.OP_LOADFUN: // Loads functions that are defined at the root stack[sp++] = new FunctionInstance(functionStore.get(CodeBlock.fetchArg1(instruction)), root); continue NEXT_INSTRUCTION; case Opcode.OP_LOAD_NESTED_FUN: { // Loads nested functions and closures (anonymous nested functions): // First, get the function code Function fun = functionStore.get(CodeBlock.fetchArg1(instruction)); int scopeIn = CodeBlock.fetchArg2(instruction); // Second, look up the function environment frame into the stack of caller frames for(Frame env = cf; env != null; env = env.previousCallFrame) { if (env.scopeId == scopeIn) { stack[sp++] = new FunctionInstance(fun, env); continue NEXT_INSTRUCTION; } } throw new RuntimeException("LOAD_NESTED_FUN cannot find matching scope: " + scopeIn); } case Opcode.OP_LOADOFUN: OverloadedFunction of = overloadedStore.get(CodeBlock.fetchArg1(instruction)); if(of.scopeIn == -1) { stack[sp++] = new OverloadedFunctionInstance(of.functions, of.constructors, root); continue NEXT_INSTRUCTION; } for(Frame env = cf; env != null; env = env.previousCallFrame) { if (env.scopeId == of.scopeIn) { stack[sp++] = new OverloadedFunctionInstance(of.functions, of.constructors, env); continue NEXT_INSTRUCTION; } } throw new RuntimeException("Could not find matching scope when loading a nested overloaded function: " + of.scopeIn); case Opcode.OP_LOADCONSTR: Type constructor = constructorStore.get(CodeBlock.fetchArg1(instruction)); stack[sp++] = constructor; continue NEXT_INSTRUCTION; case Opcode.OP_LOADVAR: case Opcode.OP_LOADVARREF: { int s = CodeBlock.fetchArg1(instruction); pos = CodeBlock.fetchArg2(instruction); if(CodeBlock.isMaxArg2(pos)){ rval = moduleVariables.get(cf.function.constantStore[s]); if(op == Opcode.OP_LOADVAR && rval == null) { // EXCEPTION HANDLING stacktrace = new ArrayList<Frame>(); stacktrace.add(cf); thrown = RuntimeExceptions.uninitializedVariable(pos, null, stacktrace); for(Frame f = cf; f != null; f = f.previousCallFrame) { int handler = f.function.getHandler(pc - 1, thrown.value.getType()); if(handler != -1) { if(f != cf) { cf = f; instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; } pc = handler; stack[sp++] = thrown; continue NEXT_INSTRUCTION; } } // If a handler has not been found in the caller functions... return thrown; } stack[sp++] = rval; continue NEXT_INSTRUCTION; } for (Frame fr = cf; fr != null; fr = fr.previousScope) { if (fr.scopeId == s) { rval = (op == Opcode.OP_LOADVAR) ? fr.stack[pos] : new Reference(fr.stack, pos); if(op == Opcode.OP_LOADLOC && rval == null) { // EXCEPTION HANDLING stacktrace = new ArrayList<Frame>(); stacktrace.add(cf); thrown = RuntimeExceptions.uninitializedVariable(pos, null, stacktrace); for(Frame f = cf; f != null; f = f.previousCallFrame) { int handler = f.function.getHandler(pc - 1, thrown.value.getType()); if(handler != -1) { if(f != cf) { cf = f; instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; } pc = handler; stack[sp++] = thrown; continue NEXT_INSTRUCTION; } } // If a handler has not been found in the caller functions... return thrown; } stack[sp++] = rval; continue NEXT_INSTRUCTION; } } throw new RuntimeException("LOADVAR or LOADVARREF cannot find matching scope: " + s); } case Opcode.OP_LOADVARDEREF: { int s = CodeBlock.fetchArg1(instruction); pos = CodeBlock.fetchArg2(instruction); for (Frame fr = cf; fr != null; fr = fr.previousScope) { if (fr.scopeId == s) { ref = (Reference) fr.stack[pos]; stack[sp++] = ref.stack[ref.pos]; continue NEXT_INSTRUCTION; } } throw new RuntimeException("LOADVARDEREF cannot find matching scope: " + s); } case Opcode.OP_STOREVAR: int s = CodeBlock.fetchArg1(instruction); pos = CodeBlock.fetchArg2(instruction); if(CodeBlock.isMaxArg2(pos)){ IValue mvar = cf.function.constantStore[s]; moduleVariables.put(mvar, (IValue)stack[sp -1]); continue NEXT_INSTRUCTION; } for (Frame fr = cf; fr != null; fr = fr.previousScope) { if (fr.scopeId == s) { fr.stack[pos] = stack[sp - 1]; // TODO: We need to re-consider how to guarantee safe use of both Java objects and IValues continue NEXT_INSTRUCTION; } } throw new RuntimeException("STOREVAR cannot find matching scope: " + s); case Opcode.OP_STOREVARDEREF: s = CodeBlock.fetchArg1(instruction); pos = CodeBlock.fetchArg2(instruction); for (Frame fr = cf; fr != null; fr = fr.previousScope) { if (fr.scopeId == s) { ref = (Reference) fr.stack[pos]; ref.stack[ref.pos] = stack[sp - 1]; continue NEXT_INSTRUCTION; } } throw new RuntimeException("STOREVARDEREF cannot find matching scope: " + s); case Opcode.OP_CALLCONSTR: constructor = constructorStore.get(CodeBlock.fetchArg1(instruction)); arity = CodeBlock.fetchArg2(instruction); assert arity == constructor.getArity(); IValue[] args = new IValue[arity]; for(int i = 0; i < arity; i++) { args[arity - 1 - i] = (IValue) stack[--sp]; } stack[sp++] = vf.constructor(constructor, args); continue NEXT_INSTRUCTION; case Opcode.OP_CALLDYN: case Opcode.OP_CALL: // In case of CALLDYN, the stack top value of type 'Type' leads to a constructor call if(op == Opcode.OP_CALLDYN && stack[sp - 1] instanceof Type) { Type constr = (Type) stack[--sp]; arity = constr.getArity(); args = new IValue[arity]; for(int i = arity - 1; i >=0; i--) { args[i] = (IValue) stack[sp - arity + i]; } sp = sp - arity; stack[sp++] = vf.constructor(constr, args); continue NEXT_INSTRUCTION; } Function fun = null; Frame previousScope = null; if(op == Opcode.OP_CALLDYN && stack[sp - 1] instanceof FunctionInstance){ FunctionInstance fun_instance = (FunctionInstance) stack[--sp]; arity = CodeBlock.fetchArg1(instruction); // TODO: add assert fun = fun_instance.function; previousScope = fun_instance.env; } else if(op == Opcode.OP_CALL) { fun = functionStore.get(CodeBlock.fetchArg1(instruction)); arity = CodeBlock.fetchArg2(instruction); assert arity == fun.nformals; previousScope = cf; } else { throw new RuntimeException("unexpected argument type for CALLDYN: " + asString(stack[sp - 1])); } instructions = fun.codeblock.getInstructions(); Frame nextFrame = new Frame(fun.scopeId, cf, previousScope, fun.maxstack, fun); for (int i = fun.nformals - 1; i >= 0; i--) { nextFrame.stack[i] = stack[sp - fun.nformals + i]; } cf.pc = pc; cf.sp = sp - fun.nformals; cf = nextFrame; stack = cf.stack; sp = fun.nlocals; pc = 0; continue NEXT_INSTRUCTION; case Opcode.OP_OCALLDYN: // Get function types to perform a type-based dynamic resolution Type types = cf.function.codeblock.getConstantType(CodeBlock.fetchArg1(instruction)); arity = CodeBlock.fetchArg2(instruction); // Objects of three types may appear on the stack: // 1. FunctionInstance due to closures // 2. OverloadedFunctionInstance due to named Rascal functions Object funcObject = stack[--sp]; // Get function arguments from the stack args = new IValue[arity]; for(int i = arity - 1; i >= 0; i--) { args[i] = (IValue) stack[sp - arity + i]; } sp = sp - arity; if(funcObject instanceof FunctionInstance) { FunctionInstance fun_instance = (FunctionInstance) funcObject; cf.sp = sp; cf.pc = pc; cf = pushArguments(cf, fun_instance.function, fun_instance.env, args); instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; continue NEXT_INSTRUCTION; } OverloadedFunctionInstance of_instance = (OverloadedFunctionInstance) funcObject; if(debug) { this.appendToTrace("OVERLOADED FUNCTION CALLDYN: "); this.appendToTrace(" with alternatives:"); for(int index : of_instance.functions) { this.appendToTrace(" " + getFunctionName(index)); } } c_ofun_call = new OverloadedFunctionInstanceCall(vf, cf, of_instance.functions, of_instance.constructors, of_instance.env, args, types); ocalls.push(c_ofun_call); fun = c_ofun_call.nextFunction(functionStore); if(fun != null) { if(debug) { this.appendToTrace(" " + "try alternative: " + fun.name); } cf.sp = sp; cf.pc = pc; cf = pushArguments(c_ofun_call.cf, fun, c_ofun_call.env, c_ofun_call.args); instructions = fun.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = 0; } else { stack[sp++] = vf.constructor(c_ofun_call.nextConstructor(constructorStore), c_ofun_call.constr_args); } continue NEXT_INSTRUCTION; case Opcode.OP_OCALL: of = overloadedStore.get(CodeBlock.fetchArg1(instruction)); arity = CodeBlock.fetchArg2(instruction); if(debug) { this.appendToTrace("OVERLOADED FUNCTION CALL: " + getOverloadedFunctionName(CodeBlock.fetchArg1(instruction))); this.appendToTrace(" with alternatives:"); for(int index : of.functions) { this.appendToTrace(" " + getFunctionName(index)); } } // Get arguments from the stack args = new IValue[arity]; for(int i = arity - 1; i >= 0; i--) { args[i] = (IValue) stack[sp - arity + i]; } sp = sp - arity; c_ofun_call = new OverloadedFunctionInstanceCall(vf, root, cf, of.functions, of.constructors, of.scopeIn, args, null); ocalls.push(c_ofun_call); fun = c_ofun_call.nextFunction(functionStore); if(fun != null) { if(debug) { this.appendToTrace(" " + "try alternative: " + fun.name); } cf.sp = sp; cf.pc = pc; cf = pushArguments(c_ofun_call.cf, fun, c_ofun_call.env, c_ofun_call.args); instructions = fun.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = 0; } else { stack[sp++] = vf.constructor(c_ofun_call.nextConstructor(constructorStore), c_ofun_call.constr_args); } continue NEXT_INSTRUCTION; case Opcode.OP_FAILRETURN: assert cf.previousCallFrame == c_ofun_call.cf; fun = c_ofun_call.nextFunction(functionStore); if(fun != null) { if(debug) { this.appendToTrace(" " + "try alternative: " + fun.name); } cf.sp = sp; cf.pc = pc; cf = pushArguments(c_ofun_call.cf, fun, c_ofun_call.env, c_ofun_call.args); instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; } else { cf = c_ofun_call.cf; instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; stack[sp++] = vf.constructor(c_ofun_call.nextConstructor(constructorStore), c_ofun_call.constr_args); } continue NEXT_INSTRUCTION; case Opcode.OP_FILTERRETURN: case Opcode.OP_RETURN0: case Opcode.OP_RETURN1: // Overloading specific if(c_ofun_call != null && cf.previousCallFrame == c_ofun_call.cf) { ocalls.pop(); c_ofun_call = ocalls.isEmpty() ? null : ocalls.peek(); } rval = null; boolean returns = cf.isCoroutine || op == Opcode.OP_RETURN1 || op == Opcode.OP_FILTERRETURN; if(op == Opcode.OP_RETURN1 || cf.isCoroutine) { if(cf.isCoroutine) { rval = Rascal_TRUE; if(op == Opcode.OP_RETURN1) { arity = CodeBlock.fetchArg1(instruction); int[] refs = cf.function.refs; if(arity != refs.length) { throw new RuntimeException("Coroutine " + cf.function.name + ": arity of return (" + arity + ") unequal to number of reference parameters (" + refs.length + ")"); } for(int i = 0; i < arity; i++) { ref = (Reference) stack[refs[arity - 1 - i]]; ref.stack[ref.pos] = stack[--sp]; } } } else { rval = stack[sp - 1]; } } // if the current frame is the frame of a top active coroutine, // then pop this coroutine from the stack of active coroutines if(cf == ccf) { activeCoroutines.pop(); ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start; } cf = cf.previousCallFrame; if(cf == null) { if(returns) { return rval; } else { return NONE; } } instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; if(returns) { stack[sp++] = rval; } continue NEXT_INSTRUCTION; case Opcode.OP_CALLJAVA: String methodName = ((IString) cf.function.constantStore[instructions[pc++]]).getValue(); String className = ((IString) cf.function.constantStore[instructions[pc++]]).getValue(); Type parameterTypes = cf.function.typeConstantStore[instructions[pc++]]; int reflect = instructions[pc++]; arity = parameterTypes.getArity(); try { sp = callJavaMethod(methodName, className, parameterTypes, reflect, stack, sp); } catch(Throw e) { thrown = Thrown.getInstance(e.getException(), e.getLocation(), new ArrayList<Frame>()); // EXCEPTION HANDLING for(Frame f = cf; f != null; f = f.previousCallFrame) { int handler = f.function.getHandler(pc - 1, thrown.value.getType()); if(handler != -1) { if(f != cf) { cf = f; instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; } pc = handler; stack[sp++] = thrown; continue NEXT_INSTRUCTION; } } // If a handler has not been found in the caller functions... return thrown; } continue NEXT_INSTRUCTION; case Opcode.OP_INIT: arity = CodeBlock.fetchArg1(instruction); Object src = stack[--sp]; Coroutine coroutine; if(src instanceof Coroutine){ coroutine = (Coroutine) src; fun = coroutine.frame.function; } else if(src instanceof FunctionInstance) { FunctionInstance fun_instance = (FunctionInstance) src; fun = fun_instance.function; Frame frame = new Frame(fun.scopeId, null, fun_instance.env, fun.maxstack, fun); coroutine = new Coroutine(frame); } else { throw new RuntimeException("Unexpected argument type for INIT: " + src.getClass() + ", " + src); } if(coroutine.isInitialized()) { throw new RuntimeException("Trying to initialize a coroutine, which has already been initialized: " + fun.getName() + " (corounine's main), called in " + cf.function.getName()); } // the main function of coroutine may have formal parameters, // therefore, INIT may take a number of arguments == formal parameters - arguments already passed to CREATE if(arity != fun.nformals - coroutine.frame.sp) { throw new RuntimeException("Too many or too few arguments to INIT, the expected number: " + (fun.nformals - coroutine.frame.sp) + "; coroutine's main: " + fun.getName() + ", called in " + cf.function.getName()); } Coroutine newCoroutine = coroutine.copy(); for (int i = arity - 1; i >= 0; i--) { newCoroutine.frame.stack[coroutine.frame.sp + i] = stack[sp - arity + i]; } newCoroutine.frame.sp = fun.nlocals; sp = sp - arity; /* Place coroutine back on stack */ stack[sp++] = newCoroutine; // Now, instead of simply suspending a coroutine during INIT, let it execute until GUARD, which has been delegated the INIT's suspension newCoroutine.suspend(newCoroutine.frame); // put the coroutine onto the stack of active coroutines activeCoroutines.push(newCoroutine); ccf = newCoroutine.start; newCoroutine.next(cf); fun = newCoroutine.frame.function; instructions = newCoroutine.frame.function.codeblock.getInstructions(); cf.pc = pc; cf.sp = sp; cf = newCoroutine.frame; stack = cf.stack; sp = cf.sp; pc = cf.pc; continue NEXT_INSTRUCTION; case Opcode.OP_GUARD: rval = stack[sp - 1]; boolean precondition; if(rval instanceof IBool) { precondition = ((IBool) rval).getValue(); } else if(rval instanceof Boolean) { precondition = (Boolean) rval; } else { throw new RuntimeException("Guard's expression has to be boolean!"); } if(cf == ccf) { coroutine = activeCoroutines.pop(); ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start; Frame prev = cf.previousCallFrame; if(precondition) { coroutine.suspend(cf); } --sp; cf.pc = pc; cf.sp = sp; cf = prev; instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; continue NEXT_INSTRUCTION; } if(!precondition) { cf.pc = pc; cf.sp = sp; cf = cf.previousCallFrame; instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; stack[sp++] = Rascal_FALSE; continue NEXT_INSTRUCTION; } continue NEXT_INSTRUCTION; case Opcode.OP_CREATE: case Opcode.OP_CREATEDYN: if(op == Opcode.OP_CREATE){ fun = functionStore.get(CodeBlock.fetchArg1(instruction)); arity = CodeBlock.fetchArg2(instruction); previousScope = null; } else { arity = CodeBlock.fetchArg1(instruction); src = stack[--sp]; if(src instanceof FunctionInstance) { FunctionInstance fun_instance = (FunctionInstance) src; fun = fun_instance.function; previousScope = fun_instance.env; } else { throw new RuntimeException("unexpected argument type for CREATEDYN: " + asString(src)); } } Frame frame = new Frame(fun.scopeId, null, previousScope, fun.maxstack, fun); // the main function of coroutine may have formal parameters, // therefore, CREATE may take a number of arguments <= formal parameters if(arity > fun.nformals) throw new RuntimeException("Too many arguments to CREATE or CREATEDYN, expected <= " + fun.nformals); for (int i = arity - 1; i >= 0; i--) { frame.stack[i] = stack[sp - arity + i]; } frame.sp = arity; coroutine = new Coroutine(frame); sp = sp - arity; stack[sp++] = coroutine; continue NEXT_INSTRUCTION; case Opcode.OP_NEXT0: case Opcode.OP_NEXT1: coroutine = (Coroutine) stack[--sp]; // Merged the hasNext and next semantics if(!coroutine.hasNext()) { if(op == Opcode.OP_NEXT1) { --sp; } stack[sp++] = FALSE; continue NEXT_INSTRUCTION; } // put the coroutine onto the stack of active coroutines activeCoroutines.push(coroutine); ccf = coroutine.start; coroutine.next(cf); fun = coroutine.frame.function; instructions = coroutine.frame.function.codeblock.getInstructions(); coroutine.frame.stack[coroutine.frame.sp++] = // Always leave an entry on the stack (op == Opcode.OP_NEXT1) ? stack[--sp] : null; cf.pc = pc; cf.sp = sp; cf = coroutine.frame; stack = cf.stack; sp = cf.sp; pc = cf.pc; continue NEXT_INSTRUCTION; case Opcode.OP_YIELD0: case Opcode.OP_YIELD1: coroutine = activeCoroutines.pop(); ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start; Frame prev = coroutine.start.previousCallFrame; rval = Rascal_TRUE; // In fact, yield has to always return TRUE if(op == Opcode.OP_YIELD1) { arity = CodeBlock.fetchArg1(instruction); int[] refs = coroutine.start.function.refs; // Takes the reference parameter positions of the top active coroutine instance if(cf != coroutine.start && cf.function.refs.length != refs.length) { throw new RuntimeException("The 'yield' from within a nested call has to take the same number of arguments as the number of the caller's reference parameters: " + cf.function.refs.length + "; " + refs.length); } if(arity != refs.length) { throw new RuntimeException("The 'yield' within a coroutine has to take the same number of arguments as the number of its reference parameters; arity: " + arity + "; reference parameter number: " + refs.length); } for(int i = 0; i < arity; i++) { ref = (Reference) coroutine.start.stack[refs[arity - 1 - i]]; // Takes the reference parameters of the top active coroutine instance ref.stack[ref.pos] = stack[--sp]; } } cf.pc = pc; cf.sp = sp; coroutine.suspend(cf); cf = prev; if(op == Opcode.OP_YIELD1 && cf == null) return rval; instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; stack[sp++] = rval; // Corresponding next will always find an entry on the stack continue NEXT_INSTRUCTION; case Opcode.OP_EXHAUST: if(cf == ccf) { activeCoroutines.pop(); ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start; } cf = cf.previousCallFrame; if(cf == null) { return Rascal_FALSE; // 'Exhaust' has to always return FALSE, i.e., signal a failure; } instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; stack[sp++] = Rascal_FALSE; // 'Exhaust' has to always return FALSE, i.e., signal a failure; continue NEXT_INSTRUCTION; case Opcode.OP_HASNEXT: coroutine = (Coroutine) stack[--sp]; stack[sp++] = coroutine.hasNext() ? TRUE : FALSE; continue NEXT_INSTRUCTION; case Opcode.OP_CALLPRIM: RascalPrimitive prim = RascalPrimitive.fromInteger(CodeBlock.fetchArg1(instruction)); arity = CodeBlock.fetchArg2(instruction); try { sp = prim.invoke(stack, sp, arity); } catch(InvocationTargetException targetException) { if(!(targetException.getTargetException() instanceof Thrown)) { throw targetException; } // EXCEPTION HANDLING thrown = (Thrown) targetException.getTargetException(); thrown.stacktrace.add(cf); sp = sp - arity; for(Frame f = cf; f != null; f = f.previousCallFrame) { int handler = f.function.getHandler(pc - 1, thrown.value.getType()); if(handler != -1) { if(f != cf) { cf = f; instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; } pc = handler; stack[sp++] = thrown; continue NEXT_INSTRUCTION; } } // If a handler has not been found in the caller functions... return thrown; } continue NEXT_INSTRUCTION; // Some specialized MuPrimitives case Opcode.OP_SUBSCRIPTARRAY: stack[sp - 2] = ((Object[]) stack[sp - 2])[((Integer) stack[sp - 1])]; sp--; continue NEXT_INSTRUCTION; case Opcode.OP_SUBSCRIPTLIST: stack[sp - 2] = ((IList) stack[sp - 2]).get((Integer) stack[sp - 1]); sp--; continue NEXT_INSTRUCTION; case Opcode.OP_LESSINT: stack[sp - 2] = ((Integer) stack[sp - 2]) < ((Integer) stack[sp - 1]); sp--; continue NEXT_INSTRUCTION; case Opcode.OP_GREATEREQUALINT: stack[sp - 2] = ((Integer) stack[sp - 2]) >= ((Integer) stack[sp - 1]); sp--; continue NEXT_INSTRUCTION; case Opcode.OP_ADDINT: stack[sp - 2] = ((Integer) stack[sp - 2]) + ((Integer) stack[sp - 1]); sp--; continue NEXT_INSTRUCTION; case Opcode.OP_SUBTRACTINT: stack[sp - 2] = ((Integer) stack[sp - 2]) - ((Integer) stack[sp - 1]); sp--; continue NEXT_INSTRUCTION; case Opcode.OP_ANDBOOL: boolean b1 = (stack[sp - 2] instanceof Boolean) ? ((Boolean) stack[sp - 2]) : ((IBool) stack[sp - 2]).getValue(); boolean b2 = (stack[sp - 1] instanceof Boolean) ? ((Boolean) stack[sp - 1]) : ((IBool) stack[sp - 1]).getValue(); stack[sp - 2] = b1 && b2; sp--; continue NEXT_INSTRUCTION; case Opcode.OP_TYPEOF: if(stack[sp - 1] instanceof HashSet<?>){ // For the benefit of set matching @SuppressWarnings("unchecked") HashSet<IValue> mset = (HashSet<IValue>) stack[sp - 1]; if(mset.isEmpty()){ stack[sp - 1] = tf.setType(tf.voidType()); } else { IValue v = mset.iterator().next(); stack[sp - 1] = tf.setType(v.getType()); } } else { stack[sp - 1] = ((IValue) stack[sp - 1]).getType(); } continue NEXT_INSTRUCTION; case Opcode.OP_SUBTYPE: stack[sp - 2] = ((Type) stack[sp - 2]).isSubtypeOf((Type) stack[sp - 1]); sp--; continue NEXT_INSTRUCTION; case Opcode.OP_CHECKARGTYPE: Type argType = ((IValue) stack[sp - 2]).getType(); Type paramType = ((Type) stack[sp - 1]); stack[sp - 2] = argType.isSubtypeOf(paramType); sp--; continue NEXT_INSTRUCTION; case Opcode.OP_LABEL: throw new RuntimeException("label instruction at runtime"); case Opcode.OP_HALT: if (debug) { stdout.println("Program halted:"); for (int i = 0; i < sp; i++) { stdout.println(i + ": " + stack[i]); } } return stack[sp - 1]; case Opcode.OP_PRINTLN: arity = CodeBlock.fetchArg1(instruction); StringBuilder w = new StringBuilder(); for(int i = arity - 1; i >= 0; i--){ String str = (stack[sp - 1 - i] instanceof IString) ? ((IString) stack[sp - 1 - i]).toString() : asString(stack[sp - 1 - i]); w.append(str).append(" "); } stdout.println(w.toString()); sp = sp - arity + 1; continue NEXT_INSTRUCTION; case Opcode.OP_THROW: Object obj = stack[--sp]; thrown = null; if(obj instanceof IValue) { stacktrace = new ArrayList<Frame>(); stacktrace.add(cf); thrown = Thrown.getInstance((IValue) obj, null, stacktrace); } else { // Then, an object of type 'Thrown' is on top of the stack thrown = (Thrown) obj; } // First, try to find a handler in the current frame function, // given the current instruction index and the value type, // then, if not found, look up the caller function(s) for(Frame f = cf; f != null; f = f.previousCallFrame) { - int handler = f.function.getHandler(pc - 1, thrown.value.getType()); + int handler = f.function.getHandler(f.pc - 1, thrown.value.getType()); if(handler != -1) { if(f != cf) { cf = f; instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; } pc = handler; stack[sp++] = thrown; continue NEXT_INSTRUCTION; } } // If a handler has not been found in the caller functions... return thrown; case Opcode.OP_LOADLOCKWP: IString name = (IString) cf.function.codeblock.getConstantValue(CodeBlock.fetchArg1(instruction)); @SuppressWarnings("unchecked") Map<String, Map.Entry<Type, IValue>> defaults = (Map<String, Map.Entry<Type, IValue>>) stack[cf.function.nformals]; Map.Entry<Type, IValue> defaultValue = defaults.get(name.getValue()); for(Frame f = cf; f != null; f = f.previousCallFrame) { IMap kargs = (IMap) f.stack[f.function.nformals - 1]; if(kargs.containsKey(name)) { val = kargs.get(name); if(val.getType().isSubtypeOf(defaultValue.getKey())) { stack[sp++] = val; continue NEXT_INSTRUCTION; } } } stack[sp++] = defaultValue.getValue(); continue NEXT_INSTRUCTION; case Opcode.OP_LOADVARKWP: continue NEXT_INSTRUCTION; case Opcode.OP_STORELOCKWP: val = (IValue) stack[sp - 1]; name = (IString) cf.function.codeblock.getConstantValue(CodeBlock.fetchArg1(instruction)); IMap kargs = (IMap) stack[cf.function.nformals - 1]; stack[cf.function.nformals - 1] = kargs.put(name, val); continue NEXT_INSTRUCTION; case Opcode.OP_STOREVARKWP: continue NEXT_INSTRUCTION; default: throw new RuntimeException("RVM main loop -- cannot decode instruction"); } switch(postOp){ case Opcode.POSTOP_CHECKUNDEF: // EXCEPTION HANDLING stacktrace = new ArrayList<Frame>(); stacktrace.add(cf); thrown = RuntimeExceptions.uninitializedVariable(pos, null, stacktrace); for(Frame f = cf; f != null; f = f.previousCallFrame) { int handler = f.function.getHandler(pc - 1, thrown.value.getType()); if(handler != -1) { if(f != cf) { cf = f; instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; } pc = handler; stack[sp++] = thrown; continue NEXT_INSTRUCTION; } } // If a handler has not been found in the caller functions... return thrown; } } } catch (Exception e) { e.printStackTrace(stderr); throw new RuntimeException("PANIC: (instruction execution): instruction: " + cf.function.codeblock.toString(pc - 1) + "; message: "+ e.getMessage() ); //stdout.println("PANIC: (instruction execution): " + e.getMessage()); //e.printStackTrace(); //stderr.println(e.getStackTrace()); } } int callJavaMethod(String methodName, String className, Type parameterTypes, int reflect, Object[] stack, int sp) throws Throw { Class<?> clazz = null; try { try { clazz = this.getClass().getClassLoader().loadClass(className); } catch(ClassNotFoundException e1) { // If the class is not found, try other class loaders for(ClassLoader loader : ctx.getEvaluator().getClassLoaders()) { try { clazz = loader.loadClass(className); break; } catch(ClassNotFoundException e2) { ; } } } if(clazz == null) { throw new RuntimeException("Class not found: " + className); } Constructor<?> cons; cons = clazz.getConstructor(IValueFactory.class); Object instance = cons.newInstance(vf); Method m = clazz.getMethod(methodName, makeJavaTypes(parameterTypes, reflect)); int nformals = parameterTypes.getArity(); Object[] parameters = new Object[nformals + reflect]; for(int i = 0; i < nformals; i++){ parameters[i] = stack[sp - nformals + i]; } if(reflect == 1) { parameters[nformals] = this.ctx; } stack[sp - nformals] = m.invoke(instance, parameters); return sp - nformals + 1; } // catch (ClassNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (NoSuchMethodException | SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { if(e.getTargetException() instanceof Throw) { throw (Throw) e.getTargetException(); } e.printStackTrace(); } return sp; } Class<?>[] makeJavaTypes(Type parameterTypes, int reflect){ JavaClasses javaClasses = new JavaClasses(); int arity = parameterTypes.getArity() + reflect; Class<?>[] jtypes = new Class<?>[arity]; for(int i = 0; i < parameterTypes.getArity(); i++){ jtypes[i] = parameterTypes.getFieldType(i).accept(javaClasses); } if(reflect == 1) { try { jtypes[arity - 1] = this.getClass().getClassLoader().loadClass("org.rascalmpl.interpreter.IEvaluatorContext"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } return jtypes; } private static class JavaClasses implements ITypeVisitor<Class<?>, RuntimeException> { @Override public Class<?> visitBool(org.eclipse.imp.pdb.facts.type.Type boolType) { return IBool.class; } @Override public Class<?> visitReal(org.eclipse.imp.pdb.facts.type.Type type) { return IReal.class; } @Override public Class<?> visitInteger(org.eclipse.imp.pdb.facts.type.Type type) { return IInteger.class; } @Override public Class<?> visitRational(org.eclipse.imp.pdb.facts.type.Type type) { return IRational.class; } @Override public Class<?> visitNumber(org.eclipse.imp.pdb.facts.type.Type type) { return INumber.class; } @Override public Class<?> visitList(org.eclipse.imp.pdb.facts.type.Type type) { return IList.class; } @Override public Class<?> visitMap(org.eclipse.imp.pdb.facts.type.Type type) { return IMap.class; } @Override public Class<?> visitAlias(org.eclipse.imp.pdb.facts.type.Type type) { return type.getAliased().accept(this); } @Override public Class<?> visitAbstractData(org.eclipse.imp.pdb.facts.type.Type type) { return IConstructor.class; } @Override public Class<?> visitSet(org.eclipse.imp.pdb.facts.type.Type type) { return ISet.class; } @Override public Class<?> visitSourceLocation(org.eclipse.imp.pdb.facts.type.Type type) { return ISourceLocation.class; } @Override public Class<?> visitString(org.eclipse.imp.pdb.facts.type.Type type) { return IString.class; } @Override public Class<?> visitNode(org.eclipse.imp.pdb.facts.type.Type type) { return INode.class; } @Override public Class<?> visitConstructor(org.eclipse.imp.pdb.facts.type.Type type) { return IConstructor.class; } @Override public Class<?> visitTuple(org.eclipse.imp.pdb.facts.type.Type type) { return ITuple.class; } @Override public Class<?> visitValue(org.eclipse.imp.pdb.facts.type.Type type) { return IValue.class; } @Override public Class<?> visitVoid(org.eclipse.imp.pdb.facts.type.Type type) { return null; } @Override public Class<?> visitParameter(org.eclipse.imp.pdb.facts.type.Type parameterType) { return parameterType.getBound().accept(this); } @Override public Class<?> visitExternal( org.eclipse.imp.pdb.facts.type.Type externalType) { return IValue.class; } @Override public Class<?> visitDateTime(Type type) { return IDateTime.class; } } }
true
true
private Object executeProgram(Frame root, Frame cf) { Object[] stack = cf.stack; // current stack int sp = cf.function.nlocals; // current stack pointer int [] instructions = cf.function.codeblock.getInstructions(); // current instruction sequence int pc = 0; // current program counter int postOp = 0; int pos = 0; ArrayList<Frame> stacktrace; Thrown thrown; int arity; String last_function_name = ""; // Overloading specific Stack<OverloadedFunctionInstanceCall> ocalls = new Stack<OverloadedFunctionInstanceCall>(); OverloadedFunctionInstanceCall c_ofun_call = null; try { NEXT_INSTRUCTION: while (true) { // if(pc < 0 || pc >= instructions.length){ // throw new RuntimeException(cf.function.name + " illegal pc: " + pc); // } int instruction = instructions[pc++]; int op = CodeBlock.fetchOp(instruction); if (debug) { int startpc = pc - 1; if(!last_function_name.equals(cf.function.name)) stdout.printf("[%03d] %s\n", startpc, cf.function.name); for (int i = 0; i < sp; i++) { stdout.println("\t " + (i < cf.function.nlocals ? "*" : " ") + i + ": " + asString(stack[i])); } stdout.printf("%5s %s\n" , "", cf.function.codeblock.toString(startpc)); } Opcode.use(instruction); switch (op) { case Opcode.OP_POP: sp--; continue NEXT_INSTRUCTION; case Opcode.OP_LOADLOC0: if(stack[0] != null){ stack[sp++] = stack[0]; continue NEXT_INSTRUCTION; } pos = 0; postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADLOC1: if(stack[1] != null){ stack[sp++] = stack[1]; continue NEXT_INSTRUCTION; } pos = 1; postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADLOC2: if(stack[2] != null){ stack[sp++] = stack[2]; continue NEXT_INSTRUCTION; } pos = 2; postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADLOC3: if(stack[3] != null){ stack[sp++] = stack[3]; continue NEXT_INSTRUCTION; } pos = 3; postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADLOC4: if(stack[4] != null){ stack[sp++] = stack[4]; continue NEXT_INSTRUCTION; } pos = 4; postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADLOC5: if(stack[5] != null){ stack[sp++] = stack[5]; continue NEXT_INSTRUCTION; } pos = 5; postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADLOC6: if(stack[6] != null){ stack[sp++] = stack[6]; continue NEXT_INSTRUCTION; } pos = 6; postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADLOC7: if(stack[7] != null){ stack[sp++] = stack[7]; continue NEXT_INSTRUCTION; } pos = 7; postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADLOC8: if(stack[8] != null){ stack[sp++] = stack[8]; continue NEXT_INSTRUCTION; } pos = 8; postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADLOC9: if(stack[9] != null){ stack[sp++] = stack[9]; continue NEXT_INSTRUCTION; } pos = 9; postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADLOC: pos = CodeBlock.fetchArg1(instruction); Object rval = stack[pos]; if(rval != null){ stack[sp++] = rval; continue NEXT_INSTRUCTION; } postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADBOOL: stack[sp++] = CodeBlock.fetchArg1(instruction) == 1 ? true : false; continue NEXT_INSTRUCTION; case Opcode.OP_LOADINT: stack[sp++] = CodeBlock.fetchArg1(instruction); continue NEXT_INSTRUCTION; case Opcode.OP_LOADCON: stack[sp++] = cf.function.constantStore[CodeBlock.fetchArg1(instruction)]; continue NEXT_INSTRUCTION; case Opcode.OP_LOADLOCREF: stack[sp++] = new Reference(stack, CodeBlock.fetchArg1(instruction)); continue NEXT_INSTRUCTION; case Opcode.OP_CALLMUPRIM: MuPrimitive muprim = MuPrimitive.fromInteger(CodeBlock.fetchArg1(instruction)); sp = muprim.invoke(stack, sp, CodeBlock.fetchArg2(instruction)); continue NEXT_INSTRUCTION; case Opcode.OP_JMP: pc = CodeBlock.fetchArg1(instruction); continue NEXT_INSTRUCTION; case Opcode.OP_JMPTRUE: if (stack[sp - 1].equals(TRUE) || stack[sp - 1].equals(Rascal_TRUE)) { pc = CodeBlock.fetchArg1(instruction); } sp--; continue NEXT_INSTRUCTION; case Opcode.OP_JMPFALSE: if (stack[sp - 1].equals(FALSE) || stack[sp - 1].equals(Rascal_FALSE)) { pc = CodeBlock.fetchArg1(instruction); } sp--; continue NEXT_INSTRUCTION; case Opcode.OP_TYPESWITCH: IValue val = (IValue) stack[--sp]; Type t = null; if(val instanceof IConstructor) { t = ((IConstructor) val).getConstructorType(); } else { t = val.getType(); } int labelIndex = ToplevelType.getToplevelTypeAsInt(t); IList labels = (IList) cf.function.constantStore[CodeBlock.fetchArg1(instruction)]; pc = ((IInteger) labels.get(labelIndex)).intValue(); continue NEXT_INSTRUCTION; case Opcode.OP_JMPINDEXED: labelIndex = ((IInteger) stack[--sp]).intValue(); labels = (IList) cf.function.constantStore[CodeBlock.fetchArg1(instruction)]; pc = ((IInteger) labels.get(labelIndex)).intValue(); continue NEXT_INSTRUCTION; case Opcode.OP_LOADTYPE: stack[sp++] = cf.function.typeConstantStore[CodeBlock.fetchArg1(instruction)]; continue NEXT_INSTRUCTION; case Opcode.OP_LOADLOCDEREF: { Reference ref = (Reference) stack[CodeBlock.fetchArg1(instruction)]; stack[sp++] = ref.stack[ref.pos]; continue NEXT_INSTRUCTION; } case Opcode.OP_STORELOC: { stack[CodeBlock.fetchArg1(instruction)] = stack[sp - 1]; continue NEXT_INSTRUCTION; } case Opcode.OP_UNWRAPTHROWN: { stack[CodeBlock.fetchArg1(instruction)] = ((Thrown) stack[--sp]).value; continue NEXT_INSTRUCTION; } case Opcode.OP_STORELOCDEREF: Reference ref = (Reference) stack[CodeBlock.fetchArg1(instruction)]; ref.stack[ref.pos] = stack[sp - 1]; // TODO: We need to re-consider how to guarantee safe use of both Java objects and IValues continue NEXT_INSTRUCTION; case Opcode.OP_LOADFUN: // Loads functions that are defined at the root stack[sp++] = new FunctionInstance(functionStore.get(CodeBlock.fetchArg1(instruction)), root); continue NEXT_INSTRUCTION; case Opcode.OP_LOAD_NESTED_FUN: { // Loads nested functions and closures (anonymous nested functions): // First, get the function code Function fun = functionStore.get(CodeBlock.fetchArg1(instruction)); int scopeIn = CodeBlock.fetchArg2(instruction); // Second, look up the function environment frame into the stack of caller frames for(Frame env = cf; env != null; env = env.previousCallFrame) { if (env.scopeId == scopeIn) { stack[sp++] = new FunctionInstance(fun, env); continue NEXT_INSTRUCTION; } } throw new RuntimeException("LOAD_NESTED_FUN cannot find matching scope: " + scopeIn); } case Opcode.OP_LOADOFUN: OverloadedFunction of = overloadedStore.get(CodeBlock.fetchArg1(instruction)); if(of.scopeIn == -1) { stack[sp++] = new OverloadedFunctionInstance(of.functions, of.constructors, root); continue NEXT_INSTRUCTION; } for(Frame env = cf; env != null; env = env.previousCallFrame) { if (env.scopeId == of.scopeIn) { stack[sp++] = new OverloadedFunctionInstance(of.functions, of.constructors, env); continue NEXT_INSTRUCTION; } } throw new RuntimeException("Could not find matching scope when loading a nested overloaded function: " + of.scopeIn); case Opcode.OP_LOADCONSTR: Type constructor = constructorStore.get(CodeBlock.fetchArg1(instruction)); stack[sp++] = constructor; continue NEXT_INSTRUCTION; case Opcode.OP_LOADVAR: case Opcode.OP_LOADVARREF: { int s = CodeBlock.fetchArg1(instruction); pos = CodeBlock.fetchArg2(instruction); if(CodeBlock.isMaxArg2(pos)){ rval = moduleVariables.get(cf.function.constantStore[s]); if(op == Opcode.OP_LOADVAR && rval == null) { // EXCEPTION HANDLING stacktrace = new ArrayList<Frame>(); stacktrace.add(cf); thrown = RuntimeExceptions.uninitializedVariable(pos, null, stacktrace); for(Frame f = cf; f != null; f = f.previousCallFrame) { int handler = f.function.getHandler(pc - 1, thrown.value.getType()); if(handler != -1) { if(f != cf) { cf = f; instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; } pc = handler; stack[sp++] = thrown; continue NEXT_INSTRUCTION; } } // If a handler has not been found in the caller functions... return thrown; } stack[sp++] = rval; continue NEXT_INSTRUCTION; } for (Frame fr = cf; fr != null; fr = fr.previousScope) { if (fr.scopeId == s) { rval = (op == Opcode.OP_LOADVAR) ? fr.stack[pos] : new Reference(fr.stack, pos); if(op == Opcode.OP_LOADLOC && rval == null) { // EXCEPTION HANDLING stacktrace = new ArrayList<Frame>(); stacktrace.add(cf); thrown = RuntimeExceptions.uninitializedVariable(pos, null, stacktrace); for(Frame f = cf; f != null; f = f.previousCallFrame) { int handler = f.function.getHandler(pc - 1, thrown.value.getType()); if(handler != -1) { if(f != cf) { cf = f; instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; } pc = handler; stack[sp++] = thrown; continue NEXT_INSTRUCTION; } } // If a handler has not been found in the caller functions... return thrown; } stack[sp++] = rval; continue NEXT_INSTRUCTION; } } throw new RuntimeException("LOADVAR or LOADVARREF cannot find matching scope: " + s); } case Opcode.OP_LOADVARDEREF: { int s = CodeBlock.fetchArg1(instruction); pos = CodeBlock.fetchArg2(instruction); for (Frame fr = cf; fr != null; fr = fr.previousScope) { if (fr.scopeId == s) { ref = (Reference) fr.stack[pos]; stack[sp++] = ref.stack[ref.pos]; continue NEXT_INSTRUCTION; } } throw new RuntimeException("LOADVARDEREF cannot find matching scope: " + s); } case Opcode.OP_STOREVAR: int s = CodeBlock.fetchArg1(instruction); pos = CodeBlock.fetchArg2(instruction); if(CodeBlock.isMaxArg2(pos)){ IValue mvar = cf.function.constantStore[s]; moduleVariables.put(mvar, (IValue)stack[sp -1]); continue NEXT_INSTRUCTION; } for (Frame fr = cf; fr != null; fr = fr.previousScope) { if (fr.scopeId == s) { fr.stack[pos] = stack[sp - 1]; // TODO: We need to re-consider how to guarantee safe use of both Java objects and IValues continue NEXT_INSTRUCTION; } } throw new RuntimeException("STOREVAR cannot find matching scope: " + s); case Opcode.OP_STOREVARDEREF: s = CodeBlock.fetchArg1(instruction); pos = CodeBlock.fetchArg2(instruction); for (Frame fr = cf; fr != null; fr = fr.previousScope) { if (fr.scopeId == s) { ref = (Reference) fr.stack[pos]; ref.stack[ref.pos] = stack[sp - 1]; continue NEXT_INSTRUCTION; } } throw new RuntimeException("STOREVARDEREF cannot find matching scope: " + s); case Opcode.OP_CALLCONSTR: constructor = constructorStore.get(CodeBlock.fetchArg1(instruction)); arity = CodeBlock.fetchArg2(instruction); assert arity == constructor.getArity(); IValue[] args = new IValue[arity]; for(int i = 0; i < arity; i++) { args[arity - 1 - i] = (IValue) stack[--sp]; } stack[sp++] = vf.constructor(constructor, args); continue NEXT_INSTRUCTION; case Opcode.OP_CALLDYN: case Opcode.OP_CALL: // In case of CALLDYN, the stack top value of type 'Type' leads to a constructor call if(op == Opcode.OP_CALLDYN && stack[sp - 1] instanceof Type) { Type constr = (Type) stack[--sp]; arity = constr.getArity(); args = new IValue[arity]; for(int i = arity - 1; i >=0; i--) { args[i] = (IValue) stack[sp - arity + i]; } sp = sp - arity; stack[sp++] = vf.constructor(constr, args); continue NEXT_INSTRUCTION; } Function fun = null; Frame previousScope = null; if(op == Opcode.OP_CALLDYN && stack[sp - 1] instanceof FunctionInstance){ FunctionInstance fun_instance = (FunctionInstance) stack[--sp]; arity = CodeBlock.fetchArg1(instruction); // TODO: add assert fun = fun_instance.function; previousScope = fun_instance.env; } else if(op == Opcode.OP_CALL) { fun = functionStore.get(CodeBlock.fetchArg1(instruction)); arity = CodeBlock.fetchArg2(instruction); assert arity == fun.nformals; previousScope = cf; } else { throw new RuntimeException("unexpected argument type for CALLDYN: " + asString(stack[sp - 1])); } instructions = fun.codeblock.getInstructions(); Frame nextFrame = new Frame(fun.scopeId, cf, previousScope, fun.maxstack, fun); for (int i = fun.nformals - 1; i >= 0; i--) { nextFrame.stack[i] = stack[sp - fun.nformals + i]; } cf.pc = pc; cf.sp = sp - fun.nformals; cf = nextFrame; stack = cf.stack; sp = fun.nlocals; pc = 0; continue NEXT_INSTRUCTION; case Opcode.OP_OCALLDYN: // Get function types to perform a type-based dynamic resolution Type types = cf.function.codeblock.getConstantType(CodeBlock.fetchArg1(instruction)); arity = CodeBlock.fetchArg2(instruction); // Objects of three types may appear on the stack: // 1. FunctionInstance due to closures // 2. OverloadedFunctionInstance due to named Rascal functions Object funcObject = stack[--sp]; // Get function arguments from the stack args = new IValue[arity]; for(int i = arity - 1; i >= 0; i--) { args[i] = (IValue) stack[sp - arity + i]; } sp = sp - arity; if(funcObject instanceof FunctionInstance) { FunctionInstance fun_instance = (FunctionInstance) funcObject; cf.sp = sp; cf.pc = pc; cf = pushArguments(cf, fun_instance.function, fun_instance.env, args); instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; continue NEXT_INSTRUCTION; } OverloadedFunctionInstance of_instance = (OverloadedFunctionInstance) funcObject; if(debug) { this.appendToTrace("OVERLOADED FUNCTION CALLDYN: "); this.appendToTrace(" with alternatives:"); for(int index : of_instance.functions) { this.appendToTrace(" " + getFunctionName(index)); } } c_ofun_call = new OverloadedFunctionInstanceCall(vf, cf, of_instance.functions, of_instance.constructors, of_instance.env, args, types); ocalls.push(c_ofun_call); fun = c_ofun_call.nextFunction(functionStore); if(fun != null) { if(debug) { this.appendToTrace(" " + "try alternative: " + fun.name); } cf.sp = sp; cf.pc = pc; cf = pushArguments(c_ofun_call.cf, fun, c_ofun_call.env, c_ofun_call.args); instructions = fun.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = 0; } else { stack[sp++] = vf.constructor(c_ofun_call.nextConstructor(constructorStore), c_ofun_call.constr_args); } continue NEXT_INSTRUCTION; case Opcode.OP_OCALL: of = overloadedStore.get(CodeBlock.fetchArg1(instruction)); arity = CodeBlock.fetchArg2(instruction); if(debug) { this.appendToTrace("OVERLOADED FUNCTION CALL: " + getOverloadedFunctionName(CodeBlock.fetchArg1(instruction))); this.appendToTrace(" with alternatives:"); for(int index : of.functions) { this.appendToTrace(" " + getFunctionName(index)); } } // Get arguments from the stack args = new IValue[arity]; for(int i = arity - 1; i >= 0; i--) { args[i] = (IValue) stack[sp - arity + i]; } sp = sp - arity; c_ofun_call = new OverloadedFunctionInstanceCall(vf, root, cf, of.functions, of.constructors, of.scopeIn, args, null); ocalls.push(c_ofun_call); fun = c_ofun_call.nextFunction(functionStore); if(fun != null) { if(debug) { this.appendToTrace(" " + "try alternative: " + fun.name); } cf.sp = sp; cf.pc = pc; cf = pushArguments(c_ofun_call.cf, fun, c_ofun_call.env, c_ofun_call.args); instructions = fun.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = 0; } else { stack[sp++] = vf.constructor(c_ofun_call.nextConstructor(constructorStore), c_ofun_call.constr_args); } continue NEXT_INSTRUCTION; case Opcode.OP_FAILRETURN: assert cf.previousCallFrame == c_ofun_call.cf; fun = c_ofun_call.nextFunction(functionStore); if(fun != null) { if(debug) { this.appendToTrace(" " + "try alternative: " + fun.name); } cf.sp = sp; cf.pc = pc; cf = pushArguments(c_ofun_call.cf, fun, c_ofun_call.env, c_ofun_call.args); instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; } else { cf = c_ofun_call.cf; instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; stack[sp++] = vf.constructor(c_ofun_call.nextConstructor(constructorStore), c_ofun_call.constr_args); } continue NEXT_INSTRUCTION; case Opcode.OP_FILTERRETURN: case Opcode.OP_RETURN0: case Opcode.OP_RETURN1: // Overloading specific if(c_ofun_call != null && cf.previousCallFrame == c_ofun_call.cf) { ocalls.pop(); c_ofun_call = ocalls.isEmpty() ? null : ocalls.peek(); } rval = null; boolean returns = cf.isCoroutine || op == Opcode.OP_RETURN1 || op == Opcode.OP_FILTERRETURN; if(op == Opcode.OP_RETURN1 || cf.isCoroutine) { if(cf.isCoroutine) { rval = Rascal_TRUE; if(op == Opcode.OP_RETURN1) { arity = CodeBlock.fetchArg1(instruction); int[] refs = cf.function.refs; if(arity != refs.length) { throw new RuntimeException("Coroutine " + cf.function.name + ": arity of return (" + arity + ") unequal to number of reference parameters (" + refs.length + ")"); } for(int i = 0; i < arity; i++) { ref = (Reference) stack[refs[arity - 1 - i]]; ref.stack[ref.pos] = stack[--sp]; } } } else { rval = stack[sp - 1]; } } // if the current frame is the frame of a top active coroutine, // then pop this coroutine from the stack of active coroutines if(cf == ccf) { activeCoroutines.pop(); ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start; } cf = cf.previousCallFrame; if(cf == null) { if(returns) { return rval; } else { return NONE; } } instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; if(returns) { stack[sp++] = rval; } continue NEXT_INSTRUCTION; case Opcode.OP_CALLJAVA: String methodName = ((IString) cf.function.constantStore[instructions[pc++]]).getValue(); String className = ((IString) cf.function.constantStore[instructions[pc++]]).getValue(); Type parameterTypes = cf.function.typeConstantStore[instructions[pc++]]; int reflect = instructions[pc++]; arity = parameterTypes.getArity(); try { sp = callJavaMethod(methodName, className, parameterTypes, reflect, stack, sp); } catch(Throw e) { thrown = Thrown.getInstance(e.getException(), e.getLocation(), new ArrayList<Frame>()); // EXCEPTION HANDLING for(Frame f = cf; f != null; f = f.previousCallFrame) { int handler = f.function.getHandler(pc - 1, thrown.value.getType()); if(handler != -1) { if(f != cf) { cf = f; instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; } pc = handler; stack[sp++] = thrown; continue NEXT_INSTRUCTION; } } // If a handler has not been found in the caller functions... return thrown; } continue NEXT_INSTRUCTION; case Opcode.OP_INIT: arity = CodeBlock.fetchArg1(instruction); Object src = stack[--sp]; Coroutine coroutine; if(src instanceof Coroutine){ coroutine = (Coroutine) src; fun = coroutine.frame.function; } else if(src instanceof FunctionInstance) { FunctionInstance fun_instance = (FunctionInstance) src; fun = fun_instance.function; Frame frame = new Frame(fun.scopeId, null, fun_instance.env, fun.maxstack, fun); coroutine = new Coroutine(frame); } else { throw new RuntimeException("Unexpected argument type for INIT: " + src.getClass() + ", " + src); } if(coroutine.isInitialized()) { throw new RuntimeException("Trying to initialize a coroutine, which has already been initialized: " + fun.getName() + " (corounine's main), called in " + cf.function.getName()); } // the main function of coroutine may have formal parameters, // therefore, INIT may take a number of arguments == formal parameters - arguments already passed to CREATE if(arity != fun.nformals - coroutine.frame.sp) { throw new RuntimeException("Too many or too few arguments to INIT, the expected number: " + (fun.nformals - coroutine.frame.sp) + "; coroutine's main: " + fun.getName() + ", called in " + cf.function.getName()); } Coroutine newCoroutine = coroutine.copy(); for (int i = arity - 1; i >= 0; i--) { newCoroutine.frame.stack[coroutine.frame.sp + i] = stack[sp - arity + i]; } newCoroutine.frame.sp = fun.nlocals; sp = sp - arity; /* Place coroutine back on stack */ stack[sp++] = newCoroutine; // Now, instead of simply suspending a coroutine during INIT, let it execute until GUARD, which has been delegated the INIT's suspension newCoroutine.suspend(newCoroutine.frame); // put the coroutine onto the stack of active coroutines activeCoroutines.push(newCoroutine); ccf = newCoroutine.start; newCoroutine.next(cf); fun = newCoroutine.frame.function; instructions = newCoroutine.frame.function.codeblock.getInstructions(); cf.pc = pc; cf.sp = sp; cf = newCoroutine.frame; stack = cf.stack; sp = cf.sp; pc = cf.pc; continue NEXT_INSTRUCTION; case Opcode.OP_GUARD: rval = stack[sp - 1]; boolean precondition; if(rval instanceof IBool) { precondition = ((IBool) rval).getValue(); } else if(rval instanceof Boolean) { precondition = (Boolean) rval; } else { throw new RuntimeException("Guard's expression has to be boolean!"); } if(cf == ccf) { coroutine = activeCoroutines.pop(); ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start; Frame prev = cf.previousCallFrame; if(precondition) { coroutine.suspend(cf); } --sp; cf.pc = pc; cf.sp = sp; cf = prev; instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; continue NEXT_INSTRUCTION; } if(!precondition) { cf.pc = pc; cf.sp = sp; cf = cf.previousCallFrame; instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; stack[sp++] = Rascal_FALSE; continue NEXT_INSTRUCTION; } continue NEXT_INSTRUCTION; case Opcode.OP_CREATE: case Opcode.OP_CREATEDYN: if(op == Opcode.OP_CREATE){ fun = functionStore.get(CodeBlock.fetchArg1(instruction)); arity = CodeBlock.fetchArg2(instruction); previousScope = null; } else { arity = CodeBlock.fetchArg1(instruction); src = stack[--sp]; if(src instanceof FunctionInstance) { FunctionInstance fun_instance = (FunctionInstance) src; fun = fun_instance.function; previousScope = fun_instance.env; } else { throw new RuntimeException("unexpected argument type for CREATEDYN: " + asString(src)); } } Frame frame = new Frame(fun.scopeId, null, previousScope, fun.maxstack, fun); // the main function of coroutine may have formal parameters, // therefore, CREATE may take a number of arguments <= formal parameters if(arity > fun.nformals) throw new RuntimeException("Too many arguments to CREATE or CREATEDYN, expected <= " + fun.nformals); for (int i = arity - 1; i >= 0; i--) { frame.stack[i] = stack[sp - arity + i]; } frame.sp = arity; coroutine = new Coroutine(frame); sp = sp - arity; stack[sp++] = coroutine; continue NEXT_INSTRUCTION; case Opcode.OP_NEXT0: case Opcode.OP_NEXT1: coroutine = (Coroutine) stack[--sp]; // Merged the hasNext and next semantics if(!coroutine.hasNext()) { if(op == Opcode.OP_NEXT1) { --sp; } stack[sp++] = FALSE; continue NEXT_INSTRUCTION; } // put the coroutine onto the stack of active coroutines activeCoroutines.push(coroutine); ccf = coroutine.start; coroutine.next(cf); fun = coroutine.frame.function; instructions = coroutine.frame.function.codeblock.getInstructions(); coroutine.frame.stack[coroutine.frame.sp++] = // Always leave an entry on the stack (op == Opcode.OP_NEXT1) ? stack[--sp] : null; cf.pc = pc; cf.sp = sp; cf = coroutine.frame; stack = cf.stack; sp = cf.sp; pc = cf.pc; continue NEXT_INSTRUCTION; case Opcode.OP_YIELD0: case Opcode.OP_YIELD1: coroutine = activeCoroutines.pop(); ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start; Frame prev = coroutine.start.previousCallFrame; rval = Rascal_TRUE; // In fact, yield has to always return TRUE if(op == Opcode.OP_YIELD1) { arity = CodeBlock.fetchArg1(instruction); int[] refs = coroutine.start.function.refs; // Takes the reference parameter positions of the top active coroutine instance if(cf != coroutine.start && cf.function.refs.length != refs.length) { throw new RuntimeException("The 'yield' from within a nested call has to take the same number of arguments as the number of the caller's reference parameters: " + cf.function.refs.length + "; " + refs.length); } if(arity != refs.length) { throw new RuntimeException("The 'yield' within a coroutine has to take the same number of arguments as the number of its reference parameters; arity: " + arity + "; reference parameter number: " + refs.length); } for(int i = 0; i < arity; i++) { ref = (Reference) coroutine.start.stack[refs[arity - 1 - i]]; // Takes the reference parameters of the top active coroutine instance ref.stack[ref.pos] = stack[--sp]; } } cf.pc = pc; cf.sp = sp; coroutine.suspend(cf); cf = prev; if(op == Opcode.OP_YIELD1 && cf == null) return rval; instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; stack[sp++] = rval; // Corresponding next will always find an entry on the stack continue NEXT_INSTRUCTION; case Opcode.OP_EXHAUST: if(cf == ccf) { activeCoroutines.pop(); ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start; } cf = cf.previousCallFrame; if(cf == null) { return Rascal_FALSE; // 'Exhaust' has to always return FALSE, i.e., signal a failure; } instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; stack[sp++] = Rascal_FALSE; // 'Exhaust' has to always return FALSE, i.e., signal a failure; continue NEXT_INSTRUCTION; case Opcode.OP_HASNEXT: coroutine = (Coroutine) stack[--sp]; stack[sp++] = coroutine.hasNext() ? TRUE : FALSE; continue NEXT_INSTRUCTION; case Opcode.OP_CALLPRIM: RascalPrimitive prim = RascalPrimitive.fromInteger(CodeBlock.fetchArg1(instruction)); arity = CodeBlock.fetchArg2(instruction); try { sp = prim.invoke(stack, sp, arity); } catch(InvocationTargetException targetException) { if(!(targetException.getTargetException() instanceof Thrown)) { throw targetException; } // EXCEPTION HANDLING thrown = (Thrown) targetException.getTargetException(); thrown.stacktrace.add(cf); sp = sp - arity; for(Frame f = cf; f != null; f = f.previousCallFrame) { int handler = f.function.getHandler(pc - 1, thrown.value.getType()); if(handler != -1) { if(f != cf) { cf = f; instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; } pc = handler; stack[sp++] = thrown; continue NEXT_INSTRUCTION; } } // If a handler has not been found in the caller functions... return thrown; } continue NEXT_INSTRUCTION; // Some specialized MuPrimitives case Opcode.OP_SUBSCRIPTARRAY: stack[sp - 2] = ((Object[]) stack[sp - 2])[((Integer) stack[sp - 1])]; sp--; continue NEXT_INSTRUCTION; case Opcode.OP_SUBSCRIPTLIST: stack[sp - 2] = ((IList) stack[sp - 2]).get((Integer) stack[sp - 1]); sp--; continue NEXT_INSTRUCTION; case Opcode.OP_LESSINT: stack[sp - 2] = ((Integer) stack[sp - 2]) < ((Integer) stack[sp - 1]); sp--; continue NEXT_INSTRUCTION; case Opcode.OP_GREATEREQUALINT: stack[sp - 2] = ((Integer) stack[sp - 2]) >= ((Integer) stack[sp - 1]); sp--; continue NEXT_INSTRUCTION; case Opcode.OP_ADDINT: stack[sp - 2] = ((Integer) stack[sp - 2]) + ((Integer) stack[sp - 1]); sp--; continue NEXT_INSTRUCTION; case Opcode.OP_SUBTRACTINT: stack[sp - 2] = ((Integer) stack[sp - 2]) - ((Integer) stack[sp - 1]); sp--; continue NEXT_INSTRUCTION; case Opcode.OP_ANDBOOL: boolean b1 = (stack[sp - 2] instanceof Boolean) ? ((Boolean) stack[sp - 2]) : ((IBool) stack[sp - 2]).getValue(); boolean b2 = (stack[sp - 1] instanceof Boolean) ? ((Boolean) stack[sp - 1]) : ((IBool) stack[sp - 1]).getValue(); stack[sp - 2] = b1 && b2; sp--; continue NEXT_INSTRUCTION; case Opcode.OP_TYPEOF: if(stack[sp - 1] instanceof HashSet<?>){ // For the benefit of set matching @SuppressWarnings("unchecked") HashSet<IValue> mset = (HashSet<IValue>) stack[sp - 1]; if(mset.isEmpty()){ stack[sp - 1] = tf.setType(tf.voidType()); } else { IValue v = mset.iterator().next(); stack[sp - 1] = tf.setType(v.getType()); } } else { stack[sp - 1] = ((IValue) stack[sp - 1]).getType(); } continue NEXT_INSTRUCTION; case Opcode.OP_SUBTYPE: stack[sp - 2] = ((Type) stack[sp - 2]).isSubtypeOf((Type) stack[sp - 1]); sp--; continue NEXT_INSTRUCTION; case Opcode.OP_CHECKARGTYPE: Type argType = ((IValue) stack[sp - 2]).getType(); Type paramType = ((Type) stack[sp - 1]); stack[sp - 2] = argType.isSubtypeOf(paramType); sp--; continue NEXT_INSTRUCTION; case Opcode.OP_LABEL: throw new RuntimeException("label instruction at runtime"); case Opcode.OP_HALT: if (debug) { stdout.println("Program halted:"); for (int i = 0; i < sp; i++) { stdout.println(i + ": " + stack[i]); } } return stack[sp - 1]; case Opcode.OP_PRINTLN: arity = CodeBlock.fetchArg1(instruction); StringBuilder w = new StringBuilder(); for(int i = arity - 1; i >= 0; i--){ String str = (stack[sp - 1 - i] instanceof IString) ? ((IString) stack[sp - 1 - i]).toString() : asString(stack[sp - 1 - i]); w.append(str).append(" "); } stdout.println(w.toString()); sp = sp - arity + 1; continue NEXT_INSTRUCTION; case Opcode.OP_THROW: Object obj = stack[--sp]; thrown = null; if(obj instanceof IValue) { stacktrace = new ArrayList<Frame>(); stacktrace.add(cf); thrown = Thrown.getInstance((IValue) obj, null, stacktrace); } else { // Then, an object of type 'Thrown' is on top of the stack thrown = (Thrown) obj; } // First, try to find a handler in the current frame function, // given the current instruction index and the value type, // then, if not found, look up the caller function(s) for(Frame f = cf; f != null; f = f.previousCallFrame) { int handler = f.function.getHandler(pc - 1, thrown.value.getType()); if(handler != -1) { if(f != cf) { cf = f; instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; } pc = handler; stack[sp++] = thrown; continue NEXT_INSTRUCTION; } } // If a handler has not been found in the caller functions... return thrown; case Opcode.OP_LOADLOCKWP: IString name = (IString) cf.function.codeblock.getConstantValue(CodeBlock.fetchArg1(instruction)); @SuppressWarnings("unchecked") Map<String, Map.Entry<Type, IValue>> defaults = (Map<String, Map.Entry<Type, IValue>>) stack[cf.function.nformals]; Map.Entry<Type, IValue> defaultValue = defaults.get(name.getValue()); for(Frame f = cf; f != null; f = f.previousCallFrame) { IMap kargs = (IMap) f.stack[f.function.nformals - 1]; if(kargs.containsKey(name)) { val = kargs.get(name); if(val.getType().isSubtypeOf(defaultValue.getKey())) { stack[sp++] = val; continue NEXT_INSTRUCTION; } } } stack[sp++] = defaultValue.getValue(); continue NEXT_INSTRUCTION; case Opcode.OP_LOADVARKWP: continue NEXT_INSTRUCTION; case Opcode.OP_STORELOCKWP: val = (IValue) stack[sp - 1]; name = (IString) cf.function.codeblock.getConstantValue(CodeBlock.fetchArg1(instruction)); IMap kargs = (IMap) stack[cf.function.nformals - 1]; stack[cf.function.nformals - 1] = kargs.put(name, val); continue NEXT_INSTRUCTION; case Opcode.OP_STOREVARKWP: continue NEXT_INSTRUCTION; default: throw new RuntimeException("RVM main loop -- cannot decode instruction"); } switch(postOp){ case Opcode.POSTOP_CHECKUNDEF: // EXCEPTION HANDLING stacktrace = new ArrayList<Frame>(); stacktrace.add(cf); thrown = RuntimeExceptions.uninitializedVariable(pos, null, stacktrace); for(Frame f = cf; f != null; f = f.previousCallFrame) { int handler = f.function.getHandler(pc - 1, thrown.value.getType()); if(handler != -1) { if(f != cf) { cf = f; instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; } pc = handler; stack[sp++] = thrown; continue NEXT_INSTRUCTION; } } // If a handler has not been found in the caller functions... return thrown; } } } catch (Exception e) { e.printStackTrace(stderr); throw new RuntimeException("PANIC: (instruction execution): instruction: " + cf.function.codeblock.toString(pc - 1) + "; message: "+ e.getMessage() ); //stdout.println("PANIC: (instruction execution): " + e.getMessage()); //e.printStackTrace(); //stderr.println(e.getStackTrace()); } }
private Object executeProgram(Frame root, Frame cf) { Object[] stack = cf.stack; // current stack int sp = cf.function.nlocals; // current stack pointer int [] instructions = cf.function.codeblock.getInstructions(); // current instruction sequence int pc = 0; // current program counter int postOp = 0; int pos = 0; ArrayList<Frame> stacktrace; Thrown thrown; int arity; String last_function_name = ""; // Overloading specific Stack<OverloadedFunctionInstanceCall> ocalls = new Stack<OverloadedFunctionInstanceCall>(); OverloadedFunctionInstanceCall c_ofun_call = null; try { NEXT_INSTRUCTION: while (true) { // if(pc < 0 || pc >= instructions.length){ // throw new RuntimeException(cf.function.name + " illegal pc: " + pc); // } int instruction = instructions[pc++]; int op = CodeBlock.fetchOp(instruction); if (debug) { int startpc = pc - 1; if(!last_function_name.equals(cf.function.name)) stdout.printf("[%03d] %s\n", startpc, cf.function.name); for (int i = 0; i < sp; i++) { stdout.println("\t " + (i < cf.function.nlocals ? "*" : " ") + i + ": " + asString(stack[i])); } stdout.printf("%5s %s\n" , "", cf.function.codeblock.toString(startpc)); } Opcode.use(instruction); switch (op) { case Opcode.OP_POP: sp--; continue NEXT_INSTRUCTION; case Opcode.OP_LOADLOC0: if(stack[0] != null){ stack[sp++] = stack[0]; continue NEXT_INSTRUCTION; } pos = 0; postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADLOC1: if(stack[1] != null){ stack[sp++] = stack[1]; continue NEXT_INSTRUCTION; } pos = 1; postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADLOC2: if(stack[2] != null){ stack[sp++] = stack[2]; continue NEXT_INSTRUCTION; } pos = 2; postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADLOC3: if(stack[3] != null){ stack[sp++] = stack[3]; continue NEXT_INSTRUCTION; } pos = 3; postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADLOC4: if(stack[4] != null){ stack[sp++] = stack[4]; continue NEXT_INSTRUCTION; } pos = 4; postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADLOC5: if(stack[5] != null){ stack[sp++] = stack[5]; continue NEXT_INSTRUCTION; } pos = 5; postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADLOC6: if(stack[6] != null){ stack[sp++] = stack[6]; continue NEXT_INSTRUCTION; } pos = 6; postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADLOC7: if(stack[7] != null){ stack[sp++] = stack[7]; continue NEXT_INSTRUCTION; } pos = 7; postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADLOC8: if(stack[8] != null){ stack[sp++] = stack[8]; continue NEXT_INSTRUCTION; } pos = 8; postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADLOC9: if(stack[9] != null){ stack[sp++] = stack[9]; continue NEXT_INSTRUCTION; } pos = 9; postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADLOC: pos = CodeBlock.fetchArg1(instruction); Object rval = stack[pos]; if(rval != null){ stack[sp++] = rval; continue NEXT_INSTRUCTION; } postOp = Opcode.POSTOP_CHECKUNDEF; break; case Opcode.OP_LOADBOOL: stack[sp++] = CodeBlock.fetchArg1(instruction) == 1 ? true : false; continue NEXT_INSTRUCTION; case Opcode.OP_LOADINT: stack[sp++] = CodeBlock.fetchArg1(instruction); continue NEXT_INSTRUCTION; case Opcode.OP_LOADCON: stack[sp++] = cf.function.constantStore[CodeBlock.fetchArg1(instruction)]; continue NEXT_INSTRUCTION; case Opcode.OP_LOADLOCREF: stack[sp++] = new Reference(stack, CodeBlock.fetchArg1(instruction)); continue NEXT_INSTRUCTION; case Opcode.OP_CALLMUPRIM: MuPrimitive muprim = MuPrimitive.fromInteger(CodeBlock.fetchArg1(instruction)); sp = muprim.invoke(stack, sp, CodeBlock.fetchArg2(instruction)); continue NEXT_INSTRUCTION; case Opcode.OP_JMP: pc = CodeBlock.fetchArg1(instruction); continue NEXT_INSTRUCTION; case Opcode.OP_JMPTRUE: if (stack[sp - 1].equals(TRUE) || stack[sp - 1].equals(Rascal_TRUE)) { pc = CodeBlock.fetchArg1(instruction); } sp--; continue NEXT_INSTRUCTION; case Opcode.OP_JMPFALSE: if (stack[sp - 1].equals(FALSE) || stack[sp - 1].equals(Rascal_FALSE)) { pc = CodeBlock.fetchArg1(instruction); } sp--; continue NEXT_INSTRUCTION; case Opcode.OP_TYPESWITCH: IValue val = (IValue) stack[--sp]; Type t = null; if(val instanceof IConstructor) { t = ((IConstructor) val).getConstructorType(); } else { t = val.getType(); } int labelIndex = ToplevelType.getToplevelTypeAsInt(t); IList labels = (IList) cf.function.constantStore[CodeBlock.fetchArg1(instruction)]; pc = ((IInteger) labels.get(labelIndex)).intValue(); continue NEXT_INSTRUCTION; case Opcode.OP_JMPINDEXED: labelIndex = ((IInteger) stack[--sp]).intValue(); labels = (IList) cf.function.constantStore[CodeBlock.fetchArg1(instruction)]; pc = ((IInteger) labels.get(labelIndex)).intValue(); continue NEXT_INSTRUCTION; case Opcode.OP_LOADTYPE: stack[sp++] = cf.function.typeConstantStore[CodeBlock.fetchArg1(instruction)]; continue NEXT_INSTRUCTION; case Opcode.OP_LOADLOCDEREF: { Reference ref = (Reference) stack[CodeBlock.fetchArg1(instruction)]; stack[sp++] = ref.stack[ref.pos]; continue NEXT_INSTRUCTION; } case Opcode.OP_STORELOC: { stack[CodeBlock.fetchArg1(instruction)] = stack[sp - 1]; continue NEXT_INSTRUCTION; } case Opcode.OP_UNWRAPTHROWN: { stack[CodeBlock.fetchArg1(instruction)] = ((Thrown) stack[--sp]).value; continue NEXT_INSTRUCTION; } case Opcode.OP_STORELOCDEREF: Reference ref = (Reference) stack[CodeBlock.fetchArg1(instruction)]; ref.stack[ref.pos] = stack[sp - 1]; // TODO: We need to re-consider how to guarantee safe use of both Java objects and IValues continue NEXT_INSTRUCTION; case Opcode.OP_LOADFUN: // Loads functions that are defined at the root stack[sp++] = new FunctionInstance(functionStore.get(CodeBlock.fetchArg1(instruction)), root); continue NEXT_INSTRUCTION; case Opcode.OP_LOAD_NESTED_FUN: { // Loads nested functions and closures (anonymous nested functions): // First, get the function code Function fun = functionStore.get(CodeBlock.fetchArg1(instruction)); int scopeIn = CodeBlock.fetchArg2(instruction); // Second, look up the function environment frame into the stack of caller frames for(Frame env = cf; env != null; env = env.previousCallFrame) { if (env.scopeId == scopeIn) { stack[sp++] = new FunctionInstance(fun, env); continue NEXT_INSTRUCTION; } } throw new RuntimeException("LOAD_NESTED_FUN cannot find matching scope: " + scopeIn); } case Opcode.OP_LOADOFUN: OverloadedFunction of = overloadedStore.get(CodeBlock.fetchArg1(instruction)); if(of.scopeIn == -1) { stack[sp++] = new OverloadedFunctionInstance(of.functions, of.constructors, root); continue NEXT_INSTRUCTION; } for(Frame env = cf; env != null; env = env.previousCallFrame) { if (env.scopeId == of.scopeIn) { stack[sp++] = new OverloadedFunctionInstance(of.functions, of.constructors, env); continue NEXT_INSTRUCTION; } } throw new RuntimeException("Could not find matching scope when loading a nested overloaded function: " + of.scopeIn); case Opcode.OP_LOADCONSTR: Type constructor = constructorStore.get(CodeBlock.fetchArg1(instruction)); stack[sp++] = constructor; continue NEXT_INSTRUCTION; case Opcode.OP_LOADVAR: case Opcode.OP_LOADVARREF: { int s = CodeBlock.fetchArg1(instruction); pos = CodeBlock.fetchArg2(instruction); if(CodeBlock.isMaxArg2(pos)){ rval = moduleVariables.get(cf.function.constantStore[s]); if(op == Opcode.OP_LOADVAR && rval == null) { // EXCEPTION HANDLING stacktrace = new ArrayList<Frame>(); stacktrace.add(cf); thrown = RuntimeExceptions.uninitializedVariable(pos, null, stacktrace); for(Frame f = cf; f != null; f = f.previousCallFrame) { int handler = f.function.getHandler(pc - 1, thrown.value.getType()); if(handler != -1) { if(f != cf) { cf = f; instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; } pc = handler; stack[sp++] = thrown; continue NEXT_INSTRUCTION; } } // If a handler has not been found in the caller functions... return thrown; } stack[sp++] = rval; continue NEXT_INSTRUCTION; } for (Frame fr = cf; fr != null; fr = fr.previousScope) { if (fr.scopeId == s) { rval = (op == Opcode.OP_LOADVAR) ? fr.stack[pos] : new Reference(fr.stack, pos); if(op == Opcode.OP_LOADLOC && rval == null) { // EXCEPTION HANDLING stacktrace = new ArrayList<Frame>(); stacktrace.add(cf); thrown = RuntimeExceptions.uninitializedVariable(pos, null, stacktrace); for(Frame f = cf; f != null; f = f.previousCallFrame) { int handler = f.function.getHandler(pc - 1, thrown.value.getType()); if(handler != -1) { if(f != cf) { cf = f; instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; } pc = handler; stack[sp++] = thrown; continue NEXT_INSTRUCTION; } } // If a handler has not been found in the caller functions... return thrown; } stack[sp++] = rval; continue NEXT_INSTRUCTION; } } throw new RuntimeException("LOADVAR or LOADVARREF cannot find matching scope: " + s); } case Opcode.OP_LOADVARDEREF: { int s = CodeBlock.fetchArg1(instruction); pos = CodeBlock.fetchArg2(instruction); for (Frame fr = cf; fr != null; fr = fr.previousScope) { if (fr.scopeId == s) { ref = (Reference) fr.stack[pos]; stack[sp++] = ref.stack[ref.pos]; continue NEXT_INSTRUCTION; } } throw new RuntimeException("LOADVARDEREF cannot find matching scope: " + s); } case Opcode.OP_STOREVAR: int s = CodeBlock.fetchArg1(instruction); pos = CodeBlock.fetchArg2(instruction); if(CodeBlock.isMaxArg2(pos)){ IValue mvar = cf.function.constantStore[s]; moduleVariables.put(mvar, (IValue)stack[sp -1]); continue NEXT_INSTRUCTION; } for (Frame fr = cf; fr != null; fr = fr.previousScope) { if (fr.scopeId == s) { fr.stack[pos] = stack[sp - 1]; // TODO: We need to re-consider how to guarantee safe use of both Java objects and IValues continue NEXT_INSTRUCTION; } } throw new RuntimeException("STOREVAR cannot find matching scope: " + s); case Opcode.OP_STOREVARDEREF: s = CodeBlock.fetchArg1(instruction); pos = CodeBlock.fetchArg2(instruction); for (Frame fr = cf; fr != null; fr = fr.previousScope) { if (fr.scopeId == s) { ref = (Reference) fr.stack[pos]; ref.stack[ref.pos] = stack[sp - 1]; continue NEXT_INSTRUCTION; } } throw new RuntimeException("STOREVARDEREF cannot find matching scope: " + s); case Opcode.OP_CALLCONSTR: constructor = constructorStore.get(CodeBlock.fetchArg1(instruction)); arity = CodeBlock.fetchArg2(instruction); assert arity == constructor.getArity(); IValue[] args = new IValue[arity]; for(int i = 0; i < arity; i++) { args[arity - 1 - i] = (IValue) stack[--sp]; } stack[sp++] = vf.constructor(constructor, args); continue NEXT_INSTRUCTION; case Opcode.OP_CALLDYN: case Opcode.OP_CALL: // In case of CALLDYN, the stack top value of type 'Type' leads to a constructor call if(op == Opcode.OP_CALLDYN && stack[sp - 1] instanceof Type) { Type constr = (Type) stack[--sp]; arity = constr.getArity(); args = new IValue[arity]; for(int i = arity - 1; i >=0; i--) { args[i] = (IValue) stack[sp - arity + i]; } sp = sp - arity; stack[sp++] = vf.constructor(constr, args); continue NEXT_INSTRUCTION; } Function fun = null; Frame previousScope = null; if(op == Opcode.OP_CALLDYN && stack[sp - 1] instanceof FunctionInstance){ FunctionInstance fun_instance = (FunctionInstance) stack[--sp]; arity = CodeBlock.fetchArg1(instruction); // TODO: add assert fun = fun_instance.function; previousScope = fun_instance.env; } else if(op == Opcode.OP_CALL) { fun = functionStore.get(CodeBlock.fetchArg1(instruction)); arity = CodeBlock.fetchArg2(instruction); assert arity == fun.nformals; previousScope = cf; } else { throw new RuntimeException("unexpected argument type for CALLDYN: " + asString(stack[sp - 1])); } instructions = fun.codeblock.getInstructions(); Frame nextFrame = new Frame(fun.scopeId, cf, previousScope, fun.maxstack, fun); for (int i = fun.nformals - 1; i >= 0; i--) { nextFrame.stack[i] = stack[sp - fun.nformals + i]; } cf.pc = pc; cf.sp = sp - fun.nformals; cf = nextFrame; stack = cf.stack; sp = fun.nlocals; pc = 0; continue NEXT_INSTRUCTION; case Opcode.OP_OCALLDYN: // Get function types to perform a type-based dynamic resolution Type types = cf.function.codeblock.getConstantType(CodeBlock.fetchArg1(instruction)); arity = CodeBlock.fetchArg2(instruction); // Objects of three types may appear on the stack: // 1. FunctionInstance due to closures // 2. OverloadedFunctionInstance due to named Rascal functions Object funcObject = stack[--sp]; // Get function arguments from the stack args = new IValue[arity]; for(int i = arity - 1; i >= 0; i--) { args[i] = (IValue) stack[sp - arity + i]; } sp = sp - arity; if(funcObject instanceof FunctionInstance) { FunctionInstance fun_instance = (FunctionInstance) funcObject; cf.sp = sp; cf.pc = pc; cf = pushArguments(cf, fun_instance.function, fun_instance.env, args); instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; continue NEXT_INSTRUCTION; } OverloadedFunctionInstance of_instance = (OverloadedFunctionInstance) funcObject; if(debug) { this.appendToTrace("OVERLOADED FUNCTION CALLDYN: "); this.appendToTrace(" with alternatives:"); for(int index : of_instance.functions) { this.appendToTrace(" " + getFunctionName(index)); } } c_ofun_call = new OverloadedFunctionInstanceCall(vf, cf, of_instance.functions, of_instance.constructors, of_instance.env, args, types); ocalls.push(c_ofun_call); fun = c_ofun_call.nextFunction(functionStore); if(fun != null) { if(debug) { this.appendToTrace(" " + "try alternative: " + fun.name); } cf.sp = sp; cf.pc = pc; cf = pushArguments(c_ofun_call.cf, fun, c_ofun_call.env, c_ofun_call.args); instructions = fun.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = 0; } else { stack[sp++] = vf.constructor(c_ofun_call.nextConstructor(constructorStore), c_ofun_call.constr_args); } continue NEXT_INSTRUCTION; case Opcode.OP_OCALL: of = overloadedStore.get(CodeBlock.fetchArg1(instruction)); arity = CodeBlock.fetchArg2(instruction); if(debug) { this.appendToTrace("OVERLOADED FUNCTION CALL: " + getOverloadedFunctionName(CodeBlock.fetchArg1(instruction))); this.appendToTrace(" with alternatives:"); for(int index : of.functions) { this.appendToTrace(" " + getFunctionName(index)); } } // Get arguments from the stack args = new IValue[arity]; for(int i = arity - 1; i >= 0; i--) { args[i] = (IValue) stack[sp - arity + i]; } sp = sp - arity; c_ofun_call = new OverloadedFunctionInstanceCall(vf, root, cf, of.functions, of.constructors, of.scopeIn, args, null); ocalls.push(c_ofun_call); fun = c_ofun_call.nextFunction(functionStore); if(fun != null) { if(debug) { this.appendToTrace(" " + "try alternative: " + fun.name); } cf.sp = sp; cf.pc = pc; cf = pushArguments(c_ofun_call.cf, fun, c_ofun_call.env, c_ofun_call.args); instructions = fun.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = 0; } else { stack[sp++] = vf.constructor(c_ofun_call.nextConstructor(constructorStore), c_ofun_call.constr_args); } continue NEXT_INSTRUCTION; case Opcode.OP_FAILRETURN: assert cf.previousCallFrame == c_ofun_call.cf; fun = c_ofun_call.nextFunction(functionStore); if(fun != null) { if(debug) { this.appendToTrace(" " + "try alternative: " + fun.name); } cf.sp = sp; cf.pc = pc; cf = pushArguments(c_ofun_call.cf, fun, c_ofun_call.env, c_ofun_call.args); instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; } else { cf = c_ofun_call.cf; instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; stack[sp++] = vf.constructor(c_ofun_call.nextConstructor(constructorStore), c_ofun_call.constr_args); } continue NEXT_INSTRUCTION; case Opcode.OP_FILTERRETURN: case Opcode.OP_RETURN0: case Opcode.OP_RETURN1: // Overloading specific if(c_ofun_call != null && cf.previousCallFrame == c_ofun_call.cf) { ocalls.pop(); c_ofun_call = ocalls.isEmpty() ? null : ocalls.peek(); } rval = null; boolean returns = cf.isCoroutine || op == Opcode.OP_RETURN1 || op == Opcode.OP_FILTERRETURN; if(op == Opcode.OP_RETURN1 || cf.isCoroutine) { if(cf.isCoroutine) { rval = Rascal_TRUE; if(op == Opcode.OP_RETURN1) { arity = CodeBlock.fetchArg1(instruction); int[] refs = cf.function.refs; if(arity != refs.length) { throw new RuntimeException("Coroutine " + cf.function.name + ": arity of return (" + arity + ") unequal to number of reference parameters (" + refs.length + ")"); } for(int i = 0; i < arity; i++) { ref = (Reference) stack[refs[arity - 1 - i]]; ref.stack[ref.pos] = stack[--sp]; } } } else { rval = stack[sp - 1]; } } // if the current frame is the frame of a top active coroutine, // then pop this coroutine from the stack of active coroutines if(cf == ccf) { activeCoroutines.pop(); ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start; } cf = cf.previousCallFrame; if(cf == null) { if(returns) { return rval; } else { return NONE; } } instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; if(returns) { stack[sp++] = rval; } continue NEXT_INSTRUCTION; case Opcode.OP_CALLJAVA: String methodName = ((IString) cf.function.constantStore[instructions[pc++]]).getValue(); String className = ((IString) cf.function.constantStore[instructions[pc++]]).getValue(); Type parameterTypes = cf.function.typeConstantStore[instructions[pc++]]; int reflect = instructions[pc++]; arity = parameterTypes.getArity(); try { sp = callJavaMethod(methodName, className, parameterTypes, reflect, stack, sp); } catch(Throw e) { thrown = Thrown.getInstance(e.getException(), e.getLocation(), new ArrayList<Frame>()); // EXCEPTION HANDLING for(Frame f = cf; f != null; f = f.previousCallFrame) { int handler = f.function.getHandler(pc - 1, thrown.value.getType()); if(handler != -1) { if(f != cf) { cf = f; instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; } pc = handler; stack[sp++] = thrown; continue NEXT_INSTRUCTION; } } // If a handler has not been found in the caller functions... return thrown; } continue NEXT_INSTRUCTION; case Opcode.OP_INIT: arity = CodeBlock.fetchArg1(instruction); Object src = stack[--sp]; Coroutine coroutine; if(src instanceof Coroutine){ coroutine = (Coroutine) src; fun = coroutine.frame.function; } else if(src instanceof FunctionInstance) { FunctionInstance fun_instance = (FunctionInstance) src; fun = fun_instance.function; Frame frame = new Frame(fun.scopeId, null, fun_instance.env, fun.maxstack, fun); coroutine = new Coroutine(frame); } else { throw new RuntimeException("Unexpected argument type for INIT: " + src.getClass() + ", " + src); } if(coroutine.isInitialized()) { throw new RuntimeException("Trying to initialize a coroutine, which has already been initialized: " + fun.getName() + " (corounine's main), called in " + cf.function.getName()); } // the main function of coroutine may have formal parameters, // therefore, INIT may take a number of arguments == formal parameters - arguments already passed to CREATE if(arity != fun.nformals - coroutine.frame.sp) { throw new RuntimeException("Too many or too few arguments to INIT, the expected number: " + (fun.nformals - coroutine.frame.sp) + "; coroutine's main: " + fun.getName() + ", called in " + cf.function.getName()); } Coroutine newCoroutine = coroutine.copy(); for (int i = arity - 1; i >= 0; i--) { newCoroutine.frame.stack[coroutine.frame.sp + i] = stack[sp - arity + i]; } newCoroutine.frame.sp = fun.nlocals; sp = sp - arity; /* Place coroutine back on stack */ stack[sp++] = newCoroutine; // Now, instead of simply suspending a coroutine during INIT, let it execute until GUARD, which has been delegated the INIT's suspension newCoroutine.suspend(newCoroutine.frame); // put the coroutine onto the stack of active coroutines activeCoroutines.push(newCoroutine); ccf = newCoroutine.start; newCoroutine.next(cf); fun = newCoroutine.frame.function; instructions = newCoroutine.frame.function.codeblock.getInstructions(); cf.pc = pc; cf.sp = sp; cf = newCoroutine.frame; stack = cf.stack; sp = cf.sp; pc = cf.pc; continue NEXT_INSTRUCTION; case Opcode.OP_GUARD: rval = stack[sp - 1]; boolean precondition; if(rval instanceof IBool) { precondition = ((IBool) rval).getValue(); } else if(rval instanceof Boolean) { precondition = (Boolean) rval; } else { throw new RuntimeException("Guard's expression has to be boolean!"); } if(cf == ccf) { coroutine = activeCoroutines.pop(); ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start; Frame prev = cf.previousCallFrame; if(precondition) { coroutine.suspend(cf); } --sp; cf.pc = pc; cf.sp = sp; cf = prev; instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; continue NEXT_INSTRUCTION; } if(!precondition) { cf.pc = pc; cf.sp = sp; cf = cf.previousCallFrame; instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; stack[sp++] = Rascal_FALSE; continue NEXT_INSTRUCTION; } continue NEXT_INSTRUCTION; case Opcode.OP_CREATE: case Opcode.OP_CREATEDYN: if(op == Opcode.OP_CREATE){ fun = functionStore.get(CodeBlock.fetchArg1(instruction)); arity = CodeBlock.fetchArg2(instruction); previousScope = null; } else { arity = CodeBlock.fetchArg1(instruction); src = stack[--sp]; if(src instanceof FunctionInstance) { FunctionInstance fun_instance = (FunctionInstance) src; fun = fun_instance.function; previousScope = fun_instance.env; } else { throw new RuntimeException("unexpected argument type for CREATEDYN: " + asString(src)); } } Frame frame = new Frame(fun.scopeId, null, previousScope, fun.maxstack, fun); // the main function of coroutine may have formal parameters, // therefore, CREATE may take a number of arguments <= formal parameters if(arity > fun.nformals) throw new RuntimeException("Too many arguments to CREATE or CREATEDYN, expected <= " + fun.nformals); for (int i = arity - 1; i >= 0; i--) { frame.stack[i] = stack[sp - arity + i]; } frame.sp = arity; coroutine = new Coroutine(frame); sp = sp - arity; stack[sp++] = coroutine; continue NEXT_INSTRUCTION; case Opcode.OP_NEXT0: case Opcode.OP_NEXT1: coroutine = (Coroutine) stack[--sp]; // Merged the hasNext and next semantics if(!coroutine.hasNext()) { if(op == Opcode.OP_NEXT1) { --sp; } stack[sp++] = FALSE; continue NEXT_INSTRUCTION; } // put the coroutine onto the stack of active coroutines activeCoroutines.push(coroutine); ccf = coroutine.start; coroutine.next(cf); fun = coroutine.frame.function; instructions = coroutine.frame.function.codeblock.getInstructions(); coroutine.frame.stack[coroutine.frame.sp++] = // Always leave an entry on the stack (op == Opcode.OP_NEXT1) ? stack[--sp] : null; cf.pc = pc; cf.sp = sp; cf = coroutine.frame; stack = cf.stack; sp = cf.sp; pc = cf.pc; continue NEXT_INSTRUCTION; case Opcode.OP_YIELD0: case Opcode.OP_YIELD1: coroutine = activeCoroutines.pop(); ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start; Frame prev = coroutine.start.previousCallFrame; rval = Rascal_TRUE; // In fact, yield has to always return TRUE if(op == Opcode.OP_YIELD1) { arity = CodeBlock.fetchArg1(instruction); int[] refs = coroutine.start.function.refs; // Takes the reference parameter positions of the top active coroutine instance if(cf != coroutine.start && cf.function.refs.length != refs.length) { throw new RuntimeException("The 'yield' from within a nested call has to take the same number of arguments as the number of the caller's reference parameters: " + cf.function.refs.length + "; " + refs.length); } if(arity != refs.length) { throw new RuntimeException("The 'yield' within a coroutine has to take the same number of arguments as the number of its reference parameters; arity: " + arity + "; reference parameter number: " + refs.length); } for(int i = 0; i < arity; i++) { ref = (Reference) coroutine.start.stack[refs[arity - 1 - i]]; // Takes the reference parameters of the top active coroutine instance ref.stack[ref.pos] = stack[--sp]; } } cf.pc = pc; cf.sp = sp; coroutine.suspend(cf); cf = prev; if(op == Opcode.OP_YIELD1 && cf == null) return rval; instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; stack[sp++] = rval; // Corresponding next will always find an entry on the stack continue NEXT_INSTRUCTION; case Opcode.OP_EXHAUST: if(cf == ccf) { activeCoroutines.pop(); ccf = activeCoroutines.isEmpty() ? null : activeCoroutines.peek().start; } cf = cf.previousCallFrame; if(cf == null) { return Rascal_FALSE; // 'Exhaust' has to always return FALSE, i.e., signal a failure; } instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; stack[sp++] = Rascal_FALSE; // 'Exhaust' has to always return FALSE, i.e., signal a failure; continue NEXT_INSTRUCTION; case Opcode.OP_HASNEXT: coroutine = (Coroutine) stack[--sp]; stack[sp++] = coroutine.hasNext() ? TRUE : FALSE; continue NEXT_INSTRUCTION; case Opcode.OP_CALLPRIM: RascalPrimitive prim = RascalPrimitive.fromInteger(CodeBlock.fetchArg1(instruction)); arity = CodeBlock.fetchArg2(instruction); try { sp = prim.invoke(stack, sp, arity); } catch(InvocationTargetException targetException) { if(!(targetException.getTargetException() instanceof Thrown)) { throw targetException; } // EXCEPTION HANDLING thrown = (Thrown) targetException.getTargetException(); thrown.stacktrace.add(cf); sp = sp - arity; for(Frame f = cf; f != null; f = f.previousCallFrame) { int handler = f.function.getHandler(pc - 1, thrown.value.getType()); if(handler != -1) { if(f != cf) { cf = f; instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; } pc = handler; stack[sp++] = thrown; continue NEXT_INSTRUCTION; } } // If a handler has not been found in the caller functions... return thrown; } continue NEXT_INSTRUCTION; // Some specialized MuPrimitives case Opcode.OP_SUBSCRIPTARRAY: stack[sp - 2] = ((Object[]) stack[sp - 2])[((Integer) stack[sp - 1])]; sp--; continue NEXT_INSTRUCTION; case Opcode.OP_SUBSCRIPTLIST: stack[sp - 2] = ((IList) stack[sp - 2]).get((Integer) stack[sp - 1]); sp--; continue NEXT_INSTRUCTION; case Opcode.OP_LESSINT: stack[sp - 2] = ((Integer) stack[sp - 2]) < ((Integer) stack[sp - 1]); sp--; continue NEXT_INSTRUCTION; case Opcode.OP_GREATEREQUALINT: stack[sp - 2] = ((Integer) stack[sp - 2]) >= ((Integer) stack[sp - 1]); sp--; continue NEXT_INSTRUCTION; case Opcode.OP_ADDINT: stack[sp - 2] = ((Integer) stack[sp - 2]) + ((Integer) stack[sp - 1]); sp--; continue NEXT_INSTRUCTION; case Opcode.OP_SUBTRACTINT: stack[sp - 2] = ((Integer) stack[sp - 2]) - ((Integer) stack[sp - 1]); sp--; continue NEXT_INSTRUCTION; case Opcode.OP_ANDBOOL: boolean b1 = (stack[sp - 2] instanceof Boolean) ? ((Boolean) stack[sp - 2]) : ((IBool) stack[sp - 2]).getValue(); boolean b2 = (stack[sp - 1] instanceof Boolean) ? ((Boolean) stack[sp - 1]) : ((IBool) stack[sp - 1]).getValue(); stack[sp - 2] = b1 && b2; sp--; continue NEXT_INSTRUCTION; case Opcode.OP_TYPEOF: if(stack[sp - 1] instanceof HashSet<?>){ // For the benefit of set matching @SuppressWarnings("unchecked") HashSet<IValue> mset = (HashSet<IValue>) stack[sp - 1]; if(mset.isEmpty()){ stack[sp - 1] = tf.setType(tf.voidType()); } else { IValue v = mset.iterator().next(); stack[sp - 1] = tf.setType(v.getType()); } } else { stack[sp - 1] = ((IValue) stack[sp - 1]).getType(); } continue NEXT_INSTRUCTION; case Opcode.OP_SUBTYPE: stack[sp - 2] = ((Type) stack[sp - 2]).isSubtypeOf((Type) stack[sp - 1]); sp--; continue NEXT_INSTRUCTION; case Opcode.OP_CHECKARGTYPE: Type argType = ((IValue) stack[sp - 2]).getType(); Type paramType = ((Type) stack[sp - 1]); stack[sp - 2] = argType.isSubtypeOf(paramType); sp--; continue NEXT_INSTRUCTION; case Opcode.OP_LABEL: throw new RuntimeException("label instruction at runtime"); case Opcode.OP_HALT: if (debug) { stdout.println("Program halted:"); for (int i = 0; i < sp; i++) { stdout.println(i + ": " + stack[i]); } } return stack[sp - 1]; case Opcode.OP_PRINTLN: arity = CodeBlock.fetchArg1(instruction); StringBuilder w = new StringBuilder(); for(int i = arity - 1; i >= 0; i--){ String str = (stack[sp - 1 - i] instanceof IString) ? ((IString) stack[sp - 1 - i]).toString() : asString(stack[sp - 1 - i]); w.append(str).append(" "); } stdout.println(w.toString()); sp = sp - arity + 1; continue NEXT_INSTRUCTION; case Opcode.OP_THROW: Object obj = stack[--sp]; thrown = null; if(obj instanceof IValue) { stacktrace = new ArrayList<Frame>(); stacktrace.add(cf); thrown = Thrown.getInstance((IValue) obj, null, stacktrace); } else { // Then, an object of type 'Thrown' is on top of the stack thrown = (Thrown) obj; } // First, try to find a handler in the current frame function, // given the current instruction index and the value type, // then, if not found, look up the caller function(s) for(Frame f = cf; f != null; f = f.previousCallFrame) { int handler = f.function.getHandler(f.pc - 1, thrown.value.getType()); if(handler != -1) { if(f != cf) { cf = f; instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; } pc = handler; stack[sp++] = thrown; continue NEXT_INSTRUCTION; } } // If a handler has not been found in the caller functions... return thrown; case Opcode.OP_LOADLOCKWP: IString name = (IString) cf.function.codeblock.getConstantValue(CodeBlock.fetchArg1(instruction)); @SuppressWarnings("unchecked") Map<String, Map.Entry<Type, IValue>> defaults = (Map<String, Map.Entry<Type, IValue>>) stack[cf.function.nformals]; Map.Entry<Type, IValue> defaultValue = defaults.get(name.getValue()); for(Frame f = cf; f != null; f = f.previousCallFrame) { IMap kargs = (IMap) f.stack[f.function.nformals - 1]; if(kargs.containsKey(name)) { val = kargs.get(name); if(val.getType().isSubtypeOf(defaultValue.getKey())) { stack[sp++] = val; continue NEXT_INSTRUCTION; } } } stack[sp++] = defaultValue.getValue(); continue NEXT_INSTRUCTION; case Opcode.OP_LOADVARKWP: continue NEXT_INSTRUCTION; case Opcode.OP_STORELOCKWP: val = (IValue) stack[sp - 1]; name = (IString) cf.function.codeblock.getConstantValue(CodeBlock.fetchArg1(instruction)); IMap kargs = (IMap) stack[cf.function.nformals - 1]; stack[cf.function.nformals - 1] = kargs.put(name, val); continue NEXT_INSTRUCTION; case Opcode.OP_STOREVARKWP: continue NEXT_INSTRUCTION; default: throw new RuntimeException("RVM main loop -- cannot decode instruction"); } switch(postOp){ case Opcode.POSTOP_CHECKUNDEF: // EXCEPTION HANDLING stacktrace = new ArrayList<Frame>(); stacktrace.add(cf); thrown = RuntimeExceptions.uninitializedVariable(pos, null, stacktrace); for(Frame f = cf; f != null; f = f.previousCallFrame) { int handler = f.function.getHandler(pc - 1, thrown.value.getType()); if(handler != -1) { if(f != cf) { cf = f; instructions = cf.function.codeblock.getInstructions(); stack = cf.stack; sp = cf.sp; pc = cf.pc; } pc = handler; stack[sp++] = thrown; continue NEXT_INSTRUCTION; } } // If a handler has not been found in the caller functions... return thrown; } } } catch (Exception e) { e.printStackTrace(stderr); throw new RuntimeException("PANIC: (instruction execution): instruction: " + cf.function.codeblock.toString(pc - 1) + "; message: "+ e.getMessage() ); //stdout.println("PANIC: (instruction execution): " + e.getMessage()); //e.printStackTrace(); //stderr.println(e.getStackTrace()); } }
diff --git a/src/org/flowvisor/message/FVFlowRemoved.java b/src/org/flowvisor/message/FVFlowRemoved.java index d7170b8..7e8dc8e 100644 --- a/src/org/flowvisor/message/FVFlowRemoved.java +++ b/src/org/flowvisor/message/FVFlowRemoved.java @@ -1,109 +1,110 @@ package org.flowvisor.message; import java.util.HashSet; import java.util.List; import java.util.Set; import org.flowvisor.classifier.CookiePair; import org.flowvisor.classifier.CookieTranslator; import org.flowvisor.classifier.FVClassifier; import org.flowvisor.flows.FlowEntry; import org.flowvisor.flows.FlowMap; import org.flowvisor.flows.SliceAction; import org.flowvisor.log.FVLog; import org.flowvisor.log.LogLevel; import org.flowvisor.openflow.protocol.FVMatch; import org.flowvisor.slicer.FVSlicer; import org.openflow.protocol.OFFlowRemoved; import org.openflow.protocol.OFMatch; import org.openflow.protocol.action.OFAction; public class FVFlowRemoved extends OFFlowRemoved implements Classifiable, Slicable { /** * Current algorithm: if flow tracking knows who sent this flow, then just * send to them * * If flow tracking doesn't know (or is disabled) send to everyone who * *could* have sent the flow * * FIXME: do the reference counting so that if a flow is expanded three * ways, only send the flow_removed up to the controller if all three flows * have expired */ @Override public void classifyFromSwitch(FVClassifier fvClassifier) { + FVLog.log(LogLevel.DEBUG, fvClassifier, "Starting flowremoved message processing"); FlowMap flowSpace = fvClassifier.getSwitchFlowMap(); Set<String> slicesToUpdate = new HashSet<String>(); String slicerFromCookie = untanslateCookie(fvClassifier); FVLog.log(LogLevel.DEBUG, fvClassifier, slicerFromCookie); String sliceName = fvClassifier.getFlowDB().processFlowRemoved(this, fvClassifier.getDPID()); if (sliceName != null) slicesToUpdate.add(sliceName); else if (slicerFromCookie != null) slicesToUpdate.add(slicerFromCookie); else { // flow tracking either disabled or broken // just fall back to everyone who *could* have inserted this flow List<FlowEntry> flowEntries = flowSpace.matches( fvClassifier.getDPID(), new FVMatch(getMatch())); for (FlowEntry flowEntry : flowEntries) { for (OFAction ofAction : flowEntry.getActionsList()) { if (ofAction instanceof SliceAction) { SliceAction sliceAction = (SliceAction) ofAction; if ((sliceAction.getSlicePerms() & SliceAction.WRITE) != 0) { slicesToUpdate.add(sliceAction.getSliceName()); } } } } } // forward this msg to each of them FVLog.log(LogLevel.DEBUG, fvClassifier, slicesToUpdate.toString()); for (String slice : slicesToUpdate) { FVSlicer fvSlicer = fvClassifier.getSlicerByName(slice); if (fvSlicer == null) { FVLog.log(LogLevel.CRIT, fvClassifier, "inconsistent state: missing fvSliver entry for: " + slice); continue; } fvSlicer.decrementFlowRules(); fvSlicer.getFlowRewriteDB().processFlowRemoved(this); fvSlicer.sendMsg(this, fvClassifier); } } @Override public void sliceFromController(FVClassifier fvClassifier, FVSlicer fvSlicer) { FVMessageUtil.dropUnexpectedMesg(this, fvSlicer); } public FVFlowRemoved setMatch(FVMatch match) { this.match = match; return this; } private String untanslateCookie(FVClassifier fvClassifier) { CookieTranslator cookieTrans = fvClassifier.getCookieTranslator(); CookiePair pair = cookieTrans.untranslate(this.cookie); this.setCookie(pair.getCookie()); return pair.getSliceName(); } @Override public OFMatch getMatch() { return this.match; } @Override public String toString() { return super.toString() + ";" + this.getMatch().toString(); } }
true
true
public void classifyFromSwitch(FVClassifier fvClassifier) { FlowMap flowSpace = fvClassifier.getSwitchFlowMap(); Set<String> slicesToUpdate = new HashSet<String>(); String slicerFromCookie = untanslateCookie(fvClassifier); FVLog.log(LogLevel.DEBUG, fvClassifier, slicerFromCookie); String sliceName = fvClassifier.getFlowDB().processFlowRemoved(this, fvClassifier.getDPID()); if (sliceName != null) slicesToUpdate.add(sliceName); else if (slicerFromCookie != null) slicesToUpdate.add(slicerFromCookie); else { // flow tracking either disabled or broken // just fall back to everyone who *could* have inserted this flow List<FlowEntry> flowEntries = flowSpace.matches( fvClassifier.getDPID(), new FVMatch(getMatch())); for (FlowEntry flowEntry : flowEntries) { for (OFAction ofAction : flowEntry.getActionsList()) { if (ofAction instanceof SliceAction) { SliceAction sliceAction = (SliceAction) ofAction; if ((sliceAction.getSlicePerms() & SliceAction.WRITE) != 0) { slicesToUpdate.add(sliceAction.getSliceName()); } } } } } // forward this msg to each of them FVLog.log(LogLevel.DEBUG, fvClassifier, slicesToUpdate.toString()); for (String slice : slicesToUpdate) { FVSlicer fvSlicer = fvClassifier.getSlicerByName(slice); if (fvSlicer == null) { FVLog.log(LogLevel.CRIT, fvClassifier, "inconsistent state: missing fvSliver entry for: " + slice); continue; } fvSlicer.decrementFlowRules(); fvSlicer.getFlowRewriteDB().processFlowRemoved(this); fvSlicer.sendMsg(this, fvClassifier); } }
public void classifyFromSwitch(FVClassifier fvClassifier) { FVLog.log(LogLevel.DEBUG, fvClassifier, "Starting flowremoved message processing"); FlowMap flowSpace = fvClassifier.getSwitchFlowMap(); Set<String> slicesToUpdate = new HashSet<String>(); String slicerFromCookie = untanslateCookie(fvClassifier); FVLog.log(LogLevel.DEBUG, fvClassifier, slicerFromCookie); String sliceName = fvClassifier.getFlowDB().processFlowRemoved(this, fvClassifier.getDPID()); if (sliceName != null) slicesToUpdate.add(sliceName); else if (slicerFromCookie != null) slicesToUpdate.add(slicerFromCookie); else { // flow tracking either disabled or broken // just fall back to everyone who *could* have inserted this flow List<FlowEntry> flowEntries = flowSpace.matches( fvClassifier.getDPID(), new FVMatch(getMatch())); for (FlowEntry flowEntry : flowEntries) { for (OFAction ofAction : flowEntry.getActionsList()) { if (ofAction instanceof SliceAction) { SliceAction sliceAction = (SliceAction) ofAction; if ((sliceAction.getSlicePerms() & SliceAction.WRITE) != 0) { slicesToUpdate.add(sliceAction.getSliceName()); } } } } } // forward this msg to each of them FVLog.log(LogLevel.DEBUG, fvClassifier, slicesToUpdate.toString()); for (String slice : slicesToUpdate) { FVSlicer fvSlicer = fvClassifier.getSlicerByName(slice); if (fvSlicer == null) { FVLog.log(LogLevel.CRIT, fvClassifier, "inconsistent state: missing fvSliver entry for: " + slice); continue; } fvSlicer.decrementFlowRules(); fvSlicer.getFlowRewriteDB().processFlowRemoved(this); fvSlicer.sendMsg(this, fvClassifier); } }
diff --git a/src/com/dmdirc/parser/irc/ProcessMode.java b/src/com/dmdirc/parser/irc/ProcessMode.java index cdce16b2c..5ac562968 100644 --- a/src/com/dmdirc/parser/irc/ProcessMode.java +++ b/src/com/dmdirc/parser/irc/ProcessMode.java @@ -1,337 +1,338 @@ /* * Copyright (c) 2006-2009 Chris Smith, Shane Mc Cormack, Gregory Holmes * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dmdirc.parser.irc; import com.dmdirc.parser.irc.callbacks.CallbackObject; import java.util.Calendar; /** * Process a Mode line. */ public class ProcessMode extends IRCProcessor { /** * Process a Mode Line. * * @param sParam Type of line to process ("MODE", "324") * @param token IRCTokenised line to process */ @Override public void process(String sParam, String[] token) { String[] sModestr; String sChannelName; if (sParam.equals("324")) { sChannelName = token[3]; sModestr = new String[token.length-4]; System.arraycopy(token, 4, sModestr, 0, token.length-4); } else if (sParam.equals("221")) { processUserMode(sParam, token, new String[]{token[token.length-1]}, true); return; } else { sChannelName = token[2]; sModestr = new String[token.length-3]; System.arraycopy(token, 3, sModestr, 0, token.length-3); } if (!isValidChannelName(sChannelName)) { processUserMode(sParam, token, sModestr, false); } else { processChanMode(sParam, token, sModestr, sChannelName); } } /** * Method to trim spaces from strings * * @param str String to trim * @return String without spaces on the ends */ private String trim(String str) { return str.trim(); } /** * Process Chan modes. * * @param sParam String representation of parameter to parse * @param token IRCTokenised Array of the incomming line * @param sModestr The modes and params * @param sChannelName Channel these modes are for */ public void processChanMode(String sParam, String token[], String sModestr[], String sChannelName) { StringBuilder sFullModeStr = new StringBuilder(); String sNonUserModeStr = ""; String sNonUserModeStrParams = ""; String sModeParam; String sTemp; int nParam = 1; long nTemp = 0, nValue = 0, nCurrent = 0; boolean bPositive = true, bBooleanMode = true; char cPositive = '+'; ChannelInfo iChannel; ChannelClientInfo iChannelClientInfo; ClientInfo iClient; ChannelClientInfo setterCCI; CallbackObject cbSingle = null; CallbackObject cbNonUser = null; if (!sParam.equals("324")) { cbSingle = getCallbackManager().getCallbackType("OnChannelSingleModeChanged"); cbNonUser = getCallbackManager().getCallbackType("OnChannelNonUserModeChanged"); } iChannel = getChannelInfo(sChannelName); if (iChannel == null) { // callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got modes for channel ("+sChannelName+") that I am not on.", myParser.getLastLine())); // iChannel = new ChannelInfo(myParser, sChannelName); // myParser.addChannel(iChannel); return; } // Get the current channel modes if (!sParam.equals("324")) { nCurrent = iChannel.getMode(); } setterCCI = iChannel.getUser(token[0]); if (IRCParser.ALWAYS_UPDATECLIENT && setterCCI != null) { // Facilitate dmdirc formatter if (setterCCI.getClient().getHost().isEmpty()) {setterCCI.getClient().setUserBits(token[0],false); } } // Loop through the mode string, and add/remove modes/params where they are needed for (int i = 0; i < sModestr[0].length(); ++i) { Character cMode = sModestr[0].charAt(i); if (cMode.equals(":".charAt(0))) { continue; } sNonUserModeStr = sNonUserModeStr+cMode; if (cMode.equals("+".charAt(0))) { cPositive = '+'; bPositive = true; } else if (cMode.equals("-".charAt(0))) { cPositive = '-'; bPositive = false; } else { if (myParser.hChanModesBool.containsKey(cMode)) { nValue = myParser.hChanModesBool.get(cMode); bBooleanMode = true; } else if (myParser.hChanModesOther.containsKey(cMode)) { nValue = myParser.hChanModesOther.get(cMode); bBooleanMode = false; } else if (myParser.hPrefixModes.containsKey(cMode)) { // (de) OP/Voice someone if (sModestr.length <= nParam) { myParser.callErrorInfo(new ParserError(ParserError.ERROR_FATAL + ParserError.ERROR_USER, "Broken Modes. Parameter required but not given.", myParser.getLastLine())); + return; } sModeParam = sModestr[nParam++]; nValue = myParser.hPrefixModes.get(cMode); callDebugInfo(IRCParser.DEBUG_INFO, "User Mode: %c / %d [%s] {Positive: %b}",cMode, nValue, sModeParam, bPositive); iChannelClientInfo = iChannel.getUser(sModeParam); if (iChannelClientInfo == null) { // Client not known? // callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got mode for client not known on channel - Added", myParser.getLastLine())); iClient = getClientInfo(sModeParam); if (iClient == null) { // callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got mode for client not known at all - Added", myParser.getLastLine())); iClient = new ClientInfo(myParser, sModeParam); myParser.addClient(iClient); } iChannelClientInfo = iChannel.addClient(iClient); } callDebugInfo(IRCParser.DEBUG_INFO, "\tOld Mode Value: %d",iChannelClientInfo.getChanMode()); if (bPositive) { iChannelClientInfo.setChanMode(iChannelClientInfo.getChanMode() | nValue); sTemp = "+"; } else { iChannelClientInfo.setChanMode(iChannelClientInfo.getChanMode() ^ (iChannelClientInfo.getChanMode() & nValue)); sTemp = "-"; } sTemp = sTemp+cMode; callChannelUserModeChanged(iChannel, iChannelClientInfo, setterCCI, token[0], sTemp); continue; } else { // unknown mode - add as boolean // callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got unknown mode "+cMode+" - Added as boolean mode", myParser.getLastLine())); myParser.hChanModesBool.put(cMode,myParser.nNextKeyCMBool); nValue = myParser.nNextKeyCMBool; bBooleanMode = true; myParser.nNextKeyCMBool = myParser.nNextKeyCMBool*2; } if (bBooleanMode) { callDebugInfo(IRCParser.DEBUG_INFO, "Boolean Mode: %c [%d] {Positive: %b}",cMode, nValue, bPositive); if (bPositive) { nCurrent = nCurrent | nValue; } else { nCurrent = nCurrent ^ (nCurrent & nValue); } } else { if ((bPositive || nValue == IRCParser.MODE_LIST || ((nValue & IRCParser.MODE_UNSET) == IRCParser.MODE_UNSET)) && (sModestr.length <= nParam)) { myParser.callErrorInfo(new ParserError(ParserError.ERROR_FATAL + ParserError.ERROR_USER, "Broken Modes. Parameter required but not given.", myParser.getLastLine())); } if (nValue == IRCParser.MODE_LIST) { // List Mode sModeParam = sModestr[nParam++]; sNonUserModeStrParams = sNonUserModeStrParams+" "+sModeParam; nTemp = (Calendar.getInstance().getTimeInMillis() / 1000); iChannel.setListModeParam(cMode, new ChannelListModeItem(sModeParam, token[0], nTemp ), bPositive); callDebugInfo(IRCParser.DEBUG_INFO, "List Mode: %c [%s] {Positive: %b}",cMode, sModeParam, bPositive); if (cbSingle != null) { cbSingle.call(iChannel, setterCCI, token[0], cPositive+cMode+" "+sModeParam ); } } else { // Mode with a parameter if (bPositive) { // +Mode - always needs a parameter to set sModeParam = sModestr[nParam++]; sNonUserModeStrParams = sNonUserModeStrParams+" "+sModeParam; callDebugInfo(IRCParser.DEBUG_INFO, "Set Mode: %c [%s] {Positive: %b}",cMode, sModeParam, bPositive); iChannel.setModeParam(cMode,sModeParam); if (cbSingle != null) { cbSingle.call(iChannel, setterCCI, token[0], cPositive+cMode+" "+sModeParam ); } } else { // -Mode - parameter isn't always needed, we need to check if ((nValue & IRCParser.MODE_UNSET) == IRCParser.MODE_UNSET) { sModeParam = sModestr[nParam++]; sNonUserModeStrParams = sNonUserModeStrParams+" "+sModeParam; } else { sModeParam = ""; } callDebugInfo(IRCParser.DEBUG_INFO, "Unset Mode: %c [%s] {Positive: %b}",cMode, sModeParam, bPositive); iChannel.setModeParam(cMode,""); if (cbSingle != null) { cbSingle.call(iChannel, setterCCI, token[0], trim(cPositive+cMode+" "+sModeParam) ); } } } } } } // Call Callbacks for (int i = 0; i < sModestr.length; ++i) { sFullModeStr.append(sModestr[i]).append(" "); } iChannel.setMode(nCurrent); if (sParam.equals("324")) { callChannelModeChanged(iChannel, null, "", sFullModeStr.toString().trim()); } else { callChannelModeChanged(iChannel, setterCCI, token[0], sFullModeStr.toString().trim()); } if (cbNonUser != null) { cbNonUser.call(iChannel, setterCCI, token[0], trim(sNonUserModeStr+sNonUserModeStrParams)); } } /** * Process user modes. * * @param sParam String representation of parameter to parse * @param token IRCTokenised Array of the incomming line * @param clearOldModes Clear old modes before applying these modes (used by 221) */ private void processUserMode(String sParam, String token[], String sModestr[], boolean clearOldModes) { long nCurrent = 0, nValue = 0; boolean bPositive = true; ClientInfo iClient; iClient = getClientInfo(token[2]); if (iClient == null) { return; } if (clearOldModes) { nCurrent = 0; } else { nCurrent = iClient.getUserMode(); } for (int i = 0; i < sModestr[0].length(); ++i) { Character cMode = sModestr[0].charAt(i); if (cMode.equals("+".charAt(0))) { bPositive = true; } else if (cMode.equals("-".charAt(0))) { bPositive = false; } else if (cMode.equals(":".charAt(0))) { continue; } else { if (myParser.hUserModes.containsKey(cMode)) { nValue = myParser.hUserModes.get(cMode); } else { // Unknown mode callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got unknown user mode "+cMode+" - Added", myParser.getLastLine())); myParser.hUserModes.put(cMode,myParser.nNextKeyUser); nValue = myParser.nNextKeyUser; myParser.nNextKeyUser = myParser.nNextKeyUser*2; } // Usermodes are always boolean callDebugInfo(IRCParser.DEBUG_INFO, "User Mode: %c [%d] {Positive: %b}",cMode, nValue, bPositive); if (bPositive) { nCurrent = nCurrent | nValue; } else { nCurrent = nCurrent ^ (nCurrent & nValue); } } } iClient.setUserMode(nCurrent); if (sParam.equals("221")) { callUserModeDiscovered(iClient, sModestr[0]); } else { callUserModeChanged(iClient, token[0], sModestr[0]); } } /** * Callback to all objects implementing the ChannelModeChanged Callback. * * @see IChannelModeChanged * @param cChannel Channel where modes were changed * @param cChannelClient Client chaning the modes (null if server) * @param sHost Host doing the mode changing (User host or server name) * @param sModes Exact String parsed * @return true if a method was called, false otherwise */ protected boolean callChannelModeChanged(ChannelInfo cChannel, ChannelClientInfo cChannelClient, String sHost, String sModes) { return getCallbackManager().getCallbackType("OnChannelModeChanged").call(cChannel, cChannelClient, sHost, sModes); } /** * Callback to all objects implementing the ChannelUserModeChanged Callback. * * @see IChannelUserModeChanged * @param cChannel Channel where modes were changed * @param cChangedClient Client being changed * @param cSetByClient Client chaning the modes (null if server) * @param sMode String representing mode change (ie +o) * @param sHost Host doing the mode changing (User host or server name) * @return true if a method was called, false otherwise */ protected boolean callChannelUserModeChanged(ChannelInfo cChannel, ChannelClientInfo cChangedClient, ChannelClientInfo cSetByClient, String sHost, String sMode) { return getCallbackManager().getCallbackType("OnChannelUserModeChanged").call(cChannel, cChangedClient, cSetByClient, sHost, sMode); } /** * Callback to all objects implementing the UserModeChanged Callback. * * @see IUserModeChanged * @param cClient Client that had the mode changed (almost always us) * @param sSetby Host that set the mode (us or servername) * @param sModes The modes set. * @return true if a method was called, false otherwise */ protected boolean callUserModeChanged(ClientInfo cClient, String sSetby, String sModes) { return getCallbackManager().getCallbackType("OnUserModeChanged").call(cClient, sSetby, sModes); } /** * Callback to all objects implementing the UserModeDiscovered Callback. * * @see IUserModeDiscovered * @param cClient Client that had the mode changed (almost always us) * @param sModes The modes set. * @return true if a method was called, false otherwise */ protected boolean callUserModeDiscovered(ClientInfo cClient, String sModes) { return getCallbackManager().getCallbackType("OnUserModeDiscovered").call(cClient, sModes); } /** * What does this IRCProcessor handle. * * @return String[] with the names of the tokens we handle. */ @Override public String[] handles() { return new String[]{"MODE", "324", "221"}; } /** * Create a new instance of the IRCProcessor Object. * * @param parser IRCParser That owns this IRCProcessor * @param manager ProcessingManager that is in charge of this IRCProcessor */ protected ProcessMode (IRCParser parser, ProcessingManager manager) { super(parser, manager); } }
true
true
public void processChanMode(String sParam, String token[], String sModestr[], String sChannelName) { StringBuilder sFullModeStr = new StringBuilder(); String sNonUserModeStr = ""; String sNonUserModeStrParams = ""; String sModeParam; String sTemp; int nParam = 1; long nTemp = 0, nValue = 0, nCurrent = 0; boolean bPositive = true, bBooleanMode = true; char cPositive = '+'; ChannelInfo iChannel; ChannelClientInfo iChannelClientInfo; ClientInfo iClient; ChannelClientInfo setterCCI; CallbackObject cbSingle = null; CallbackObject cbNonUser = null; if (!sParam.equals("324")) { cbSingle = getCallbackManager().getCallbackType("OnChannelSingleModeChanged"); cbNonUser = getCallbackManager().getCallbackType("OnChannelNonUserModeChanged"); } iChannel = getChannelInfo(sChannelName); if (iChannel == null) { // callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got modes for channel ("+sChannelName+") that I am not on.", myParser.getLastLine())); // iChannel = new ChannelInfo(myParser, sChannelName); // myParser.addChannel(iChannel); return; } // Get the current channel modes if (!sParam.equals("324")) { nCurrent = iChannel.getMode(); } setterCCI = iChannel.getUser(token[0]); if (IRCParser.ALWAYS_UPDATECLIENT && setterCCI != null) { // Facilitate dmdirc formatter if (setterCCI.getClient().getHost().isEmpty()) {setterCCI.getClient().setUserBits(token[0],false); } } // Loop through the mode string, and add/remove modes/params where they are needed for (int i = 0; i < sModestr[0].length(); ++i) { Character cMode = sModestr[0].charAt(i); if (cMode.equals(":".charAt(0))) { continue; } sNonUserModeStr = sNonUserModeStr+cMode; if (cMode.equals("+".charAt(0))) { cPositive = '+'; bPositive = true; } else if (cMode.equals("-".charAt(0))) { cPositive = '-'; bPositive = false; } else { if (myParser.hChanModesBool.containsKey(cMode)) { nValue = myParser.hChanModesBool.get(cMode); bBooleanMode = true; } else if (myParser.hChanModesOther.containsKey(cMode)) { nValue = myParser.hChanModesOther.get(cMode); bBooleanMode = false; } else if (myParser.hPrefixModes.containsKey(cMode)) { // (de) OP/Voice someone if (sModestr.length <= nParam) { myParser.callErrorInfo(new ParserError(ParserError.ERROR_FATAL + ParserError.ERROR_USER, "Broken Modes. Parameter required but not given.", myParser.getLastLine())); } sModeParam = sModestr[nParam++]; nValue = myParser.hPrefixModes.get(cMode); callDebugInfo(IRCParser.DEBUG_INFO, "User Mode: %c / %d [%s] {Positive: %b}",cMode, nValue, sModeParam, bPositive); iChannelClientInfo = iChannel.getUser(sModeParam); if (iChannelClientInfo == null) { // Client not known? // callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got mode for client not known on channel - Added", myParser.getLastLine())); iClient = getClientInfo(sModeParam); if (iClient == null) { // callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got mode for client not known at all - Added", myParser.getLastLine())); iClient = new ClientInfo(myParser, sModeParam); myParser.addClient(iClient); } iChannelClientInfo = iChannel.addClient(iClient); } callDebugInfo(IRCParser.DEBUG_INFO, "\tOld Mode Value: %d",iChannelClientInfo.getChanMode()); if (bPositive) { iChannelClientInfo.setChanMode(iChannelClientInfo.getChanMode() | nValue); sTemp = "+"; } else { iChannelClientInfo.setChanMode(iChannelClientInfo.getChanMode() ^ (iChannelClientInfo.getChanMode() & nValue)); sTemp = "-"; } sTemp = sTemp+cMode; callChannelUserModeChanged(iChannel, iChannelClientInfo, setterCCI, token[0], sTemp); continue; } else { // unknown mode - add as boolean // callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got unknown mode "+cMode+" - Added as boolean mode", myParser.getLastLine())); myParser.hChanModesBool.put(cMode,myParser.nNextKeyCMBool); nValue = myParser.nNextKeyCMBool; bBooleanMode = true; myParser.nNextKeyCMBool = myParser.nNextKeyCMBool*2; } if (bBooleanMode) { callDebugInfo(IRCParser.DEBUG_INFO, "Boolean Mode: %c [%d] {Positive: %b}",cMode, nValue, bPositive); if (bPositive) { nCurrent = nCurrent | nValue; } else { nCurrent = nCurrent ^ (nCurrent & nValue); } } else { if ((bPositive || nValue == IRCParser.MODE_LIST || ((nValue & IRCParser.MODE_UNSET) == IRCParser.MODE_UNSET)) && (sModestr.length <= nParam)) { myParser.callErrorInfo(new ParserError(ParserError.ERROR_FATAL + ParserError.ERROR_USER, "Broken Modes. Parameter required but not given.", myParser.getLastLine())); } if (nValue == IRCParser.MODE_LIST) { // List Mode sModeParam = sModestr[nParam++]; sNonUserModeStrParams = sNonUserModeStrParams+" "+sModeParam; nTemp = (Calendar.getInstance().getTimeInMillis() / 1000); iChannel.setListModeParam(cMode, new ChannelListModeItem(sModeParam, token[0], nTemp ), bPositive); callDebugInfo(IRCParser.DEBUG_INFO, "List Mode: %c [%s] {Positive: %b}",cMode, sModeParam, bPositive); if (cbSingle != null) { cbSingle.call(iChannel, setterCCI, token[0], cPositive+cMode+" "+sModeParam ); } } else { // Mode with a parameter if (bPositive) { // +Mode - always needs a parameter to set sModeParam = sModestr[nParam++]; sNonUserModeStrParams = sNonUserModeStrParams+" "+sModeParam; callDebugInfo(IRCParser.DEBUG_INFO, "Set Mode: %c [%s] {Positive: %b}",cMode, sModeParam, bPositive); iChannel.setModeParam(cMode,sModeParam); if (cbSingle != null) { cbSingle.call(iChannel, setterCCI, token[0], cPositive+cMode+" "+sModeParam ); } } else { // -Mode - parameter isn't always needed, we need to check if ((nValue & IRCParser.MODE_UNSET) == IRCParser.MODE_UNSET) { sModeParam = sModestr[nParam++]; sNonUserModeStrParams = sNonUserModeStrParams+" "+sModeParam; } else { sModeParam = ""; } callDebugInfo(IRCParser.DEBUG_INFO, "Unset Mode: %c [%s] {Positive: %b}",cMode, sModeParam, bPositive); iChannel.setModeParam(cMode,""); if (cbSingle != null) { cbSingle.call(iChannel, setterCCI, token[0], trim(cPositive+cMode+" "+sModeParam) ); } } } } } } // Call Callbacks for (int i = 0; i < sModestr.length; ++i) { sFullModeStr.append(sModestr[i]).append(" "); } iChannel.setMode(nCurrent); if (sParam.equals("324")) { callChannelModeChanged(iChannel, null, "", sFullModeStr.toString().trim()); }
public void processChanMode(String sParam, String token[], String sModestr[], String sChannelName) { StringBuilder sFullModeStr = new StringBuilder(); String sNonUserModeStr = ""; String sNonUserModeStrParams = ""; String sModeParam; String sTemp; int nParam = 1; long nTemp = 0, nValue = 0, nCurrent = 0; boolean bPositive = true, bBooleanMode = true; char cPositive = '+'; ChannelInfo iChannel; ChannelClientInfo iChannelClientInfo; ClientInfo iClient; ChannelClientInfo setterCCI; CallbackObject cbSingle = null; CallbackObject cbNonUser = null; if (!sParam.equals("324")) { cbSingle = getCallbackManager().getCallbackType("OnChannelSingleModeChanged"); cbNonUser = getCallbackManager().getCallbackType("OnChannelNonUserModeChanged"); } iChannel = getChannelInfo(sChannelName); if (iChannel == null) { // callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got modes for channel ("+sChannelName+") that I am not on.", myParser.getLastLine())); // iChannel = new ChannelInfo(myParser, sChannelName); // myParser.addChannel(iChannel); return; } // Get the current channel modes if (!sParam.equals("324")) { nCurrent = iChannel.getMode(); } setterCCI = iChannel.getUser(token[0]); if (IRCParser.ALWAYS_UPDATECLIENT && setterCCI != null) { // Facilitate dmdirc formatter if (setterCCI.getClient().getHost().isEmpty()) {setterCCI.getClient().setUserBits(token[0],false); } } // Loop through the mode string, and add/remove modes/params where they are needed for (int i = 0; i < sModestr[0].length(); ++i) { Character cMode = sModestr[0].charAt(i); if (cMode.equals(":".charAt(0))) { continue; } sNonUserModeStr = sNonUserModeStr+cMode; if (cMode.equals("+".charAt(0))) { cPositive = '+'; bPositive = true; } else if (cMode.equals("-".charAt(0))) { cPositive = '-'; bPositive = false; } else { if (myParser.hChanModesBool.containsKey(cMode)) { nValue = myParser.hChanModesBool.get(cMode); bBooleanMode = true; } else if (myParser.hChanModesOther.containsKey(cMode)) { nValue = myParser.hChanModesOther.get(cMode); bBooleanMode = false; } else if (myParser.hPrefixModes.containsKey(cMode)) { // (de) OP/Voice someone if (sModestr.length <= nParam) { myParser.callErrorInfo(new ParserError(ParserError.ERROR_FATAL + ParserError.ERROR_USER, "Broken Modes. Parameter required but not given.", myParser.getLastLine())); return; } sModeParam = sModestr[nParam++]; nValue = myParser.hPrefixModes.get(cMode); callDebugInfo(IRCParser.DEBUG_INFO, "User Mode: %c / %d [%s] {Positive: %b}",cMode, nValue, sModeParam, bPositive); iChannelClientInfo = iChannel.getUser(sModeParam); if (iChannelClientInfo == null) { // Client not known? // callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got mode for client not known on channel - Added", myParser.getLastLine())); iClient = getClientInfo(sModeParam); if (iClient == null) { // callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got mode for client not known at all - Added", myParser.getLastLine())); iClient = new ClientInfo(myParser, sModeParam); myParser.addClient(iClient); } iChannelClientInfo = iChannel.addClient(iClient); } callDebugInfo(IRCParser.DEBUG_INFO, "\tOld Mode Value: %d",iChannelClientInfo.getChanMode()); if (bPositive) { iChannelClientInfo.setChanMode(iChannelClientInfo.getChanMode() | nValue); sTemp = "+"; } else { iChannelClientInfo.setChanMode(iChannelClientInfo.getChanMode() ^ (iChannelClientInfo.getChanMode() & nValue)); sTemp = "-"; } sTemp = sTemp+cMode; callChannelUserModeChanged(iChannel, iChannelClientInfo, setterCCI, token[0], sTemp); continue; } else { // unknown mode - add as boolean // callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got unknown mode "+cMode+" - Added as boolean mode", myParser.getLastLine())); myParser.hChanModesBool.put(cMode,myParser.nNextKeyCMBool); nValue = myParser.nNextKeyCMBool; bBooleanMode = true; myParser.nNextKeyCMBool = myParser.nNextKeyCMBool*2; } if (bBooleanMode) { callDebugInfo(IRCParser.DEBUG_INFO, "Boolean Mode: %c [%d] {Positive: %b}",cMode, nValue, bPositive); if (bPositive) { nCurrent = nCurrent | nValue; } else { nCurrent = nCurrent ^ (nCurrent & nValue); } } else { if ((bPositive || nValue == IRCParser.MODE_LIST || ((nValue & IRCParser.MODE_UNSET) == IRCParser.MODE_UNSET)) && (sModestr.length <= nParam)) { myParser.callErrorInfo(new ParserError(ParserError.ERROR_FATAL + ParserError.ERROR_USER, "Broken Modes. Parameter required but not given.", myParser.getLastLine())); } if (nValue == IRCParser.MODE_LIST) { // List Mode sModeParam = sModestr[nParam++]; sNonUserModeStrParams = sNonUserModeStrParams+" "+sModeParam; nTemp = (Calendar.getInstance().getTimeInMillis() / 1000); iChannel.setListModeParam(cMode, new ChannelListModeItem(sModeParam, token[0], nTemp ), bPositive); callDebugInfo(IRCParser.DEBUG_INFO, "List Mode: %c [%s] {Positive: %b}",cMode, sModeParam, bPositive); if (cbSingle != null) { cbSingle.call(iChannel, setterCCI, token[0], cPositive+cMode+" "+sModeParam ); } } else { // Mode with a parameter if (bPositive) { // +Mode - always needs a parameter to set sModeParam = sModestr[nParam++]; sNonUserModeStrParams = sNonUserModeStrParams+" "+sModeParam; callDebugInfo(IRCParser.DEBUG_INFO, "Set Mode: %c [%s] {Positive: %b}",cMode, sModeParam, bPositive); iChannel.setModeParam(cMode,sModeParam); if (cbSingle != null) { cbSingle.call(iChannel, setterCCI, token[0], cPositive+cMode+" "+sModeParam ); } } else { // -Mode - parameter isn't always needed, we need to check if ((nValue & IRCParser.MODE_UNSET) == IRCParser.MODE_UNSET) { sModeParam = sModestr[nParam++]; sNonUserModeStrParams = sNonUserModeStrParams+" "+sModeParam; } else { sModeParam = ""; } callDebugInfo(IRCParser.DEBUG_INFO, "Unset Mode: %c [%s] {Positive: %b}",cMode, sModeParam, bPositive); iChannel.setModeParam(cMode,""); if (cbSingle != null) { cbSingle.call(iChannel, setterCCI, token[0], trim(cPositive+cMode+" "+sModeParam) ); } } } } } } // Call Callbacks for (int i = 0; i < sModestr.length; ++i) { sFullModeStr.append(sModestr[i]).append(" "); } iChannel.setMode(nCurrent); if (sParam.equals("324")) { callChannelModeChanged(iChannel, null, "", sFullModeStr.toString().trim()); }
diff --git a/org.modelexecution.fumldebug.debugger.uml2/src/org/modelexecution/fumldebug/debugger/uml2/provider/UML2ActivityProvider.java b/org.modelexecution.fumldebug.debugger.uml2/src/org/modelexecution/fumldebug/debugger/uml2/provider/UML2ActivityProvider.java index ebe6210..938c44d 100644 --- a/org.modelexecution.fumldebug.debugger.uml2/src/org/modelexecution/fumldebug/debugger/uml2/provider/UML2ActivityProvider.java +++ b/org.modelexecution.fumldebug.debugger.uml2/src/org/modelexecution/fumldebug/debugger/uml2/provider/UML2ActivityProvider.java @@ -1,113 +1,113 @@ /* * Copyright (c) 2012 Vienna University of Technology. * 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: * Philip Langer - initial API and implementation */ package org.modelexecution.fumldebug.debugger.uml2.provider; import java.util.Collection; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.modelexecution.fuml.convert.ConverterRegistry; import org.modelexecution.fuml.convert.IConversionResult; import org.modelexecution.fuml.convert.IConverter; import org.modelexecution.fumldebug.debugger.provider.IActivityProvider; import fUML.Syntax.Activities.IntermediateActivities.Activity; import fUML.Syntax.Classes.Kernel.NamedElement; public class UML2ActivityProvider implements IActivityProvider { private final ConverterRegistry converterRegistry = ConverterRegistry .getInstance(); private ResourceSet resourceSet; private Resource emfResource; private IFile iFile; private IConversionResult conversionResult; public UML2ActivityProvider(IResource iResource) { - if (iFile instanceof IFile && iFile.exists()) { + if (iResource instanceof IFile && iResource.exists()) { throw new IllegalArgumentException( "Resource is not a valid file or does not exist."); } this.iFile = (IFile) iResource; initializeResourceSet(); initializeResource(); } private void initializeResourceSet() { resourceSet = new ResourceSetImpl(); } private void initializeResource() { loadResource(); convertResource(); } private void loadResource() { emfResource = loadResource(iFile); } private Resource loadResource(IFile file) { return resourceSet.getResource(createURI(file), true); } private URI createURI(IFile file) { return URI.createURI("platform:/resource/" //$NON-NLS-1$ + file.getProject().getName() + "/" //$NON-NLS-1$ + file.getProjectRelativePath()); } private void convertResource() { IConverter converter = converterRegistry.getConverter(emfResource); conversionResult = converter.convert(emfResource); } @Override public IResource getResource() { return iFile; } @Override public Collection<Activity> getActivities() { return conversionResult.getActivities(); } @Override public Activity getActivity(String name) { for (Activity activity : conversionResult.getAllActivities()) { if (equalsName(name, activity)) { return activity; } } return null; } private boolean equalsName(String name, Activity activity) { return name.equals(activity.name) || name.equals(activity.qualifiedName); } @Override public String getSourceFileName(NamedElement namedElement) { return iFile.getName(); } @Override public void unload() { emfResource.unload(); } }
true
true
public UML2ActivityProvider(IResource iResource) { if (iFile instanceof IFile && iFile.exists()) { throw new IllegalArgumentException( "Resource is not a valid file or does not exist."); } this.iFile = (IFile) iResource; initializeResourceSet(); initializeResource(); }
public UML2ActivityProvider(IResource iResource) { if (iResource instanceof IFile && iResource.exists()) { throw new IllegalArgumentException( "Resource is not a valid file or does not exist."); } this.iFile = (IFile) iResource; initializeResourceSet(); initializeResource(); }
diff --git a/tests/org.eclipse.birt.report.engine.tests/test/org/eclipse/birt/report/engine/api/script/element/ElementTest.java b/tests/org.eclipse.birt.report.engine.tests/test/org/eclipse/birt/report/engine/api/script/element/ElementTest.java index a1d1968eb..f4cec43e0 100644 --- a/tests/org.eclipse.birt.report.engine.tests/test/org/eclipse/birt/report/engine/api/script/element/ElementTest.java +++ b/tests/org.eclipse.birt.report.engine.tests/test/org/eclipse/birt/report/engine/api/script/element/ElementTest.java @@ -1,1102 +1,1102 @@ /******************************************************************************* * Copyright (c) 2005 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.engine.api.script.element; import junit.framework.TestCase; import org.eclipse.birt.report.engine.api.script.ScriptException; import org.eclipse.birt.report.engine.script.internal.element.ActionImpl; import org.eclipse.birt.report.engine.script.internal.element.Cell; import org.eclipse.birt.report.engine.script.internal.element.DataItem; import org.eclipse.birt.report.engine.script.internal.element.DataSet; import org.eclipse.birt.report.engine.script.internal.element.DataSource; import org.eclipse.birt.report.engine.script.internal.element.DynamicText; import org.eclipse.birt.report.engine.script.internal.element.Grid; import org.eclipse.birt.report.engine.script.internal.element.Group; import org.eclipse.birt.report.engine.script.internal.element.HideRuleImpl; import org.eclipse.birt.report.engine.script.internal.element.HighlightRuleImpl; import org.eclipse.birt.report.engine.script.internal.element.Image; import org.eclipse.birt.report.engine.script.internal.element.Label; import org.eclipse.birt.report.engine.script.internal.element.List; import org.eclipse.birt.report.engine.script.internal.element.Listing; import org.eclipse.birt.report.engine.script.internal.element.ReportItem; import org.eclipse.birt.report.engine.script.internal.element.Row; import org.eclipse.birt.report.engine.script.internal.element.StyleDesign; import org.eclipse.birt.report.engine.script.internal.element.Table; import org.eclipse.birt.report.engine.script.internal.element.TextItem; import org.eclipse.birt.report.model.api.ActionHandle; import org.eclipse.birt.report.model.api.CellHandle; import org.eclipse.birt.report.model.api.DataItemHandle; import org.eclipse.birt.report.model.api.DataSetHandle; import org.eclipse.birt.report.model.api.DataSourceHandle; import org.eclipse.birt.report.model.api.DesignConfig; import org.eclipse.birt.report.model.api.DesignEngine; import org.eclipse.birt.report.model.api.ElementFactory; import org.eclipse.birt.report.model.api.GridHandle; import org.eclipse.birt.report.model.api.GroupHandle; import org.eclipse.birt.report.model.api.HideRuleHandle; import org.eclipse.birt.report.model.api.ImageHandle; import org.eclipse.birt.report.model.api.LabelHandle; import org.eclipse.birt.report.model.api.ListHandle; import org.eclipse.birt.report.model.api.ReportDesignHandle; import org.eclipse.birt.report.model.api.RowHandle; import org.eclipse.birt.report.model.api.SessionHandle; import org.eclipse.birt.report.model.api.SharedStyleHandle; import org.eclipse.birt.report.model.api.StructureFactory; import org.eclipse.birt.report.model.api.StyleHandle; import org.eclipse.birt.report.model.api.TableHandle; import org.eclipse.birt.report.model.api.TextDataHandle; import org.eclipse.birt.report.model.api.TextItemHandle; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants; import org.eclipse.birt.report.model.api.elements.structures.Action; import org.eclipse.birt.report.model.api.elements.structures.ComputedColumn; import org.eclipse.birt.report.model.api.elements.structures.FilterCondition; import org.eclipse.birt.report.model.api.elements.structures.HideRule; import org.eclipse.birt.report.model.api.elements.structures.HighlightRule; import org.eclipse.birt.report.model.api.elements.structures.SortKey; import com.ibm.icu.util.ULocale; /** * Tests the report element representations in the scripting environment. * Basically tests that all getters/setter correspond correctly to each other * (setFoo("foo") -> getFoo() should return "foo"). * */ public class ElementTest extends TestCase { private static final String TARGET_WINDOW = "targetWindow"; private static final String REPORT_NAME = "reportName"; private static final int Y1 = 40; private static final int X1 = 30; private static final int WIDTH1 = 20; private static final String IN = "in"; private static final int HEIGHT1 = 10; private static final String GRID = "Grid"; private static final String CONTENT_KEY = "contentKey"; private static final String TEXT_CONTENT = "textContent"; private static final String TEXT_ITEM = "TextItem"; private static final String CAPTION_KEY = "captionKey"; private static final String CAPTION = "caption"; private static final String TABLE = "Table"; private static final String WORD_SPACING = "21px"; private static final String WINDOWS = "6"; private static final String TEXT_INDENT = "20px"; private static final String STRINGFORMAT = "stringformat"; private static final String PADDING_TOP = "19pt"; private static final String PADDING_RIGHT = "18pt"; private static final String PADDING_LEFT = "17pt"; private static final String PADDING_BOTTOM = "16pt"; private static final String ORPHANS = "5"; private static final String MASTER_PAGE = "masterPage"; private static final String MARGIN_TOP = "15pt"; private static final String MARGIN_RIGHT = "14pt"; private static final String MARGIN_LEFT = "13pt"; private static final String MARGIN_BOTTOM = "12pt"; private static final String LINE_HEIGHT = "11pt"; private static final String LETTER_SPACING = "10pt"; private static final String FONT_SIZE = "20pt"; private static final String YY_MM_DD = "YY-MM-DD"; private static final String WHITE = "white"; private static final String BORDER_TOP_WIDTH = "15px"; private static final String GRAY = "gray"; private static final String BORDER_RIGHT_WIDTH = "14px"; private static final String YELLOW = "yellow"; private static final String BORDER_LEFT_WIDTH = "13px"; private static final String GREEN = "green"; private static final String BORDER_BOTTOM_WIDTH = "12px"; private static final String BLUE = "blue"; private static final String BACKGROUND_POSITION_Y = "11px"; private static final String BACKGROUND_POSITION_X = "10px"; private static final String IMAGE_URL = "imageUrl"; private static final String RED = "red"; private static final String STYLE = "Style"; private static final String LIST = "List"; private static final String VALUE_EXPRESSION = "valueExpression"; private static final String URI = "URI"; private static final String IMAGE_NAME = "imageName"; private static final String IMAGE = "Image"; private static final double INTERVAL_RANGE = 11.5; private static final String INTERVAL_BASE = "2000"; private static final String YEAR = "year"; private static final String TEST = "test"; private static final String TEXT_DATA = "TextData"; private static final String DATA_SOURCE = "DataSource"; private static final String QUERY = "query"; private static final String VALUE = "value"; private static final String KEY = "key"; private static final String TEXT_KEY = "textKey"; private static final String TEXT = "text"; private static final String HELP_TEXT_KEY = "helpTextKey"; private static final String HELP_TEXT = "helpText"; private static final String LABEL = "Label"; private static final String Y2 = "40cm"; private static final String X2 = "30cm"; private static final String TOC = "TOC"; private static final String WIDTH2 = "20cm"; private static final String HEIGHT2 = "10cm"; private static final String BOOKMARK = "bookmark"; private static final String USER_PROP = "userProp"; private static final String USER_PROP2 = "userProp2"; private static final String INTEGER = "integer"; private static final String USER_PROP1 = "userProp1"; private static final String EXPRESSION = "expression"; private static final String NAMED_EXPRESSION = "namedExpression"; private static final String NAME = "name"; private static final String DISPLAY_NAME_KEY = "displayNameKey"; private static final String DISPLAY_NAME = "displayName"; private static final String XML = "<xml/>"; private static final String COMMENTS = "comments"; private static final String IMAGE_FILE = "imageFile"; private ElementFactory factory; private ReportDesignHandle designHandle; public void setUp( ) { SessionHandle sessionHandle = new DesignEngine( new DesignConfig( ) ) .newSessionHandle( ULocale.ENGLISH ); designHandle = sessionHandle.createDesign( ); factory = new ElementFactory( designHandle.getModule( ) ); } private void doTestAction( LabelHandle handle ) throws SemanticException, ScriptException { ActionHandle actionHandle = handle.setAction( new Action( ) ); IAction action = new ActionImpl( actionHandle, handle ); action.setFormatType( DesignChoiceConstants.ACTION_FORMAT_TYPE_HTML ); assertEquals( DesignChoiceConstants.ACTION_FORMAT_TYPE_HTML, action .getFormatType( ) ); action .setLinkType( DesignChoiceConstants.ACTION_LINK_TYPE_DRILL_THROUGH ); assertEquals( DesignChoiceConstants.ACTION_LINK_TYPE_DRILL_THROUGH, action.getLinkType( ) ); action.setReportName( REPORT_NAME ); assertEquals( REPORT_NAME, action.getReportName( ) ); action.setTargetBookmark( BOOKMARK ); assertEquals( BOOKMARK, action.getTargetBookmark( ) ); action.setTargetWindow( TARGET_WINDOW ); assertEquals( TARGET_WINDOW, action.getTargetWindow( ) ); // Set to hyperlink so getURI not return null action.setLinkType( DesignChoiceConstants.ACTION_LINK_TYPE_HYPERLINK ); action.setURI( URI ); assertEquals( URI, action.getURI( ) ); } private void doTestReportElement( IReportElement element ) throws ScriptException { element.setComments( COMMENTS ); assertEquals( COMMENTS, element.getComments( ) ); element.setCustomXml( XML ); assertEquals( XML, element.getCustomXml( ) ); element.setDisplayName( DISPLAY_NAME ); assertEquals( DISPLAY_NAME, element.getDisplayName( ) ); element.setDisplayNameKey( DISPLAY_NAME_KEY ); assertEquals( DISPLAY_NAME_KEY, element.getDisplayNameKey( ) ); element.setName( NAME ); assertEquals( NAME, element.getName( ) ); element.setNamedExpression( NAMED_EXPRESSION, EXPRESSION ); assertEquals( EXPRESSION, element.getNamedExpression( NAMED_EXPRESSION ) ); element.setUserProperty( USER_PROP1, new Integer( 1 ), INTEGER ); assertEquals( new Integer( 1 ), element.getUserProperty( USER_PROP1 ) ); element.setUserProperty( USER_PROP2, USER_PROP ); assertEquals( USER_PROP, element.getUserProperty( USER_PROP2 ) ); } private void doTestReportItem( IReportItem item ) throws ScriptException { item.setBookmark( BOOKMARK ); assertEquals( BOOKMARK, item.getBookmark( ) ); item.setHeight( HEIGHT1 ); assertEquals( HEIGHT1 + IN, item.getHeight( ) ); item.setHeight( HEIGHT2 ); assertEquals( HEIGHT2, item.getHeight( ) ); item.setWidth( WIDTH1 ); assertEquals( WIDTH1 + IN, item.getWidth( ) ); item.setWidth( WIDTH2 ); assertEquals( WIDTH2, item.getWidth( ) ); item.setTocExpression( TOC ); assertEquals( TOC, item.getTocExpression( ) ); item.setX( X1 ); assertEquals( X1 + IN, item.getX( ) ); item.setX( X2 ); assertEquals( X2, item.getX( ) ); item.setY( Y1 ); assertEquals( Y1 + IN, item.getY( ) ); item.setY( Y2 ); assertEquals( Y2, item.getY( ) ); } public void testLabel( ) throws ScriptException, SemanticException { LabelHandle labelHandle = factory.newLabel( LABEL ); ILabel label = new Label( labelHandle ); doTestReportElement( label ); doTestReportItem( label ); doTestAction( labelHandle ); label.setHelpText( HELP_TEXT ); assertEquals( HELP_TEXT, label.getHelpText( ) ); label.setHelpTextKey( HELP_TEXT_KEY ); assertEquals( HELP_TEXT_KEY, label.getHelpTextKey( ) ); label.setText( TEXT ); assertEquals( TEXT, label.getText( ) ); label.setTextKey( TEXT_KEY ); assertEquals( TEXT_KEY, label.getTextKey( ) ); } public void testCell( ) throws ScriptException { CellHandle cellHandle = factory.newCell( ); ICell cell = new Cell( cellHandle ); cell.setColumn( 2 ); assertEquals( 2, cell.getColumn( ) ); assertEquals( 1, cell.getColumnSpan( ) ); cell.setDrop( DesignChoiceConstants.DROP_TYPE_ALL ); assertEquals( DesignChoiceConstants.DROP_TYPE_ALL, cell.getDrop( ) ); assertEquals( 1, cell.getRowSpan( ) ); } public void testDataItem( ) throws ScriptException { DataItemHandle dataHandle = factory.newDataItem( "DataItem" ); IDataItem data = new DataItem( dataHandle ); data.setHelpText( HELP_TEXT ); assertEquals( HELP_TEXT, data.getHelpText( ) ); data.setHelpTextKey( HELP_TEXT_KEY ); assertEquals( HELP_TEXT_KEY, data.getHelpTextKey( ) ); } /** * Test <code>IDataBinding</code> method. * * @throws ScriptException * @throws SemanticException */ public void testDataBinding( ) throws ScriptException, SemanticException { TableHandle tableHandle = factory.newTableItem( "table", 3 );//$NON-NLS-1$ designHandle.getBody( ).add( tableHandle ); ComputedColumn column = StructureFactory.newComputedColumn( tableHandle, "column1" );//$NON-NLS-1$ column.setExpression( "row[\"123\"]" );//$NON-NLS-1$ tableHandle.addColumnBinding( column, true ); ComputedColumn column2 = StructureFactory.newComputedColumn( tableHandle, "column2" );//$NON-NLS-1$ column2.setExpression( "row[\"234\"]" );//$NON-NLS-1$ tableHandle.addColumnBinding( column2, true ); IReportItem item = new ReportItem( tableHandle ); IDataBinding[] bindings = item.getDataBindings( ); assertEquals( 2, bindings.length ); IDataBinding binding = bindings[0]; IDataBinding binding2 = bindings[1]; assertEquals( "column1", binding.getName( ) );//$NON-NLS-1$ assertEquals( "column2", binding2.getName( ) );//$NON-NLS-1$ binding.setAggregateOn( "11" ); //$NON-NLS-1$ assertEquals( "11", binding.getAggregateOn( ) ); //$NON-NLS-1$ binding.setDataType( "any" ); //$NON-NLS-1$ assertEquals( "any", binding.getDataType( ) ); //$NON-NLS-1$ binding.setExpression( "row[\"123\"]" ); //$NON-NLS-1$ assertEquals( "row[\"123\"]", binding.getExpression( ) ); //$NON-NLS-1$ assertEquals( "column1", binding.getName( ) ); //$NON-NLS-1$ assertEquals( "row[\"234\"]", item.getDataBinding( "column2" ) );//$NON-NLS-1$//$NON-NLS-2$ } /** * Tests addColumnBinding , addHighLightRule , addHideRule , * addFilterCondition , addSortCondition. * * @throws SemanticException * @throws ScriptException */ public void testAddFunction( ) throws SemanticException, ScriptException { TableHandle tableHandle = factory.newTableItem( "table", 3 );//$NON-NLS-1$ designHandle.getBody( ).add( tableHandle ); IDataBinding binding = StructureScriptAPIFactory.createDataBinding( ); binding.setExpression( "expression" );//$NON-NLS-1$ binding.setName( "name" );//$NON-NLS-1$ IListing item = new Listing( tableHandle ); item.addDataBinding( binding ); IDataBinding binding2 = StructureScriptAPIFactory .createDataBinding( ); try { item.addDataBinding( binding2 ); fail( ); } catch ( ScriptException e ) { // We want an exception here } RowHandle rowHandle = (RowHandle) tableHandle.getFooter( ) .getContents( ).get( 0 ); IRow row = new Row( rowHandle ); IHighlightRule highlight = StructureScriptAPIFactory .createHighLightRule( ); row.addHighlightRule( highlight ); IHideRule hideRule = StructureScriptAPIFactory.createHideRule( ); item.addHideRule( hideRule ); IFilterCondition filter = StructureScriptAPIFactory .createFilterCondition( ); try { item.addFilterCondition( filter ); fail( ); } catch ( ScriptException e ) { // We want an exception here } filter.setExpr( "expr" );//$NON-NLS-1$ item.addFilterCondition( filter ); ISortCondition sort = StructureScriptAPIFactory.createSortCondition( ); try { item.addSortCondition( sort ); fail( ); } catch ( ScriptException e ) { // We want an exception here } sort.setKey( "key" );//$NON-NLS-1$ item.addSortCondition( sort ); } /** * Test <code>IHighLightRule</code> * * @throws SemanticException * @throws ScriptException */ public void testHighLightRule( ) throws SemanticException, ScriptException { TableHandle tableHandle = factory.newTableItem( "table", 3 );//$NON-NLS-1$ designHandle.getBody( ).add( tableHandle ); HighlightRule rule = StructureFactory.createHighlightRule( ); SharedStyleHandle style = factory.newStyle( "Style" );//$NON-NLS-1$ style.getPropertyHandle( "highlightRules" ).addItem( rule );//$NON-NLS-1$ designHandle.getStyles( ).add( style ); tableHandle.setStyle( style ); RowHandle rowHandle = (RowHandle) tableHandle.getHeader( ).get( 0 ); IRow item = new Row( rowHandle ); IHighlightRule iRule = new HighlightRuleImpl( rule ); item.addHighlightRule( iRule ); IHighlightRule[] rules = item.getHighlightRules( ); assertEquals( 1, rules.length ); iRule = rules[0]; iRule.setColor( "red" ); //$NON-NLS-1$ assertEquals( "red", iRule.getColor( ) ); //$NON-NLS-1$ iRule.setDateTimeFormat( "mm dd, yyyy" );//$NON-NLS-1$ assertEquals( "mm dd, yyyy", iRule.getDateTimeFormat( ) ); //$NON-NLS-1$ iRule.setFontStyle( "oblique" );//$NON-NLS-1$ assertEquals( "oblique", iRule.getFontStyle( ) ); //$NON-NLS-1$ iRule.setFontWeight( "900" );//$NON-NLS-1$ assertEquals( "900", iRule.getFontWeight( ) ); //$NON-NLS-1$ iRule.setStringFormat( "no format" );//$NON-NLS-1$ assertEquals( "no format", iRule.getStringFormat( ) ); //$NON-NLS-1$ iRule.setTestExpression( "expression" );//$NON-NLS-1$ assertEquals( "expression", iRule.getTestExpression( ) ); //$NON-NLS-1$ iRule.setColor( "#FFFFFF" );//$NON-NLS-1$ assertEquals( "#FFFFFF", iRule.getColor( ) );//$NON-NLS-1$ iRule.setOperator( "between" );//$NON-NLS-1$ assertEquals( "between", iRule.getOperator( ) );//$NON-NLS-1$ iRule.setValue1( "100" );//$NON-NLS-1$ assertEquals( "100", iRule.getValue1( ) );//$NON-NLS-1$ iRule.setValue2( "300" );//$NON-NLS-1$ assertEquals( "300", iRule.getValue2( ) );//$NON-NLS-1$ iRule.setBackGroundColor( "#FF0000" );//$NON-NLS-1$ assertEquals( "#FF0000", iRule.getBackGroundColor( ) );//$NON-NLS-1$ item.removeHighlightRules( ); rules = item.getHighlightRules( ); assertEquals( 0, rules.length ); } /** * Test <code>IFilterCondition</code> * * @throws SemanticException * @throws ScriptException */ public void testFilterCondition( ) throws SemanticException, ScriptException { TableHandle tableHandle = factory.newTableItem( "table", 3 );//$NON-NLS-1$ designHandle.getBody( ).add( tableHandle ); FilterCondition cond = StructureFactory.createFilterCond( ); cond.setExpr( "inner join" );//$NON-NLS-1$ tableHandle.getPropertyHandle( "filter" ).addItem( cond );//$NON-NLS-1$ IListing item = new Listing( tableHandle ); IFilterCondition[] conds = item.getFilterConditions( ); assertEquals( 1, conds.length ); IFilterCondition iFilter = conds[0]; assertEquals( "eq", iFilter.getOperator( ) );//$NON-NLS-1$ iFilter.setOperator( "between" ); //$NON-NLS-1$ assertEquals( "between", iFilter.getOperator( ) ); //$NON-NLS-1$ iFilter.setValue1( "1" ); //$NON-NLS-1$ assertEquals( "1", iFilter.getValue1( ) ); //$NON-NLS-1$ iFilter.setValue2( "100" ); //$NON-NLS-1$ assertEquals( "100", iFilter.getValue2( ) ); //$NON-NLS-1$ } /** * Test <code>ISortCondition</code> * * @throws SemanticException * @throws ScriptException */ public void testSortCondition( ) throws SemanticException, ScriptException { TableHandle tableHandle = factory.newTableItem( "table", 3 );//$NON-NLS-1$ designHandle.getBody( ).add( tableHandle ); SortKey sort = StructureFactory.createSortKey( ); sort.setKey( "key" );//$NON-NLS-1$ tableHandle.getPropertyHandle( "sort" ).addItem( sort );//$NON-NLS-1$ IListing item = new Listing( tableHandle ); ISortCondition[] sorts = item.getSortConditions( ); assertEquals( 1, sorts.length ); ISortCondition iSort = sorts[0]; assertEquals( "key", iSort.getKey( ) );//$NON-NLS-1$ iSort.setDirection( "desc" ); //$NON-NLS-1$ assertEquals( "desc", iSort.getDirection( ) ); //$NON-NLS-1$ iSort.setKey( "1" ); //$NON-NLS-1$ assertEquals( "1", iSort.getKey( ) ); //$NON-NLS-1$ } /** * Test <code>IHideRule</code> * * @throws SemanticException * @throws ScriptException */ public void testHideRule( ) throws SemanticException, ScriptException { TableHandle tableHandle = factory.newTableItem( "table", 3 );//$NON-NLS-1$ designHandle.getBody( ).add( tableHandle ); HideRule hide = StructureFactory.createHideRule( ); hide.setFormat( "format" );//$NON-NLS-1$ HideRuleHandle hideHandle = (HideRuleHandle) tableHandle .getPropertyHandle( "visibility" ).addItem( hide );//$NON-NLS-1$ HideRule hide2 = StructureFactory.createHideRule( ); hide2.setExpression( "expr2" );//$NON-NLS-1$ hide2.setFormat( "format" );//$NON-NLS-1$ tableHandle.getPropertyHandle( "visibility" ).addItem( hide2 );//$NON-NLS-1$ IReportItem item = new ReportItem( tableHandle ); IHideRule[] rules = item.getHideRules( ); assertEquals( 2, rules.length ); IHideRule iHide = new HideRuleImpl( hideHandle ); assertEquals( "format", iHide.getFormat( ) ); //$NON-NLS-1$ iHide.setValueExpr( "valueExpr" ); //$NON-NLS-1$ assertEquals( "valueExpr", iHide.getValueExpr( ) ); //$NON-NLS-1$ item.removeHideRule( iHide ); rules = item.getHideRules( ); assertEquals( 1, rules.length ); } public void testDataSet( ) throws ScriptException { DataSetHandle dataSetHandle = factory.newOdaDataSet( "DataSet", null ); IDataSet dataSet = new DataSet( dataSetHandle ); dataSet.setPrivateDriverProperty( KEY, VALUE ); assertEquals( VALUE, dataSet.getPrivateDriverProperty( KEY ) ); dataSet.setQueryText( QUERY ); assertEquals( QUERY, dataSet.getQueryText( ) ); } public void testDataSource( ) throws ScriptException { DataSourceHandle dataSourceHandle = factory.newOdaDataSource( DATA_SOURCE, null ); IDataSource dataSource = new DataSource( dataSourceHandle ); dataSource.setPrivateDriverProperty( KEY, VALUE ); assertEquals( VALUE, dataSource.getPrivateDriverProperty( KEY ) ); } public void testDynamicText( ) throws ScriptException { TextDataHandle textDataHandle = factory.newTextData( TEXT_DATA ); IDynamicText dynamicText = new DynamicText( textDataHandle ); dynamicText .setContentType( DesignChoiceConstants.TEXT_CONTENT_TYPE_HTML ); assertEquals( DesignChoiceConstants.TEXT_CONTENT_TYPE_HTML, dynamicText .getContentType( ) ); try { dynamicText.setContentType( TEST ); fail( "\"test\" should not be a valid content type" ); } catch ( ScriptException e ) { // We want an exception here, since "test" should not be a valid // content type } dynamicText.setValueExpr( EXPRESSION ); assertEquals( EXPRESSION, dynamicText.getValueExpr( ) ); } public void testGrid( ) throws ScriptException { GridHandle gridHandle = factory.newGridItem( GRID ); new Grid( gridHandle ); // No methods on IGrid to test... } public void testGroup( ) throws ScriptException { GroupHandle groupHandle = factory.newTableGroup( ); IGroup group = new Group( groupHandle ); group.setInterval( YEAR ); assertEquals( YEAR, group.getInterval( ) ); group.setIntervalBase( INTERVAL_BASE ); assertEquals( INTERVAL_BASE, group.getIntervalBase( ) ); group.setIntervalRange( INTERVAL_RANGE ); assertTrue( INTERVAL_RANGE == group.getIntervalRange( ) ); group.setKeyExpr( EXPRESSION ); assertEquals( EXPRESSION, group.getKeyExpr( ) ); group.setName( NAME ); assertEquals( NAME, group.getName( ) ); group.setSortDirection( DesignChoiceConstants.SORT_DIRECTION_DESC ); assertEquals( DesignChoiceConstants.SORT_DIRECTION_DESC, group .getSortDirection( ) ); try { group.setSortDirection( TEST ); fail( "\"test\" should not be a valid sort direction" ); } catch ( ScriptException e ) { // We want an exception here, since "test" should not be a valid // sort direction } group.setTocExpression( TOC ); assertEquals( TOC, group.getTocExpression( ) ); group.setHideDetail( true ); assertTrue( group.getHideDetail( )); } public void testImage( ) throws ScriptException { ImageHandle imageHandle = factory.newImage( IMAGE ); IImage image = new Image( imageHandle ); image.setHelpText( HELP_TEXT ); assertEquals( HELP_TEXT, image.getHelpText( ) ); image.setHelpTextKey( HELP_TEXT_KEY ); assertEquals( HELP_TEXT_KEY, image.getHelpTextKey( ) ); image.setImageName( IMAGE_NAME ); assertEquals( IMAGE_NAME, image.getImageName( ) ); image.setScale( 50.5 ); assertTrue( 50.5 == image.getScale( ) ); image.setSize( DesignChoiceConstants.IMAGE_SIZE_SCALE_TO_ITEM ); assertEquals( DesignChoiceConstants.IMAGE_SIZE_SCALE_TO_ITEM, image .getSize( ) ); try { image.setSize( TEST ); fail( "\"test\" should not be a valid sizing method" ); } catch ( ScriptException e ) { // We want an exception here, since "test" should not be a valid // sizing method } image.setSource( DesignChoiceConstants.IMAGE_REF_TYPE_URL ); assertEquals( DesignChoiceConstants.IMAGE_REF_TYPE_URL, image .getSource( ) ); try { image.setSource( TEST ); fail( "\"test\" should not be a valid image source" ); } catch ( ScriptException e ) { // We want an exception here, since "test" should not be a valid // image source } image.setTypeExpression( EXPRESSION ); assertEquals( EXPRESSION, image.getTypeExpression( ) ); image.setValueExpression( VALUE_EXPRESSION ); assertEquals( VALUE_EXPRESSION, image.getValueExpression( ) ); image.setURL( IMAGE_URL ); assertEquals( IMAGE_URL, image.getURL( ) ); image.setFile( IMAGE_FILE ); assertEquals( IMAGE_FILE, image.getFile( ) ); } public void testList( ) throws ScriptException { ListHandle listHandle = factory.newList( LIST ); new List( listHandle ); // No methods to test on IList } public void testRow( ) throws ScriptException { RowHandle rowHandle = factory.newTableRow( ); IRow row = new Row( rowHandle ); row.setBookmark( BOOKMARK ); assertEquals( BOOKMARK, row.getBookmark( ) ); } public void testStyle( ) throws ScriptException { StyleHandle styleHandle = factory.newStyle( STYLE ); IScriptStyleDesign style = new StyleDesign( styleHandle ); style .setBackgroundAttachment( DesignChoiceConstants.BACKGROUND_ATTACHMENT_SCROLL ); assertEquals( DesignChoiceConstants.BACKGROUND_ATTACHMENT_SCROLL, style .getBackgroundAttachment( ) ); style.setBackgroundColor( RED ); assertEquals( RED, style.getBackgroundColor( ) ); style.setBackgroundImage( IMAGE_URL ); assertEquals( IMAGE_URL, style.getBackgroundImage( ) ); style.setBackGroundPositionX( BACKGROUND_POSITION_X ); assertEquals( BACKGROUND_POSITION_X, style.getBackGroundPositionX( ) ); style.setBackGroundPositionY( BACKGROUND_POSITION_Y ); assertEquals( BACKGROUND_POSITION_Y, style.getBackGroundPositionY( ) ); style .setBackgroundRepeat( DesignChoiceConstants.BACKGROUND_REPEAT_REPEAT ); assertEquals( DesignChoiceConstants.BACKGROUND_REPEAT_REPEAT, style .getBackgroundRepeat( ) ); style.setBorderBottomColor( BLUE ); assertEquals( BLUE, style.getBorderBottomColor( ) ); style.setBorderBottomStyle( DesignChoiceConstants.LINE_STYLE_SOLID ); assertEquals( DesignChoiceConstants.LINE_STYLE_SOLID, style .getBorderBottomStyle( ) ); style.setBorderBottomWidth( BORDER_BOTTOM_WIDTH ); assertEquals( BORDER_BOTTOM_WIDTH, style.getBorderBottomWidth( ) ); style.setBorderLeftColor( GREEN ); assertEquals( GREEN, style.getBorderLeftColor( ) ); style.setBorderLeftStyle( DesignChoiceConstants.LINE_STYLE_DOTTED ); assertEquals( DesignChoiceConstants.LINE_STYLE_DOTTED, style .getBorderLeftStyle( ) ); style.setBorderLeftWidth( BORDER_LEFT_WIDTH ); assertEquals( BORDER_LEFT_WIDTH, style.getBorderLeftWidth( ) ); style.setBorderRightColor( YELLOW ); assertEquals( YELLOW, style.getBorderRightColor( ) ); style.setBorderRightStyle( DesignChoiceConstants.LINE_STYLE_DASHED ); assertEquals( DesignChoiceConstants.LINE_STYLE_DASHED, style .getBorderRightStyle( ) ); style.setBorderRightWidth( BORDER_RIGHT_WIDTH ); assertEquals( BORDER_RIGHT_WIDTH, style.getBorderRightWidth( ) ); style.setBorderTopColor( GRAY ); assertEquals( GRAY, style.getBorderTopColor( ) ); style.setBorderTopStyle( DesignChoiceConstants.LINE_STYLE_DOUBLE ); assertEquals( DesignChoiceConstants.LINE_STYLE_DOUBLE, style .getBorderTopStyle( ) ); style.setBorderTopWidth( BORDER_TOP_WIDTH ); assertEquals( BORDER_TOP_WIDTH, style.getBorderTopWidth( ) ); style.setCanShrink( true ); assertTrue( style.canShrink( ) ); style.setColor( WHITE ); assertEquals( WHITE, style.getColor( ) ); style.setDateTimeFormat( YY_MM_DD ); assertEquals( YY_MM_DD, style.getDateTimeFormat( ) ); style .setDateTimeFormatCategory( DesignChoiceConstants.DATETIEM_FORMAT_TYPE_MUDIUM_DATE ); assertEquals( DesignChoiceConstants.DATETIEM_FORMAT_TYPE_MUDIUM_DATE, style.getDateTimeFormatCategory( ) ); style.setDisplay( DesignChoiceConstants.DISPLAY_INLINE ); assertEquals( DesignChoiceConstants.DISPLAY_INLINE, style.getDisplay( ) ); style.setFontFamily( DesignChoiceConstants.FONT_FAMILY_SANS_SERIF ); assertEquals( DesignChoiceConstants.FONT_FAMILY_SANS_SERIF, style .getFontFamily( ) ); style.setFontSize( FONT_SIZE ); assertEquals( FONT_SIZE, style.getFontSize( ) ); style.setFontStyle( DesignChoiceConstants.FONT_STYLE_ITALIC ); assertEquals( DesignChoiceConstants.FONT_STYLE_ITALIC, style .getFontStyle( ) ); style.setFontVariant( DesignChoiceConstants.FONT_VARIANT_SMALL_CAPS ); assertEquals( DesignChoiceConstants.FONT_VARIANT_SMALL_CAPS, style .getFontVariant( ) ); style.setFontWeight( DesignChoiceConstants.FONT_WEIGHT_BOLD ); assertEquals( DesignChoiceConstants.FONT_WEIGHT_BOLD, style .getFontWeight( ) ); style.setLetterSpacing( LETTER_SPACING ); assertEquals( LETTER_SPACING, style.getLetterSpacing( ) ); style.setLineHeight( LINE_HEIGHT ); assertEquals( LINE_HEIGHT, style.getLineHeight( ) ); style.setMarginBottom( MARGIN_BOTTOM ); assertEquals( MARGIN_BOTTOM, style.getMarginBottom( ) ); style.setMarginLeft( MARGIN_LEFT ); assertEquals( MARGIN_LEFT, style.getMarginLeft( ) ); style.setMarginRight( MARGIN_RIGHT ); assertEquals( MARGIN_RIGHT, style.getMarginRight( ) ); style.setMarginTop( MARGIN_TOP ); assertEquals( MARGIN_TOP, style.getMarginTop( ) ); style.setMasterPage( MASTER_PAGE ); assertEquals( MASTER_PAGE, style.getMasterPage( ) ); style .setNumberFormat( DesignChoiceConstants.NUMBER_FORMAT_TYPE_CURRENCY ); assertEquals( DesignChoiceConstants.NUMBER_FORMAT_TYPE_CURRENCY, style .getNumberFormat( ) ); style .setNumberFormatCategory( DesignChoiceConstants.NUMBER_FORMAT_TYPE_PERCENT ); assertEquals( DesignChoiceConstants.NUMBER_FORMAT_TYPE_PERCENT, style .getNumberFormatCategory( ) ); style.setOrphans( ORPHANS ); assertEquals( ORPHANS, style.getOrphans( ) ); style.setPaddingBottom( PADDING_BOTTOM ); assertEquals( PADDING_BOTTOM, style.getPaddingBottom( ) ); style.setPaddingLeft( PADDING_LEFT ); assertEquals( PADDING_LEFT, style.getPaddingLeft( ) ); style.setPaddingRight( PADDING_RIGHT ); assertEquals( PADDING_RIGHT, style.getPaddingRight( ) ); style.setPaddingTop( PADDING_TOP ); assertEquals( PADDING_TOP, style.getPaddingTop( ) ); - style.setPageBreakAfter( DesignChoiceConstants.PAGE_BREAK_AFTER_AVOID ); - assertEquals( DesignChoiceConstants.PAGE_BREAK_AFTER_AVOID, style + style.setPageBreakAfter( DesignChoiceConstants.PAGE_BREAK_AFTER_ALWAYS ); + assertEquals( DesignChoiceConstants.PAGE_BREAK_AFTER_ALWAYS, style .getPageBreakAfter( ) ); style.setShowIfBlank( true ); assertTrue( style.getShowIfBlank( ) ); style.setStringFormat( STRINGFORMAT ); assertEquals( STRINGFORMAT, style.getStringFormat( ) ); style .setStringFormatCategory( DesignChoiceConstants.STRING_FORMAT_TYPE_PHONE_NUMBER ); assertEquals( DesignChoiceConstants.STRING_FORMAT_TYPE_PHONE_NUMBER, style.getStringFormatCategory( ) ); style.setTextAlign( DesignChoiceConstants.TEXT_ALIGN_RIGHT ); assertEquals( DesignChoiceConstants.TEXT_ALIGN_RIGHT, style .getTextAlign( ) ); style.setTextIndent( TEXT_INDENT ); assertEquals( TEXT_INDENT, style.getTextIndent( ) ); style .setTextLineThrough( DesignChoiceConstants.TEXT_LINE_THROUGH_LINE_THROUGH ); assertEquals( DesignChoiceConstants.TEXT_LINE_THROUGH_LINE_THROUGH, style.getTextLineThrough( ) ); style.setTextOverline( DesignChoiceConstants.TEXT_OVERLINE_OVERLINE ); assertEquals( DesignChoiceConstants.TEXT_OVERLINE_OVERLINE, style .getTextOverline( ) ); style.setTextTransform( DesignChoiceConstants.TRANSFORM_LOWERCASE ); assertEquals( DesignChoiceConstants.TRANSFORM_LOWERCASE, style .getTextTransform( ) ); style.setTextUnderline( DesignChoiceConstants.TEXT_UNDERLINE_UNDERLINE ); assertEquals( DesignChoiceConstants.TEXT_UNDERLINE_UNDERLINE, style .getTextUnderline( ) ); style.setVerticalAlign( DesignChoiceConstants.VERTICAL_ALIGN_TOP ); assertEquals( DesignChoiceConstants.VERTICAL_ALIGN_TOP, style .getVerticalAlign( ) ); style.setWhiteSpace( DesignChoiceConstants.WHITE_SPACE_NOWRAP ); assertEquals( DesignChoiceConstants.WHITE_SPACE_NOWRAP, style .getWhiteSpace( ) ); style.setWidows( WINDOWS ); assertEquals( WINDOWS, style.getWidows( ) ); style.setWordSpacing( WORD_SPACING ); assertEquals( WORD_SPACING, style.getWordSpacing( ) ); } public void testTable( ) throws ScriptException { TableHandle tableHandle = factory.newTableItem( TABLE ); ITable table = new Table( tableHandle ); table.setCaption( CAPTION ); assertEquals( CAPTION, table.getCaption( ) ); table.setCaptionKey( CAPTION_KEY ); assertEquals( CAPTION_KEY, table.getCaptionKey( ) ); table.setRepeatHeader( true ); assertTrue( table.repeatHeader( ) ); } public void testTextItem( ) throws ScriptException { TextItemHandle textItemHandle = factory.newTextItem( TEXT_ITEM ); ITextItem text = new TextItem( textItemHandle ); text.setContent( TEXT_CONTENT ); assertEquals( TEXT_CONTENT, text.getContent( ) ); text.setContentKey( CONTENT_KEY ); assertEquals( CONTENT_KEY, text.getContentKey( ) ); text.setContentType( DesignChoiceConstants.TEXT_CONTENT_TYPE_HTML ); assertEquals( DesignChoiceConstants.TEXT_CONTENT_TYPE_HTML, text .getContentType( ) ); } }
true
true
public void testStyle( ) throws ScriptException { StyleHandle styleHandle = factory.newStyle( STYLE ); IScriptStyleDesign style = new StyleDesign( styleHandle ); style .setBackgroundAttachment( DesignChoiceConstants.BACKGROUND_ATTACHMENT_SCROLL ); assertEquals( DesignChoiceConstants.BACKGROUND_ATTACHMENT_SCROLL, style .getBackgroundAttachment( ) ); style.setBackgroundColor( RED ); assertEquals( RED, style.getBackgroundColor( ) ); style.setBackgroundImage( IMAGE_URL ); assertEquals( IMAGE_URL, style.getBackgroundImage( ) ); style.setBackGroundPositionX( BACKGROUND_POSITION_X ); assertEquals( BACKGROUND_POSITION_X, style.getBackGroundPositionX( ) ); style.setBackGroundPositionY( BACKGROUND_POSITION_Y ); assertEquals( BACKGROUND_POSITION_Y, style.getBackGroundPositionY( ) ); style .setBackgroundRepeat( DesignChoiceConstants.BACKGROUND_REPEAT_REPEAT ); assertEquals( DesignChoiceConstants.BACKGROUND_REPEAT_REPEAT, style .getBackgroundRepeat( ) ); style.setBorderBottomColor( BLUE ); assertEquals( BLUE, style.getBorderBottomColor( ) ); style.setBorderBottomStyle( DesignChoiceConstants.LINE_STYLE_SOLID ); assertEquals( DesignChoiceConstants.LINE_STYLE_SOLID, style .getBorderBottomStyle( ) ); style.setBorderBottomWidth( BORDER_BOTTOM_WIDTH ); assertEquals( BORDER_BOTTOM_WIDTH, style.getBorderBottomWidth( ) ); style.setBorderLeftColor( GREEN ); assertEquals( GREEN, style.getBorderLeftColor( ) ); style.setBorderLeftStyle( DesignChoiceConstants.LINE_STYLE_DOTTED ); assertEquals( DesignChoiceConstants.LINE_STYLE_DOTTED, style .getBorderLeftStyle( ) ); style.setBorderLeftWidth( BORDER_LEFT_WIDTH ); assertEquals( BORDER_LEFT_WIDTH, style.getBorderLeftWidth( ) ); style.setBorderRightColor( YELLOW ); assertEquals( YELLOW, style.getBorderRightColor( ) ); style.setBorderRightStyle( DesignChoiceConstants.LINE_STYLE_DASHED ); assertEquals( DesignChoiceConstants.LINE_STYLE_DASHED, style .getBorderRightStyle( ) ); style.setBorderRightWidth( BORDER_RIGHT_WIDTH ); assertEquals( BORDER_RIGHT_WIDTH, style.getBorderRightWidth( ) ); style.setBorderTopColor( GRAY ); assertEquals( GRAY, style.getBorderTopColor( ) ); style.setBorderTopStyle( DesignChoiceConstants.LINE_STYLE_DOUBLE ); assertEquals( DesignChoiceConstants.LINE_STYLE_DOUBLE, style .getBorderTopStyle( ) ); style.setBorderTopWidth( BORDER_TOP_WIDTH ); assertEquals( BORDER_TOP_WIDTH, style.getBorderTopWidth( ) ); style.setCanShrink( true ); assertTrue( style.canShrink( ) ); style.setColor( WHITE ); assertEquals( WHITE, style.getColor( ) ); style.setDateTimeFormat( YY_MM_DD ); assertEquals( YY_MM_DD, style.getDateTimeFormat( ) ); style .setDateTimeFormatCategory( DesignChoiceConstants.DATETIEM_FORMAT_TYPE_MUDIUM_DATE ); assertEquals( DesignChoiceConstants.DATETIEM_FORMAT_TYPE_MUDIUM_DATE, style.getDateTimeFormatCategory( ) ); style.setDisplay( DesignChoiceConstants.DISPLAY_INLINE ); assertEquals( DesignChoiceConstants.DISPLAY_INLINE, style.getDisplay( ) ); style.setFontFamily( DesignChoiceConstants.FONT_FAMILY_SANS_SERIF ); assertEquals( DesignChoiceConstants.FONT_FAMILY_SANS_SERIF, style .getFontFamily( ) ); style.setFontSize( FONT_SIZE ); assertEquals( FONT_SIZE, style.getFontSize( ) ); style.setFontStyle( DesignChoiceConstants.FONT_STYLE_ITALIC ); assertEquals( DesignChoiceConstants.FONT_STYLE_ITALIC, style .getFontStyle( ) ); style.setFontVariant( DesignChoiceConstants.FONT_VARIANT_SMALL_CAPS ); assertEquals( DesignChoiceConstants.FONT_VARIANT_SMALL_CAPS, style .getFontVariant( ) ); style.setFontWeight( DesignChoiceConstants.FONT_WEIGHT_BOLD ); assertEquals( DesignChoiceConstants.FONT_WEIGHT_BOLD, style .getFontWeight( ) ); style.setLetterSpacing( LETTER_SPACING ); assertEquals( LETTER_SPACING, style.getLetterSpacing( ) ); style.setLineHeight( LINE_HEIGHT ); assertEquals( LINE_HEIGHT, style.getLineHeight( ) ); style.setMarginBottom( MARGIN_BOTTOM ); assertEquals( MARGIN_BOTTOM, style.getMarginBottom( ) ); style.setMarginLeft( MARGIN_LEFT ); assertEquals( MARGIN_LEFT, style.getMarginLeft( ) ); style.setMarginRight( MARGIN_RIGHT ); assertEquals( MARGIN_RIGHT, style.getMarginRight( ) ); style.setMarginTop( MARGIN_TOP ); assertEquals( MARGIN_TOP, style.getMarginTop( ) ); style.setMasterPage( MASTER_PAGE ); assertEquals( MASTER_PAGE, style.getMasterPage( ) ); style .setNumberFormat( DesignChoiceConstants.NUMBER_FORMAT_TYPE_CURRENCY ); assertEquals( DesignChoiceConstants.NUMBER_FORMAT_TYPE_CURRENCY, style .getNumberFormat( ) ); style .setNumberFormatCategory( DesignChoiceConstants.NUMBER_FORMAT_TYPE_PERCENT ); assertEquals( DesignChoiceConstants.NUMBER_FORMAT_TYPE_PERCENT, style .getNumberFormatCategory( ) ); style.setOrphans( ORPHANS ); assertEquals( ORPHANS, style.getOrphans( ) ); style.setPaddingBottom( PADDING_BOTTOM ); assertEquals( PADDING_BOTTOM, style.getPaddingBottom( ) ); style.setPaddingLeft( PADDING_LEFT ); assertEquals( PADDING_LEFT, style.getPaddingLeft( ) ); style.setPaddingRight( PADDING_RIGHT ); assertEquals( PADDING_RIGHT, style.getPaddingRight( ) ); style.setPaddingTop( PADDING_TOP ); assertEquals( PADDING_TOP, style.getPaddingTop( ) ); style.setPageBreakAfter( DesignChoiceConstants.PAGE_BREAK_AFTER_AVOID ); assertEquals( DesignChoiceConstants.PAGE_BREAK_AFTER_AVOID, style .getPageBreakAfter( ) ); style.setShowIfBlank( true ); assertTrue( style.getShowIfBlank( ) ); style.setStringFormat( STRINGFORMAT ); assertEquals( STRINGFORMAT, style.getStringFormat( ) ); style .setStringFormatCategory( DesignChoiceConstants.STRING_FORMAT_TYPE_PHONE_NUMBER ); assertEquals( DesignChoiceConstants.STRING_FORMAT_TYPE_PHONE_NUMBER, style.getStringFormatCategory( ) ); style.setTextAlign( DesignChoiceConstants.TEXT_ALIGN_RIGHT ); assertEquals( DesignChoiceConstants.TEXT_ALIGN_RIGHT, style .getTextAlign( ) ); style.setTextIndent( TEXT_INDENT ); assertEquals( TEXT_INDENT, style.getTextIndent( ) ); style .setTextLineThrough( DesignChoiceConstants.TEXT_LINE_THROUGH_LINE_THROUGH ); assertEquals( DesignChoiceConstants.TEXT_LINE_THROUGH_LINE_THROUGH, style.getTextLineThrough( ) ); style.setTextOverline( DesignChoiceConstants.TEXT_OVERLINE_OVERLINE ); assertEquals( DesignChoiceConstants.TEXT_OVERLINE_OVERLINE, style .getTextOverline( ) ); style.setTextTransform( DesignChoiceConstants.TRANSFORM_LOWERCASE ); assertEquals( DesignChoiceConstants.TRANSFORM_LOWERCASE, style .getTextTransform( ) ); style.setTextUnderline( DesignChoiceConstants.TEXT_UNDERLINE_UNDERLINE ); assertEquals( DesignChoiceConstants.TEXT_UNDERLINE_UNDERLINE, style .getTextUnderline( ) ); style.setVerticalAlign( DesignChoiceConstants.VERTICAL_ALIGN_TOP ); assertEquals( DesignChoiceConstants.VERTICAL_ALIGN_TOP, style .getVerticalAlign( ) ); style.setWhiteSpace( DesignChoiceConstants.WHITE_SPACE_NOWRAP ); assertEquals( DesignChoiceConstants.WHITE_SPACE_NOWRAP, style .getWhiteSpace( ) ); style.setWidows( WINDOWS ); assertEquals( WINDOWS, style.getWidows( ) ); style.setWordSpacing( WORD_SPACING ); assertEquals( WORD_SPACING, style.getWordSpacing( ) ); }
public void testStyle( ) throws ScriptException { StyleHandle styleHandle = factory.newStyle( STYLE ); IScriptStyleDesign style = new StyleDesign( styleHandle ); style .setBackgroundAttachment( DesignChoiceConstants.BACKGROUND_ATTACHMENT_SCROLL ); assertEquals( DesignChoiceConstants.BACKGROUND_ATTACHMENT_SCROLL, style .getBackgroundAttachment( ) ); style.setBackgroundColor( RED ); assertEquals( RED, style.getBackgroundColor( ) ); style.setBackgroundImage( IMAGE_URL ); assertEquals( IMAGE_URL, style.getBackgroundImage( ) ); style.setBackGroundPositionX( BACKGROUND_POSITION_X ); assertEquals( BACKGROUND_POSITION_X, style.getBackGroundPositionX( ) ); style.setBackGroundPositionY( BACKGROUND_POSITION_Y ); assertEquals( BACKGROUND_POSITION_Y, style.getBackGroundPositionY( ) ); style .setBackgroundRepeat( DesignChoiceConstants.BACKGROUND_REPEAT_REPEAT ); assertEquals( DesignChoiceConstants.BACKGROUND_REPEAT_REPEAT, style .getBackgroundRepeat( ) ); style.setBorderBottomColor( BLUE ); assertEquals( BLUE, style.getBorderBottomColor( ) ); style.setBorderBottomStyle( DesignChoiceConstants.LINE_STYLE_SOLID ); assertEquals( DesignChoiceConstants.LINE_STYLE_SOLID, style .getBorderBottomStyle( ) ); style.setBorderBottomWidth( BORDER_BOTTOM_WIDTH ); assertEquals( BORDER_BOTTOM_WIDTH, style.getBorderBottomWidth( ) ); style.setBorderLeftColor( GREEN ); assertEquals( GREEN, style.getBorderLeftColor( ) ); style.setBorderLeftStyle( DesignChoiceConstants.LINE_STYLE_DOTTED ); assertEquals( DesignChoiceConstants.LINE_STYLE_DOTTED, style .getBorderLeftStyle( ) ); style.setBorderLeftWidth( BORDER_LEFT_WIDTH ); assertEquals( BORDER_LEFT_WIDTH, style.getBorderLeftWidth( ) ); style.setBorderRightColor( YELLOW ); assertEquals( YELLOW, style.getBorderRightColor( ) ); style.setBorderRightStyle( DesignChoiceConstants.LINE_STYLE_DASHED ); assertEquals( DesignChoiceConstants.LINE_STYLE_DASHED, style .getBorderRightStyle( ) ); style.setBorderRightWidth( BORDER_RIGHT_WIDTH ); assertEquals( BORDER_RIGHT_WIDTH, style.getBorderRightWidth( ) ); style.setBorderTopColor( GRAY ); assertEquals( GRAY, style.getBorderTopColor( ) ); style.setBorderTopStyle( DesignChoiceConstants.LINE_STYLE_DOUBLE ); assertEquals( DesignChoiceConstants.LINE_STYLE_DOUBLE, style .getBorderTopStyle( ) ); style.setBorderTopWidth( BORDER_TOP_WIDTH ); assertEquals( BORDER_TOP_WIDTH, style.getBorderTopWidth( ) ); style.setCanShrink( true ); assertTrue( style.canShrink( ) ); style.setColor( WHITE ); assertEquals( WHITE, style.getColor( ) ); style.setDateTimeFormat( YY_MM_DD ); assertEquals( YY_MM_DD, style.getDateTimeFormat( ) ); style .setDateTimeFormatCategory( DesignChoiceConstants.DATETIEM_FORMAT_TYPE_MUDIUM_DATE ); assertEquals( DesignChoiceConstants.DATETIEM_FORMAT_TYPE_MUDIUM_DATE, style.getDateTimeFormatCategory( ) ); style.setDisplay( DesignChoiceConstants.DISPLAY_INLINE ); assertEquals( DesignChoiceConstants.DISPLAY_INLINE, style.getDisplay( ) ); style.setFontFamily( DesignChoiceConstants.FONT_FAMILY_SANS_SERIF ); assertEquals( DesignChoiceConstants.FONT_FAMILY_SANS_SERIF, style .getFontFamily( ) ); style.setFontSize( FONT_SIZE ); assertEquals( FONT_SIZE, style.getFontSize( ) ); style.setFontStyle( DesignChoiceConstants.FONT_STYLE_ITALIC ); assertEquals( DesignChoiceConstants.FONT_STYLE_ITALIC, style .getFontStyle( ) ); style.setFontVariant( DesignChoiceConstants.FONT_VARIANT_SMALL_CAPS ); assertEquals( DesignChoiceConstants.FONT_VARIANT_SMALL_CAPS, style .getFontVariant( ) ); style.setFontWeight( DesignChoiceConstants.FONT_WEIGHT_BOLD ); assertEquals( DesignChoiceConstants.FONT_WEIGHT_BOLD, style .getFontWeight( ) ); style.setLetterSpacing( LETTER_SPACING ); assertEquals( LETTER_SPACING, style.getLetterSpacing( ) ); style.setLineHeight( LINE_HEIGHT ); assertEquals( LINE_HEIGHT, style.getLineHeight( ) ); style.setMarginBottom( MARGIN_BOTTOM ); assertEquals( MARGIN_BOTTOM, style.getMarginBottom( ) ); style.setMarginLeft( MARGIN_LEFT ); assertEquals( MARGIN_LEFT, style.getMarginLeft( ) ); style.setMarginRight( MARGIN_RIGHT ); assertEquals( MARGIN_RIGHT, style.getMarginRight( ) ); style.setMarginTop( MARGIN_TOP ); assertEquals( MARGIN_TOP, style.getMarginTop( ) ); style.setMasterPage( MASTER_PAGE ); assertEquals( MASTER_PAGE, style.getMasterPage( ) ); style .setNumberFormat( DesignChoiceConstants.NUMBER_FORMAT_TYPE_CURRENCY ); assertEquals( DesignChoiceConstants.NUMBER_FORMAT_TYPE_CURRENCY, style .getNumberFormat( ) ); style .setNumberFormatCategory( DesignChoiceConstants.NUMBER_FORMAT_TYPE_PERCENT ); assertEquals( DesignChoiceConstants.NUMBER_FORMAT_TYPE_PERCENT, style .getNumberFormatCategory( ) ); style.setOrphans( ORPHANS ); assertEquals( ORPHANS, style.getOrphans( ) ); style.setPaddingBottom( PADDING_BOTTOM ); assertEquals( PADDING_BOTTOM, style.getPaddingBottom( ) ); style.setPaddingLeft( PADDING_LEFT ); assertEquals( PADDING_LEFT, style.getPaddingLeft( ) ); style.setPaddingRight( PADDING_RIGHT ); assertEquals( PADDING_RIGHT, style.getPaddingRight( ) ); style.setPaddingTop( PADDING_TOP ); assertEquals( PADDING_TOP, style.getPaddingTop( ) ); style.setPageBreakAfter( DesignChoiceConstants.PAGE_BREAK_AFTER_ALWAYS ); assertEquals( DesignChoiceConstants.PAGE_BREAK_AFTER_ALWAYS, style .getPageBreakAfter( ) ); style.setShowIfBlank( true ); assertTrue( style.getShowIfBlank( ) ); style.setStringFormat( STRINGFORMAT ); assertEquals( STRINGFORMAT, style.getStringFormat( ) ); style .setStringFormatCategory( DesignChoiceConstants.STRING_FORMAT_TYPE_PHONE_NUMBER ); assertEquals( DesignChoiceConstants.STRING_FORMAT_TYPE_PHONE_NUMBER, style.getStringFormatCategory( ) ); style.setTextAlign( DesignChoiceConstants.TEXT_ALIGN_RIGHT ); assertEquals( DesignChoiceConstants.TEXT_ALIGN_RIGHT, style .getTextAlign( ) ); style.setTextIndent( TEXT_INDENT ); assertEquals( TEXT_INDENT, style.getTextIndent( ) ); style .setTextLineThrough( DesignChoiceConstants.TEXT_LINE_THROUGH_LINE_THROUGH ); assertEquals( DesignChoiceConstants.TEXT_LINE_THROUGH_LINE_THROUGH, style.getTextLineThrough( ) ); style.setTextOverline( DesignChoiceConstants.TEXT_OVERLINE_OVERLINE ); assertEquals( DesignChoiceConstants.TEXT_OVERLINE_OVERLINE, style .getTextOverline( ) ); style.setTextTransform( DesignChoiceConstants.TRANSFORM_LOWERCASE ); assertEquals( DesignChoiceConstants.TRANSFORM_LOWERCASE, style .getTextTransform( ) ); style.setTextUnderline( DesignChoiceConstants.TEXT_UNDERLINE_UNDERLINE ); assertEquals( DesignChoiceConstants.TEXT_UNDERLINE_UNDERLINE, style .getTextUnderline( ) ); style.setVerticalAlign( DesignChoiceConstants.VERTICAL_ALIGN_TOP ); assertEquals( DesignChoiceConstants.VERTICAL_ALIGN_TOP, style .getVerticalAlign( ) ); style.setWhiteSpace( DesignChoiceConstants.WHITE_SPACE_NOWRAP ); assertEquals( DesignChoiceConstants.WHITE_SPACE_NOWRAP, style .getWhiteSpace( ) ); style.setWidows( WINDOWS ); assertEquals( WINDOWS, style.getWidows( ) ); style.setWordSpacing( WORD_SPACING ); assertEquals( WORD_SPACING, style.getWordSpacing( ) ); }
diff --git a/N06/src/Main/src/java/monsterMashGroupProject/RequestController.java b/N06/src/Main/src/java/monsterMashGroupProject/RequestController.java index 28e3dbb..5a23c3c 100644 --- a/N06/src/Main/src/java/monsterMashGroupProject/RequestController.java +++ b/N06/src/Main/src/java/monsterMashGroupProject/RequestController.java @@ -1,66 +1,66 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package monsterMashGroupProject; import databaseManagement.PersistManager; import databaseManagement.Requests; import java.io.IOException; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author jamesslater */ public class RequestController { PersistManager persistIt = new PersistManager(); Requests request; - public String controller(String requestID, String choice){ + public String controller(String requestID, String acceptbtn, String declinebtn){ FriendHandler friendHand = new FriendHandler(); persistIt.init(); List<Requests> requestList = persistIt.searchRequets(); for(int i = 0; i < requestList.size(); i++){ if(requestList.get(i).getId().equals(requestID)){ this.request = requestList.get(i); } } - if ((choice.equals("acceptbtn")&&(request.getType().equals("FriendRequest")))){ + if ((acceptbtn.equals("Accept")&&(request.getType().equals("FriendRequest")))){ try { friendHand.acceptFriendRequest(request); } catch (IOException ex) { Logger.getLogger(RequestController.class.getName()).log(Level.SEVERE, null, ex); } } return "welcome.jsp"; } /** * Allows the user to reject a sendRequest, sendRequest is removed from * sendRequest list, requester is not alerted. * * @param requester * @param recipient */ public void rejectRequest(Requests request) { persistIt.init(); persistIt.remove(request); persistIt.shutdown(); } }
false
true
public String controller(String requestID, String choice){ FriendHandler friendHand = new FriendHandler(); persistIt.init(); List<Requests> requestList = persistIt.searchRequets(); for(int i = 0; i < requestList.size(); i++){ if(requestList.get(i).getId().equals(requestID)){ this.request = requestList.get(i); } } if ((choice.equals("acceptbtn")&&(request.getType().equals("FriendRequest")))){ try { friendHand.acceptFriendRequest(request); } catch (IOException ex) { Logger.getLogger(RequestController.class.getName()).log(Level.SEVERE, null, ex); } } return "welcome.jsp"; }
public String controller(String requestID, String acceptbtn, String declinebtn){ FriendHandler friendHand = new FriendHandler(); persistIt.init(); List<Requests> requestList = persistIt.searchRequets(); for(int i = 0; i < requestList.size(); i++){ if(requestList.get(i).getId().equals(requestID)){ this.request = requestList.get(i); } } if ((acceptbtn.equals("Accept")&&(request.getType().equals("FriendRequest")))){ try { friendHand.acceptFriendRequest(request); } catch (IOException ex) { Logger.getLogger(RequestController.class.getName()).log(Level.SEVERE, null, ex); } } return "welcome.jsp"; }
diff --git a/Worker/src/main/java/org/trianacode/TrianaCloud/Worker/Worker.java b/Worker/src/main/java/org/trianacode/TrianaCloud/Worker/Worker.java index 5439b30..af3ccc3 100644 --- a/Worker/src/main/java/org/trianacode/TrianaCloud/Worker/Worker.java +++ b/Worker/src/main/java/org/trianacode/TrianaCloud/Worker/Worker.java @@ -1,220 +1,220 @@ /* * * * Copyright - TrianaCloud * * Copyright (C) 2012. Kieran Evans. All Rights Reserved. * * * * 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 org.trianacode.TrianaCloud.Worker; import com.rabbitmq.client.AMQP.BasicProperties; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.QueueingConsumer; import com.rabbitmq.client.MissedHeartbeatException; import org.apache.log4j.Logger; import org.trianacode.TrianaCloud.Utils.Task; import org.trianacode.TrianaCloud.Utils.TaskExecutor; import org.trianacode.TrianaCloud.Utils.TaskExecutorLoader; import org.trianacode.TrianaCloud.Utils.TaskOps; import java.util.*; import java.text.*; import java.io.File; import java.net.MalformedURLException; import java.net.URL; /** * @author Kieran David Evans * @version 1.0.0 Feb 26, 2012 */ /* * The worker looks for tasks, and executes them. Easy. */ public class Worker { private Logger logger = Logger.getLogger(this.getClass().toString()); private static boolean continueLoop = true; private static TaskExecutorLoader tel; public static void main(String[] argv) { while (continueLoop){ try{ go(argv); }catch (MissedHeartbeatException e) { System.out.println(" [-] Heartbeat Missed! Restarting!"); tel = null; } } } public static void go(String[] argv) throws MissedHeartbeatException { Connection connection = null; Channel channel; try { loadPlugins(argv); ConnectionFactory factory = new ConnectionFactory(); factory.setHost("s-vmc.cs.cf.ac.uk"); factory.setPort(7000); factory.setUsername("trianacloud"); factory.setPassword("trianacloud"); factory.setRequestedHeartbeat(60); connection = factory.newConnection(); channel = connection.createChannel(); //Use tc_exchange (TrianaCloud_exchange) in the topic config. ///TODO:Grab this from argv or config file channel.exchangeDeclare("tc_exchange", "topic"); /* "dart.triana" is the queue name. If the task is covered by multiple topic bindings, it's duplicated. If there are multiple queues for a topic binding, it's duplicated. This could be useful for debugging, logging and auditing. This could also be used to implement validation, which inherently ensures that the two (or more) duplicate tasks to compare and validate aren't executed on the same machine. But for a standard single worker, single task config, follow the rule of thumb. Rule of thumb: if the topic binding is the same, the queue name should be the same. If you're using wildcards in a topic name, MAKE SURE other topics/queues don't collide. e.g.: BAD: dart.triana on worker1 #.triana on worker2 GOOD: dart.eddie.triana (this will grab those with this exact topic) *.triana (* substitutes exactly one word. dart.eddie.triana ISN'T caught) */ //String routingKey = "*.kieran"; // String routingKey = "*.triana"; QueueingConsumer consumer = new QueueingConsumer(channel); for (String routingKey : tel.routingKeys) { System.out.println(" [x] Routing Key: " + routingKey); ///TODO:Grab from argv or config file String queueName = channel.queueDeclare(routingKey, true, false, true, null).getQueue(); channel.queueBind(queueName, "tc_exchange", routingKey); //Makes sure tasks are shared properly, this tells rabbit to only grab one message at a time. channel.basicQos(1); channel.basicConsume(queueName, false, consumer); } System.out.println(" [x] Awaiting RPC requests"); while (continueLoop) { byte[] response = new byte[0]; QueueingConsumer.Delivery delivery = consumer.nextDelivery(); BasicProperties props = delivery.getProperties(); BasicProperties replyProps = new BasicProperties .Builder() .correlationId(props.getCorrelationId()) .build(); TaskExecutor ex; try { ///TODO: Use metadata to figure out which Executor to use. ///TODO: Figure out what wire-protocol to use. Something simple like ASN.1? Or a subset of it? //String message = new String(delivery.getBody()); byte[] message = delivery.getBody(); ex = tel.getExecutor("org.trianacode.TrianaCloud.TrianaTaskExecutor.Executor"); //TaskExecutor ex = tel.getExecutor("org.trianacode.TrianaCloud.CommandLineExecutor.Executor"); - timeOut(" [x] Executing Task at "); + timeOutput(" [x] Executing Task at "); Task t = TaskOps.decodeTask(message); ex.setTask(t); - timeOut(" [x] Finished executing Task at "); + timeOutput(" [x] Finished executing Task at "); response = ex.executeTask(); } catch (Exception e) { ///TODO: filter the errors. Worker errors should skip the Ack, and allow the task to be redone. ///TODO: Two new exeptions for the task executor, one to indicate that the execution failed due to /// the data, one to indicate some other error. The former would be ack'ed and sent back, as /// it's a user error (i.e. the data is bad). The latter would indicate any other errors (bad /// config, random error, missile strike). System.out.println(" [.] " + e.toString()); e.printStackTrace(); response = new byte[0]; } finally { channel.basicPublish("", props.getReplyTo(), replyProps, response); //Acknowledge that the task has been received. If a crash happens before here, then Rabbit automagically //sticks the message back in the queue. channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); //TODO bye bye!! // System.exit(0); } } } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (Exception e) { e.printStackTrace(); } } } } public static void timeOutput(String s){ String d; Format formatter; Date date = new Date(); formatter = new SimpleDateFormat("hh:mm:ss"); d = formatter.format(date); System.out.println(s+d); } private static void loadPlugins(String[] argv) throws MalformedURLException { System.out.println(" [x] Loading Plugins"); ClassLoader classLoader = Worker.class.getClassLoader(); ///TODO:Make sure there's not a better way to do this URL[] urls = new URL[1]; ///TODO:Grab a plugin dir from the config file String workingDir; File f; if (argv.length > 0) { workingDir = argv[0]; f = new File(workingDir); } else { workingDir = System.getProperty("user.dir"); f = new File(workingDir + File.separator + "depsdir"); } System.out.println("Addon path : " + f.getAbsolutePath()); urls[0] = f.toURI().toURL(); //Load plugins using the fancy-pants loader hacked together using the code from iharvey and the intarwebs tel = new TaskExecutorLoader(urls, classLoader); } }
false
true
public static void go(String[] argv) throws MissedHeartbeatException { Connection connection = null; Channel channel; try { loadPlugins(argv); ConnectionFactory factory = new ConnectionFactory(); factory.setHost("s-vmc.cs.cf.ac.uk"); factory.setPort(7000); factory.setUsername("trianacloud"); factory.setPassword("trianacloud"); factory.setRequestedHeartbeat(60); connection = factory.newConnection(); channel = connection.createChannel(); //Use tc_exchange (TrianaCloud_exchange) in the topic config. ///TODO:Grab this from argv or config file channel.exchangeDeclare("tc_exchange", "topic"); /* "dart.triana" is the queue name. If the task is covered by multiple topic bindings, it's duplicated. If there are multiple queues for a topic binding, it's duplicated. This could be useful for debugging, logging and auditing. This could also be used to implement validation, which inherently ensures that the two (or more) duplicate tasks to compare and validate aren't executed on the same machine. But for a standard single worker, single task config, follow the rule of thumb. Rule of thumb: if the topic binding is the same, the queue name should be the same. If you're using wildcards in a topic name, MAKE SURE other topics/queues don't collide. e.g.: BAD: dart.triana on worker1 #.triana on worker2 GOOD: dart.eddie.triana (this will grab those with this exact topic) *.triana (* substitutes exactly one word. dart.eddie.triana ISN'T caught) */ //String routingKey = "*.kieran"; // String routingKey = "*.triana"; QueueingConsumer consumer = new QueueingConsumer(channel); for (String routingKey : tel.routingKeys) { System.out.println(" [x] Routing Key: " + routingKey); ///TODO:Grab from argv or config file String queueName = channel.queueDeclare(routingKey, true, false, true, null).getQueue(); channel.queueBind(queueName, "tc_exchange", routingKey); //Makes sure tasks are shared properly, this tells rabbit to only grab one message at a time. channel.basicQos(1); channel.basicConsume(queueName, false, consumer); } System.out.println(" [x] Awaiting RPC requests"); while (continueLoop) { byte[] response = new byte[0]; QueueingConsumer.Delivery delivery = consumer.nextDelivery(); BasicProperties props = delivery.getProperties(); BasicProperties replyProps = new BasicProperties .Builder() .correlationId(props.getCorrelationId()) .build(); TaskExecutor ex; try { ///TODO: Use metadata to figure out which Executor to use. ///TODO: Figure out what wire-protocol to use. Something simple like ASN.1? Or a subset of it? //String message = new String(delivery.getBody()); byte[] message = delivery.getBody(); ex = tel.getExecutor("org.trianacode.TrianaCloud.TrianaTaskExecutor.Executor"); //TaskExecutor ex = tel.getExecutor("org.trianacode.TrianaCloud.CommandLineExecutor.Executor"); timeOut(" [x] Executing Task at "); Task t = TaskOps.decodeTask(message); ex.setTask(t); timeOut(" [x] Finished executing Task at "); response = ex.executeTask(); } catch (Exception e) { ///TODO: filter the errors. Worker errors should skip the Ack, and allow the task to be redone. ///TODO: Two new exeptions for the task executor, one to indicate that the execution failed due to /// the data, one to indicate some other error. The former would be ack'ed and sent back, as /// it's a user error (i.e. the data is bad). The latter would indicate any other errors (bad /// config, random error, missile strike). System.out.println(" [.] " + e.toString()); e.printStackTrace(); response = new byte[0]; } finally { channel.basicPublish("", props.getReplyTo(), replyProps, response); //Acknowledge that the task has been received. If a crash happens before here, then Rabbit automagically //sticks the message back in the queue. channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); //TODO bye bye!! // System.exit(0); } } } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (Exception e) { e.printStackTrace(); } } } }
public static void go(String[] argv) throws MissedHeartbeatException { Connection connection = null; Channel channel; try { loadPlugins(argv); ConnectionFactory factory = new ConnectionFactory(); factory.setHost("s-vmc.cs.cf.ac.uk"); factory.setPort(7000); factory.setUsername("trianacloud"); factory.setPassword("trianacloud"); factory.setRequestedHeartbeat(60); connection = factory.newConnection(); channel = connection.createChannel(); //Use tc_exchange (TrianaCloud_exchange) in the topic config. ///TODO:Grab this from argv or config file channel.exchangeDeclare("tc_exchange", "topic"); /* "dart.triana" is the queue name. If the task is covered by multiple topic bindings, it's duplicated. If there are multiple queues for a topic binding, it's duplicated. This could be useful for debugging, logging and auditing. This could also be used to implement validation, which inherently ensures that the two (or more) duplicate tasks to compare and validate aren't executed on the same machine. But for a standard single worker, single task config, follow the rule of thumb. Rule of thumb: if the topic binding is the same, the queue name should be the same. If you're using wildcards in a topic name, MAKE SURE other topics/queues don't collide. e.g.: BAD: dart.triana on worker1 #.triana on worker2 GOOD: dart.eddie.triana (this will grab those with this exact topic) *.triana (* substitutes exactly one word. dart.eddie.triana ISN'T caught) */ //String routingKey = "*.kieran"; // String routingKey = "*.triana"; QueueingConsumer consumer = new QueueingConsumer(channel); for (String routingKey : tel.routingKeys) { System.out.println(" [x] Routing Key: " + routingKey); ///TODO:Grab from argv or config file String queueName = channel.queueDeclare(routingKey, true, false, true, null).getQueue(); channel.queueBind(queueName, "tc_exchange", routingKey); //Makes sure tasks are shared properly, this tells rabbit to only grab one message at a time. channel.basicQos(1); channel.basicConsume(queueName, false, consumer); } System.out.println(" [x] Awaiting RPC requests"); while (continueLoop) { byte[] response = new byte[0]; QueueingConsumer.Delivery delivery = consumer.nextDelivery(); BasicProperties props = delivery.getProperties(); BasicProperties replyProps = new BasicProperties .Builder() .correlationId(props.getCorrelationId()) .build(); TaskExecutor ex; try { ///TODO: Use metadata to figure out which Executor to use. ///TODO: Figure out what wire-protocol to use. Something simple like ASN.1? Or a subset of it? //String message = new String(delivery.getBody()); byte[] message = delivery.getBody(); ex = tel.getExecutor("org.trianacode.TrianaCloud.TrianaTaskExecutor.Executor"); //TaskExecutor ex = tel.getExecutor("org.trianacode.TrianaCloud.CommandLineExecutor.Executor"); timeOutput(" [x] Executing Task at "); Task t = TaskOps.decodeTask(message); ex.setTask(t); timeOutput(" [x] Finished executing Task at "); response = ex.executeTask(); } catch (Exception e) { ///TODO: filter the errors. Worker errors should skip the Ack, and allow the task to be redone. ///TODO: Two new exeptions for the task executor, one to indicate that the execution failed due to /// the data, one to indicate some other error. The former would be ack'ed and sent back, as /// it's a user error (i.e. the data is bad). The latter would indicate any other errors (bad /// config, random error, missile strike). System.out.println(" [.] " + e.toString()); e.printStackTrace(); response = new byte[0]; } finally { channel.basicPublish("", props.getReplyTo(), replyProps, response); //Acknowledge that the task has been received. If a crash happens before here, then Rabbit automagically //sticks the message back in the queue. channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); //TODO bye bye!! // System.exit(0); } } } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (Exception e) { e.printStackTrace(); } } } }
diff --git a/NearMeServer/src/com/nearme/DatabasePoiFinder.java b/NearMeServer/src/com/nearme/DatabasePoiFinder.java index cd86d18..0eba3a4 100644 --- a/NearMeServer/src/com/nearme/DatabasePoiFinder.java +++ b/NearMeServer/src/com/nearme/DatabasePoiFinder.java @@ -1,113 +1,113 @@ package com.nearme; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import javax.sql.DataSource; /** * A PoiFinder class which talks to an SQL database and pulls out lists of Points of Interest * * @author twhume * */ public class DatabasePoiFinder implements PoiFinder { private DataSource dataSource = null; static Connection conn = null; static String bd = "nearme"; static String login = "root"; static String password = "123"; static String url = "jdbc:mysql://localhost/"+bd; public static void main(String args[]) throws Exception { Class.forName("com.mysql.jdbc.Driver").newInstance(); //load the driver of mysql conn = DriverManager.getConnection(url,login,password); // connect with data base if (conn != null) { System.out.println("Database connection "+url); //conn.close(); } } /* Talk to this DataSource to deal with the database */ public DatabasePoiFinder(DataSource d) { this.dataSource = d; } /** * Pull out a list of Points of Interest matching the contents of the PoiQuery passed in, * and return them in a list. */ public List<Poi> find (PoiQuery pq) { //TODO this is where the database magic happens String value= "Pubs"; //the option in the android String var=" "; ArrayList<Poi> ret = new ArrayList<Poi>(); try { Connection conn = dataSource.getConnection(); PoiType type = null; // ResultSet rtype = st.executeQuery("SELECT id FROM type where name='"+value+"';"); //consult(type) // while (rtype.next()) { // type = new PoiType(value, rtype.getInt(1)); // var= rtype.getString(1); //get the id of the type // } // ResultSet rs = st.executeQuery("SELECT * FROM poi"); // where type='"+var+"';"); //consult database (poi) /** * Algorithm taken from * * http://stackoverflow.com/questions/574691/mysql-great-circle-distance-haversine-formula * */ PreparedStatement locationSearch = conn.prepareStatement("SELECT *, ( 6371 * acos( cos( radians(?) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(?) ) + sin( radians(?) ) * sin( radians( latitude ) ) ) ) AS distance FROM poi HAVING distance < ? ORDER BY distance"); locationSearch.setDouble(1, pq.getLatitude()); locationSearch.setDouble(2, pq.getLongitude()); locationSearch.setDouble(3, pq.getLatitude()); - locationSearch.setDouble(4, (pq.getRadius()/1000)); + locationSearch.setDouble(4, pq.getRadius()); ResultSet rs = locationSearch.executeQuery(); while (rs.next()) //Return false when there is not more data in the table { Poi newPoi = new Poi(rs.getString("name"), rs.getDouble("latitude"), rs.getDouble("longitude"), type, rs.getInt("Id")); ret.add(newPoi); System.out.println(rs.getObject("name")+ ", Longitude: "+rs.getObject("longitude")+ ", Latitude: "+rs.getObject("latitude")); } rs.close(); } catch (SQLException e) { e.printStackTrace(); } return ret; } }
true
true
public List<Poi> find (PoiQuery pq) { //TODO this is where the database magic happens String value= "Pubs"; //the option in the android String var=" "; ArrayList<Poi> ret = new ArrayList<Poi>(); try { Connection conn = dataSource.getConnection(); PoiType type = null; // ResultSet rtype = st.executeQuery("SELECT id FROM type where name='"+value+"';"); //consult(type) // while (rtype.next()) { // type = new PoiType(value, rtype.getInt(1)); // var= rtype.getString(1); //get the id of the type // } // ResultSet rs = st.executeQuery("SELECT * FROM poi"); // where type='"+var+"';"); //consult database (poi) /** * Algorithm taken from * * http://stackoverflow.com/questions/574691/mysql-great-circle-distance-haversine-formula * */ PreparedStatement locationSearch = conn.prepareStatement("SELECT *, ( 6371 * acos( cos( radians(?) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(?) ) + sin( radians(?) ) * sin( radians( latitude ) ) ) ) AS distance FROM poi HAVING distance < ? ORDER BY distance"); locationSearch.setDouble(1, pq.getLatitude()); locationSearch.setDouble(2, pq.getLongitude()); locationSearch.setDouble(3, pq.getLatitude()); locationSearch.setDouble(4, (pq.getRadius()/1000)); ResultSet rs = locationSearch.executeQuery(); while (rs.next()) //Return false when there is not more data in the table { Poi newPoi = new Poi(rs.getString("name"), rs.getDouble("latitude"), rs.getDouble("longitude"), type, rs.getInt("Id")); ret.add(newPoi); System.out.println(rs.getObject("name")+ ", Longitude: "+rs.getObject("longitude")+ ", Latitude: "+rs.getObject("latitude")); } rs.close(); } catch (SQLException e) { e.printStackTrace(); } return ret; }
public List<Poi> find (PoiQuery pq) { //TODO this is where the database magic happens String value= "Pubs"; //the option in the android String var=" "; ArrayList<Poi> ret = new ArrayList<Poi>(); try { Connection conn = dataSource.getConnection(); PoiType type = null; // ResultSet rtype = st.executeQuery("SELECT id FROM type where name='"+value+"';"); //consult(type) // while (rtype.next()) { // type = new PoiType(value, rtype.getInt(1)); // var= rtype.getString(1); //get the id of the type // } // ResultSet rs = st.executeQuery("SELECT * FROM poi"); // where type='"+var+"';"); //consult database (poi) /** * Algorithm taken from * * http://stackoverflow.com/questions/574691/mysql-great-circle-distance-haversine-formula * */ PreparedStatement locationSearch = conn.prepareStatement("SELECT *, ( 6371 * acos( cos( radians(?) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(?) ) + sin( radians(?) ) * sin( radians( latitude ) ) ) ) AS distance FROM poi HAVING distance < ? ORDER BY distance"); locationSearch.setDouble(1, pq.getLatitude()); locationSearch.setDouble(2, pq.getLongitude()); locationSearch.setDouble(3, pq.getLatitude()); locationSearch.setDouble(4, pq.getRadius()); ResultSet rs = locationSearch.executeQuery(); while (rs.next()) //Return false when there is not more data in the table { Poi newPoi = new Poi(rs.getString("name"), rs.getDouble("latitude"), rs.getDouble("longitude"), type, rs.getInt("Id")); ret.add(newPoi); System.out.println(rs.getObject("name")+ ", Longitude: "+rs.getObject("longitude")+ ", Latitude: "+rs.getObject("latitude")); } rs.close(); } catch (SQLException e) { e.printStackTrace(); } return ret; }
diff --git a/src/com/android/contacts/list/DefaultContactListAdapter.java b/src/com/android/contacts/list/DefaultContactListAdapter.java index 2a8d66581..3409f5652 100644 --- a/src/com/android/contacts/list/DefaultContactListAdapter.java +++ b/src/com/android/contacts/list/DefaultContactListAdapter.java @@ -1,254 +1,254 @@ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.contacts.list; import com.android.contacts.preference.ContactsPreferences; import android.content.ContentUris; import android.content.Context; import android.content.CursorLoader; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.net.Uri.Builder; import android.preference.PreferenceManager; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.GroupMembership; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.Directory; import android.provider.ContactsContract.RawContacts; import android.provider.ContactsContract.SearchSnippetColumns; import android.text.TextUtils; import android.view.View; import java.util.ArrayList; import java.util.List; /** * A cursor adapter for the {@link ContactsContract.Contacts#CONTENT_TYPE} content type. */ public class DefaultContactListAdapter extends ContactListAdapter { public static final char SNIPPET_START_MATCH = '\u0001'; public static final char SNIPPET_END_MATCH = '\u0001'; public static final String SNIPPET_ELLIPSIS = "\u2026"; public static final int SNIPPET_MAX_TOKENS = 5; public static final String SNIPPET_ARGS = SNIPPET_START_MATCH + "," + SNIPPET_END_MATCH + "," + SNIPPET_ELLIPSIS + "," + SNIPPET_MAX_TOKENS; public DefaultContactListAdapter(Context context) { super(context); } @Override public void configureLoader(CursorLoader loader, long directoryId) { if (loader instanceof ProfileAndContactsLoader) { ((ProfileAndContactsLoader) loader).setLoadProfile(shouldIncludeProfile()); } ContactListFilter filter = getFilter(); if (isSearchMode()) { String query = getQueryString(); if (query == null) { query = ""; } query = query.trim(); if (TextUtils.isEmpty(query)) { // Regardless of the directory, we don't want anything returned, // so let's just send a "nothing" query to the local directory. loader.setUri(Contacts.CONTENT_URI); loader.setProjection(PROJECTION_CONTACT); loader.setSelection("0"); } else { Builder builder = Contacts.CONTENT_FILTER_URI.buildUpon(); builder.appendPath(query); // Builder will encode the query builder.appendQueryParameter(ContactsContract.DIRECTORY_PARAM_KEY, String.valueOf(directoryId)); if (directoryId != Directory.DEFAULT && directoryId != Directory.LOCAL_INVISIBLE) { builder.appendQueryParameter(ContactsContract.LIMIT_PARAM_KEY, String.valueOf(getDirectoryResultLimit())); } builder.appendQueryParameter(SearchSnippetColumns.SNIPPET_ARGS_PARAM_KEY, SNIPPET_ARGS); builder.appendQueryParameter(SearchSnippetColumns.DEFERRED_SNIPPETING_KEY,"1"); loader.setUri(builder.build()); loader.setProjection(FILTER_PROJECTION); } } else { configureUri(loader, directoryId, filter); configureProjection(loader, directoryId, filter); configureSelection(loader, directoryId, filter); } String sortOrder; if (getSortOrder() == ContactsContract.Preferences.SORT_ORDER_PRIMARY) { sortOrder = Contacts.SORT_KEY_PRIMARY; } else { sortOrder = Contacts.SORT_KEY_ALTERNATIVE; } loader.setSortOrder(sortOrder); } protected void configureUri(CursorLoader loader, long directoryId, ContactListFilter filter) { Uri uri = Contacts.CONTENT_URI; if (filter != null) { if (filter.filterType == ContactListFilter.FILTER_TYPE_GROUP) { uri = Data.CONTENT_URI; } else if (filter.filterType == ContactListFilter.FILTER_TYPE_SINGLE_CONTACT) { String lookupKey = getSelectedContactLookupKey(); if (lookupKey != null) { uri = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey); } else { uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, getSelectedContactId()); } } } if (directoryId == Directory.DEFAULT && isSectionHeaderDisplayEnabled()) { uri = buildSectionIndexerUri(uri); } // The "All accounts" filter is the same as the entire contents of Directory.DEFAULT if (filter != null && filter.filterType != ContactListFilter.FILTER_TYPE_CUSTOM && filter.filterType != ContactListFilter.FILTER_TYPE_SINGLE_CONTACT) { uri = uri.buildUpon().appendQueryParameter( ContactsContract.DIRECTORY_PARAM_KEY, String.valueOf(Directory.DEFAULT)) .build(); } loader.setUri(uri); } protected void configureProjection( CursorLoader loader, long directoryId, ContactListFilter filter) { if (filter != null && filter.filterType == ContactListFilter.FILTER_TYPE_GROUP) { loader.setProjection(PROJECTION_DATA); } else { loader.setProjection(PROJECTION_CONTACT); } } private void configureSelection( CursorLoader loader, long directoryId, ContactListFilter filter) { if (filter == null) { return; } if (directoryId != Directory.DEFAULT) { return; } StringBuilder selection = new StringBuilder(); List<String> selectionArgs = new ArrayList<String>(); switch (filter.filterType) { case ContactListFilter.FILTER_TYPE_ALL_ACCOUNTS: { // We have already added directory=0 to the URI, which takes care of this // filter break; } case ContactListFilter.FILTER_TYPE_SINGLE_CONTACT: { // We have already added the lookup key to the URI, which takes care of this // filter break; } case ContactListFilter.FILTER_TYPE_STARRED: { selection.append(Contacts.STARRED + "!=0"); break; } case ContactListFilter.FILTER_TYPE_WITH_PHONE_NUMBERS_ONLY: { selection.append(Contacts.HAS_PHONE_NUMBER + "=1"); break; } case ContactListFilter.FILTER_TYPE_CUSTOM: { selection.append(Contacts.IN_VISIBLE_GROUP + "=1"); if (isCustomFilterForPhoneNumbersOnly()) { selection.append(" AND " + Contacts.HAS_PHONE_NUMBER + "=1"); } break; } case ContactListFilter.FILTER_TYPE_ACCOUNT: { - // TODO (stopship): avoid the use of private API + // TODO: avoid the use of private API selection.append( Contacts._ID + " IN (" + "SELECT DISTINCT " + RawContacts.CONTACT_ID + " FROM raw_contacts" + " WHERE " + RawContacts.ACCOUNT_TYPE + "=?" + " AND " + RawContacts.ACCOUNT_NAME + "=?"); selectionArgs.add(filter.accountType); selectionArgs.add(filter.accountName); if (filter.dataSet != null) { selection.append(" AND " + RawContacts.DATA_SET + "=?"); selectionArgs.add(filter.dataSet); } else { selection.append(" AND " + RawContacts.DATA_SET + " IS NULL"); } selection.append(")"); break; } case ContactListFilter.FILTER_TYPE_GROUP: { selection.append(Data.MIMETYPE + "=?" + " AND " + GroupMembership.GROUP_ROW_ID + "=?"); selectionArgs.add(GroupMembership.CONTENT_ITEM_TYPE); selectionArgs.add(String.valueOf(filter.groupId)); break; } } loader.setSelection(selection.toString()); loader.setSelectionArgs(selectionArgs.toArray(new String[0])); } @Override protected void bindView(View itemView, int partition, Cursor cursor, int position) { final ContactListItemView view = (ContactListItemView)itemView; view.setHighlightedPrefix(isSearchMode() ? getUpperCaseQueryString() : null); if (isSelectionVisible()) { view.setActivated(isSelectedContact(partition, cursor)); } bindSectionHeaderAndDivider(view, position, cursor); if (isQuickContactEnabled()) { bindQuickContact(view, partition, cursor, CONTACT_PHOTO_ID_COLUMN_INDEX, CONTACT_ID_COLUMN_INDEX, CONTACT_LOOKUP_KEY_COLUMN_INDEX); } else { bindPhoto(view, partition, cursor); } bindName(view, cursor); bindPresenceAndStatusMessage(view, cursor); if (isSearchMode()) { bindSearchSnippet(view, cursor); } else { view.setSnippet(null); } } private boolean isCustomFilterForPhoneNumbersOnly() { // TODO: this flag should not be stored in shared prefs. It needs to be in the db. SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext()); return prefs.getBoolean(ContactsPreferences.PREF_DISPLAY_ONLY_PHONES, ContactsPreferences.PREF_DISPLAY_ONLY_PHONES_DEFAULT); } }
true
true
private void configureSelection( CursorLoader loader, long directoryId, ContactListFilter filter) { if (filter == null) { return; } if (directoryId != Directory.DEFAULT) { return; } StringBuilder selection = new StringBuilder(); List<String> selectionArgs = new ArrayList<String>(); switch (filter.filterType) { case ContactListFilter.FILTER_TYPE_ALL_ACCOUNTS: { // We have already added directory=0 to the URI, which takes care of this // filter break; } case ContactListFilter.FILTER_TYPE_SINGLE_CONTACT: { // We have already added the lookup key to the URI, which takes care of this // filter break; } case ContactListFilter.FILTER_TYPE_STARRED: { selection.append(Contacts.STARRED + "!=0"); break; } case ContactListFilter.FILTER_TYPE_WITH_PHONE_NUMBERS_ONLY: { selection.append(Contacts.HAS_PHONE_NUMBER + "=1"); break; } case ContactListFilter.FILTER_TYPE_CUSTOM: { selection.append(Contacts.IN_VISIBLE_GROUP + "=1"); if (isCustomFilterForPhoneNumbersOnly()) { selection.append(" AND " + Contacts.HAS_PHONE_NUMBER + "=1"); } break; } case ContactListFilter.FILTER_TYPE_ACCOUNT: { // TODO (stopship): avoid the use of private API selection.append( Contacts._ID + " IN (" + "SELECT DISTINCT " + RawContacts.CONTACT_ID + " FROM raw_contacts" + " WHERE " + RawContacts.ACCOUNT_TYPE + "=?" + " AND " + RawContacts.ACCOUNT_NAME + "=?"); selectionArgs.add(filter.accountType); selectionArgs.add(filter.accountName); if (filter.dataSet != null) { selection.append(" AND " + RawContacts.DATA_SET + "=?"); selectionArgs.add(filter.dataSet); } else { selection.append(" AND " + RawContacts.DATA_SET + " IS NULL"); } selection.append(")"); break; } case ContactListFilter.FILTER_TYPE_GROUP: { selection.append(Data.MIMETYPE + "=?" + " AND " + GroupMembership.GROUP_ROW_ID + "=?"); selectionArgs.add(GroupMembership.CONTENT_ITEM_TYPE); selectionArgs.add(String.valueOf(filter.groupId)); break; } } loader.setSelection(selection.toString()); loader.setSelectionArgs(selectionArgs.toArray(new String[0])); }
private void configureSelection( CursorLoader loader, long directoryId, ContactListFilter filter) { if (filter == null) { return; } if (directoryId != Directory.DEFAULT) { return; } StringBuilder selection = new StringBuilder(); List<String> selectionArgs = new ArrayList<String>(); switch (filter.filterType) { case ContactListFilter.FILTER_TYPE_ALL_ACCOUNTS: { // We have already added directory=0 to the URI, which takes care of this // filter break; } case ContactListFilter.FILTER_TYPE_SINGLE_CONTACT: { // We have already added the lookup key to the URI, which takes care of this // filter break; } case ContactListFilter.FILTER_TYPE_STARRED: { selection.append(Contacts.STARRED + "!=0"); break; } case ContactListFilter.FILTER_TYPE_WITH_PHONE_NUMBERS_ONLY: { selection.append(Contacts.HAS_PHONE_NUMBER + "=1"); break; } case ContactListFilter.FILTER_TYPE_CUSTOM: { selection.append(Contacts.IN_VISIBLE_GROUP + "=1"); if (isCustomFilterForPhoneNumbersOnly()) { selection.append(" AND " + Contacts.HAS_PHONE_NUMBER + "=1"); } break; } case ContactListFilter.FILTER_TYPE_ACCOUNT: { // TODO: avoid the use of private API selection.append( Contacts._ID + " IN (" + "SELECT DISTINCT " + RawContacts.CONTACT_ID + " FROM raw_contacts" + " WHERE " + RawContacts.ACCOUNT_TYPE + "=?" + " AND " + RawContacts.ACCOUNT_NAME + "=?"); selectionArgs.add(filter.accountType); selectionArgs.add(filter.accountName); if (filter.dataSet != null) { selection.append(" AND " + RawContacts.DATA_SET + "=?"); selectionArgs.add(filter.dataSet); } else { selection.append(" AND " + RawContacts.DATA_SET + " IS NULL"); } selection.append(")"); break; } case ContactListFilter.FILTER_TYPE_GROUP: { selection.append(Data.MIMETYPE + "=?" + " AND " + GroupMembership.GROUP_ROW_ID + "=?"); selectionArgs.add(GroupMembership.CONTENT_ITEM_TYPE); selectionArgs.add(String.valueOf(filter.groupId)); break; } } loader.setSelection(selection.toString()); loader.setSelectionArgs(selectionArgs.toArray(new String[0])); }
diff --git a/h2/src/test/org/h2/test/synth/TestConcurrentUpdate.java b/h2/src/test/org/h2/test/synth/TestConcurrentUpdate.java index b4a34b7e3..c2e9b17b8 100644 --- a/h2/src/test/org/h2/test/synth/TestConcurrentUpdate.java +++ b/h2/src/test/org/h2/test/synth/TestConcurrentUpdate.java @@ -1,132 +1,133 @@ /* * Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0, * and the EPL 1.0 (http://h2database.com/html/license.html). * Initial Developer: H2 Group */ package org.h2.test.synth; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Random; import org.h2.api.ErrorCode; import org.h2.test.TestBase; import org.h2.util.Task; /** * A concurrent test. */ public class TestConcurrentUpdate extends TestBase { private static final int THREADS = 3; private static final int ROW_COUNT = 10; /** * Run just this test. * * @param a ignored */ public static void main(String... a) throws Exception { TestBase t = TestBase.createCaller().init(); t.config.memory = true; t.test(); } @Override public void test() throws Exception { + deleteDb("concurrent"); final String url = getURL("concurrent;MULTI_THREADED=TRUE", true); Connection conn = getConnection(url); Statement stat = conn.createStatement(); stat.execute("create table test(id int primary key, name varchar)"); Task[] tasks = new Task[THREADS]; for (int i = 0; i < THREADS; i++) { final int threadId = i; Task t = new Task() { @Override public void call() throws Exception { Random r = new Random(threadId); Connection conn = getConnection(url); PreparedStatement insert = conn.prepareStatement( "insert into test values(?, ?)"); PreparedStatement update = conn.prepareStatement( "update test set name = ? where id = ?"); PreparedStatement delete = conn.prepareStatement( "delete from test where id = ?"); PreparedStatement select = conn.prepareStatement( "select * from test where id = ?"); while (!stop) { try { int x = r.nextInt(ROW_COUNT); String data = "x" + r.nextInt(ROW_COUNT); switch (r.nextInt(3)) { case 0: insert.setInt(1, x); insert.setString(2, data); insert.execute(); break; case 1: update.setString(1, data); update.setInt(2, x); update.execute(); break; case 2: delete.setInt(1, x); delete.execute(); break; case 4: select.setInt(1, x); ResultSet rs = select.executeQuery(); while (rs.next()) { rs.getString(2); } break; } } catch (SQLException e) { handleException(e); } } conn.close(); } }; tasks[i] = t; t.execute(); } // test 2 seconds for (int i = 0; i < 200; i++) { Thread.sleep(10); for (Task t : tasks) { if (t.isFinished()) { i = 1000; break; } } } for (Task t : tasks) { t.get(); } conn.close(); } /** * Handle or ignore the exception. * * @param e the exception */ void handleException(SQLException e) throws SQLException { switch (e.getErrorCode()) { case ErrorCode.CONCURRENT_UPDATE_1: case ErrorCode.DUPLICATE_KEY_1: case ErrorCode.ROW_NOT_FOUND_WHEN_DELETING_1: case ErrorCode.LOCK_TIMEOUT_1: break; default: throw e; } } }
true
true
public void test() throws Exception { final String url = getURL("concurrent;MULTI_THREADED=TRUE", true); Connection conn = getConnection(url); Statement stat = conn.createStatement(); stat.execute("create table test(id int primary key, name varchar)"); Task[] tasks = new Task[THREADS]; for (int i = 0; i < THREADS; i++) { final int threadId = i; Task t = new Task() { @Override public void call() throws Exception { Random r = new Random(threadId); Connection conn = getConnection(url); PreparedStatement insert = conn.prepareStatement( "insert into test values(?, ?)"); PreparedStatement update = conn.prepareStatement( "update test set name = ? where id = ?"); PreparedStatement delete = conn.prepareStatement( "delete from test where id = ?"); PreparedStatement select = conn.prepareStatement( "select * from test where id = ?"); while (!stop) { try { int x = r.nextInt(ROW_COUNT); String data = "x" + r.nextInt(ROW_COUNT); switch (r.nextInt(3)) { case 0: insert.setInt(1, x); insert.setString(2, data); insert.execute(); break; case 1: update.setString(1, data); update.setInt(2, x); update.execute(); break; case 2: delete.setInt(1, x); delete.execute(); break; case 4: select.setInt(1, x); ResultSet rs = select.executeQuery(); while (rs.next()) { rs.getString(2); } break; } } catch (SQLException e) { handleException(e); } } conn.close(); } }; tasks[i] = t; t.execute(); } // test 2 seconds for (int i = 0; i < 200; i++) { Thread.sleep(10); for (Task t : tasks) { if (t.isFinished()) { i = 1000; break; } } } for (Task t : tasks) { t.get(); } conn.close(); }
public void test() throws Exception { deleteDb("concurrent"); final String url = getURL("concurrent;MULTI_THREADED=TRUE", true); Connection conn = getConnection(url); Statement stat = conn.createStatement(); stat.execute("create table test(id int primary key, name varchar)"); Task[] tasks = new Task[THREADS]; for (int i = 0; i < THREADS; i++) { final int threadId = i; Task t = new Task() { @Override public void call() throws Exception { Random r = new Random(threadId); Connection conn = getConnection(url); PreparedStatement insert = conn.prepareStatement( "insert into test values(?, ?)"); PreparedStatement update = conn.prepareStatement( "update test set name = ? where id = ?"); PreparedStatement delete = conn.prepareStatement( "delete from test where id = ?"); PreparedStatement select = conn.prepareStatement( "select * from test where id = ?"); while (!stop) { try { int x = r.nextInt(ROW_COUNT); String data = "x" + r.nextInt(ROW_COUNT); switch (r.nextInt(3)) { case 0: insert.setInt(1, x); insert.setString(2, data); insert.execute(); break; case 1: update.setString(1, data); update.setInt(2, x); update.execute(); break; case 2: delete.setInt(1, x); delete.execute(); break; case 4: select.setInt(1, x); ResultSet rs = select.executeQuery(); while (rs.next()) { rs.getString(2); } break; } } catch (SQLException e) { handleException(e); } } conn.close(); } }; tasks[i] = t; t.execute(); } // test 2 seconds for (int i = 0; i < 200; i++) { Thread.sleep(10); for (Task t : tasks) { if (t.isFinished()) { i = 1000; break; } } } for (Task t : tasks) { t.get(); } conn.close(); }
diff --git a/projects/bundles/solaris/src/test/java/org/identityconnectors/solaris/SolarisConnectionTest.java b/projects/bundles/solaris/src/test/java/org/identityconnectors/solaris/SolarisConnectionTest.java index 7b7b2343..57c1fb57 100644 --- a/projects/bundles/solaris/src/test/java/org/identityconnectors/solaris/SolarisConnectionTest.java +++ b/projects/bundles/solaris/src/test/java/org/identityconnectors/solaris/SolarisConnectionTest.java @@ -1,194 +1,194 @@ /* * ==================== * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2008-2009 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of the Common Development * and Distribution License("CDDL") (the "License"). You may not use this file * except in compliance with the License. * * You can obtain a copy of the License at * http://IdentityConnectors.dev.java.net/legal/license.txt * See the License for the specific language governing permissions and limitations * under the License. * * When distributing the Covered Code, include this CDDL Header Notice in each file * and include the License file at identityconnectors/legal/license.txt. * If applicable, add the following below this CDDL Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * ==================== */ package org.identityconnectors.solaris; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.identityconnectors.common.CollectionUtil; import org.identityconnectors.common.logging.Log; import org.identityconnectors.common.security.GuardedString; import org.identityconnectors.framework.common.exceptions.ConnectorException; import org.identityconnectors.solaris.test.SolarisTestBase; import org.identityconnectors.solaris.test.SolarisTestCommon; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; public class SolarisConnectionTest extends SolarisTestBase { private static final String TIMEOUT_BETWEEN_MSGS = "0.5"; private static final String LAST_ECHOED_INFO = "sausage."; private final Log log = Log.getLog(SolarisConnectionTest.class); /** test connection to the configuration given by default credentials (build.groovy) */ @Test public void testGoodConnection() { SolarisConnector connector = new SolarisConnector(); connector.init(getConfiguration()); try { connector.checkAlive(); } finally { connector.dispose(); } } /** * test that if an error occurs in the output, an exception is thrown. */ @Test public void testErrorReplyScenario() { Set<String> rejects = new HashSet<String>(); final String ERROR = "ERROR"; rejects.add(ERROR); try { getConnection().executeCommand( String.format("echo \"%s: ahoj ship\"", ERROR), rejects); Assert.fail("no exception thrown, when error found."); } catch (ConnectorException e) { // OK } } @Test @Ignore public void testErrorReplyScenarioWithTimeout() { Set<String> rejects = new HashSet<String>(); final String ERROR_MARKER = "ERROR"; rejects.add(ERROR_MARKER); try { // Tougher test (it demands setting a long timeout on the connection.) //conn.executeCommand(String.format("export timeout=\"%s\" && echo \"%s: ahoj\" && sleep \"$timeout\" && echo \"ship\" && sleep \"$timeout\" && echo \"egg\" && sleep \"$timeout\" && echo \"spam\" && sleep \"$timeout\" && echo \"%s\"", TIMEOUT_BETWEEN_MSGS, ERROR_MARKER, LAST_ECHOED_INFO), rejects); // Weaker test getConnection().executeCommand(String.format("export timeout=\"%s\" && echo \"%s: ahoj\" && sleep \"$timeout\" && echo \"%s\"", TIMEOUT_BETWEEN_MSGS, ERROR_MARKER, LAST_ECHOED_INFO), rejects); Assert.fail("no exception thrown, when error found."); } catch (ConnectorException e) { final String exMsg = e.getMessage(); String msg = String.format("Buffer <%s> doesn't containt the last echoed info: '%s'.", exMsg, LAST_ECHOED_INFO); //System.out.println("TEST: found: <" exMsg ">"); Assert.assertTrue(msg, exMsg.contains(LAST_ECHOED_INFO)); } } @Test public void testSpecialAccepts() { final String MSG = "AHOJ"; final String errMarker = "ERROR"; getConnection().executeCommand(String.format("echo \"%s\"", MSG), Collections.<String>emptySet(), CollectionUtil.newSet(MSG)); try { getConnection().executeCommand(String.format("echo \"%s %s\"", errMarker, MSG), CollectionUtil.newSet(errMarker), CollectionUtil.newSet(MSG)); Assert.fail("no exception thrown when error should be found in the output."); } catch (ConnectorException ex) { //OK } } @Test public void testTelnetConnection() { if (!SolarisTestCommon.getProperty("unitTests.SolarisConnection.testTelnetMode", Boolean.class)) { log.info("skipping testTelnetConnection test, because the resource doesn't support it."); return; } // connection is recreated after every test method call so we are free to modify it. SolarisConfiguration config = getConnection().getConfiguration(); config.setPort(23); config.setConnectionType(ConnectionType.TELNET.toString()); SolarisConnection conn = new SolarisConnection(config); String out = conn.executeCommand("echo 'ahoj ship'"); Assert.assertTrue(out.contains("ahoj ship")); conn.dispose(); } @Test public void testSSHPubKeyConnection() { if (!SolarisTestCommon.getProperty("unitTests.SolarisConnection.testSSHPubkeyMode", Boolean.class)) { log.info("skipping testSSHPubKeyConnection test, because the resource doesn't support it."); return; } // connection is recreated after every test method call so we are free to modify it. SolarisConfiguration config = getConnection().getConfiguration(); config.setPassphrase(SolarisTestCommon.getProperty("rootPassphrase", GuardedString.class)); config.setPrivateKey(SolarisTestCommon.getProperty("rootPrivateKey", GuardedString.class)); config.setConnectionType(ConnectionType.SSHPUBKEY.toString()); SolarisConnection conn = new SolarisConnection(config); String out = conn.executeCommand("echo 'ahoj ship'"); Assert.assertTrue(out.contains("ahoj ship")); conn.dispose(); } @Test public void testSudoAuthorization() { if (!SolarisTestCommon.getProperty("unitTests.SolarisConnection.testsudoAuthorization", Boolean.class)) { log.info("skipping testSSHPubKeyConnection test, because the resource doesn't support it."); return; } // connection is recreated after every test method call so we are free to modify it. SolarisConfiguration config = getConnection().getConfiguration(); config.setSudoAuthorization(true); config.setLoginUser("david"); config.setLoginShellPrompt("\\$"); - config.setPassword(new GuardedString(SolarisTestCommon.getProperty("pass", String.class).toCharArray())); - config.setCredentials(new GuardedString(SolarisTestCommon.getProperty("pass", String.class).toCharArray())); + config.setPassword(SolarisTestCommon.getProperty("pass", GuardedString.class)); + config.setCredentials(SolarisTestCommon.getProperty("pass", GuardedString.class)); SolarisConnection conn = new SolarisConnection(config); String out = conn.executeCommand("echo 'ahoj ship'"); Assert.assertTrue(out.contains("ahoj ship")); conn.dispose(); } @Test public void checkAliveTest() { try { getConnection().checkAlive(); } catch (Exception ex) { Assert.fail("no exception is expected."); } getConnection().dispose(); try { getConnection().checkAlive(); Assert.fail("exception should be thrown"); } catch (Exception ex) { // OK } } @Override public boolean createGroup() { return false; } @Override public int getCreateUsersNumber() { return 0; } }
true
true
public void testSudoAuthorization() { if (!SolarisTestCommon.getProperty("unitTests.SolarisConnection.testsudoAuthorization", Boolean.class)) { log.info("skipping testSSHPubKeyConnection test, because the resource doesn't support it."); return; } // connection is recreated after every test method call so we are free to modify it. SolarisConfiguration config = getConnection().getConfiguration(); config.setSudoAuthorization(true); config.setLoginUser("david"); config.setLoginShellPrompt("\\$"); config.setPassword(new GuardedString(SolarisTestCommon.getProperty("pass", String.class).toCharArray())); config.setCredentials(new GuardedString(SolarisTestCommon.getProperty("pass", String.class).toCharArray())); SolarisConnection conn = new SolarisConnection(config); String out = conn.executeCommand("echo 'ahoj ship'"); Assert.assertTrue(out.contains("ahoj ship")); conn.dispose(); }
public void testSudoAuthorization() { if (!SolarisTestCommon.getProperty("unitTests.SolarisConnection.testsudoAuthorization", Boolean.class)) { log.info("skipping testSSHPubKeyConnection test, because the resource doesn't support it."); return; } // connection is recreated after every test method call so we are free to modify it. SolarisConfiguration config = getConnection().getConfiguration(); config.setSudoAuthorization(true); config.setLoginUser("david"); config.setLoginShellPrompt("\\$"); config.setPassword(SolarisTestCommon.getProperty("pass", GuardedString.class)); config.setCredentials(SolarisTestCommon.getProperty("pass", GuardedString.class)); SolarisConnection conn = new SolarisConnection(config); String out = conn.executeCommand("echo 'ahoj ship'"); Assert.assertTrue(out.contains("ahoj ship")); conn.dispose(); }
diff --git a/common/com/cane/item/ItemCane.java b/common/com/cane/item/ItemCane.java index c6b6eba..8b33b7b 100644 --- a/common/com/cane/item/ItemCane.java +++ b/common/com/cane/item/ItemCane.java @@ -1,172 +1,172 @@ package com.cane.item; import java.util.ArrayList; import java.util.List; import com.cane.CaneCraft; import com.cane.block.BlockCane; import net.minecraft.block.Block; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.oredict.OreDictionary; public class ItemCane extends ItemCC { public static String[] itemNames = new String[]{"Iron", "Copper", "Tin", "Silver", "Gold", "Diamond", "Redstone", "Compressed Iron", "Compressed Copper", "Compressed Tin", "Compressed Silver", "Compressed Gold", "Compressed Diamond", "Compressed Redstone", "Soul"}; public static ItemStack[] output; public ItemCane(int id) { super(id); this.setHasSubtypes(true); } public boolean onItemUse(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int face, float par8, float par9, float par10) { int prevBlockID = world.getBlockId(x, y, z); if (prevBlockID == Block.snow.blockID) { face = 1; } else if (prevBlockID != Block.vine.blockID && prevBlockID != Block.tallGrass.blockID && prevBlockID != Block.deadBush.blockID) { if (face == 0) { --y; } if (face == 1) { ++y; } if (face == 2) { --z; } if (face == 3) { ++z; } if (face == 4) { --x; } if (face == 5) { ++x; } } if (!player.canPlayerEdit(x, y, z, face, itemStack)) { return false; } else if (itemStack.stackSize == 0) { return false; } else { BlockCane block = CaneCraft.Blocks.cane; int metadata = itemStack.getItemDamage(); if(block.canPlaceBlockAtMetadata(world, x, y, z, metadata)) { if (world.setBlockAndMetadataWithNotify(x, y, z, block.blockID, metadata)) { if (world.getBlockId(x, y, z) == block.blockID) { block.onBlockPlacedBy(world, x, y, z, player); - block.func_85105_g(world, x, y, z, metadata); + block.onPostBlockPlaced(world, x, y, z, metadata); world.playSoundEffect((double)((float)x + 0.5F), (double)((float)y + 0.5F), (double)((float)z + 0.5F), block.stepSound.getPlaceSound(), (block.stepSound.getVolume() + 1.0F) / 2.0F, block.stepSound.getPitch() * 0.8F); --itemStack.stackSize; } } } return true; } } @Override public int getIconFromDamage(int damage) { return damage; } @Override public String getItemNameIS(ItemStack itemStack) { return "cane"+itemStack.getItemDamage(); } @SuppressWarnings("unchecked") @Override public void getSubItems(int val, CreativeTabs tab, List list) { for(int i = 0; i < itemNames.length; i++) { list.add(new ItemStack(this, 1, i)); } } public static void initOutputs() { output = new ItemStack[] { new ItemStack(Item.ingotIron), null, null, null, new ItemStack(Item.ingotGold), new ItemStack(Item.diamond), new ItemStack(CaneCraft.Items.caneUtil, 1, 18), new ItemStack(Item.ingotIron, 9), null, null, null, new ItemStack(Item.ingotGold, 9), new ItemStack(Item.diamond, 9), new ItemStack(CaneCraft.Items.caneUtil, 1, 19), new ItemStack(CaneCraft.Items.caneUtil, 1, 20) }; output[1] = getOre("ingotCopper", 1); output[2] = getOre("ingotTin", 1); output[3] = getOre("ingotSilver", 1); output[8] = getOre("ingotCopper", 9); output[9] = getOre("ingotTin", 9); output[10] = getOre("ingotSilver", 9); } private static ItemStack getOre(String s, int q) { ArrayList<ItemStack> ores = OreDictionary.getOres(s); if(ores.size() > 0) { ItemStack svar = ores.get(0).copy(); svar.stackSize = q; return svar; } return null; } }
true
true
public boolean onItemUse(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int face, float par8, float par9, float par10) { int prevBlockID = world.getBlockId(x, y, z); if (prevBlockID == Block.snow.blockID) { face = 1; } else if (prevBlockID != Block.vine.blockID && prevBlockID != Block.tallGrass.blockID && prevBlockID != Block.deadBush.blockID) { if (face == 0) { --y; } if (face == 1) { ++y; } if (face == 2) { --z; } if (face == 3) { ++z; } if (face == 4) { --x; } if (face == 5) { ++x; } } if (!player.canPlayerEdit(x, y, z, face, itemStack)) { return false; } else if (itemStack.stackSize == 0) { return false; } else { BlockCane block = CaneCraft.Blocks.cane; int metadata = itemStack.getItemDamage(); if(block.canPlaceBlockAtMetadata(world, x, y, z, metadata)) { if (world.setBlockAndMetadataWithNotify(x, y, z, block.blockID, metadata)) { if (world.getBlockId(x, y, z) == block.blockID) { block.onBlockPlacedBy(world, x, y, z, player); block.func_85105_g(world, x, y, z, metadata); world.playSoundEffect((double)((float)x + 0.5F), (double)((float)y + 0.5F), (double)((float)z + 0.5F), block.stepSound.getPlaceSound(), (block.stepSound.getVolume() + 1.0F) / 2.0F, block.stepSound.getPitch() * 0.8F); --itemStack.stackSize; } } } return true; } }
public boolean onItemUse(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int face, float par8, float par9, float par10) { int prevBlockID = world.getBlockId(x, y, z); if (prevBlockID == Block.snow.blockID) { face = 1; } else if (prevBlockID != Block.vine.blockID && prevBlockID != Block.tallGrass.blockID && prevBlockID != Block.deadBush.blockID) { if (face == 0) { --y; } if (face == 1) { ++y; } if (face == 2) { --z; } if (face == 3) { ++z; } if (face == 4) { --x; } if (face == 5) { ++x; } } if (!player.canPlayerEdit(x, y, z, face, itemStack)) { return false; } else if (itemStack.stackSize == 0) { return false; } else { BlockCane block = CaneCraft.Blocks.cane; int metadata = itemStack.getItemDamage(); if(block.canPlaceBlockAtMetadata(world, x, y, z, metadata)) { if (world.setBlockAndMetadataWithNotify(x, y, z, block.blockID, metadata)) { if (world.getBlockId(x, y, z) == block.blockID) { block.onBlockPlacedBy(world, x, y, z, player); block.onPostBlockPlaced(world, x, y, z, metadata); world.playSoundEffect((double)((float)x + 0.5F), (double)((float)y + 0.5F), (double)((float)z + 0.5F), block.stepSound.getPlaceSound(), (block.stepSound.getVolume() + 1.0F) / 2.0F, block.stepSound.getPitch() * 0.8F); --itemStack.stackSize; } } } return true; } }
diff --git a/components/bio-formats/src/loci/formats/in/MetamorphReader.java b/components/bio-formats/src/loci/formats/in/MetamorphReader.java index e35708d17..3335b66a4 100644 --- a/components/bio-formats/src/loci/formats/in/MetamorphReader.java +++ b/components/bio-formats/src/loci/formats/in/MetamorphReader.java @@ -1,1646 +1,1648 @@ // // MetamorphReader.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.File; import java.io.IOException; import java.text.DecimalFormatSymbols; import java.util.Arrays; import java.util.Calendar; import java.util.TimeZone; import java.util.Vector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import loci.common.DataTools; import loci.common.DateTools; import loci.common.Location; import loci.common.RandomAccessInputStream; import loci.common.xml.XMLTools; import loci.formats.CoreMetadata; import loci.formats.FormatException; import loci.formats.FormatTools; import loci.formats.MetadataTools; import loci.formats.meta.MetadataStore; import ome.xml.model.primitives.PositiveFloat; import loci.formats.tiff.IFD; import loci.formats.tiff.IFDList; import loci.formats.tiff.PhotoInterp; import loci.formats.tiff.TiffIFDEntry; import loci.formats.tiff.TiffParser; import loci.formats.tiff.TiffRational; import ome.xml.model.primitives.PositiveInteger; /** * Reader is the file format reader for Metamorph STK files. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="http://trac.openmicroscopy.org.uk/ome/browser/bioformats.git/components/bio-formats/src/loci/formats/in/MetamorphReader.java">Trac</a>, * <a href="http://git.openmicroscopy.org/?p=bioformats.git;a=blob;f=components/bio-formats/src/loci/formats/in/MetamorphReader.java;hb=HEAD">Gitweb</a></dd></dl> * * @author Eric Kjellman egkjellman at wisc.edu * @author Melissa Linkert melissa at glencoesoftware.com * @author Curtis Rueden ctrueden at wisc.edu * @author Sebastien Huart Sebastien dot Huart at curie.fr */ public class MetamorphReader extends BaseTiffReader { // -- Constants -- /** Logger for this class. */ private static final Logger LOGGER = LoggerFactory.getLogger(MetamorphReader.class); public static final String SHORT_DATE_FORMAT = "yyyyMMdd HH:mm:ss"; public static final String MEDIUM_DATE_FORMAT = "yyyyMMdd HH:mm:ss.SSS"; public static final String LONG_DATE_FORMAT = "dd/MM/yyyy HH:mm:ss:SSS"; public static final String[] ND_SUFFIX = {"nd"}; public static final String[] STK_SUFFIX = {"stk", "tif", "tiff"}; // IFD tag numbers of important fields private static final int METAMORPH_ID = 33628; private static final int UIC1TAG = METAMORPH_ID; private static final int UIC2TAG = 33629; private static final int UIC3TAG = 33630; private static final int UIC4TAG = 33631; // -- Fields -- /** The TIFF's name */ private String imageName; /** The TIFF's creation date */ private String imageCreationDate; /** The TIFF's emWavelength */ private long[] emWavelength; private double[] wave; private String binning; private double zoom, stepSize; private Double exposureTime; private Vector<String> waveNames; private Vector<String> stageNames; private long[] internalStamps; private double[] zDistances, stageX, stageY; private double zStart; private Double sizeX = null, sizeY = null; private double tempZ; private boolean validZ; private int mmPlanes; //number of metamorph planes private MetamorphReader[][] stkReaders; /** List of STK files in the dataset. */ private String[][] stks; private String ndFilename; private boolean canLookForND = true; private boolean[] firstSeriesChannels; // -- Constructor -- /** Constructs a new Metamorph reader. */ public MetamorphReader() { super("Metamorph STK", new String[] {"stk", "nd", "tif", "tiff"}); domains = new String[] {FormatTools.LM_DOMAIN}; hasCompanionFiles = true; suffixSufficient = false; } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isThisType(String, boolean) */ public boolean isThisType(String name, boolean open) { Location location = new Location(name); if (!location.exists()) { return false; } if (checkSuffix(name, "nd")) return true; if (open) { location = location.getAbsoluteFile(); Location parent = location.getParentFile(); String baseName = location.getName(); while (baseName.indexOf("_") >= 0) { baseName = baseName.substring(0, baseName.lastIndexOf("_")); if (checkSuffix(name, suffixes) && (new Location(parent, baseName + ".nd").exists() || new Location(parent, baseName + ".ND").exists())) { return true; } } } return super.isThisType(name, open); } /* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream stream) throws IOException { TiffParser tp = new TiffParser(stream); IFD ifd = tp.getFirstIFD(); if (ifd == null) return false; String software = ifd.getIFDTextValue(IFD.SOFTWARE); boolean validSoftware = software != null && software.trim().toLowerCase().startsWith("metamorph"); return validSoftware || (ifd.containsKey(UIC1TAG) && ifd.containsKey(UIC3TAG) && ifd.containsKey(UIC4TAG)); } /* @see loci.formats.IFormatReader#isSingleFile(String) */ public boolean isSingleFile(String id) throws FormatException, IOException { return !checkSuffix(id, ND_SUFFIX); } /* @see loci.formats.IFormatReader#fileGroupOption(String) */ public int fileGroupOption(String id) throws FormatException, IOException { if (checkSuffix(id, ND_SUFFIX)) return FormatTools.MUST_GROUP; Location l = new Location(id).getAbsoluteFile(); String[] files = l.getParentFile().list(); for (String file : files) { if (checkSuffix(file, ND_SUFFIX) && l.getName().startsWith(file.substring(0, file.lastIndexOf(".")))) { return FormatTools.MUST_GROUP; } } return FormatTools.CANNOT_GROUP; } /* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */ public String[] getSeriesUsedFiles(boolean noPixels) { FormatTools.assertId(currentId, true, 1); if (!noPixels && stks == null) return new String[] {currentId}; else if (stks == null) return new String[0]; Vector<String> v = new Vector<String>(); if (ndFilename != null) v.add(ndFilename); if (!noPixels) { for (String stk : stks[getSeries()]) { if (stk != null && new Location(stk).exists()) { v.add(stk); } } } return v.toArray(new String[v.size()]); } /** * @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.assertId(currentId, true, 1); if (stks == null) { return super.openBytes(no, buf, x, y, w, h); } int[] coords = FormatTools.getZCTCoords(this, no % getSizeZ()); int ndx = no / getSizeZ(); if (stks[series].length == 1) ndx = 0; String file = stks[series][ndx]; if (file == null) return buf; // the original file is a .nd file, so we need to construct a new reader // for the constituent STK files stkReaders[series][ndx].setMetadataOptions( new DefaultMetadataOptions(MetadataLevel.MINIMUM)); stkReaders[series][ndx].setId(file); int plane = stks[series].length == 1 ? no : coords[0]; stkReaders[series][ndx].openBytes(plane, buf, x, y, w, h); stkReaders[series][ndx].close(); return buf; } /* @see loci.formats.IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (stkReaders != null) { for (MetamorphReader[] s : stkReaders) { if (s != null) { for (MetamorphReader reader : s) { if (reader != null) reader.close(fileOnly); } } } } if (!fileOnly) { imageName = imageCreationDate = null; emWavelength = null; stks = null; mmPlanes = 0; ndFilename = null; wave = null; binning = null; zoom = stepSize = 0; exposureTime = null; waveNames = stageNames = null; internalStamps = null; zDistances = stageX = stageY = null; firstSeriesChannels = null; sizeX = sizeY = null; tempZ = 0d; validZ = false; stkReaders = null; } } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { if (checkSuffix(id, ND_SUFFIX)) { LOGGER.info("Initializing " + id); // find an associated STK file String stkFile = id.substring(0, id.lastIndexOf(".")); if (stkFile.indexOf(File.separator) != -1) { stkFile = stkFile.substring(stkFile.lastIndexOf(File.separator) + 1); } Location parent = new Location(id).getAbsoluteFile().getParentFile(); LOGGER.info("Looking for STK file in {}", parent.getAbsolutePath()); String[] dirList = parent.list(true); for (String f : dirList) { int underscore = f.indexOf("_"); if (underscore < 0) underscore = f.indexOf("."); if (underscore < 0) underscore = f.length(); String prefix = f.substring(0, underscore); if ((f.equals(stkFile) || stkFile.startsWith(prefix)) && checkSuffix(f, STK_SUFFIX)) { stkFile = new Location(parent.getAbsolutePath(), f).getAbsolutePath(); break; } } if (!checkSuffix(stkFile, STK_SUFFIX)) { throw new FormatException("STK file not found in " + parent.getAbsolutePath() + "."); } super.initFile(stkFile); } else super.initFile(id); Location ndfile = null; if (checkSuffix(id, ND_SUFFIX)) ndfile = new Location(id); else if (canLookForND) { // an STK file was passed to initFile // let's check the parent directory for an .nd file Location stk = new Location(id).getAbsoluteFile(); String stkName = stk.getName(); String stkPrefix = stkName; if (stkPrefix.indexOf("_") >= 0) { stkPrefix = stkPrefix.substring(0, stkPrefix.indexOf("_") + 1); } Location parent = stk.getParentFile(); String[] list = parent.list(true); for (String f : list) { if (checkSuffix(f, ND_SUFFIX)) { String prefix = f.substring(0, f.lastIndexOf(".")); if (prefix.indexOf("_") >= 0) { prefix = prefix.substring(0, prefix.indexOf("_") + 1); } if (stkName.startsWith(prefix) || prefix.equals(stkPrefix)) { ndfile = new Location(parent, f).getAbsoluteFile(); if (prefix.equals(stkPrefix)) { break; } } } } } String creationTime = null; if (ndfile != null && ndfile.exists() && (fileGroupOption(id) == FormatTools.MUST_GROUP || isGroupFiles())) { // parse key/value pairs from .nd file int zc = getSizeZ(), cc = getSizeC(), tc = getSizeT(); int nstages = 0; String z = null, c = null, t = null; Vector<Boolean> hasZ = new Vector<Boolean>(); waveNames = new Vector<String>(); stageNames = new Vector<String>(); boolean useWaveNames = true; ndFilename = ndfile.getAbsolutePath(); String[] lines = DataTools.readFile(ndFilename).split("\n"); for (String line : lines) { int comma = line.indexOf(","); if (comma <= 0) continue; String key = line.substring(1, comma - 1).trim(); String value = line.substring(comma + 1).trim(); addGlobalMeta(key, value); if (key.equals("NZSteps")) z = value; else if (key.equals("NWavelengths")) c = value; else if (key.equals("NTimePoints")) t = value; else if (key.startsWith("WaveDoZ")) { hasZ.add(new Boolean(value.toLowerCase())); } else if (key.startsWith("WaveName")) { waveNames.add(value.substring(1, value.length() - 1)); } else if (key.startsWith("Stage")) { stageNames.add(value); } else if (key.startsWith("StartTime")) { creationTime = value; } else if (key.equals("ZStepSize")) { char separator = new DecimalFormatSymbols().getDecimalSeparator(); value = value.replace('.', separator); value = value.replace(',', separator); stepSize = Double.parseDouble(value); } else if (key.equals("NStagePositions")) { nstages = Integer.parseInt(value); } else if (key.equals("WaveInFileName")) { useWaveNames = Boolean.parseBoolean(value); } } // figure out how many files we need if (z != null) zc = Integer.parseInt(z); if (c != null) cc = Integer.parseInt(c); if (t != null) tc = Integer.parseInt(t); if (cc == 0) cc = 1; int numFiles = cc * tc; if (nstages > 0) numFiles *= nstages; // determine series count int seriesCount = nstages == 0 ? 1 : nstages; firstSeriesChannels = new boolean[cc]; Arrays.fill(firstSeriesChannels, true); boolean differentZs = false; for (int i=0; i<cc; i++) { boolean hasZ1 = i < hasZ.size() && hasZ.get(i).booleanValue(); boolean hasZ2 = i != 0 && (i - 1 < hasZ.size()) && hasZ.get(i - 1).booleanValue(); if (i > 0 && hasZ1 != hasZ2) { if (!differentZs) seriesCount *= 2; differentZs = true; } } int channelsInFirstSeries = cc; if (differentZs) { channelsInFirstSeries = 0; for (int i=0; i<cc; i++) { if (hasZ.get(i).booleanValue()) channelsInFirstSeries++; else firstSeriesChannels[i] = false; } } stks = new String[seriesCount][]; if (seriesCount == 1) stks[0] = new String[numFiles]; else if (differentZs) { int stages = nstages == 0 ? 1 : nstages; for (int i=0; i<stages; i++) { stks[i * 2] = new String[channelsInFirstSeries * tc]; stks[i * 2 + 1] = new String[(cc - channelsInFirstSeries) * tc]; } } else { for (int i=0; i<stks.length; i++) { stks[i] = new String[numFiles / stks.length]; } } String prefix = ndfile.getPath(); prefix = prefix.substring(prefix.lastIndexOf(File.separator) + 1, prefix.lastIndexOf(".")); // build list of STK files int[] pt = new int[seriesCount]; for (int i=0; i<tc; i++) { int ns = nstages == 0 ? 1 : nstages; for (int s=0; s<ns; s++) { for (int j=0; j<cc; j++) { boolean validZ = j >= hasZ.size() || hasZ.get(j).booleanValue(); int seriesNdx = s * (seriesCount / ns); if ((seriesCount != 1 && !validZ) || (nstages == 0 && ((!validZ && cc > 1) || seriesCount > 1))) { - seriesNdx++; + if (j > 0) { + seriesNdx++; + } } if (seriesNdx >= stks.length || seriesNdx >= pt.length || pt[seriesNdx] >= stks[seriesNdx].length) { continue; } stks[seriesNdx][pt[seriesNdx]] = prefix; if (j < waveNames.size() && waveNames.get(j) != null) { stks[seriesNdx][pt[seriesNdx]] += "_w" + (j + 1); if (useWaveNames) { String waveName = waveNames.get(j); // If there are underscores in the wavelength name, translate // them to hyphens. (See #558) waveName = waveName.replace('_', '-'); // If there are slashes (forward or backward) in the wavelength // name, translate them to hyphens. (See #5922) waveName = waveName.replace('/', '-'); waveName = waveName.replace('\\', '-'); stks[seriesNdx][pt[seriesNdx]] += waveName; } } if (nstages > 0) { stks[seriesNdx][pt[seriesNdx]] += "_s" + (s + 1); } if (tc > 1) { stks[seriesNdx][pt[seriesNdx]] += "_t" + (i + 1) + ".STK"; } else stks[seriesNdx][pt[seriesNdx]] += ".STK"; pt[seriesNdx]++; } } } ndfile = ndfile.getAbsoluteFile(); // check that each STK file exists for (int s=0; s<stks.length; s++) { for (int f=0; f<stks[s].length; f++) { Location l = new Location(ndfile.getParent(), stks[s][f]); stks[s][f] = getRealSTKFile(l); } } String file = locateFirstValidFile(); if (file == null) { throw new FormatException( "Unable to locate at lease one valid STK file!"); } RandomAccessInputStream s = new RandomAccessInputStream(file); TiffParser tp = new TiffParser(s); IFD ifd = tp.getFirstIFD(); s.close(); core[0].sizeX = (int) ifd.getImageWidth(); core[0].sizeY = (int) ifd.getImageLength(); core[0].sizeZ = zc; core[0].sizeC = cc; core[0].sizeT = tc; core[0].imageCount = zc * tc * cc; core[0].dimensionOrder = "XYZCT"; if (stks != null && stks.length > 1) { CoreMetadata[] newCore = new CoreMetadata[stks.length]; for (int i=0; i<stks.length; i++) { newCore[i] = new CoreMetadata(); newCore[i].sizeX = getSizeX(); newCore[i].sizeY = getSizeY(); newCore[i].sizeZ = getSizeZ(); newCore[i].sizeC = getSizeC(); newCore[i].sizeT = getSizeT(); newCore[i].pixelType = getPixelType(); newCore[i].imageCount = getImageCount(); newCore[i].dimensionOrder = getDimensionOrder(); newCore[i].rgb = isRGB(); newCore[i].littleEndian = isLittleEndian(); newCore[i].interleaved = isInterleaved(); newCore[i].orderCertain = true; } if (stks.length > nstages) { int ns = nstages == 0 ? 1 : nstages; for (int j=0; j<ns; j++) { newCore[j * 2].sizeC = stks[j * 2].length / getSizeT(); newCore[j * 2 + 1].sizeC = stks[j * 2 + 1].length / newCore[j * 2 + 1].sizeT; newCore[j * 2 + 1].sizeZ = 1; newCore[j * 2].imageCount = newCore[j * 2].sizeC * newCore[j * 2].sizeT * newCore[j * 2].sizeZ; newCore[j * 2 + 1].imageCount = newCore[j * 2 + 1].sizeC * newCore[j * 2 + 1].sizeT; } } core = newCore; } } if (stks == null) { stkReaders = new MetamorphReader[1][1]; stkReaders[0][0] = new MetamorphReader(); stkReaders[0][0].setCanLookForND(false); } else { stkReaders = new MetamorphReader[stks.length][]; for (int i=0; i<stks.length; i++) { stkReaders[i] = new MetamorphReader[stks[i].length]; for (int j=0; j<stkReaders[i].length; j++) { stkReaders[i][j] = new MetamorphReader(); stkReaders[i][j].setCanLookForND(false); if (j > 0) { stkReaders[i][j].setMetadataOptions( new DefaultMetadataOptions(MetadataLevel.MINIMUM)); } } } } Vector<String> timestamps = null; MetamorphHandler handler = null; MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this, true); String detectorID = MetadataTools.createLSID("Detector", 0, 0); for (int i=0; i<getSeriesCount(); i++) { setSeries(i); handler = new MetamorphHandler(getSeriesMetadata()); String instrumentID = MetadataTools.createLSID("Instrument", i); store.setInstrumentID(instrumentID, i); store.setImageInstrumentRef(instrumentID, i); if (i == 0) { store.setDetectorID(detectorID, 0, 0); store.setDetectorType(getDetectorType("Other"), 0, 0); } String comment = getFirstComment(i); if (comment != null && comment.startsWith("<MetaData>")) { try { XMLTools.parseXML(XMLTools.sanitizeXML(comment), handler); } catch (IOException e) { } } if (creationTime != null) { String date = DateTools.formatDate(creationTime, SHORT_DATE_FORMAT); store.setImageAcquiredDate(date, 0); } else if (i > 0) MetadataTools.setDefaultCreationDate(store, id, i); store.setImageName(makeImageName(i), i); if (getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM) { continue; } store.setImageDescription("", i); store.setImagingEnvironmentTemperature(handler.getTemperature(), i); if (sizeX == null) sizeX = handler.getPixelSizeX(); if (sizeY == null) sizeY = handler.getPixelSizeY(); if (sizeX > 0) { store.setPixelsPhysicalSizeX(new PositiveFloat(sizeX), i); } if (sizeY > 0) { store.setPixelsPhysicalSizeY(new PositiveFloat(sizeY), i); } if (zDistances != null) { stepSize = zDistances[0]; } if (stepSize > 0) { store.setPixelsPhysicalSizeZ(new PositiveFloat(stepSize), i); } int waveIndex = 0; for (int c=0; c<getEffectiveSizeC(); c++) { if (firstSeriesChannels == null || (stageNames != null && stageNames.size() == getSeriesCount())) { waveIndex = c; } else if (firstSeriesChannels != null) { int s = i % 2; while (firstSeriesChannels[waveIndex] == (s == 1) && waveIndex < firstSeriesChannels.length) { waveIndex++; } } if (waveNames != null && waveIndex < waveNames.size()) { store.setChannelName(waveNames.get(waveIndex), i, c); } if (handler.getBinning() != null) binning = handler.getBinning(); if (binning != null) { store.setDetectorSettingsBinning(getBinning(binning), i, c); } if (handler.getReadOutRate() != 0) { store.setDetectorSettingsReadOutRate(handler.getReadOutRate(), i, c); } store.setDetectorSettingsID(detectorID, i, c); if (wave != null && waveIndex < wave.length && (int) wave[waveIndex] >= 1) { store.setChannelLightSourceSettingsWavelength( new PositiveInteger((int) wave[waveIndex]), i, c); // link LightSource to Image String lightSourceID = MetadataTools.createLSID("LightSource", i, c); store.setLaserID(lightSourceID, i, c); store.setChannelLightSourceSettingsID(lightSourceID, i, c); store.setLaserType(getLaserType("Other"), i, c); store.setLaserLaserMedium(getLaserMedium("Other"), i, c); } waveIndex++; } timestamps = handler.getTimestamps(); for (int t=0; t<timestamps.size(); t++) { addSeriesMeta("timestamp " + t, DateTools.formatDate(timestamps.get(t), MEDIUM_DATE_FORMAT)); } long startDate = 0; if (timestamps.size() > 0) { startDate = DateTools.getTime(timestamps.get(0), MEDIUM_DATE_FORMAT); } Double positionX = new Double(handler.getStagePositionX()); Double positionY = new Double(handler.getStagePositionY()); Vector<Double> exposureTimes = handler.getExposures(); if (exposureTimes.size() == 0) { for (int p=0; p<getImageCount(); p++) { exposureTimes.add(exposureTime); } } int lastFile = -1; IFD lastIFD = null; long[] lastOffsets = null; double distance = zStart; for (int p=0; p<getImageCount(); p++) { int[] coords = getZCTCoords(p); Double deltaT = new Double(0); Double exposureTime = new Double(0); Double xmlZPosition = null; int fileIndex = getIndex(0, 0, coords[2]) / getSizeZ(); if (fileIndex >= 0) { String file = stks == null ? currentId : stks[i][fileIndex]; if (file != null) { RandomAccessInputStream stream = new RandomAccessInputStream(file); TiffParser tp = new TiffParser(stream); tp.checkHeader(); if (fileIndex != lastFile) { lastFile = fileIndex; lastOffsets = tp.getIFDOffsets(); } lastIFD = tp.getIFD(lastOffsets[p % lastOffsets.length]); stream.close(); comment = lastIFD.getComment(); if (comment != null) comment = comment.trim(); handler = new MetamorphHandler(getSeriesMetadata()); if (comment != null && comment.startsWith("<MetaData>")) { XMLTools.parseXML(comment, handler); } timestamps = handler.getTimestamps(); exposureTimes = handler.getExposures(); Vector<Double> zPositions = handler.getZPositions(); if (zPositions != null && zPositions.size() > 0) { xmlZPosition = zPositions.get(0); } } } int index = 0; if (timestamps.size() > 0) { if (coords[2] < timestamps.size()) index = coords[2]; String stamp = timestamps.get(index); long ms = DateTools.getTime(stamp, MEDIUM_DATE_FORMAT); deltaT = new Double((ms - startDate) / 1000.0); } else if (internalStamps != null && p < internalStamps.length) { long delta = internalStamps[p] - internalStamps[0]; deltaT = new Double(delta / 1000.0); if (coords[2] < exposureTimes.size()) index = coords[2]; } if (index < exposureTimes.size()) { exposureTime = exposureTimes.get(index); } store.setPlaneDeltaT(deltaT, i, p); store.setPlaneExposureTime(exposureTime, i, p); if (stageX != null && p < stageX.length) { store.setPlanePositionX(stageX[p], i, p); } if (stageY != null && p < stageY.length) { store.setPlanePositionY(stageY[p], i, p); } if (zDistances != null && p < zDistances.length) { if (p > 0) { if (zDistances[p] != 0d) distance += zDistances[p]; else distance += zDistances[0]; } store.setPlanePositionZ(distance, i, p); } else if (xmlZPosition != null) { store.setPlanePositionZ(xmlZPosition, i, p); } } } setSeries(0); } // -- Internal BaseTiffReader API methods -- /* @see BaseTiffReader#initStandardMetadata() */ protected void initStandardMetadata() throws FormatException, IOException { super.initStandardMetadata(); core[0].sizeZ = 1; core[0].sizeT = 0; int rgbChannels = getSizeC(); // Now that the base TIFF standard metadata has been parsed, we need to // parse out the STK metadata from the UIC4TAG. TiffIFDEntry uic1tagEntry = null; TiffIFDEntry uic2tagEntry = null; TiffIFDEntry uic4tagEntry = null; try { uic1tagEntry = tiffParser.getFirstIFDEntry(UIC1TAG); uic2tagEntry = tiffParser.getFirstIFDEntry(UIC2TAG); uic4tagEntry = tiffParser.getFirstIFDEntry(UIC4TAG); } catch (IllegalArgumentException exc) { LOGGER.debug("Unknown tag", exc); } try { if (uic4tagEntry != null) { mmPlanes = uic4tagEntry.getValueCount(); } if (uic2tagEntry != null) { parseUIC2Tags(uic2tagEntry.getValueOffset()); } if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { if (uic4tagEntry != null) { parseUIC4Tags(uic4tagEntry.getValueOffset()); } if (uic1tagEntry != null) { parseUIC1Tags(uic1tagEntry.getValueOffset(), uic1tagEntry.getValueCount()); } } in.seek(uic4tagEntry.getValueOffset()); } catch (NullPointerException exc) { LOGGER.debug("", exc); } catch (IOException exc) { LOGGER.debug("Failed to parse proprietary tags", exc); } try { // copy ifds into a new array of Hashtables that will accommodate the // additional image planes IFD firstIFD = ifds.get(0); long[] uic2 = firstIFD.getIFDLongArray(UIC2TAG); if (uic2 == null) { throw new FormatException("Invalid Metamorph file. Tag " + UIC2TAG + " not found."); } core[0].imageCount = uic2.length; Object entry = firstIFD.getIFDValue(UIC3TAG); TiffRational[] uic3 = entry instanceof TiffRational[] ? (TiffRational[]) entry : new TiffRational[] {(TiffRational) entry}; wave = new double[uic3.length]; Vector<Double> uniqueWavelengths = new Vector<Double>(); for (int i=0; i<uic3.length; i++) { wave[i] = uic3[i].doubleValue(); addSeriesMeta("Wavelength [" + intFormatMax(i, mmPlanes) + "]", wave[i]); Double v = new Double(wave[i]); if (!uniqueWavelengths.contains(v)) uniqueWavelengths.add(v); } if (getSizeC() == 1) { core[0].sizeC = uniqueWavelengths.size(); } IFDList tempIFDs = new IFDList(); long[] oldOffsets = firstIFD.getStripOffsets(); long[] stripByteCounts = firstIFD.getStripByteCounts(); int rowsPerStrip = (int) firstIFD.getRowsPerStrip()[0]; int stripsPerImage = getSizeY() / rowsPerStrip; if (stripsPerImage * rowsPerStrip != getSizeY()) stripsPerImage++; PhotoInterp check = firstIFD.getPhotometricInterpretation(); if (check == PhotoInterp.RGB_PALETTE) { firstIFD.putIFDValue(IFD.PHOTOMETRIC_INTERPRETATION, PhotoInterp.BLACK_IS_ZERO); } emWavelength = firstIFD.getIFDLongArray(UIC3TAG); // for each image plane, construct an IFD hashtable IFD temp; for (int i=0; i<getImageCount(); i++) { // copy data from the first IFD temp = new IFD(firstIFD); // now we need a StripOffsets entry - the original IFD doesn't have this long[] newOffsets = new long[stripsPerImage]; if (stripsPerImage * (i + 1) <= oldOffsets.length) { System.arraycopy(oldOffsets, stripsPerImage * i, newOffsets, 0, stripsPerImage); } else { System.arraycopy(oldOffsets, 0, newOffsets, 0, stripsPerImage); long image = (stripByteCounts[0] / rowsPerStrip) * getSizeY(); for (int q=0; q<stripsPerImage; q++) { newOffsets[q] += i * image; } } temp.putIFDValue(IFD.STRIP_OFFSETS, newOffsets); long[] newByteCounts = new long[stripsPerImage]; if (stripsPerImage * i < stripByteCounts.length) { System.arraycopy(stripByteCounts, stripsPerImage * i, newByteCounts, 0, stripsPerImage); } else { Arrays.fill(newByteCounts, stripByteCounts[0]); } temp.putIFDValue(IFD.STRIP_BYTE_COUNTS, newByteCounts); tempIFDs.add(temp); } ifds = tempIFDs; } catch (IllegalArgumentException exc) { LOGGER.debug("Unknown tag", exc); } catch (NullPointerException exc) { LOGGER.debug("", exc); } catch (FormatException exc) { LOGGER.debug("Failed to build list of IFDs", exc); } // parse (mangle) TIFF comment String descr = ifds.get(0).getComment(); if (descr != null) { String[] lines = descr.split("\n"); StringBuffer sb = new StringBuffer(); for (int i=0; i<lines.length; i++) { String line = lines[i].trim(); int colon = line.indexOf(": "); String descrValue = null; if (colon < 0) { // normal line (not a key/value pair) if (line.length() > 0) { // not a blank line descrValue = line; } } else { if (i == 0) { // first line could be mangled; make a reasonable guess int dot = line.lastIndexOf(".", colon); if (dot >= 0) { descrValue = line.substring(0, dot + 1); } line = line.substring(dot + 1); colon -= dot + 1; } // append value to description if (descrValue != null) { sb.append(descrValue); if (!descrValue.endsWith(".")) sb.append("."); sb.append(" "); } // add key/value pair embedded in comment as separate metadata String key = line.substring(0, colon); String value = line.substring(colon + 2); addSeriesMeta(key, value); if (key.equals("Exposure")) { if (value.indexOf("=") != -1) { value = value.substring(value.indexOf("=") + 1).trim(); } if (value.indexOf(" ") != -1) { value = value.substring(0, value.indexOf(" ")); } try { char separator = new DecimalFormatSymbols().getDecimalSeparator(); value = value.replace('.', separator); value = value.replace(',', separator); double exposure = Double.parseDouble(value); exposureTime = new Double(exposure / 1000); } catch (NumberFormatException e) { } } else if (key.equals("Bit Depth")) { if (value.indexOf("-") != -1) { value = value.substring(0, value.indexOf("-")); } try { core[0].bitsPerPixel = Integer.parseInt(value); } catch (NumberFormatException e) { } } } } // replace comment with trimmed version descr = sb.toString().trim(); if (descr.equals("")) metadata.remove("Comment"); else addSeriesMeta("Comment", descr); } core[0].sizeT = getImageCount() / (getSizeZ() * (getSizeC() / rgbChannels)); if (getSizeT() * getSizeZ() * (getSizeC() / rgbChannels) != getImageCount()) { core[0].sizeT = 1; core[0].sizeZ = getImageCount() / (getSizeC() / rgbChannels); } // if '_t' is present in the file name, swap Z and T sizes // this file was probably part of a larger dataset, but the .nd file is // missing String filename = currentId.substring(currentId.lastIndexOf(File.separator) + 1); if (filename.indexOf("_t") != -1 && getSizeT() > 1) { int z = getSizeZ(); core[0].sizeZ = getSizeT(); core[0].sizeT = z; } if (getSizeZ() == 0) core[0].sizeZ = 1; if (getSizeT() == 0) core[0].sizeT = 1; if (getSizeZ() * getSizeT() * (isRGB() ? 1 : getSizeC()) != getImageCount()) { core[0].sizeZ = getImageCount(); core[0].sizeT = 1; if (!isRGB()) core[0].sizeC = 1; } } // -- Helper methods -- /** * Check that the given STK file exists. If it does, then return the * absolute path. If it does not, then apply various formatting rules until * an existing file is found. * * @return the absolute path of an STK file, or null if no STK file is found. */ private String getRealSTKFile(Location l) { if (l.exists()) return l.getAbsolutePath(); String name = l.getName(); String parent = l.getParent(); if (name.indexOf("_") > 0) { String prefix = name.substring(0, name.indexOf("_")); String suffix = name.substring(name.indexOf("_")); String basePrefix = new Location(currentId).getName(); int end = basePrefix.indexOf("_"); if (end < 0) end = basePrefix.indexOf("."); basePrefix = basePrefix.substring(0, end); if (!basePrefix.equals(prefix)) { name = basePrefix + suffix; Location p = new Location(parent, name); if (p.exists()) return p.getAbsolutePath(); } } // '%' can be converted to '-' if (name.indexOf("%") != -1) { name = name.replaceAll("%", "-"); l = new Location(parent, name); if (!l.exists()) { // try replacing extension name = name.substring(0, name.lastIndexOf(".")) + ".TIF"; l = new Location(parent, name); if (!l.exists()) { name = name.substring(0, name.lastIndexOf(".")) + ".tif"; l = new Location(parent, name); return l.exists() ? l.getAbsolutePath() : null; } } } if (!l.exists()) { // try replacing extension int index = name.lastIndexOf("."); if (index < 0) index = name.length(); name = name.substring(0, index) + ".TIF"; l = new Location(parent, name); if (!l.exists()) { name = name.substring(0, name.lastIndexOf(".")) + ".tif"; l = new Location(parent, name); if (!l.exists()) { name = name.substring(0, name.lastIndexOf(".")) + ".stk"; l = new Location(parent, name); return l.exists() ? l.getAbsolutePath() : null; } } } return l.getAbsolutePath(); } /** * Returns the TIFF comment from the first IFD of the first STK file in the * given series. */ private String getFirstComment(int i) throws IOException { if (stks != null && stks[i][0] != null) { RandomAccessInputStream stream = new RandomAccessInputStream(stks[i][0]); TiffParser tp = new TiffParser(stream); String comment = tp.getComment(); stream.close(); return comment; } return ifds.get(0).getComment(); } /** Create an appropriate name for the given series. */ private String makeImageName(int i) { String name = ""; if (stageNames != null && stageNames.size() > 0) { int stagePosition = i / (getSeriesCount() / stageNames.size()); name += "Stage " + stageNames.get(stagePosition) + "; "; } if (firstSeriesChannels != null) { for (int c=0; c<firstSeriesChannels.length; c++) { if (firstSeriesChannels[c] == ((i % 2) == 0) && c < waveNames.size()) { name += waveNames.get(c) + "/"; } } if (name.length() > 0) { name = name.substring(0, name.length() - 1); } } return name; } /** * Populates metadata fields with some contained in MetaMorph UIC2 Tag. * (for each plane: 6 integers: * zdistance numerator, zdistance denominator, * creation date, creation time, modif date, modif time) * @param uic2offset offset to UIC2 (33629) tag entries * * not a regular tiff tag (6*N entries, N being the tagCount) * @throws IOException */ void parseUIC2Tags(long uic2offset) throws IOException { long saveLoc = in.getFilePointer(); in.seek(uic2offset); /*number of days since the 1st of January 4713 B.C*/ String cDate; /*milliseconds since 0:00*/ String cTime; /*z step, distance separating previous slice from current one*/ String iAsString; zDistances = new double[mmPlanes]; internalStamps = new long[mmPlanes]; for (int i=0; i<mmPlanes; i++) { iAsString = intFormatMax(i, mmPlanes); if (in.getFilePointer() + 8 > in.length()) break; zDistances[i] = readRational(in).doubleValue(); addSeriesMeta("zDistance[" + iAsString + "]", zDistances[i]); if (zDistances[i] != 0.0) core[0].sizeZ++; cDate = decodeDate(in.readInt()); cTime = decodeTime(in.readInt()); internalStamps[i] = DateTools.getTime(cDate + " " + cTime, LONG_DATE_FORMAT); addSeriesMeta("creationDate[" + iAsString + "]", cDate); addSeriesMeta("creationTime[" + iAsString + "]", cTime); // modification date and time are skipped as they all seem equal to 0...? in.skip(8); } if (getSizeZ() == 0) core[0].sizeZ = 1; in.seek(saveLoc); } /** * UIC4 metadata parser * * UIC4 Table contains per-plane blocks of metadata * stage X/Y positions, * camera chip offsets, * stage labels... * @param long uic4offset: offset of UIC4 table (not tiff-compliant) * @throws IOException */ private void parseUIC4Tags(long uic4offset) throws IOException { long saveLoc = in.getFilePointer(); in.seek(uic4offset); if (in.getFilePointer() + 2 >= in.length()) return; tempZ = 0d; validZ = false; short id = in.readShort(); while (id != 0) { switch (id) { case 28: readStagePositions(); break; case 29: readRationals( new String[] {"cameraXChipOffset", "cameraYChipOffset"}); break; case 37: readStageLabels(); break; case 40: readRationals(new String[] {"UIC4 absoluteZ"}); break; case 41: readAbsoluteZValid(); break; case 46: in.skipBytes(mmPlanes * 8); // TODO break; default: in.skipBytes(4); } id = in.readShort(); } in.seek(saveLoc); if (validZ) zStart = tempZ; } private void readStagePositions() throws IOException { stageX = new double[mmPlanes]; stageY = new double[mmPlanes]; String pos; for (int i=0; i<mmPlanes; i++) { pos = intFormatMax(i, mmPlanes); stageX[i] = readRational(in).doubleValue(); stageY[i] = readRational(in).doubleValue(); addSeriesMeta("stageX[" + pos + "]", stageX[i]); addSeriesMeta("stageY[" + pos + "]", stageY[i]); addGlobalMeta("X position for position #" + (getSeries() + 1), stageX[i]); addGlobalMeta("Y position for position #" + (getSeries() + 1), stageY[i]); } } private void readRationals(String[] labels) throws IOException { String pos; for (int i=0; i<mmPlanes; i++) { pos = intFormatMax(i, mmPlanes); for (int q=0; q<labels.length; q++) { double v = readRational(in).doubleValue(); if (labels[q].endsWith("absoluteZ") && i == 0) { tempZ = v; } addSeriesMeta(labels[q] + "[" + pos + "]", v); } } } void readStageLabels() throws IOException { int strlen; String iAsString; for (int i=0; i<mmPlanes; i++) { iAsString = intFormatMax(i, mmPlanes); strlen = in.readInt(); addSeriesMeta("stageLabel[" + iAsString + "]", in.readString(strlen)); } } void readAbsoluteZValid() throws IOException { for (int i=0; i<mmPlanes; i++) { int valid = in.readInt(); addSeriesMeta("absoluteZValid[" + intFormatMax(i, mmPlanes) + "]", valid); if (i == 0) { validZ = valid == 1; } } } /** * UIC1 entry parser * @throws IOException * @param long uic1offset : offset as found in the tiff tag 33628 (UIC1Tag) * @param int uic1count : number of entries in UIC1 table (not tiff-compliant) */ private void parseUIC1Tags(long uic1offset, int uic1count) throws IOException { // Loop through and parse out each field. A field whose // code is "0" represents the end of the fields so we'll stop // when we reach that; much like a NULL terminated C string. long saveLoc = in.getFilePointer(); in.seek(uic1offset); int currentID; long valOrOffset; // variable declarations, because switch is dumb int num, denom; String thedate, thetime; long lastOffset; tempZ = 0d; validZ = false; for (int i=0; i<uic1count; i++) { if (in.getFilePointer() >= in.length()) break; currentID = in.readInt(); valOrOffset = in.readInt() & 0xffffffffL; lastOffset = in.getFilePointer(); String key = getKey(currentID); Object value = String.valueOf(valOrOffset); switch (currentID) { case 3: value = valOrOffset != 0 ? "on" : "off"; break; case 4: case 5: case 21: case 22: case 23: case 24: case 38: case 39: value = readRational(in, valOrOffset); break; case 6: case 25: in.seek(valOrOffset); num = in.readInt(); if (num + in.getFilePointer() >= in.length()) { num = (int) (in.length() - in.getFilePointer() - 1); } value = in.readString(num); break; case 7: in.seek(valOrOffset); num = in.readInt(); imageName = in.readString(num); value = imageName; break; case 8: if (valOrOffset == 1) value = "inside"; else if (valOrOffset == 2) value = "outside"; else value = "off"; break; case 17: // oh how we hate you Julian format... in.seek(valOrOffset); thedate = decodeDate(in.readInt()); thetime = decodeTime(in.readInt()); imageCreationDate = thedate + " " + thetime; value = imageCreationDate; break; case 16: in.seek(valOrOffset); thedate = decodeDate(in.readInt()); thetime = decodeTime(in.readInt()); value = thedate + " " + thetime; break; case 26: in.seek(valOrOffset); int standardLUT = in.readInt(); switch (standardLUT) { case 0: value = "monochrome"; break; case 1: value = "pseudocolor"; break; case 2: value = "Red"; break; case 3: value = "Green"; break; case 4: value = "Blue"; break; case 5: value = "user-defined"; break; default: value = "monochrome"; } break; case 34: value = String.valueOf(in.readInt()); break; case 46: in.seek(valOrOffset); int xBin = in.readInt(); int yBin = in.readInt(); binning = xBin + "x" + yBin; value = binning; break; case 40: if (valOrOffset != 0) { in.seek(valOrOffset); readRationals(new String[] {"UIC1 absoluteZ"}); } break; case 41: if (valOrOffset != 0) { in.seek(valOrOffset); readAbsoluteZValid(); } break; case 49: in.seek(valOrOffset); readPlaneData(); break; } addSeriesMeta(key, value); in.seek(lastOffset); if ("Zoom".equals(key) && value != null) { zoom = Double.parseDouble(value.toString()); } if ("XCalibration".equals(key) && value != null) { if (value instanceof TiffRational) { sizeX = ((TiffRational) value).doubleValue(); } else sizeX = new Double(value.toString()); } if ("YCalibration".equals(key) && value != null) { if (value instanceof TiffRational) { sizeY = ((TiffRational) value).doubleValue(); } else sizeY = new Double(value.toString()); } } in.seek(saveLoc); if (validZ) zStart = tempZ; } // -- Utility methods -- /** Converts a Julian date value into a human-readable string. */ public static String decodeDate(int julian) { long a, b, c, d, e, alpha, z; short day, month, year; // code reused from the Metamorph data specification z = julian + 1; if (z < 2299161L) a = z; else { alpha = (long) ((z - 1867216.25) / 36524.25); a = z + 1 + alpha - alpha / 4; } b = (a > 1721423L ? a + 1524 : a + 1158); c = (long) ((b - 122.1) / 365.25); d = (long) (365.25 * c); e = (long) ((b - d) / 30.6001); day = (short) (b - d - (long) (30.6001 * e)); month = (short) ((e < 13.5) ? e - 1 : e - 13); year = (short) ((month > 2.5) ? (c - 4716) : c - 4715); return intFormat(day, 2) + "/" + intFormat(month, 2) + "/" + year; } /** Converts a time value in milliseconds into a human-readable string. */ public static String decodeTime(int millis) { Calendar time = Calendar.getInstance(TimeZone.getTimeZone("GMT")); time.setTimeInMillis(millis); String hours = intFormat(time.get(Calendar.HOUR_OF_DAY), 2); String minutes = intFormat(time.get(Calendar.MINUTE), 2); String seconds = intFormat(time.get(Calendar.SECOND), 2); String ms = intFormat(time.get(Calendar.MILLISECOND), 3); return hours + ":" + minutes + ":" + seconds + ":" + ms; } /** Formats an integer value with leading 0s if needed. */ public static String intFormat(int myint, int digits) { return String.format("%0" + digits + "d", myint); } /** * Formats an integer with leading 0 using maximum sequence number. * * @param myint integer to format * @param maxint max of "myint" * @return String */ public static String intFormatMax(int myint, int maxint) { return intFormat(myint, String.valueOf(maxint).length()); } /** * Locates the first valid file in the STK arrays. * @return Path to the first valid file. */ private String locateFirstValidFile() { for (int q = 0; q < stks.length; q++) { for (int f = 0; f < stks.length; f++) { if (stks[q][f] != null) { return stks[q][f]; } } } return null; } private TiffRational readRational(RandomAccessInputStream s) throws IOException { return readRational(s, s.getFilePointer()); } private TiffRational readRational(RandomAccessInputStream s, long offset) throws IOException { s.seek(offset); int num = s.readInt(); int denom = s.readInt(); return new TiffRational(num, denom); } private void setCanLookForND(boolean v) { FormatTools.assertId(currentId, false, 1); canLookForND = v; } private void readPlaneData() throws IOException { in.skipBytes(4); int keyLength = in.read(); String key = in.readString(keyLength); in.skipBytes(4); int type = in.read(); int index = 0; switch (type) { case 1: in.skipBytes(1); while (getGlobalMeta("Channel #" + index + " " + key) != null) { index++; } addGlobalMeta("Channel #" + index + " " + key, in.readDouble()); break; case 2: int valueLength = in.read(); String value = in.readString(valueLength); if (valueLength == 0) { in.skipBytes(4); valueLength = in.read(); value = in.readString(valueLength); } while (getGlobalMeta("Channel #" + index + " " + key) != null) { index++; } addGlobalMeta("Channel #" + index + " " + key, value); if (key.equals("_IllumSetting_")) { if (waveNames == null) waveNames = new Vector<String>(); waveNames.add(value); } break; } } private String getKey(int id) { switch (id) { case 0: return "AutoScale"; case 1: return "MinScale"; case 2: return "MaxScale"; case 3: return "Spatial Calibration"; case 4: return "XCalibration"; case 5: return "YCalibration"; case 6: return "CalibrationUnits"; case 7: return "Name"; case 8: return "ThreshState"; case 9: return "ThreshStateRed"; // there is no 10 case 11: return "ThreshStateGreen"; case 12: return "ThreshStateBlue"; case 13: return "ThreshStateLo"; case 14: return "ThreshStateHi"; case 15: return "Zoom"; case 16: return "DateTime"; case 17: return "LastSavedTime"; case 18: return "currentBuffer"; case 19: return "grayFit"; case 20: return "grayPointCount"; case 21: return "grayX"; case 22: return "grayY"; case 23: return "grayMin"; case 24: return "grayMax"; case 25: return "grayUnitName"; case 26: return "StandardLUT"; case 27: return "Wavelength"; case 28: return "StagePosition"; case 29: return "CameraChipOffset"; case 30: return "OverlayMask"; case 31: return "OverlayCompress"; case 32: return "Overlay"; case 33: return "SpecialOverlayMask"; case 34: return "SpecialOverlayCompress"; case 35: return "SpecialOverlay"; case 36: return "ImageProperty"; case 38: return "AutoScaleLoInfo"; case 39: return "AutoScaleHiInfo"; case 40: return "AbsoluteZ"; case 41: return "AbsoluteZValid"; case 42: return "Gamma"; case 43: return "GammaRed"; case 44: return "GammaGreen"; case 45: return "GammaBlue"; case 46: return "CameraBin"; case 47: return "NewLUT"; case 48: return "ImagePropertyEx"; case 49: return "PlaneProperty"; case 50: return "UserLutTable"; case 51: return "RedAutoScaleInfo"; case 52: return "RedAutoScaleLoInfo"; case 53: return "RedAutoScaleHiInfo"; case 54: return "RedMinScaleInfo"; case 55: return "RedMaxScaleInfo"; case 56: return "GreenAutoScaleInfo"; case 57: return "GreenAutoScaleLoInfo"; case 58: return "GreenAutoScaleHiInfo"; case 59: return "GreenMinScaleInfo"; case 60: return "GreenMaxScaleInfo"; case 61: return "BlueAutoScaleInfo"; case 62: return "BlueAutoScaleLoInfo"; case 63: return "BlueAutoScaleHiInfo"; case 64: return "BlueMinScaleInfo"; case 65: return "BlueMaxScaleInfo"; case 66: return "OverlayPlaneColor"; } return null; } }
true
true
protected void initFile(String id) throws FormatException, IOException { if (checkSuffix(id, ND_SUFFIX)) { LOGGER.info("Initializing " + id); // find an associated STK file String stkFile = id.substring(0, id.lastIndexOf(".")); if (stkFile.indexOf(File.separator) != -1) { stkFile = stkFile.substring(stkFile.lastIndexOf(File.separator) + 1); } Location parent = new Location(id).getAbsoluteFile().getParentFile(); LOGGER.info("Looking for STK file in {}", parent.getAbsolutePath()); String[] dirList = parent.list(true); for (String f : dirList) { int underscore = f.indexOf("_"); if (underscore < 0) underscore = f.indexOf("."); if (underscore < 0) underscore = f.length(); String prefix = f.substring(0, underscore); if ((f.equals(stkFile) || stkFile.startsWith(prefix)) && checkSuffix(f, STK_SUFFIX)) { stkFile = new Location(parent.getAbsolutePath(), f).getAbsolutePath(); break; } } if (!checkSuffix(stkFile, STK_SUFFIX)) { throw new FormatException("STK file not found in " + parent.getAbsolutePath() + "."); } super.initFile(stkFile); } else super.initFile(id); Location ndfile = null; if (checkSuffix(id, ND_SUFFIX)) ndfile = new Location(id); else if (canLookForND) { // an STK file was passed to initFile // let's check the parent directory for an .nd file Location stk = new Location(id).getAbsoluteFile(); String stkName = stk.getName(); String stkPrefix = stkName; if (stkPrefix.indexOf("_") >= 0) { stkPrefix = stkPrefix.substring(0, stkPrefix.indexOf("_") + 1); } Location parent = stk.getParentFile(); String[] list = parent.list(true); for (String f : list) { if (checkSuffix(f, ND_SUFFIX)) { String prefix = f.substring(0, f.lastIndexOf(".")); if (prefix.indexOf("_") >= 0) { prefix = prefix.substring(0, prefix.indexOf("_") + 1); } if (stkName.startsWith(prefix) || prefix.equals(stkPrefix)) { ndfile = new Location(parent, f).getAbsoluteFile(); if (prefix.equals(stkPrefix)) { break; } } } } } String creationTime = null; if (ndfile != null && ndfile.exists() && (fileGroupOption(id) == FormatTools.MUST_GROUP || isGroupFiles())) { // parse key/value pairs from .nd file int zc = getSizeZ(), cc = getSizeC(), tc = getSizeT(); int nstages = 0; String z = null, c = null, t = null; Vector<Boolean> hasZ = new Vector<Boolean>(); waveNames = new Vector<String>(); stageNames = new Vector<String>(); boolean useWaveNames = true; ndFilename = ndfile.getAbsolutePath(); String[] lines = DataTools.readFile(ndFilename).split("\n"); for (String line : lines) { int comma = line.indexOf(","); if (comma <= 0) continue; String key = line.substring(1, comma - 1).trim(); String value = line.substring(comma + 1).trim(); addGlobalMeta(key, value); if (key.equals("NZSteps")) z = value; else if (key.equals("NWavelengths")) c = value; else if (key.equals("NTimePoints")) t = value; else if (key.startsWith("WaveDoZ")) { hasZ.add(new Boolean(value.toLowerCase())); } else if (key.startsWith("WaveName")) { waveNames.add(value.substring(1, value.length() - 1)); } else if (key.startsWith("Stage")) { stageNames.add(value); } else if (key.startsWith("StartTime")) { creationTime = value; } else if (key.equals("ZStepSize")) { char separator = new DecimalFormatSymbols().getDecimalSeparator(); value = value.replace('.', separator); value = value.replace(',', separator); stepSize = Double.parseDouble(value); } else if (key.equals("NStagePositions")) { nstages = Integer.parseInt(value); } else if (key.equals("WaveInFileName")) { useWaveNames = Boolean.parseBoolean(value); } } // figure out how many files we need if (z != null) zc = Integer.parseInt(z); if (c != null) cc = Integer.parseInt(c); if (t != null) tc = Integer.parseInt(t); if (cc == 0) cc = 1; int numFiles = cc * tc; if (nstages > 0) numFiles *= nstages; // determine series count int seriesCount = nstages == 0 ? 1 : nstages; firstSeriesChannels = new boolean[cc]; Arrays.fill(firstSeriesChannels, true); boolean differentZs = false; for (int i=0; i<cc; i++) { boolean hasZ1 = i < hasZ.size() && hasZ.get(i).booleanValue(); boolean hasZ2 = i != 0 && (i - 1 < hasZ.size()) && hasZ.get(i - 1).booleanValue(); if (i > 0 && hasZ1 != hasZ2) { if (!differentZs) seriesCount *= 2; differentZs = true; } } int channelsInFirstSeries = cc; if (differentZs) { channelsInFirstSeries = 0; for (int i=0; i<cc; i++) { if (hasZ.get(i).booleanValue()) channelsInFirstSeries++; else firstSeriesChannels[i] = false; } } stks = new String[seriesCount][]; if (seriesCount == 1) stks[0] = new String[numFiles]; else if (differentZs) { int stages = nstages == 0 ? 1 : nstages; for (int i=0; i<stages; i++) { stks[i * 2] = new String[channelsInFirstSeries * tc]; stks[i * 2 + 1] = new String[(cc - channelsInFirstSeries) * tc]; } } else { for (int i=0; i<stks.length; i++) { stks[i] = new String[numFiles / stks.length]; } } String prefix = ndfile.getPath(); prefix = prefix.substring(prefix.lastIndexOf(File.separator) + 1, prefix.lastIndexOf(".")); // build list of STK files int[] pt = new int[seriesCount]; for (int i=0; i<tc; i++) { int ns = nstages == 0 ? 1 : nstages; for (int s=0; s<ns; s++) { for (int j=0; j<cc; j++) { boolean validZ = j >= hasZ.size() || hasZ.get(j).booleanValue(); int seriesNdx = s * (seriesCount / ns); if ((seriesCount != 1 && !validZ) || (nstages == 0 && ((!validZ && cc > 1) || seriesCount > 1))) { seriesNdx++; } if (seriesNdx >= stks.length || seriesNdx >= pt.length || pt[seriesNdx] >= stks[seriesNdx].length) { continue; } stks[seriesNdx][pt[seriesNdx]] = prefix; if (j < waveNames.size() && waveNames.get(j) != null) { stks[seriesNdx][pt[seriesNdx]] += "_w" + (j + 1); if (useWaveNames) { String waveName = waveNames.get(j); // If there are underscores in the wavelength name, translate // them to hyphens. (See #558) waveName = waveName.replace('_', '-'); // If there are slashes (forward or backward) in the wavelength // name, translate them to hyphens. (See #5922) waveName = waveName.replace('/', '-'); waveName = waveName.replace('\\', '-'); stks[seriesNdx][pt[seriesNdx]] += waveName; } } if (nstages > 0) { stks[seriesNdx][pt[seriesNdx]] += "_s" + (s + 1); } if (tc > 1) { stks[seriesNdx][pt[seriesNdx]] += "_t" + (i + 1) + ".STK"; } else stks[seriesNdx][pt[seriesNdx]] += ".STK"; pt[seriesNdx]++; } } } ndfile = ndfile.getAbsoluteFile(); // check that each STK file exists for (int s=0; s<stks.length; s++) { for (int f=0; f<stks[s].length; f++) { Location l = new Location(ndfile.getParent(), stks[s][f]); stks[s][f] = getRealSTKFile(l); } } String file = locateFirstValidFile(); if (file == null) { throw new FormatException( "Unable to locate at lease one valid STK file!"); } RandomAccessInputStream s = new RandomAccessInputStream(file); TiffParser tp = new TiffParser(s); IFD ifd = tp.getFirstIFD(); s.close(); core[0].sizeX = (int) ifd.getImageWidth(); core[0].sizeY = (int) ifd.getImageLength(); core[0].sizeZ = zc; core[0].sizeC = cc; core[0].sizeT = tc; core[0].imageCount = zc * tc * cc; core[0].dimensionOrder = "XYZCT"; if (stks != null && stks.length > 1) { CoreMetadata[] newCore = new CoreMetadata[stks.length]; for (int i=0; i<stks.length; i++) { newCore[i] = new CoreMetadata(); newCore[i].sizeX = getSizeX(); newCore[i].sizeY = getSizeY(); newCore[i].sizeZ = getSizeZ(); newCore[i].sizeC = getSizeC(); newCore[i].sizeT = getSizeT(); newCore[i].pixelType = getPixelType(); newCore[i].imageCount = getImageCount(); newCore[i].dimensionOrder = getDimensionOrder(); newCore[i].rgb = isRGB(); newCore[i].littleEndian = isLittleEndian(); newCore[i].interleaved = isInterleaved(); newCore[i].orderCertain = true; } if (stks.length > nstages) { int ns = nstages == 0 ? 1 : nstages; for (int j=0; j<ns; j++) { newCore[j * 2].sizeC = stks[j * 2].length / getSizeT(); newCore[j * 2 + 1].sizeC = stks[j * 2 + 1].length / newCore[j * 2 + 1].sizeT; newCore[j * 2 + 1].sizeZ = 1; newCore[j * 2].imageCount = newCore[j * 2].sizeC * newCore[j * 2].sizeT * newCore[j * 2].sizeZ; newCore[j * 2 + 1].imageCount = newCore[j * 2 + 1].sizeC * newCore[j * 2 + 1].sizeT; } } core = newCore; } } if (stks == null) { stkReaders = new MetamorphReader[1][1]; stkReaders[0][0] = new MetamorphReader(); stkReaders[0][0].setCanLookForND(false); } else { stkReaders = new MetamorphReader[stks.length][]; for (int i=0; i<stks.length; i++) { stkReaders[i] = new MetamorphReader[stks[i].length]; for (int j=0; j<stkReaders[i].length; j++) { stkReaders[i][j] = new MetamorphReader(); stkReaders[i][j].setCanLookForND(false); if (j > 0) { stkReaders[i][j].setMetadataOptions( new DefaultMetadataOptions(MetadataLevel.MINIMUM)); } } } } Vector<String> timestamps = null; MetamorphHandler handler = null; MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this, true); String detectorID = MetadataTools.createLSID("Detector", 0, 0); for (int i=0; i<getSeriesCount(); i++) { setSeries(i); handler = new MetamorphHandler(getSeriesMetadata()); String instrumentID = MetadataTools.createLSID("Instrument", i); store.setInstrumentID(instrumentID, i); store.setImageInstrumentRef(instrumentID, i); if (i == 0) { store.setDetectorID(detectorID, 0, 0); store.setDetectorType(getDetectorType("Other"), 0, 0); } String comment = getFirstComment(i); if (comment != null && comment.startsWith("<MetaData>")) { try { XMLTools.parseXML(XMLTools.sanitizeXML(comment), handler); } catch (IOException e) { } } if (creationTime != null) { String date = DateTools.formatDate(creationTime, SHORT_DATE_FORMAT); store.setImageAcquiredDate(date, 0); } else if (i > 0) MetadataTools.setDefaultCreationDate(store, id, i); store.setImageName(makeImageName(i), i); if (getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM) { continue; } store.setImageDescription("", i); store.setImagingEnvironmentTemperature(handler.getTemperature(), i); if (sizeX == null) sizeX = handler.getPixelSizeX(); if (sizeY == null) sizeY = handler.getPixelSizeY(); if (sizeX > 0) { store.setPixelsPhysicalSizeX(new PositiveFloat(sizeX), i); } if (sizeY > 0) { store.setPixelsPhysicalSizeY(new PositiveFloat(sizeY), i); } if (zDistances != null) { stepSize = zDistances[0]; } if (stepSize > 0) { store.setPixelsPhysicalSizeZ(new PositiveFloat(stepSize), i); } int waveIndex = 0; for (int c=0; c<getEffectiveSizeC(); c++) { if (firstSeriesChannels == null || (stageNames != null && stageNames.size() == getSeriesCount())) { waveIndex = c; } else if (firstSeriesChannels != null) { int s = i % 2; while (firstSeriesChannels[waveIndex] == (s == 1) && waveIndex < firstSeriesChannels.length) { waveIndex++; } } if (waveNames != null && waveIndex < waveNames.size()) { store.setChannelName(waveNames.get(waveIndex), i, c); } if (handler.getBinning() != null) binning = handler.getBinning(); if (binning != null) { store.setDetectorSettingsBinning(getBinning(binning), i, c); } if (handler.getReadOutRate() != 0) { store.setDetectorSettingsReadOutRate(handler.getReadOutRate(), i, c); } store.setDetectorSettingsID(detectorID, i, c); if (wave != null && waveIndex < wave.length && (int) wave[waveIndex] >= 1) { store.setChannelLightSourceSettingsWavelength( new PositiveInteger((int) wave[waveIndex]), i, c); // link LightSource to Image String lightSourceID = MetadataTools.createLSID("LightSource", i, c); store.setLaserID(lightSourceID, i, c); store.setChannelLightSourceSettingsID(lightSourceID, i, c); store.setLaserType(getLaserType("Other"), i, c); store.setLaserLaserMedium(getLaserMedium("Other"), i, c); } waveIndex++; } timestamps = handler.getTimestamps(); for (int t=0; t<timestamps.size(); t++) { addSeriesMeta("timestamp " + t, DateTools.formatDate(timestamps.get(t), MEDIUM_DATE_FORMAT)); } long startDate = 0; if (timestamps.size() > 0) { startDate = DateTools.getTime(timestamps.get(0), MEDIUM_DATE_FORMAT); } Double positionX = new Double(handler.getStagePositionX()); Double positionY = new Double(handler.getStagePositionY()); Vector<Double> exposureTimes = handler.getExposures(); if (exposureTimes.size() == 0) { for (int p=0; p<getImageCount(); p++) { exposureTimes.add(exposureTime); } } int lastFile = -1; IFD lastIFD = null; long[] lastOffsets = null; double distance = zStart; for (int p=0; p<getImageCount(); p++) { int[] coords = getZCTCoords(p); Double deltaT = new Double(0); Double exposureTime = new Double(0); Double xmlZPosition = null; int fileIndex = getIndex(0, 0, coords[2]) / getSizeZ(); if (fileIndex >= 0) { String file = stks == null ? currentId : stks[i][fileIndex]; if (file != null) { RandomAccessInputStream stream = new RandomAccessInputStream(file); TiffParser tp = new TiffParser(stream); tp.checkHeader(); if (fileIndex != lastFile) { lastFile = fileIndex; lastOffsets = tp.getIFDOffsets(); } lastIFD = tp.getIFD(lastOffsets[p % lastOffsets.length]); stream.close(); comment = lastIFD.getComment(); if (comment != null) comment = comment.trim(); handler = new MetamorphHandler(getSeriesMetadata()); if (comment != null && comment.startsWith("<MetaData>")) { XMLTools.parseXML(comment, handler); } timestamps = handler.getTimestamps(); exposureTimes = handler.getExposures(); Vector<Double> zPositions = handler.getZPositions(); if (zPositions != null && zPositions.size() > 0) { xmlZPosition = zPositions.get(0); } } } int index = 0; if (timestamps.size() > 0) { if (coords[2] < timestamps.size()) index = coords[2]; String stamp = timestamps.get(index); long ms = DateTools.getTime(stamp, MEDIUM_DATE_FORMAT); deltaT = new Double((ms - startDate) / 1000.0); } else if (internalStamps != null && p < internalStamps.length) { long delta = internalStamps[p] - internalStamps[0]; deltaT = new Double(delta / 1000.0); if (coords[2] < exposureTimes.size()) index = coords[2]; } if (index < exposureTimes.size()) { exposureTime = exposureTimes.get(index); } store.setPlaneDeltaT(deltaT, i, p); store.setPlaneExposureTime(exposureTime, i, p); if (stageX != null && p < stageX.length) { store.setPlanePositionX(stageX[p], i, p); } if (stageY != null && p < stageY.length) { store.setPlanePositionY(stageY[p], i, p); } if (zDistances != null && p < zDistances.length) { if (p > 0) { if (zDistances[p] != 0d) distance += zDistances[p]; else distance += zDistances[0]; } store.setPlanePositionZ(distance, i, p); } else if (xmlZPosition != null) { store.setPlanePositionZ(xmlZPosition, i, p); } } } setSeries(0); }
protected void initFile(String id) throws FormatException, IOException { if (checkSuffix(id, ND_SUFFIX)) { LOGGER.info("Initializing " + id); // find an associated STK file String stkFile = id.substring(0, id.lastIndexOf(".")); if (stkFile.indexOf(File.separator) != -1) { stkFile = stkFile.substring(stkFile.lastIndexOf(File.separator) + 1); } Location parent = new Location(id).getAbsoluteFile().getParentFile(); LOGGER.info("Looking for STK file in {}", parent.getAbsolutePath()); String[] dirList = parent.list(true); for (String f : dirList) { int underscore = f.indexOf("_"); if (underscore < 0) underscore = f.indexOf("."); if (underscore < 0) underscore = f.length(); String prefix = f.substring(0, underscore); if ((f.equals(stkFile) || stkFile.startsWith(prefix)) && checkSuffix(f, STK_SUFFIX)) { stkFile = new Location(parent.getAbsolutePath(), f).getAbsolutePath(); break; } } if (!checkSuffix(stkFile, STK_SUFFIX)) { throw new FormatException("STK file not found in " + parent.getAbsolutePath() + "."); } super.initFile(stkFile); } else super.initFile(id); Location ndfile = null; if (checkSuffix(id, ND_SUFFIX)) ndfile = new Location(id); else if (canLookForND) { // an STK file was passed to initFile // let's check the parent directory for an .nd file Location stk = new Location(id).getAbsoluteFile(); String stkName = stk.getName(); String stkPrefix = stkName; if (stkPrefix.indexOf("_") >= 0) { stkPrefix = stkPrefix.substring(0, stkPrefix.indexOf("_") + 1); } Location parent = stk.getParentFile(); String[] list = parent.list(true); for (String f : list) { if (checkSuffix(f, ND_SUFFIX)) { String prefix = f.substring(0, f.lastIndexOf(".")); if (prefix.indexOf("_") >= 0) { prefix = prefix.substring(0, prefix.indexOf("_") + 1); } if (stkName.startsWith(prefix) || prefix.equals(stkPrefix)) { ndfile = new Location(parent, f).getAbsoluteFile(); if (prefix.equals(stkPrefix)) { break; } } } } } String creationTime = null; if (ndfile != null && ndfile.exists() && (fileGroupOption(id) == FormatTools.MUST_GROUP || isGroupFiles())) { // parse key/value pairs from .nd file int zc = getSizeZ(), cc = getSizeC(), tc = getSizeT(); int nstages = 0; String z = null, c = null, t = null; Vector<Boolean> hasZ = new Vector<Boolean>(); waveNames = new Vector<String>(); stageNames = new Vector<String>(); boolean useWaveNames = true; ndFilename = ndfile.getAbsolutePath(); String[] lines = DataTools.readFile(ndFilename).split("\n"); for (String line : lines) { int comma = line.indexOf(","); if (comma <= 0) continue; String key = line.substring(1, comma - 1).trim(); String value = line.substring(comma + 1).trim(); addGlobalMeta(key, value); if (key.equals("NZSteps")) z = value; else if (key.equals("NWavelengths")) c = value; else if (key.equals("NTimePoints")) t = value; else if (key.startsWith("WaveDoZ")) { hasZ.add(new Boolean(value.toLowerCase())); } else if (key.startsWith("WaveName")) { waveNames.add(value.substring(1, value.length() - 1)); } else if (key.startsWith("Stage")) { stageNames.add(value); } else if (key.startsWith("StartTime")) { creationTime = value; } else if (key.equals("ZStepSize")) { char separator = new DecimalFormatSymbols().getDecimalSeparator(); value = value.replace('.', separator); value = value.replace(',', separator); stepSize = Double.parseDouble(value); } else if (key.equals("NStagePositions")) { nstages = Integer.parseInt(value); } else if (key.equals("WaveInFileName")) { useWaveNames = Boolean.parseBoolean(value); } } // figure out how many files we need if (z != null) zc = Integer.parseInt(z); if (c != null) cc = Integer.parseInt(c); if (t != null) tc = Integer.parseInt(t); if (cc == 0) cc = 1; int numFiles = cc * tc; if (nstages > 0) numFiles *= nstages; // determine series count int seriesCount = nstages == 0 ? 1 : nstages; firstSeriesChannels = new boolean[cc]; Arrays.fill(firstSeriesChannels, true); boolean differentZs = false; for (int i=0; i<cc; i++) { boolean hasZ1 = i < hasZ.size() && hasZ.get(i).booleanValue(); boolean hasZ2 = i != 0 && (i - 1 < hasZ.size()) && hasZ.get(i - 1).booleanValue(); if (i > 0 && hasZ1 != hasZ2) { if (!differentZs) seriesCount *= 2; differentZs = true; } } int channelsInFirstSeries = cc; if (differentZs) { channelsInFirstSeries = 0; for (int i=0; i<cc; i++) { if (hasZ.get(i).booleanValue()) channelsInFirstSeries++; else firstSeriesChannels[i] = false; } } stks = new String[seriesCount][]; if (seriesCount == 1) stks[0] = new String[numFiles]; else if (differentZs) { int stages = nstages == 0 ? 1 : nstages; for (int i=0; i<stages; i++) { stks[i * 2] = new String[channelsInFirstSeries * tc]; stks[i * 2 + 1] = new String[(cc - channelsInFirstSeries) * tc]; } } else { for (int i=0; i<stks.length; i++) { stks[i] = new String[numFiles / stks.length]; } } String prefix = ndfile.getPath(); prefix = prefix.substring(prefix.lastIndexOf(File.separator) + 1, prefix.lastIndexOf(".")); // build list of STK files int[] pt = new int[seriesCount]; for (int i=0; i<tc; i++) { int ns = nstages == 0 ? 1 : nstages; for (int s=0; s<ns; s++) { for (int j=0; j<cc; j++) { boolean validZ = j >= hasZ.size() || hasZ.get(j).booleanValue(); int seriesNdx = s * (seriesCount / ns); if ((seriesCount != 1 && !validZ) || (nstages == 0 && ((!validZ && cc > 1) || seriesCount > 1))) { if (j > 0) { seriesNdx++; } } if (seriesNdx >= stks.length || seriesNdx >= pt.length || pt[seriesNdx] >= stks[seriesNdx].length) { continue; } stks[seriesNdx][pt[seriesNdx]] = prefix; if (j < waveNames.size() && waveNames.get(j) != null) { stks[seriesNdx][pt[seriesNdx]] += "_w" + (j + 1); if (useWaveNames) { String waveName = waveNames.get(j); // If there are underscores in the wavelength name, translate // them to hyphens. (See #558) waveName = waveName.replace('_', '-'); // If there are slashes (forward or backward) in the wavelength // name, translate them to hyphens. (See #5922) waveName = waveName.replace('/', '-'); waveName = waveName.replace('\\', '-'); stks[seriesNdx][pt[seriesNdx]] += waveName; } } if (nstages > 0) { stks[seriesNdx][pt[seriesNdx]] += "_s" + (s + 1); } if (tc > 1) { stks[seriesNdx][pt[seriesNdx]] += "_t" + (i + 1) + ".STK"; } else stks[seriesNdx][pt[seriesNdx]] += ".STK"; pt[seriesNdx]++; } } } ndfile = ndfile.getAbsoluteFile(); // check that each STK file exists for (int s=0; s<stks.length; s++) { for (int f=0; f<stks[s].length; f++) { Location l = new Location(ndfile.getParent(), stks[s][f]); stks[s][f] = getRealSTKFile(l); } } String file = locateFirstValidFile(); if (file == null) { throw new FormatException( "Unable to locate at lease one valid STK file!"); } RandomAccessInputStream s = new RandomAccessInputStream(file); TiffParser tp = new TiffParser(s); IFD ifd = tp.getFirstIFD(); s.close(); core[0].sizeX = (int) ifd.getImageWidth(); core[0].sizeY = (int) ifd.getImageLength(); core[0].sizeZ = zc; core[0].sizeC = cc; core[0].sizeT = tc; core[0].imageCount = zc * tc * cc; core[0].dimensionOrder = "XYZCT"; if (stks != null && stks.length > 1) { CoreMetadata[] newCore = new CoreMetadata[stks.length]; for (int i=0; i<stks.length; i++) { newCore[i] = new CoreMetadata(); newCore[i].sizeX = getSizeX(); newCore[i].sizeY = getSizeY(); newCore[i].sizeZ = getSizeZ(); newCore[i].sizeC = getSizeC(); newCore[i].sizeT = getSizeT(); newCore[i].pixelType = getPixelType(); newCore[i].imageCount = getImageCount(); newCore[i].dimensionOrder = getDimensionOrder(); newCore[i].rgb = isRGB(); newCore[i].littleEndian = isLittleEndian(); newCore[i].interleaved = isInterleaved(); newCore[i].orderCertain = true; } if (stks.length > nstages) { int ns = nstages == 0 ? 1 : nstages; for (int j=0; j<ns; j++) { newCore[j * 2].sizeC = stks[j * 2].length / getSizeT(); newCore[j * 2 + 1].sizeC = stks[j * 2 + 1].length / newCore[j * 2 + 1].sizeT; newCore[j * 2 + 1].sizeZ = 1; newCore[j * 2].imageCount = newCore[j * 2].sizeC * newCore[j * 2].sizeT * newCore[j * 2].sizeZ; newCore[j * 2 + 1].imageCount = newCore[j * 2 + 1].sizeC * newCore[j * 2 + 1].sizeT; } } core = newCore; } } if (stks == null) { stkReaders = new MetamorphReader[1][1]; stkReaders[0][0] = new MetamorphReader(); stkReaders[0][0].setCanLookForND(false); } else { stkReaders = new MetamorphReader[stks.length][]; for (int i=0; i<stks.length; i++) { stkReaders[i] = new MetamorphReader[stks[i].length]; for (int j=0; j<stkReaders[i].length; j++) { stkReaders[i][j] = new MetamorphReader(); stkReaders[i][j].setCanLookForND(false); if (j > 0) { stkReaders[i][j].setMetadataOptions( new DefaultMetadataOptions(MetadataLevel.MINIMUM)); } } } } Vector<String> timestamps = null; MetamorphHandler handler = null; MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this, true); String detectorID = MetadataTools.createLSID("Detector", 0, 0); for (int i=0; i<getSeriesCount(); i++) { setSeries(i); handler = new MetamorphHandler(getSeriesMetadata()); String instrumentID = MetadataTools.createLSID("Instrument", i); store.setInstrumentID(instrumentID, i); store.setImageInstrumentRef(instrumentID, i); if (i == 0) { store.setDetectorID(detectorID, 0, 0); store.setDetectorType(getDetectorType("Other"), 0, 0); } String comment = getFirstComment(i); if (comment != null && comment.startsWith("<MetaData>")) { try { XMLTools.parseXML(XMLTools.sanitizeXML(comment), handler); } catch (IOException e) { } } if (creationTime != null) { String date = DateTools.formatDate(creationTime, SHORT_DATE_FORMAT); store.setImageAcquiredDate(date, 0); } else if (i > 0) MetadataTools.setDefaultCreationDate(store, id, i); store.setImageName(makeImageName(i), i); if (getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM) { continue; } store.setImageDescription("", i); store.setImagingEnvironmentTemperature(handler.getTemperature(), i); if (sizeX == null) sizeX = handler.getPixelSizeX(); if (sizeY == null) sizeY = handler.getPixelSizeY(); if (sizeX > 0) { store.setPixelsPhysicalSizeX(new PositiveFloat(sizeX), i); } if (sizeY > 0) { store.setPixelsPhysicalSizeY(new PositiveFloat(sizeY), i); } if (zDistances != null) { stepSize = zDistances[0]; } if (stepSize > 0) { store.setPixelsPhysicalSizeZ(new PositiveFloat(stepSize), i); } int waveIndex = 0; for (int c=0; c<getEffectiveSizeC(); c++) { if (firstSeriesChannels == null || (stageNames != null && stageNames.size() == getSeriesCount())) { waveIndex = c; } else if (firstSeriesChannels != null) { int s = i % 2; while (firstSeriesChannels[waveIndex] == (s == 1) && waveIndex < firstSeriesChannels.length) { waveIndex++; } } if (waveNames != null && waveIndex < waveNames.size()) { store.setChannelName(waveNames.get(waveIndex), i, c); } if (handler.getBinning() != null) binning = handler.getBinning(); if (binning != null) { store.setDetectorSettingsBinning(getBinning(binning), i, c); } if (handler.getReadOutRate() != 0) { store.setDetectorSettingsReadOutRate(handler.getReadOutRate(), i, c); } store.setDetectorSettingsID(detectorID, i, c); if (wave != null && waveIndex < wave.length && (int) wave[waveIndex] >= 1) { store.setChannelLightSourceSettingsWavelength( new PositiveInteger((int) wave[waveIndex]), i, c); // link LightSource to Image String lightSourceID = MetadataTools.createLSID("LightSource", i, c); store.setLaserID(lightSourceID, i, c); store.setChannelLightSourceSettingsID(lightSourceID, i, c); store.setLaserType(getLaserType("Other"), i, c); store.setLaserLaserMedium(getLaserMedium("Other"), i, c); } waveIndex++; } timestamps = handler.getTimestamps(); for (int t=0; t<timestamps.size(); t++) { addSeriesMeta("timestamp " + t, DateTools.formatDate(timestamps.get(t), MEDIUM_DATE_FORMAT)); } long startDate = 0; if (timestamps.size() > 0) { startDate = DateTools.getTime(timestamps.get(0), MEDIUM_DATE_FORMAT); } Double positionX = new Double(handler.getStagePositionX()); Double positionY = new Double(handler.getStagePositionY()); Vector<Double> exposureTimes = handler.getExposures(); if (exposureTimes.size() == 0) { for (int p=0; p<getImageCount(); p++) { exposureTimes.add(exposureTime); } } int lastFile = -1; IFD lastIFD = null; long[] lastOffsets = null; double distance = zStart; for (int p=0; p<getImageCount(); p++) { int[] coords = getZCTCoords(p); Double deltaT = new Double(0); Double exposureTime = new Double(0); Double xmlZPosition = null; int fileIndex = getIndex(0, 0, coords[2]) / getSizeZ(); if (fileIndex >= 0) { String file = stks == null ? currentId : stks[i][fileIndex]; if (file != null) { RandomAccessInputStream stream = new RandomAccessInputStream(file); TiffParser tp = new TiffParser(stream); tp.checkHeader(); if (fileIndex != lastFile) { lastFile = fileIndex; lastOffsets = tp.getIFDOffsets(); } lastIFD = tp.getIFD(lastOffsets[p % lastOffsets.length]); stream.close(); comment = lastIFD.getComment(); if (comment != null) comment = comment.trim(); handler = new MetamorphHandler(getSeriesMetadata()); if (comment != null && comment.startsWith("<MetaData>")) { XMLTools.parseXML(comment, handler); } timestamps = handler.getTimestamps(); exposureTimes = handler.getExposures(); Vector<Double> zPositions = handler.getZPositions(); if (zPositions != null && zPositions.size() > 0) { xmlZPosition = zPositions.get(0); } } } int index = 0; if (timestamps.size() > 0) { if (coords[2] < timestamps.size()) index = coords[2]; String stamp = timestamps.get(index); long ms = DateTools.getTime(stamp, MEDIUM_DATE_FORMAT); deltaT = new Double((ms - startDate) / 1000.0); } else if (internalStamps != null && p < internalStamps.length) { long delta = internalStamps[p] - internalStamps[0]; deltaT = new Double(delta / 1000.0); if (coords[2] < exposureTimes.size()) index = coords[2]; } if (index < exposureTimes.size()) { exposureTime = exposureTimes.get(index); } store.setPlaneDeltaT(deltaT, i, p); store.setPlaneExposureTime(exposureTime, i, p); if (stageX != null && p < stageX.length) { store.setPlanePositionX(stageX[p], i, p); } if (stageY != null && p < stageY.length) { store.setPlanePositionY(stageY[p], i, p); } if (zDistances != null && p < zDistances.length) { if (p > 0) { if (zDistances[p] != 0d) distance += zDistances[p]; else distance += zDistances[0]; } store.setPlanePositionZ(distance, i, p); } else if (xmlZPosition != null) { store.setPlanePositionZ(xmlZPosition, i, p); } } } setSeries(0); }
diff --git a/com.ggasoftware.indigo.knime.plugin/src/com/ggasoftware/indigo/knime/rautomapper/IndigoReactionAutomapperNodeModel.java b/com.ggasoftware.indigo.knime.plugin/src/com/ggasoftware/indigo/knime/rautomapper/IndigoReactionAutomapperNodeModel.java index 8903140..2b76428 100644 --- a/com.ggasoftware.indigo.knime.plugin/src/com/ggasoftware/indigo/knime/rautomapper/IndigoReactionAutomapperNodeModel.java +++ b/com.ggasoftware.indigo.knime.plugin/src/com/ggasoftware/indigo/knime/rautomapper/IndigoReactionAutomapperNodeModel.java @@ -1,279 +1,282 @@ package com.ggasoftware.indigo.knime.rautomapper; import java.io.File; import java.io.IOException; import org.knime.core.data.DataCell; import org.knime.core.data.DataColumnSpec; import org.knime.core.data.DataColumnSpecCreator; import org.knime.core.data.DataRow; import org.knime.core.data.DataTableSpec; import org.knime.core.data.DataType; import org.knime.core.data.def.DefaultRow; import org.knime.core.data.def.StringCell; import org.knime.core.node.BufferedDataContainer; import org.knime.core.node.BufferedDataTable; import org.knime.core.node.CanceledExecutionException; import org.knime.core.node.ExecutionContext; import org.knime.core.node.ExecutionMonitor; import org.knime.core.node.InvalidSettingsException; import org.knime.core.node.NodeModel; import org.knime.core.node.NodeSettingsRO; import org.knime.core.node.NodeSettingsWO; import org.knime.core.node.defaultnodesettings.SettingsModelBoolean; import org.knime.core.node.defaultnodesettings.SettingsModelColumnName; import org.knime.core.node.defaultnodesettings.SettingsModelInteger; import com.ggasoftware.indigo.IndigoException; import com.ggasoftware.indigo.knime.cell.IndigoDataValue; import com.ggasoftware.indigo.knime.cell.IndigoQueryReactionCell; import com.ggasoftware.indigo.knime.cell.IndigoReactionCell; import com.ggasoftware.indigo.knime.plugin.IndigoPlugin; /** * This is the model implementation of ReactionAutomapper. * * * @author */ public class IndigoReactionAutomapperNodeModel extends NodeModel { public enum AAMode { Discard, Keep, Alter, Clear } static final String CFGKEY_COLUMN = "column"; static final String CFGKEY_REPLACE = "replaceColumn"; static final String CFGKEY_NEWCOLUMN = "newColumn"; static final String CFGKEY_MODE = "mode"; static final String DEFAULT_COLUMN = null; static final boolean DEFAULT_REPLACE = true; static final String DEFAULT_NEWCOLUMN = null; static final int DEFAULT_MODE = AAMode.Discard.ordinal(); private final SettingsModelColumnName m_column = new SettingsModelColumnName( IndigoReactionAutomapperNodeModel.CFGKEY_COLUMN, IndigoReactionAutomapperNodeModel.DEFAULT_COLUMN); private final SettingsModelBoolean m_replace = new SettingsModelBoolean( IndigoReactionAutomapperNodeModel.CFGKEY_REPLACE, IndigoReactionAutomapperNodeModel.DEFAULT_REPLACE); private final SettingsModelColumnName m_newColumn = new SettingsModelColumnName( IndigoReactionAutomapperNodeModel.CFGKEY_NEWCOLUMN, IndigoReactionAutomapperNodeModel.DEFAULT_NEWCOLUMN); private final SettingsModelInteger m_mode = new SettingsModelInteger( IndigoReactionAutomapperNodeModel.CFGKEY_MODE, IndigoReactionAutomapperNodeModel.DEFAULT_MODE ); /** * Constructor for the node model. */ protected IndigoReactionAutomapperNodeModel() { super(1, 2); } /** * {@inheritDoc} */ @Override protected BufferedDataTable[] execute(final BufferedDataTable[] inData, final ExecutionContext exec) throws Exception { DataTableSpec inputTableSpec = inData[0].getDataTableSpec(); DataTableSpec[] outputSpecs = getDataTableSpecs(inputTableSpec); BufferedDataContainer validOutputContainer = exec.createDataContainer(outputSpecs[0]); BufferedDataContainer invalidOutputContainer = exec.createDataContainer(outputSpecs[1]); int colIdx = inputTableSpec.findColumnIndex(m_column.getStringValue()); if (colIdx == -1) throw new Exception("column not found"); int newColIdx = m_replace.getBooleanValue() ? colIdx : inputTableSpec.getNumColumns(); int rowNumber = 1; for (DataRow inputRow : inData[0]) { DataCell[] cells = new DataCell[inputRow.getNumCells() + (m_replace.getBooleanValue() ? 0 : 1)]; DataCell newcell = null; String message = null; try { IndigoPlugin.lock(); if (inputRow.getCell(colIdx) instanceof IndigoReactionCell) { newcell = new IndigoReactionCell(((IndigoReactionCell)inputRow.getCell(colIdx)).getIndigoObject().clone()); } else if (inputRow.getCell(colIdx) instanceof IndigoQueryReactionCell) { IndigoQueryReactionCell reactionCell = (IndigoQueryReactionCell)inputRow.getCell(colIdx); newcell = reactionCell.clone(); + } else { + newcell = DataType.getMissingCell(); } - ((IndigoDataValue)newcell).getIndigoObject().automap(AAMode.values()[m_mode.getIntValue()].name().toLowerCase()); + if(!newcell.isMissing()) + ((IndigoDataValue)newcell).getIndigoObject().automap(AAMode.values()[m_mode.getIntValue()].name().toLowerCase()); } catch (IndigoException e) { message = e.getMessage(); } finally { IndigoPlugin.unlock(); } if (newcell != null) { for (int i = 0; i < inputRow.getNumCells(); i++) { cells[i] = m_replace.getBooleanValue() && i == newColIdx ? newcell : inputRow.getCell(i); } if (!m_replace.getBooleanValue()) { cells[newColIdx] = newcell; } validOutputContainer.addRowToTable(new DefaultRow(inputRow.getKey(), cells)); } else { for (int i = 0; i < inputRow.getNumCells(); i++) { cells[i] = (m_replace.getBooleanValue() && i == newColIdx) ? new StringCell(message) : inputRow.getCell(i); } if (!m_replace.getBooleanValue()) { cells[newColIdx] = new StringCell(message); } invalidOutputContainer.addRowToTable(new DefaultRow(inputRow.getKey(), cells)); } exec.checkCanceled(); exec.setProgress(rowNumber / (double) inData[0].getRowCount(), "Adding row " + rowNumber); rowNumber++; } validOutputContainer.close(); invalidOutputContainer.close(); return new BufferedDataTable[] { validOutputContainer.getTable(), invalidOutputContainer.getTable() }; } /** * {@inheritDoc} */ @Override protected void reset() { } protected DataTableSpec[] getDataTableSpecs (DataTableSpec inputTableSpec) throws InvalidSettingsException { if (m_column.getStringValue() == null || m_column.getStringValue().length() < 1) throw new InvalidSettingsException("Column name not specified"); if (!m_replace.getBooleanValue()) if (m_newColumn.getStringValue() == null || m_newColumn.getStringValue().length() < 1) throw new InvalidSettingsException("No new column name specified"); int colIdx = inputTableSpec.findColumnIndex(m_column.getStringValue()); if (colIdx == -1) throw new InvalidSettingsException("column not found"); String newColName = m_newColumn.getStringValue(); int newColIdx = inputTableSpec.getNumColumns(); if (m_replace.getBooleanValue()) { newColName = m_column.getStringValue(); newColIdx = colIdx; } DataType newtype = inputTableSpec.getColumnSpec(colIdx).getType(); DataColumnSpec validOutputColumnSpec = new DataColumnSpecCreator(newColName, newtype).createSpec(); DataColumnSpec invalidOutputColumnSpec = new DataColumnSpecCreator(newColName, StringCell.TYPE).createSpec(); DataColumnSpec[] validOutputColumnSpecs, invalidOutputColumnSpecs; if (m_replace.getBooleanValue()) { validOutputColumnSpecs = new DataColumnSpec[inputTableSpec.getNumColumns()]; invalidOutputColumnSpecs = new DataColumnSpec[inputTableSpec.getNumColumns()]; } else { validOutputColumnSpecs = new DataColumnSpec[inputTableSpec.getNumColumns() + 1]; invalidOutputColumnSpecs = new DataColumnSpec[inputTableSpec.getNumColumns() + 1]; } for (int i = 0; i < inputTableSpec.getNumColumns(); i++) { DataColumnSpec columnSpec = inputTableSpec.getColumnSpec(i); if (m_replace.getBooleanValue() && i == newColIdx) { validOutputColumnSpecs[i] = validOutputColumnSpec; invalidOutputColumnSpecs[i] = invalidOutputColumnSpec; } else { validOutputColumnSpecs[i] = columnSpec; invalidOutputColumnSpecs[i] = columnSpec; } } if (!m_replace.getBooleanValue()) { validOutputColumnSpecs[newColIdx] = validOutputColumnSpec; invalidOutputColumnSpecs[newColIdx] = invalidOutputColumnSpec; } return new DataTableSpec[] { new DataTableSpec(validOutputColumnSpecs), new DataTableSpec(invalidOutputColumnSpecs) }; } /** * {@inheritDoc} */ @Override protected DataTableSpec[] configure(final DataTableSpec[] inSpecs) throws InvalidSettingsException { return getDataTableSpecs(inSpecs[0]); } /** * {@inheritDoc} */ @Override protected void saveSettingsTo(final NodeSettingsWO settings) { m_column.saveSettingsTo(settings); m_replace.saveSettingsTo(settings); m_newColumn.saveSettingsTo(settings); m_mode.saveSettingsTo(settings); } /** * {@inheritDoc} */ @Override protected void loadValidatedSettingsFrom(final NodeSettingsRO settings) throws InvalidSettingsException { m_column.loadSettingsFrom(settings); m_replace.loadSettingsFrom(settings); m_newColumn.loadSettingsFrom(settings); m_mode.loadSettingsFrom(settings); } /** * {@inheritDoc} */ @Override protected void validateSettings(final NodeSettingsRO settings) throws InvalidSettingsException { m_column.validateSettings(settings); m_replace.validateSettings(settings); m_newColumn.validateSettings(settings); m_mode.validateSettings(settings); } /** * {@inheritDoc} */ @Override protected void loadInternals(final File internDir, final ExecutionMonitor exec) throws IOException, CanceledExecutionException { } /** * {@inheritDoc} */ @Override protected void saveInternals(final File internDir, final ExecutionMonitor exec) throws IOException, CanceledExecutionException { } }
false
true
protected BufferedDataTable[] execute(final BufferedDataTable[] inData, final ExecutionContext exec) throws Exception { DataTableSpec inputTableSpec = inData[0].getDataTableSpec(); DataTableSpec[] outputSpecs = getDataTableSpecs(inputTableSpec); BufferedDataContainer validOutputContainer = exec.createDataContainer(outputSpecs[0]); BufferedDataContainer invalidOutputContainer = exec.createDataContainer(outputSpecs[1]); int colIdx = inputTableSpec.findColumnIndex(m_column.getStringValue()); if (colIdx == -1) throw new Exception("column not found"); int newColIdx = m_replace.getBooleanValue() ? colIdx : inputTableSpec.getNumColumns(); int rowNumber = 1; for (DataRow inputRow : inData[0]) { DataCell[] cells = new DataCell[inputRow.getNumCells() + (m_replace.getBooleanValue() ? 0 : 1)]; DataCell newcell = null; String message = null; try { IndigoPlugin.lock(); if (inputRow.getCell(colIdx) instanceof IndigoReactionCell) { newcell = new IndigoReactionCell(((IndigoReactionCell)inputRow.getCell(colIdx)).getIndigoObject().clone()); } else if (inputRow.getCell(colIdx) instanceof IndigoQueryReactionCell) { IndigoQueryReactionCell reactionCell = (IndigoQueryReactionCell)inputRow.getCell(colIdx); newcell = reactionCell.clone(); } ((IndigoDataValue)newcell).getIndigoObject().automap(AAMode.values()[m_mode.getIntValue()].name().toLowerCase()); } catch (IndigoException e) { message = e.getMessage(); } finally { IndigoPlugin.unlock(); } if (newcell != null) { for (int i = 0; i < inputRow.getNumCells(); i++) { cells[i] = m_replace.getBooleanValue() && i == newColIdx ? newcell : inputRow.getCell(i); } if (!m_replace.getBooleanValue()) { cells[newColIdx] = newcell; } validOutputContainer.addRowToTable(new DefaultRow(inputRow.getKey(), cells)); } else { for (int i = 0; i < inputRow.getNumCells(); i++) { cells[i] = (m_replace.getBooleanValue() && i == newColIdx) ? new StringCell(message) : inputRow.getCell(i); } if (!m_replace.getBooleanValue()) { cells[newColIdx] = new StringCell(message); } invalidOutputContainer.addRowToTable(new DefaultRow(inputRow.getKey(), cells)); } exec.checkCanceled(); exec.setProgress(rowNumber / (double) inData[0].getRowCount(), "Adding row " + rowNumber); rowNumber++; } validOutputContainer.close(); invalidOutputContainer.close(); return new BufferedDataTable[] { validOutputContainer.getTable(), invalidOutputContainer.getTable() }; }
protected BufferedDataTable[] execute(final BufferedDataTable[] inData, final ExecutionContext exec) throws Exception { DataTableSpec inputTableSpec = inData[0].getDataTableSpec(); DataTableSpec[] outputSpecs = getDataTableSpecs(inputTableSpec); BufferedDataContainer validOutputContainer = exec.createDataContainer(outputSpecs[0]); BufferedDataContainer invalidOutputContainer = exec.createDataContainer(outputSpecs[1]); int colIdx = inputTableSpec.findColumnIndex(m_column.getStringValue()); if (colIdx == -1) throw new Exception("column not found"); int newColIdx = m_replace.getBooleanValue() ? colIdx : inputTableSpec.getNumColumns(); int rowNumber = 1; for (DataRow inputRow : inData[0]) { DataCell[] cells = new DataCell[inputRow.getNumCells() + (m_replace.getBooleanValue() ? 0 : 1)]; DataCell newcell = null; String message = null; try { IndigoPlugin.lock(); if (inputRow.getCell(colIdx) instanceof IndigoReactionCell) { newcell = new IndigoReactionCell(((IndigoReactionCell)inputRow.getCell(colIdx)).getIndigoObject().clone()); } else if (inputRow.getCell(colIdx) instanceof IndigoQueryReactionCell) { IndigoQueryReactionCell reactionCell = (IndigoQueryReactionCell)inputRow.getCell(colIdx); newcell = reactionCell.clone(); } else { newcell = DataType.getMissingCell(); } if(!newcell.isMissing()) ((IndigoDataValue)newcell).getIndigoObject().automap(AAMode.values()[m_mode.getIntValue()].name().toLowerCase()); } catch (IndigoException e) { message = e.getMessage(); } finally { IndigoPlugin.unlock(); } if (newcell != null) { for (int i = 0; i < inputRow.getNumCells(); i++) { cells[i] = m_replace.getBooleanValue() && i == newColIdx ? newcell : inputRow.getCell(i); } if (!m_replace.getBooleanValue()) { cells[newColIdx] = newcell; } validOutputContainer.addRowToTable(new DefaultRow(inputRow.getKey(), cells)); } else { for (int i = 0; i < inputRow.getNumCells(); i++) { cells[i] = (m_replace.getBooleanValue() && i == newColIdx) ? new StringCell(message) : inputRow.getCell(i); } if (!m_replace.getBooleanValue()) { cells[newColIdx] = new StringCell(message); } invalidOutputContainer.addRowToTable(new DefaultRow(inputRow.getKey(), cells)); } exec.checkCanceled(); exec.setProgress(rowNumber / (double) inData[0].getRowCount(), "Adding row " + rowNumber); rowNumber++; } validOutputContainer.close(); invalidOutputContainer.close(); return new BufferedDataTable[] { validOutputContainer.getTable(), invalidOutputContainer.getTable() }; }