answer
stringlengths
17
10.2M
package edu.gvsu.tveye.adapter; import android.content.Context; import android.graphics.Color; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; public class SettingsGridAdapter extends BaseAdapter { private String[] names; private Context context; public SettingsGridAdapter(Context context) { this(context, new String[0]); } public SettingsGridAdapter(Context context, String[] names) { this.context = context; this.names = names; } public void setNames(String[] names) { this.names = names; notifyDataSetChanged(); } public int getCount() { return names.length; } public Object getItem(int i) { return names[i]; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { TextView textView; if(convertView == null) { textView = new TextView(context); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 28); textView.setPadding(5, 5, 5, 5); textView.setBackgroundColor(Color.RED); } else { textView = (TextView) convertView; } textView.setText(names[position]); return textView; } }
/** * EditEntityScreen * * Class representing the screen that allows users to edit properties of * grid entities, including triggers and appearance. * * @author Willy McHie * Wheaton College, CSCI 335, Spring 2013 */ package edu.wheaton.simulator.gui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import javax.swing.*; import javax.swing.GroupLayout.Alignment; import com.sun.corba.se.impl.encoding.CodeSetConversion.BTCConverter; import edu.wheaton.simulator.datastructure.ElementAlreadyContainedException; import edu.wheaton.simulator.entity.Prototype; import edu.wheaton.simulator.entity.Trigger; import edu.wheaton.simulator.expression.Expression; //TODO deletes prototype after editing public class EditEntityScreen extends Screen { private static final long serialVersionUID = 4021299442173260142L; private Boolean editing; private Prototype agent; private JTextField nameField; private JColorChooser colorTool; private ArrayList<JTextField> fieldNames; private ArrayList<JTextField> fieldValues; private ArrayList<JComboBox> fieldTypes; private String[] typeNames = { "Integer", "Double", "String", "Boolean" }; private ArrayList<JButton> fieldDeleteButtons; private ArrayList<JPanel> fieldSubPanels; private Component glue; private Component glue2; private JButton addFieldButton; private JToggleButton[][] buttons; private JPanel fieldListPanel; private ArrayList<JTextField> triggerNames; private ArrayList<JTextField> triggerPriorities; private ArrayList<JTextField> triggerConditions; private ArrayList<JTextField> triggerResults; private ArrayList<JButton> triggerDeleteButtons; private ArrayList<JPanel> triggerSubPanels; private JButton addTriggerButton; private JPanel triggerListPanel; private HashSet<Integer> removedFields; private HashSet<Integer> removedTriggers; public EditEntityScreen(final ScreenManager sm) { super(sm); this.setLayout(new BorderLayout()); JLabel label = new JLabel("Edit Entities"); label.setHorizontalAlignment(SwingConstants.CENTER); label.setHorizontalTextPosition(SwingConstants.CENTER); JTabbedPane tabs = new JTabbedPane(); JPanel lowerPanel = new JPanel(); JPanel generalPanel = new JPanel(); JPanel mainPanel = new JPanel(); JPanel iconPanel = new JPanel(); JPanel fieldMainPanel = new JPanel(); JPanel fieldLabelsPanel = new JPanel(); fieldListPanel = new JPanel(); JPanel triggerMainPanel = new JPanel(); JPanel triggerLabelsPanel = new JPanel(); triggerListPanel = new JPanel(); removedFields = new HashSet<Integer>(); removedTriggers = new HashSet<Integer>(); JLabel generalLabel = new JLabel("General Info"); generalLabel.setHorizontalAlignment(SwingConstants.CENTER); generalLabel.setPreferredSize(new Dimension(300, 80)); JLabel nameLabel = new JLabel("Name: "); nameField = new JTextField(25); nameField.setMaximumSize(new Dimension(400, 40)); colorTool = new JColorChooser(); JPanel colorPanel = new JPanel(); colorPanel.add(colorTool); colorPanel.setAlignmentX(LEFT_ALIGNMENT); iconPanel.setLayout(new GridLayout(7, 7)); iconPanel.setMinimumSize(new Dimension(500, 500)); iconPanel.setAlignmentX(RIGHT_ALIGNMENT); buttons = new JToggleButton[7][7]; //Creates the icon design object. for (int i = 0; i < 7; i++) { for (int j = 0; j < 7; j++) { buttons[i][j] = new JToggleButton(); buttons[i][j].setOpaque(true); buttons[i][j].setBackground(Color.WHITE); buttons[i][j].setActionCommand(i + "" + j); //When the button is pushed it switches colors. buttons[i][j].addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { String str = ae.getActionCommand(); JToggleButton jb = buttons[Integer.parseInt(str .charAt(0) + "")][Integer.parseInt(str .charAt(1) + "")]; if (jb.getBackground().equals(Color.WHITE)) jb.setBackground(Color.BLACK); else jb.setBackground(Color.WHITE); } }); iconPanel.add(buttons[i][j]); } } JButton loadIconButton = new JButton("Load icon"); mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS)); mainPanel.setMaximumSize(new Dimension(1200, 500)); generalPanel .setLayout(new BoxLayout(generalPanel, BoxLayout.PAGE_AXIS)); mainPanel.add(colorPanel); mainPanel.add(iconPanel); generalPanel.add(generalLabel); generalPanel.add(nameLabel); generalPanel.add(nameField); generalPanel.add(mainPanel); generalPanel.add(loadIconButton); JLabel fieldLabel = new JLabel("Field Info"); fieldLabel.setHorizontalAlignment(SwingConstants.CENTER); fieldLabel.setPreferredSize(new Dimension(300, 100)); JLabel fieldNameLabel = new JLabel("Field Name"); fieldNameLabel.setPreferredSize(new Dimension(200, 30)); JLabel fieldValueLabel = new JLabel("Field Initial Value"); fieldValueLabel.setPreferredSize(new Dimension(400, 30)); JLabel fieldTypeLabel = new JLabel("Field Type"); fieldNameLabel.setPreferredSize(new Dimension(350, 30)); fieldNames = new ArrayList<JTextField>(); fieldValues = new ArrayList<JTextField>(); fieldTypes = new ArrayList<JComboBox>(); fieldDeleteButtons = new ArrayList<JButton>(); fieldSubPanels = new ArrayList<JPanel>(); addFieldButton = new JButton("Add Field"); addFieldButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { addField(); } }); glue = Box.createVerticalGlue(); addField(); // TODO make sure components line up fieldMainPanel.setLayout(new BorderLayout()); JPanel fieldBodyPanel = new JPanel(); fieldBodyPanel.setLayout(new BoxLayout(fieldBodyPanel, BoxLayout.Y_AXIS)); fieldLabelsPanel.setLayout(new BoxLayout(fieldLabelsPanel, BoxLayout.X_AXIS)); fieldListPanel.setLayout(new BoxLayout(fieldListPanel, BoxLayout.Y_AXIS)); fieldSubPanels.get(0).setLayout( new BoxLayout(fieldSubPanels.get(0), BoxLayout.X_AXIS)); fieldMainPanel.add(fieldLabel, BorderLayout.NORTH); fieldLabelsPanel.add(Box.createHorizontalGlue()); fieldLabelsPanel.add(fieldNameLabel); fieldNameLabel.setHorizontalAlignment(SwingConstants.LEFT); fieldNameLabel.setAlignmentX(LEFT_ALIGNMENT); fieldLabelsPanel.add(fieldTypeLabel); fieldTypeLabel.setHorizontalAlignment(SwingConstants.LEFT); fieldLabelsPanel.add(fieldValueLabel); fieldLabelsPanel.add(Box.createHorizontalGlue()); fieldValueLabel.setHorizontalAlignment(SwingConstants.CENTER); fieldSubPanels.get(0).add(fieldNames.get(0)); fieldSubPanels.get(0).add(fieldTypes.get(0)); fieldSubPanels.get(0).add(fieldValues.get(0)); fieldSubPanels.get(0).add(fieldDeleteButtons.get(0)); fieldListPanel.add(fieldSubPanels.get(0)); fieldListPanel.add(addFieldButton); fieldListPanel.add(glue); // fieldSubPanels.get(0).setAlignmentY(TOP_ALIGNMENT); fieldBodyPanel.add(fieldLabelsPanel); fieldBodyPanel.add(fieldListPanel); fieldMainPanel.add(fieldBodyPanel, BorderLayout.CENTER); JLabel triggerLabel = new JLabel("Trigger Info"); triggerLabel.setHorizontalAlignment(SwingConstants.CENTER); triggerLabel.setPreferredSize(new Dimension(300, 100)); JLabel triggerNameLabel = new JLabel("Trigger Name"); triggerNameLabel.setPreferredSize(new Dimension(130, 30)); JLabel triggerPriorityLabel = new JLabel("Trigger Priority"); triggerPriorityLabel.setPreferredSize(new Dimension(180, 30)); JLabel triggerConditionLabel = new JLabel("Trigger Condition"); triggerConditionLabel.setPreferredSize(new Dimension(300, 30)); JLabel triggerResultLabel = new JLabel("Trigger Result"); triggerResultLabel.setPreferredSize(new Dimension(300, 30)); triggerNames = new ArrayList<JTextField>(); triggerPriorities = new ArrayList<JTextField>(); triggerConditions = new ArrayList<JTextField>(); triggerResults = new ArrayList<JTextField>(); triggerDeleteButtons = new ArrayList<JButton>(); triggerSubPanels = new ArrayList<JPanel>(); addTriggerButton = new JButton("Add Trigger"); addTriggerButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { addTrigger(); } }); glue2 = Box.createVerticalGlue(); addTrigger(); // TODO make sure components line up triggerMainPanel.setLayout(new BorderLayout()); JPanel triggerBodyPanel = new JPanel(); triggerBodyPanel.setLayout(new BoxLayout(triggerBodyPanel, BoxLayout.Y_AXIS)); triggerLabelsPanel.setLayout(new BoxLayout(triggerLabelsPanel, BoxLayout.X_AXIS)); triggerListPanel.setLayout(new BoxLayout(triggerListPanel, BoxLayout.Y_AXIS)); triggerSubPanels.get(0).setLayout( new BoxLayout(triggerSubPanels.get(0), BoxLayout.X_AXIS)); triggerMainPanel.add(triggerLabel, BorderLayout.NORTH); triggerLabelsPanel.add(Box.createHorizontalGlue()); triggerLabelsPanel.add(triggerNameLabel); triggerNameLabel.setHorizontalAlignment(SwingConstants.LEFT); triggerLabelsPanel.add(triggerPriorityLabel); triggerLabelsPanel.add(triggerConditionLabel); triggerLabelsPanel.add(triggerResultLabel); triggerLabelsPanel.add(Box.createHorizontalGlue()); triggerSubPanels.get(0).add(triggerNames.get(0)); triggerSubPanels.get(0).add(triggerPriorities.get(0)); triggerSubPanels.get(0).add(triggerConditions.get(0)); triggerSubPanels.get(0).add(triggerResults.get(0)); triggerSubPanels.get(0).add(triggerDeleteButtons.get(0)); triggerListPanel.add(triggerSubPanels.get(0)); triggerListPanel.add(addTriggerButton); triggerListPanel.add(glue2); triggerBodyPanel.add(triggerLabelsPanel); triggerLabelsPanel.setAlignmentX(CENTER_ALIGNMENT); triggerBodyPanel.add(triggerListPanel); triggerSubPanels.get(0).setAlignmentX(CENTER_ALIGNMENT); // triggerSubPanels.get(0).setAlignmentY(TOP_ALIGNMENT); triggerMainPanel.add(triggerBodyPanel, BorderLayout.CENTER); tabs.addTab("General", generalPanel); tabs.addTab("Fields", fieldMainPanel); tabs.addTab("Triggers", triggerMainPanel); JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { sm.update(sm.getScreen("Edit Simulation")); reset(); } }); JButton finishButton = new JButton("Finish"); finishButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (sendInfo()) { sm.update(sm.getScreen("Edit Simulation")); reset(); } } }); lowerPanel.add(cancelButton); lowerPanel.add(finishButton); this.add(label, BorderLayout.NORTH); this.add(tabs, BorderLayout.CENTER); this.add(lowerPanel, BorderLayout.SOUTH); } public void load(String str) { reset(); agent = sm.getFacade().getPrototype(str); nameField.setText(agent.getName()); colorTool.setColor(agent.getColor()); byte[] designBytes = agent.getDesign(); for (byte b : designBytes) System.out.println("lB:" + b); byte byter = Byte.parseByte("0000001", 2); for (int i = 0; i < 7; i++) { for (int j = 0; j < 7; j++) { if ((designBytes[i] & (byter << j)) != Byte.parseByte("0000000", 2)) { buttons[i][6-j].doClick(); } } } Map<String, String> fields = agent.getFieldMap(); int i = 0; for (String s : fields.keySet()) { addField(); fieldNames.get(i).setText(s); fieldValues.get(i).setText(s); i++; } List<Trigger> triggers = agent.getTriggers(); int j = 0; for (Trigger t : triggers) { addTrigger(); triggerNames.get(j).setText(t.getName()); triggerConditions.get(j).setText(t.getConditions().toString()); triggerResults.get(j).setText(t.getBehavior().toString()); triggerPriorities.get(j).setText(t.getPriority() +""); } } public void reset() { agent = null; nameField.setText(""); colorTool.setColor(Color.WHITE); for (int x = 0; x < 7; x++) { for (int y = 0; y < 7; y++) { buttons[x][y].setSelected(false); buttons[x][y].setBackground(Color.WHITE); } } fieldNames.clear(); fieldTypes.clear(); fieldValues.clear(); fieldDeleteButtons.clear(); fieldSubPanels.clear(); removedFields.clear(); fieldListPanel.removeAll(); fieldListPanel.add(addFieldButton); triggerNames.clear(); triggerPriorities.clear(); triggerConditions.clear(); triggerResults.clear(); triggerDeleteButtons.clear(); triggerSubPanels.clear(); removedTriggers.clear(); triggerListPanel.removeAll(); triggerListPanel.add(addTriggerButton); } public boolean sendInfo() { boolean toReturn = false; try { for (int i = 0; i < fieldNames.size(); i++) { if (fieldNames.get(i).getText().equals("") || fieldValues.get(i).getText().equals("")) { throw new Exception("All fields must have input"); } } for (int j = 0; j < triggerNames.size(); j++) { if (triggerNames.get(j).getText().equals("") || triggerConditions.get(j).getText().equals("") || triggerResults.get(j).getText().equals("")) { throw new Exception("All fields must have input"); } if (Integer.parseInt(triggerPriorities.get(j).getText()) < 0) { throw new Exception("Priority must be greater than 0"); } } if (!editing) { sm.getFacade().createPrototype(nameField.getText(), sm.getFacade().getGrid(), colorTool.getColor(), generateBytes()); agent = sm.getFacade().getPrototype(nameField.getText()); } else { agent.setPrototypeName(agent.getName(), nameField.getText()); agent.setColor(colorTool.getColor()); agent.setDesign(generateBytes()); Prototype.addPrototype(agent.getName(), agent); } for (int i = 0; i < fieldNames.size(); i++) { if (removedFields.contains(i)) { if (agent.hasField(fieldNames.get(i).getText())) agent.removeField(fieldNames.get(i)); } else { if (agent.hasField(fieldNames.get(i).getText())) { agent.updateField(fieldNames.get(i).getText(), fieldValues.get(i).getText()); } else try { agent.addField(fieldNames.get(i).getText(), fieldValues.get(i).getText()); } catch (ElementAlreadyContainedException e) { e.printStackTrace(); } } } for (int i = 0; i < triggerNames.size(); i++) { if (removedTriggers.contains(i)) { if (agent.hasTrigger(triggerNames.get(i).getText())) agent.removeTrigger(triggerNames.get(i).getText()); } else { if (agent.hasTrigger(triggerNames.get(i).getText())) agent.updateTrigger(triggerNames.get(i).getText(), generateTrigger(i)); else agent.addTrigger(generateTrigger(i)); } } for (int i = 0; i < triggerNames.size(); i++) { if (removedTriggers.contains(i)) { if (agent.hasTrigger(triggerNames.get(i).getText())) agent.removeTrigger(triggerNames.get(i).getText()); } else { if (agent.hasTrigger(triggerNames.get(i).getText())) agent.updateTrigger(triggerNames.get(i).getText(), generateTrigger(i)); else agent.addTrigger(generateTrigger(i)); } } toReturn = true; } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "Priorities field must be an integer greater than 0."); e.printStackTrace(); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage()); } finally { return toReturn; } } public void setEditing(Boolean b) { editing = b; } private void addField() { JPanel newPanel = new JPanel(); newPanel.setLayout(new BoxLayout(newPanel, BoxLayout.X_AXIS)); JTextField newName = new JTextField(25); newName.setMaximumSize(new Dimension(300, 40)); fieldNames.add(newName); JComboBox newType = new JComboBox(typeNames); newType.setMaximumSize(new Dimension(200, 40)); fieldTypes.add(newType); JTextField newValue = new JTextField(25); newValue.setMaximumSize(new Dimension(300, 40)); fieldValues.add(newValue); JButton newButton = new JButton("Delete"); newButton.addActionListener(new DeleteFieldListener()); fieldDeleteButtons.add(newButton); newButton.setActionCommand(fieldDeleteButtons.indexOf(newButton) + ""); newPanel.add(newName); newPanel.add(newType); newPanel.add(newValue); newPanel.add(newButton); fieldSubPanels.add(newPanel); fieldListPanel.add(newPanel); fieldListPanel.add(addFieldButton); fieldListPanel.add(glue); repaint(); } private void addTrigger() { JPanel newPanel = new JPanel(); newPanel.setLayout(new BoxLayout(newPanel, BoxLayout.X_AXIS)); JTextField newName = new JTextField(25); newName.setMaximumSize(new Dimension(200, 40)); triggerNames.add(newName); JTextField newPriority = new JTextField(15); newPriority.setMaximumSize(new Dimension(150, 40)); triggerPriorities.add(newPriority); JTextField newCondition = new JTextField(50); newCondition.setMaximumSize(new Dimension(300, 40)); triggerConditions.add(newCondition); JTextField newResult = new JTextField(50); newResult.setMaximumSize(new Dimension(300, 40)); triggerResults.add(newResult); JButton newButton = new JButton("Delete"); newButton.addActionListener(new DeleteTriggerListener()); triggerDeleteButtons.add(newButton); newButton.setActionCommand(triggerDeleteButtons.indexOf(newButton) + ""); newPanel.add(newName); newPanel.add(newPriority); newPanel.add(newCondition); newPanel.add(newResult); newPanel.add(newButton); triggerSubPanels.add(newPanel); triggerListPanel.add(newPanel); triggerListPanel.add(addTriggerButton); triggerListPanel.add(glue2); repaint(); } private byte[] generateBytes() { String str = ""; byte[] toReturn = new byte[7]; for (int column = 0; column < 7; column++) { for (int row = 0; row < 7; row++) { if (buttons[column][row].getBackground().equals(Color.BLACK)) { System.out.print("1"); str += "1"; } else { System.out.print("0"); str += "0"; } } str += ":"; System.out.print(":"); } str = str.substring(0, str.lastIndexOf(':')); String[] byteStr = str.split(":"); System.out.println("BOO: " + str); for (String s : byteStr) System.out.println("genB:" +s); for (int i = 0; i < 7; i++) { toReturn[i] = Byte.parseByte(byteStr[i], 2); } return toReturn; } private Trigger generateTrigger(int i) { return new Trigger(triggerNames.get(i).getText(), Integer.parseInt(triggerPriorities.get(i).getText()), new Expression(triggerConditions.get(i).getText()), new Expression(triggerResults.get(i).getText())); } private class DeleteFieldListener implements ActionListener { private String action; @Override public void actionPerformed(ActionEvent e) { removedFields.add(Integer.parseInt(e.getActionCommand())); fieldListPanel.remove(fieldSubPanels.get(Integer.parseInt(e .getActionCommand()))); repaint(); } } private class DeleteTriggerListener implements ActionListener { private String action; @Override public void actionPerformed(ActionEvent e) { removedTriggers.add(Integer.parseInt(e.getActionCommand())); triggerListPanel.remove(triggerSubPanels.get(Integer.parseInt(e .getActionCommand()))); repaint(); } } @Override public void load() { reset(); addField(); addTrigger(); } }
/* Open Source Software - may be modified and shared by FRC teams. The code */ /* the project. */ package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.Jaguar; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.SimpleRobot; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.buttons.JoystickButton; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the SimpleRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Salamander extends SimpleRobot { boolean gearboxstate = false, b, a, prevalue = false; //Jags Jaguar leftDrive1 = new Jaguar(2); Jaguar rightDrive1 = new Jaguar(1); //Joystick Joystick rightJoy = new Joystick(1); Joystick leftJoy = new Joystick(2); //Buttons JoystickButton leftTrig = new JoystickButton(leftJoy,1); JoystickButton rightTrig = new JoystickButton(rightJoy,1); //int double speedVal =0.5; public void autonomous() { SmartDashboard.putString("Mode:", " Auto"); leftDrive1.set((0.2)*(-1)); rightDrive1.set((0.2)); Timer.delay(1); leftDrive1.set(0); rightDrive1.set(0); } public void operatorControl() { SmartDashboard.putString("Mode:"," Enabled"); while(isEnabled() && isOperatorControl()) { Timer.delay(0.1); leftDrive1.set((leftJoy.getY())*(speedVal)*(-1)); rightDrive1.set((rightJoy.getY())*(speedVal)); //Software Gearbox if (leftTrig.get() && rightTrig.get()) { a = true; // b if both buttons pressed } else { a = false; } if (!prevalue && a){ gearboxstate=!gearboxstate; } if (gearboxstate){ SmartDashboard.putString("Gear:", " HIGH"); speedVal =1; } else { SmartDashboard.putString("Gear:", " LOW"); speedVal =0.5; } if (a){ prevalue = true; } else { prevalue = false; } } } public void disabled() { SmartDashboard.putString("Mode:"," Disabled"); speedVal =0.5; //Print Disabled to dashboard } }
package emergencylanding.k.library.debug; import java.util.HashMap; import org.lwjgl.opengl.Display; import emergencylanding.k.library.internalstate.Entity; import emergencylanding.k.library.lwjgl.DisplayLayer; import emergencylanding.k.library.lwjgl.render.Render; import emergencylanding.k.library.main.KMain; import emergencylanding.k.library.sound.SoundPlayer; import emergencylanding.k.library.util.LUtils; public class TestSound extends KMain { public static void main(String[] args) throws Exception { DisplayLayer.initDisplay(false, 800, 600, "Testing EL Sound", true, args); while (!Display.isCloseRequested()) { DisplayLayer.loop(120); } DisplayLayer.destroy(); System.exit(0); } @Override public void onDisplayUpdate(int delta) { DisplayLayer.readDevices(); } @Override public void init(String[] args) { SoundPlayer.playWAV(LUtils.TOP_LEVEL.getAbsolutePath() + "\\res\\wav\\test.wav", 1.0f, .50f, true); SoundPlayer.playWAV(LUtils.TOP_LEVEL.getAbsolutePath() + "\\res\\wav\\test.wav", 1.0f, .10f, true); SoundPlayer.playWAV(LUtils.TOP_LEVEL.getAbsolutePath() + "\\res\\wav\\test.wav", 1.0f, .15f, true); } @Override public void registerRenders( HashMap<Class<? extends Entity>, Render<? extends Entity>> classToRender) { } }
package gov.nih.nci.calab.ui.core; import gov.nih.nci.calab.dto.characterization.CharacterizationBean; import gov.nih.nci.calab.dto.characterization.CharacterizationTypeBean; import gov.nih.nci.calab.dto.common.InstrumentBean; import gov.nih.nci.calab.dto.common.LabFileBean; import gov.nih.nci.calab.dto.common.ProtocolBean; import gov.nih.nci.calab.dto.common.ProtocolFileBean; import gov.nih.nci.calab.dto.common.UserBean; import gov.nih.nci.calab.dto.function.FunctionBean; import gov.nih.nci.calab.dto.inventory.AliquotBean; import gov.nih.nci.calab.dto.inventory.ContainerBean; import gov.nih.nci.calab.dto.inventory.ContainerInfoBean; import gov.nih.nci.calab.dto.inventory.SampleBean; import gov.nih.nci.calab.dto.remote.GridNodeBean; import gov.nih.nci.calab.dto.workflow.AssayBean; import gov.nih.nci.calab.dto.workflow.RunBean; import gov.nih.nci.calab.exception.InvalidSessionException; import gov.nih.nci.calab.service.common.LookupService; import gov.nih.nci.calab.service.search.GridSearchService; import gov.nih.nci.calab.service.search.SearchNanoparticleService; import gov.nih.nci.calab.service.search.SearchReportService; import gov.nih.nci.calab.service.security.UserService; import gov.nih.nci.calab.service.submit.SubmitNanoparticleService; import gov.nih.nci.calab.service.util.CaNanoLabComparators; import gov.nih.nci.calab.service.util.CaNanoLabConstants; import gov.nih.nci.calab.service.util.StringUtils; import gov.nih.nci.calab.service.workflow.ExecuteWorkflowService; import gov.nih.nci.security.exceptions.CSException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.struts.util.LabelValueBean; /** * This class sets up session level or servlet context level variables to be * used in various actions during the setup of query forms. * * @author pansu * */ public class InitSessionSetup { private static LookupService lookupService; private static UserService userService; private InitSessionSetup() throws Exception { lookupService = new LookupService(); userService = new UserService(CaNanoLabConstants.CSM_APP_NAME); } public static InitSessionSetup getInstance() throws Exception { return new InitSessionSetup(); } public void setCurrentRun(HttpServletRequest request) throws Exception { HttpSession session = request.getSession(); String runId = (String) request.getParameter("runId"); if (runId == null && session.getAttribute("currentRun") == null) { throw new InvalidSessionException( "The session containing a run doesn't exists."); } else if (runId == null && session.getAttribute("currentRun") != null) { RunBean currentRun = (RunBean) session.getAttribute("currentRun"); runId = currentRun.getId(); } if (session.getAttribute("currentRun") == null || session.getAttribute("newRunCreated") != null) { ExecuteWorkflowService executeWorkflowService = new ExecuteWorkflowService(); RunBean runBean = executeWorkflowService.getCurrentRun(runId); session.setAttribute("currentRun", runBean); } session.removeAttribute("newRunCreated"); } public void clearRunSession(HttpSession session) { session.removeAttribute("currentRun"); } public void setAllUsers(HttpSession session) throws Exception { if ((session.getAttribute("newUserCreated") != null) || (session.getServletContext().getAttribute("allUsers") == null)) { List allUsers = userService.getAllUsers(); session.getServletContext().setAttribute("allUsers", allUsers); } session.removeAttribute("newUserCreated"); } public void setSampleSourceUnmaskedAliquots(HttpSession session) throws Exception { // set map between sample source and samples that have unmasked aliquots if (session.getAttribute("sampleSourceSamplesWithUnmaskedAliquots") == null || session.getAttribute("allSampleSourcesWithUnmaskedAliquots") == null || session.getAttribute("newAliquotCreated") != null) { Map<String, SortedSet<SampleBean>> sampleSourceSamples = lookupService .getSampleSourceSamplesWithUnmaskedAliquots(); session.setAttribute("sampleSourceSamplesWithUnmaskedAliquots", sampleSourceSamples); List<String> sources = new ArrayList<String>(sampleSourceSamples .keySet()); session.setAttribute("allSampleSourcesWithUnmaskedAliquots", sources); } setAllSampleUnmaskedAliquots(session); session.removeAttribute("newAliquotCreated"); } public void clearSampleSourcesWithUnmaskedAliquotsSession( HttpSession session) { session.removeAttribute("allSampleSourcesWithUnmaskedAliquots"); } public void setAllSampleUnmaskedAliquots(HttpSession session) throws Exception { // set map between samples and unmasked aliquots if (session.getAttribute("allUnmaskedSampleAliquots") == null || session.getAttribute("newAliquotCreated") != null) { Map<String, SortedSet<AliquotBean>> sampleAliquots = lookupService .getUnmaskedSampleAliquots(); List<String> sampleNames = new ArrayList<String>(sampleAliquots .keySet()); Collections.sort(sampleNames, new CaNanoLabComparators.SortableNameComparator()); session.setAttribute("allUnmaskedSampleAliquots", sampleAliquots); session.setAttribute("allSampleNamesWithAliquots", sampleNames); } session.removeAttribute("newAliquotCreated"); } public void clearSampleUnmaskedAliquotsSession(HttpSession session) { session.removeAttribute("allUnmaskedSampleAliquots"); session.removeAttribute("allSampleNamesWithAliquots"); } public void setAllAssayTypeAssays(HttpSession session) throws Exception { if (session.getServletContext().getAttribute("allAssayTypes") == null) { List assayTypes = lookupService.getAllAssayTypes(); session.getServletContext().setAttribute("allAssayTypes", assayTypes); } if (session.getServletContext().getAttribute("allAssayTypeAssays") == null) { Map<String, SortedSet<AssayBean>> assayTypeAssays = lookupService .getAllAssayTypeAssays(); List<String> assayTypes = new ArrayList<String>(assayTypeAssays .keySet()); session.getServletContext().setAttribute("allAssayTypeAssays", assayTypeAssays); session.getServletContext().setAttribute("allAvailableAssayTypes", assayTypes); } } public void setAllSampleSources(HttpSession session) throws Exception { if (session.getAttribute("allSampleSources") == null || session.getAttribute("newSampleCreated") != null) { List sampleSources = lookupService.getAllSampleSources(); session.setAttribute("allSampleSources", sampleSources); } // clear the new sample created flag session.removeAttribute("newSampleCreated"); } public void clearSampleSourcesSession(HttpSession session) { session.removeAttribute("allSampleSources"); } public void setAllSampleContainerTypes(HttpSession session) throws Exception { if (session.getAttribute("allSampleContainerTypes") == null || session.getAttribute("newSampleCreated") != null) { List containerTypes = lookupService.getAllSampleContainerTypes(); session.setAttribute("allSampleContainerTypes", containerTypes); } // clear the new sample created flag session.removeAttribute("newSampleCreated"); } public void clearSampleContainerTypesSession(HttpSession session) { session.removeAttribute("allSampleContainerTypes"); } public void setAllSampleTypes(ServletContext appContext) throws Exception { if (appContext.getAttribute("allSampleTypes") == null) { List sampleTypes = lookupService.getAllSampleTypes(); appContext.setAttribute("allSampleTypes", sampleTypes); } } public void clearSampleTypesSession(HttpSession session) { // session.removeAttribute("allSampleTypes"); } public void setAllSampleSOPs(HttpSession session) throws Exception { if (session.getServletContext().getAttribute("allSampleSOPs") == null) { List sampleSOPs = lookupService.getAllSampleSOPs(); session.getServletContext().setAttribute("allSampleSOPs", sampleSOPs); } } public void setAllSampleContainerInfo(HttpSession session) throws Exception { if (session.getAttribute("sampleContainerInfo") == null || session.getAttribute("newSampleCreated") != null) { ContainerInfoBean containerInfo = lookupService .getSampleContainerInfo(); session.setAttribute("sampleContainerInfo", containerInfo); } // clear the new sample created flag session.removeAttribute("newSampleCreated"); } public void setCurrentUser(HttpSession session) throws Exception { // get user and date information String creator = ""; if (session.getAttribute("user") != null) { UserBean user = (UserBean) session.getAttribute("user"); creator = user.getLoginName(); } String creationDate = StringUtils.convertDateToString(new Date(), CaNanoLabConstants.DATE_FORMAT); session.setAttribute("creator", creator); session.setAttribute("creationDate", creationDate); } public void setAllAliquotContainerTypes(HttpSession session) throws Exception { if (session.getAttribute("allAliquotContainerTypes") == null || session.getAttribute("newAliquotCreated") != null) { List containerTypes = lookupService.getAllAliquotContainerTypes(); session.setAttribute("allAliquotContainerTypes", containerTypes); } session.removeAttribute("newAliquotCreated"); } public void clearAliquotContainerTypesSession(HttpSession session) { session.removeAttribute("allAliquotContainerTypes"); } public void setAllAliquotContainerInfo(HttpSession session) throws Exception { if (session.getAttribute("aliquotContainerInfo") == null || session.getAttribute("newAliquotCreated") != null) { ContainerInfoBean containerInfo = lookupService .getAliquotContainerInfo(); session.setAttribute("aliquotContainerInfo", containerInfo); } session.removeAttribute("newAliquotCreated"); } public void setAllAliquotCreateMethods(HttpSession session) throws Exception { if (session.getServletContext().getAttribute("aliquotCreateMethods") == null) { List methods = lookupService.getAliquotCreateMethods(); session.getServletContext().setAttribute("aliquotCreateMethods", methods); } } public void setAllSampleContainers(HttpSession session) throws Exception { if (session.getAttribute("allSampleContainers") == null || session.getAttribute("newSampleCreated") != null) { Map<String, SortedSet<ContainerBean>> sampleContainers = lookupService .getAllSampleContainers(); List<String> sampleNames = new ArrayList<String>(sampleContainers .keySet()); Collections.sort(sampleNames, new CaNanoLabComparators.SortableNameComparator()); session.setAttribute("allSampleContainers", sampleContainers); session.setAttribute("allSampleNames", sampleNames); } session.removeAttribute("newSampleCreated"); } public void clearSampleContainersSession(HttpSession session) { session.removeAttribute("allSampleContainers"); session.removeAttribute("allSampleNames"); } public void setAllSourceSampleIds(HttpSession session) throws Exception { if (session.getAttribute("allSourceSampleIds") == null || session.getAttribute("newSampleCreated") != null) { List sourceSampleIds = lookupService.getAllSourceSampleIds(); session.setAttribute("allSourceSampleIds", sourceSampleIds); } // clear the new sample created flag session.removeAttribute("newSampleCreated"); } public void clearSourceSampleIdsSession(HttpSession session) { session.removeAttribute("allSourceSampleIds"); } public void clearWorkflowSession(HttpSession session) { clearRunSession(session); clearSampleSourcesWithUnmaskedAliquotsSession(session); clearSampleUnmaskedAliquotsSession(session); session.removeAttribute("httpFileUploadSessionData"); } public void clearSearchSession(HttpSession session) { clearSampleTypesSession(session); clearSampleContainerTypesSession(session); clearAliquotContainerTypesSession(session); clearSourceSampleIdsSession(session); clearSampleSourcesSession(session); session.removeAttribute("aliquots"); session.removeAttribute("sampleContainers"); } public void clearInventorySession(HttpSession session) { clearSampleTypesSession(session); clearSampleContainersSession(session); clearSampleContainerTypesSession(session); clearSampleUnmaskedAliquotsSession(session); clearAliquotContainerTypesSession(session); session.removeAttribute("createSampleForm"); session.removeAttribute("createAliquotForm"); session.removeAttribute("aliquotMatrix"); } public static LookupService getLookupService() { return lookupService; } public static UserService getUserService() { return userService; } public boolean canUserExecuteClass(HttpSession session, Class classObj) throws CSException { UserBean user = (UserBean) session.getAttribute("user"); // assume the part of the package name containing the function domain // is the same as the protection element defined in CSM String[] nameStrs = classObj.getName().split("\\."); String domain = nameStrs[nameStrs.length - 2]; return userService.checkExecutePermission(user, domain); } public void setParticleTypeParticles(HttpSession session) throws Exception { if (session.getAttribute("particleTypeParticles") == null || session.getAttribute("newSampleCreated") != null || session.getAttribute("newParticleCreated") != null) { Map<String, SortedSet<String>> particleTypeParticles = lookupService .getAllParticleTypeParticles(); List<String> particleTypes = new ArrayList<String>( particleTypeParticles.keySet()); Collections.sort(particleTypes); session.setAttribute("allParticleTypeParticles", particleTypeParticles); session.setAttribute("allParticleTypes", particleTypes); } session.removeAttribute("newParticleCreated"); } public void setAllVisibilityGroups(HttpSession session) throws Exception { if (session.getAttribute("allVisibilityGroups") == null || session.getAttribute("newSampleCreated") != null) { List<String> groupNames = userService.getAllVisibilityGroups(); session.setAttribute("allVisibilityGroups", groupNames); } } public void setAllDendrimerCores(HttpSession session) throws Exception { if (session.getServletContext().getAttribute("allDendrimerCores") == null) { String[] dendrimerCores = lookupService.getAllDendrimerCores(); session.getServletContext().setAttribute("allDendrimerCores", dendrimerCores); } } public void setAllDendrimerSurfaceGroupNames(HttpSession session) throws Exception { if (session.getServletContext().getAttribute( "allDendrimerSurfaceGroupNames") == null || session.getAttribute("newCharacterizationCreated") != null) { String[] surfaceGroupNames = lookupService .getAllDendrimerSurfaceGroupNames(); session.getServletContext().setAttribute( "allDendrimerSurfaceGroupNames", surfaceGroupNames); } } public void setAllDendrimerBranches(HttpSession session) throws Exception { if (session.getServletContext().getAttribute("allDendrimerBranches") == null || session.getAttribute("newCharacterizationCreated") != null) { String[] branches = lookupService.getAllDendrimerBranches(); session.getServletContext().setAttribute("allDendrimerBranches", branches); } } public void setAllDendrimerGenerations(HttpSession session) throws Exception { if (session.getServletContext().getAttribute("allDendrimerGenerations") == null || session.getAttribute("newCharacterizationCreated") != null) { String[] generations = lookupService.getAllDendrimerGenerations(); session.getServletContext().setAttribute("allDendrimerGenerations", generations); } } public void addSessionAttributeElement(HttpSession session, String attributeName, String newElement) throws Exception { String[] attributeValues = (String[]) session.getServletContext() .getAttribute(attributeName); if (!StringUtils.contains(attributeValues, newElement, true)) { session.getServletContext().setAttribute(attributeName, StringUtils.add(attributeValues, newElement)); } } public void setAllMetalCompositions(HttpSession session) throws Exception { if (session.getServletContext().getAttribute("allMetalCompositions") == null) { String[] compositions = lookupService.getAllMetalCompositions(); session.getServletContext().setAttribute("allMetalCompositions", compositions); } } public void setAllPolymerInitiators(HttpSession session) throws Exception { if ((session.getServletContext().getAttribute("allPolymerInitiators") == null) || (session.getAttribute("newCharacterizationCreated") != null)) { String[] initiators = lookupService.getAllPolymerInitiators(); session.getServletContext().setAttribute("allPolymerInitiators", initiators); } } public void setAllParticleSources(HttpSession session) throws Exception { if (session.getAttribute("allParticleSources") == null || session.getAttribute("newSampleCreated") != null) { List particleSources = lookupService.getAllParticleSources(); session.setAttribute("allParticleSources", particleSources); } // clear the new sample created flag session.removeAttribute("newSampleCreated"); } public void setSideParticleMenu(HttpServletRequest request, String particleName, String particleType) throws Exception { HttpSession session = request.getSession(); UserBean user = (UserBean) session.getAttribute("user"); SearchReportService searchReportService = new SearchReportService(); if (session.getAttribute("particleReports") == null || session.getAttribute("newReportCreated") != null || session.getAttribute("newParticleCreated") != null) { List<LabFileBean> reportBeans = searchReportService .getReportInfo(particleName, particleType, CaNanoLabConstants.REPORT, user); session.setAttribute("particleReports", reportBeans); } if (session.getAttribute("particleAssociatedFiles") == null || session.getAttribute("newReportCreated") != null || session.getAttribute("newParticleCreated") != null) { List<LabFileBean> associatedBeans = searchReportService .getReportInfo(particleName, particleType, CaNanoLabConstants.ASSOCIATED_FILE, user); session.setAttribute("particleAssociatedFiles", associatedBeans); } // not part of the side menu, but need to up if (session.getAttribute("newParticleCreated") != null) { setParticleTypeParticles(session); } session.removeAttribute("newParticleCreated"); session.removeAttribute("newReportCreated"); session.removeAttribute("detailPage"); setStaticDropdowns(session); setAllFunctionTypes(session); setFunctionTypeFunctions(session, particleName, particleType); setAllCharacterizations(session, particleName, particleType); } /** * Set characterizations stored in the database * * @param session * @param particleName * @param particleType * @throws Exception */ public void setAllCharacterizations(HttpSession session, String particleName, String particleType) throws Exception { setAllCharacterizationTypes(session); Map<String, List<String>> charTypeChars = (Map<String, List<String>>) session .getServletContext().getAttribute("allCharTypeChars"); if (session.getAttribute("allCharacterizations") == null || session.getAttribute("newCharacterizationCreated") != null || session.getAttribute("newParticleCreated") != null) { SearchNanoparticleService service = new SearchNanoparticleService(); List<CharacterizationBean> charBeans = service .getCharacterizationInfo(particleName, particleType); Map<String, List<CharacterizationBean>> charMap = new HashMap<String, List<CharacterizationBean>>(); for (String charType : charTypeChars.keySet()) { List<CharacterizationBean> newCharBeans = new ArrayList<CharacterizationBean>(); List<String> charList = (List<String>) charTypeChars .get(charType); for (CharacterizationBean charBean : charBeans) { if (charList.contains(charBean.getName())) { newCharBeans.add(charBean); } } if (!newCharBeans.isEmpty()) { charMap.put(charType, newCharBeans); } } session.setAttribute("allCharacterizations", charMap); } session.removeAttribute("newCharacterizationCreated"); session.removeAttribute("newParticleCreated"); } public void setFunctionTypeFunctions(HttpSession session, String particleName, String particleType) throws Exception { if (session.getAttribute("allFuncTypeFuncs") == null || session.getAttribute("newFunctionCreated") != null) { SearchNanoparticleService service = new SearchNanoparticleService(); Map<String, List<FunctionBean>> funcTypeFuncs = service .getFunctionInfo(particleName, particleType); session.setAttribute("allFuncTypeFuncs", funcTypeFuncs); } session.removeAttribute("newFunctionCreated"); } public void setRemoteSideParticleMenu(HttpServletRequest request, String particleName, GridNodeBean gridNode) throws Exception { HttpSession session = request.getSession(); GridSearchService service = new GridSearchService(); if (session.getAttribute("remoteCharTypeChars") == null || session.getAttribute("newCharacterizationCreated") != null || session.getAttribute("newRemoteParticleCreated") != null) { Map<String, List<CharacterizationBean>> charTypeChars = service .getRemoteCharacterizationMap(particleName, gridNode); session.setAttribute("remoteCharTypeChars", charTypeChars); } if (session.getAttribute("remoteFuncTypeFuncs") == null || session.getAttribute("newFunctionCreated") != null || session.getAttribute("newRemoteParticleCreated") != null) { Map<String, List<FunctionBean>> funcTypeFuncs = service .getRemoteFunctionMap(particleName, gridNode); session.setAttribute("remoteFuncTypeFuncs", funcTypeFuncs); } if (session.getAttribute("remoteParticleReports") == null || session.getAttribute("newReportCreated") != null || session.getAttribute("newRemoteParticleCreated") != null) { List<LabFileBean> reportBeans = service.getRemoteReports( particleName, gridNode); session.setAttribute("remoteParticleReports", reportBeans); } if (session.getAttribute("remoteParticleAssociatedFiles") == null || session.getAttribute("newReportCreated") != null || session.getAttribute("newRemoteParticleCreated") != null) { List<LabFileBean> associatedBeans = service .getRemoteAssociatedFiles(particleName, gridNode); session.setAttribute("remoteParticleAssociatedFiles", associatedBeans); } // not part of the side menu, but need to up if (session.getAttribute("newRemoteParticleCreated") != null) { setParticleTypeParticles(session); } session.removeAttribute("newCharacterizationCreated"); session.removeAttribute("newFunctionCreated"); session.removeAttribute("newRemoteParticleCreated"); session.removeAttribute("newReportCreated"); session.removeAttribute("detailPage"); setStaticDropdowns(session); } public void setAllMorphologyTypes(HttpSession session) throws Exception { if (session.getServletContext().getAttribute("allMorphologyTypes") == null) { String[] morphologyTypes = lookupService.getAllMorphologyTypes(); session.getServletContext().setAttribute("allMorphologyTypes", morphologyTypes); } } public void setAllShapeTypes(HttpSession session) throws Exception { if (session.getServletContext().getAttribute("allShapeTypes") == null) { String[] shapeTypes = lookupService.getAllShapeTypes(); session.getServletContext().setAttribute("allShapeTypes", shapeTypes); } } public void setAllStressorTypes(HttpSession session) throws Exception { if (session.getServletContext().getAttribute("allStessorTypes") == null) { String[] stressorTypes = lookupService.getAllStressorTypes(); session.getServletContext().setAttribute("allStressorTypes", stressorTypes); } } public void setStaticDropdowns(HttpSession session) { // set static boolean yes or no and characterization source choices session.setAttribute("booleanChoices", CaNanoLabConstants.BOOLEAN_CHOICES); session.setAttribute("characterizationSources", CaNanoLabConstants.CHARACTERIZATION_SOURCES); session.setAttribute("allCarbonNanotubeWallTypes", CaNanoLabConstants.CARBON_NANOTUBE_WALLTYPES); if (session.getAttribute("allReportTypes") == null) { String[] allReportTypes = lookupService.getAllReportTypes(); session.setAttribute("allReportTypes", allReportTypes); } session.setAttribute("allFunctionLinkageTypes", CaNanoLabConstants.FUNCTION_LINKAGE_TYPES); session.setAttribute("allFunctionAgentTypes", CaNanoLabConstants.FUNCTION_AGENT_TYPES); } public void setProtocolType(HttpSession session) throws Exception { // set protocol types, and protocol names for all these types SortedSet<String> protocolTypes = lookupService.getAllProtocolTypes(); for (int i = 0; i < CaNanoLabConstants.PROTOCOL_TYPES.length; i++) { if (!protocolTypes.contains(CaNanoLabConstants.PROTOCOL_TYPES[i])) protocolTypes.add(CaNanoLabConstants.PROTOCOL_TYPES[i]); } session.setAttribute("protocolTypes", protocolTypes); } public void setProtocolSubmitPage(HttpSession session, UserBean user) throws Exception { // set protocol types, and protocol names for all these types setProtocolType(session); SortedSet<String> protocolTypes = (SortedSet<String>) session .getAttribute("protocolTypes"); SortedSet<ProtocolBean> pbs = lookupService.getAllProtocols(user); // Now generate two maps: one for type and nameList, // and one for type and protocolIdList (for the protocol name dropdown // box) Map<String, List<String>> typeNamesMap = new HashMap<String, List<String>>(); Map<String, List<String>> typeIdsMap = new HashMap<String, List<String>>(); Map<String, List<String>> nameVersionsMap = new HashMap<String, List<String>>(); Map<String, List<String>> nameIdsMap = new HashMap<String, List<String>>(); for (String type : protocolTypes) { for (ProtocolBean pb : pbs) { if (type.equals(pb.getType())) { List<String> nameList = typeNamesMap.get(type); List<String> idList = typeIdsMap.get(type); if (nameList == null) { nameList = new ArrayList<String>(); nameList.add(pb.getName()); typeNamesMap.put(type, nameList); } else { nameList.add(pb.getName()); } if (idList == null) { idList = new ArrayList<String>(); idList.add(pb.getId().toString()); typeIdsMap.put(type, idList); } else { idList.add(pb.getId().toString()); } } } } for (ProtocolBean pb : pbs) { String id = pb.getId(); List<String> versionList = new ArrayList<String>(); List<String> idList = new ArrayList<String>(); List<ProtocolFileBean> fileBeanList = pb.getFileBeanList(); Map<String, ProtocolFileBean> map = new HashMap<String, ProtocolFileBean>(); for (ProtocolFileBean fb : fileBeanList) { versionList.add(fb.getVersion()); map.put(fb.getVersion(), fb); } String[] vlist = versionList.toArray(new String[0]); Arrays.sort(vlist); versionList.clear(); for (int i = 0; i < vlist.length; i++) { ProtocolFileBean fb = map.get(vlist[i]); versionList.add(fb.getVersion()); idList.add(fb.getId()); } nameVersionsMap.put(id, versionList); nameIdsMap.put(id, idList); } session.setAttribute("AllProtocolTypeNames", typeNamesMap); session.setAttribute("AllProtocolTypeIds", typeIdsMap); session.setAttribute("protocolNames", new ArrayList<String>()); session.setAttribute("AllProtocolNameVersions", nameVersionsMap); session.setAttribute("AllProtocolNameFileIds", nameIdsMap); session.setAttribute("protocolVersions", new ArrayList<String>()); } public void setAllProtocolNameVersionsByType(HttpSession session, String type) throws Exception { // set protocol name and its versions for a given protocol type. Map<ProtocolBean, List<ProtocolFileBean>> nameVersions = lookupService .getAllProtocolNameVersionByType(type); SortedSet<LabelValueBean> set = new TreeSet<LabelValueBean>(); Set keySet = nameVersions.keySet(); for (Iterator it = keySet.iterator(); it.hasNext();) { ProtocolBean pb = (ProtocolBean) it.next(); List<ProtocolFileBean> fbList = nameVersions.get(pb); for (ProtocolFileBean fb : fbList) { set.add(new LabelValueBean(pb.getName() + " - " + fb.getVersion(), fb.getId())); } } session.setAttribute("protocolNameVersionsByType", set); } public void setAllRunFiles(HttpSession session, String particleName) throws Exception { if (session.getAttribute("allRunFiles") == null || session.getAttribute("newParticleCreated") != null || session.getAttribute("newFileLoaded") != null) { SubmitNanoparticleService service = new SubmitNanoparticleService(); List<LabFileBean> runFileBeans = service .getAllRunFiles(particleName); session.setAttribute("allRunFiles", runFileBeans); } session.removeAttribute("newParticleCreated"); session.removeAttribute("newFileLoaded"); } public void setAllAreaMeasureUnits(HttpSession session) throws Exception { if (session.getServletContext().getAttribute("allAreaMeasureUnits") == null) { String[] areaUnits = lookupService.getAllAreaMeasureUnits(); session.getServletContext().setAttribute("allAreaMeasureUnits", areaUnits); } } public void setAllChargeMeasureUnits(HttpSession session) throws Exception { if (session.getServletContext().getAttribute("allChargeMeasureUnits") == null) { String[] chargeUnits = lookupService.getAllChargeMeasureUnits(); session.getServletContext().setAttribute("allChargeMeasureUnits", chargeUnits); } } public void setAllControlTypes(HttpSession session) throws Exception { if (session.getServletContext().getAttribute("allControlTypes") == null) { String[] controlTypes = lookupService.getAllControlTypes(); session.getServletContext().setAttribute("allControlTypes", controlTypes); } } public void setAllConditionTypes(HttpSession session) throws Exception { if (session.getServletContext().getAttribute("allConditionTypes") == null) { String[] conditionTypes = lookupService.getAllConditionTypes(); session.getServletContext().setAttribute("allConditionTypes", conditionTypes); } } public void setAllConditionUnits(HttpSession session) throws Exception { if (session.getServletContext().getAttribute("allConditionTypeUnits") == null) { Map<String, String[]> conditionTypeUnits = lookupService .getAllConditionUnits(); session.getServletContext().setAttribute("allConditionTypeUnits", conditionTypeUnits); } } public void setAllAgentTypes(HttpSession session) throws Exception { if (session.getServletContext().getAttribute("allAgentTypes") == null) { Map<String, String[]> agentTypes = lookupService.getAllAgentTypes(); session.getServletContext().setAttribute("allAgentTypes", agentTypes); } } public void setAllAgentTargetTypes(HttpSession session) throws Exception { if (session.getServletContext().getAttribute("allAgentTargetTypes") == null) { Map<String, String[]> agentTargetTypes = lookupService .getAllAgentTargetTypes(); session.getServletContext().setAttribute("allAgentTargetTypes", agentTargetTypes); } } public void setAllTimeUnits(HttpSession session) throws Exception { if (session.getServletContext().getAttribute("allTimeUnits") == null) { String[] timeUnits = lookupService.getAllTimeUnits(); session.getServletContext().setAttribute("allTimeUnits", timeUnits); } } public void setAllConcentrationUnits(HttpSession session) throws Exception { if (session.getServletContext().getAttribute("allConcentrationUnits") == null) { String[] concentrationUnits = lookupService .getAllConcentrationUnits(); session.getServletContext().setAttribute("allConcentrationUnits", concentrationUnits); } } public void setAllCellLines(HttpSession session) throws Exception { if (session.getServletContext().getAttribute("allCellLines") == null) { String[] cellLines = lookupService.getAllCellLines(); session.getServletContext().setAttribute("allCellLines", cellLines); } } public void setAllActivationMethods(HttpSession session) throws Exception { if (session.getServletContext().getAttribute("allActivationMethods") == null) { String[] activationMethods = lookupService .getAllActivationMethods(); session.getServletContext().setAttribute("allActivationMethods", activationMethods); } } public void setAllSpecies(HttpSession session) throws Exception { if (session.getServletContext().getAttribute("allSpecies") == null) { List<LabelValueBean> species = lookupService.getAllSpecies(); session.getServletContext().setAttribute("allSpecies", species); } } public void setApplicationOwner(HttpSession session) { if (session.getServletContext().getAttribute("applicationOwner") == null) { session.getServletContext().setAttribute("applicationOwner", CaNanoLabConstants.APP_OWNER); } } // public void addCellLine(HttpSession session, String option) throws // Exception { // String[] cellLines = (String[]) // session.getServletContext().getAttribute("allCellLines"); // if (!StringHelper.contains(cellLines, option, true)) { // session.getServletContext().setAttribute("allCellLines", // StringHelper.add(cellLines, option)); /** * Create default CSM groups for default visible groups and admin * */ public void createDefaultCSMGroups() throws Exception { for (String groupName : CaNanoLabConstants.VISIBLE_GROUPS) { userService.createAGroup(groupName); } userService.createAGroup(CaNanoLabConstants.CSM_ADMIN); } public void setAllInstruments(HttpSession session) throws Exception { if (session.getAttribute("allInstruments") == null || session.getAttribute("newInstrumentCreated") != null) { List<InstrumentBean> instruments = lookupService .getAllInstruments(); List<String> manufacturers = new ArrayList<String>(); Map<String, List<String>> typeToManufacturers = new TreeMap<String, List<String>>(); List<String> instrumentTypes = new ArrayList<String>(); for (InstrumentBean instrument : instruments) { String type = instrument.getType(); if (typeToManufacturers.get(type) != null) { manufacturers = (List<String>) typeToManufacturers .get(type); } else { manufacturers = new ArrayList<String>(); typeToManufacturers.put(type, manufacturers); } manufacturers.add(instrument.getManufacturer()); if (!instrumentTypes.contains(type)) { instrumentTypes.add(type); } } session.setAttribute("allInstruments", instruments); session.setAttribute("allInstrumentTypeToManufacturers", typeToManufacturers); } session.removeAttribute("newInstrumentCreated"); } public void setAllDerivedDataFileTypes(HttpSession session) throws Exception { if (session.getAttribute("allDerivedDataFileTypes") == null || session.getAttribute("newCharacterizationCreated") != null) { List<String> fileTypes = lookupService.getAllDerivedDataFileTypes(); session.setAttribute("allDerivedDataFileTypes", fileTypes); } session.removeAttribute("newCharacterizationCreated"); } public void setAllFunctionTypes(HttpSession session) throws Exception { // set in application context if (session.getServletContext().getAttribute("allFunctionTypes") == null) { List<String> types = lookupService.getAllFunctionTypes(); session.getServletContext().setAttribute("allFunctionTypes", types); } } public void setAllCharacterizationTypes(HttpSession session) throws Exception { // set in application context if (session.getServletContext() .getAttribute("allCharacterizationTypes") == null) { List<CharacterizationTypeBean> types = lookupService .getAllCharacterizationTypes(); session.getServletContext().setAttribute( "allCharacterizationTypes", types); } // set in application context mapping between characterization type and // child characterization names if (session.getServletContext().getAttribute("allCharTypeChars") == null) { Map<String, List<String>> charTypeChars = lookupService .getCharacterizationTypeCharacterizations(); session.getServletContext().setAttribute("allCharTypeChars", charTypeChars); } } public void setDerivedDataCategoriesDatumNames(HttpSession session, String characterizationName) throws Exception { List<String> categories = lookupService .getDerivedDataCategories(characterizationName); session.setAttribute("derivedDataCategories", categories); List<String> datumNames = lookupService .getDerivedDatumNames(characterizationName); session.setAttribute("datumNames", datumNames); } public void setAllCharacterizationMeasureUnitsTypes(HttpSession session, String charName) throws Exception { Map<String, List<String>> unitMap = lookupService.getAllMeasureUnits(); List<String> charUnits = unitMap.get(charName); //add an empty one to indicate no unit charUnits.add(""); if (charUnits == null) { charUnits = new ArrayList<String>(); } List<String> types = lookupService.getAllMeasureTypes(); session.setAttribute("charMeasureUnits", charUnits); session.setAttribute("charMeasureTypes", types); } }
package info.tregmine.listeners; import java.util.EnumSet; import java.util.Set; import org.bukkit.Location; import org.bukkit.entity.Arrow; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; import org.bukkit.event.entity.EntityDamageByEntityEvent; //import org.bukkit.ChatColor; //import org.bukkit.entity.Arrow; //import org.bukkit.event.entity.EntityDamageEvent; //import org.bukkit.event.entity.EntityShootBowEvent; import info.tregmine.Tregmine; import info.tregmine.api.TregminePlayer; import info.tregmine.quadtree.Point; import info.tregmine.zones.Zone; import info.tregmine.zones.Lot; import info.tregmine.zones.ZoneWorld; public class ZoneEntityListener implements Listener { private static final Set<EntityType> allowedMobs = EnumSet.of( EntityType.CHICKEN, EntityType.COW, EntityType.PIG, EntityType.SHEEP, EntityType.SQUID, EntityType.WOLF, EntityType.IRON_GOLEM, EntityType.SNOWMAN, EntityType.BAT, EntityType.VILLAGER, EntityType.MUSHROOM_COW, EntityType.OCELOT, EntityType.HORSE); private Tregmine plugin; public ZoneEntityListener(Tregmine instance) { this.plugin = instance; } @EventHandler public void onCreatureSpawn(CreatureSpawnEvent event) { Entity entity = event.getEntity(); Location location = event.getLocation(); Point pos = new Point(location.getBlockX(), location.getBlockZ()); ZoneWorld world = plugin.getWorld(entity.getWorld()); Zone zone = world.findZone(pos); if (zone == null || zone.hasHostiles()) { return; } if (!allowedMobs.contains(event.getEntityType()) && event.getSpawnReason() == SpawnReason.NATURAL) { event.setCancelled(true); } } @EventHandler public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { if (event.getEntity().getWorld().getName().matches("world_the_end")) { return; } if (!(event instanceof EntityDamageByEntityEvent)) { return; } if (!(event.getEntity() instanceof Player)) { return; } EntityDamageByEntityEvent edbeEvent = (EntityDamageByEntityEvent)event; if (!(edbeEvent.getDamager() instanceof Player)) { return; } Entity entity = event.getEntity(); ZoneWorld world = plugin.getWorld(entity.getWorld()); TregminePlayer player = plugin.getPlayer((Player) event.getEntity()); Location location = player.getLocation(); Point pos = new Point(location.getBlockX(), location.getBlockZ()); Zone currentZone = player.updateCurrentZone(); if (currentZone == null) { event.setCancelled(true); return; } if (currentZone == null || !currentZone.isPvp()) { event.setCancelled(true); } else { event.setCancelled(false); return; } Lot currentLot = world.findLot(pos); if (currentLot == null) { event.setCancelled(true); return; } if (currentLot.hasFlag(Lot.Flags.PVP)) { event.setCancelled(false); return; } else { event.setCancelled(true); } } @EventHandler public void onDamage(EntityDamageByEntityEvent e) { Entity e1 = e.getEntity(); Entity d1 = e.getDamager(); if (e1 instanceof Player && d1 instanceof Arrow) { if (((Arrow)d1).getShooter() instanceof Player) { ZoneWorld world = plugin.getWorld(e1.getWorld()); TregminePlayer player = plugin.getPlayer((Player) e1); Location location = player.getLocation(); Point pos = new Point(location.getBlockX(), location.getBlockZ()); Zone currentZone = player.updateCurrentZone(); if (currentZone == null) { e.setCancelled(true); return; } Lot currentLot = world.findLot(pos); if (currentLot == null) { e.setCancelled(true); return; } if (currentLot.hasFlag(Lot.Flags.PVP)) { e.setCancelled(false); } else { e.setCancelled(true); } } } } }
package io.flutter.jxbrowser; import com.intellij.openapi.application.ApplicationListener; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.SystemInfo; import com.teamdev.jxbrowser.engine.Engine; import com.teamdev.jxbrowser.engine.EngineOptions; import com.teamdev.jxbrowser.engine.PasswordStore; import io.flutter.FlutterInitializer; import java.io.File; import java.nio.file.Paths; import static com.teamdev.jxbrowser.engine.RenderingMode.HARDWARE_ACCELERATED; import static com.teamdev.jxbrowser.engine.RenderingMode.OFF_SCREEN; public class EmbeddedBrowserEngine { private static final Logger LOG = Logger.getInstance(EmbeddedBrowserEngine.class); private final Engine engine; public static EmbeddedBrowserEngine getInstance() { return ServiceManager.getService(EmbeddedBrowserEngine.class); } public EmbeddedBrowserEngine() { final String dataPath = JxBrowserManager.DOWNLOAD_PATH + File.separatorChar + "user-data"; LOG.info("JxBrowser user data path: " + dataPath); // TODO(helin24): HiDPI environments is not currently supported for Linux, but once it is we can change to HARDWARE_ACCELERATED there. final EngineOptions.Builder optionsBuilder = EngineOptions.newBuilder(SystemInfo.isMac ? HARDWARE_ACCELERATED : OFF_SCREEN) .userDataDir(Paths.get(dataPath)) .passwordStore(PasswordStore.BASIC) .addSwitch("--disable-features=NativeNotifications"); if (SystemInfo.isLinux) { optionsBuilder.addSwitch("--force-device-scale-factor=1"); } final EngineOptions options = optionsBuilder.build(); Engine temp; try { temp = Engine.newInstance(options); } catch (Exception ex) { temp = null; LOG.info(ex); FlutterInitializer.getAnalytics().sendExpectedException("jxbrowser-engine", ex); } engine = temp; ApplicationManager.getApplication().addApplicationListener(new ApplicationListener() { @Override public boolean canExitApplication() { try { if (engine != null && !engine.isClosed()) { engine.close(); } } catch (Exception ex) { LOG.info(ex); FlutterInitializer.getAnalytics().sendExpectedException("jxbrowswer-engine-close", ex); } return true; } }); } public Engine getEngine() { return engine; } }
// $Id: TrimmedTile.java,v 1.3 2002/06/19 23:28:14 mdb Exp $ package com.threerings.media.tile; import java.awt.Graphics; import java.awt.Image; import java.awt.Rectangle; import java.awt.Shape; import java.awt.image.BufferedImage; import com.samskivert.util.StringUtil; import com.threerings.media.util.ImageUtil; /** * Behaves just like a regular tile, but contains a "trimmed" image which * is one where the source image has been trimmed to the smallest * rectangle that contains all the non-transparent pixels of the original * image. */ public class TrimmedTile extends Tile { /** * Creates a trimmed tile using the supplied tileset image with the * specified bounds and coordinates. * * @param tilesetSource the tileset image that contains our trimmed * tile image. * @param bounds contains the width and height of the * <em>untrimmed</em> tile, but the x and y offset of the * <em>trimmed</em> tile image in the supplied tileset source image. * @param tbounds the bounds of the trimmed image in the coordinate * system defined by the untrimmed image. */ public TrimmedTile (Image image, Rectangle bounds, Rectangle tbounds) { super(image, bounds); _tbounds = tbounds; } // documentation inherited public void paint (Graphics gfx, int x, int y) { if (_subimage == null) { createSubImage(); } gfx.drawImage(_subimage, x + _tbounds.x, y + _tbounds.y, null); } /** * Returns the bounds of the trimmed image within the coordinate * system defined by the complete virtual tile. The returned rectangle * should <em>not</em> be modified. */ public Rectangle getTrimmedBounds () { return _tbounds; } // documentation inherited public Image getImage () { String errmsg = "Can't convert trimmed tile to image " + "[tile=" + this + "]."; throw new RuntimeException(errmsg); } // documentation inherited public boolean hitTest (int x, int y) { return ImageUtil.hitTest(_image, _bounds.x + x, _bounds.y + y); } // documentation inherited protected void createSubImage () { if (_image instanceof BufferedImage) { _subimage = ImageUtil.getSubimage(_image, _bounds.x, _bounds.y, _tbounds.width, _tbounds.height); } else { String errmsg = "Can't obtain tile image [tile=" + this + "]."; throw new RuntimeException(errmsg); } } // documentation inherited protected void toString (StringBuffer buf) { buf.append(", tbounds=").append(StringUtil.toString(_tbounds)); } /** The dimensions of the trimmed image in the coordinate space * defined by the untrimmed image. */ protected Rectangle _tbounds; }
package com.vaklinov.zcashui; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.border.EtchedBorder; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableColumnModel; import javax.swing.table.TableColumn; public class AddressBookPanel extends JPanel { private static class AddressBookEntry { final String name,address; AddressBookEntry(String name, String address) { this.name = name; this.address = address; } } private final List<AddressBookEntry> entries = new ArrayList<>(); private final Set<String> names = new HashSet<>(); private JTable table; private JButton sendCashButton, deleteContactButton,copyToClipboardButton; private JPanel buildButtonsPanel() { JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED)); panel.setLayout(new FlowLayout(FlowLayout.CENTER, 3, 3)); JButton newContactButton = new JButton("New contact..."); panel.add(newContactButton); sendCashButton = new JButton("Send ZCash"); sendCashButton.setEnabled(false); panel.add(sendCashButton); copyToClipboardButton = new JButton("Copy address to clipboard"); copyToClipboardButton.setEnabled(false); panel.add(copyToClipboardButton); deleteContactButton = new JButton("Delete contact"); deleteContactButton.setEnabled(false); panel.add(deleteContactButton); return panel; } private JScrollPane buildTablePanel() { table = new JTable(new AddressBookTableModel(),new DefaultTableColumnModel()); TableColumn nameColumn = new TableColumn(0); TableColumn addressColumn = new TableColumn(1); table.addColumn(nameColumn); table.addColumn(addressColumn); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // one at a time table.getSelectionModel().addListSelectionListener(new AddressListSelectionListener()); table.addMouseListener(new AddressMouseListener()); JScrollPane scrollPane = new JScrollPane(table); return scrollPane; } public AddressBookPanel() { BoxLayout boxLayout = new BoxLayout(this,BoxLayout.Y_AXIS); setLayout(boxLayout); add(buildTablePanel()); add(buildButtonsPanel()); // add some entries for testing AddressBookEntry entry1 = new AddressBookEntry("pesho","asdf"); AddressBookEntry entry2 = new AddressBookEntry("gosho","fdsa"); AddressBookEntry entry3 = new AddressBookEntry("tosho","qwer"); entries.add(entry1);entries.add(entry2);entries.add(entry3); } private class AddressMouseListener extends MouseAdapter { @Override public void mousePressed(MouseEvent e) { if (e.isConsumed() || (!e.isPopupTrigger())) return; int row = table.rowAtPoint(e.getPoint()); int column = table.columnAtPoint(e.getPoint()); table.changeSelection(row, column, false, false); AddressBookEntry entry = entries.get(row); JPopupMenu menu = new JPopupMenu(); JMenuItem sendCash = new JMenuItem("Send ZCash to "+entry.name); menu.add(sendCash); JMenuItem copyAddress = new JMenuItem("Copy address to clipboard"); menu.add(copyAddress); JMenuItem deleteEntry = new JMenuItem("Delete "+entry.name+" from contacts"); menu.add(deleteEntry); menu.show(e.getComponent(), e.getPoint().x, e.getPoint().y); e.consume(); } } private class AddressListSelectionListener implements ListSelectionListener { @Override public void valueChanged(ListSelectionEvent e) { int row = table.getSelectedRow(); if (row < 0) { sendCashButton.setEnabled(false); deleteContactButton.setEnabled(false); copyToClipboardButton.setEnabled(false); return; } String name = entries.get(row).name; sendCashButton.setText("Send ZCash to "+name); sendCashButton.setEnabled(true); deleteContactButton.setText("Delete contact "+name); deleteContactButton.setEnabled(true); copyToClipboardButton.setEnabled(true); } } private class AddressBookTableModel extends AbstractTableModel { @Override public int getRowCount() { return entries.size(); } @Override public int getColumnCount() { return 2; } @Override public String getColumnName(int columnIndex) { switch(columnIndex) { case 0 : return "name"; case 1 : return "address"; default: throw new IllegalArgumentException("invalid column "+columnIndex); } } @Override public Class<?> getColumnClass(int columnIndex) { return String.class; } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return false; } @Override public Object getValueAt(int rowIndex, int columnIndex) { AddressBookEntry entry = entries.get(rowIndex); switch(columnIndex) { case 0 : return entry.name; case 1 : return entry.address; default: throw new IllegalArgumentException("bad column "+columnIndex); } } } }
package org.jaxen.function; import java.util.List; import org.jaxen.Context; import org.jaxen.Function; import org.jaxen.FunctionCallException; import org.jaxen.Navigator; public class RoundFunction implements Function { /** Returns the nearest integer to the number. * * @param context the context at the point in the * expression when the function is called * @param args a list with exactly one item which will be converted to a * <code>Double</code> as if by the XPath <code>number()</code> function * * @return a <code>Double</code> containing the integer nearest to * <code>args.get(0)</code> * * @throws FunctionCallException if <code>args</code> has more or less than one item */ public Object call(Context context, List args) throws FunctionCallException { if (args.size() == 1) { return evaluate( args.get(0), context.getNavigator() ); } throw new FunctionCallException( "round() requires one argument." ); } /** * Returns the integer nearest to the argument. * If necessary, the argument is first converted to a <code>Double</code> * as if by the XPath <code>number()</code> function. * * @param obj the object to be rounded * @param nav ignored * * @return a <code>Double</code> containing the integer nearest to <code>obj</code> */ public static Number evaluate(Object obj, Navigator nav) { Double d = NumberFunction.evaluate( obj, nav ); if (d.isNaN() || d.isInfinite()) { return d; } double value = d.doubleValue(); return new Double( Math.round( value ) ); } }
// Clirr: compares two versions of a java library for binary compatibility // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package net.sf.clirr.checks; import net.sf.clirr.event.Severity; import net.sf.clirr.framework.ApiDiffDispatcher; import net.sf.clirr.framework.ClassSetChangeCheck; import org.apache.bcel.util.ClassSet; /** * Checks whether a class/interface has been removed from the public API. * * @author lkuehne */ public final class RemovedClassCheck extends AbstractClassSetChangeCheck implements ClassSetChangeCheck { public RemovedClassCheck(ApiDiffDispatcher dispatcher) { super(dispatcher); } public void check(ClassSet compatBaseline, ClassSet currentVersion) { String[] oldClassNames = compatBaseline.getClassNames(); String[] newClassNames = currentVersion.getClassNames(); compareClassNameSets(oldClassNames, newClassNames, "Removed ", Severity.ERROR); } }
package net.spy.memcached; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentLinkedQueue; import net.spy.SpyObject; import net.spy.memcached.ops.GetOperation; import net.spy.memcached.ops.Operation; import net.spy.memcached.ops.OptimizedGet; /** * Connection to a cluster of memcached servers. */ public class MemcachedConnection extends SpyObject { // The number of empty selects we'll allow before taking action. It's too // easy to write a bug that causes it to loop uncontrollably. This helps // find those bugs and often works around them. private static final int EXCESSIVE_EMPTY = 100; // maximum amount of time to wait between reconnect attempts private static final long MAX_DELAY = 30000; private volatile boolean shutDown=false; // If true, get optimization will collapse multiple sequential get ops private boolean optimizeGets=true; private Selector selector=null; private QueueAttachment[] connections=null; private int emptySelects=0; // AddedQueue is used to track the QueueAttachments for which operations // have recently been queued. private ConcurrentLinkedQueue<QueueAttachment> addedQueue=null; // reconnectQueue contains the attachments that need to be reconnected // The key is the time at which they are eligible for reconnect private SortedMap<Long, QueueAttachment> reconnectQueue=null; /** * Construct a memcached connection. * * @param bufSize the size of the buffer used for reading from the server * @param f the factory that will provide an operation queue * @param a the addresses of the servers to connect to * * @throws IOException if a connection attempt fails early */ public MemcachedConnection(int bufSize, ConnectionFactory f, List<InetSocketAddress> a) throws IOException { reconnectQueue=new TreeMap<Long, QueueAttachment>(); addedQueue=new ConcurrentLinkedQueue<QueueAttachment>(); selector=Selector.open(); connections=new QueueAttachment[a.size()]; int cons=0; for(SocketAddress sa : a) { SocketChannel ch=SocketChannel.open(); ch.configureBlocking(false); QueueAttachment qa=new QueueAttachment(sa, ch, bufSize, f.createOperationQueue(), f.createOperationQueue(), f.createOperationQueue()); qa.which=cons; int ops=0; if(ch.connect(sa)) { getLogger().info("Connected to %s immediately", qa); qa.reconnectAttempt=0; assert ch.isConnected(); } else { getLogger().info("Added %s to connect queue", qa); ops=SelectionKey.OP_CONNECT; } qa.sk=ch.register(selector, ops, qa); assert ch.isConnected() || qa.sk.interestOps() == SelectionKey.OP_CONNECT : "Not connected, and not wanting to connect"; connections[cons++]=qa; } } /** * Enable or disable get optimization. * * When enabled (default), multiple sequential gets are collapsed into one. */ public void setGetOptimization(boolean to) { optimizeGets=to; } private boolean selectorsMakeSense() { for(QueueAttachment qa : connections) { if(qa.sk.isValid()) { if(qa.channel.isConnected()) { int sops=qa.sk.interestOps(); int expected=0; if(qa.hasReadOp()) { expected |= SelectionKey.OP_READ; } if(qa.hasWriteOp()) { expected |= SelectionKey.OP_WRITE; } if(qa.toWrite > 0) { expected |= SelectionKey.OP_WRITE; } assert sops == expected : "Invalid ops: " + qa + ", expected " + expected + ", got " + sops; } else { int sops=qa.sk.interestOps(); assert sops == SelectionKey.OP_CONNECT : "Not connected, and not watching for connect: " + sops; } } } getLogger().debug("Checked the selectors."); return true; } /** * MemcachedClient calls this method to handle IO over the connections. */ @SuppressWarnings("unchecked") public void handleIO() throws IOException { if(shutDown) { throw new IOException("No IO while shut down"); } // Deal with all of the stuff that's been added, but may not be marked // writable. handleInputQueue(); getLogger().debug("Done dealing with queue."); long delay=0; if(!reconnectQueue.isEmpty()) { long now=System.currentTimeMillis(); long then=reconnectQueue.firstKey(); delay=Math.max(then-now, 1); } getLogger().debug("Selecting with delay of %sms", delay); assert selectorsMakeSense() : "Selectors don't make sense."; int selected=selector.select(delay); Set<SelectionKey> selectedKeys=selector.selectedKeys(); if(selectedKeys.isEmpty()) { getLogger().debug("No selectors ready, interrupted: " + Thread.interrupted()); if(++emptySelects > EXCESSIVE_EMPTY) { for(SelectionKey sk : selector.keys()) { getLogger().info("%s has %s, interested in %s", sk, sk.readyOps(), sk.interestOps()); if(sk.readyOps() != 0) { getLogger().info("%s has a ready op, handling IO", sk); handleIO(sk); } else { queueReconnect((QueueAttachment)sk.attachment()); } } assert emptySelects < EXCESSIVE_EMPTY + 10 : "Too many empty selects"; } } else { getLogger().debug("Selected %d, selected %d keys", selected, selectedKeys.size()); emptySelects=0; for(SelectionKey sk : selectedKeys) { getLogger().debug( "Got selection key: %s (r=%s, w=%s, c=%s, op=%s)", sk, sk.isReadable(), sk.isWritable(), sk.isConnectable(), sk.attachment()); handleIO(sk); } // for each selector selectedKeys.clear(); } if(!reconnectQueue.isEmpty()) { attemptReconnects(); } } // Handle any requests that have been made against the client. private void handleInputQueue() { if(!addedQueue.isEmpty()) { getLogger().debug("Handling queue"); // If there's stuff in the added queue. Try to process it. Collection<QueueAttachment> toAdd=new HashSet<QueueAttachment>(); try { QueueAttachment qa=null; boolean readyForIO=false; while((qa=addedQueue.remove()) != null) { if(qa.channel != null && qa.channel.isConnected()) { Operation op=qa.getCurrentWriteOp(); if(op != null) { readyForIO=true; getLogger().debug("Handling queued write %s", qa); } } else { toAdd.add(qa); } qa.copyInputQueue(); if(readyForIO) { try { if(qa.wbuf.hasRemaining()) { handleWrites(qa.sk, qa); } } catch(IOException e) { getLogger().warn("Exception handling write", e); queueReconnect(qa); } } fixupOps(qa); } } catch(NoSuchElementException e) { // out of stuff. } addedQueue.addAll(toAdd); } } // Handle IO for a specific selector. Any IOException will cause a // reconnect private void handleIO(SelectionKey sk) { assert !sk.isAcceptable() : "We don't do accepting here."; QueueAttachment qa=(QueueAttachment)sk.attachment(); if(sk.isConnectable()) { getLogger().info("Connection state changed for %s", sk); try { if(qa.channel.finishConnect()) { assert qa.channel.isConnected() : "Not connected."; qa.reconnectAttempt=0; addedQueue.offer(qa); if(qa.wbuf.hasRemaining()) { handleWrites(sk, qa); } } else { assert !qa.channel.isConnected() : "connected"; } } catch(IOException e) { getLogger().warn("Problem handling connect", e); queueReconnect(qa); } } else { if(sk.isWritable()) { try { handleWrites(sk, qa); } catch (IOException e) { getLogger().info("IOExcepting handling %s, reconnecting", qa.getCurrentWriteOp(), e); } } if(sk.isReadable()) { try { handleReads(sk, qa); } catch (IOException e) { getLogger().info("IOExcepting handling %s, reconnecting", qa.getCurrentReadOp(), e); } } } fixupOps(qa); } private void handleWrites(SelectionKey sk, QueueAttachment qa) throws IOException { qa.fillWriteBuffer(optimizeGets); boolean canWriteMore=qa.toWrite > 0; while(canWriteMore) { int wrote=qa.channel.write(qa.wbuf); assert wrote >= 0 : "Wrote negative bytes?"; qa.toWrite -= wrote; assert qa.toWrite >= 0 : "toWrite went negative after writing " + wrote + " bytes for " + qa; getLogger().debug("Wrote %d bytes", wrote); qa.fillWriteBuffer(optimizeGets); canWriteMore = wrote > 0 && qa.toWrite > 0; } } private void handleReads(SelectionKey sk, QueueAttachment qa) throws IOException { Operation currentOp = qa.getCurrentReadOp(); int read=qa.channel.read(qa.rbuf); while(read > 0) { getLogger().debug("Read %d bytes", read); qa.rbuf.flip(); while(qa.rbuf.remaining() > 0) { assert currentOp != null : "No read operation"; currentOp.readFromBuffer(qa.rbuf); if(currentOp.getState() == Operation.State.COMPLETE) { getLogger().debug( "Completed read op: %s and giving the next %d bytes", currentOp, qa.rbuf.remaining()); Operation op=qa.removeCurrentReadOp(); assert op == currentOp : "Expected to pop " + currentOp + " got " + op; currentOp=qa.getCurrentReadOp(); } } qa.rbuf.clear(); read=qa.channel.read(qa.rbuf); } } private void fixupOps(QueueAttachment qa) { if(qa.sk.isValid()) { int iops=qa.getSelectionOps(); getLogger().debug("Setting interested opts to %d", iops); qa.sk.interestOps(iops); } else { getLogger().debug("Selection key is not valid."); } } // Make a debug string out of the given buffer's values static String dbgBuffer(ByteBuffer b, int size) { StringBuilder sb=new StringBuilder(); byte[] bytes=b.array(); for(int i=0; i<size; i++) { char ch=(char)bytes[i]; if(Character.isWhitespace(ch) || Character.isLetterOrDigit(ch)) { sb.append(ch); } else { sb.append("\\x"); sb.append(Integer.toHexString(bytes[i] & 0xff)); } } return sb.toString(); } private void queueReconnect(QueueAttachment qa) { if(!shutDown) { getLogger().warn("Closing, and reopening %s, attempt %d.", qa, qa.reconnectAttempt); qa.sk.cancel(); assert !qa.sk.isValid() : "Cancelled selection key is valid"; qa.reconnectAttempt++; try { qa.channel.socket().close(); } catch(IOException e) { getLogger().warn("IOException trying to close a socket", e); } qa.channel=null; long delay=Math.min((100*qa.reconnectAttempt) ^ 2, MAX_DELAY); reconnectQueue.put(System.currentTimeMillis() + delay, qa); // Need to do a little queue management. setupResend(qa); } } private void attemptReconnects() throws IOException { long now=System.currentTimeMillis(); for(Iterator<QueueAttachment> i= reconnectQueue.headMap(now).values().iterator(); i.hasNext();) { QueueAttachment qa=i.next(); i.remove(); getLogger().info("Reconnecting %s", qa); SocketChannel ch=SocketChannel.open(); ch.configureBlocking(false); int ops=0; if(ch.connect(qa.socketAddress)) { getLogger().info("Immediately reconnected to %s", qa); assert ch.isConnected(); } else { ops=SelectionKey.OP_CONNECT; } qa.channel=ch; qa.sk=ch.register(selector, ops, qa); } } private void setupResend(QueueAttachment qa) { // First, reset the current write op. Operation op=qa.getCurrentWriteOp(); if(op != null) { op.getBuffer().reset(); } // Now cancel all the pending read operations. Might be better to // to requeue them. while(qa.hasReadOp()) { op=qa.removeCurrentReadOp(); getLogger().warn("Discarding partially completed op: %s", op); op.cancel(); } } /** * Get the number of connections currently handled. */ public int getNumConnections() { return connections.length; } /** * Get the remote address of the socket with the given ID. * * @param which which id * @return the rmeote address */ public SocketAddress getAddressOf(int which) { return connections[which].socketAddress; } /** * Add an operation to the given connection. * * @param which the connection offset * @param o the operation */ @SuppressWarnings("unchecked") public void addOperation(int which, Operation o) { QueueAttachment qa=connections[which]; o.initialize(); qa.addOp(o); addedQueue.offer(qa); Selector s=selector.wakeup(); assert s == selector : "Wakeup returned the wrong selector."; getLogger().debug("Added %s to %d", o, which); } /** * Shut down all of the connections. */ public void shutdown() throws IOException { for(QueueAttachment qa : connections) { qa.channel.close(); qa.sk=null; if(qa.toWrite > 0) { getLogger().warn("Shut down with %d bytes remaining to write", qa.toWrite); } getLogger().debug("Shut down channel %s", qa.channel); } selector.close(); getLogger().debug("Shut down selector %s", selector); } @Override public String toString() { StringBuilder sb=new StringBuilder(); sb.append("{MemcachedConnection to"); for(QueueAttachment qa : connections) { sb.append(" "); sb.append(qa.socketAddress); } sb.append("}"); return sb.toString(); } private static class QueueAttachment extends SpyObject { public int which=0; public int reconnectAttempt=1; public SocketAddress socketAddress=null; public SocketChannel channel=null; public int toWrite=0; public ByteBuffer rbuf=null; public ByteBuffer wbuf=null; private BlockingQueue<Operation> writeQ=null; private BlockingQueue<Operation> readQ=null; private BlockingQueue<Operation> inputQueue=null; private GetOperation getOp=null; public SelectionKey sk=null; public QueueAttachment(SocketAddress sa, SocketChannel c, int bufSize, BlockingQueue<Operation> rq, BlockingQueue<Operation> wq, BlockingQueue<Operation> iq) { super(); assert sa != null : "No SocketAddress"; assert c != null : "No SocketChannel"; assert bufSize > 0 : "Invalid buffer size: " + bufSize; assert rq != null : "No operation read queue"; assert wq != null : "No operation write queue"; assert iq != null : "No input queue"; socketAddress=sa; channel=c; rbuf=ByteBuffer.allocate(bufSize); wbuf=ByteBuffer.allocate(bufSize); wbuf.clear(); readQ=rq; writeQ=wq; inputQueue=iq; } public void copyInputQueue() { Collection<Operation> tmp=new ArrayList<Operation>(); inputQueue.drainTo(tmp); writeQ.addAll(tmp); } // Prepare the pending operations. Return true if there are any pending // ops private boolean preparePending() { // Copy the input queue into the write queue. copyInputQueue(); // Now check the ops Operation nextOp=getCurrentWriteOp(); while(nextOp != null && nextOp.isCancelled()) { getLogger().info("Removing cancelled operation: %s", nextOp); removeCurrentWriteOp(); nextOp=getCurrentWriteOp(); } return nextOp != null; } public void fillWriteBuffer(boolean optimizeGets) { if(toWrite == 0) { wbuf.clear(); Operation o=getCurrentWriteOp(); while(o != null && toWrite < wbuf.capacity()) { assert o.getState() == Operation.State.WRITING; ByteBuffer obuf=o.getBuffer(); int bytesToCopy=Math.min(wbuf.remaining(), obuf.remaining()); byte b[]=new byte[bytesToCopy]; obuf.get(b); wbuf.put(b); getLogger().debug("After copying stuff from %s: %s", o, wbuf); if(!o.getBuffer().hasRemaining()) { o.writeComplete(); transitionWriteItem(); preparePending(); if(optimizeGets) { optimize(); } o=getCurrentWriteOp(); } toWrite += bytesToCopy; } wbuf.flip(); assert toWrite <= wbuf.capacity() : "toWrite exceeded capacity: " + this; assert toWrite == wbuf.remaining() : "Expected " + toWrite + " remaining, got " + wbuf.remaining(); } else { getLogger().debug("Buffer is full, skipping"); } } public void transitionWriteItem() { Operation op=removeCurrentWriteOp(); assert op != null : "There is no write item to transition"; assert op.getState() == Operation.State.READING; getLogger().debug("Transitioning %s to read", op); readQ.add(op); } public void optimize() { // make sure there are at least two get operations in a row before // attempting to optimize them. if(writeQ.peek() instanceof GetOperation) { getOp=(GetOperation)writeQ.remove(); if(writeQ.peek() instanceof GetOperation) { OptimizedGet og=new OptimizedGet(getOp); getOp=og; while(writeQ.peek() instanceof GetOperation) { GetOperation o=(GetOperation) writeQ.remove(); if(!o.isCancelled()) { og.addOperation(o); } } // Initialize the new mega get getOp.initialize(); assert getOp.getState() == Operation.State.WRITING; getLogger().debug( "Set up %s with %s keys and %s callbacks", this, og.numKeys(), og.numCallbacks()); } } } public Operation getCurrentReadOp() { return readQ.peek(); } public Operation removeCurrentReadOp() { return readQ.remove(); } public Operation getCurrentWriteOp() { return getOp == null ? writeQ.peek() : getOp; } public Operation removeCurrentWriteOp() { Operation rv=getOp; if(rv == null) { rv=writeQ.remove(); } else { getOp=null; } return rv; } public boolean hasReadOp() { return !readQ.isEmpty(); } public boolean hasWriteOp() { return !(getOp == null && writeQ.isEmpty()); } public void addOp(Operation op) { boolean added=inputQueue.add(op); assert added; } public int getSelectionOps() { int rv=0; if(channel.isConnected()) { if(hasReadOp()) { rv |= SelectionKey.OP_READ; } if(toWrite > 0 || hasWriteOp()) { rv |= SelectionKey.OP_WRITE; } } else { rv = SelectionKey.OP_CONNECT; } return rv; } @Override public String toString() { int sops=0; if(sk!= null && sk.isValid()) { sops=sk.interestOps(); } int rsize=readQ.size() + (getOp == null ? 0 : 1); int wsize=writeQ.size(); int isize=inputQueue.size(); return "{QA sa=" + socketAddress + ", #Rops=" + rsize + ", #Wops=" + wsize + ", #iq=" + isize + ", topRop=" + getCurrentReadOp() + ", topWop=" + getCurrentWriteOp() + ", toWrite=" + toWrite + ", interested=" + sops + "}"; } } }
package voldemort.store.readonly; import java.io.File; import java.io.StringReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.apache.commons.httpclient.HostConfiguration; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpConnectionManager; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; import voldemort.VoldemortException; import voldemort.cluster.Cluster; import voldemort.cluster.Node; import voldemort.utils.Utils; import voldemort.xml.ClusterMapper; /** * A helper class to invoke the FETCH and SWAP operations on a remote store via * HTTP. * * @author jay * */ public class StoreSwapper { private static final Logger logger = Logger.getLogger(StoreSwapper.class); private final Cluster cluster; private final ExecutorService executor; private final HttpClient httpClient; private final String readOnlyMgmtPath; private final String basePath; public StoreSwapper(Cluster cluster, ExecutorService executor, HttpClient httpClient, String readOnlyMgmtPath, String basePath) { super(); this.cluster = cluster; this.executor = executor; this.httpClient = httpClient; this.readOnlyMgmtPath = readOnlyMgmtPath; this.basePath = basePath; } public void swapStoreData(String storeName) { List<String[]> fetched = invokeFetch(); invokeSwap(storeName, fetched); } private List<String[]> invokeFetch() { // do fetch Map<Integer, Future<String[]>> fetchFiles = new HashMap<Integer, Future<String[]>>(); for(final Node node: cluster.getNodes()) { fetchFiles.put(node.getId(), executor.submit(new Callable<String[]>() { public String[] call() throws Exception { String url = node.getHttpUrl() + "/" + readOnlyMgmtPath; PostMethod post = new PostMethod(url); post.addParameter("operation", "fetch"); String indexFile = basePath + "/" + node.getId() + ".index"; String dataFile = basePath + "/" + node.getId() + ".data"; post.addParameter("index", indexFile); post.addParameter("data", dataFile); logger.info("Invoking fetch for node " + node.getId() + " for " + indexFile + " and " + dataFile); int responseCode = httpClient.executeMethod(post); String response = post.getResponseBodyAsString(30000); if(responseCode != 200) throw new VoldemortException("Swap request on node " + node.getId() + " failed: " + post.getStatusText()); String[] files = response.split("\n"); if(files.length != 2) throw new VoldemortException("Expected two files, but found " + files.length + " in '" + response + "'."); logger.info("Fetch succeeded on node " + node.getId()); return files; } })); } // wait for all operations to complete successfully List<String[]> results = new ArrayList<String[]>(); for(int nodeId = 0; nodeId < cluster.getNumberOfNodes(); nodeId++) { Future<String[]> val = fetchFiles.get(nodeId); try { results.add(val.get()); } catch(ExecutionException e) { throw new VoldemortException(e.getCause()); } catch(InterruptedException e) { throw new VoldemortException(e); } } return results; } private void invokeSwap(String storeName, List<String[]> fetchFiles) { // do swap int successes = 0; Exception exception = null; for(int nodeId = 0; nodeId < cluster.getNumberOfNodes(); nodeId++) { try { Node node = cluster.getNodeById(nodeId); String url = node.getHttpUrl() + "/" + readOnlyMgmtPath; PostMethod post = new PostMethod(url); post.addParameter("operation", "swap"); String indexFile = fetchFiles.get(nodeId)[0]; String dataFile = fetchFiles.get(nodeId)[1]; logger.info("Attempting swap for node " + nodeId + " index = " + indexFile + ", data = " + dataFile); post.addParameter("index", indexFile); post.addParameter("data", dataFile); post.addParameter("store", storeName); int responseCode = httpClient.executeMethod(post); String response = post.getStatusText(); if(responseCode == 200) { successes++; logger.info("Swap succeeded for node " + node.getId()); } else { throw new VoldemortException(response); } } catch(Exception e) { exception = e; logger.error("Exception thrown during swap operation on node " + nodeId + ": ", e); } } if(exception != null) throw new VoldemortException(exception); } public static void main(String[] args) throws Exception { if(args.length != 4) Utils.croak("USAGE: cluster.xml store_name mgmtpath file_path"); String clusterXml = args[0]; String storeName = args[1]; String mgmtPath = args[2]; String filePath = args[3]; String clusterStr = FileUtils.readFileToString(new File(clusterXml)); Cluster cluster = new ClusterMapper().readCluster(new StringReader(clusterStr)); ExecutorService executor = Executors.newFixedThreadPool(10); HttpConnectionManager manager = new MultiThreadedHttpConnectionManager(); int numConnections = cluster.getNumberOfNodes() + 3; manager.getParams().setMaxTotalConnections(numConnections); manager.getParams().setMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION, numConnections); HttpClient client = new HttpClient(manager); client.getParams().setParameter("http.socket.timeout", 3 * 60 * 60 * 1000); StoreSwapper swapper = new StoreSwapper(cluster, executor, client, mgmtPath, filePath); swapper.swapStoreData(storeName); logger.info("Swap succeeded on all nodes."); executor.shutdownNow(); executor.awaitTermination(1, TimeUnit.SECONDS); System.exit(0); } }
package jsonbroker.samples.websocket; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import jsonbroker.library.common.http.web_socket.TextWebSocket; import jsonbroker.library.common.log.Log; import jsonbroker.library.server.http.ConnectionDelegate; public class EchoWebSocket implements ConnectionDelegate { private static Log log = Log.getLog(EchoWebSocket.class); TextWebSocket _echoWebSocket; Socket _socket; @Override public ConnectionDelegate processRequest(Socket socket, InputStream inputStream, OutputStream outputStream) { if( _socket != socket ) { _echoWebSocket = new TextWebSocket( socket ); } String line = _echoWebSocket.recieveTextFrame(); log.debug( line, "line" ); if( null == line ) { return null; } _echoWebSocket.sendTextFrame( line ); return this; } }
package ameba.http.session; import ameba.core.Requests; import ameba.mvc.assets.AssetsResource; import ameba.util.Times; import com.google.common.base.Charsets; import com.google.common.hash.Hashing; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Priority; import javax.inject.Singleton; import javax.ws.rs.Priorities; import javax.ws.rs.container.*; import javax.ws.rs.core.*; import java.lang.invoke.MethodHandle; import java.util.List; import java.util.UUID; /** * @author icode */ @PreMatching @Priority(Priorities.AUTHENTICATION - 500) @Singleton public class SessionFilter implements ContainerRequestFilter, ContainerResponseFilter { private static final Logger logger = LoggerFactory.getLogger(SessionFilter.class); private static final String SET_COOKIE_KEY = SessionFilter.class.getName() + ".__SET_SESSION_COOKIE__"; static String DEFAULT_SESSION_ID_COOKIE_KEY = "s"; static long SESSION_TIMEOUT = Times.parseDuration("2h"); static int COOKIE_MAX_AGE = NewCookie.DEFAULT_MAX_AGE; static MethodHandle METHOD_HANDLE; @Context private UriInfo uriInfo; private boolean isIgnore() { List<Object> resources = uriInfo.getMatchedResources(); return resources.size() != 0 && AssetsResource.class.isAssignableFrom(resources.get(0).getClass()); } @Override @SuppressWarnings("unchecked") public void filter(ContainerRequestContext requestContext) { if (isIgnore()) { return; } Cookie cookie = requestContext.getCookies().get(DEFAULT_SESSION_ID_COOKIE_KEY); boolean isNew = false; if (cookie == null) { isNew = true; cookie = newCookie(requestContext); } AbstractSession session; String host = Requests.getRemoteRealAddr(); if (host == null || host.equals("unknown")) { host = Requests.getRemoteAddr(); } String sessionId = cookie.getValue(); if (METHOD_HANDLE != null) { try { session = (AbstractSession) METHOD_HANDLE.invoke(sessionId, host, SESSION_TIMEOUT, isNew); } catch (Throwable throwable) { throw new SessionExcption("new session instance error"); } } else { session = new CacheSession(sessionId, host, SESSION_TIMEOUT, isNew); } if (!session.isNew()) { try { checkSession(session, requestContext); } catch (Exception e) { try { checkSession(session, requestContext); } catch (Exception ex) { logger.warn("get session error", e); } } } Session.sessionThreadLocal.set(session); } private void checkSession(AbstractSession session, ContainerRequestContext requestContext) { if (session.isInvalid()) { Cookie cookie = newCookie(requestContext); session.setId(cookie.getValue()); } else { session.touch(); session.flush(); } } protected String newSessionId() { return Hashing.sha1() .hashString( UUID.randomUUID().toString() + Math.random() + this.hashCode() + System.nanoTime(), Charsets.UTF_8 ) .toString(); } private NewCookie newCookie(ContainerRequestContext requestContext) { // URI uri = requestContext.getUriInfo().getBaseUri(); // String domain = uri.getHost(); // // localhost domain must be null // if (domain.equalsIgnoreCase("localhost")) { // domain = null; NewCookie cookie = new NewCookie( DEFAULT_SESSION_ID_COOKIE_KEY, newSessionId(), "/", null, Cookie.DEFAULT_VERSION, null, COOKIE_MAX_AGE, null, requestContext.getSecurityContext().isSecure(), true); requestContext.setProperty(SET_COOKIE_KEY, cookie); return cookie; } @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) { if (isIgnore()) { return; } try { Session.flush(); } catch (Exception e) { logger.warn("flush session error", e); } NewCookie cookie = (NewCookie) requestContext.getProperty(SET_COOKIE_KEY); if (cookie != null) responseContext.getHeaders().add(HttpHeaders.SET_COOKIE, cookie.toString()); Session.sessionThreadLocal.remove(); } }
package atg.tools.ant.util; import org.apache.tools.ant.BuildException; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.jar.Manifest; /** * Utility class for dealing with JAR manifest files. * * @author msicker * @version 2.0 */ public final class ManifestUtils { public static final String META_INF = "META-INF"; public static final String MANIFEST_MF = "MANIFEST.MF"; private ManifestUtils() { } public static File getManifestIn(final File baseDirectory) { verifyDirectoryExists(baseDirectory); final File metaInf = new File(baseDirectory, META_INF); if (metaInf.exists() && !metaInf.isDirectory()) { throw new BuildException("The location `" + metaInf + "' already exists, but is not a directory."); } return new File(metaInf, MANIFEST_MF); } public static File touchManifestIn(final File baseDirectory) { verifyDirectoryExists(baseDirectory); final File metaInf = new File(baseDirectory, META_INF); if (!(metaInf.exists() || metaInf.mkdir())) { throw new BuildException("Could not create directory `" + metaInf + "'."); } final File manifest = new File(metaInf, MANIFEST_MF); if (manifest.exists()) { verify("Couldn't touch file `" + manifest + "'.", manifest.setLastModified(System.currentTimeMillis())); } else { try { verify("Couldn't create file `" + manifest + "'.", manifest.createNewFile()); } catch (final IOException e) { throw new BuildException("Could not create file: " + manifest, e); } } return manifest; } private static void verifyDirectoryExists(final File baseDirectory) { if (!baseDirectory.isDirectory()) { throw new BuildException("Provided file `" + baseDirectory.getAbsolutePath() + "' is not a valid directory."); } } private static void verify(final String message, final boolean b) { if (!b) { throw new BuildException(message); } } /** * Loads a given manifest file into a Manifest. * * @param file file containing manifest metadata. * * @return said file parsed into a Manifest object. * * @throws IOException if the given file does not exist or is an invalid manifest file. */ public static Manifest load(final File file) throws IOException { BufferedInputStream bis = null; try { bis = new BufferedInputStream(new FileInputStream(file)); return new Manifest(bis); } finally { FileUtils.closeSilently(bis); } } }
package br.uff.ic.utility; import br.uff.ic.utility.graph.Edge; import br.uff.ic.utility.graph.GraphVertex; import java.util.Collection; import java.util.logging.Logger; import edu.uci.ics.jung.graph.Graph; import edu.uci.ics.jung.graph.util.Pair; import java.util.HashMap; import java.util.Map; public class GraphCollapser { private static final Logger logger = Logger.getLogger(GraphCollapser.class.getClass().getName()); private Graph originalGraph; boolean considerEdgeLabelForMerge; public GraphCollapser(Graph originalGraph, boolean considerEdgeLabelForMerge) { this.originalGraph = originalGraph; this.considerEdgeLabelForMerge = considerEdgeLabelForMerge; } Graph createGraph() throws InstantiationException, IllegalAccessException { return (Graph) originalGraph.getClass().newInstance(); } /** * Method to collapse vertices into a single graph-vertex. It also collapses the edges, summarizing them * @param inGraph * @param clusterGraph * @return the collapsed graph */ public Graph collapse(Graph inGraph, GraphVertex clusterGraph) { if (clusterGraph.clusterGraph.getVertexCount() < 2) { return inGraph; } Graph graph = inGraph; try { graph = createGraph(); } catch (Exception ex) { ex.printStackTrace(); } Collection cluster = clusterGraph.clusterGraph.getVertices(); Map<String, Object> collapsedEdges = new HashMap<>(); Map<String, Object> mergedEdges = new HashMap<>(); // add all vertices in the delegate, unless the vertex is in the // cluster. for (Object v : inGraph.getVertices()) { if (cluster.contains(v) == false) { graph.addVertex(v); } } // add the clusterGraph as a vertex // GraphVertex gv = GraphUtils.CreateVertexGraph(clusterGraph); // graph.addVertex(gv); graph.addVertex(clusterGraph); //add all edges from the inGraph, unless both endpoints of // the edge are in the cluster for (Object e : (Collection<?>) inGraph.getEdges()) { Pair endpoints = inGraph.getEndpoints(e); // don't add edges whose endpoints are both in the cluster if (cluster.containsAll(endpoints) == false) { if (cluster.contains(endpoints.getFirst())) { Object edge = hasEdge(collapsedEdges, mergedEdges, e, ((Edge)e).getLabel(), ((Edge)e).getType(), cluster.hashCode(), endpoints.getSecond().hashCode()); graph.addEdge(edge, clusterGraph, endpoints.getSecond(), inGraph.getEdgeType(e)); // graph.addEdge(e, clusterGraph, endpoints.getSecond(), inGraph.getEdgeType(e)); } else if (cluster.contains(endpoints.getSecond())) { Object edge = hasEdge(collapsedEdges, mergedEdges, e, ((Edge)e).getLabel(), ((Edge)e).getType(), endpoints.getFirst().hashCode(), cluster.hashCode()); graph.addEdge(edge, endpoints.getFirst(), clusterGraph, inGraph.getEdgeType(e)); // graph.addEdge(e, endpoints.getFirst(), clusterGraph, inGraph.getEdgeType(e)); } else { graph.addEdge(e, endpoints.getFirst(), endpoints.getSecond(), inGraph.getEdgeType(e)); } } } return graph; } /** * Method to determine if there are other edges from the same type that goes to a cluster vertex. If there are any, then it will create a summarized edge and hide the original edges * @param collapsedEdges is a map that contains the processed edges * @param mergedEdges is a map that contains the summarized edges * @param e is the current edge * @param type is the edge type * @param source is the source hashcode * @param target is the target hashcode * @return the edge to be added in the graph */ private Object hasEdge(Map<String, Object> collapsedEdges, Map<String, Object> mergedEdges, Object e, String label, String type, int source, int target) { String key; if(considerEdgeLabelForMerge) key = label + " " + type + " " + source + " " + target; else key = type + " " + source + " " + target; if(collapsedEdges.containsKey(key)) { ((Edge)e).setHide(true); Object edge = collapsedEdges.get(key); ((Edge)edge).setHide(true); // If first time, create the edge if(!mergedEdges.containsKey(key)) { Edge newEdge = new Edge(((Edge)edge).getID(), ((Edge)edge).getType(), ((Edge)edge).getStringValue(), ((Edge)edge).getLabel(), ((Edge)edge).attributes, ((Edge)edge).getTarget(), ((Edge)edge).getSource()); newEdge = newEdge.merge((Edge) e); mergedEdges.put(key, newEdge); return newEdge; } else { // Else update it Edge newEdge = ((Edge)mergedEdges.get(key)).merge((Edge) e); mergedEdges.put(key, newEdge); return newEdge; // Need to update the summarized edge values // Need to hide e // return true; } } else { collapsedEdges.put(key, e); return e; // ((Edge)e).setHide(true); // Need to create a single summarized edge // Need to hide e // return false; } // collapsedEdges.put(key, e); } /** * Method to expand the cluster-vertex * @param inGraph * @param clusterGraph * @return the graph without the selected cluster-vertex */ public Graph expand(Graph inGraph, GraphVertex clusterGraph) { Graph graph = inGraph; try { graph = createGraph(); } catch (Exception ex) { ex.printStackTrace(); } Collection cluster = clusterGraph.clusterGraph.getVertices(); logger.fine("cluster to expand is " + cluster); // put all clusterGraph vertices and edges into the new Graph for (Object v : cluster) { graph.addVertex(v); for (Object edge : clusterGraph.clusterGraph.getIncidentEdges(v)) { Pair endpoints = clusterGraph.clusterGraph.getEndpoints(edge); graph.addEdge(edge, endpoints.getFirst(), endpoints.getSecond(), clusterGraph.clusterGraph.getEdgeType(edge)); } } // add all the vertices from the current graph except for // the cluster we are expanding for (Object v : inGraph.getVertices()) { if (v.equals(clusterGraph) == false) { graph.addVertex(v); } } // now that all vertices have been added, add the edges, // ensuring that no edge contains a vertex that has not // already been added for (Object v : inGraph.getVertices()) { if (v.equals(clusterGraph) == false) { for (Object edge : inGraph.getIncidentEdges(v)) { Pair endpoints = inGraph.getEndpoints(edge); Object v1 = endpoints.getFirst(); Object v2 = endpoints.getSecond(); if (cluster.containsAll(endpoints) == false) { if (clusterGraph.equals(v1)) { if(!((Edge)edge).getLabel().contains("(Merged)")) { // i need a new v1 // Object originalV1 = originalGraph.getEndpoints(edge).getFirst(); Object originalV1 = ((Edge)edge).getSource(); Object newV1 = findVertex(graph, originalV1); assert newV1 != null : "newV1 for " + originalV1 + " was not found!"; ((Edge)edge).setHide(false); graph.addEdge(edge, newV1, v2, inGraph.getEdgeType(edge)); } } else if (clusterGraph.equals(v2)) { if(!((Edge)edge).getLabel().contains("(Merged)")) { // i need a new v2 // Object originalV2 = originalGraph.getEndpoints(edge).getSecond(); Object originalV2 = ((Edge)edge).getTarget(); Object newV2 = findVertex(graph, originalV2); assert newV2 != null : "newV2 for " + originalV2 + " was not found!"; ((Edge)edge).setHide(false); graph.addEdge(edge, v1, newV2, inGraph.getEdgeType(edge)); } } else { graph.addEdge(edge, v1, v2, inGraph.getEdgeType(edge)); } } } } } return graph; } Object findVertex(Graph inGraph, Object vertex) { Collection vertices = inGraph.getVertices(); if (vertices.contains(vertex)) { return vertex; } for (Object v : vertices) { if (v instanceof GraphVertex) { GraphVertex g = (GraphVertex) v; if (contains(g.clusterGraph, vertex)) { return v; } } } return null; } private boolean contains(Graph inGraph, Object vertex) { boolean contained = false; if (inGraph.getVertices().contains(vertex)) { return true; } for (Object v : inGraph.getVertices()) { if (v instanceof GraphVertex) { contained |= contains((Graph) ((GraphVertex)v).clusterGraph, vertex); } } return contained; } public GraphVertex getClusterGraph(Graph inGraph, Collection picked) { Graph clusterGraph; try { clusterGraph = createGraph(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } for (Object v : picked) { clusterGraph.addVertex(v); Collection edges = inGraph.getIncidentEdges(v); for (Object edge : edges) { Pair endpoints = inGraph.getEndpoints(edge); Object v1 = endpoints.getFirst(); Object v2 = endpoints.getSecond(); if (picked.containsAll(endpoints)) { clusterGraph.addEdge(edge, v1, v2, inGraph.getEdgeType(edge)); } } } GraphVertex gv = GraphUtils.CreateVertexGraph(clusterGraph); return gv; // return clusterGraph; } }
package ca.blarg.gdx.states; import ca.blarg.gdx.GameApp; import ca.blarg.gdx.ReflectionUtils; import ca.blarg.gdx.Strings; import ca.blarg.gdx.events.EventManager; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.utils.Disposable; import java.util.LinkedList; public class StateManager implements Disposable { public final GameApp gameApp; public final EventManager eventManager; LinkedList<StateInfo> states; LinkedList<StateInfo> pushQueue; LinkedList<StateInfo> swapQueue; boolean pushQueueHasOverlay; boolean swapQueueHasOverlay; boolean lastCleanedStatesWereAllOverlays; public StateManager(GameApp gameApp, EventManager eventManager) { if (gameApp == null) throw new IllegalArgumentException("gameApp cannot be null."); Gdx.app.debug("StateManager", "ctor"); states = new LinkedList<StateInfo>(); pushQueue = new LinkedList<StateInfo>(); swapQueue = new LinkedList<StateInfo>(); this.gameApp = gameApp; this.eventManager = eventManager; } /*** public state getters ***/ public GameState getTopState() { StateInfo top = getTop(); return (top == null ? null : top.state); } public GameState getTopNonOverlayState() { StateInfo top = getTopNonOverlay(); return (top == null ? null : top.state); } public GameState getStateBefore(GameState state) { if (state == null) throw new IllegalArgumentException("state cannot be null."); StateInfo info = getStateInfoFor(state); if (info == null) return null; int index = states.indexOf(info); if (index == 0) return null; else return states.get(index - 1).state; } public GameState getStateAfter(GameState state) { if (state == null) throw new IllegalArgumentException("state cannot be null."); StateInfo info = getStateInfoFor(state); if (info == null) return null; int index = states.indexOf(info); if (index == states.size() - 1) return null; else return states.get(index + 1).state; } public GameState getStateBeforeOfType(GameState state, Class<? extends GameState> type) { if (state == null) throw new IllegalArgumentException("state cannot be null."); if (type == null) throw new IllegalArgumentException("type cannot be null."); StateInfo info = getStateInfoFor(state); if (info == null) return null; for (int i = states.indexOf(info); i >= 0; --i) { GameState current = states.get(i).state; if (type.isInstance(current)) return current; } return null; } public GameState getStateAfterOfType(GameState state, Class<? extends GameState> type) { if (state == null) throw new IllegalArgumentException("state cannot be null."); if (type == null) throw new IllegalArgumentException("type cannot be null."); StateInfo info = getStateInfoFor(state); if (info == null) return null; for (int i = states.indexOf(info); i < states.size(); ++i) { GameState current = states.get(i).state; if (type.isInstance(current)) return current; } return null; } public boolean isTransitioning() { for (int i = 0; i < states.size(); ++i) { if (states.get(i).isTransitioning) return true; } return false; } public boolean isEmpty() { return (states.size() == 0 && pushQueue.size() == 0 && swapQueue.size() == 0); } public boolean isStateTransitioning(GameState state) { if (state == null) throw new IllegalArgumentException("state cannot be null."); StateInfo info = getStateInfoFor(state); return (info == null ? false : info.isTransitioning); } public boolean isTopState(GameState state) { if (state == null) throw new IllegalArgumentException("state cannot be null."); StateInfo info = getTop(); return (info == null ? false : (info.state == state)); } public boolean hasState(String name) { for (int i = 0; i < states.size(); ++i) { StateInfo info = states.get(i); if (!Strings.isNullOrEmpty(info.name) && info.name.equals(name)) return true; } return false; } /** Push / Pop / Overlay / Swap / Queue ***/ public <T extends GameState> T push(Class<T> stateType) { return push(stateType, null); } public <T extends GameState> T push(Class<T> stateType, String name) { T newState; try { newState = ReflectionUtils.instantiateObject(stateType, new Class<?>[] { StateManager.class, EventManager.class }, new Object[] { this, eventManager }); } catch (Exception e) { throw new IllegalArgumentException("Could not instantiate a GameState instance of that type."); } StateInfo stateInfo = new StateInfo(newState, name); queueForPush(stateInfo); return newState; } public <T extends GameState> T overlay(Class<T> stateType) { return overlay(stateType, null); } public <T extends GameState> T overlay(Class<T> stateType, String name) { T newState; try { newState = ReflectionUtils.instantiateObject(stateType, new Class<?>[] { StateManager.class, EventManager.class }, new Object[] { this, eventManager }); } catch (Exception e) { throw new IllegalArgumentException("Could not instantiate a GameState instance of that type."); } StateInfo stateInfo = new StateInfo(newState, name); stateInfo.isOverlay = true; queueForPush(stateInfo); return newState; } public <T extends GameState> T swapTopWith(Class<T> stateType) { return swapTopWith(stateType, null); } public <T extends GameState> T swapTopWith(Class<T> stateType, String name) { // figure out if the current top state is an overlay or not. use that // same setting for the new state that is being swapped in StateInfo currentTopStateInfo = getTop(); if (currentTopStateInfo == null) throw new UnsupportedOperationException("Cannot swap, no existing states."); boolean isOverlay = currentTopStateInfo.isOverlay; T newState; try { newState = ReflectionUtils.instantiateObject(stateType, new Class<?>[] { StateManager.class, EventManager.class }, new Object[] { this, eventManager }); } catch (Exception e) { throw new IllegalArgumentException("Could not instantiate a GameState instance of that type."); } StateInfo stateInfo = new StateInfo(newState, name); stateInfo.isOverlay = isOverlay; queueForSwap(stateInfo, false); return newState; } public <T extends GameState> T swapTopNonOverlayWith(Class<T> stateType) { return swapTopWith(stateType, null); } public <T extends GameState> T swapTopNonOverlayWith(Class<T> stateType, String name) { T newState; try { newState = ReflectionUtils.instantiateObject(stateType, new Class<?>[] { StateManager.class, EventManager.class }, new Object[] { this, eventManager }); } catch (Exception e) { throw new IllegalArgumentException("Could not instantiate a GameState instance of that type."); } StateInfo stateInfo = new StateInfo(newState, name); queueForSwap(stateInfo, true); return newState; } public void pop() { if (isTransitioning()) throw new UnsupportedOperationException(); Gdx.app.debug("StateManager", "Pop initiated for top-most state only."); startOnlyTopStateTransitioningOut(false); } public void popTopNonOverlay() { if (isTransitioning()) throw new UnsupportedOperationException(); Gdx.app.debug("StateManager", "Pop initiated for all top active states."); startTopStatesTransitioningOut(false); } public void pop(GameState state) { if (isTransitioning()) throw new UnsupportedOperationException(); StateInfo stateInfo = getStateInfoFor(state); if (stateInfo == null) throw new IllegalArgumentException("Trying to pop GameState that is not part of this StateManager."); if (stateInfo.isInactive) throw new IllegalArgumentException("This method can only be used to pop active GameStates."); startThisStateAndAboveTransitioningOut(stateInfo, false); } private void queueForPush(StateInfo newStateInfo) { if (newStateInfo == null) throw new IllegalArgumentException("newStateInfo cannot be null."); if (newStateInfo.state == null) throw new IllegalArgumentException("New StateInfo object has null GameState."); if (pushQueueHasOverlay && !newStateInfo.isOverlay) throw new UnsupportedOperationException("Cannot queue new non-overlay state while queue is active with overlay states."); Gdx.app.debug("StateManager", String.format("Queueing state %s for pushing.", newStateInfo)); if (!newStateInfo.isOverlay) startTopStatesTransitioningOut(true); pushQueue.add(newStateInfo); if (newStateInfo.isOverlay) pushQueueHasOverlay = true; } private void queueForSwap(StateInfo newStateInfo, boolean swapTopNonOverlay) { if (newStateInfo == null) throw new IllegalArgumentException("newStateInfo cannot be null."); if (newStateInfo.state == null) throw new IllegalArgumentException("New StateInfo object has null GameState."); if (swapQueueHasOverlay && !newStateInfo.isOverlay) throw new UnsupportedOperationException("Cannot queue new non-overlay state while queue is active with overlay states."); Gdx.app.debug("StateManager", String.format("Queueing state %s for swapping with %s.", newStateInfo, (swapTopNonOverlay ? "all top active states" : "only top-most active state."))); if (swapTopNonOverlay) startTopStatesTransitioningOut(false); else startOnlyTopStateTransitioningOut(false); swapQueue.add(newStateInfo); if (newStateInfo.isOverlay) swapQueueHasOverlay = true; } /*** events ***/ public void onAppPause() { for (int i = getTopNonOverlayIndex(); i != -1 && i < states.size(); ++i) { StateInfo stateInfo = states.get(i); if (!stateInfo.isInactive) stateInfo.state.onAppPause(); } } public void onAppResume() { for (int i = getTopNonOverlayIndex(); i != -1 && i < states.size(); ++i) { StateInfo stateInfo = states.get(i); if (!stateInfo.isInactive) stateInfo.state.onAppResume(); } } public void onResize() { for (int i = getTopNonOverlayIndex(); i != -1 && i < states.size(); ++i) { StateInfo stateInfo = states.get(i); if (!stateInfo.isInactive) stateInfo.state.onResize(); } } public void onRender(float interpolation) { for (int i = getTopNonOverlayIndex(); i != -1 && i < states.size(); ++i) { StateInfo stateInfo = states.get(i); if (!stateInfo.isInactive) { stateInfo.state.onRender(interpolation); stateInfo.state.effectManager.onRenderGlobal(interpolation); } } } public void onUpdateGameState(float delta) { lastCleanedStatesWereAllOverlays = false; cleanupInactiveStates(); checkForFinishedStates(); processQueues(); resumeStatesIfNeeded(); updateTransitions(delta); for (int i = getTopNonOverlayIndex(); i != -1 && i < states.size(); ++i) { StateInfo stateInfo = states.get(i); if (!stateInfo.isInactive) stateInfo.state.onUpdateGameState(delta); } } public void onUpdateFrame(float delta) { for (int i = getTopNonOverlayIndex(); i != -1 && i < states.size(); ++i) { StateInfo stateInfo = states.get(i); if (!stateInfo.isInactive) stateInfo.state.onUpdateFrame(delta); } } /*** internal state management functions ***/ private void startTopStatesTransitioningOut(boolean pausing) { int i = getTopNonOverlayIndex(); if (i == -1) return; for (; i < states.size(); ++i) { // only look at active states, since inactive ones have already been // transitioned out and will be removed on the next onUpdate() if (!states.get(i).isInactive) transitionOut(states.get(i), !pausing); } } private void startOnlyTopStateTransitioningOut(boolean pausing) { StateInfo info = getTop(); // if it's not active, then it's just been transitioned out and will be // removed on the next onUpdate() if (!info.isInactive) transitionOut(info, !pausing); } private void startThisStateAndAboveTransitioningOut(StateInfo info, boolean pausing) { int i = states.indexOf(info); if (i == -1) return; for (; i < states.size(); ++i) { // only look at active states, since inactive ones have already been // transitioned out and will be removed on the next onUpdate() if (!states.get(i).isInactive) transitionOut(states.get(i), !pausing); } } private void cleanupInactiveStates() { // we don't want to remove any states until everything is done transitioning. // this is to avoid the scenario where the top non-overlay state finishes // transitioning before one of the overlays. if we removed it, the overlays // would then be overlayed over an inactive non-overlay (which wouldn't get // resumed until the current active overlays were done being transitioned) if (isTransitioning()) return; boolean cleanedUpSomething = false; boolean cleanedUpNonOverlay = false; int i = 0; while (i < states.size()) { StateInfo stateInfo = states.get(i); if (stateInfo.isInactive && stateInfo.isBeingPopped) { cleanedUpSomething = true; if (!stateInfo.isOverlay) cleanedUpNonOverlay = true; // remove this state and move to the next node // (index doesn't change, we're removing one, so next index now equals this index) states.remove(i); Gdx.app.debug("StateManager", String.format("Deleting inactive popped state %s.", stateInfo)); stateInfo.state.dispose(); } else { i++; } } if (cleanedUpSomething && !cleanedUpNonOverlay) lastCleanedStatesWereAllOverlays = true; } private void checkForFinishedStates() { if (states.size() == 0) return; // don't do anything if something is currently transitioning if (isTransitioning()) return; boolean needToAlsoTransitionOutOverlays = false; // check the top non-overlay state first to see if it's finished // and should be transitioned out StateInfo topNonOverlayStateInfo = getTopNonOverlay(); if (!topNonOverlayStateInfo.isInactive && topNonOverlayStateInfo.state.isFinished()) { Gdx.app.debug("StateManager", String.format("State %s marked as finished.", topNonOverlayStateInfo)); transitionOut(topNonOverlayStateInfo, true); needToAlsoTransitionOutOverlays = true; } // now also check the overlay states (if there were any). we force them to // transition out if the non-overlay state started to transition out so that // we don't end up with overlay states without a parent non-overlay state // start the loop off 1 beyond the top non-overlay (which is where the // overlays are, if any) int i = getTopNonOverlayIndex(); if (i != -1) { for (++i; i < states.size(); ++i) { StateInfo stateInfo = states.get(i); if (!stateInfo.isInactive && (stateInfo.state.isFinished() || needToAlsoTransitionOutOverlays)) { Gdx.app.debug("StateManager", String.format("State %s marked as finished.", stateInfo)); transitionOut(stateInfo, true); } } } } private void processQueues() { // don't do anything if stuff is currently transitioning if (isTransitioning()) return; if (pushQueue.size() > 0 && swapQueue.size() > 0) throw new UnsupportedOperationException("Cannot process queues when both the swap and push queues have items currently in them."); // for each state in the queu, add it to the main list and start transitioning it in // (note, only one of these queues will be processed each tick due to the above check!) while (pushQueue.size() > 0) { StateInfo stateInfo = pushQueue.removeFirst(); if (states.size() > 0) { // if this new state is an overlay, and the current top state is both // currently active and is not currently marked as being overlay-ed // then we should pause it due to overlay StateInfo currentTopStateInfo = getTop(); if (stateInfo.isOverlay && !currentTopStateInfo.isInactive && !currentTopStateInfo.isOverlayed) { Gdx.app.debug("StateManager", String.format("Pausing %sstate %s due to overlay.", (currentTopStateInfo.isOverlay ? "overlay " : ""), currentTopStateInfo)); currentTopStateInfo.state.onPause(true); // also mark the current top state as being overlay-ed currentTopStateInfo.isOverlayed = true; } } states.addLast(stateInfo); Gdx.app.debug("StateManager", String.format("Pushing %sstate %s from push-queue.", (stateInfo.isOverlay ? "overlay " : ""), stateInfo)); stateInfo.state.onPush(); transitionIn(stateInfo, false); } while (swapQueue.size() > 0) { StateInfo stateInfo = swapQueue.removeFirst(); // if this new state is an overlay, and the current top state is both // currently active and is not currently marked as being overlay-ed // then we should pause it due to overlay StateInfo currentTopStateInfo = getTop(); if (stateInfo.isOverlay && !currentTopStateInfo.isInactive && !currentTopStateInfo.isOverlayed) { Gdx.app.debug("StateManager", String.format("Pausing %sstate %s due to overlay.", (currentTopStateInfo.isOverlay ? "overlay " : ""), currentTopStateInfo)); currentTopStateInfo.state.onPause(true); // also mark the current top state as being overlay-ed currentTopStateInfo.isOverlayed = true; } states.addLast(stateInfo); Gdx.app.debug("StateManager", String.format("Pushing %sstate %s from swap-queue.", (stateInfo.isOverlay ? "overlay " : ""), stateInfo)); stateInfo.state.onPush(); transitionIn(stateInfo, false); } pushQueueHasOverlay = false; swapQueueHasOverlay = false; } private void resumeStatesIfNeeded() { if (states.size() == 0) return; // don't do anything if stuff is currently transitioning if (isTransitioning()) return; // did we just clean up one or more overlay states? if (lastCleanedStatesWereAllOverlays) { // then we need to resume the current top state // (those paused with the flag "from an overlay") StateInfo stateInfo = getTop(); if (stateInfo.isInactive || !stateInfo.isOverlayed) throw new UnsupportedOperationException(); Gdx.app.debug("StateManager", String.format("Resuming %sstate %s due to overlay removal.", (stateInfo.isOverlay ? "overlay " : ""), stateInfo)); stateInfo.state.onResume(true); stateInfo.isOverlayed = false; return; } // if the top state is no inactive, then we don't need to resume anything if (!getTop().isInactive) return; Gdx.app.debug("StateManager", "Top-most state is inactive. Resuming all top states up to and including the next non-overlay."); // top state is inactive. time to reusme one or more states... // find the topmost non-overlay state and take it and all overlay states that // are above it, and transition them in for (int i = getTopNonOverlayIndex(); i != -1 && i < states.size(); ++i) { StateInfo stateInfo = states.get(i); Gdx.app.debug("StateManager", String.format("Resuming %sstate %s.", (stateInfo.isOverlay ? "overlay " : ""), stateInfo)); stateInfo.state.onResume(false); transitionIn(stateInfo, true); } } private void updateTransitions(float delta) { for (int i = getTopNonOverlayIndex(); i != -1 && i < states.size(); ++i) { StateInfo stateInfo = states.get(i); if (stateInfo.isTransitioning) { boolean isDone = stateInfo.state.onTransition(delta, stateInfo.isTransitioningOut, stateInfo.isTransitionStarting); if (isDone) { Gdx.app.debug("StateManager", String.format("Transition %s %sstate %s finished.", (stateInfo.isTransitioningOut ? "out of" : "into"), (stateInfo.isOverlay ? "overlay " : ""), stateInfo)); // if the state was being transitioned out, then we should mark // it as inactive, and trigger it's onPop() or onPause() event now if (stateInfo.isTransitioningOut) { if (stateInfo.isBeingPopped) { Gdx.app.debug("StateManager", String.format("Popping %sstate %s", (stateInfo.isOverlay ? "overlay " : ""), stateInfo)); stateInfo.state.onPop(); // TODO: do I care enough to port the return value stuff which goes here? } else { Gdx.app.debug("StateManager", String.format("Pausing %sstate %s.", (stateInfo.isOverlay ? "overlay " : ""), stateInfo)); stateInfo.state.onPause(false); } stateInfo.isInactive = true; } // done transitioning stateInfo.isTransitioning = false; stateInfo.isTransitioningOut = false; } stateInfo.isTransitionStarting = false; } } } private void transitionIn(StateInfo stateInfo, boolean forResuming) { stateInfo.isInactive = false; stateInfo.isTransitioning = true; stateInfo.isTransitioningOut = false; stateInfo.isTransitionStarting = true; Gdx.app.debug("StateManager", String.format("Transition into %sstate %s started.", (stateInfo.isOverlay ? "overlay " : ""), stateInfo)); //if (forResuming) // stateInfo.getState().getProcessManager().onResume(false); } private void transitionOut(StateInfo stateInfo, boolean forPopping) { stateInfo.isTransitioning = true; stateInfo.isTransitioningOut = true; stateInfo.isTransitionStarting = true; stateInfo.isBeingPopped = forPopping; Gdx.app.debug("StateManager", String.format("Transition out of %sstate %s started.", (stateInfo.isOverlay ? "overlay " : ""), stateInfo)); //if (forPopping) // stateInfo.getState().getProcessManager().removeAll(); //else // stateInfo.getState().getProcessManager().onPause(false); } /*** private state getters ***/ private StateInfo getStateInfoFor(GameState state) { if (state == null) throw new IllegalArgumentException("state cannot be null."); for (int i = 0; i < states.size(); ++i) { if (states.get(i).state == state) return states.get(i); } return null; } private StateInfo getTop() { return (states.isEmpty() ? null : states.getLast()); } private StateInfo getTopNonOverlay() { int index = getTopNonOverlayIndex(); return (index == -1 ? null : states.get(index)); } private int getTopNonOverlayIndex() { for (int i = states.size() - 1; i >= 0; i if (!states.get(i).isOverlay) return i; } return (states.size() > 0 ? 0 : -1); } /*** cleanup ***/ public void dispose() { if (states == null) return; Gdx.app.debug("StateManager", "dispose"); while (states.size() > 0) { StateInfo stateInfo = states.getLast(); Gdx.app.debug("StateManager", String.format("Popping state %s as part of StateManager shutdown.", stateInfo)); stateInfo.state.onPop(); stateInfo.state.dispose(); states.removeLast(); } // these queues will likely not have anything in them, but just in case ... while (pushQueue.size() > 0) { StateInfo stateInfo = pushQueue.removeFirst(); Gdx.app.debug("StateManager", String.format("Deleting push-queued state %s as part of StateManager shutdown.", stateInfo)); stateInfo.state.dispose(); } while (swapQueue.size() > 0) { StateInfo stateInfo = swapQueue.removeFirst(); Gdx.app.debug("StateManager", String.format("Deleting swap-queued state %s as part of StateManager shutdown.", stateInfo)); stateInfo.state.dispose(); } states = null; pushQueue = null; swapQueue = null; } }
package cat.udl.eps.butterp.data; import cat.udl.eps.butterp.environment.Environment; public final class Integer implements SExpression { public final int value; public Integer(int value) { this.value = value; } @Override public SExpression eval(Environment env) { throw new UnsupportedOperationException("not implemented yet"); } @Override public boolean equals(Object o) { return o instanceof Integer && ((Integer)o).value == value; } @Override public int hashCode() { return value; // Since the return is an int, we can use its actual value. } @Override public String toString() { return String.valueOf(value); } }
package ch.tkuhn.nanopub.server; import java.io.IOException; import java.util.regex.Pattern; import javax.servlet.http.HttpServletResponse; import net.trustyuri.TrustyUriUtils; import com.mongodb.BasicDBObject; import com.mongodb.DBCollection; import com.mongodb.DBCursor; public class ListPage extends Page { private boolean asHtml; public static void show(ServerRequest req, HttpServletResponse httpResp) throws IOException { ListPage obj = new ListPage(req, httpResp); obj.show(); } public ListPage(ServerRequest req, HttpServletResponse httpResp) { super(req, httpResp); String rf = getReq().getPresentationFormat(); if (rf == null) { String suppFormats = "text/plain,text/html"; asHtml = "text/html".equals(Utils.getMimeType(getHttpReq(), suppFormats)); } else { asHtml = "text/html".equals(getReq().getPresentationFormat()); } } public void show() throws IOException { DBCollection coll = NanopubDb.get().getNanopubCollection(); Pattern p = Pattern.compile(getReq().getListQueryRegex()); BasicDBObject query = new BasicDBObject("_id", p); DBCursor cursor = coll.find(query); int c = 0; int maxListSize = ServerConf.get().getMaxListSize(); printStart(); boolean hasContinuation = false; while (cursor.hasNext()) { c++; if (c > maxListSize) { hasContinuation = true; break; } printElement(cursor.next().get("uri").toString()); } if (c == 0 && asHtml) { println("<p><em>(no nanopub with artifact code starting with '" + getReq().getListQuerySequence() + "')</em></p>"); } if (hasContinuation) { printContinuation(); } printEnd(); if (asHtml) { getResp().setContentType("text/html"); } else { getResp().setContentType("text/plain"); } } private void printStart() throws IOException { if (asHtml) { String seq = getReq().getListQuerySequence(); printHtmlHeader("Nanopub Server: List of nanopubs " + seq); print("<h3>List of stored nanopubs"); if (seq.length() > 0) { print(" (with artifact code starting with '" + seq + "')"); } println("</h3>"); println("<table><tbody>"); } } private void printElement(String npUri) throws IOException { if (asHtml) { print("<tr>"); print("<td>"); print("<a href=\"" + TrustyUriUtils.getArtifactCode(npUri) + "\">get</a> ("); print("<a href=\"" + TrustyUriUtils.getArtifactCode(npUri) + ".trig\">trig</a>,"); print("<a href=\"" + TrustyUriUtils.getArtifactCode(npUri) + ".nq\">nq</a>,"); print("<a href=\"" + TrustyUriUtils.getArtifactCode(npUri) + ".xml\">xml</a>)"); print("</td>"); print("<td>"); print("<a href=\"" + TrustyUriUtils.getArtifactCode(npUri) + ".txt\">show</a> ("); print("<a href=\"" + TrustyUriUtils.getArtifactCode(npUri) + ".trig.txt\">trig</a>,"); print("<a href=\"" + TrustyUriUtils.getArtifactCode(npUri) + ".nq.txt\">nq</a>,"); print("<a href=\"" + TrustyUriUtils.getArtifactCode(npUri) + ".xml.txt\">xml</a>)"); print("</td>"); print("<td><span class=\"code\">" + npUri + "</span></td>"); println("</tr>"); } else { println(npUri); } } private void printContinuation() throws IOException { if (asHtml) { println("<p><em>... and more:</em> "); for (char ch : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".toCharArray()) { println("<span class=\"code\"><a href=\"" + getReq().getListQuerySequence() + ch + "+\">" + ch + "</a></span>"); } println("</p>"); } else { println("..."); } } private void printEnd() throws IOException { if (asHtml) { println("</tbody></table>"); println("<p>[<a href=\"" + getReq().getRequestString() + ".txt\">as plain text</a>]</p>"); printHtmlFooter(); } } }
package chav1961.purelib.basic; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Array; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import chav1961.purelib.basic.exceptions.CommandLineParametersException; import chav1961.purelib.basic.exceptions.ContentException; import chav1961.purelib.sql.SQLUtils; /** * <p>This class is used to parse and access command line arguments for console-based applications. Recommended template to use it is produce * child class for it:</p> * <code> * . . .<br> * class ChildArgParser extends ArgParser {<br> * public ChildArgParser(){<br> * super(new ZZZarg(...),...);<br> * }<br> * }<br> * . . .<br> * static ChildArgParser parser = new ChildArgParser();<br> * . . . <br> * public static void main(String[] args) {<br> * ChildArgParser currentList = parser.parse(args);<br> * . . .<br> * int value = currentList.getValue("intName",int.class);<br> * . . .<br> * }<br> * </code> * <p>The class supports a set of argument types (marked as ZZZarg in the example above):</p> * <ul> * <li>{linkplain BooleanArg} - argument-flag</li> * <li>{linkplain IntegerArg} - long integer argument</li> * <li>{linkplain RealArg} - double or BigDecimal argument</li> * <li>{linkplain StringArg} - string argument</li> * <li>{linkplain EnumArg} - any enumeration argument</li> * <li>{linkplain URIArg} - {@linkplain URI} argument</li> * <li>{linkplain StringListArg} - list of string argument(s)</li> * <li>{linkplain ConfigArg} - configuration source argument</li> * <li>{linkplain SwitchArg} - configuration source argument</li> * <li>{linkplain PatternArg} - pattern source argument</li> * </ul> * <p>Any of these arguments can be declared as positional or key-value argument. Positional arguments must be declared before key-value arguments. * Positional argument has name to access to it, but doesn't require the name to be typed in the command string. Key-value argument also has a name and the name * must be typed in the command string. Order to type key-value arguments in the command string is not important.</p> * <p>{@linkplain ConfigArg} argument type is used to store part or all the command line arguments in external data source (file, URI connection etc). When you get value * for any argument and it doesn't explicitly typed in the command string, it's value will be extracted from the external data source. External data source must have format * compatible with {@linkplain SubstitutableProperties} requirements.</p> * <p>This class can be used in multi-threaded environment</p> * * @see chav1961.purelib.basic JUnit tests * * @author Alexander Chernomyrdin aka chav1961 * @since 0.0.3 * @lastUpdate 0.0.4 */ public class ArgParser { private final char keyPrefix; private final boolean caseSensitive; private final ArgDescription[] desc; private final Map<String,String[]> pairs; private final boolean hasConfigArg; protected ArgParser(final ArgDescription... desc) throws IllegalArgumentException { this('-',true,desc); } protected ArgParser(final char keyPrefix, final boolean caseSensitive, final ArgDescription... desc) throws IllegalArgumentException { if (desc == null || desc.length == 0) { throw new IllegalArgumentException("Argument description list can't be null or empty array"); } else if (Utils.checkArrayContent4Nulls(desc) >= 0) { throw new IllegalArgumentException("Nulls inside desc argument"); } else { final Set<String> names = new HashSet<>(); boolean prevPosWasList = false, hasConfig = false; for (ArgDescription item : desc) { final String key = caseSensitive ? item.getName() : item.getName().toLowerCase(); if (names.contains(key)) { throw new IllegalArgumentException("Duplicate key name ["+item.getName()+"] in the parameters list"); } else if (item.isPositional() && !item.hasValue()) { throw new IllegalArgumentException("Positional parameter ["+item.getName()+"] is marked as has no value!"); } else if (item.isList() && !item.hasValue()) { throw new IllegalArgumentException("List value parameter ["+item.getName()+"] is marked as has no value!"); } else if (item.isPositional() && prevPosWasList) { throw new IllegalArgumentException("List-specified positional parameter ["+item.getName()+"] has list-specified predecessor!"); } else { prevPosWasList = item.isList(); names.add(item.getName()); if (item instanceof ConfigArg) { hasConfig = true; } } } this.keyPrefix = keyPrefix; this.caseSensitive = caseSensitive; this.desc = desc; this.pairs = null; this.hasConfigArg = hasConfig; } } private ArgParser(final char keyPrefix, final boolean caseSensitive, final ArgDescription[] desc, final boolean hasConfigArg, final Map<String,String[]> pairs) { this.keyPrefix = keyPrefix; this.caseSensitive = caseSensitive; this.desc = desc; this.hasConfigArg = hasConfigArg; this.pairs = Collections.unmodifiableMap(pairs); } /** * <p>Parse parameters and return new instance of {@linkplain ArgParser} to access them</p> * @param args parameters to parse * @return new {@linkplain ArgParser} instance to access to the parameters parsed * @throws CommandLineParametersException on any parsing errors */ public ArgParser parse(final String... args) throws CommandLineParametersException { return parse(false,false,args); } /** * <p>Parse parameters and return new instance of {@linkplain ArgParser} to access them</p> * @param ignoreExtra ignore extra arguments without exceptions * @param ignoreUnknown ignore unknown arguments without exceptions * @param args parameters to parse * @return new {@linkplain ArgParser} instance to access to the parameters parsed * @throws CommandLineParametersException on any parsing errors */ public ArgParser parse(final boolean ignoreExtra, final boolean ignoreUnknown, final String... args) throws CommandLineParametersException { if (this.pairs != null) { throw new IllegalStateException("Attempt to call parse(...) on parsed instance. This method can be called on 'parent' instance only"); } else if (args == null) { throw new NullPointerException("Argument list to parse can't be null"); } else { final Map<String,String[]> pairs = new HashMap<>(); parseParameters(ignoreExtra,ignoreUnknown,keyPrefix,caseSensitive,desc,hasConfigArg,args,pairs); return new ArgParser(keyPrefix,caseSensitive,desc,hasConfigArg,pairs); } } @SuppressWarnings("unchecked") public <T> T getValue(final String key, final Class<T> awaited) throws CommandLineParametersException, IllegalStateException, IllegalArgumentException, NullPointerException { if (this.pairs == null) { throw new IllegalStateException("Attempt to call getValue(...) on 'parent' instance. Call parse(...) method and use value returned for this purpose"); } else if (key == null || key.isEmpty()) { throw new IllegalArgumentException("Key to get value for can't be null or empty"); } else if (awaited == null) { throw new NullPointerException("Result class awaited can't be null"); } else { final String keyFind = caseSensitive ? key : key.toLowerCase(); final ArgDescription found = forKey(keyFind,desc,caseSensitive); if (found == null) { if (awaited == String.class) { return pairs.get(keyFind) == null ? null : (T)pairs.get(keyFind)[0].toString(); } else { throw new IllegalArgumentException("Unknown of undeclared key ["+key+"]: only String.class can be used for awaited class"); } } else if (pairs.containsKey(keyFind)) { return (T)convert(found,awaited,pairs.get(keyFind)); } else { return (T)convert(found,awaited,found.getDefaultValue()); } } } public boolean isTyped(final String key) throws IllegalStateException, IllegalArgumentException{ if (this.pairs == null) { throw new IllegalStateException("Attempt to call isTyped() on 'parent' instance. Call parse(...) method and use value returned for this purpose"); } else if (key == null || key.isEmpty()) { throw new IllegalArgumentException("Key to test can't be null or empty"); } else { final String keyFind = caseSensitive ? key : key.toLowerCase(); return pairs.containsKey(keyFind);// || forKey(keyFind,desc,caseSensitive) != null; } } /** * <p>Are all parameters typed</p> * @param keys parameters to test * @return true of all parameters typed * @since 0.0.4 */ public boolean allAreTyped(final String... keys) { if (keys == null || keys.length == 0 || Utils.checkArrayContent4Nulls(keys) > 0) { throw new IllegalArgumentException("Keys to test are null, empty or contain nulls inside"); } else { for (String item : keys) { if (!isTyped(item)) { return false; } } return true; } } public String getUsage(final String applicationName) throws IllegalArgumentException { if (applicationName == null || applicationName.isEmpty()) { throw new IllegalArgumentException("Application name can't be null or empty"); } else { final StringBuilder sb = new StringBuilder(); sb.append("Usage: ").append(applicationName); for (ArgDescription item : desc) { sb.append(' '); if (item.isPositional()) { sb.append('<').append(item.getName()).append('>'); } else { sb.append(keyPrefix).append(item.getName()); if (item.hasValue()) { sb.append(" <value>"); } } if (item.isList()) { sb.append("..."); } } sb.append('\n'); for (ArgDescription item : desc) { sb.append('\t'); if (item.isPositional()) { sb.append(item.getName()).append(": - ").append(item.getHelpDescriptor()).append('\n'); } else { sb.append(keyPrefix).append(item.getName()).append(": - ").append(item.getHelpDescriptor()).append('\n'); } } return sb.toString(); } } static void parseParameters(final boolean ignoreExtra, final boolean ignoreUnknown, final char keyPrefix, final boolean caseSensitive, final ArgDescription[] desc, final boolean hasConfigArg, final String[] args, final Map<String, String[]> pairs) throws CommandLineParametersException { final Set<String> names = new HashSet<>(); ArgDescription confArg = null; int positional = 0; loop: for (int index = 0; index < args.length; index++) { if (args[index].isEmpty() || args[index].charAt(0) != keyPrefix) { int found = 0; for (ArgDescription item : desc) { if (hasConfigArg) { names.add(item.getName()); if (item instanceof ConfigArg) { confArg = item; } } if (item.isPositional()) { if (found == positional) { if (item.isList()) { final List<String> collection = new ArrayList<>(); index = collectList(args,index,keyPrefix,collection)-1; for (String value : collection) { item.validate(value); } pairs.put(item.getName(),collection.toArray(new String[collection.size()])); } else { item.validate(args[index]); pairs.put(item.getName(),new String[]{args[index]}); } positional++; continue loop; } else { found++; } } } if (!ignoreExtra) { throw new CommandLineParametersException("Extra positional parameter ["+args[index]+"] was detected"); } } else { final String key = args[index].substring(1); final String keyFind = caseSensitive ? key : key.toLowerCase(); final ArgDescription found = forKey(keyFind,desc,caseSensitive); if (found == null) { if (!ignoreUnknown) { throw new CommandLineParametersException("Key parameter [-"+key+"] is not supported for the parser"); } } else if (found.hasValue()) { if (index == args.length-1) { throw new CommandLineParametersException("Key parameter [-"+key+"] has no value awaited"); } else if (found.isList()) { final List<String> collection = new ArrayList<>(); index = collectList(args,index+1,keyPrefix,collection)-1; for (String value : collection) { found.validate(value); } pairs.put(found.getName(),collection.toArray(new String[collection.size()])); } else { found.validate(args[index+1]); pairs.put(found.getName(),new String[]{args[index+1]}); index++; } } else { found.validate("true"); pairs.put(found.getName(),new String[]{"true"}); } } } final StringBuilder sb = new StringBuilder(); for (ArgDescription item : desc) { if (item.isMandatory()) { if (!pairs.containsKey(item.getName())) { sb.append(',').append(item.getName()); } } } if (sb.length() > 0) { throw new CommandLineParametersException("Mandatory argument(s) ["+sb.toString().substring(1)+"] are missing in the parameters"); } if (hasConfigArg && confArg != null && (pairs.containsKey(confArg.getName()) || confArg.getDefaultValue() != null)) { final SubstitutableProperties sp = new SubstitutableProperties(); final String confSource = (pairs.containsKey(confArg.getName()) ? pairs.get(confArg.getName()) : confArg.getDefaultValue())[0]; final URI sourceURI = confArg.getValue(confSource,URI.class); try(final InputStream is = (sourceURI.isAbsolute() ? sourceURI : URI.create("file:"+sourceURI.toString())).toURL().openStream()) { sp.load(is); } catch (IOException e) { throw new CommandLineParametersException("I/O error reading configuration source ["+confSource+"] : "+e.getLocalizedMessage()); } if (!ignoreUnknown) { for (Entry<Object,Object> item : sp.entrySet()) { if (!names.contains(item.getKey().toString())) { sb.append(',').append(item.getKey().toString()); } } if (sb.length() > 0) { throw new CommandLineParametersException("Configuration source ["+confSource+"] contains unknown parameters ["+sb.substring(1)+"]"); } } for (Entry<Object,Object> item : sp.entrySet()) { pairs.putIfAbsent(item.getKey().toString(),new String[]{sp.getProperty(item.getKey().toString())}); } } } static int collectList(final String[] args, int from, final char keyPrefix, final List<String> collection) { for (;from < args.length; from++) { if (args[from].length() == 0 || args[from].charAt(0) != keyPrefix) { collection.add(args[from]); } else { break; } } return from; } @SuppressWarnings("unchecked") static <T> T convert(final ArgDescription desc, final Class<T> awaited, final String[] value) throws CommandLineParametersException { if (value != null) { if (awaited.isArray()) { final Object[] result = (Object[]) Array.newInstance(awaited.getComponentType(),value.length); for (int index = 0; index < value.length; index++) { Array.set(result,index,desc.getValue(value[index],awaited.getComponentType())); } return(T)result; } else if (value.length > 0 && value[0] != null) { return (T)desc.getValue(value[0],awaited); } else { return null; } } else { return null; } } static ArgDescription forKey(final String key, final ArgDescription[] desc, final boolean caseSensitive) { for (ArgDescription item : desc) { if (!caseSensitive && item.getName().equals(key) || caseSensitive && item.getName().equalsIgnoreCase(key)) { return item; } } return null; } protected interface ArgDescription { String getName(); String getHelpDescriptor(); <T> T getValue(String value, Class<T> awaited) throws CommandLineParametersException; String[] getDefaultValue(); boolean isMandatory(); boolean isPositional(); boolean isList(); boolean hasValue(); void validate(String value) throws CommandLineParametersException; } protected abstract static class AbstractArg implements ArgDescription { private final String name; private final String helpDescriptor; private final boolean isMandatory; private final boolean isPositional; public AbstractArg(final String name, final boolean isMandatory, final boolean isPositional, final String helpDescriptor) { if (name == null || name.isEmpty()) { throw new IllegalArgumentException("Argument name can't be null or empty"); } else if (helpDescriptor == null || helpDescriptor.isEmpty()) { throw new IllegalArgumentException("Argument help descriptor can't be null or empty"); } else { this.name = name; this.helpDescriptor = helpDescriptor; this.isMandatory = isMandatory; this.isPositional = isPositional; } } @Override public abstract <T> T getValue(final String value, final Class<T> awaited) throws CommandLineParametersException; @Override public abstract String[] getDefaultValue(); @Override public abstract boolean isList(); @Override public abstract void validate(final String value) throws CommandLineParametersException; @Override public String getName() { return name; } @Override public String getHelpDescriptor() { return helpDescriptor; } @Override public boolean isMandatory() { return isMandatory; } @Override public boolean isPositional() { return isPositional; } @Override public boolean hasValue() { return true; } @Override public String toString() { return "AbstractArg [name=" + name + ", helpDescriptor=" + helpDescriptor + ", isMandatory=" + isMandatory + ", isPositional=" + isPositional + "]"; } } protected static class BooleanArg extends AbstractArg { private static final Set<Class<?>> SUPPORTED_CONVERSIONS = new HashSet<>(); static { SUPPORTED_CONVERSIONS.add(boolean.class); SUPPORTED_CONVERSIONS.add(Boolean.class); SUPPORTED_CONVERSIONS.add(String.class); } private final String[] defaults; public BooleanArg(final String name, final boolean isMandatory, final boolean isPositional, final String helpDescriptor) { super(name, isMandatory, isPositional, helpDescriptor); this.defaults = new String[]{"false"}; } public BooleanArg(final String name, final boolean isPositional, final String helpDescriptor, final boolean defaultValue) { super(name, false, isPositional, helpDescriptor); this.defaults = new String[]{String.valueOf(defaultValue)}; } @Override public <T> T getValue(final String value, final Class<T> awaited) throws CommandLineParametersException { try{if (SUPPORTED_CONVERSIONS.contains(awaited)) { return (T)SQLUtils.convert(awaited, value); } else { throw new CommandLineParametersException("Argument ["+getName()+"] can be converted to boolean or string type only, conversion to ["+awaited.getCanonicalName()+"] is not supported"); } } catch (ContentException e) { throw new CommandLineParametersException("Error converting argument ["+getName()+"] value ["+value+"] to ["+awaited.getCanonicalName()+"] type"); } } @Override public String[] getDefaultValue() { return defaults; } @Override public boolean isList() { return false; } @Override public void validate(final String value) throws CommandLineParametersException { if (value == null || value.isEmpty()) { throw new CommandLineParametersException("Argument ["+getName()+"]: value can't be null or empty"); } else { if (!"true".equalsIgnoreCase(value) && !"false".equalsIgnoreCase(value)) { throw new CommandLineParametersException("Argument ["+getName()+"]: value doesn't have valid boolean: "+value); } } } @Override public boolean hasValue() { return isPositional(); } @Override public String toString() { return "BooleanArg [defaults=" + Arrays.toString(defaults) + ", toString()=" + super.toString() + "]"; } } protected static class IntegerArg extends AbstractArg { private static final Set<Class<?>> SUPPORTED_CONVERSIONS = new HashSet<>(); static { SUPPORTED_CONVERSIONS.add(long.class); SUPPORTED_CONVERSIONS.add(Long.class); SUPPORTED_CONVERSIONS.add(int.class); SUPPORTED_CONVERSIONS.add(Integer.class); SUPPORTED_CONVERSIONS.add(short.class); SUPPORTED_CONVERSIONS.add(Short.class); SUPPORTED_CONVERSIONS.add(byte.class); SUPPORTED_CONVERSIONS.add(Byte.class); SUPPORTED_CONVERSIONS.add(String.class); } private final String[] defaults; private final long[][] ranges; public IntegerArg(final String name, final boolean isMandatory, final boolean isPositional, final String helpDescriptor) { this(name,isMandatory,isPositional,helpDescriptor,new long[][]{new long[]{Long.MIN_VALUE,Long.MAX_VALUE}}); } public IntegerArg(final String name, final boolean isPositional, final String helpDescriptor, final long defaultValue) { this(name,isPositional,helpDescriptor,defaultValue,new long[][]{new long[]{Long.MIN_VALUE,Long.MAX_VALUE}}); } public IntegerArg(final String name, final boolean isMandatory, final boolean isPositional, final String helpDescriptor, final long[][] availableRanges) { super(name, isMandatory, isPositional, helpDescriptor); this.defaults = new String[]{"0"}; this.ranges = availableRanges; } public IntegerArg(final String name, final boolean isPositional, final String helpDescriptor, final long defaultValue, final long[][] availableRanges) { super(name, false, isPositional, helpDescriptor); this.defaults = new String[]{String.valueOf(defaultValue)}; this.ranges = availableRanges; } @Override public <T> T getValue(final String value, final Class<T> awaited) throws CommandLineParametersException { try{if (SUPPORTED_CONVERSIONS.contains(awaited)) { return (T)SQLUtils.convert(awaited, value); } else { throw new CommandLineParametersException("Argument ["+getName()+"] can be converted to integer or string type only, conversion to ["+awaited.getCanonicalName()+"] is not supported"); } } catch (ContentException e) { throw new CommandLineParametersException("Error converting argument ["+getName()+"] value ["+value+"] to ["+awaited.getCanonicalName()+"] type"); } } @Override public String[] getDefaultValue() { return defaults; } @Override public boolean isList() { return false; } @Override public void validate(final String value) throws CommandLineParametersException { if (value == null || value.isEmpty()) { throw new CommandLineParametersException("Argument ["+getName()+"]: value can't be null or empty"); } else { try{final long longValue = Long.valueOf(value).longValue(); for (long[] range : ranges) { if (range[0] <= longValue && longValue <= range[1]) { return; } } final StringBuilder sb = new StringBuilder(); for (long[] range : ranges) { if (range[0] == range[1]) { sb.append(',').append(range[0]); } else { sb.append(',').append(range[0]).append("..").append(range[1]); } } throw new CommandLineParametersException("Argument ["+getName()+"]: value ["+longValue+"] out of range. Available values are "+sb.delete(0, 0).toString()); } catch (NumberFormatException exc) { throw new CommandLineParametersException("Argument ["+getName()+"]: value doesn't have valid integer: "+value); } } } @Override public String toString() { return "IntegerArg [defaults=" + Arrays.toString(defaults) + ", toString()=" + super.toString() + "]"; } } protected static class RealArg extends AbstractArg { private static final Set<Class<?>> SUPPORTED_CONVERSIONS = new HashSet<>(); static { SUPPORTED_CONVERSIONS.add(float.class); SUPPORTED_CONVERSIONS.add(Float.class); SUPPORTED_CONVERSIONS.add(double.class); SUPPORTED_CONVERSIONS.add(Double.class); SUPPORTED_CONVERSIONS.add(String.class); } private final String[] defaults; public RealArg(final String name, final boolean isMandatory, final boolean isPositional, final String helpDescriptor) { super(name, isMandatory, isPositional, helpDescriptor); this.defaults = new String[]{"0.0"}; } public RealArg(final String name, final boolean isPositional, final String helpDescriptor, final double defaultValue) { super(name, false, isPositional, helpDescriptor); this.defaults = new String[]{String.valueOf(defaultValue)}; } @Override public <T> T getValue(final String value, final Class<T> awaited) throws CommandLineParametersException { try{if (SUPPORTED_CONVERSIONS.contains(awaited)) { return (T)SQLUtils.convert(awaited, value); } else { throw new CommandLineParametersException("Argument ["+getName()+"] can be converted to floating or string type only, conversion to ["+awaited.getCanonicalName()+"] is not supported"); } } catch (ContentException e) { throw new CommandLineParametersException("Error converting argument ["+getName()+"] value ["+value+"] to ["+awaited.getCanonicalName()+"] type"); } } @Override public String[] getDefaultValue() { return defaults; } @Override public boolean isList() { return false; } @Override public void validate(final String value) throws CommandLineParametersException { if (value == null || value.isEmpty()) { throw new CommandLineParametersException("Argument ["+getName()+"]: value can't be null or empty"); } else { try{Double.valueOf(value).doubleValue(); } catch (NumberFormatException exc) { throw new CommandLineParametersException("Argument ["+getName()+"]: value doesn't have valid real: "+value); } } } @Override public String toString() { return "RealArg [defaults=" + Arrays.toString(defaults) + ", toString()=" + super.toString() + "]"; } } protected static class StringArg extends AbstractArg { private final String[] defaults; public StringArg(final String name, final boolean isMandatory, final boolean isPositional, final String helpDescriptor) { super(name, isMandatory, isPositional, helpDescriptor); this.defaults = new String[]{""}; } public StringArg(final String name, final boolean isPositional, final String helpDescriptor, final String defaultValue) { super(name, false, isPositional, helpDescriptor); this.defaults = new String[]{defaultValue}; } @SuppressWarnings("unchecked") @Override public <T> T getValue(final String value, final Class<T> awaited) throws CommandLineParametersException { if (String.class.isAssignableFrom(awaited)) { return (T)value; } else { throw new CommandLineParametersException("Argument ["+getName()+"] can be converted to string type only, conversion to ["+awaited.getCanonicalName()+"] is not supported"); } } @Override public String[] getDefaultValue() { return defaults; } @Override public boolean isList() { return false; } @Override public void validate(final String value) throws CommandLineParametersException { if (value == null) { throw new CommandLineParametersException("Argument ["+getName()+"]: value can't be null"); } } @Override public String toString() { return "StringArg [defaults=" + Arrays.toString(defaults) + ", toString()=" + super.toString() + "]"; } } protected static class PatternArg extends StringArg { public PatternArg(final String name, final boolean isMandatory, final boolean isPositional, final String helpDescriptor) { super(name, isMandatory, isPositional, helpDescriptor); } public PatternArg(final String name, final boolean isPositional, final String helpDescriptor, final String defaultValue) { super(name, isPositional, helpDescriptor, defaultValue); } @SuppressWarnings("unchecked") @Override public <T> T getValue(final String value, final Class<T> awaited) throws CommandLineParametersException { if (Pattern.class.isAssignableFrom(awaited)) { validate(value); return (T)Pattern.compile(value); } else { return super.getValue(value,awaited); } } @Override public void validate(final String value) throws CommandLineParametersException { if (value == null || value.isEmpty()) { throw new CommandLineParametersException("Argument ["+getName()+"]: value can't be null or empty"); } else { try{Pattern.compile(value); } catch (PatternSyntaxException exc) { throw new CommandLineParametersException("Argument ["+getName()+"], value ["+value+"]: invalid syntax ("+exc.getLocalizedMessage()+")"); } } } @Override public String toString() { return "PatternArg [defaults=" + Arrays.toString(getDefaultValue()) + ", toString()=" + super.toString() + "]"; } } protected static class URIArg extends AbstractArg { private static final Set<Class<?>> SUPPORTED_CONVERSIONS = new HashSet<>(); static { SUPPORTED_CONVERSIONS.add(URI.class); SUPPORTED_CONVERSIONS.add(String.class); } private final String[] defaults; public URIArg(final String name, final boolean isMandatory, final boolean isPositional, final String helpDescriptor) { super(name, isMandatory, isPositional, helpDescriptor); this.defaults = new String[]{""}; } public URIArg(final String name, final boolean isPositional, final String helpDescriptor, final String defaultValue) { super(name, false, isPositional, helpDescriptor); this.defaults = new String[]{defaultValue}; } @Override public <T> T getValue(final String value, final Class<T> awaited) throws CommandLineParametersException { try{if (SUPPORTED_CONVERSIONS.contains(awaited)) { return (T)SQLUtils.convert(awaited, value); } else { throw new CommandLineParametersException("Argument ["+getName()+"] can be converted to URI or string type only, conversion to ["+awaited.getCanonicalName()+"] is not supported"); } } catch (ContentException e) { throw new CommandLineParametersException("Error converting argument ["+getName()+"] value ["+value+"] to ["+awaited.getCanonicalName()+"] type"); } } @Override public String[] getDefaultValue() { return defaults; } @Override public boolean isList() { return false; } @Override public void validate(final String value) throws CommandLineParametersException { if (value == null || value.isEmpty()) { throw new CommandLineParametersException("Argument ["+getName()+"]: value can't be null or empty"); } else { try{URI.create(value); } catch (IllegalArgumentException exc) { throw new CommandLineParametersException("Argument ["+getName()+"]: value doesn't have valid URI: "+value+" ("+exc.getLocalizedMessage()+")"); } } } @Override public String toString() { return "URIArg [defaults=" + Arrays.toString(defaults) + ", toString()=" + super.toString() + "]"; } } protected static class FileArg extends AbstractArg { private static final Set<Class<?>> SUPPORTED_CONVERSIONS = new HashSet<>(); static { SUPPORTED_CONVERSIONS.add(File.class); SUPPORTED_CONVERSIONS.add(String.class); } private final String[] defaults; public FileArg(final String name, final boolean isMandatory, final boolean isPositional, final String helpDescriptor) { super(name, isMandatory, isPositional, helpDescriptor); this.defaults = new String[]{""}; } public FileArg(final String name, final boolean isPositional, final String helpDescriptor, final String defaultValue) { super(name, false, isPositional, helpDescriptor); this.defaults = new String[]{defaultValue}; } @Override public <T> T getValue(final String value, final Class<T> awaited) throws CommandLineParametersException { try{if (SUPPORTED_CONVERSIONS.contains(awaited)) { return (T)SQLUtils.convert(awaited, value); } else { throw new CommandLineParametersException("Argument ["+getName()+"] can be converted to URI or string type only, conversion to ["+awaited.getCanonicalName()+"] is not supported"); } } catch (ContentException e) { throw new CommandLineParametersException("Error converting argument ["+getName()+"] value ["+value+"] to ["+awaited.getCanonicalName()+"] type"); } } @Override public String[] getDefaultValue() { return defaults; } @Override public boolean isList() { return false; } @Override public void validate(final String value) throws CommandLineParametersException { if (value == null || value.isEmpty()) { throw new CommandLineParametersException("Argument ["+getName()+"]: value can't be null or empty"); } } @Override public String toString() { return "FileArg [defaults=" + Arrays.toString(defaults) + ", toString()=" + super.toString() + "]"; } } protected static class EnumArg<Type extends Enum<Type>> extends AbstractArg { private final String[] defaults; private final Class<Type> enumType; public EnumArg(final String name, final Class<Type> enumType, final boolean isMandatory, final boolean isPositional, final String helpDescriptor) { super(name, isMandatory, isPositional, helpDescriptor); this.enumType = enumType; this.defaults = new String[]{enumType.getEnumConstants()[0].name()}; } public EnumArg(final String name, final Class<Type> enumType, final boolean isPositional, final String helpDescriptor, final Type defaultValue) { super(name, false, isPositional, helpDescriptor); this.enumType = enumType; this.defaults = new String[]{defaultValue.name()}; } @SuppressWarnings("unchecked") @Override public <T> T getValue(final String value, final Class<T> awaited) throws CommandLineParametersException { if (enumType.isAssignableFrom(awaited)) { return (T)Enum.valueOf((Class<Type>)awaited,value); } else { throw new CommandLineParametersException("Argument ["+getName()+"] can be converted to enumeration ["+enumType.getSimpleName()+"] only, conversion to ["+awaited.getCanonicalName()+"] is not supported"); } } @Override public String[] getDefaultValue() { return defaults; } @Override public boolean isList() { return false; } @Override public void validate(final String value) throws CommandLineParametersException { if (value == null || value.isEmpty()) { throw new CommandLineParametersException("Argument ["+getName()+"]: value can't be null or empty"); } else { try{Enum.valueOf(enumType,value); } catch (IllegalArgumentException e) { throw new CommandLineParametersException("Value ["+value+"] is invalid or missing in ["+enumType.getCanonicalName()+"] enumeration"); } } } @Override public String toString() { return "EnumArg [defaults=" + Arrays.toString(defaults) + ", enumType=" + enumType + ", toString()=" + super.toString() + "]"; } } protected static class StringListArg extends AbstractArg { private final String[] defaults; public StringListArg(final String name, final boolean isMandatory, final boolean isPositional, final String helpDescriptor) { super(name, isMandatory, isPositional, helpDescriptor); this.defaults = new String[0]; } public StringListArg(final String name, final boolean isPositional, final String helpDescriptor, final String... defaultValue) { super(name, false, isPositional, helpDescriptor); this.defaults = defaultValue; } @SuppressWarnings("unchecked") @Override public <T> T getValue(final String value, final Class<T> awaited) throws CommandLineParametersException { if (String.class.isAssignableFrom(awaited)) { return (T)value; } else { throw new CommandLineParametersException("Argument ["+getName()+"] can be converted to string type only, conversion to ["+awaited.getCanonicalName()+"] is not supported"); } } @Override public String[] getDefaultValue() { return defaults; } @Override public boolean isList() { return true; } @Override public void validate(final String value) throws IllegalArgumentException { if (value == null) { throw new IllegalArgumentException("Argument ["+getName()+"]: value can't be null"); } } @Override public String toString() { return "StringListArg [defaults=" + Arrays.toString(defaults) + ", toString()=" + super.toString() + "]"; } } protected static class ConfigArg extends URIArg { private static final Set<Class<?>> SUPPORTED_CONVERSIONS = new HashSet<>(); static { SUPPORTED_CONVERSIONS.add(URI.class); SUPPORTED_CONVERSIONS.add(String.class); } private final String[] defaults; public ConfigArg(final String name, final boolean isMandatory, final boolean isPositional, final String helpDescriptor) { super(name, isMandatory, isPositional, helpDescriptor); this.defaults = new String[0]; } public ConfigArg(final String name, final boolean isPositional, final String helpDescriptor, final String defaultValue) { super(name, false, isPositional, helpDescriptor); this.defaults = new String[]{defaultValue}; } @Override public <T> T getValue(final String value, final Class<T> awaited) throws CommandLineParametersException { try{if (SUPPORTED_CONVERSIONS.contains(awaited)) { return (T)SQLUtils.convert(awaited, value); } else { throw new CommandLineParametersException("Argument ["+getName()+"] can be converted to URI or string type only, conversion to ["+awaited.getCanonicalName()+"] is not supported"); } } catch (ContentException e) { throw new CommandLineParametersException("Error converting argument ["+getName()+"] value ["+value+"] to ["+awaited.getCanonicalName()+"] type"); } } @Override public String[] getDefaultValue() { return defaults; } @Override public boolean isList() { return false; } @Override public void validate(final String value) throws CommandLineParametersException { if (value == null || value.isEmpty()) { throw new CommandLineParametersException("Argument ["+getName()+"]: value can't be null or empty"); } else { try{URI.create(value); } catch (IllegalArgumentException exc) { throw new CommandLineParametersException("Argument ["+getName()+"]: value doesn't have valid URI: "+value+" ("+exc.getLocalizedMessage()+")"); } } } @Override public String toString() { return "ConfigArg [defaults=" + Arrays.toString(defaults) + ", toString()=" + super.toString() + "]"; } } protected static class SwitchArg<T extends Enum<T>> extends EnumArg<T> { private final ArgParser[] parsers; public SwitchArg(final String name, final Class<T> enumType, final boolean isMandatory, final boolean isPositional, final String helpDescriptor, final ArgParser... parsers) { super(name, enumType, isMandatory, isPositional, helpDescriptor); if (parsers == null || parsers.length != enumType.getEnumConstants().length) { throw new IllegalArgumentException("Parser list can't be null and must contain exactly ["+enumType.getEnumConstants().length+"] items"); } else { this.parsers = parsers; } } public SwitchArg(final String name, final Class<T> enumType, final boolean isPositional, final String helpDescriptor, final T defaultValue, final ArgParser... parsers) { super(name, enumType, isPositional, helpDescriptor, defaultValue); if (parsers == null || parsers.length != enumType.getEnumConstants().length) { throw new IllegalArgumentException("Parser list can't be null and must contain exactly ["+enumType.getEnumConstants().length+"] items"); } else { this.parsers = parsers; } } public ArgParser[] getParsers() { return parsers; } } }
package com.github.lstephen.ootp.ai; import com.github.lstephen.ootp.ai.config.Config; import com.github.lstephen.ootp.ai.data.Id; import com.github.lstephen.ootp.ai.draft.DraftReport; import com.github.lstephen.ootp.ai.io.Printables; import com.github.lstephen.ootp.ai.ootp5.report.SpringTraining; import com.github.lstephen.ootp.ai.player.Player; import com.github.lstephen.ootp.ai.player.Slot; import com.github.lstephen.ootp.ai.player.ratings.BattingRatings; import com.github.lstephen.ootp.ai.player.ratings.PitchingRatings; import com.github.lstephen.ootp.ai.player.ratings.PlayerRatings; import com.github.lstephen.ootp.ai.player.ratings.Position; import com.github.lstephen.ootp.ai.regression.BattingRegression; import com.github.lstephen.ootp.ai.regression.PitchingRegression; import com.github.lstephen.ootp.ai.regression.Predictions; import com.github.lstephen.ootp.ai.report.FreeAgents; import com.github.lstephen.ootp.ai.report.GenericValueReport; import com.github.lstephen.ootp.ai.report.LeagueBattingReport; import com.github.lstephen.ootp.ai.report.RosterReport; import com.github.lstephen.ootp.ai.report.SalaryRegression; import com.github.lstephen.ootp.ai.report.SalaryReport; import com.github.lstephen.ootp.ai.report.TeamReport; import com.github.lstephen.ootp.ai.report.Trade; import com.github.lstephen.ootp.ai.roster.Changes; import com.github.lstephen.ootp.ai.roster.Changes.ChangeType; import com.github.lstephen.ootp.ai.roster.FourtyManRoster; import com.github.lstephen.ootp.ai.roster.Roster; import com.github.lstephen.ootp.ai.roster.Roster.Status; import com.github.lstephen.ootp.ai.roster.RosterSelection; import com.github.lstephen.ootp.ai.roster.Team; import com.github.lstephen.ootp.ai.selection.BestStartersSelection; import com.github.lstephen.ootp.ai.selection.Mode; import com.github.lstephen.ootp.ai.selection.Selections; import com.github.lstephen.ootp.ai.selection.bench.Bench; import com.github.lstephen.ootp.ai.selection.depthchart.AllDepthCharts; import com.github.lstephen.ootp.ai.selection.depthchart.DepthChartSelection; import com.github.lstephen.ootp.ai.selection.lineup.AllLineups; import com.github.lstephen.ootp.ai.selection.lineup.LineupSelection; import com.github.lstephen.ootp.ai.selection.rotation.Rotation; import com.github.lstephen.ootp.ai.selection.rotation.RotationSelection; import com.github.lstephen.ootp.ai.site.SingleTeam; import com.github.lstephen.ootp.ai.site.Site; import com.github.lstephen.ootp.ai.site.SiteDefinition; import com.github.lstephen.ootp.ai.site.SiteHolder; import com.github.lstephen.ootp.ai.site.Version; import com.github.lstephen.ootp.ai.site.impl.SiteDefinitionFactory; import com.github.lstephen.ootp.ai.splits.Splits; import com.github.lstephen.ootp.ai.stats.SplitPercentages; import com.github.lstephen.ootp.ai.stats.SplitPercentagesHolder; import com.github.lstephen.ootp.ai.stats.SplitStats; import com.github.lstephen.ootp.ai.value.FreeAgentAcquisition; import com.github.lstephen.ootp.ai.value.PlayerValue; import com.github.lstephen.ootp.ai.value.TradeValue; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Collections; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import com.google.common.base.Charsets; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Ordering; import com.google.common.collect.Sets; import org.joda.time.DateTimeConstants; /** * * @author lstephen */ public class Main { private static final Logger LOG = Logger.getLogger(Main.class.getName()); private static final SiteDefinition TWML = SiteDefinitionFactory.ootp6( "TWML", "http: private static final SiteDefinition CBL = SiteDefinitionFactory.ootp5( "CBL", "http: private static final SiteDefinition HFTC = SiteDefinitionFactory.ootp5( "HFTC", "http: private static final SiteDefinition OLD_BTH_CHC = SiteDefinitionFactory.ootp6("BTH", "http://bthbaseball.allsimbaseball10.com/game/oldbth/lgreports/", Id.<Team>valueOf(20), "National", 30); private static final SiteDefinition OLD_BTH_NYY = SiteDefinitionFactory.ootp6("OLD_BTH_NYY", "http://bthbaseball.allsimbaseball10.com/game/oldbth/lgreports/", Id.<Team>valueOf(3), "American", 30); private static final SiteDefinition BTHUSTLE = SiteDefinitionFactory.ootp6("BTHUSTLE", "http://bthbaseball.allsimbaseball10.com/game/lgreports/", Id.<Team>valueOf(14), "National", 16); private static final SiteDefinition SAVOY = SiteDefinitionFactory.ootp5("SAVOY", "http: private static final SiteDefinition LBB = SiteDefinitionFactory.ootp5("LBB", "http://bbs56.net/LBB/Site/Leaguesite/", Id.<Team>valueOf(3), "AL", 20); private static final SiteDefinition GABL = SiteDefinitionFactory.ootp5("GABL", "http: private static final SiteDefinition TFMS = SiteDefinitionFactory.ootp5("TFMS", "tfms5-2004/", Id.<Team>valueOf(3), "League 2", 16); private static final ImmutableMap<String, SiteDefinition> SITES = ImmutableMap .<String, SiteDefinition>builder() .put("TWML", TWML) .put("CBL", CBL) .put("HFTC", HFTC) .put("OLD_BTH_CHC", OLD_BTH_CHC) .put("OLD_BTH_NYY", OLD_BTH_NYY) .put("BTHUSTLE", BTHUSTLE) .put("LBB", LBB) .put("SAVOY", SAVOY) .put("GABL", GABL) .build(); private static ImmutableSet<SiteDefinition> LOOK_TO_NEXT_SEASON = ImmutableSet.of(); private static ImmutableSet<SiteDefinition> PLAYOFFS = ImmutableSet.of(); private static ImmutableSet<SiteDefinition> INAUGURAL_DRAFT = ImmutableSet.of(); public static void main(String[] args) throws IOException { new Main().run(); } public void run() throws IOException { String site = System.getenv("OOTPAI_SITE"); if (site == null) { throw new IllegalStateException("OOTPAI_SITE is required"); } run(SITES.get(site)); } private void run(SiteDefinition def) throws IOException { Preconditions.checkNotNull(def, "SiteDefinition not found"); File outputDirectory = new File(Config.createDefault().getValue("output.dir").or("c:/ootp")); try ( FileOutputStream out = new FileOutputStream(new File(outputDirectory, def.getName() + ".txt"), false)) { run(def, out); } } private void run(SiteDefinition def, OutputStream out) throws IOException { LOG.log(Level.INFO, "Running for {0}...", def.getName()); String clearCache = System.getenv("OOTPAI_CLEAR_CACHE"); if ("true".equals(clearCache)) { LOG.log(Level.INFO, "Clearing cache..."); def.getSite().clearCache(); } Boolean isLookToNextSeason = Boolean.FALSE; Boolean isPlayoffs = Boolean.FALSE; if (LOOK_TO_NEXT_SEASON.contains(def)) { isLookToNextSeason = Boolean.TRUE; } if (PLAYOFFS.contains(def)) { isPlayoffs = Boolean.TRUE; } final Site site = def.getSite(); SiteHolder.set(site); Printables.print(LeagueBattingReport.create(site)).to(out); LOG.log(Level.INFO, "Extracting current roster and team..."); Roster oldRoster = site.extractRoster(); Team team = site.extractTeam(); LOG.log(Level.INFO, "Running regressions..."); SplitPercentages pcts = SplitPercentages.create(site); SplitPercentagesHolder.set(pcts); final BattingRegression battingRegression = BattingRegression.run(site); Printables.print(battingRegression.correlationReport()).to(out); final PitchingRegression pitchingRegression = PitchingRegression.run(site); Printables.print(pitchingRegression.correlationReport()).to(out); if (isLookToNextSeason) { battingRegression.ignoreStatsInPredictions(); pitchingRegression.ignoreStatsInPredictions(); } pcts.print(out); SplitStats.setPercentages(pcts); PlayerRatings.setPercentages(pcts); BestStartersSelection.setPercentages(pcts); Bench.setPercentages(pcts); LOG.info("Loading manual changes..."); Changes changes = Changes.load(site); team.processManualChanges(changes); LOG.info("Setting up Predictions..."); final Predictions ps = Predictions.predict(team).using(battingRegression, pitchingRegression, site.getPitcherSelectionMethod()); final TradeValue tv = new TradeValue(team, ps, battingRegression, pitchingRegression); boolean isExpandedRosters = site.getDate().getMonthOfYear() == DateTimeConstants.SEPTEMBER; int month = site.getDate().getMonthOfYear(); Mode mode = Mode.REGULAR_SEASON; if (month < DateTimeConstants.APRIL) { mode = Mode.PRESEASON; } else if (isExpandedRosters) { mode = Mode.EXPANDED; } LOG.info("Loading FAS..."); Iterable<FreeAgentAcquisition> faas = Collections.emptyList(); Set<Player> released = Sets.newHashSet(); FreeAgents fas = FreeAgents.create(site, changes, tv.getTradeTargetValue(), tv); if (INAUGURAL_DRAFT.contains(def)) { RosterReport rr = RosterReport.create(site, team); Printables.print(rr).to(out); final GenericValueReport generic = new GenericValueReport(team, ps, battingRegression, pitchingRegression, null); if (battingRegression.isEmpty() && pitchingRegression.isEmpty()) { generic.setCustomValueFunction((Player p) -> { Double base = 0.0; if (p.isPitcher()) { Splits<PitchingRatings<?>> rs = p.getPitchingRatings(); PitchingRatings<?> vL = rs.getVsLeft(); PitchingRatings<?> vR = rs.getVsRight(); base = (vL.getStuff() + vL.getMovement() + vL.getControl() + 2.0 * (vR.getStuff() + vR.getMovement() + vR.getControl())) / 3.0; } else { Splits<BattingRatings<?>> rs = p.getBattingRatings(); BattingRatings<?> vL = rs.getVsLeft(); BattingRatings<?> vR = rs.getVsRight(); base = (vL.getContact() + vL.getPower() + vL.getEye() + 2.0 * (vR.getContact() + vR.getPower() + vR.getEye())) / 3.0; } Integer need = Slot.getPlayerSlots(p) .stream() .filter((s) -> s != Slot.P) .filter((s) -> s != Slot.H || Slot.getPrimarySlot(p) == Slot.H) .map((s) -> rr.getTargetRatio() - rr.getRatio(s)) .max(Integer::compare) .orElse(0); need = Math.max(0, need); int intangibles = 0; if (p.getClutch().isPresent()) { switch (p.getClutch().get()) { case GREAT: intangibles += 1; break; case SUFFERS: intangibles += -1; break; default: // do nothing } } if (p.getConsistency().isPresent()) { switch (p.getConsistency().get()) { case VERY_INCONSISTENT: intangibles -= 1; break; case GOOD: intangibles += 1; break; default: // do nothing } } Double mrFactor = Slot.getPrimarySlot(p) == Slot.MR ? 0.865 : 1.0; return new Double(mrFactor * base - p.getAge() + need - PlayerValue.getAgingFactor(p) + intangibles).intValue(); }); } generic.setTitle("Selected"); generic.setPlayers(team); generic.print(out); generic.setTitle("Free Agents"); generic.setPlayers(site.getFreeAgents()); generic.print(out); return; } LOG.info("Calculating top FA targets..."); Iterable<Player> topFaTargets = fas.getTopTargets(mode); Integer minRosterSize = 90; Integer maxRosterSize = 110; if (site.getName().equals("LBB")) { maxRosterSize = 100; } if (site.getName().equals("PSD")) { maxRosterSize = 165; minRosterSize = 135; } if (oldRoster.size() > maxRosterSize) { for (int i = 0; i < 2; i++) { Optional<Player> release = fas.getPlayerToRelease(team); if (release.isPresent()) { team.remove(release.get()); released.add(release.get()); } } } if (site.getDate().getMonthOfYear() < DateTimeConstants.SEPTEMBER && site.getDate().getMonthOfYear() > DateTimeConstants.MARCH && !battingRegression.isEmpty() && !pitchingRegression.isEmpty()) { LOG.info("Determining FA acquisition..."); if (oldRoster.size() <= maxRosterSize) { Integer n = 2; if (site.getName().equals("CBL") || site.getName().equals("TWML") || site.getName().equals("BTHUSTLE")) { n = 1; } if (site.getName().equals("SAVOY") || site.getName().equals("GABL") || site.getName().equals("BTH") || site.getName().contains("OLD_BTH")) { n = 0; } faas = FreeAgentAcquisition.select(site, changes, team, fas.all(), tv, n); if (oldRoster.size() > minRosterSize) { for (FreeAgentAcquisition faa : faas) { team.remove(faa.getRelease()); } } } } ImmutableSet<Player> futureFas = ImmutableSet.of(); if (isLookToNextSeason) { futureFas = ImmutableSet.copyOf( Iterables.filter(team, site.isFutureFreeAgent())); System.out.print("Removing (FA):"); for (Player p : Player.byShortName().immutableSortedCopy(futureFas)) { System.out.print(p.getShortName() + "/"); } System.out.println(); team.remove(futureFas); } RosterSelection selection = RosterSelection.ootp6(team, battingRegression, pitchingRegression, tv); if (site.getType() == Version.OOTP5) { selection = RosterSelection.ootp5(team, battingRegression, pitchingRegression, tv); } selection.setPrevious(oldRoster); LOG.log(Level.INFO, "Selecting new rosters..."); Mode selectionMode = mode; if (isPlayoffs) { selectionMode = Mode.PLAYOFFS; } Roster newRoster = selection.select(selectionMode, changes); newRoster.setTargetMinimum(minRosterSize); newRoster.setTargetMaximum(maxRosterSize); selection.printBattingSelectionTable(out, newRoster, site.getTeamBatting()); selection.printPitchingSelectionTable(out, newRoster, site.getTeamPitching()); Printables.print(newRoster).to(out); LOG.info("Calculating roster changes..."); Printables.print(newRoster.getChangesFrom(oldRoster)).to(out); for (FreeAgentAcquisition faa : faas) { Player player = faa.getFreeAgent(); out.write( String.format( "%4s -> %-4s %2s %s%n", "FA", "", player.getPosition(), player.getShortName()) .getBytes(Charsets.ISO_8859_1)); } LOG.log(Level.INFO, "Choosing rotation..."); Rotation rotation = RotationSelection .forMode( selectionMode, pitchingRegression.predict(team), site.getPitcherSelectionMethod()) .selectRotation(ImmutableSet.<Player>of(), Selections.onlyPitchers(newRoster.getPlayers(Status.ML))); Printables.print(rotation).to(out); LOG.log(Level.INFO, "Choosing lineups..."); AllLineups lineups = new LineupSelection(battingRegression.predict(newRoster.getAllPlayers())) .select(Selections.onlyHitters(newRoster.getPlayers(Status.ML))); LOG.log(Level.INFO, "Choosing Depth Charts..."); AllDepthCharts depthCharts = DepthChartSelection .create(battingRegression.predict(newRoster.getAllPlayers())) .select(lineups, Selections.onlyHitters(newRoster.getPlayers(Status.ML))); Printables.print(depthCharts).to(out); Printables.print(lineups).to(out); LOG.log(Level.INFO, "Salary Regression..."); SalaryRegression salaryRegression = new SalaryRegression(tv, site); Integer n = Iterables.size(site.getTeamIds()); int count = 1; for (Id<Team> id : site.getTeamIds()) { LOG.log(Level.INFO, "{0}/{1}...", new Object[] { count, n }); salaryRegression.add(site.getSalariedPlayers(id)); count++; } Printables.print(salaryRegression).to(out); final GenericValueReport generic = new GenericValueReport(team, ps, battingRegression, pitchingRegression, salaryRegression); generic.setCustomValueFunction(tv.getTradeTargetValue()); generic.setReverse(false); LOG.log(Level.INFO, "Strategy..."); generic.setTitle("Bunt for Hit"); generic.setPlayers(newRoster .getPlayers(Status.ML) .stream() .filter(p -> p.getBuntForHitRating().normalize().get() >= 80) .collect(Collectors.toSet())); generic.print(out); if (site.getDate().getMonthOfYear() == DateTimeConstants.MARCH) { LOG.log(Level.INFO, "Spring training..."); Printables .print(SpringTraining.create( site.getType(), newRoster.getAllPlayers())) .to(out); } generic.printReplacementLevelReport(out); RosterReport rosterReport = RosterReport.create(site, newRoster); Printables.print(rosterReport).to(out); LOG.info("Draft..."); ImmutableSet<Player> drafted = ImmutableSet.copyOf(changes.get(Changes.ChangeType.PICKED)); Iterable<Player> remaining = Sets.difference( ImmutableSet.copyOf(FluentIterable.from(site.getDraft()).filter(Predicates.notNull())), drafted); if (!Iterables.isEmpty(remaining)) { generic.setTitle("Drafted"); generic.setPlayers(drafted); generic.print(out); generic.setTitle("Remaining"); generic.setPlayers(remaining); generic.print(out); } DraftReport.create(site, tv).print(out); LOG.info("Extensions report..."); generic.setTitle("Extensions"); generic.setPlayers( Iterables.concat( Iterables.filter(newRoster.getAllPlayers(), site.isFutureFreeAgent()), futureFas)); generic.print(out); LOG.info("Arbitration report..."); generic.setTitle("Arbitration"); generic.setPlayers(Iterables.filter(newRoster.getAllPlayers(), new Predicate<Player>() { public boolean apply(Player p) { return p.getSalary().endsWith("a"); } })); generic.print(out); LOG.info("Salary report..."); SalaryReport salary = new SalaryReport(team, site); Printables.print(salary).to(out); if (def.getName().equals("BTHUSTLE")) { LOG.info("40 man roster reports..."); FourtyManRoster fourtyMan = new FourtyManRoster( newRoster, Predictions .predict(newRoster.getAllPlayers()) .using(battingRegression, pitchingRegression, ps.getPitcherOverall()), tv); Printables.print(fourtyMan).to(out); generic.setTitle("+40"); generic.setPlayers(ImmutableSet .<Player>builder() .addAll(fourtyMan.getPlayersToAdd()) .addAll(FluentIterable .from(changes.get(ChangeType.FOURTY_MAN)) .filter(Predicates.in(newRoster.getAllPlayers()))) .build()); generic.print(out); generic.setTitle("-40"); generic.setPlayers(fourtyMan.getPlayersToRemove()); generic.print(out); generic.setTitle("Waive"); generic.setPlayers(isExpandedRosters ? ImmutableSet.of() : fourtyMan.getPlayersToWaive()); generic.print(out); } if (battingRegression.isEmpty() || pitchingRegression.isEmpty()) { return; } if (def.getName().equals("BTHUSTLE")) { LOG.info("Waviers report..."); generic.setTitle("Waivers"); generic.setPlayers(site.getWaiverWire()); generic.print(out); if (site.getDate().getMonthOfYear() < DateTimeConstants.APRIL) { LOG.info("Rule 5..."); generic.setTitle("Rule 5"); generic.setPlayers( Iterables.filter( site.getRuleFiveDraft(), new Predicate<Player>() { public boolean apply(Player p) { return tv.getCurrentValueVsReplacement(p) >= 0; } })); generic.print(out); } } LOG.info("FA report..."); generic.setTitle("Top Targets"); generic.setPlayers(topFaTargets); generic.print(out); generic.setTitle("Free Agents"); generic.setPlayers(site.getFreeAgents()); generic.setLimit(50); generic.print(out); generic.setTitle("Trade Values"); generic.setPlayers( Iterables.concat( newRoster.getAllPlayers(), futureFas, Iterables.transform( faas, FreeAgentAcquisition::getRelease), released)); generic.setLimit(200); generic.setMultiplier(1.1); generic.print(out); Set<Player> all = Sets.newHashSet(); Set<Player> minorLeaguers = Sets.newHashSet(); LOG.log(Level.INFO, "Team reports..."); generic.setLimit(50); generic.setMultiplier(0.91); count = 1; for (Id<Team> id : site.getTeamIds()) { SingleTeam t = site.getSingleTeam(id); LOG.log(Level.INFO, "{0} ({1}/{2})...", new Object[] { t.getName(), count, n }); generic.setTitle(t.getName()); Roster r = t.getRoster(); Iterables.addAll(all, r.getAllPlayers()); Iterables.addAll(minorLeaguers, r.getPlayers(Status.AAA)); Iterables.addAll(minorLeaguers, r.getPlayers(Status.AA)); Iterables.addAll(minorLeaguers, r.getPlayers(Status.A)); Iterables.addAll(minorLeaguers, r.getPlayers(Status.SA)); Iterables.addAll(minorLeaguers, r.getPlayers(Status.R)); generic.setPlayers(r.getAllPlayers()); generic.print(out); count++; } TeamReport now = TeamReport.create( "Now", ps, site, new PlayerValue(ps, battingRegression, pitchingRegression) .getNowValue()); if (!site.getName().contains("OLD_BTH") && !site.getName().equals("BTH")) { LOG.info("Power Rankings..."); Printables.print(site.getPowerRankingsReport(now)).to(out); } LOG.info("Team Now Report..."); now.sortByEndOfSeason(); Printables.print(now).to(out); LOG.info("Team Medium Term Report..."); TeamReport future = TeamReport.create( "Medium Term", ps, site, new PlayerValue(ps, battingRegression, pitchingRegression) .getFutureValue()); future.sortByTalentLevel(); Printables.print(future).to(out); generic.setLimit(10); generic.clearMultiplier(); generic.setCustomValueFunction( new PlayerValue(ps, battingRegression, pitchingRegression) .getFutureValue()); for (final Slot s : Slot.values()) { if (s == Slot.P) { continue; } LOG.log(Level.INFO, "Slot Report: {0}...", s.name()); generic.setTitle("Top: " + s.name()); generic.setPlayers(Iterables.filter(all, new Predicate<Player>() { public boolean apply(Player p) { return Slot.getPrimarySlot(p) == s; } })); generic.print(out); } for (final Position pos : ImmutableList.of(Position.SECOND_BASE, Position.THIRD_BASE)) { LOG.log(Level.INFO, "Position Report: {0}...", pos.name()); generic.setTitle("Top: " + pos.name()); generic.setPlayers(Iterables.filter(all, new Predicate<Player>() { public boolean apply(Player pl) { return pl.getPosition().equals(pos.getAbbreviation()); } })); generic.print(out); } LOG.log(Level.INFO, "League wide replacement Level..."); generic.setCustomValueFunction(tv.getTradeTargetValue()); /*LOG.log(Level.INFO, "Trade target report..."); generic.setTitle("Trade Targets"); generic.setLimit(50); generic.setPlayers(all); generic.print(out);*/ /*LOG.log(Level.INFO, "Minor league report..."); generic.setTitle("Minor Leagues"); generic.setPlayers(minorLeaguers); generic.setLimit(50); generic.print(out);*/ LOG.log(Level.INFO, "Trade Bait report..."); generic.setCustomValueFunction(tv.getTradeBaitValue(site, salaryRegression)); generic.setTitle("Trade Bait"); generic.setPlayers(newRoster.getAllPlayers()); generic.setLimit(200); generic.clearMultiplier(); generic.print(out); generic.setCustomValueFunction(tv.getTradeTargetValue()); Iterable<Player> topBait = Ordering .natural() .reverse() .onResultOf(tv.getTradeBaitValue(site, salaryRegression)) .sortedCopy(newRoster.getAllPlayers()); /*LOG.log(Level.INFO, "Top Trades..."); int idx = 1; for (Trade trade : Iterables.limit( Trade.getTopTrades( tv, site, salaryRegression, Iterables.limit(topBait, newRoster.size() / 10), all), 20)) { generic.setTitle("#" + idx + "-" + trade.getValue(tv, site, salaryRegression)); generic.setPlayers(trade); generic.print(out); idx++; }*/ /*LOG.info("Below Replacement Trades..."); ImmutableSet<Player> belowReplacementBait = ImmutableSet.copyOf( Iterables.filter( Iterables.limit(topBait, newRoster.size() / 10), new Predicate<Player>() { @Override public boolean apply(Player p) { return tv.getCurrentValueVsReplacement(p) < 0 && tv.getFutureValueVsReplacement(p) < 0; } })); idx = 1; for (Trade trade : Iterables.limit( Trade.getTopTrades( tv, site, salaryRegression, belowReplacementBait, all), 20)) { generic.setTitle("BR #" + idx + "-" + trade.getValue(tv, site, salaryRegression)); generic.setPlayers(trade); generic.print(out); idx++; }*/ LOG.log(Level.INFO, "Non Top 10 prospects..."); ImmutableSet<Player> nonTopTens = ImmutableSet.copyOf( Iterables.filter( all, new Predicate<Player>() { public boolean apply(Player p) { return !p.getTeamTopProspectPosition().isPresent() && p.getAge() <= 25 && site.getCurrentSalary(p) == 0; } })); generic.setTitle("Non Top prospects"); generic.setMultiplier(0.91); generic.setLimit(50); generic.setPlayers(nonTopTens); generic.print(out); /*idx = 1; for (Trade trade : Iterables.limit( Trade.getTopTrades( tv, site, salaryRegression, belowReplacementBait, nonTopTens), 20)) { generic.setTitle("NTT #" + idx + "-" + trade.getValue(tv, site, salaryRegression)); generic.setPlayers(trade); generic.print(out); idx++; }*/ LOG.log(Level.INFO, "Minor league non-prospects..."); ImmutableSet<Player> mlNonProspects = ImmutableSet.copyOf( Iterables.filter( minorLeaguers, new Predicate<Player>() { public boolean apply(Player p) { return p.getAge() > 25; } })); generic.setTitle("ML non-prospects"); generic.setPlayers(mlNonProspects); generic.print(out); generic.clearMultiplier(); //LOG.log(Level.INFO, "Top Trades for non-prospect minor leaguers..."); /*idx = 1; for (Trade trade : Iterables.limit( Trade.getTopTrades( tv, site, salaryRegression, belowReplacementBait, mlNonProspects), 20)) { generic.setTitle("NP-ML #" + idx + "-" + trade.getValue(tv, site, salaryRegression)); generic.setPlayers(trade); generic.print(out); idx++; }*/ LOG.log(Level.INFO, "Done."); } }
package com.haogrgr.test.util; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Objects; /** * BigDecimal * * @author desheng.tu * @date 2015612 2:17:23 * */ public final class ArithUtils { /** * return a + b + c */ public static BigDecimal add(BigDecimal a, BigDecimal b, BigDecimal... c) { Objects.requireNonNull(a); Objects.requireNonNull(b); BigDecimal sum = a.add(b); if (c != null && c.length > 0) { for (int i = 0; i < c.length; i++) { Objects.requireNonNull(c[i]); sum = sum.add(c[i]); } } return sum; } /** * return a + b + c */ public static BigDecimal add(BigDecimal a, long b, long... c) { Objects.requireNonNull(a); BigDecimal sum = a.add(BigDecimal.valueOf(b)); if (c != null && c.length > 0) { for (int i = 0; i < c.length; i++) { sum = sum.add(BigDecimal.valueOf(c[i])); } } return sum; } /** * return a + b + c */ public static BigDecimal add(BigDecimal a, double b, double... c) { Objects.requireNonNull(a); BigDecimal sum = a.add(BigDecimal.valueOf(b)); if (c != null && c.length > 0) { for (int i = 0; i < c.length; i++) { sum = sum.add(BigDecimal.valueOf(c[i])); } } return sum; } /** * return a + b + c, , 0 */ public static BigDecimal addna(BigDecimal a, BigDecimal b, BigDecimal... c) { a = a == null ? BigDecimal.ZERO : a; b = b == null ? BigDecimal.ZERO : b; BigDecimal sum = a.add(b); if (c != null && c.length > 0) { for (int i = 0; i < c.length; i++) { if (c[i] != null) sum = sum.add(c[i]); } } return sum; } /** * return a -b -c */ public static BigDecimal sub(BigDecimal a, BigDecimal b, BigDecimal... c) { Objects.requireNonNull(a); Objects.requireNonNull(b); BigDecimal sub = a.subtract(b); if (c != null && c.length > 0) { for (int i = 0; i < c.length; i++) { Objects.requireNonNull(c[i]); sub = sub.subtract(c[i]); } } return sub; } /** * return a -b -c */ public static BigDecimal sub(BigDecimal a, long b, long... c) { Objects.requireNonNull(a); BigDecimal sub = a.subtract(BigDecimal.valueOf(b)); if (c != null && c.length > 0) { for (int i = 0; i < c.length; i++) { sub = sub.subtract(BigDecimal.valueOf(c[i])); } } return sub; } /** * return a -b -c */ public static BigDecimal sub(BigDecimal a, double b, double... c) { Objects.requireNonNull(a); BigDecimal sub = a.subtract(BigDecimal.valueOf(b)); if (c != null && c.length > 0) { for (int i = 0; i < c.length; i++) { sub = sub.subtract(BigDecimal.valueOf(c[i])); } } return sub; } /** * return a -b -c, , 0 */ public static BigDecimal subna(BigDecimal a, BigDecimal b, BigDecimal... c) { a = a == null ? BigDecimal.ZERO : a; b = b == null ? BigDecimal.ZERO : b; BigDecimal sub = a.subtract(b); if (c != null && c.length > 0) { for (int i = 0; i < c.length; i++) { if (c[i] != null) sub = sub.subtract(c[i]); } } return sub; } /** * return a * b * c */ public static BigDecimal mul(BigDecimal a, BigDecimal b, BigDecimal... c) { Objects.requireNonNull(a); Objects.requireNonNull(b); BigDecimal mul = a.multiply(b); if (c != null && c.length > 0) { for (int i = 0; i < c.length; i++) { Objects.requireNonNull(c[i]); mul = mul.multiply(c[i]); } } return mul; } /** * return a * b * c */ public static BigDecimal mul(BigDecimal a, long b, long... c) { Objects.requireNonNull(a); BigDecimal mul = a.multiply(BigDecimal.valueOf(b)); if (c != null && c.length > 0) { for (int i = 0; i < c.length; i++) { mul = mul.multiply(BigDecimal.valueOf(c[i])); } } return mul; } /** * return a * b * c */ public static BigDecimal mul(BigDecimal a, double b, double... c) { Objects.requireNonNull(a); BigDecimal mul = a.multiply(BigDecimal.valueOf(b)); if (c != null && c.length > 0) { for (int i = 0; i < c.length; i++) { mul = mul.multiply(BigDecimal.valueOf(c[i])); } } return mul; } /** * return (a / b) / c */ public static BigDecimal div(BigDecimal a, BigDecimal b, BigDecimal... c) { Objects.requireNonNull(a); Objects.requireNonNull(b); BigDecimal divide = a.divide(b); if (c != null && c.length > 0) { for (int i = 0; i < c.length; i++) { Objects.requireNonNull(c[i]); divide = divide.divide(c[i]); } } return divide; } /** * return (a / b) / c */ public static BigDecimal div(BigDecimal a, long b, long... c) { Objects.requireNonNull(a); BigDecimal divide = a.divide(BigDecimal.valueOf(b)); if (c != null && c.length > 0) { for (int i = 0; i < c.length; i++) { divide = divide.divide(BigDecimal.valueOf(c[i])); } } return divide; } /** * return (a / b) / c */ public static BigDecimal div(BigDecimal a, double b, double... c) { Objects.requireNonNull(a); BigDecimal divide = a.divide(BigDecimal.valueOf(b)); if (c != null && c.length > 0) { for (int i = 0; i < c.length; i++) { divide = divide.divide(BigDecimal.valueOf(c[i])); } } return divide; } /** * return a > b */ public static boolean gt(BigDecimal a, BigDecimal b) { Objects.requireNonNull(a); Objects.requireNonNull(b); return a.compareTo(b) == 1; } /** * return a > b */ public static boolean gt(BigDecimal a, long b) { Objects.requireNonNull(a); return a.compareTo(BigDecimal.valueOf(b)) == 1; } /** * return a > b */ public static boolean gt(BigDecimal a, double b) { Objects.requireNonNull(a); return a.compareTo(BigDecimal.valueOf(b)) == 1; } /** * return a >= b */ public static boolean gtOrEq(BigDecimal a, BigDecimal b) { Objects.requireNonNull(a); Objects.requireNonNull(b); return a.compareTo(b) > -1; } /** * return a >= b */ public static boolean gtOrEq(BigDecimal a, long b) { Objects.requireNonNull(a); return a.compareTo(BigDecimal.valueOf(b)) > -1; } /** * return a >= b */ public static boolean gtOrEq(BigDecimal a, double b) { Objects.requireNonNull(a); return a.compareTo(BigDecimal.valueOf(b)) > -1; } /** * return a < b */ public static boolean lt(BigDecimal a, BigDecimal b) { Objects.requireNonNull(a); Objects.requireNonNull(b); return a.compareTo(b) == -1; } /** * return a < b */ public static boolean lt(BigDecimal a, long b) { Objects.requireNonNull(a); return a.compareTo(BigDecimal.valueOf(b)) == -1; } /** * return a < b */ public static boolean lt(BigDecimal a, double b) { Objects.requireNonNull(a); return a.compareTo(BigDecimal.valueOf(b)) == -1; } /** * return a <= b */ public static boolean ltOrEq(BigDecimal a, BigDecimal b) { Objects.requireNonNull(a); Objects.requireNonNull(b); return a.compareTo(b) < 1; } /** * return a <= b */ public static boolean ltOrEq(BigDecimal a, long b) { Objects.requireNonNull(a); return a.compareTo(BigDecimal.valueOf(b)) < 1; } /** * return a <= b */ public static boolean ltOrEq(BigDecimal a, double b) { Objects.requireNonNull(a); return a.compareTo(BigDecimal.valueOf(b)) < 1; } /** * return a == b */ public static boolean eq(BigDecimal a, BigDecimal b, BigDecimal... c) { Objects.requireNonNull(a); Objects.requireNonNull(b); if (a.compareTo(b) != 0) { return false; } if (c != null && c.length > 0) { for (int i = 0; i < c.length; i++) { Objects.requireNonNull(c[i]); if (a.compareTo(c[i]) != 0) return false; } } return true; } /** * return a == b */ public static boolean eq(BigDecimal a, long b) { Objects.requireNonNull(a); return a.compareTo(BigDecimal.valueOf(b)) == 0; } /** * return a == b */ public static boolean eq(BigDecimal a, double b) { Objects.requireNonNull(a); return a.compareTo(BigDecimal.valueOf(b)) == 0; } public static BigDecimal halfUp(BigDecimal n) { return n.setScale(2, RoundingMode.HALF_UP); } public static BigDecimal halfUp(double n) { return BigDecimal.valueOf(n).setScale(2, RoundingMode.HALF_UP); } public static BigDecimal halfUp(BigDecimal n, int scale) { return n.setScale(scale, RoundingMode.HALF_UP); } public static BigDecimal halfUp(double n, int scale) { return BigDecimal.valueOf(n).setScale(scale, RoundingMode.HALF_UP); } public static BigDecimal max(BigDecimal... eles) { if (eles == null || eles.length == 0) { return null; } BigDecimal max = eles[0]; for (BigDecimal ele : eles) { Objects.requireNonNull(ele); if (gt(ele, max)) max = ele; } return max; } public static BigDecimal min(BigDecimal... eles) { if (eles == null || eles.length == 0) { return null; } BigDecimal min = eles[0]; for (BigDecimal ele : eles) { Objects.requireNonNull(ele); if (lt(ele, min)) min = ele; } return min; } public static BigDecimal transform(Number number) { if (BigDecimal.class.isInstance(number)) { return (BigDecimal) number; } if (Float.class.isInstance(number)) { return BigDecimal.valueOf((Float) number); } if (Double.class.isInstance(number)) { return BigDecimal.valueOf((Double) number); } if (Long.class.isInstance(number)) { return BigDecimal.valueOf((Long) number); } if (Integer.class.isInstance(number)) { return BigDecimal.valueOf((Integer) number); } if (Short.class.isInstance(number)) { return BigDecimal.valueOf((Short) number); } if (Byte.class.isInstance(number)) { return BigDecimal.valueOf((Byte) number); } throw new IllegalArgumentException(" : " + number); } }
package com.ircclouds.irc.api; import java.io.*; import java.math.*; import java.net.*; import java.util.*; import org.apache.log4j.*; import org.slf4j.*; import org.slf4j.Logger; import com.ircclouds.irc.api.commands.*; import com.ircclouds.irc.api.domain.*; import com.ircclouds.irc.api.filters.*; import com.ircclouds.irc.api.listeners.*; import com.ircclouds.irc.api.state.*; import com.ircclouds.irc.api.utils.*; public class IRCApiImpl implements IRCApi { private static final Logger LOG = LoggerFactory.getLogger(IRCApiImpl.class); private IIRCSession session; private AbstractExecuteCommandListener executeCmdListener; private IIRCState state; private int asyncId = 0; private IMessageFilter filter; private ApiMessageFilter apiFilter = new ApiMessageFilter(asyncId); private IMessageFilter abstractAndMsgFilter = new AbstractAndMessageFilter(apiFilter) { @Override protected IMessageFilter getSecondFilter() { return filter; } }; public IRCApiImpl(Boolean aSaveIRCState) { configLog4j(); state = new DisconnectedIRCState(); session = new AbstractIRCSession() { @Override protected IRCServerOptions getIRCServerOptions() { return state.getServerOptions(); } @Override public IMessageFilter getMessageFilter() { if (filter != null) { return abstractAndMsgFilter; } else { return apiFilter; } } }; session.addListeners(ListenerLevel.PRIVATE, executeCmdListener = new ExecuteCommandListenerImpl(session, getStateUpdater(aSaveIRCState)), new PingVersionListenerImpl( session)); } @Override public void connect(final IServerParameters aServerParameters, final Callback<IIRCState> aCallback) { if (state.isConnected()) { throw new ApiException("Already connected!"); } executeCmdListener.submitConnectCallback(newConnectCallback(aCallback), aServerParameters); boolean _isOpen = false; try { if (_isOpen = session.open(aServerParameters.getServer())) { execute(new ConnectCmd(aServerParameters)); } else { aCallback.onFailure("Failed to open connection to [" + aServerParameters.getServer().toString() + "]"); } } catch (IOException aExc) { LOG.error("Error opening session", aExc); throw new ApiException(aExc); } finally { if (!_isOpen) { closeSession(); } } } @Override public void disconnect(String aQuitMessage) { checkConnected(); execute(new QuitCmd(aQuitMessage)); ((IRCStateImpl) (state)).setConnected(false); } @Override public void joinChannel(String aChannelName) { joinChannel(aChannelName, ""); } @Override public void joinChannel(String aChannelName, Callback<IRCChannel> aCallback) { joinChannel(aChannelName, "", aCallback); } @Override public void joinChannel(String aChannelName, String aKey) { checkConnected(); execute(new JoinChanCmd(prependChanType(aChannelName), aKey)); } @Override public void joinChannel(String aChannelName, String aKey, final Callback<IRCChannel> aCallback) { checkConnected(); aChannelName = prependChanType(aChannelName); executeCmdListener.submitJoinChannelCallback(aChannelName, aCallback); execute(new JoinChanCmd(aChannelName, aKey)); } @Override public void leaveChannel(String aChannelName) { leaveChannel(aChannelName, ""); } @Override public void leaveChannel(String aChannelName, Callback<String> aCallback) { leaveChannel(aChannelName, "", aCallback); } @Override public void leaveChannel(String aChannelName, String aPartMessage) { checkConnected(); execute(new PartChanCmd(aChannelName, aPartMessage)); } @Override public void leaveChannel(String aChannelName, String aPartMessage, Callback<String> aCallback) { checkConnected(); executeCmdListener.submitPartChannelCallback(aChannelName, aCallback); execute(new PartChanCmd(aChannelName, aPartMessage)); } @Override public void channelMessage(String aChannelName, String aMessage) { checkConnected(); execute(new SendChannelMessage(aChannelName, aMessage)); } @Override public void channelMessage(String aChannelName, String aMessage, Callback<String> aCallback) { checkConnected(); executeCmdListener.submitSendMessageCallback(asyncId, aCallback); apiFilter.addValue(asyncId); execute(new SendChannelMessage(aChannelName, aMessage, asyncId++)); } @Override public void privateMessage(String aNick, String aText) { checkConnected(); execute(new SendPrivateMessage(aNick, aText)); } @Override public void privateMessage(String aNick, String aText, Callback<String> aCallback) { checkConnected(); executeCmdListener.submitSendMessageCallback(asyncId, aCallback); apiFilter.addValue(asyncId); execute(new SendPrivateMessage(aNick, aText, asyncId++)); } @Override public void actInChannel(String aChannelName, String aActionMessage) { checkConnected(); execute(new SendChannelActionMessage(aChannelName, aActionMessage)); } @Override public void actInChannel(String aChannelName, String aActionMessage, Callback<String> aCallback) { checkConnected(); executeCmdListener.submitSendMessageCallback(asyncId, aCallback); apiFilter.addValue(asyncId); execute(new SendChannelActionMessage(aChannelName, aActionMessage, asyncId++)); } @Override public void actInPrivate(String aNick, String aActionMessage) { checkConnected(); execute(new SendPrivateActionMessage(aNick, aActionMessage)); } @Override public void actInPrivate(String aNick, String aActionMessage, Callback<String> aCallback) { checkConnected(); executeCmdListener.submitSendMessageCallback(asyncId, aCallback); execute(new SendPrivateActionMessage(aNick, aActionMessage, asyncId++)); } @Override public void changeNick(String aNewNick) { checkConnected(); execute(new ChangeNickCmd(aNewNick)); } @Override public void changeNick(String aNewNickname, Callback<String> aCallback) { checkConnected(); executeCmdListener.submitChangeNickCallback(aNewNickname, aCallback); apiFilter.addValue(asyncId); execute(new ChangeNickCmd(aNewNickname)); } @Override public void changeTopic(final String aChannel, final String aSuggestedTopic) { checkConnected(); execute(new ChangeTopicCmd(aChannel, aSuggestedTopic)); } @Override public void changeMode(String aModeString) { checkConnected(); execute(new ChangeModeCmd(aModeString)); } @Override public void sendRawMessage(String aMessage) { execute(new SendRawMessage(aMessage)); } @Override public void addListener(IMessageListener aListener) { session.addListeners(ListenerLevel.PUBLIC, aListener); } @Override public void deleteListener(IMessageListener aListener) { session.removeListener(aListener); } @Override public void setMessageFilter(IMessageFilter aFilter) { filter = aFilter; } @Override public void dccSend(String aNick, File aFile, Integer aListeningPort) { new Thread(new DCCSendListener(aFile, aListeningPort)).start(); privateMessage(aNick, '\001' + "DCC SEND " + aFile.getName() + " " + getLocalAddressRepresentation() + " " + aListeningPort + " " + aFile.length() + '\001'); } private String getLocalAddressRepresentation() { try { InetAddress _localHost = InetAddress.getLocalHost(); byte[] _address = _localHost.getAddress(); if (_address.length == 4) { return new BigInteger(1, _address).toString(); } else { return _localHost.getHostAddress(); } } catch (UnknownHostException aExc) { LOG.error("", aExc); throw new ApiException(aExc); } } @Override public void dccSend(final String aNick, final File aFile) { dccSend(aNick, aFile, NetUtils.getRandDccPort()); } protected ICommandServer getCommandServer() { return session.getCommandServer(); } private String prependChanType(String aChannelName) { for (Character _c : state.getServerOptions().getChanTypes()) { if (_c.equals(aChannelName.charAt(0))) { return aChannelName; } } return state.getServerOptions().getChanTypes().iterator().next() + aChannelName; } private void closeSession() { try { session.close(); } catch (IOException aExc) { LOG.error("Error Closing Session.", aExc); } } private void checkConnected() { if (!state.isConnected()) { throw new ApiException("Not connected!"); } } private Callback<IIRCState> newConnectCallback(final Callback<IIRCState> aCallback) { return new Callback<IIRCState>() { @Override public void onSuccess(IIRCState aConnectedState) { state = aConnectedState; ((IRCStateImpl) (state)).setConnected(true); aCallback.onSuccess(aConnectedState); } @Override public void onFailure(String aErrorMessage) { aCallback.onFailure(aErrorMessage); } }; } private void configLog4j() { PropertyConfigurator.configure(getLog4jProperties()); } private Properties getLog4jProperties() { Properties _p = new Properties(); _p.put("log4j.rootLogger", "DEBUG, A1"); _p.put("log4j.appender.A1.layout", "org.apache.log4j.PatternLayout"); _p.put("log4j.appender.A1", "org.apache.log4j.ConsoleAppender"); _p.put("log4j.appender.A1.layout.ConversionPattern", "%d [%t] %p %c{1} - %m%n"); _p.put("log4j.logger.org.eclipse", "WARN"); return _p; } private void execute(ICommand aCommand) { try { getCommandServer().execute(aCommand); } catch (IOException aExc) { LOG.error("Error executing command", aExc); throw new RuntimeException(aExc); } } private ISaveState getStateUpdater(Boolean aSaveIRCState) { ISaveState _stateUpdater = new AbstractIRCStateUpdater() { @Override public IIRCState getIRCState() { return state; } }; if (aSaveIRCState) { session.addListeners(ListenerLevel.PRIVATE, (AbstractIRCStateUpdater) _stateUpdater); } else { _stateUpdater = new ISaveState() { @Override public void save(IRCChannel aChannel) { // NOP } @Override public IIRCState getIRCState() { return state; } @Override public void delete(String aChannelName) { // NOP } @Override public void updateNick(String aNewNick) { // NOP } }; } return _stateUpdater; } }
package com.jnape.palatable.lambda.io; import com.jnape.palatable.lambda.adt.Either; import com.jnape.palatable.lambda.adt.Try; import com.jnape.palatable.lambda.adt.Unit; import com.jnape.palatable.lambda.adt.choice.Choice2; import com.jnape.palatable.lambda.functions.Fn0; import com.jnape.palatable.lambda.functions.Fn1; import com.jnape.palatable.lambda.functions.builtin.fn2.LazyRec; import com.jnape.palatable.lambda.functions.specialized.SideEffect; import com.jnape.palatable.lambda.functor.Applicative; import com.jnape.palatable.lambda.functor.builtin.Lazy; import com.jnape.palatable.lambda.monad.Monad; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import static com.jnape.palatable.lambda.adt.Try.failure; import static com.jnape.palatable.lambda.adt.Try.trying; import static com.jnape.palatable.lambda.adt.Unit.UNIT; import static com.jnape.palatable.lambda.adt.choice.Choice2.a; import static com.jnape.palatable.lambda.adt.choice.Choice2.b; import static com.jnape.palatable.lambda.functions.Fn0.fn0; import static com.jnape.palatable.lambda.functions.builtin.fn1.Constantly.constantly; import static com.jnape.palatable.lambda.functions.builtin.fn1.Downcast.downcast; import static com.jnape.palatable.lambda.functor.builtin.Lazy.lazy; import static com.jnape.palatable.lambda.monad.Monad.join; import static java.lang.Thread.interrupted; import static java.util.concurrent.CompletableFuture.completedFuture; import static java.util.concurrent.CompletableFuture.supplyAsync; import static java.util.concurrent.ForkJoinPool.commonPool; /** * A {@link Monad} representing some side-effecting computation to be performed. Note that because {@link IO} inherently * offers an interface supporting parallelism, the optimal execution strategy for any given {@link IO} is encoded in * its composition. * * @param <A> the result type */ public abstract class IO<A> implements Monad<A, IO<?>> { private IO() { } /** * Run the effect represented by this {@link IO} instance, blocking the current thread until the effect terminates. * * @return the result of the effect */ public abstract A unsafePerformIO(); /** * Returns a {@link CompletableFuture} representing the result of this eventual effect. By default, this will * immediately run the effect in terms of the implicit {@link Executor} available to {@link CompletableFuture} * (usually the {@link java.util.concurrent.ForkJoinPool}). Note that specific {@link IO} constructions may allow * this method to delegate to externally-managed {@link CompletableFuture} instead of synthesizing their own. * * @return the {@link CompletableFuture} representing this {@link IO}'s eventual result * @see IO#unsafePerformAsyncIO(Executor) */ public final CompletableFuture<A> unsafePerformAsyncIO() { return unsafePerformAsyncIO(commonPool()); } /** * Returns a {@link CompletableFuture} representing the result of this eventual effect. By default, this will * immediately run the effect in terms of the provided {@link Executor}. Note that specific {@link IO} * constructions may allow this method to delegate to externally-managed {@link CompletableFuture} instead of * synthesizing their own. * * @param executor the {@link Executor} to run the {@link CompletableFuture} from * @return the {@link CompletableFuture} representing this {@link IO}'s eventual result * @see IO#unsafePerformAsyncIO() */ public abstract CompletableFuture<A> unsafePerformAsyncIO(Executor executor); /** * Given a function from any {@link Throwable} to the result type <code>A</code>, if this {@link IO} successfully * yields a result, return it; otherwise, map the {@link Throwable} to the result type and return that. * * @param recoveryFn the recovery function * @return the guarded {@link IO} */ public final IO<A> exceptionally(Fn1<? super Throwable, ? extends A> recoveryFn) { return exceptionallyIO(t -> io(recoveryFn.apply(t))); } /** * Like {@link IO#exceptionally(Fn1) exceptionally}, but recover the {@link Throwable} via another {@link IO} * operation. If both {@link IO IOs} throw, the "cleanup" {@link IO IO's} {@link Throwable} is * {@link Throwable#addSuppressed(Throwable) suppressed} by this {@link IO IO's} {@link Throwable}. * * @param recoveryFn the recovery function * @return the guarded {@link IO} */ public final IO<A> exceptionallyIO(Fn1<? super Throwable, ? extends IO<A>> recoveryFn) { return new IO<A>() { @Override public A unsafePerformIO() { return trying(fn0(IO.this::unsafePerformIO)) .recover(t -> { IO<A> recoveryIO = recoveryFn.apply(t); return trying(fn0(recoveryIO::unsafePerformIO)) .fmap(Try::success) .recover(t2 -> { t.addSuppressed(t2); return failure(t); }) .orThrow(); }); } @Override public CompletableFuture<A> unsafePerformAsyncIO(Executor executor) { return IO.this.unsafePerformAsyncIO(executor) .thenApply(CompletableFuture::completedFuture) .exceptionally(t -> recoveryFn.apply(t).unsafePerformAsyncIO(executor) .thenApply(CompletableFuture::completedFuture) .exceptionally(t2 -> { t.addSuppressed(t2); return new CompletableFuture<A>() {{ completeExceptionally(t); }}; }).thenCompose(f -> f)) .thenCompose(f -> f); } }; } /** * Return an {@link IO} that will run <code>ensureIO</code> strictly after running this {@link IO} regardless of * whether this {@link IO} terminates normally, analogous to a finally block. * * @param ensureIO the {@link IO} to ensure runs strictly after this {@link IO} * @return the combined {@link IO} */ public final IO<A> ensuring(IO<?> ensureIO) { return join(fmap(a -> ensureIO.fmap(constantly(a))) .exceptionally(t -> join(ensureIO.<IO<A>>fmap(constantly(io(() -> {throw t;}))) .exceptionally(t2 -> io(() -> { t.addSuppressed(t2); throw t; }))))); } /** * Return a safe {@link IO} that will never throw by lifting the result of this {@link IO} into {@link Either}, * catching any {@link Throwable} and wrapping it in a {@link Either#left(Object) left}. * * @return the safe {@link IO} */ public final IO<Either<Throwable, A>> safe() { return fmap(Either::<Throwable, A>right).exceptionally(Either::left); } /** * {@inheritDoc} */ @Override public final <B> IO<B> pure(B b) { return io(b); } /** * {@inheritDoc} */ @Override public final <B> IO<B> fmap(Fn1<? super A, ? extends B> fn) { return Monad.super.<B>fmap(fn).coerce(); } /** * {@inheritDoc} */ @Override public final <B> IO<B> zip(Applicative<Fn1<? super A, ? extends B>, IO<?>> appFn) { return new Compose<>(this, a((IO<Fn1<? super A, ? extends B>>) appFn)); } /** * {@inheritDoc} */ @Override public final <B> Lazy<IO<B>> lazyZip(Lazy<? extends Applicative<Fn1<? super A, ? extends B>, IO<?>>> lazyAppFn) { return Monad.super.lazyZip(lazyAppFn).<IO<B>>fmap(Monad<B, IO<?>>::coerce).coerce(); } /** * {@inheritDoc} */ @Override public final <B> IO<B> discardL(Applicative<B, IO<?>> appB) { return Monad.super.discardL(appB).coerce(); } /** * {@inheritDoc} */ @Override public final <B> IO<A> discardR(Applicative<B, IO<?>> appB) { return Monad.super.discardR(appB).coerce(); } /** * {@inheritDoc} */ @Override public final <B> IO<B> flatMap(Fn1<? super A, ? extends Monad<B, IO<?>>> f) { @SuppressWarnings({"unchecked", "RedundantCast"}) Choice2<IO<?>, Fn1<Object, IO<?>>> composition = b((Fn1<Object, IO<?>>) (Object) f); return new Compose<>(this, composition); } /** * Produce an {@link IO} that throws the given {@link Throwable} when executed. * * @param t the {@link Throwable} * @param <A> any result type * @return the {@link IO} */ public static <A> IO<A> throwing(Throwable t) { return io(() -> {throw t;}); } /** * Wrap the given {@link IO} in an {@link IO} that first checks if the {@link Thread#currentThread() thread} the * {@link IO} runs on is {@link Thread#interrupted() interrupted}. If it is, an {@link InterruptedException} is * thrown; otherwise the given {@link IO} is executed as usual. Note that for {@link IO}s supporting parallelism, * the thread that is checked for interruption may not necessarily be the same thread that the {@link IO} ultimately * runs on. * * @param io the {@link IO} to wrap * @param <A> the {@link IO} result type * @return an {@link IO} that first checks for {@link Thread#interrupted() thread interrupts} */ public static <A> IO<A> interruptible(IO<A> io) { return join(io(() -> { if (interrupted()) throw new InterruptedException(); return io; })); } public static <A> IO<A> monitorSync(Object lock, IO<A> io) { return io(() -> { synchronized (lock) { return io.unsafePerformIO(); } }); } /** * Fuse all fork opportunities of a given {@link IO} such that, unless it is {@link IO#pin(IO, Executor) pinned} * (or is originally {@link IO#externallyManaged(Fn0) externally managed}), no parallelism will be used when * running it, regardless of what semantics are used when it is executed. * * @param io the {@link IO} * @param <A> the {@link IO} result type * @return the fused {@link IO} * @see IO#pin(IO, Executor) */ public static <A> IO<A> fuse(IO<A> io) { return io(io::unsafePerformIO); } /** * Pin an {@link IO} to an {@link Executor} such that regardless of what future decisions are made, when it runs, it * will run using whatever parallelism is supported by the {@link Executor}'s threading model. Note that if this * {@link IO} has already been pinned (or is originally {@link IO#externallyManaged(Fn0) externally managed}), * pinning to an additional {@link Executor} has no meaningful effect. * * @param io the {@link IO} * @param executor the {@link Executor} * @param <A> the {@link IO} result type * @return the {@link IO} pinned to the {@link Executor} * @see IO#fuse(IO) */ public static <A> IO<A> pin(IO<A> io, Executor executor) { return IO.externallyManaged(() -> io.unsafePerformAsyncIO(executor)); } /** * Static factory method for creating an {@link IO} that just returns <code>a</code> when performed. * * @param a the result * @param <A> the result type * @return the {@link IO} */ public static <A> IO<A> io(A a) { return new IO<A>() { @Override public A unsafePerformIO() { return a; } @Override public CompletableFuture<A> unsafePerformAsyncIO(Executor executor) { return completedFuture(a); } }; } /** * Static factory method for coercing a lambda to an {@link IO}. * * @param fn0 the lambda to coerce * @param <A> the result type * @return the {@link IO} */ public static <A> IO<A> io(Fn0<? extends A> fn0) { return new IO<A>() { @Override public A unsafePerformIO() { return fn0.apply(); } @Override public CompletableFuture<A> unsafePerformAsyncIO(Executor executor) { return supplyAsync(fn0::apply, executor); } }; } /** * Static factory method for creating an {@link IO} that runs a {@link SideEffect} and returns {@link Unit}. * * @param sideEffect the {@link SideEffect} * @return the {@link IO} */ public static IO<Unit> io(SideEffect sideEffect) { return io(fn0(() -> { sideEffect.Ω(); return UNIT; })); } /** * Static factory method for creating an {@link IO} from an externally managed source of * {@link CompletableFuture completable futures}. * <p> * Note that constructing an {@link IO} this way results in no intermediate futures being constructed by either * {@link IO#unsafePerformAsyncIO()} or {@link IO#unsafePerformAsyncIO(Executor)}, and {@link IO#unsafePerformIO()} * is synonymous with invoking {@link CompletableFuture#get()} on the externally managed future. * * @param supplier the source of externally managed {@link CompletableFuture completable futures} * @param <A> the result type * @return the {@link IO} */ public static <A> IO<A> externallyManaged(Fn0<CompletableFuture<A>> supplier) { return new IO<A>() { @Override public A unsafePerformIO() { return fn0(() -> unsafePerformAsyncIO().get()).apply(); } @Override public CompletableFuture<A> unsafePerformAsyncIO(Executor executor) { return supplier.apply(); } }; } private static final class Compose<A> extends IO<A> { private final IO<?> source; private final Choice2<IO<?>, Fn1<Object, IO<?>>> composition; private Compose(IO<?> source, Choice2<IO<?>, Fn1<Object, IO<?>>> composition) { this.source = source; this.composition = composition; } @Override public A unsafePerformIO() { Lazy<Object> lazyA = LazyRec.<IO<?>, Object>lazyRec( (f, io) -> { if (io instanceof IO.Compose<?>) { Compose<?> compose = (Compose<?>) io; Lazy<Object> head = f.apply(compose.source); return compose.composition .match(zip -> head.flatMap(x -> f.apply(zip) .<Fn1<Object, Object>>fmap(downcast()) .fmap(g -> g.apply(x))), flatMap -> head.fmap(flatMap).flatMap(f)); } return lazy(io::unsafePerformIO); }, this); return downcast(lazyA.value()); } @Override @SuppressWarnings("unchecked") public CompletableFuture<A> unsafePerformAsyncIO(Executor executor) { Lazy<CompletableFuture<Object>> lazyFuture = LazyRec.<IO<?>, CompletableFuture<Object>>lazyRec( (f, io) -> { if (io instanceof IO.Compose<?>) { Compose<?> compose = (Compose<?>) io; Lazy<CompletableFuture<Object>> head = f.apply(compose.source); return compose.composition .match(zip -> head.flatMap(futureX -> f.apply(zip) .fmap(futureF -> futureF.thenCombineAsync( futureX, (f2, x) -> ((Fn1<Object, Object>) f2).apply(x), executor))), flatMap -> head.fmap(futureX -> futureX .thenComposeAsync(x -> f.apply(flatMap.apply(x)).value(), executor))); } return lazy(() -> (CompletableFuture<Object>) io.unsafePerformAsyncIO(executor)); }, this); return (CompletableFuture<A>) lazyFuture.value(); } } }
package com.molina.cvmfs.history; import com.molina.cvmfs.common.DatabaseObject; import java.io.File; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Wrapper around CernVM-FS 2.1.x repository history databases * * @author Jose Molina Colmenero */ public class History extends DatabaseObject { private String schema; private String fqrn; public History(File databaseFile) throws IllegalStateException, SQLException { super(databaseFile); readProperties(); } public static History open(String historyPath) throws SQLException { return new History(new File(historyPath)); } public String getSchema() { return schema; } public String getFqrn() { return fqrn; } private void readProperties() throws SQLException { Map<String, Object> properties = readPropertiesTable(); assert (properties.containsKey("schema") && properties.get("schema").equals("1.0")); if (properties.containsKey("fqrn")) fqrn = (String) properties.get("fqrn"); schema = (String) properties.get("schema"); } private RevisionTag getTagByQuery(String query) throws SQLException { Statement statement = createStatement(); ResultSet result = statement.executeQuery(query); if (result != null && result.next()) { RevisionTag rt = new RevisionTag(result); statement.close(); result.close(); return rt; } return null; } public List<RevisionTag> listTags() throws SQLException { Statement statement = createStatement(); ResultSet results = statement.executeQuery(RevisionTag.sqlQueryAll()); List<RevisionTag> tags = new ArrayList<RevisionTag>(); while (results.next()) { tags.add(new RevisionTag(results)); } results.getStatement().close(); results.close(); return tags; } public RevisionTag getTagByName(String name) throws SQLException { return getTagByQuery(RevisionTag.sqlQueryName(name)); } public RevisionTag getTagByRevision(int revision) throws SQLException { return getTagByQuery(RevisionTag.sqlQueryRevision(revision)); } public RevisionTag getTagByDate(long timestamp) throws SQLException { return getTagByQuery(RevisionTag.sqlQueryDate(timestamp)); } }
package com.nelsonjrodrigues.pchud; import java.io.IOException; import com.nelsonjrodrigues.pchud.net.MessageListener; import com.nelsonjrodrigues.pchud.net.NetThread; import com.nelsonjrodrigues.pchud.net.PcMessage; import com.nelsonjrodrigues.pchud.world.Worlds; import lombok.extern.slf4j.Slf4j; @Slf4j public class PcHud { public static void main(String[] args) { Thread.setDefaultUncaughtExceptionHandler((t, e) -> { log.error("Uncaught thread exception, exiting", e); System.exit(-1); }); Worlds worlds = new Worlds(); worlds.addPropertyChangeListener(evt -> { log.debug("{}", worlds); }); try { NetThread netThread = new NetThread(); netThread.addMessageListener(new LogMessageListener()); netThread.addMessageListener(worlds); netThread.start(); netThread.join(); } catch (IOException | InterruptedException e) { log.error(e.getMessage(), e); } log.debug("Exiting"); } @Slf4j private static class LogMessageListener implements MessageListener { @Override public void onMessage(PcMessage message) { log.debug("OnMessage {}", message); } @Override public void onTimeout() { log.debug("OnTimeout"); } } }
package com.pengyifan.bioc.io; import java.io.Closeable; import java.io.IOException; import java.io.Reader; import javax.xml.namespace.QName; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.StartDocument; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import org.apache.commons.lang3.Validate; import org.codehaus.stax2.XMLEventReader2; import org.codehaus.stax2.XMLInputFactory2; import org.codehaus.stax2.evt.DTD2; import com.pengyifan.bioc.BioCAnnotation; import com.pengyifan.bioc.BioCCollection; import com.pengyifan.bioc.BioCDocument; import com.pengyifan.bioc.BioCLocation; import com.pengyifan.bioc.BioCNode; import com.pengyifan.bioc.BioCPassage; import com.pengyifan.bioc.BioCRelation; import com.pengyifan.bioc.BioCSentence; class BioCReader implements Closeable { static enum Level { COLLECTION_LEVEL, DOCUMENT_LEVEL, PASSAGE_LEVEL, SENTENCE_LEVEL } BioCCollection collection; BioCDocument document; BioCPassage passage; BioCSentence sentence; XMLEventReader2 reader; private int state; Level level; protected BioCReader(Reader reader, Level level) throws FactoryConfigurationError, XMLStreamException { XMLInputFactory2 factory = (XMLInputFactory2) XMLInputFactory2 .newInstance(); factory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false); factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); factory.setProperty(XMLInputFactory.IS_COALESCING, false); factory.setProperty(XMLInputFactory.IS_VALIDATING, false); factory.setProperty(XMLInputFactory.SUPPORT_DTD, true); this.reader = (XMLEventReader2) factory.createXMLEventReader(reader); this.level = level; state = 0; } @Override public void close() throws IOException { try { reader.close(); } catch (XMLStreamException e) { throw new IOException(e.getMessage(), e); } } private String getAttribute(StartElement startElement, String key) { return startElement.getAttributeByName(new QName(key)).getValue(); } private String getText() throws XMLStreamException { return reader.nextEvent().asCharacters().getData(); } protected Object read() throws XMLStreamException { String localName = null; while (reader.hasNext()) { XMLEvent event = reader.nextEvent(); switch (state) { case 0: if (event.isStartElement()) { StartElement startElement = event.asStartElement(); localName = startElement.getName().getLocalPart(); if (localName.equals("collection")) { state = 1; } } else if (event.isStartDocument()) { StartDocument startDocument = (StartDocument) event; collection = new BioCCollection(); collection.setEncoding(startDocument.getCharacterEncodingScheme()); collection.setVersion(startDocument.getVersion()); collection.setStandalone(startDocument.isStandalone()); } else if (event.getEventType() == XMLStreamConstants.DTD) { collection.setDtd((DTD2) event); } break; case 1: if (event.isStartElement()) { StartElement startElement = event.asStartElement(); localName = startElement.getName().getLocalPart(); if (localName.equals("source")) { collection.setSource(getText()); } else if (localName.equals("date")) { collection.setDate(getText()); } else if (localName.equals("key")) { collection.setKey(getText()); } else if (localName.equals("infon")) { collection.putInfon( getAttribute(startElement, "key"), getText()); } else if (localName.equals("document")) { // read document document = new BioCDocument(); state = 2; } else { // blank } } else if (event.isEndElement()) { EndElement endElement = event.asEndElement(); localName = endElement.getName().getLocalPart(); if (localName.equals("collection")) { sentence = null; passage = null; document = null; state = 0; } break; } break; case 2: if (event.isStartElement()) { StartElement startElement = event.asStartElement(); localName = startElement.getName().getLocalPart(); if (localName.equals("id")) { document.setID(getText()); } else if (localName.equals("infon")) { document.putInfon( getAttribute(startElement, "key"), getText()); } else if (localName.equals("passage")) { // read passage passage = new BioCPassage(); state = 3; } else if (localName.equals("relation")) { // read relation document.addRelation(readRelation(startElement)); } else { // blank } } else if (event.isEndElement()) { EndElement endElement = event.asEndElement(); localName = endElement.getName().getLocalPart(); if (localName.equals("document")) { state = 1; if (level == Level.DOCUMENT_LEVEL) { return document; } else if (document != null) { collection.addDocument(document); } } break; } break; case 3: if (event.isStartElement()) { StartElement startElement = event.asStartElement(); localName = startElement.getName().getLocalPart(); if (localName.equals("offset")) { passage.setOffset(Integer.parseInt(getText())); } else if (localName.equals("text")) { passage.setText(getText()); } else if (localName.equals("infon")) { passage.putInfon( getAttribute(startElement, "key"), getText()); } else if (localName.equals("annotation")) { passage.addAnnotation(readAnnotation(startElement)); } else if (localName.equals("relation")) { passage.addRelation(readRelation(startElement)); } else if (localName.equals("sentence")) { // read sentence sentence = new BioCSentence(); state = 4; } else { // blank } } else if (event.isEndElement()) { EndElement endElement = event.asEndElement(); localName = endElement.getName().getLocalPart(); if (localName.equals("passage")) { state = 2; if (level == Level.PASSAGE_LEVEL) { return passage; } else if (passage != null) { document.addPassage(passage); } } break; } break; case 4: if (event.isStartElement()) { StartElement startElement = event.asStartElement(); localName = startElement.getName().getLocalPart(); if (localName.equals("offset")) { sentence.setOffset(Integer.parseInt(getText())); } else if (localName.equals("text")) { sentence.setText(getText()); } else if (localName.equals("infon")) { sentence.putInfon( getAttribute(startElement, "key"), getText()); } else if (localName.equals("annotation")) { sentence.addAnnotation(readAnnotation(startElement)); } else if (localName.equals("relation")) { sentence.addRelation(readRelation(startElement)); } else { // blank } } else if (event.isEndElement()) { EndElement endElement = event.asEndElement(); localName = endElement.getName().getLocalPart(); if (localName.equals("sentence")) { state = 3; if (level == Level.SENTENCE_LEVEL) { return sentence; } else if (sentence != null) { passage.addSentence(sentence); } } break; } } } return collection; } private BioCAnnotation readAnnotation(StartElement annotationEvent) throws XMLStreamException { BioCAnnotation ann = new BioCAnnotation(); ann.setID(getAttribute(annotationEvent, "id")); String localName = null; while (reader.hasNext()) { XMLEvent event = reader.nextEvent(); if (event.isStartElement()) { StartElement startElement = event.asStartElement(); localName = startElement.getName().getLocalPart(); if (localName.equals("text")) { ann.setText(getText()); } else if (localName.equals("infon")) { ann.putInfon( startElement.getAttributeByName(new QName("key")).getValue(), getText()); } else if (localName.equals("location")) { ann.addLocation(new BioCLocation( Integer.parseInt(getAttribute(startElement, "offset")), Integer.parseInt(getAttribute(startElement, "length")))); } } else if (event.isEndElement()) { EndElement endElement = event.asEndElement(); localName = endElement.getName().getLocalPart(); if (localName.equals("annotation")) { return ann; } } } Validate.isTrue(false, "should not reach here"); return null; } private BioCRelation readRelation(StartElement relationEvent) throws XMLStreamException { BioCRelation rel = new BioCRelation(); rel.setID(getAttribute(relationEvent, "id")); String localName = null; while (reader.hasNext()) { XMLEvent event = reader.nextEvent(); if (event.isStartElement()) { StartElement startElement = event.asStartElement(); localName = startElement.getName().getLocalPart(); if (localName.equals("infon")) { rel.putInfon( getAttribute(startElement, "key"), getText()); } else if (localName.equals("node")) { BioCNode node = new BioCNode(getAttribute(startElement, "refid"), getAttribute(startElement, "role")); rel.addNode(node); } } else if (event.isEndElement()) { EndElement endElement = event.asEndElement(); localName = endElement.getName().getLocalPart(); if (localName.equals("relation")) { return rel; } } } Validate.isTrue(false, "should not reach here"); return null; } }
package com.perimeterx.http; import com.fasterxml.jackson.core.JsonProcessingException; import com.perimeterx.http.async.PxClientAsyncHandler; import com.perimeterx.models.activities.Activity; import com.perimeterx.models.activities.EnforcerTelemetry; import com.perimeterx.models.configuration.PXConfiguration; import com.perimeterx.models.configuration.PXDynamicConfiguration; import com.perimeterx.models.exceptions.PXException; import com.perimeterx.models.httpmodels.CaptchaRequest; import com.perimeterx.models.httpmodels.CaptchaResponse; import com.perimeterx.models.httpmodels.RiskRequest; import com.perimeterx.models.httpmodels.RiskResponse; import com.perimeterx.utils.Constants; import com.perimeterx.utils.JsonUtils; import com.perimeterx.utils.PXCommonUtils; import org.apache.commons.io.IOUtils; import org.apache.http.HttpHeaders; import org.apache.http.HttpStatus; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.nio.client.methods.HttpAsyncMethods; import org.apache.http.nio.protocol.BasicAsyncResponseConsumer; import org.apache.http.nio.protocol.HttpAsyncRequestProducer; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.charset.Charset; import java.util.List; import java.util.Observable; import java.util.Observer; public class PXHttpClient implements PXClient { private static final Logger logger = LoggerFactory.getLogger(PXHttpClient.class); private static PXHttpClient instance; private static final Charset UTF_8 = Charset.forName("utf-8"); private CloseableHttpClient httpClient; private CloseableHttpAsyncClient asyncHttpClient; private PXConfiguration pxConfiguration; public static PXHttpClient getInstance(PXConfiguration pxConfiguration, CloseableHttpAsyncClient asyncHttpClient, CloseableHttpClient httpClient) { if (instance == null) { synchronized (PXHttpClient.class) { if (instance == null) { instance = new PXHttpClient(pxConfiguration, asyncHttpClient, httpClient); } } } return instance; } private PXHttpClient(PXConfiguration pxConfiguration, CloseableHttpAsyncClient asyncHttpClient, CloseableHttpClient httpClient) { this.pxConfiguration = pxConfiguration; this.httpClient = httpClient; this.asyncHttpClient = asyncHttpClient; } @Override public RiskResponse riskApiCall(RiskRequest riskRequest) throws PXException, IOException { CloseableHttpResponse httpResponse = null; try { String requestBody = JsonUtils.writer.writeValueAsString(riskRequest); logger.info("Risk API Request: {}", requestBody); HttpPost post = new HttpPost(this.pxConfiguration.getServerURL() + Constants.API_RISK); post.setEntity(new StringEntity(requestBody, UTF_8)); post.setConfig(PXCommonUtils.getRequestConfig(pxConfiguration.getConnectionTimeout(),pxConfiguration.getApiTimeout())); httpResponse = httpClient.execute(post); String s = IOUtils.toString(httpResponse.getEntity().getContent(), UTF_8); logger.info("Risk API Response: {}", s); if (httpResponse.getStatusLine().getStatusCode() == 200) { return JsonUtils.riskResponseReader.readValue(s); } return null; } finally { if (httpResponse != null) { httpResponse.close(); } } } @Override public void sendActivity(Activity activity) throws PXException, IOException { CloseableHttpResponse httpResponse = null; try { String requestBody = JsonUtils.writer.writeValueAsString(activity); logger.info("Sending Activity: {}", requestBody); HttpPost post = new HttpPost(this.pxConfiguration.getServerURL() + Constants.API_ACTIVITIES); post.setEntity(new StringEntity(requestBody, UTF_8)); post.setConfig(PXCommonUtils.getRequestConfig(pxConfiguration.getConnectionTimeout(),pxConfiguration.getApiTimeout())); httpResponse = httpClient.execute(post); EntityUtils.consume(httpResponse.getEntity()); } catch (Exception e) { throw new PXException(e); } finally { if (httpResponse != null) { httpResponse.close(); } } } @Override public void sendBatchActivities(List<Activity> activities) throws PXException, IOException { HttpAsyncRequestProducer producer = null; try { asyncHttpClient.start(); String requestBody = JsonUtils.writer.writeValueAsString(activities); logger.info("Sending Activity: {}", requestBody); HttpPost post = new HttpPost(this.pxConfiguration.getServerURL() + Constants.API_ACTIVITIES); post.setEntity(new StringEntity(requestBody, UTF_8)); post.setConfig(PXCommonUtils.getRequestConfig(pxConfiguration.getConnectionTimeout(),pxConfiguration.getApiTimeout())); post.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); post.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + pxConfiguration.getAppId()); producer = HttpAsyncMethods.create(post); asyncHttpClient.execute(producer, new BasicAsyncResponseConsumer(), new PxClientAsyncHandler()); } catch (Exception e) { throw new PXException(e); } finally { if (producer != null) { producer.close(); } } } public CaptchaResponse sendCaptchaRequest(CaptchaRequest captchaRequest) throws PXException, IOException { CloseableHttpResponse httpResponse = null; try { String requestBody = JsonUtils.writer.writeValueAsString(captchaRequest); logger.info("Sending captcha verification: {}", requestBody); HttpPost post = new HttpPost(this.pxConfiguration.getServerURL() + Constants.API_CAPTCHA); post.setEntity(new StringEntity(requestBody, UTF_8)); post.setConfig(PXCommonUtils.getRequestConfig(pxConfiguration.getConnectionTimeout(),pxConfiguration.getApiTimeout())); httpResponse = httpClient.execute(post); String s = IOUtils.toString(httpResponse.getEntity().getContent(), UTF_8); logger.info("Captcha verification response: {}", s); if (httpResponse.getStatusLine().getStatusCode() == 200) { return JsonUtils.captchaResponseReader.readValue(s); } return null; } finally { if (httpResponse != null) { httpResponse.close(); } } } @Override public PXDynamicConfiguration getConfigurationFromServer() { logger.debug("TimerConfigUpdater[getConfiguration]"); String queryParams = ""; if (pxConfiguration.getChecksum() != null) { logger.debug("TimerConfigUpdater[getConfiguration]: adding checksum"); queryParams = "?checksum=" + pxConfiguration.getChecksum(); } PXDynamicConfiguration stub = null; HttpGet get = new HttpGet(pxConfiguration.getRemoteConfigurationUrl() + Constants.API_REMOTE_CONFIGURATION + queryParams); try (CloseableHttpResponse httpResponse = httpClient.execute(get)){ int httpCode = httpResponse.getStatusLine().getStatusCode(); if (httpCode == HttpStatus.SC_OK) { String bodyContent = IOUtils.toString(httpResponse.getEntity().getContent(), UTF_8); stub = JsonUtils.pxConfigurationStubReader.readValue(bodyContent); logger.debug("[getConfiguration] GET request successfully executed {}", bodyContent); } else if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_NO_CONTENT) { logger.debug("[getConfiguration] No updates found"); } else { logger.debug("[getConfiguration] Failed to get remote configuration, status code {}", httpCode); } return stub; } catch (Exception e) { logger.error("[getConfiguration] EXCEPTION {}", e.getMessage()); return null; } } @Override public void sendEnforcerTelemetry(EnforcerTelemetry enforcerTelemetry) throws PXException, IOException{ HttpAsyncRequestProducer producer = null; try { asyncHttpClient.start(); String requestBody = JsonUtils.writer.writeValueAsString(enforcerTelemetry); logger.info("Sending enforcer telemetry: {}", requestBody); HttpPost post = new HttpPost(this.pxConfiguration.getServerURL() + Constants.API_ENFORCER_TELEMETRY); post.setEntity(new StringEntity(requestBody, UTF_8)); PXCommonUtils.getDefaultHeaders(pxConfiguration.getAuthToken()); post.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); post.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + pxConfiguration.getAppId()); post.setConfig(PXCommonUtils.getRequestConfig(pxConfiguration.getConnectionTimeout(),pxConfiguration.getApiTimeout())); producer = HttpAsyncMethods.create(post); asyncHttpClient.execute(producer, new BasicAsyncResponseConsumer(), new PxClientAsyncHandler()); } catch (Exception e) { e.printStackTrace(); } finally { if (producer != null) { producer.close(); } } } }
package com.relayrides.pushy; import java.lang.ref.WeakReference; import java.security.KeyStore; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public class PushManager<T extends ApnsPushNotification> { private final BlockingQueue<T> queue; private final ApnsEnvironment environment; private final KeyStore keyStore; private final char[] keyStorePassword; private final ApnsClientThread<T> clientThread; private final ArrayList<WeakReference<FailedDeliveryListener<T>>> failedDeliveryListeners; public PushManager(final ApnsEnvironment environment, final KeyStore keyStore, final char[] keyStorePassword) { this.queue = new LinkedBlockingQueue<T>(); this.failedDeliveryListeners = new ArrayList<WeakReference<FailedDeliveryListener<T>>>(); this.environment = environment; this.keyStore = keyStore; this.keyStorePassword = keyStorePassword; this.clientThread = new ApnsClientThread<T>(this); } public ApnsEnvironment getEnvironment() { return this.environment; } public KeyStore getKeyStore() { return this.keyStore; } public char[] getKeyStorePassword() { return this.keyStorePassword; } public synchronized void start() { this.clientThread.start(); } public void enqueuePushNotification(final T notification) { this.queue.add(notification); } public void enqueueAllNotifications(final Collection<T> notifications) { this.queue.addAll(notifications); } public synchronized List<T> shutdown() throws InterruptedException { this.clientThread.shutdown(); this.clientThread.join(); return new ArrayList<T>(this.queue); } public void registerFailedDeliveryListener(final FailedDeliveryListener<T> listener) { this.failedDeliveryListeners.add(new WeakReference<FailedDeliveryListener<T>>(listener)); } protected void notifyListenersOfFailedDelivery(final T notification, final Throwable cause) { for (final WeakReference<FailedDeliveryListener<T>> listenerReference : this.failedDeliveryListeners) { final FailedDeliveryListener<T> listener = listenerReference.get(); if (listener != null) { listener.handleFailedDelivery(notification, cause); } } } protected BlockingQueue<T> getQueue() { return this.queue; } }
package crazypants.enderio.config; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Locale; import com.enderio.core.common.event.ConfigFileChangedEvent; import com.enderio.core.common.vecmath.VecmathUtil; import crazypants.enderio.EnderIO; import crazypants.enderio.Log; import crazypants.enderio.capacitor.CapacitorKey; import crazypants.enderio.network.PacketHandler; import net.minecraft.enchantment.Enchantment.Rarity; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.client.event.ConfigChangedEvent.OnConfigChangedEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent; import net.minecraftforge.fml.relauncher.Side; public final class Config { public static class Section { public final String name; public final String lang; public Section(String name, String lang) { this.name = name; this.lang = lang; register(); } private void register() { sections.add(this); } public String lc() { return name.toLowerCase(Locale.US); } } public static final List<Section> sections; static { sections = new ArrayList<Section>(); } public static Configuration config; public static final Section sectionPower = new Section("Power Settings", "power"); public static final Section sectionRecipe = new Section("Recipe Settings", "recipe"); public static final Section sectionItems = new Section("Item Enabling", "item"); public static final Section sectionEfficiency = new Section("Efficiency Settings", "efficiency"); public static final Section sectionPersonal = new Section("Personal Settings", "personal"); public static final Section sectionAnchor = new Section("Anchor Settings", "anchor"); public static final Section sectionStaff = new Section("Staff Settings", "staff"); public static final Section sectionDarkSteel = new Section("Dark Steel", "darksteel"); public static final Section sectionFarm = new Section("Farm Settings", "farm"); public static final Section sectionAesthetic = new Section("Aesthetic Settings", "aesthetic"); public static final Section sectionAdvanced = new Section("Advanced Settings", "advanced"); public static final Section sectionMagnet = new Section("Magnet Settings", "magnet"); public static final Section sectionFluid = new Section("Fluid Settings", "fluid"); public static final Section sectionSpawner = new Section("PoweredSpawner Settings", "spawner"); public static final Section sectionKiller = new Section("Killer Joe Settings", "killerjoe"); public static final Section sectionSoulBinder = new Section("Soul Binder Settings", "soulBinder"); public static final Section sectionAttractor = new Section("Mob Attractor Settings", "attractor"); public static final Section sectionLootConfig = new Section("Loot Config", "lootconfig"); public static final Section sectionMobConfig = new Section("Mob Config", "mobconfig"); public static final Section sectionRailConfig = new Section("Rail", "railconfig"); public static final Section sectionEnchantments = new Section("Enchantments", "enchantments"); public static final Section sectionWeather = new Section("Weather", "weather"); public static final Section sectionTelepad = new Section("Telepad", "telepad"); public static final Section sectionInventoryPanel = new Section("InventoryPanel", "inventorypanel"); public static final Section sectionMisc = new Section("Misc", "misc"); public static final Section sectionCapacitor = new Section("Capacitor Values", "capacitor"); public static final double DEFAULT_CONDUIT_SCALE = 0.6; public static final float EXPLOSION_RESISTANT = 2000f * 3.0f / 5.0f; // obsidian public static boolean registerRecipes = true; public static boolean jeiUseShortenedPainterRecipes = true; public static boolean reinforcedObsidianEnabled = true; public static boolean useAlternateTesseractModel = false; public static boolean photovoltaicCellEnabled = true; public static boolean reservoirEnabled = true; public static double conduitScale = DEFAULT_CONDUIT_SCALE; public static boolean transceiverEnabled = true; public static double transceiverEnergyLoss = 0.1; public static int transceiverBucketTransmissionCostRF = 100; public static File configDirectory; public static int recipeLevel = 2; public static boolean addPeacefulRecipes = false; public static boolean allowExternalTickSpeedup = true; public static boolean createSyntheticRecipes = true; public static boolean detailedPowerTrackingEnabled = false; public static boolean useSneakMouseWheelYetaWrench = true; public static boolean useSneakRightClickYetaWrench = false; public static int yetaWrenchOverlayMode = 0; public static boolean itemConduitUsePhyscialDistance = false; public static int enderFluidConduitExtractRate = 200; public static int enderFluidConduitMaxIoRate = 800; public static int advancedFluidConduitExtractRate = 100; public static int advancedFluidConduitMaxIoRate = 400; public static int fluidConduitExtractRate = 50; public static int fluidConduitMaxIoRate = 200; public static int gasConduitExtractRate = 200; public static int gasConduitMaxIoRate = 800; public static boolean updateLightingWhenHidingFacades = false; public static boolean travelAnchorEnabled = true; public static int travelAnchorMaxDistance = 48; public static int travelAnchorCooldown = 0; public static boolean travelAnchorSneak = true; public static boolean travelAnchorSkipWarning = true; public static int travelStaffMaxDistance = 128; public static float travelStaffPowerPerBlockRF = 250; public static int travelStaffMaxBlinkDistance = 16; public static int travelStaffBlinkPauseTicks = 10; public static boolean travelStaffEnabled = true; public static boolean travelStaffBlinkEnabled = true; public static boolean travelStaffBlinkThroughSolidBlocksEnabled = true; public static boolean travelStaffBlinkThroughClearBlocksEnabled = true; public static boolean travelStaffBlinkThroughUnbreakableBlocksEnabled = false; public static String[] travelStaffBlinkBlackList = new String[] { "minecraft:bedrock", "Thaumcraft:blockWarded" }; public static boolean travelStaffOffhandBlinkEnabled = true; public static boolean travelStaffOffhandTravelEnabled = true; public static boolean travelStaffOffhandEnderIOEnabled = true; public static boolean travelStaffOffhandShowsTravelTargets = true; public static float travelAnchorZoomScale = 0.2f; public static int enderIoRange = 8; public static boolean enderIoMeAccessEnabled = true; public static boolean darkSteelRightClickPlaceEnabled = true; public static double[] darkSteelPowerDamgeAbsorptionRatios = {0.5, 0.6, 0.75, 0.95}; public static int darkSteelPowerStorageBase = 100000; public static int darkSteelPowerStorageLevelOne = 150000; public static int darkSteelPowerStorageLevelTwo = 250000; public static int darkSteelPowerStorageLevelThree = 1000000; public static float darkSteelSpeedOneWalkModifier = 0.1f; public static float darkSteelSpeedTwoWalkMultiplier = 0.2f; public static float darkSteelSpeedThreeWalkMultiplier = 0.3f; public static float darkSteelSpeedOneSprintModifier = 0.1f; public static float darkSteelSpeedTwoSprintMultiplier = 0.3f; public static float darkSteelSpeedThreeSprintMultiplier = 0.5f; public static int darkSteelSpeedOneCost = 10; public static int darkSteelSpeedTwoCost = 15; public static int darkSteelSpeedThreeCost = 20; public static double darkSteelBootsJumpModifier = 1.5; public static int darkSteelJumpOneCost = 10; public static int darkSteelJumpTwoCost = 15; public static int darkSteelJumpThreeCost = 20; public static boolean slotZeroPlacesEight = true; public static int darkSteelWalkPowerCost = darkSteelPowerStorageLevelTwo / 3000; public static int darkSteelSprintPowerCost = darkSteelWalkPowerCost * 4; public static boolean darkSteelDrainPowerFromInventory = false; public static int darkSteelBootsJumpPowerCost = 150; public static int darkSteelFallDistanceCost = 75; public static float darkSteelSwordPoweredDamageBonus = 1.0f; public static float darkSteelSwordPoweredSpeedBonus = 0.4f; public static float darkSteelSwordWitherSkullChance = 0.05f; public static float darkSteelSwordWitherSkullLootingModifier = 0.05f; public static float darkSteelSwordSkullChance = 0.1f; public static float darkSteelSwordSkullLootingModifier = 0.075f; public static float vanillaSwordSkullLootingModifier = 0.05f; public static float vanillaSwordSkullChance = 0.05f; public static float ticCleaverSkullDropChance = 0.1f; public static float ticBeheadingSkullModifier = 0.075f; public static float fakePlayerSkullChance = 0.5f; public static int darkSteelSwordPowerUsePerHit = 750; public static double darkSteelSwordEnderPearlDropChance = 1; public static double darkSteelSwordEnderPearlDropChancePerLooting = 0.5; public static int darkSteelPickEffeciencyObsidian = 50; public static int darkSteelPickPowerUseObsidian = 10000; public static float darkSteelPickApplyObsidianEffeciencyAtHardess = 40; public static int darkSteelPickPowerUsePerDamagePoint = 750; public static float darkSteelPickEffeciencyBoostWhenPowered = 2; public static boolean darkSteelPickMinesTiCArdite = true; public static int darkSteelAxePowerUsePerDamagePoint = 750; public static int darkSteelAxePowerUsePerDamagePointMultiHarvest = 1500; public static float darkSteelAxeEffeciencyBoostWhenPowered = 2; public static float darkSteelAxeSpeedPenaltyMultiHarvest = 4; public static int darkSteelShearsDurabilityFactor = 5; public static int darkSteelShearsPowerUsePerDamagePoint = 250; public static float darkSteelShearsEffeciencyBoostWhenPowered = 2.0f; public static int darkSteelShearsBlockAreaBoostWhenPowered = 2; public static float darkSteelShearsEntityAreaBoostWhenPowered = 3.0f; public static int darkSteelUpgradeVibrantCost = 10; public static int darkSteelUpgradePowerOneCost = 10; public static int darkSteelUpgradePowerTwoCost = 15; public static int darkSteelUpgradePowerThreeCost = 20; public static int darkSteelGliderCost = 10; public static double darkSteelGliderHorizontalSpeed = 0.03; public static double darkSteelGliderVerticalSpeed = -0.05; public static double darkSteelGliderVerticalSpeedSprinting = -0.15; public static int darkSteelGogglesOfRevealingCost = 10; public static int darkSteelApiaristArmorCost = 10; public static int darkSteelSwimCost = 10; public static int darkSteelNightVisionCost = 10; public static int darkSteelSoundLocatorCost = 10; public static int darkSteelSoundLocatorRange = 40; public static int darkSteelSoundLocatorLifespan = 40; public static int darkSteelTravelCost = 30; public static int darkSteelSpoonCost = 10; public static int darkSteelSolarOneGen = 10; public static int darkSteelSolarOneCost = 10; public static int darkSteelSolarTwoGen = 40; public static int darkSteelSolarTwoCost = 20; public static int darkSteelSolarThreeGen = 80; public static int darkSteelSolarThreeCost = 40; public static boolean darkSteelSolarChargeOthers = true; public static float darkSteelAnvilDamageChance = 0.024f; public static float darkSteelLadderSpeedBoost = 0.06f; public static int hootchPowerPerCycleRF = 60; public static int hootchPowerTotalBurnTime = 6000; public static int rocketFuelPowerPerCycleRF = 160; public static int rocketFuelPowerTotalBurnTime = 7000; public static int fireWaterPowerPerCycleRF = 80; public static int fireWaterPowerTotalBurnTime = 15000; public static int vatPowerUserPerTickRF = 20; public static int maxPhotovoltaicOutputRF = 10; public static int maxPhotovoltaicAdvancedOutputRF = 40; public static int maxPhotovoltaicVibrantOutputRF = 160; public static int zombieGeneratorRfPerTick = 80; public static int zombieGeneratorTicksPerBucketFuel = 10000; public static boolean addFuelTooltipsToAllFluidContainers = true; public static boolean addFurnaceFuelTootip = true; public static boolean addDurabilityTootip = true; public static int farmActionEnergyUseRF = 500; public static int farmAxeActionEnergyUseRF = 1000; public static int farmBonemealActionEnergyUseRF = 160; public static int farmBonemealTryEnergyUseRF = 80; public static boolean farmAxeDamageOnLeafBreak = false; public static float farmToolTakeDamageChance = 1; public static boolean disableFarmNotification = false; public static boolean farmEssenceBerriesEnabled = true; public static boolean farmManaBeansEnabled = false; public static boolean farmHarvestJungleWhenCocoa = false; public static String[] hoeStrings = new String[] { "minecraft:wooden_hoe", "minecraft:stone_hoe", "minecraft:iron_hoe", "minecraft:diamond_hoe", "minecraft:golden_hoe", "MekanismTools:ObsidianHoe", "MekanismTools:LapisLazuliHoe", "MekanismTools:OsmiumHoe", "MekanismTools:BronzeHoe", "MekanismTools:GlowstoneHoe", "MekanismTools:SteelHoe", "Steamcraft:hoeBrass", "Steamcraft:hoeGildedGold", "Railcraft:tool.steel.hoe", "TConstruct:mattock", "appliedenergistics2:item.ToolCertusQuartzHoe", "appliedenergistics2:item.ToolNetherQuartzHoe", "ProjRed|Exploration:projectred.exploration.hoeruby", "ProjRed|Exploration:projectred.exploration.hoesapphire", "ProjRed|Exploration:projectred.exploration.hoeperidot", "magicalcrops:magicalcrops_AccioHoe", "magicalcrops:magicalcrops_CrucioHoe", "magicalcrops:magicalcrops_ImperioHoe", // disabled as it is currently not unbreaking as advertised "magicalcrops:magicalcrops_ZivicioHoe", "magicalcrops:magicalcropsarmor_AccioHoe", "magicalcrops:magicalcropsarmor_CrucioHoe", "magicalcrops:magicalcropsarmor_ImperioHoe", "BiomesOPlenty:hoeAmethyst", "BiomesOPlenty:hoeMud", "Eln:Eln.Copper Hoe", "Thaumcraft:ItemHoeThaumium", "Thaumcraft:ItemHoeElemental", "Thaumcraft:ItemHoeVoid", "ThermalFoundation:tool.hoeInvar", "ThermalFoundation:tool.hoeCopper", "ThermalFoundation:tool.hoeBronze", "ThermalFoundation:tool.hoeSilver", "ThermalFoundation:tool.hoeElectrum", "ThermalFoundation:tool.hoeTin", "ThermalFoundation:tool.hoeLead", "ThermalFoundation:tool.hoeNickel", "ThermalFoundation:tool.hoePlatinum", "TwilightForest:item.steeleafHoe", "TwilightForest:item.ironwoodHoe", "IC2:itemToolBronzeHoe" }; public static List<ItemStack> farmHoes = new ArrayList<ItemStack>(); public static int farmSaplingReserveAmount = 8; public static int magnetPowerUsePerSecondRF = 1; public static int magnetPowerCapacityRF = 100000; public static int magnetRange = 5; public static String[] magnetBlacklist = new String[] { "appliedenergistics2:item.ItemCrystalSeed", "Botania:livingrock", "Botania:manaTablet" }; public static int magnetMaxItems = 20; public static boolean magnetAllowInMainInventory = false; public static boolean magnetAllowInBaublesSlot = true; public static boolean magnetAllowDeactivatedInBaublesSlot = false; public static boolean magnetAllowPowerExtraction = false; public static String magnetBaublesType = "AMULET"; public static int crafterRfPerCraft = 2500; public static int capacitorBankMaxIoRF = 5000; public static int capacitorBankMaxStorageRF = 5000000; public static int capacitorBankTierOneMaxIoRF = 1000; public static int capacitorBankTierOneMaxStorageRF = 1000000; public static int capacitorBankTierTwoMaxIoRF = 5000; public static int capacitorBankTierTwoMaxStorageRF = 5000000; public static int capacitorBankTierThreeMaxIoRF = 25000; public static int capacitorBankTierThreeMaxStorageRF = 25000000; public static boolean capacitorBankRenderPowerOverlayOnItem = false; public static int poweredSpawnerMinDelayTicks = 200; public static int poweredSpawnerMaxDelayTicks = 800; public static int poweredSpawnerMaxPlayerDistance = 0; public static int poweredSpawnerDespawnTimeSeconds = 120; public static int poweredSpawnerSpawnCount = 4; public static int poweredSpawnerSpawnRange = 4; public static int poweredSpawnerMaxNearbyEntities = 6; public static int poweredSpawnerMaxSpawnTries = 3; public static boolean poweredSpawnerUseVanillaSpawChecks = false; public static double brokenSpawnerDropChance = 1; public static String[] brokenSpawnerToolBlacklist = new String[] { "RotaryCraft:rotarycraft_item_bedpick" }; public static int powerSpawnerAddSpawnerCost = 30; public static int painterEnergyPerTaskRF = 2000; public static int vacuumChestRange = 6; public static int wirelessChargerRange = 24; public static long nutrientFoodBoostDelay = 400; public static int enchanterBaseLevelCost = 4; public static boolean machineSoundsEnabled = true; public static float machineSoundVolume = 1.0f; public static int killerJoeNutrientUsePerAttackMb = 5; public static double killerJoeAttackHeight = 2; public static double killerJoeAttackWidth = 2; public static double killerJoeAttackLength = 4; public static double killerJoeHooverXpWidth = 5; public static double killerJoeHooverXpLength = 10; public static int killerJoeMaxXpLevel = Integer.MAX_VALUE; public static boolean killerJoeMustSee = false; public static boolean killerPvPoffDisablesSwing = false; public static boolean killerPvPoffIsIgnored = false; public static boolean allowTileEntitiesAsPaintSource = true; public static boolean isGasConduitEnabled = true; public static boolean enableMEConduits = true; public static boolean enableOCConduits = true; public static boolean enableOCConduitsAnimatedTexture = true; public static List<String> soulVesselBlackList = Collections.<String> emptyList(); public static boolean soulVesselCapturesBosses = false; public static int soulBinderBrokenSpawnerRF = 2500000; public static int soulBinderBrokenSpawnerLevels = 15; public static int soulBinderReanimationRF = 100000; public static int soulBinderReanimationLevels = 10; public static int soulBinderEnderCystalRF = 100000; public static int soulBinderEnderCystalLevels = 10; public static int soulBinderAttractorCystalRF = 100000; public static int soulBinderAttractorCystalLevels = 10; public static int soulBinderEnderRailRF = 100000; public static int soulBinderEnderRailLevels = 10; public static int soulBinderTunedPressurePlateLevels = 3; public static int soulBinderTunedPressurePlateRF = 250000; public static int soulBinderMaxXpLevel = 40; public static boolean powerConduitCanDifferentTiersConnect = false; public static int powerConduitTierOneRF = 640; public static int powerConduitTierTwoRF = 5120; public static int powerConduitTierThreeRF = 20480; public static boolean powerConduitOutputMJ = true; public static boolean spawnGuardStopAllSlimesDebug = false; public static boolean spawnGuardStopAllSquidSpawning = false; public static int weatherObeliskClearFluid = 2000; public static int weatherObeliskRainFluid = 500; public static int weatherObeliskThunderFluid = 1000; //Loot Defaults public static boolean lootDarkSteel = true; public static boolean lootItemConduitProbe = true; public static boolean lootQuartz = true; public static boolean lootNetherWart = true; public static boolean lootEnderPearl = true; public static boolean lootElectricSteel = true; public static boolean lootRedstoneAlloy = true; public static boolean lootPhasedIron = true; public static boolean lootPhasedGold = true; public static boolean lootTravelStaff = true; public static boolean lootTheEnder = true; public static boolean lootDarkSteelBoots = true; public static boolean dumpMobNames = false; public static boolean enderRailEnabled = true; public static int enderRailPowerRequireCrossDimensions = 10000; public static int enderRailPowerRequiredPerBlock = 10; public static boolean enderRailCapSameDimensionPowerAtCrossDimensionCost = true; public static int enderRailTicksBeforeForceSpawningLinkedCarts = 60; public static boolean enderRailTeleportPlayers = false; public static int xpObeliskMaxXpLevel = Integer.MAX_VALUE; public static String xpJuiceName = "xpjuice"; public static boolean clearGlassConnectToFusedQuartz = false; public static boolean glassConnectToTheirVariants = true; public static Rarity enchantmentSoulBoundWeight = Rarity.UNCOMMON; public static boolean enchantmentSoulBoundEnabled = true; public static boolean telepadLockDimension = true; public static boolean telepadLockCoords = true; public static int telepadPowerCoefficient = 100000; public static int telepadPowerInterdimensional = 100000; public static boolean inventoryPanelFree = false; public static float inventoryPanelPowerPerMB = 800.0f; public static float inventoryPanelScanCostPerSlot = 0.1f; public static float inventoryPanelExtractCostPerItem = 12.0f; public static float inventoryPanelExtractCostPerOperation = 32.0f; public static boolean photovoltaicCanTypesJoins = true; public static int photovoltaicRecalcSunTick = 100; public static boolean debugUpdatePackets = false; public static void load(FMLPreInitializationEvent event) { PacketHandler.INSTANCE.registerMessage(PacketConfigSync.class, PacketConfigSync.class, PacketHandler.nextID(), Side.CLIENT); MinecraftForge.EVENT_BUS.register(new Config()); configDirectory = new File(event.getModConfigurationDirectory(), EnderIO.DOMAIN); if(!configDirectory.exists()) { configDirectory.mkdir(); } File configFile = new File(configDirectory, "EnderIO.cfg"); config = new Configuration(configFile); syncConfig(false); } public static void syncConfig(boolean load) { try { if (load) { config.load(); } Config.processConfig(config); } catch (Exception e) { Log.error("EnderIO has a problem loading it's configuration"); e.printStackTrace(); } finally { if(config.hasChanged()) { config.save(); } } } @SubscribeEvent public void onConfigChanged(OnConfigChangedEvent event) { if (event.getModID().equals(EnderIO.MODID)) { Log.info("Updating config..."); syncConfig(false); init(); postInit(); } } @SubscribeEvent public void onConfigFileChanged(ConfigFileChangedEvent event) { if (event.getModID().equals(EnderIO.MODID)) { Log.info("Updating config..."); syncConfig(true); event.setSuccessful(); init(); postInit(); } } @SubscribeEvent public void onPlayerLoggon(PlayerLoggedInEvent evt) { PacketHandler.INSTANCE.sendTo(new PacketConfigSync(), (EntityPlayerMP) evt.player); } public static void processConfig(Configuration config) { capacitorBankMaxIoRF = config.get(sectionPower.name, "capacitorBankMaxIoRF", capacitorBankMaxIoRF, "The maximum IO for a single capacitor in RF/t") .getInt(capacitorBankMaxIoRF); capacitorBankMaxStorageRF = config.get(sectionPower.name, "capacitorBankMaxStorageRF", capacitorBankMaxStorageRF, "The maximum storage for a single capacitor in RF") .getInt(capacitorBankMaxStorageRF); capacitorBankTierOneMaxIoRF = config.get(sectionPower.name, "capacitorBankTierOneMaxIoRF", capacitorBankTierOneMaxIoRF, "The maximum IO for a single tier one capacitor in RF/t") .getInt(capacitorBankTierOneMaxIoRF); capacitorBankTierOneMaxStorageRF = config.get(sectionPower.name, "capacitorBankTierOneMaxStorageRF", capacitorBankTierOneMaxStorageRF, "The maximum storage for a single tier one capacitor in RF") .getInt(capacitorBankTierOneMaxStorageRF); capacitorBankTierTwoMaxIoRF = config.get(sectionPower.name, "capacitorBankTierTwoMaxIoRF", capacitorBankTierTwoMaxIoRF, "The maximum IO for a single tier two capacitor in RF/t") .getInt(capacitorBankTierTwoMaxIoRF); capacitorBankTierTwoMaxStorageRF = config.get(sectionPower.name, "capacitorBankTierTwoMaxStorageRF", capacitorBankTierTwoMaxStorageRF, "The maximum storage for a single tier two capacitor in RF") .getInt(capacitorBankTierTwoMaxStorageRF); capacitorBankTierThreeMaxIoRF = config.get(sectionPower.name, "capacitorBankTierThreeMaxIoRF", capacitorBankTierThreeMaxIoRF, "The maximum IO for a single tier three capacitor in RF/t") .getInt(capacitorBankTierThreeMaxIoRF); capacitorBankTierThreeMaxStorageRF = config.get(sectionPower.name, "capacitorBankTierThreeMaxStorageRF", capacitorBankTierThreeMaxStorageRF, "The maximum storage for a single tier three capacitor in RF") .getInt(capacitorBankTierThreeMaxStorageRF); capacitorBankRenderPowerOverlayOnItem = config.getBoolean("capacitorBankRenderPowerOverlayOnItem", sectionAesthetic.name, capacitorBankRenderPowerOverlayOnItem, "When true the the capacitor bank item wil get a power bar in addition to the gauge on the bank"); powerConduitTierOneRF = config.get(sectionPower.name, "powerConduitTierOneRF", powerConduitTierOneRF, "The maximum IO for the tier 1 power conduit") .getInt(powerConduitTierOneRF); powerConduitTierTwoRF = config.get(sectionPower.name, "powerConduitTierTwoRF", powerConduitTierTwoRF, "The maximum IO for the tier 2 power conduit") .getInt(powerConduitTierTwoRF); powerConduitTierThreeRF = config.get(sectionPower.name, "powerConduitTierThreeRF", powerConduitTierThreeRF, "The maximum IO for the tier 3 power conduit") .getInt(powerConduitTierThreeRF); powerConduitCanDifferentTiersConnect = config .getBoolean("powerConduitCanDifferentTiersConnect", sectionPower.name, powerConduitCanDifferentTiersConnect, "If set to false power conduits of different tiers cannot be connected. in this case a block such as a cap. bank is needed to bridge different tiered networks"); powerConduitOutputMJ = config.getBoolean("powerConduitOutputMJ", sectionPower.name, powerConduitOutputMJ, "When set to true power conduits will output MJ if RF is not supported"); painterEnergyPerTaskRF = config.get(sectionPower.name, "painterEnergyPerTaskRF", painterEnergyPerTaskRF, "The total amount of RF required to paint one block") .getInt(painterEnergyPerTaskRF); recipeLevel = config.get(sectionRecipe.name, "recipeLevel", recipeLevel, "How expensive should the crafting recipes be? -1=don't register any crafting/smelting recipes, 0=cheapest, 1=cheaper, 2=normal, 3=expensive").getInt( recipeLevel); registerRecipes = config .get(sectionRecipe.name, "registerRecipes", registerRecipes, "If set to false: No crafting recipes (crafting table and furnace) will be registered. You need to use Creative mode or something like minetweaker to add them yourself.") .getBoolean(registerRecipes); addPeacefulRecipes = config.get(sectionRecipe.name, "addPeacefulRecipes", addPeacefulRecipes, "When enabled peaceful recipes are added for soulbinder based crafting components.") .getBoolean(addPeacefulRecipes); allowTileEntitiesAsPaintSource = config.get(sectionRecipe.name, "allowTileEntitiesAsPaintSource", allowTileEntitiesAsPaintSource, "When enabled blocks with tile entities (e.g. machines) can be used as paint targets.") .getBoolean(allowTileEntitiesAsPaintSource); createSyntheticRecipes = config .get( sectionRecipe.name, "createSyntheticRecipes", createSyntheticRecipes, "Automatically create alloy smelter recipes with double and tripple inputs and different slot allocations (1+1+1, 2+1, 1+2, 3 and 2) for single-input recipes.") .getBoolean(createSyntheticRecipes); allowExternalTickSpeedup = config.get(sectionMisc.name, "allowExternalTickSpeedup", allowExternalTickSpeedup, "Allows machines to run faster if another mod speeds up the tickrate. Running at higher tickrates is " + "unsupported. Disable this if you run into any kind of problem.") .getBoolean(allowExternalTickSpeedup); enchanterBaseLevelCost = config.get(sectionRecipe.name, "enchanterBaseLevelCost", enchanterBaseLevelCost, "Base level cost added to all recipes in the enchanter.").getInt(enchanterBaseLevelCost); photovoltaicCellEnabled = config.get(sectionItems.name, "photovoltaicCellEnabled", photovoltaicCellEnabled, "If set to false: Photovoltaic Cells will not be craftable.") .getBoolean(photovoltaicCellEnabled); reservoirEnabled= config.get(sectionItems.name, "reservoirEnabled", reservoirEnabled, "If set to false reservoirs will not be craftable.") .getBoolean(reservoirEnabled); transceiverEnabled = config.get(sectionItems.name, "transceiverEnabled", transceiverEnabled, "If set to false: Dimensional Transceivers will not be craftable.") .getBoolean(transceiverEnabled); maxPhotovoltaicOutputRF = config.get(sectionPower.name, "maxPhotovoltaicOutputRF", maxPhotovoltaicOutputRF, "Maximum output in RF/t of the Photovoltaic Panels.").getInt(maxPhotovoltaicOutputRF); maxPhotovoltaicAdvancedOutputRF = config.get(sectionPower.name, "maxPhotovoltaicAdvancedOutputRF", maxPhotovoltaicAdvancedOutputRF, "Maximum output in RF/t of the Advanced Photovoltaic Panels.").getInt(maxPhotovoltaicAdvancedOutputRF); maxPhotovoltaicVibrantOutputRF = config.get(sectionPower.name, "maxPhotovoltaicVibrantOutputRF", maxPhotovoltaicVibrantOutputRF, "Maximum output in RF/t of the Vibrant Photovoltaic Panels.").getInt(maxPhotovoltaicVibrantOutputRF); photovoltaicCanTypesJoins = config.get(sectionPower.name, "photovoltaicCanTypesJoins", photovoltaicCanTypesJoins, "When enabled Photovoltaic Panels of different kinds can join together as a multi-block").getBoolean(photovoltaicCanTypesJoins); photovoltaicRecalcSunTick = config.get(sectionPower.name, "photovoltaicRecalcSunTick", photovoltaicRecalcSunTick, "How often (in ticks) the Photovoltaic Panels should check the sun's angle.").getInt(photovoltaicRecalcSunTick); conduitScale = config.get(sectionAesthetic.name, "conduitScale", DEFAULT_CONDUIT_SCALE, "Valid values are between 0-1, smallest conduits at 0, largest at 1.\n" + "In SMP, all clients must be using the same value as the server.").getDouble(DEFAULT_CONDUIT_SCALE); conduitScale = VecmathUtil.clamp(conduitScale, 0, 1); wirelessChargerRange = config.get(sectionEfficiency.name, "wirelessChargerRange", wirelessChargerRange, "The range of the wireless charger").getInt(wirelessChargerRange); fluidConduitExtractRate = config.get(sectionEfficiency.name, "fluidConduitExtractRate", fluidConduitExtractRate, "Number of millibuckets per tick extracted by a fluid conduits auto extracting").getInt(fluidConduitExtractRate); fluidConduitMaxIoRate = config.get(sectionEfficiency.name, "fluidConduitMaxIoRate", fluidConduitMaxIoRate, "Number of millibuckets per tick that can pass through a single connection to a fluid conduit.").getInt(fluidConduitMaxIoRate); advancedFluidConduitExtractRate = config.get(sectionEfficiency.name, "advancedFluidConduitExtractRate", advancedFluidConduitExtractRate, "Number of millibuckets per tick extracted by pressurized fluid conduits auto extracting").getInt(advancedFluidConduitExtractRate); advancedFluidConduitMaxIoRate = config.get(sectionEfficiency.name, "advancedFluidConduitMaxIoRate", advancedFluidConduitMaxIoRate, "Number of millibuckets per tick that can pass through a single connection to an pressurized fluid conduit.").getInt(advancedFluidConduitMaxIoRate); enderFluidConduitExtractRate = config.get(sectionEfficiency.name, "enderFluidConduitExtractRate", enderFluidConduitExtractRate, "Number of millibuckets per tick extracted by ender fluid conduits auto extracting").getInt(enderFluidConduitExtractRate); enderFluidConduitMaxIoRate = config.get(sectionEfficiency.name, "enderFluidConduitMaxIoRate", enderFluidConduitMaxIoRate, "Number of millibuckets per tick that can pass through a single connection to an ender fluid conduit.").getInt(enderFluidConduitMaxIoRate); gasConduitExtractRate = config.get(sectionEfficiency.name, "gasConduitExtractRate", gasConduitExtractRate, "Amount of gas per tick extracted by gas conduits auto extracting").getInt(gasConduitExtractRate); gasConduitMaxIoRate = config.get(sectionEfficiency.name, "gasConduitMaxIoRate", gasConduitMaxIoRate, "Amount of gas per tick that can pass through a single connection to a gas conduit.").getInt(gasConduitMaxIoRate); useAlternateTesseractModel = config.get(sectionAesthetic.name, "useAlternateTransceiverModel", useAlternateTesseractModel, "Use TheKazador's alternative model for the Dimensional Transceiver") .getBoolean(false); transceiverEnergyLoss = config.get(sectionPower.name, "transceiverEnergyLoss", transceiverEnergyLoss, "Amount of energy lost when transfered by Dimensional Transceiver; 0 is no loss, 1 is 100% loss").getDouble(transceiverEnergyLoss); transceiverBucketTransmissionCostRF = config.get(sectionEfficiency.name, "transceiverBucketTransmissionCostRF", transceiverBucketTransmissionCostRF, "The cost in RF of transporting a bucket of fluid via a Dimensional Transceiver.").getInt(transceiverBucketTransmissionCostRF); vatPowerUserPerTickRF = config.get(sectionPower.name, "vatPowerUserPerTickRF", vatPowerUserPerTickRF, "Power use (RF/t) used by the vat.").getInt(vatPowerUserPerTickRF); detailedPowerTrackingEnabled = config .get( sectionAdvanced.name, "perInterfacePowerTrackingEnabled", detailedPowerTrackingEnabled, "Enable per tick sampling on individual power inputs and outputs. This allows slightly more detailed messages from the RF Reader but has a negative impact on server performance.") .getBoolean(detailedPowerTrackingEnabled); jeiUseShortenedPainterRecipes = config .get(sectionPersonal.name, "jeiUseShortenedPainterRecipes", jeiUseShortenedPainterRecipes, "If true, only a handful of sample painter recipes will be shown in JEI. Enable this if you have timing problems starting a world or logging into a server.") .getBoolean(jeiUseShortenedPainterRecipes); useSneakMouseWheelYetaWrench = config.get(sectionPersonal.name, "useSneakMouseWheelYetaWrench", useSneakMouseWheelYetaWrench, "If true, shift-mouse wheel will change the conduit display mode when the YetaWrench is equipped.") .getBoolean(useSneakMouseWheelYetaWrench); useSneakRightClickYetaWrench = config.get(sectionPersonal.name, "useSneakRightClickYetaWrench", useSneakRightClickYetaWrench, "If true, shift-clicking the YetaWrench on a null or non wrenchable object will change the conduit display mode.").getBoolean( useSneakRightClickYetaWrench); yetaWrenchOverlayMode = config.getInt("yetaWrenchOverlayMode",sectionPersonal.name, yetaWrenchOverlayMode, 0, 2, "What kind of overlay to use when holding the yeta wrench\n\n" + "0 - Sideways scrolling in ceter of screen\n" + "1 - Vertical icon bar in bottom right\n" + "2 - Old-style group of icons in bottom right"); machineSoundsEnabled = config.get(sectionPersonal.name, "useMachineSounds", machineSoundsEnabled, "If true, machines will make sounds.").getBoolean( machineSoundsEnabled); machineSoundVolume = (float) config.get(sectionPersonal.name, "machineSoundVolume", machineSoundVolume, "Volume of machine sounds.").getDouble( machineSoundVolume); itemConduitUsePhyscialDistance = config.get(sectionEfficiency.name, "itemConduitUsePhyscialDistance", itemConduitUsePhyscialDistance, "If true, " + "'line of sight' distance rather than conduit path distance is used to calculate priorities.") .getBoolean(itemConduitUsePhyscialDistance); vacuumChestRange = config.get(sectionEfficiency.name, "vacumChestRange", vacuumChestRange, "The range of the vacuum chest").getInt(vacuumChestRange); reinforcedObsidianEnabled = config.get(sectionItems.name, "reinforcedObsidianEnabled", reinforcedObsidianEnabled, "When set to false reinforced obsidian is not craftable.").getBoolean(reinforcedObsidianEnabled); travelAnchorEnabled = config.get(sectionItems.name, "travelAnchorEnabled", travelAnchorEnabled, "When set to false: the travel anchor will not be craftable.").getBoolean(travelAnchorEnabled); travelAnchorMaxDistance = config.get(sectionAnchor.name, "travelAnchorMaxDistance", travelAnchorMaxDistance, "Maximum number of blocks that can be traveled from one travel anchor to another.").getInt(travelAnchorMaxDistance); travelAnchorCooldown = config.get(sectionAnchor.name, "travelAnchorCooldown", travelAnchorCooldown, "Number of ticks cooldown between activations (1 sec = 20 ticks)").getInt(travelAnchorCooldown); travelAnchorSneak = config.get(sectionAnchor.name, "travelAnchorSneak", travelAnchorSneak, "Add sneak as an option to activate travel anchors").getBoolean(travelAnchorSneak); travelAnchorSkipWarning = config.get(sectionAnchor.name, "travelAnchorSkipWarning", travelAnchorSkipWarning, "Travel Anchors send a chat warning when skipping inaccessible anchors").getBoolean(travelAnchorSkipWarning); travelStaffMaxDistance = config.get(sectionStaff.name, "travelStaffMaxDistance", travelStaffMaxDistance, "Maximum number of blocks that can be traveled using the Staff of Traveling.").getInt(travelStaffMaxDistance); travelStaffPowerPerBlockRF = (float) config.get(sectionStaff.name, "travelStaffPowerPerBlockRF", travelStaffPowerPerBlockRF, "Number of RF required per block traveled using the Staff of Traveling.").getDouble(travelStaffPowerPerBlockRF); travelStaffMaxBlinkDistance = config.get(sectionStaff.name, "travelStaffMaxBlinkDistance", travelStaffMaxBlinkDistance, "Max number of blocks teleported when shift clicking the staff.").getInt(travelStaffMaxBlinkDistance); travelStaffBlinkPauseTicks = config.get(sectionStaff.name, "travelStaffBlinkPauseTicks", travelStaffBlinkPauseTicks, "Minimum number of ticks between 'blinks'. Values of 10 or less allow a limited sort of flight.").getInt(travelStaffBlinkPauseTicks); travelStaffEnabled = config.get(sectionStaff.name, "travelStaffEnabled", travelStaffEnabled, "If set to false: the travel staff will not be craftable.").getBoolean(travelStaffEnabled); travelStaffBlinkEnabled = config.get(sectionStaff.name, "travelStaffBlinkEnabled", travelStaffBlinkEnabled, "If set to false: the travel staff can not be used to shift-right click teleport, or blink.").getBoolean(travelStaffBlinkEnabled); travelStaffBlinkThroughSolidBlocksEnabled = config.get(sectionStaff.name, "travelStaffBlinkThroughSolidBlocksEnabled", travelStaffBlinkThroughSolidBlocksEnabled, "If set to false: the travel staff can be used to blink through any block.").getBoolean(travelStaffBlinkThroughSolidBlocksEnabled); travelStaffBlinkThroughClearBlocksEnabled = config .get(sectionItems.name, "travelStaffBlinkThroughClearBlocksEnabled", travelStaffBlinkThroughClearBlocksEnabled, "If travelStaffBlinkThroughSolidBlocksEnabled is set to false and this is true: the travel " + "staff can only be used to blink through transparent or partial blocks (e.g. torches). " + "If both are false: only air blocks may be teleported through.") .getBoolean(travelStaffBlinkThroughClearBlocksEnabled); travelStaffBlinkThroughUnbreakableBlocksEnabled = config.get(sectionItems.name, "travelStaffBlinkThroughUnbreakableBlocksEnabled", travelStaffBlinkThroughUnbreakableBlocksEnabled, "Allows the travel staff to blink through unbreakable blocks such as warded blocks and bedrock.") .getBoolean(); travelStaffBlinkBlackList = config.getStringList("travelStaffBlinkBlackList", sectionStaff.name, travelStaffBlinkBlackList, "Lists the blocks that cannot be teleported through in the form 'modID:blockName'"); travelAnchorZoomScale = config.getFloat("travelAnchorZoomScale", sectionStaff.name, travelAnchorZoomScale, 0, 1, "Set the max zoomed size of a travel anchor as an aprox. percentage of screen height"); travelStaffOffhandBlinkEnabled = config .get(sectionStaff.name, "travelStaffOffhandBlinkEnabled", travelStaffOffhandBlinkEnabled, "If set to false: the travel staff can not be used to shift-right click teleport, or blink, when held in the off-hand.") .getBoolean(travelStaffOffhandBlinkEnabled); travelStaffOffhandTravelEnabled = config .get(sectionStaff.name, "travelStaffOffhandTravelEnabled", travelStaffOffhandTravelEnabled, "If set to false: the travel staff can not be used to click teleport to Travel Anchors, when held in the off-hand.") .getBoolean(travelStaffOffhandTravelEnabled); travelStaffOffhandEnderIOEnabled = config .get(sectionStaff.name, "travelStaffOffhandEnderIOEnabled", travelStaffOffhandEnderIOEnabled, "If set to false: the travel staff can not be used to activate the Ender IO, when held in the off-hand.") .getBoolean(travelStaffOffhandEnderIOEnabled); travelStaffOffhandShowsTravelTargets = config .get(sectionStaff.name, "travelStaffOffhandShowsTravelTargets", travelStaffOffhandShowsTravelTargets, "If set to false: Teleportation targets will not be highlighted for travel items held in the off-hand.") .getBoolean(travelStaffOffhandShowsTravelTargets); enderIoRange = config.get(sectionEfficiency.name, "enderIoRange", enderIoRange, "Range accessible (in blocks) when using the Ender IO.").getInt(enderIoRange); enderIoMeAccessEnabled = config.get(sectionPersonal.name, "enderIoMeAccessEnabled", enderIoMeAccessEnabled, "If false: you will not be able to access a ME access or crafting terminal using the Ender IO.").getBoolean(enderIoMeAccessEnabled); updateLightingWhenHidingFacades = config.get(sectionEfficiency.name, "updateLightingWhenHidingFacades", updateLightingWhenHidingFacades, "When true: correct lighting is recalculated (client side) for conduit bundles when transitioning to" + " from being hidden behind a facade. This produces " + "better quality rendering but can result in frame stutters when switching to/from a wrench.") .getBoolean(updateLightingWhenHidingFacades); darkSteelRightClickPlaceEnabled = config.get(sectionDarkSteel.name, "darkSteelRightClickPlaceEnabled", darkSteelRightClickPlaceEnabled, "Enable / disable right click to place block using dark steel tools.").getBoolean(darkSteelRightClickPlaceEnabled); darkSteelPowerDamgeAbsorptionRatios = config .get(sectionDarkSteel.name, "darkSteelPowerDamgeAbsorptionRatios", darkSteelPowerDamgeAbsorptionRatios, "A list of the amount of durability damage absorbed when items are powered. In order of upgrade level. 1=100% so items take no durability damage when powered.") .getDoubleList(); darkSteelPowerStorageBase = config.get(sectionDarkSteel.name, "darkSteelPowerStorageBase", darkSteelPowerStorageBase, "Base amount of power stored by dark steel items.").getInt(darkSteelPowerStorageBase); darkSteelPowerStorageLevelOne = config.get(sectionDarkSteel.name, "darkSteelPowerStorageLevelOne", darkSteelPowerStorageLevelOne, "Amount of power stored by dark steel items with a level 1 upgrade.").getInt(darkSteelPowerStorageLevelOne); darkSteelPowerStorageLevelTwo = config.get(sectionDarkSteel.name, "darkSteelPowerStorageLevelTwo", darkSteelPowerStorageLevelTwo, "Amount of power stored by dark steel items with a level 2 upgrade.").getInt(darkSteelPowerStorageLevelTwo); darkSteelPowerStorageLevelThree = config.get(sectionDarkSteel.name, "darkSteelPowerStorageLevelThree", darkSteelPowerStorageLevelThree, "Amount of power stored by dark steel items with a level 3 upgrade.").getInt(darkSteelPowerStorageLevelThree); darkSteelUpgradeVibrantCost = config.get(sectionDarkSteel.name, "darkSteelUpgradeVibrantCost", darkSteelUpgradeVibrantCost, "Number of levels required for the 'Empowered.").getInt(darkSteelUpgradeVibrantCost); darkSteelUpgradePowerOneCost = config.get(sectionDarkSteel.name, "darkSteelUpgradePowerOneCost", darkSteelUpgradePowerOneCost, "Number of levels required for the 'Power 1.").getInt(darkSteelUpgradePowerOneCost); darkSteelUpgradePowerTwoCost = config.get(sectionDarkSteel.name, "darkSteelUpgradePowerTwoCost", darkSteelUpgradePowerTwoCost, "Number of levels required for the 'Power 2.").getInt(darkSteelUpgradePowerTwoCost); darkSteelUpgradePowerThreeCost = config.get(sectionDarkSteel.name, "darkSteelUpgradePowerThreeCost", darkSteelUpgradePowerThreeCost, "Number of levels required for the 'Power 3' upgrade.").getInt(darkSteelUpgradePowerThreeCost); darkSteelJumpOneCost = config.get(sectionDarkSteel.name, "darkSteelJumpOneCost", darkSteelJumpOneCost, "Number of levels required for the 'Jump 1' upgrade.").getInt(darkSteelJumpOneCost); darkSteelJumpTwoCost = config.get(sectionDarkSteel.name, "darkSteelJumpTwoCost", darkSteelJumpTwoCost, "Number of levels required for the 'Jump 2' upgrade.").getInt(darkSteelJumpTwoCost); darkSteelJumpThreeCost = config.get(sectionDarkSteel.name, "darkSteelJumpThreeCost", darkSteelJumpThreeCost, "Number of levels required for the 'Jump 3' upgrade.").getInt(darkSteelJumpThreeCost); darkSteelSpeedOneCost = config.get(sectionDarkSteel.name, "darkSteelSpeedOneCost", darkSteelSpeedOneCost, "Number of levels required for the 'Speed 1' upgrade.").getInt(darkSteelSpeedOneCost); darkSteelSpeedTwoCost = config.get(sectionDarkSteel.name, "darkSteelSpeedTwoCost", darkSteelSpeedTwoCost, "Number of levels required for the 'Speed 2' upgrade.").getInt(darkSteelSpeedTwoCost); darkSteelSpeedThreeCost = config.get(sectionDarkSteel.name, "darkSteelSpeedThreeCost", darkSteelSpeedThreeCost, "Number of levels required for the 'Speed 3' upgrade.").getInt(darkSteelSpeedThreeCost); slotZeroPlacesEight = config.get(sectionDarkSteel.name, "shouldSlotZeroWrap", slotZeroPlacesEight, "Should the dark steel placement, when in the first (0th) slot, place the item in the last slot. If false, will place what's in the second slot.").getBoolean(); darkSteelSpeedOneWalkModifier = (float) config.get(sectionDarkSteel.name, "darkSteelSpeedOneWalkModifier", darkSteelSpeedOneWalkModifier, "Speed modifier applied when walking in the Dark Steel Boots with Speed I.").getDouble(darkSteelSpeedOneWalkModifier); darkSteelSpeedTwoWalkMultiplier = (float) config.get(sectionDarkSteel.name, "darkSteelSpeedTwoWalkMultiplier", darkSteelSpeedTwoWalkMultiplier, "Speed modifier applied when walking in the Dark Steel Boots with Speed I.").getDouble(darkSteelSpeedTwoWalkMultiplier); darkSteelSpeedThreeWalkMultiplier = (float) config.get(sectionDarkSteel.name, "darkSteelSpeedThreeWalkMultiplier", darkSteelSpeedThreeWalkMultiplier, "Speed modifier applied when walking in the Dark Steel Boots with Speed I.").getDouble(darkSteelSpeedThreeWalkMultiplier); darkSteelSpeedOneSprintModifier = (float) config.get(sectionDarkSteel.name, "darkSteelSpeedOneSprintModifier", darkSteelSpeedOneSprintModifier, "Speed modifier applied when walking in the Dark Steel Boots with Speed I.").getDouble(darkSteelSpeedOneSprintModifier); darkSteelSpeedTwoSprintMultiplier = (float) config.get(sectionDarkSteel.name, "darkSteelSpeedTwoSprintMultiplier", darkSteelSpeedTwoSprintMultiplier, "Speed modifier applied when walking in the Dark Steel Boots with Speed I.").getDouble(darkSteelSpeedTwoSprintMultiplier); darkSteelSpeedThreeSprintMultiplier = (float) config.get(sectionDarkSteel.name, "darkSteelSpeedThreeSprintMultiplier", darkSteelSpeedThreeSprintMultiplier, "Speed modifier applied when walking in the Dark Steel Boots with Speed I.").getDouble(darkSteelSpeedThreeSprintMultiplier); darkSteelBootsJumpModifier = config.get(sectionDarkSteel.name, "darkSteelBootsJumpModifier", darkSteelBootsJumpModifier, "Jump height modifier applied when jumping with Dark Steel Boots equipped").getDouble(darkSteelBootsJumpModifier); darkSteelPowerStorageBase = config.get(sectionDarkSteel.name, "darkSteelPowerStorage", darkSteelPowerStorageBase, "Amount of power stored (RF) per crystal in the armor items recipe.").getInt(darkSteelPowerStorageBase); darkSteelWalkPowerCost = config.get(sectionDarkSteel.name, "darkSteelWalkPowerCost", darkSteelWalkPowerCost, "Amount of power stored (RF) per block walked when wearing the dark steel boots.").getInt(darkSteelWalkPowerCost); darkSteelSprintPowerCost = config.get(sectionDarkSteel.name, "darkSteelSprintPowerCost", darkSteelWalkPowerCost, "Amount of power stored (RF) per block walked when wearing the dark steel boots.").getInt(darkSteelSprintPowerCost); darkSteelDrainPowerFromInventory = config.get(sectionDarkSteel.name, "darkSteelDrainPowerFromInventory", darkSteelDrainPowerFromInventory, "If true, dark steel armor will drain power stored (RF) in power containers in the players inventory.").getBoolean(darkSteelDrainPowerFromInventory); darkSteelBootsJumpPowerCost = config.get(sectionDarkSteel.name, "darkSteelBootsJumpPowerCost", darkSteelBootsJumpPowerCost, "Base amount of power used per jump (RF) dark steel boots. The second jump in a 'double jump' uses 2x this etc").getInt(darkSteelBootsJumpPowerCost); darkSteelFallDistanceCost = config.get(sectionDarkSteel.name, "darkSteelFallDistanceCost", darkSteelFallDistanceCost, "Amount of power used (RF) per block height of fall distance damage negated.").getInt(darkSteelFallDistanceCost); darkSteelSwimCost = config.get(sectionDarkSteel.name, "darkSteelSwimCost", darkSteelSwimCost, "Number of levels required for the 'Swim' upgrade.").getInt(darkSteelSwimCost); darkSteelNightVisionCost = config.get(sectionDarkSteel.name, "darkSteelNightVisionCost", darkSteelNightVisionCost, "Number of levels required for the 'Night Vision' upgrade.").getInt(darkSteelNightVisionCost); darkSteelGliderCost = config.get(sectionDarkSteel.name, "darkSteelGliderCost", darkSteelGliderCost, "Number of levels required for the 'Glider' upgrade.").getInt(darkSteelGliderCost); darkSteelGliderHorizontalSpeed = config.get(sectionDarkSteel.name, "darkSteelGliderHorizontalSpeed", darkSteelGliderHorizontalSpeed, "Horizontal movement speed modifier when gliding.").getDouble(darkSteelGliderHorizontalSpeed); darkSteelGliderVerticalSpeed = config.get(sectionDarkSteel.name, "darkSteelGliderVerticalSpeed", darkSteelGliderVerticalSpeed, "Rate of altitude loss when gliding.").getDouble(darkSteelGliderVerticalSpeed); darkSteelGliderVerticalSpeedSprinting = config.get(sectionDarkSteel.name, "darkSteelGliderVerticalSpeedSprinting", darkSteelGliderVerticalSpeedSprinting, "Rate of altitude loss when sprinting and gliding.").getDouble(darkSteelGliderVerticalSpeedSprinting); darkSteelSoundLocatorCost = config.get(sectionDarkSteel.name, "darkSteelSoundLocatorCost", darkSteelSoundLocatorCost, "Number of levels required for the 'Sound Locator' upgrade.").getInt(darkSteelSoundLocatorCost); darkSteelSoundLocatorRange = config.get(sectionDarkSteel.name, "darkSteelSoundLocatorRange", darkSteelSoundLocatorRange, "Range of the 'Sound Locator' upgrade.").getInt(darkSteelSoundLocatorRange); darkSteelSoundLocatorLifespan = config.get(sectionDarkSteel.name, "darkSteelSoundLocatorLifespan", darkSteelSoundLocatorLifespan, "Number of ticks the 'Sound Locator' icons are displayed for.").getInt(darkSteelSoundLocatorLifespan); darkSteelGogglesOfRevealingCost= config.get(sectionDarkSteel.name, "darkSteelGogglesOfRevealingCost", darkSteelGogglesOfRevealingCost, "Number of levels required for the Goggles of Revealing upgrade.").getInt(darkSteelGogglesOfRevealingCost); darkSteelApiaristArmorCost= config.get(sectionDarkSteel.name, "darkSteelApiaristArmorCost", darkSteelApiaristArmorCost, "Number of levels required for the Apiarist Armor upgrade.").getInt(darkSteelApiaristArmorCost); darkSteelTravelCost = config.get(sectionDarkSteel.name, "darkSteelTravelCost", darkSteelTravelCost, "Number of levels required for the 'Travel' upgrade.").getInt(darkSteelTravelCost); darkSteelSpoonCost = config.get(sectionDarkSteel.name, "darkSteelSpoonCost", darkSteelSpoonCost, "Number of levels required for the 'Spoon' upgrade.").getInt(darkSteelSpoonCost); darkSteelSolarOneCost = config.get(sectionDarkSteel.name, "darkSteelSolarOneCost", darkSteelSolarOneCost, "Cost in XP levels of the Solar I upgrade.").getInt(); darkSteelSolarOneGen = config.get(sectionDarkSteel.name, "darkSteelSolarOneGen", darkSteelSolarOneGen, "RF per SECOND generated by the Solar I upgrade. Split between all equipped DS armors.").getInt(); darkSteelSolarTwoCost = config.get(sectionDarkSteel.name, "darkSteelSolarTwoCost", darkSteelSolarTwoCost, "Cost in XP levels of the Solar II upgrade.").getInt(); darkSteelSolarTwoGen = config.get(sectionDarkSteel.name, "darkSteelSolarTwoGen", darkSteelSolarTwoGen, "RF per SECOND generated by the Solar II upgrade. Split between all equipped DS armors.").getInt(); darkSteelSolarThreeCost = config.get(sectionDarkSteel.name, "darkSteelSolarThreeCost", darkSteelSolarThreeCost, "Cost in XP levels of the Solar III upgrade.").getInt(); darkSteelSolarThreeGen = config.get(sectionDarkSteel.name, "darkSteelSolarThreeGen", darkSteelSolarThreeGen, "RF per SECOND generated by the Solar III upgrade. Split between all equipped DS armors.").getInt(); darkSteelSolarChargeOthers = config.get(sectionDarkSteel.name, "darkSteelSolarChargeOthers", darkSteelSolarChargeOthers, "If enabled allows the solar upgrade to charge non-darksteel armors that the player is wearing.").getBoolean(); darkSteelSwordSkullChance = (float) config.get(sectionDarkSteel.name, "darkSteelSwordSkullChance", darkSteelSwordSkullChance, "The base chance that a skull will be dropped when using a powered dark steel sword (0 = no chance, 1 = 100% chance)").getDouble( darkSteelSwordSkullChance); darkSteelSwordSkullLootingModifier = (float) config.get(sectionDarkSteel.name, "darkSteelSwordSkullLootingModifier", darkSteelSwordSkullLootingModifier, "The chance per looting level that a skull will be dropped when using a powered dark steel sword (0 = no chance, 1 = 100% chance)").getDouble( darkSteelSwordSkullLootingModifier); darkSteelSwordPoweredDamageBonus = (float) config.get(sectionDarkSteel.name, "darkSteelSwordPoweredDamageBonus", darkSteelSwordPoweredDamageBonus, "The extra damage dealt when the sword is powered").getDouble( darkSteelSwordPoweredDamageBonus); darkSteelSwordPoweredSpeedBonus = (float) config.get(sectionDarkSteel.name, "darkSteelSwordPoweredSpeedBonus", darkSteelSwordPoweredSpeedBonus, "The increase in attack speed when powered").getDouble( darkSteelSwordPoweredSpeedBonus); darkSteelSwordWitherSkullChance = (float) config.get(sectionDarkSteel.name, "darkSteelSwordWitherSkullChance", darkSteelSwordWitherSkullChance, "The base chance that a wither skull will be dropped when using a powered dark steel sword (0 = no chance, 1 = 100% chance)").getDouble( darkSteelSwordWitherSkullChance); darkSteelSwordWitherSkullLootingModifier = (float) config.get(sectionDarkSteel.name, "darkSteelSwordWitherSkullLootingModifie", darkSteelSwordWitherSkullLootingModifier, "The chance per looting level that a wither skull will be dropped when using a powered dark steel sword (0 = no chance, 1 = 100% chance)").getDouble( darkSteelSwordWitherSkullLootingModifier); vanillaSwordSkullChance = (float) config.get(sectionDarkSteel.name, "vanillaSwordSkullChance", vanillaSwordSkullChance, "The base chance that a skull will be dropped when using a non dark steel sword (0 = no chance, 1 = 100% chance)").getDouble( vanillaSwordSkullChance); vanillaSwordSkullLootingModifier = (float) config.get(sectionPersonal.name, "vanillaSwordSkullLootingModifier", vanillaSwordSkullLootingModifier, "The chance per looting level that a skull will be dropped when using a non-dark steel sword (0 = no chance, 1 = 100% chance)").getDouble( vanillaSwordSkullLootingModifier); ticCleaverSkullDropChance = (float) config.get(sectionDarkSteel.name, "ticCleaverSkullDropChance", ticCleaverSkullDropChance, "The base chance that an Enderman Skull will be dropped when using TiC Cleaver").getDouble( ticCleaverSkullDropChance); ticBeheadingSkullModifier = (float) config.get(sectionPersonal.name, "ticBeheadingSkullModifier", ticBeheadingSkullModifier, "The chance per level of Beheading that a skull will be dropped when using a TiC weapon").getDouble( ticBeheadingSkullModifier); fakePlayerSkullChance = (float) config .get( sectionDarkSteel.name, "fakePlayerSkullChance", fakePlayerSkullChance, "The ratio of skull drops when a mob is killed by a 'FakePlayer', such as Killer Joe. When set to 0 no skulls will drop, at 1 the rate of skull drops is not modified") .getDouble( fakePlayerSkullChance); darkSteelSwordPowerUsePerHit = config.get(sectionDarkSteel.name, "darkSteelSwordPowerUsePerHit", darkSteelSwordPowerUsePerHit, "The amount of power (RF) used per hit.").getInt(darkSteelSwordPowerUsePerHit); darkSteelSwordEnderPearlDropChance = config.get(sectionDarkSteel.name, "darkSteelSwordEnderPearlDropChance", darkSteelSwordEnderPearlDropChance, "The chance that an ender pearl will be dropped when using a dark steel sword (0 = no chance, 1 = 100% chance)").getDouble( darkSteelSwordEnderPearlDropChance); darkSteelSwordEnderPearlDropChancePerLooting = config.get(sectionDarkSteel.name, "darkSteelSwordEnderPearlDropChancePerLooting", darkSteelSwordEnderPearlDropChancePerLooting, "The chance for each looting level that an additional ender pearl will be dropped when using a dark steel sword (0 = no chance, 1 = 100% chance)") .getDouble( darkSteelSwordEnderPearlDropChancePerLooting); darkSteelPickPowerUseObsidian = config.get(sectionDarkSteel.name, "darkSteelPickPowerUseObsidian", darkSteelPickPowerUseObsidian, "The amount of power (RF) used to break an obsidian block.").getInt(darkSteelPickPowerUseObsidian); darkSteelPickEffeciencyObsidian = config.get(sectionDarkSteel.name, "darkSteelPickEffeciencyObsidian", darkSteelPickEffeciencyObsidian, "The efficiency when breaking obsidian with a powered Dark Pickaxe.").getInt(darkSteelPickEffeciencyObsidian); darkSteelPickApplyObsidianEffeciencyAtHardess = (float) config.get(sectionDarkSteel.name, "darkSteelPickApplyObsidianEffeciencyAtHardess", darkSteelPickApplyObsidianEffeciencyAtHardess, "If set to a value > 0, the obsidian speed and power use will be used for all blocks with hardness >= to this value.").getDouble( darkSteelPickApplyObsidianEffeciencyAtHardess); darkSteelPickPowerUsePerDamagePoint = config.get(sectionDarkSteel.name, "darkSteelPickPowerUsePerDamagePoint", darkSteelPickPowerUsePerDamagePoint, "Power use (RF) per damage/durability point avoided.").getInt(darkSteelPickPowerUsePerDamagePoint); darkSteelPickEffeciencyBoostWhenPowered = (float) config.get(sectionDarkSteel.name, "darkSteelPickEffeciencyBoostWhenPowered", darkSteelPickEffeciencyBoostWhenPowered, "The increase in efficiency when powered.").getDouble(darkSteelPickEffeciencyBoostWhenPowered); darkSteelPickMinesTiCArdite = config.getBoolean("darkSteelPickMinesTiCArdite", sectionDarkSteel.name, darkSteelPickMinesTiCArdite, "When true the dark steel pick will be able to mine TiC Ardite and Cobalt"); darkSteelAxePowerUsePerDamagePoint = config.get(sectionDarkSteel.name, "darkSteelAxePowerUsePerDamagePoint", darkSteelAxePowerUsePerDamagePoint, "Power use (RF) per damage/durability point avoided.").getInt(darkSteelAxePowerUsePerDamagePoint); darkSteelAxePowerUsePerDamagePointMultiHarvest = config.get(sectionDarkSteel.name, "darkSteelPickAxeUsePerDamagePointMultiHarvest", darkSteelAxePowerUsePerDamagePointMultiHarvest, "Power use (RF) per damage/durability point avoided when shift-harvesting multiple logs").getInt(darkSteelAxePowerUsePerDamagePointMultiHarvest); darkSteelAxeSpeedPenaltyMultiHarvest = (float) config.get(sectionDarkSteel.name, "darkSteelAxeSpeedPenaltyMultiHarvest", darkSteelAxeSpeedPenaltyMultiHarvest, "How much slower shift-harvesting logs is.").getDouble(darkSteelAxeSpeedPenaltyMultiHarvest); darkSteelAxeEffeciencyBoostWhenPowered = (float) config.get(sectionDarkSteel.name, "darkSteelAxeEffeciencyBoostWhenPowered", darkSteelAxeEffeciencyBoostWhenPowered, "The increase in efficiency when powered.").getDouble(darkSteelAxeEffeciencyBoostWhenPowered); darkSteelShearsDurabilityFactor = config.get(sectionDarkSteel.name, "darkSteelShearsDurabilityFactor", darkSteelShearsDurabilityFactor, "How much more durable as vanilla shears they are.").getInt(darkSteelShearsDurabilityFactor); darkSteelShearsPowerUsePerDamagePoint = config.get(sectionDarkSteel.name, "darkSteelShearsPowerUsePerDamagePoint", darkSteelShearsPowerUsePerDamagePoint, "Power use (RF) per damage/durability point avoided.").getInt(darkSteelShearsPowerUsePerDamagePoint); darkSteelShearsEffeciencyBoostWhenPowered = (float) config.get(sectionDarkSteel.name, "darkSteelShearsEffeciencyBoostWhenPowered", darkSteelShearsEffeciencyBoostWhenPowered, "The increase in efficiency when powered.").getDouble(darkSteelShearsEffeciencyBoostWhenPowered); darkSteelShearsBlockAreaBoostWhenPowered = config.get(sectionDarkSteel.name, "darkSteelShearsBlockAreaBoostWhenPowered", darkSteelShearsBlockAreaBoostWhenPowered, "The increase in effected area (radius) when powered and used on blocks.").getInt(darkSteelShearsBlockAreaBoostWhenPowered); darkSteelShearsEntityAreaBoostWhenPowered = (float) config.get(sectionDarkSteel.name, "darkSteelShearsEntityAreaBoostWhenPowered", darkSteelShearsEntityAreaBoostWhenPowered, "The increase in effected area (radius) when powered and used on sheep.").getDouble(darkSteelShearsEntityAreaBoostWhenPowered); darkSteelAnvilDamageChance = (float) config.get(sectionDarkSteel.name, "darkSteelAnvilDamageChance", darkSteelAnvilDamageChance, "Chance that the dark steel anvil will take damage after repairing something.").getDouble(); darkSteelLadderSpeedBoost = (float) config.get(sectionDarkSteel.name, "darkSteelLadderSpeedBoost", darkSteelLadderSpeedBoost, "Speed boost, in blocks per tick, that the DS ladder gives over the vanilla ladder.").getDouble(); hootchPowerPerCycleRF = config.get(sectionPower.name, "hootchPowerPerCycleRF", hootchPowerPerCycleRF, "The amount of power generated per BC engine cycle. Examples: BC Oil = 30, BC Fuel = 60").getInt(hootchPowerPerCycleRF); hootchPowerTotalBurnTime = config.get(sectionPower.name, "hootchPowerTotalBurnTime", hootchPowerTotalBurnTime, "The total burn time. Examples: BC Oil = 5000, BC Fuel = 25000").getInt(hootchPowerTotalBurnTime); rocketFuelPowerPerCycleRF = config.get(sectionPower.name, "rocketFuelPowerPerCycleRF", rocketFuelPowerPerCycleRF, "The amount of power generated per BC engine cycle. Examples: BC Oil = 3, BC Fuel = 6").getInt(rocketFuelPowerPerCycleRF); rocketFuelPowerTotalBurnTime = config.get(sectionPower.name, "rocketFuelPowerTotalBurnTime", rocketFuelPowerTotalBurnTime, "The total burn time. Examples: BC Oil = 5000, BC Fuel = 25000").getInt(rocketFuelPowerTotalBurnTime); fireWaterPowerPerCycleRF = config.get(sectionPower.name, "fireWaterPowerPerCycleRF", fireWaterPowerPerCycleRF, "The amount of power generated per BC engine cycle. Examples: BC Oil = 30, BC Fuel = 60").getInt(fireWaterPowerPerCycleRF); fireWaterPowerTotalBurnTime = config.get(sectionPower.name, "fireWaterPowerTotalBurnTime", fireWaterPowerTotalBurnTime, "The total burn time. Examples: BC Oil = 5000, BC Fuel = 25000").getInt(fireWaterPowerTotalBurnTime); zombieGeneratorRfPerTick = config.get(sectionPower.name, "zombieGeneratorRfPerTick", zombieGeneratorRfPerTick, "The amount of power generated per tick.").getInt(zombieGeneratorRfPerTick); zombieGeneratorTicksPerBucketFuel = config.get(sectionPower.name, "zombieGeneratorTicksPerMbFuel", zombieGeneratorTicksPerBucketFuel, "The number of ticks one bucket of fuel lasts.").getInt(zombieGeneratorTicksPerBucketFuel); addFuelTooltipsToAllFluidContainers = config.get(sectionPersonal.name, "addFuelTooltipsToAllFluidContainers", addFuelTooltipsToAllFluidContainers, "If true, the RF/t and burn time of the fuel will be displayed in all tooltips for fluid containers with fuel.").getBoolean( addFuelTooltipsToAllFluidContainers); addDurabilityTootip = config.get(sectionPersonal.name, "addDurabilityTootip", addFuelTooltipsToAllFluidContainers, "If true, adds durability tooltips to tools and armor").getBoolean( addDurabilityTootip); addFurnaceFuelTootip = config.get(sectionPersonal.name, "addFurnaceFuelTootip", addFuelTooltipsToAllFluidContainers, "If true, adds burn duration tooltips to furnace fuels").getBoolean(addFurnaceFuelTootip); farmActionEnergyUseRF = config.get(sectionFarm.name, "farmActionEnergyUseRF", farmActionEnergyUseRF, "The amount of power used by a farm per action (eg plant, till, harvest) ").getInt(farmActionEnergyUseRF); farmAxeActionEnergyUseRF = config.get(sectionFarm.name, "farmAxeActionEnergyUseRF", farmAxeActionEnergyUseRF, "The amount of power used by a farm per wood block 'chopped'").getInt(farmAxeActionEnergyUseRF); farmBonemealActionEnergyUseRF = config.get(sectionFarm.name, "farmBonemealActionEnergyUseRF", farmBonemealActionEnergyUseRF, "The amount of power used by a farm per bone meal used").getInt(farmBonemealActionEnergyUseRF); farmBonemealTryEnergyUseRF = config.get(sectionFarm.name, "farmBonemealTryEnergyUseRF", farmBonemealTryEnergyUseRF, "The amount of power used by a farm per bone meal try").getInt(farmBonemealTryEnergyUseRF); farmAxeDamageOnLeafBreak = config.get(sectionFarm.name, "farmAxeDamageOnLeafBreak", farmAxeDamageOnLeafBreak, "Should axes in a farm take damage when breaking leaves?").getBoolean(farmAxeDamageOnLeafBreak); farmToolTakeDamageChance = (float) config.get(sectionFarm.name, "farmToolTakeDamageChance", farmToolTakeDamageChance, "The chance that a tool in the farm will take damage.").getDouble(farmToolTakeDamageChance); disableFarmNotification = config.get(sectionFarm.name, "disableFarmNotifications", disableFarmNotification, "Disable the notification text above the farm block.").getBoolean(); farmEssenceBerriesEnabled = config.get(sectionFarm.name, "farmEssenceBerriesEnabled", farmEssenceBerriesEnabled, "This setting controls whether essence berry bushes from TiC can be harvested by the farm.").getBoolean(); farmManaBeansEnabled = config.get(sectionFarm.name, "farmManaBeansEnabled", farmManaBeansEnabled, "This setting controls whether mana beans from Thaumcraft can be harvested by the farm.").getBoolean(); farmHarvestJungleWhenCocoa = config.get(sectionFarm.name, "farmHarvestJungleWhenCocoa", farmHarvestJungleWhenCocoa, "If this is enabled the farm will harvest jungle wood even if it has cocoa beans in its inventory.").getBoolean(); hoeStrings = config.get(sectionFarm.name, "farmHoes", hoeStrings, "Use this to specify items that can be hoes in the farming station. Use the registry name (eg. modid:name).").getStringList(); farmSaplingReserveAmount = config.get(sectionFarm.name, "farmSaplingReserveAmount", farmSaplingReserveAmount, "The amount of saplings the farm has to have in reserve to switch to shearing all leaves. If there are less " + "saplings in store, it will only shear part the leaves and break the others for spalings. Set this to 0 to " + "always shear all leaves.").getInt(farmSaplingReserveAmount); magnetPowerUsePerSecondRF = config.get(sectionMagnet.name, "magnetPowerUsePerTickRF", magnetPowerUsePerSecondRF, "The amount of RF power used per tick when the magnet is active").getInt(magnetPowerUsePerSecondRF); magnetPowerCapacityRF = config.get(sectionMagnet.name, "magnetPowerCapacityRF", magnetPowerCapacityRF, "Amount of RF power stored in a fully charged magnet").getInt(magnetPowerCapacityRF); magnetRange = config.get(sectionMagnet.name, "magnetRange", magnetRange, "Range of the magnet in blocks.").getInt(magnetRange); magnetMaxItems = config.get(sectionMagnet.name, "magnetMaxItems", magnetMaxItems, "Maximum number of items the magnet can effect at a time. (-1 for unlimited)").getInt(magnetMaxItems); magnetBlacklist = config.getStringList("magnetBlacklist", sectionMagnet.name, magnetBlacklist, "These items will not be picked up by the magnet."); magnetAllowInMainInventory = config.get(sectionMagnet.name, "magnetAllowInMainInventory", magnetAllowInMainInventory, "If true the magnet will also work in the main inventory, not just the hotbar").getBoolean(magnetAllowInMainInventory); magnetAllowInBaublesSlot = config.get(sectionMagnet.name, "magnetAllowInBaublesSlot", magnetAllowInBaublesSlot, "If true the magnet can be put into the 'amulet' Baubles slot (requires Baubles to be installed)").getBoolean(magnetAllowInBaublesSlot); magnetAllowDeactivatedInBaublesSlot = config.get(sectionMagnet.name, "magnetAllowDeactivatedInBaublesSlot", magnetAllowDeactivatedInBaublesSlot, "If true the magnet can be put into the 'amulet' Baubles slot even if switched off (requires Baubles to be installed and magnetAllowInBaublesSlot to be on)").getBoolean(magnetAllowDeactivatedInBaublesSlot); magnetAllowPowerExtraction = config.get(sectionMagnet.name, "magnetAllowPowerExtraction", magnetAllowPowerExtraction, "If true the magnet can be used as a battery.").getBoolean(magnetAllowPowerExtraction); magnetBaublesType = config.get(sectionMagnet.name, "magnetBaublesType", magnetBaublesType, "The BaublesType the magnet should be, 'AMULET', 'RING' or 'BELT' (requires Baubles to be installed and magnetAllowInBaublesSlot to be on)").getString(); crafterRfPerCraft = config.get("AutoCrafter Settings", "crafterRfPerCraft", crafterRfPerCraft, "RF used per autocrafted recipe").getInt(crafterRfPerCraft); poweredSpawnerMinDelayTicks = config.get(sectionSpawner.name, "poweredSpawnerMinDelayTicks", poweredSpawnerMinDelayTicks, "Min tick delay between spawns for a non-upgraded spawner").getInt(poweredSpawnerMinDelayTicks); poweredSpawnerMaxDelayTicks = config.get(sectionSpawner.name, "poweredSpawnerMaxDelayTicks", poweredSpawnerMaxDelayTicks, "Min tick delay between spawns for a non-upgraded spawner").getInt(poweredSpawnerMaxDelayTicks); poweredSpawnerMaxPlayerDistance = config.get(sectionSpawner.name, "poweredSpawnerMaxPlayerDistance", poweredSpawnerMaxPlayerDistance, "Max distance of the closest player for the spawner to be active. A zero value will remove the player check").getInt(poweredSpawnerMaxPlayerDistance); poweredSpawnerDespawnTimeSeconds = config.get(sectionSpawner.name, "poweredSpawnerDespawnTimeSeconds" , poweredSpawnerDespawnTimeSeconds, "Number of seconds in which spawned entities are protected from despawning").getInt(poweredSpawnerDespawnTimeSeconds); poweredSpawnerSpawnCount = config.get(sectionSpawner.name, "poweredSpawnerSpawnCount" , poweredSpawnerSpawnCount, "Number of entities to spawn each time").getInt(poweredSpawnerSpawnCount); poweredSpawnerSpawnRange = config.get(sectionSpawner.name, "poweredSpawnerSpawnRange" , poweredSpawnerSpawnRange, "Spawning range in X/Z").getInt(poweredSpawnerSpawnRange); poweredSpawnerMaxNearbyEntities = config.get(sectionSpawner.name, "poweredSpawnerMaxNearbyEntities" , poweredSpawnerMaxNearbyEntities, "Max number of entities in the nearby area until no more are spawned. A zero value will remove this check").getInt(poweredSpawnerMaxNearbyEntities); poweredSpawnerMaxSpawnTries = config.get(sectionSpawner.name, "poweredSpawnerMaxSpawnTries" , poweredSpawnerMaxSpawnTries, "Number of tries to find a suitable spawning location").getInt(poweredSpawnerMaxSpawnTries); poweredSpawnerUseVanillaSpawChecks = config.get(sectionSpawner.name, "poweredSpawnerUseVanillaSpawChecks", poweredSpawnerUseVanillaSpawChecks, "If true, regular spawn checks such as lighting level and dimension will be made before spawning mobs").getBoolean(poweredSpawnerUseVanillaSpawChecks); brokenSpawnerDropChance = (float) config.get(sectionSpawner.name, "brokenSpawnerDropChance", brokenSpawnerDropChance, "The chance a broken spawner will be dropped when a spawner is broken. 1 = 100% chance, 0 = 0% chance").getDouble(brokenSpawnerDropChance); brokenSpawnerToolBlacklist = config.getStringList("brokenSpawnerToolBlacklist", sectionSpawner.name, brokenSpawnerToolBlacklist, "When a spawner is broken with these tools they will not drop a broken spawner"); powerSpawnerAddSpawnerCost = config.get(sectionSpawner.name, "powerSpawnerAddSpawnerCost", powerSpawnerAddSpawnerCost, "The number of levels it costs to add a broken spawner").getInt(powerSpawnerAddSpawnerCost); nutrientFoodBoostDelay = config.get(sectionFluid.name, "nutrientFluidFoodBoostDelay", nutrientFoodBoostDelay, "The delay in ticks between when nutrient distillation boosts your food value.").getInt((int) nutrientFoodBoostDelay); killerJoeNutrientUsePerAttackMb = config.get(sectionKiller.name, "killerJoeNutrientUsePerAttackMb", killerJoeNutrientUsePerAttackMb, "The number of millibuckets of nutrient fluid used per attack.").getInt(killerJoeNutrientUsePerAttackMb); killerJoeAttackHeight = config.get(sectionKiller.name, "killerJoeAttackHeight", killerJoeAttackHeight, "The reach of attacks above and bellow Joe.").getDouble(killerJoeAttackHeight); killerJoeAttackWidth = config.get(sectionKiller.name, "killerJoeAttackWidth", killerJoeAttackWidth, "The reach of attacks to each side of Joe.").getDouble(killerJoeAttackWidth); killerJoeAttackLength = config.get(sectionKiller.name, "killerJoeAttackLength", killerJoeAttackLength, "The reach of attacks in front of Joe.").getDouble(killerJoeAttackLength); killerJoeHooverXpLength = config.get(sectionKiller.name, "killerJoeHooverXpLength", killerJoeHooverXpLength, "The distance from which XP will be gathered to each side of Joe.").getDouble(killerJoeHooverXpLength); killerJoeHooverXpWidth = config.get(sectionKiller.name, "killerJoeHooverXpWidth", killerJoeHooverXpWidth, "The distance from which XP will be gathered in front of Joe.").getDouble(killerJoeHooverXpWidth); killerJoeMaxXpLevel = config.get(sectionMisc.name, "killerJoeMaxXpLevel", killerJoeMaxXpLevel, "Maximum level of XP the killer joe can contain.").getInt(); killerJoeMustSee = config.get(sectionKiller.name, "killerJoeMustSee", killerJoeMustSee, "Set whether the Killer Joe can attack through blocks.").getBoolean(); killerPvPoffDisablesSwing = config .get(sectionKiller.name, "killerPvPoffDisablesSwing", killerPvPoffDisablesSwing, "Set whether the Killer Joe swings even if PvP is off (that swing will do nothing unless killerPvPoffIsIgnored is enabled).") .getBoolean(); killerPvPoffIsIgnored = config .get(sectionKiller.name, "killerPvPoffIsIgnored", killerPvPoffIsIgnored, "Set whether the Killer Joe ignores PvP settings and always hits players (killerPvPoffDisablesSwing must be off for this to work).") .getBoolean(); // Add deprecated comment config.getString("isGasConduitEnabled", sectionItems.name, "auto", "Deprecated option. Use boolean \"gasConduitsEnabled\" below."); isGasConduitEnabled = config.getBoolean("gasConduitEnabled", sectionItems.name, isGasConduitEnabled, "If true, gas conduits will be enabled if the Mekanism Gas API is found. False to forcibly disable."); enableMEConduits = config.getBoolean("enableMEConduits", sectionItems.name, enableMEConduits, "Allows ME conduits. Only has an effect with AE2 installed."); enableOCConduits = config.getBoolean("enableOCConduits", sectionItems.name, enableOCConduits, "Allows OC conduits. Only has an effect with OpenComputers installed."); enableOCConduitsAnimatedTexture = config.getBoolean("enableOCConduitsAnimatedTexture", sectionItems.name, enableOCConduitsAnimatedTexture, "Use the animated texture for OC conduits."); soulVesselBlackList = Arrays.asList(config.getStringList("soulVesselBlackList", sectionSoulBinder.name, soulVesselBlackList.toArray(new String[0]), "Entities listed here will can not be captured in a Soul Vial")); soulVesselCapturesBosses = config.getBoolean("soulVesselCapturesBosses", sectionSoulBinder.name, soulVesselCapturesBosses, "When set to false, any mob with a 'boss bar' won't be able to be captured in the Soul Vial"); soulBinderBrokenSpawnerRF = config.get(sectionSoulBinder.name, "soulBinderBrokenSpawnerRF", soulBinderBrokenSpawnerRF, "The number of RF required to change the type of a broken spawner.").getInt(soulBinderBrokenSpawnerRF); soulBinderReanimationRF = config.get(sectionSoulBinder.name, "soulBinderReanimationRF", soulBinderReanimationRF, "The number of RF required to to re-animated a mob head.").getInt(soulBinderReanimationRF); soulBinderEnderCystalRF = config.get(sectionSoulBinder.name, "soulBinderEnderCystalRF", soulBinderEnderCystalRF, "The number of RF required to create an ender crystal.").getInt(soulBinderEnderCystalRF); soulBinderAttractorCystalRF = config.get(sectionSoulBinder.name, "soulBinderAttractorCystalRF", soulBinderAttractorCystalRF, "The number of RF required to create an attractor crystal.").getInt(soulBinderAttractorCystalRF); soulBinderEnderRailRF = config.get(sectionSoulBinder.name, "soulBinderEnderRailRF", soulBinderEnderRailRF, "The number of RF required to create an ender rail.").getInt(soulBinderEnderRailRF); soulBinderTunedPressurePlateRF = config.get(sectionSoulBinder.name, "soulBinderTunedPressurePlateRF", soulBinderTunedPressurePlateRF, "The number of RF required to tune a pressure plate.").getInt(soulBinderTunedPressurePlateRF); soulBinderAttractorCystalLevels = config.get(sectionSoulBinder.name, "soulBinderAttractorCystalLevels", soulBinderAttractorCystalLevels, "The number of levels required to create an attractor crystal.").getInt(soulBinderAttractorCystalLevels); soulBinderEnderCystalLevels = config.get(sectionSoulBinder.name, "soulBinderEnderCystalLevels", soulBinderEnderCystalLevels, "The number of levels required to create an ender crystal.").getInt(soulBinderEnderCystalLevels); soulBinderReanimationLevels = config.get(sectionSoulBinder.name, "soulBinderReanimationLevels", soulBinderReanimationLevels, "The number of levels required to re-animate a mob head.").getInt(soulBinderReanimationLevels); soulBinderBrokenSpawnerLevels = config.get(sectionSoulBinder.name, "soulBinderBrokenSpawnerLevels", soulBinderBrokenSpawnerLevels, "The number of levels required to change the type of a broken spawner.").getInt(soulBinderBrokenSpawnerLevels); soulBinderEnderRailLevels = config.get(sectionSoulBinder.name, "soulBinderEnderRailLevels", soulBinderEnderRailLevels, "The number of levels required to create an ender rail.").getInt(soulBinderEnderRailLevels); soulBinderTunedPressurePlateLevels = config.get(sectionSoulBinder.name, "soulBinderTunedPressurePlateLevels", soulBinderTunedPressurePlateLevels, "The number of levels required to tune a pressure plate.").getInt(soulBinderTunedPressurePlateLevels); soulBinderMaxXpLevel = config.get(sectionSoulBinder.name, "soulBinderMaxXPLevel", soulBinderMaxXpLevel, "Maximum level of XP the soul binder can contain.").getInt(); spawnGuardStopAllSlimesDebug = config.getBoolean("spawnGuardStopAllSlimesDebug", sectionAttractor.name, spawnGuardStopAllSlimesDebug, "When true slimes wont be allowed to spawn at all. Only added to aid testing in super flat worlds."); spawnGuardStopAllSquidSpawning = config.getBoolean("spawnGuardStopAllSquidSpawning", sectionAttractor.name, spawnGuardStopAllSquidSpawning, "When true no squid will be spawned."); weatherObeliskClearFluid = config.get(sectionWeather.name, "weatherObeliskClearFluid", weatherObeliskClearFluid, "The fluid required (in mB) to set the world to clear weather").getInt(); weatherObeliskRainFluid = config.get(sectionWeather.name, "weatherObeliskRainFluid", weatherObeliskRainFluid, "The fluid required (in mB) to set the world to rainy weather").getInt(); weatherObeliskThunderFluid = config.get(sectionWeather.name, "weatherObeliskThunderFluid", weatherObeliskThunderFluid, "The fluid required (in mB) to set the world to thundering weather").getInt(); // Loot Config lootDarkSteel = config.getBoolean("lootDarkSteel", sectionLootConfig.name, lootDarkSteel, "Adds Darksteel Ingots to loot tables"); lootItemConduitProbe = config.getBoolean("lootItemConduitProbe", sectionLootConfig.name, lootItemConduitProbe, "Adds ItemConduitProbe to loot tables"); lootQuartz = config.getBoolean("lootQuartz", sectionLootConfig.name, lootQuartz, "Adds quartz to loot tables"); lootNetherWart = config.getBoolean("lootNetherWart", sectionLootConfig.name, lootNetherWart, "Adds nether wart to loot tables"); lootEnderPearl = config.getBoolean("lootEnderPearl", sectionLootConfig.name, lootEnderPearl, "Adds ender pearls to loot tables"); lootElectricSteel = config.getBoolean("lootElectricSteel", sectionLootConfig.name, lootElectricSteel, "Adds Electric Steel Ingots to loot tables"); lootRedstoneAlloy = config.getBoolean("lootRedstoneAlloy", sectionLootConfig.name, lootRedstoneAlloy, "Adds Redstone Alloy Ingots to loot tables"); lootPhasedIron = config.getBoolean("lootPhasedIron", sectionLootConfig.name, lootPhasedIron, "Adds Phased Iron Ingots to loot tables"); lootPhasedGold = config.getBoolean("lootPhasedGold", sectionLootConfig.name, lootPhasedGold, "Adds Phased Gold Ingots to loot tables"); lootTravelStaff = config.getBoolean("lootTravelStaff", sectionLootConfig.name, lootTravelStaff, "Adds Travel Staff to loot tables"); lootTheEnder = config.getBoolean("lootTheEnder", sectionLootConfig.name, lootTheEnder, "Adds The Ender to loot tables"); lootDarkSteelBoots = config.getBoolean("lootDarkSteelBoots", sectionLootConfig.name, lootDarkSteelBoots, "Adds Darksteel Boots to loot tables"); enderRailEnabled = config.getBoolean("enderRailEnabled", sectionRailConfig.name, enderRailEnabled, "Whether Ender Rails are enabled"); enderRailPowerRequireCrossDimensions = config.get(sectionRailConfig.name, "enderRailPowerRequireCrossDimensions", enderRailPowerRequireCrossDimensions, "The amount of power required to transport a cart across dimensions").getInt(enderRailPowerRequireCrossDimensions); enderRailPowerRequiredPerBlock = config.get(sectionRailConfig.name, "enderRailPowerRequiredPerBlock", enderRailPowerRequiredPerBlock, "The amount of power required to teleport a cart per block in the same dimension").getInt(enderRailPowerRequiredPerBlock); enderRailCapSameDimensionPowerAtCrossDimensionCost = config.getBoolean("enderRailCapSameDimensionPowerAtCrossDimensionCost", sectionRailConfig.name, enderRailCapSameDimensionPowerAtCrossDimensionCost, "When set to true the RF cost of sending a cart within the same dimension will be capped to the cross dimension cost"); enderRailTicksBeforeForceSpawningLinkedCarts = config.get(sectionRailConfig.name, "enderRailTicksBeforeForceSpawningLinkedCarts", enderRailTicksBeforeForceSpawningLinkedCarts, "The number of ticks to wait for the track to clear before force spawning the next cart in a (RailCraft) linked set").getInt(enderRailTicksBeforeForceSpawningLinkedCarts); enderRailTeleportPlayers = config.getBoolean("enderRailTeleportPlayers", sectionRailConfig.name, enderRailTeleportPlayers, "If true player in minecarts will be teleported. WARN: WIP, seems to cause a memory leak."); dumpMobNames = config.getBoolean("dumpMobNames", sectionMobConfig.name, dumpMobNames, "When set to true a list of all registered mobs will be dumped to config/enderio/mobTypes.txt The names are in the format required by EIOs mob blacklists."); xpObeliskMaxXpLevel = config.get(sectionMisc.name, "xpObeliskMaxXpLevel", xpObeliskMaxXpLevel, "Maximum level of XP the xp obelisk can contain.").getInt(); xpJuiceName = config.getString("xpJuiceName", sectionMisc.name, xpJuiceName, "Id of liquid XP fluid (WARNING: only for users who know what they are doing - changing this id can break worlds) - this should match with OpenBlocks when installed"); glassConnectToTheirVariants = config.getBoolean("glassConnectToTheirVariants", sectionMisc.name, glassConnectToTheirVariants, "If true, quite clear glass and fused quartz will connect textures with their respective enlightened and darkened variants."); clearGlassConnectToFusedQuartz = config.getBoolean("clearGlassConnectToFusedQuartz", sectionMisc.name, clearGlassConnectToFusedQuartz, "If true, quite clear glass will connect textures with fused quartz."); enchantmentSoulBoundEnabled = config.getBoolean("enchantmentSoulBoundEnabled", sectionEnchantments.name, enchantmentSoulBoundEnabled, "If false the soul bound enchantment will not be available"); String rareStr = config.get(sectionEnchantments.name, "enchantmentSoulBoundWeight", enchantmentSoulBoundWeight.toString(), "The rarity of the enchantment. COMMON, UNCOMMON, RARE, VERY_RARE ").getString(); try { enchantmentSoulBoundWeight = Rarity.valueOf(rareStr); } catch (Exception e) { Log.warn("Could not set value config entry enchantmentWitherArrowRarity Specified value " + rareStr); e.printStackTrace(); } telepadLockDimension = config.get(sectionTelepad.name, "lockDimension", telepadLockDimension, "If true, the dimension cannot be set via the GUI, the coord selector must be used.").getBoolean(); telepadLockCoords = config.get(sectionTelepad.name, "lockCoords", telepadLockCoords, "If true, the coordinates cannot be set via the GUI, the coord selector must be used.").getBoolean(); telepadPowerCoefficient = config.get(sectionTelepad.name, "powerCoefficient", telepadPowerCoefficient, "Power for a teleport is calculated by the formula:\npower = [this value] * ln(0.005*distance + 1)").getInt(); telepadPowerInterdimensional = config.get(sectionTelepad.name, "powerInterdimensional", telepadPowerInterdimensional, "The amount of RF required for an interdimensional teleport.").getInt(); inventoryPanelFree = config.getBoolean("inventoryPanelFree", sectionInventoryPanel.name, inventoryPanelFree, "If true, the inv panel will not accept fluids and will be active permanently."); inventoryPanelPowerPerMB = config.getFloat("powerPerMB", sectionInventoryPanel.name, inventoryPanelPowerPerMB, 1.0f, 10000.0f, "Internal power generated per mB. The default of 800/mB matches the RF generation of the Zombie generator. A panel tries to refill only once every second - setting this value too low slows down the scanning speed."); inventoryPanelScanCostPerSlot = config.getFloat("scanCostPerSlot", sectionInventoryPanel.name, inventoryPanelScanCostPerSlot, 0.0f, 10.0f, "Internal power used for scanning a slot"); inventoryPanelExtractCostPerItem = config.getFloat("extractCostPerItem", sectionInventoryPanel.name, inventoryPanelExtractCostPerItem, 0.0f, 10.0f, "Internal power used per item extracted (not a stack of items)"); inventoryPanelExtractCostPerOperation = config.getFloat("extractCostPerOperation", sectionInventoryPanel.name, inventoryPanelExtractCostPerOperation, 0.0f, 10000.0f, "Internal power used per extract operation (independent of stack size)"); debugUpdatePackets = config.getBoolean("debugUpdatePackets", sectionPersonal.name, debugUpdatePackets, "DEBUG: If true, TEs will flash when they recieve an update packet."); CapacitorKey.processConfig(config); } public static void checkYetaAccess() { if(!useSneakMouseWheelYetaWrench && !useSneakRightClickYetaWrench) { Log.warn("Both useSneakMouseWheelYetaWrench and useSneakRightClickYetaWrench are set to false. Enabling right click."); useSneakRightClickYetaWrench = true; } } public static void init() { } public static void postInit() { for (String s : hoeStrings) { ItemStack hoe = getStackForString(s); if(hoe != null) { farmHoes.add(hoe); } } } public static ItemStack getStackForString(String s) { String[] nameAndMeta = s.split(";"); int meta = nameAndMeta.length == 1 ? 0 : Integer.parseInt(nameAndMeta[1]); String[] data = nameAndMeta[0].split(":"); Item item = Item.REGISTRY.getObject(new ResourceLocation(data[0], data[1])); if(item == null) { return null; } return new ItemStack(item, 1, meta); } private Config() { } }
package dk.itu.kelvin.store; // General utilities import java.util.ArrayList; import java.util.List; import java.util.Properties; // Models import dk.itu.kelvin.model.Element; import dk.itu.kelvin.model.Way; import dk.itu.kelvin.model.Relation; import dk.itu.kelvin.model.BoundingBox; import dk.itu.kelvin.model.Node; // Utilities import dk.itu.kelvin.util.SpatialIndex; import dk.itu.kelvin.util.PointTree; import dk.itu.kelvin.util.RectangleTree; import dk.itu.kelvin.util.WeightedGraph; /** * Common store for storing all elements in the chart. */ public final class ElementStore extends Store<Element, SpatialIndex.Bounds> { /** * UID for identifying serialized objects. */ private static final long serialVersionUID = 3081; /** * Weighted graph for all carRoads. */ private final WeightedGraph<Node, Way> carGraph; /** * Weighted graph for all roads. */ private final WeightedGraph<Node, Way> bicycleGraph; /** * A list for all land elements. */ private List<Way> land = new ArrayList<>(); /** * A list for all way elements. */ private List<Way> ways = new ArrayList<>(); /** * A list for all road elements. */ private List<Way> roads = new ArrayList<>(); /** * A list for all cycleways elements. */ private List<Way> cycleways = new ArrayList<>(); /** * A list for all transportWays elements. */ private List<Way> transportWays = new ArrayList<>(); /** * A list for all water elements. */ private List<Relation> relations = new ArrayList<>(); /** * A list for all Points Of Interest. */ private List<Node> pois = new ArrayList<>(); /** * A list for all bounds. */ private BoundingBox bounds; /** * Point tree for quick search in node elements. */ private transient SpatialIndex<Node> poiTree; /** * Rectangle tree for quick search in way elements. */ private transient SpatialIndex<Way> waysTree; /** * Rectangle tree for quick search in land elements. */ private transient SpatialIndex<Way> landTree; /** * Rectangle tree for quick search in way elements. */ private transient SpatialIndex<Relation> relationsTree; /** * Rectangle tree for quick search in road elements. */ private transient SpatialIndex<Way> roadsTree; /** * Point tree for quick search in cycleways elements. */ private transient SpatialIndex<Way> cyclewaysTree; /** * Point tree for quick search in transportWays elements. */ private transient RectangleTree<Way> transportWaysTree; /** * Indicates whether waysTree needs to be indexed or not. */ private transient boolean waysIsDirty; /** * Indicates whether roadsTree needs to be indexed or not. */ private transient boolean roadsIsDirty; /** * Indicates whether roadsTree needs to be indexed or not. */ private transient boolean cyclewaysIsDirty; /** * Indicates whether landsTree needs to be indexed or not. */ private transient boolean landIsDirty; /** * Indicates whether relationsTree needs to be indexed or not. */ private transient boolean relationsIsDirty; /** * Indicates whether poiTree needs to be indexed or not. */ private transient boolean poiIsDirty; /** * Initialize a new element store. */ public ElementStore() { Properties carProperties = new Properties(); carProperties.setProperty("bicycle", "no"); Properties bicycleProperties = new Properties(); bicycleProperties.setProperty("bicycle", "yes"); this.carGraph = new WeightedGraph<>(carProperties); this.bicycleGraph = new WeightedGraph<>(bicycleProperties); } /** * Adds a way element to the associated list. * * @param w The element to be added. */ public void add(final Way w) { String highway = w.tag("highway"); String cycleway = w.tag("cycleway"); String bicycleRoad = w.tag("bicycle_road"); if (highway != null) { switch (highway) { case "motorway": case "trunk": case "primary": case "secondary": case "tertiary": case "unclassified": case "residential": case "service": case "motorway_link": case "trunk_link": case "primary_link": case "secondary_link": case "tertiary_link": case "living_street": case "road": this.roads.add(w); this.transportWays.add(w); this.addEdge(w); this.roadsIsDirty = true; break; case "cycleway": this.cycleways.add(w); this.transportWays.add(w); this.addEdge(w); this.cyclewaysIsDirty = true; break; default: break; } } else if (cycleway != null) { switch (cycleway) { case "lane": case "opposite": case "opposite_lane": case "track": case "opposite_track": case "share_busway": case "shared_lane": this.cycleways.add(w); this.transportWays.add(w); this.addEdge(w); this.cyclewaysIsDirty = true; break; default: break; } } else if (bicycleRoad != null) { switch (bicycleRoad) { case "yes": this.cycleways.add(w); this.transportWays.add(w); this.addEdge(w); this.cyclewaysIsDirty = true; break; default: break; } } else { this.ways.add(w); this.waysIsDirty = true; } } /** * Accessor to carGraph. * @return A graph for to shortest path for cars. */ public WeightedGraph<Node, Way> carGraph() { return this.carGraph; } /** * Accessor to bicycleGraph. * @return A graph for to shortest path for bicycles. */ public WeightedGraph<Node, Way> bycicleGraph() { return this.bicycleGraph; } /** * Adds a land element to the associated list. * * @param l the land element to be added. */ public void addLand(final Way l) { this.land.add(l); this.landIsDirty = true; } /** * Adds a relations element to the associated collection. * @param r the relation element. */ public void add(final Relation r) { this.relations.add(r); this.relationsIsDirty = true; } /** * Adds bound element to the associated collection. * @param b the relation element. */ public void add(final BoundingBox b) { this.bounds = b; } /** * Adds POI element to the associated collection. * @param n The node object which represent a POI. */ public void add(final Node n) { this.pois.add(n); this.poiIsDirty = true; } /** * Returns new search query. * @return the query object. */ public Query find() { return new Query(); } /** * Return the transportWayTree. * @return transportWaysTree. */ public RectangleTree<Way> transportWaysTree() { this.index(); return this.transportWaysTree; } /** * Finds elements that meet the criteria. * * @param q The criteria object to look up elements based on. * @return the list of elements that meet the criteria. */ private List<Element> search(final Query q) { this.index(); List<Element> elementList = new ArrayList<>(); for (String s: q.types) { switch (s) { case "transportWay": elementList.addAll(this.transportWaysTree.range(q.bounds)); break; case "way": elementList.addAll(this.waysTree.range(q.bounds)); break; case "land": elementList.addAll(this.landTree.range(q.bounds)); break; case "relation": elementList.addAll(this.relationsTree.range(q.bounds)); break; case "poi": elementList.addAll(this.poiTree.range(q.bounds, (element) -> { return element.tags().containsValue(q.tag); })); break; default: break; } } return elementList; } /** * Adds all elements of the param into a new list. * @param list the list to be added. * @return the resulting list. */ public List<Element> getElements(final List<Element> list) { List<Element> liste = new ArrayList<>(); for (Element e : list) { liste.add(e); } return liste; } /** * (Re-)build all indexes if needed. */ private void index() { if (this.waysTree == null || this.waysIsDirty) { this.waysTree = new RectangleTree<>(this.ways); this.waysIsDirty = false; } if (this.relationsTree == null || this.relationsIsDirty) { this.relationsTree = new RectangleTree<>(this.relations); this.relationsIsDirty = false; } if (this.landTree == null || this.landIsDirty) { this.landTree = new RectangleTree<>(this.land); this.landIsDirty = false; } if (this.poiTree == null || this.poiIsDirty) { this.poiTree = new PointTree<>(this.pois); this.poiIsDirty = false; } if (this.roadsTree == null || this.roadsIsDirty) { this.roadsTree = new RectangleTree<>(this.roads); this.roadsIsDirty = false; this.transportWaysTree = new RectangleTree<>(this.transportWays); this.roadsIsDirty = false; } if (this.cyclewaysTree == null || this.cyclewaysIsDirty) { this.cyclewaysTree = new RectangleTree<>(this.cycleways); this.cyclewaysIsDirty = false; this.transportWaysTree = new RectangleTree<>(this.transportWays); this.roadsIsDirty = false; } } /** * Split a way into edges and add them to graph. * @param way A way to split into edges. */ private void addEdge(final Way way) { if (way == null) { return; } this.carGraph.add(way); this.bicycleGraph.add(way); } /** * The search query object. */ public class Query { /** * Specifies object type to search for. */ private String[] types; /** * Specifies the tag to search for. */ private String tag; /** * Bounds to search for. */ private SpatialIndex.Bounds bounds; /** * Getter for type field. * @return list of types. */ public final String[] type() { return this.types; } /** * Getter for bounds field. * * @return the bounds. */ public final SpatialIndex.Bounds bounds() { return this.bounds; } /** * Adds strings to a list and adds to field. * @param type the different type strings. * @return the Query object. */ public final Query types(final String... type) { int n = type.length; this.types = new String[n]; for (int i = 0; i < n; i++) { this.types[i] = type[i]; } return this; } /** * Set the tag field. * @param tag to search for. * @return the Query object. */ public final Query tag(final String tag) { this.tag = tag; return this; } /** * Creates a bounds object and sets it in the field. * @param minX minimum x coordinate. * @param minY minimum y coordinate. * @param maxX maximum x coordinate. * @param maxY maximum y coordinate. * @return the Query object. */ public final Query bounds( final float minX, final float minY, final float maxX, final float maxY ) { this.bounds = new SpatialIndex.Bounds(minX, minY, maxX, maxY); return this; } /** * Set the bounds field. * @param b the bounds object to be set. * @return the Query object. */ public final Query bounds(final SpatialIndex.Bounds b) { this.bounds = b; return this; } /** * Gets the elements searched for. * @return list of results. */ public final List<Element> get() { return ElementStore.this.search(this); } } }
package edu.jhu.nlp.joint; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.LinkedHashSet; import java.util.List; import org.apache.commons.cli.ParseException; import org.apache.log4j.Logger; import edu.jhu.autodiff.erma.DepParseDecodeLoss.DepParseDecodeLossFactory; import edu.jhu.autodiff.erma.ErmaBp.ErmaBpPrm; import edu.jhu.autodiff.erma.ErmaObjective.BeliefsModuleFactory; import edu.jhu.autodiff.erma.ExpectedRecall.ExpectedRecallFactory; import edu.jhu.autodiff.erma.InsideOutsideDepParse; import edu.jhu.autodiff.erma.MeanSquaredError.MeanSquaredErrorFactory; import edu.jhu.gm.data.FgExampleListBuilder.CacheType; import edu.jhu.gm.decode.MbrDecoder.Loss; import edu.jhu.gm.decode.MbrDecoder.MbrDecoderPrm; import edu.jhu.gm.feat.ObsFeatureConjoiner.ObsFeatureConjoinerPrm; import edu.jhu.gm.inf.BeliefPropagation.BpScheduleType; import edu.jhu.gm.inf.BeliefPropagation.BpUpdateOrder; import edu.jhu.gm.inf.BruteForceInferencer.BruteForceInferencerPrm; import edu.jhu.gm.inf.FgInferencerFactory; import edu.jhu.gm.model.Var.VarType; import edu.jhu.gm.train.CrfTrainer.CrfTrainerPrm; import edu.jhu.gm.train.CrfTrainer.Trainer; import edu.jhu.hlt.optimize.AdaDelta; import edu.jhu.hlt.optimize.AdaDelta.AdaDeltaPrm; import edu.jhu.hlt.optimize.AdaGradComidL2; import edu.jhu.hlt.optimize.AdaGradComidL2.AdaGradComidL2Prm; import edu.jhu.hlt.optimize.AdaGradSchedule; import edu.jhu.hlt.optimize.AdaGradSchedule.AdaGradSchedulePrm; import edu.jhu.hlt.optimize.BottouSchedule; import edu.jhu.hlt.optimize.BottouSchedule.BottouSchedulePrm; import edu.jhu.hlt.optimize.MalletLBFGS; import edu.jhu.hlt.optimize.MalletLBFGS.MalletLBFGSPrm; import edu.jhu.hlt.optimize.SGD; import edu.jhu.hlt.optimize.SGD.SGDPrm; import edu.jhu.hlt.optimize.SGDFobos; import edu.jhu.hlt.optimize.SGDFobos.SGDFobosPrm; import edu.jhu.hlt.optimize.StanfordQNMinimizer; import edu.jhu.hlt.optimize.function.DifferentiableFunction; import edu.jhu.hlt.optimize.functions.L2; import edu.jhu.nlp.AnnoPipeline; import edu.jhu.nlp.Annotator; import edu.jhu.nlp.CorpusStatistics.CorpusStatisticsPrm; import edu.jhu.nlp.EvalPipeline; import edu.jhu.nlp.InformationGainFeatureTemplateSelector; import edu.jhu.nlp.InformationGainFeatureTemplateSelector.InformationGainFeatureTemplateSelectorPrm; import edu.jhu.nlp.InformationGainFeatureTemplateSelector.SrlFeatTemplates; import edu.jhu.nlp.data.simple.AnnoSentenceCollection; import edu.jhu.nlp.data.simple.CorpusHandler; import edu.jhu.nlp.depparse.DepParseFeatureExtractor.DepParseFeatureExtractorPrm; import edu.jhu.nlp.depparse.FirstOrderPruner; import edu.jhu.nlp.depparse.PosTagDistancePruner; import edu.jhu.nlp.embed.Embeddings.Scaling; import edu.jhu.nlp.embed.EmbeddingsAnnotator; import edu.jhu.nlp.embed.EmbeddingsAnnotator.EmbeddingsAnnotatorPrm; import edu.jhu.nlp.eval.DepParseEvaluator; import edu.jhu.nlp.eval.OraclePruningAccuracy; import edu.jhu.nlp.eval.RelationEvaluator; import edu.jhu.nlp.eval.SrlEvaluator; import edu.jhu.nlp.eval.SrlSelfLoops; import edu.jhu.nlp.features.TemplateLanguage; import edu.jhu.nlp.features.TemplateLanguage.AT; import edu.jhu.nlp.features.TemplateLanguage.FeatTemplate; import edu.jhu.nlp.features.TemplateReader; import edu.jhu.nlp.features.TemplateSets; import edu.jhu.nlp.features.TemplateWriter; import edu.jhu.nlp.joint.JointNlpAnnotator.InitParams; import edu.jhu.nlp.joint.JointNlpAnnotator.JointNlpAnnotatorPrm; import edu.jhu.nlp.joint.JointNlpDecoder.JointNlpDecoderPrm; import edu.jhu.nlp.joint.JointNlpEncoder.JointNlpFeatureExtractorPrm; import edu.jhu.nlp.joint.JointNlpFgExamplesBuilder.JointNlpFgExampleBuilderPrm; import edu.jhu.nlp.relations.RelationsOptions; import edu.jhu.nlp.srl.SrlFactorGraphBuilder.RoleStructure; import edu.jhu.nlp.srl.SrlFeatureExtractor.SrlFeatureExtractorPrm; import edu.jhu.nlp.tag.BrownClusterTagger; import edu.jhu.nlp.tag.BrownClusterTagger.BrownClusterTaggerPrm; import edu.jhu.prim.util.math.FastMath; import edu.jhu.util.Prng; import edu.jhu.util.Timer; import edu.jhu.util.cli.ArgParser; import edu.jhu.util.cli.Opt; import edu.jhu.util.collections.Lists; import edu.jhu.util.report.Reporter; import edu.jhu.util.report.ReporterManager; import edu.jhu.util.semiring.Algebra; import edu.jhu.util.semiring.Algebras; /** * Pipeline runner for SRL experiments. * @author mgormley * @author mmitchell */ public class JointNlpRunner { public static enum Optimizer { LBFGS, QN, SGD, ADAGRAD, ADAGRAD_COMID, ADADELTA, FOBOS, ASGD }; public enum ErmaLoss { MSE, EXPECTED_RECALL, DP_DECODE_LOSS }; public enum Inference { BRUTE_FORCE, BP }; public enum RegularizerType { L2, NONE }; public enum AlgebraType { REAL(Algebras.REAL_ALGEBRA), LOG(Algebras.LOG_SEMIRING), LOG_SIGN(Algebras.LOG_SIGN_ALGEBRA), // SHIFTED_REAL and SPLIT algebras are for testing only. SHIFTED_REAL(Algebras.SHIFTED_REAL_ALGEBRA), SPLIT(Algebras.SPLIT_ALGEBRA); private Algebra s; private AlgebraType(Algebra s) { this.s = s; } public Algebra getAlgebra() { return s; } } private static final Logger log = Logger.getLogger(JointNlpRunner.class); private static final Reporter rep = Reporter.getReporter(JointNlpRunner.class); // Options not specific to the model @Opt(name = "seed", hasArg = true, description = "Pseudo random number generator seed for everything else.") public static long seed = Prng.DEFAULT_SEED; @Opt(hasArg = true, description = "Number of threads for computation.") public static int threads = 1; @Opt(hasArg = true, description = "Whether to use a log-add table for faster computation.") public static boolean useLogAddTable = false; // Options for model IO @Opt(hasArg = true, description = "File from which to read a serialized model.") public static File modelIn = null; @Opt(hasArg = true, description = "File to which to serialize the model.") public static File modelOut = null; @Opt(hasArg = true, description = "File to which to print a human readable version of the model.") public static File printModel = null; // Options for initialization. @Opt(hasArg = true, description = "How to initialize the parameters of the model.") public static InitParams initParams = InitParams.UNIFORM; // Options for inference. @Opt(hasArg = true, description = "Type of inference method.") public static Inference inference = Inference.BP; @Opt(hasArg = true, description = "Whether to run inference in the log-domain.") public static AlgebraType algebra = AlgebraType.REAL; @Opt(hasArg = true, description = "Whether to run inference in the log-domain.") public static boolean logDomain = true; @Opt(hasArg = true, description = "The BP schedule type.") public static BpScheduleType bpSchedule = BpScheduleType.TREE_LIKE; @Opt(hasArg = true, description = "The BP update order.") public static BpUpdateOrder bpUpdateOrder = BpUpdateOrder.SEQUENTIAL; @Opt(hasArg = true, description = "The max number of BP iterations.") public static int bpMaxIterations = 1; @Opt(hasArg = true, description = "Whether to normalize the messages.") public static boolean normalizeMessages = false; @Opt(hasArg = true, description = "The maximum message residual for convergence testing.") public static double bpConvergenceThreshold = 1e-3; @Opt(hasArg = true, description = "Directory to dump debugging information for BP.") public static File bpDumpDir = null; // Options for Brown clusters. @Opt(hasArg = true, description = "Brown cluster file") public static File brownClusters = null; @Opt(hasArg = true, description = "Max length for the brown clusters") public static int bcMaxTagLength = Integer.MAX_VALUE; // Options for Embeddings. @Opt(hasArg=true, description="Path to word embeddings text file.") public static File embeddingsFile = null; @Opt(hasArg=true, description="Method for normalization of the embeddings.") public static Scaling embNorm = Scaling.L2_NORM; @Opt(hasArg=true, description="Amount to scale embeddings after normalization.") public static double embScalar = 15.0; // Options for SRL factor graph structure. @Opt(hasArg = true, description = "The structure of the Role variables.") public static RoleStructure roleStructure = RoleStructure.PREDS_GIVEN; @Opt(hasArg = true, description = "Whether Role variables with unknown predicates should be latent.") public static boolean makeUnknownPredRolesLatent = true; @Opt(hasArg = true, description = "Whether to allow a predicate to assign a role to itself. (This should be turned on for English)") public static boolean allowPredArgSelfLoops = false; @Opt(hasArg = true, description = "Whether to include factors between the sense and role variables.") public static boolean binarySenseRoleFactors = false; @Opt(hasArg = true, description = "Whether to predict predicate sense.") public static boolean predictSense = false; @Opt(hasArg = true, description = "Whether to predict predicate positions.") public static boolean predictPredPos = false; // Options for joint factor graph structure. @Opt(hasArg = true, description = "Whether to include unary factors in the model.") public static boolean unaryFactors = false; // Options for SRL feature selection. @Opt(hasArg = true, description = "Whether to do feature selection.") public static boolean featureSelection = true; @Opt(hasArg = true, description = "The number of feature bigrams to form.") public static int numFeatsToSelect = 32; @Opt(hasArg = true, description = "The max number of sentences to use for feature selection") public static int numSentsForFeatSelect = 1000; // Options for feature extraction. @Opt(hasArg = true, description = "For testing only: whether to use only the bias feature.") public static boolean biasOnly = false; @Opt(hasArg = true, description = "The value of the mod for use in the feature hashing trick. If <= 0, feature-hashing will be disabled.") public static int featureHashMod = 524288; // 2^19 // Options for SRL feature extraction. @Opt(hasArg = true, description = "Cutoff for OOV words.") public static int cutoff = 3; @Opt(hasArg = true, description = "For preprocessing: Minimum feature count for caching.") public static int featCountCutoff = 4; @Opt(hasArg = true, description = "Whether to include unsupported features.") public static boolean includeUnsupportedFeatures = false; @Opt(hasArg = true, description = "Whether to add the Simple features.") public static boolean useSimpleFeats = true; @Opt(hasArg = true, description = "Whether to add the Naradowsky features.") public static boolean useNaradFeats = true; @Opt(hasArg = true, description = "Whether to add the Zhao features.") public static boolean useZhaoFeats = true; @Opt(hasArg = true, description = "Whether to add the Bjorkelund features.") public static boolean useBjorkelundFeats = true; @Opt(hasArg = true, description = "Whether to add dependency path features.") public static boolean useLexicalDepPathFeats = false; @Opt(hasArg = true, description = "Whether to include pairs of features.") public static boolean useTemplates = false; @Opt(hasArg = true, description = "Sense feature templates.") public static String senseFeatTpls = TemplateSets.bjorkelundSenseFeatsResource; @Opt(hasArg = true, description = "Arg feature templates.") public static String argFeatTpls = TemplateSets.bjorkelundArgFeatsResource; @Opt(hasArg = true, description = "Sense feature template output file.") public static File senseFeatTplsOut = null; @Opt(hasArg = true, description = "Arg feature template output file.") public static File argFeatTplsOut = null; // Options for dependency parse factor graph structure. @Opt(hasArg = true, description = "The type of the link variables.") public static VarType linkVarType = VarType.LATENT; @Opt(hasArg = true, description = "Whether to include a projective dependency tree global factor.") public static boolean useProjDepTreeFactor = false; @Opt(hasArg = true, description = "Whether to include 2nd-order grandparent factors in the model.") public static boolean grandparentFactors = false; @Opt(hasArg = true, description = "Whether to include 2nd-order sibling factors in the model.") public static boolean siblingFactors = false; @Opt(hasArg = true, description = "Whether to exclude non-projective grandparent factors.") public static boolean excludeNonprojectiveGrandparents = true; // Options for dependency parsing pruning. @Opt(hasArg = true, description = "File from which to read a first-order pruning model.") public static File pruneModel = null; @Opt(hasArg = true, description = "Whether to prune higher-order factors via a first-order pruning model.") public static boolean pruneByModel = false; @Opt(hasArg = true, description = "Whether to prune edges with a deterministic distance-based pruning approach.") public static boolean pruneByDist = false; // Options for Dependency parser feature extraction. @Opt(hasArg = true, description = "1st-order factor feature templates.") public static String dp1FeatTpls = TemplateSets.mcdonaldDepFeatsResource; @Opt(hasArg = true, description = "2nd-order factor feature templates.") public static String dp2FeatTpls = TemplateSets.carreras07Dep2FeatsResource; @Opt(hasArg = true, description = "Whether to use SRL features for dep parsing.") public static boolean acl14DepFeats = true; @Opt(hasArg = true, description = "Whether to use the fast feature set for dep parsing.") public static boolean dpFastFeats = true; // Options for relation extraction. @Opt(hasArg = true, description = "Relation feature templates.") public static String relFeatTpls = null; // Options for data munging. @Deprecated @Opt(hasArg=true, description="Whether to normalize and clean words.") public static boolean normalizeWords = false; // Options for caching. @Opt(hasArg = true, description = "The type of cache/store to use for training/testing instances.") public static CacheType cacheType = CacheType.CACHE; @Opt(hasArg = true, description = "When caching, the maximum number of examples to keep cached in memory or -1 for SoftReference caching.") public static int maxEntriesInMemory = 100; @Opt(hasArg = true, description = "Whether to gzip an object before caching it.") public static boolean gzipCache = false; // Options for optimization. @Opt(hasArg=true, description="The optimization method to use for training.") public static Optimizer optimizer = Optimizer.LBFGS; @Opt(hasArg=true, description="The variance for the L2 regularizer.") public static double l2variance = 1.0; @Opt(hasArg=true, description="The type of regularizer.") public static RegularizerType regularizer = RegularizerType.L2; @Opt(hasArg=true, description="Max iterations for L-BFGS training.") public static int maxLbfgsIterations = 1000; @Opt(hasArg=true, description="Number of effective passes over the dataset for SGD.") public static int sgdNumPasses = 30; @Opt(hasArg=true, description="The batch size to use at each step of SGD.") public static int sgdBatchSize = 15; @Opt(hasArg=true, description="The initial learning rate for SGD.") public static double sgdInitialLr = 0.1; @Opt(hasArg=true, description="Whether to sample with replacement for SGD.") public static boolean sgdWithRepl = false; @Opt(hasArg=true, description="Whether to automatically select the learning rate.") public static boolean sgdAutoSelectLr = true; @Opt(hasArg=true, description="How many epochs between auto-select runs.") public static int sgdAutoSelecFreq = 5; @Opt(hasArg=true, description="Whether to compute the function value on iterations other than the last.") public static boolean sgdComputeValueOnNonFinalIter = true; @Opt(hasArg=true, description="Whether to do parameter averaging.") public static boolean sgdAveraging = false; @Opt(hasArg=true, description="The AdaGrad parameter for scaling the learning rate.") public static double adaGradEta = 0.1; @Opt(hasArg=true, description="The constant addend for AdaGrad.") public static double adaGradConstantAddend = 1e-9; @Opt(hasArg=true, description="The decay rate for AdaDelta.") public static double adaDeltaDecayRate = 0.95; @Opt(hasArg=true, description="The constant addend for AdaDelta.") public static double adaDeltaConstantAddend = Math.pow(Math.E, -6.); @Opt(hasArg=true, description="Stop training by this date/time.") public static Date stopTrainingBy = null; // Options for training. @Opt(hasArg=true, description="Whether to use the mean squared error instead of conditional log-likelihood when evaluating training quality.") public static boolean useMseForValue = false; @Opt(hasArg=true, description="The type of trainer to use (e.g. conditional log-likelihood, ERMA).") public static Trainer trainer = Trainer.CLL; // Options for training a dependency parser with ERMA. @Opt(hasArg=true, description="The start temperature for the softmax MBR decoder for dependency parsing.") public static double dpStartTemp = 10; @Opt(hasArg=true, description="The end temperature for the softmax MBR decoder for dependency parsing.") public static double dpEndTemp = .1; @Opt(hasArg=true, description="Whether to transition from MSE to the softmax MBR decoder with expected recall.") public static boolean dpAnnealMse = true; @Opt(hasArg=true, description="Whether to transition from MSE to the softmax MBR decoder with expected recall.") public static ErmaLoss dpLoss = ErmaLoss.DP_DECODE_LOSS; public JointNlpRunner() { } public void run() throws ParseException, IOException { Timer t = new Timer(); t.start(); FastMath.useLogAddTable = useLogAddTable; if (useLogAddTable) { log.warn("Using log-add table instead of exact computation. When using global factors, this may result in numerical instability."); } if (stopTrainingBy != null && new Date().after(stopTrainingBy)) { log.warn("Training will never begin since stopTrainingBy has already happened: " + stopTrainingBy); log.warn("Ignoring stopTrainingBy by setting it to null."); stopTrainingBy = null; } // Initialize the data reader/writer. CorpusHandler corpus = new CorpusHandler(); // Get a model. if (modelIn == null && !corpus.hasTrain()) { throw new ParseException("Either --modelIn or --train must be specified."); } JointNlpAnnotatorPrm prm = getJointNlpAnnotatorPrm(); if (modelIn == null && corpus.hasTrain()) { // Feature selection. // TODO: Move feature selection into the pipeline. featureSelection(corpus.getTrainGold(), prm.buPrm.fePrm); } AnnoPipeline anno = new AnnoPipeline(); EvalPipeline eval = new EvalPipeline(); JointNlpAnnotator jointAnno = new JointNlpAnnotator(prm); if (modelIn != null) { jointAnno.loadModel(modelIn); } { // Add Brown clusters. if (brownClusters != null) { anno.add(new Annotator() { @Override public void annotate(AnnoSentenceCollection sents) { log.info("Adding Brown clusters."); BrownClusterTagger bct = new BrownClusterTagger(getBrownCluterTaggerPrm()); bct.read(brownClusters); bct.annotate(sents); log.info("Brown cluster hit rate: " + bct.getHitRate()); } }); } else { log.info("No Brown clusters file specified."); } // Add word embeddings. if (embeddingsFile != null) { anno.add(new Annotator() { @Override public void annotate(AnnoSentenceCollection sents) { log.info("Adding word embeddings."); EmbeddingsAnnotator ea = new EmbeddingsAnnotator(getEmbeddingsAnnotatorPrm()); ea.annotate(sents); log.info("Embeddings hit rate: " + ea.getHitRate()); } }); } else { log.info("No embeddings file specified."); } if (pruneByDist) { // Prune via the distance-based pruner. anno.add(new PosTagDistancePruner()); } if (pruneByModel) { if (pruneModel == null) { throw new IllegalStateException("If pruneEdges is true, pruneModel must be specified."); } anno.add(new FirstOrderPruner(pruneModel, getSrlFgExampleBuilderPrm(null), getDecoderPrm())); } // Various NLP annotations. anno.add(jointAnno); } { if (pruneByDist || pruneByModel) { eval.add(new OraclePruningAccuracy()); } if (CorpusHandler.getGoldOnlyAts().contains(AT.DEP_TREE)) { eval.add(new DepParseEvaluator()); } if (CorpusHandler.getGoldOnlyAts().contains(AT.SRL)) { eval.add(new SrlSelfLoops()); eval.add(new SrlEvaluator()); } if (CorpusHandler.getGoldOnlyAts().contains(AT.REL_LABELS)) { eval.add(new RelationEvaluator()); } } AnnoSentenceCollection devGold = null; AnnoSentenceCollection devInput = null; if (corpus.hasTrain()) { String name = "train"; AnnoSentenceCollection trainGold = corpus.getTrainGold(); AnnoSentenceCollection trainInput = corpus.getTrainInput(); // (Dev data might be null.) devGold = corpus.getDevGold(); devInput = corpus.getDevInput(); // Train a model. (The PipelineAnnotator also annotates all the input.) anno.train(trainInput, trainGold, devInput, devGold); // Decode and evaluate the train data. corpus.writeTrainPreds(trainInput); eval.evaluate(trainInput, trainGold, name); corpus.clearTrainCache(); if (modelOut != null) { jointAnno.saveModel(modelOut); } if (printModel != null) { jointAnno.printModel(printModel); } } if (corpus.hasDev()) { // Write dev data predictions. String name = "dev"; if (devInput == null) { // Train did not yet annotate the dev data. devInput = corpus.getDevInput(); anno.annotate(devInput); } corpus.writeDevPreds(devInput); // Evaluate dev data. devGold = corpus.getDevGold(); eval.evaluate(devInput, devGold, name); corpus.clearDevCache(); } if (corpus.hasTest()) { // Decode test data. String name = "test"; AnnoSentenceCollection testInput = corpus.getTestInput(); anno.annotate(testInput); corpus.writeTestPreds(testInput); // Evaluate test data. AnnoSentenceCollection testGold = corpus.getTestGold(); eval.evaluate(testInput, testGold, name); corpus.clearTestCache(); } t.stop(); rep.report("elapsedSec", t.totSec()); } /** * Do feature selection and update fePrm with the chosen feature templates. */ private void featureSelection(AnnoSentenceCollection sents, JointNlpFeatureExtractorPrm fePrm) throws IOException, ParseException { SrlFeatureExtractorPrm srlFePrm = fePrm.srlFePrm; // Remove annotation types from the features which are explicitly excluded. removeAts(fePrm); if (useTemplates && featureSelection) { CorpusStatisticsPrm csPrm = getCorpusStatisticsPrm(); InformationGainFeatureTemplateSelectorPrm prm = new InformationGainFeatureTemplateSelectorPrm(); prm.featureHashMod = featureHashMod; prm.numThreads = threads; prm.numToSelect = numFeatsToSelect; prm.maxNumSentences = numSentsForFeatSelect; prm.selectSense = predictSense; SrlFeatTemplates sft = new SrlFeatTemplates(srlFePrm.fePrm.soloTemplates, srlFePrm.fePrm.pairTemplates, null); InformationGainFeatureTemplateSelector ig = new InformationGainFeatureTemplateSelector(prm); sft = ig.getFeatTemplatesForSrl(sents, csPrm, sft); ig.shutdown(); srlFePrm.fePrm.soloTemplates = sft.srlSense; srlFePrm.fePrm.pairTemplates = sft.srlArg; } if (CorpusHandler.getGoldOnlyAts().contains(AT.SRL) && acl14DepFeats) { fePrm.dpFePrm.firstOrderTpls = srlFePrm.fePrm.pairTemplates; } if (useTemplates) { log.info("Num sense feature templates: " + srlFePrm.fePrm.soloTemplates.size()); log.info("Num arg feature templates: " + srlFePrm.fePrm.pairTemplates.size()); if (senseFeatTplsOut != null) { TemplateWriter.write(senseFeatTplsOut, srlFePrm.fePrm.soloTemplates); } if (argFeatTplsOut != null) { TemplateWriter.write(argFeatTplsOut, srlFePrm.fePrm.pairTemplates); } } } private void removeAts(JointNlpEncoder.JointNlpFeatureExtractorPrm fePrm) { List<AT> ats = Lists.union(CorpusHandler.getRemoveAts(), CorpusHandler.getPredAts()); if (brownClusters == null) { // Filter out the Brown cluster features. log.warn("Filtering out Brown cluster features."); ats.add(AT.BROWN); } for (AT at : ats) { fePrm.srlFePrm.fePrm.soloTemplates = TemplateLanguage.filterOutRequiring(fePrm.srlFePrm.fePrm.soloTemplates, at); fePrm.srlFePrm.fePrm.pairTemplates = TemplateLanguage.filterOutRequiring(fePrm.srlFePrm.fePrm.pairTemplates, at); fePrm.dpFePrm.firstOrderTpls = TemplateLanguage.filterOutRequiring(fePrm.dpFePrm.firstOrderTpls, at); fePrm.dpFePrm.secondOrderTpls = TemplateLanguage.filterOutRequiring(fePrm.dpFePrm.secondOrderTpls, at); } } private static JointNlpAnnotatorPrm getJointNlpAnnotatorPrm() throws ParseException { JointNlpAnnotatorPrm prm = new JointNlpAnnotatorPrm(); prm.crfPrm = getCrfTrainerPrm(); prm.csPrm = getCorpusStatisticsPrm(); prm.dePrm = getDecoderPrm(); prm.initParams = initParams; prm.ofcPrm = getObsFeatureConjoinerPrm(); JointNlpFeatureExtractorPrm fePrm = getJointNlpFeatureExtractorPrm(); prm.buPrm = getSrlFgExampleBuilderPrm(fePrm); return prm; } private static JointNlpFgExampleBuilderPrm getSrlFgExampleBuilderPrm(JointNlpEncoder.JointNlpFeatureExtractorPrm fePrm) { JointNlpFgExampleBuilderPrm prm = new JointNlpFgExampleBuilderPrm(); // Factor graph structure. prm.fgPrm.dpPrm.linkVarType = linkVarType; prm.fgPrm.dpPrm.useProjDepTreeFactor = useProjDepTreeFactor; prm.fgPrm.dpPrm.unaryFactors = unaryFactors; prm.fgPrm.dpPrm.excludeNonprojectiveGrandparents = excludeNonprojectiveGrandparents; prm.fgPrm.dpPrm.grandparentFactors = grandparentFactors; prm.fgPrm.dpPrm.siblingFactors = siblingFactors; prm.fgPrm.dpPrm.pruneEdges = pruneByDist || pruneByModel; prm.fgPrm.srlPrm.makeUnknownPredRolesLatent = makeUnknownPredRolesLatent; prm.fgPrm.srlPrm.roleStructure = roleStructure; prm.fgPrm.srlPrm.allowPredArgSelfLoops = allowPredArgSelfLoops; prm.fgPrm.srlPrm.unaryFactors = unaryFactors; prm.fgPrm.srlPrm.binarySenseRoleFactors = binarySenseRoleFactors; prm.fgPrm.srlPrm.predictSense = predictSense; prm.fgPrm.srlPrm.predictPredPos = predictPredPos; // Relation Feature extraction. if (CorpusHandler.getGoldOnlyAts().contains(AT.REL_LABELS)) { if (relFeatTpls != null) { prm.fgPrm.relPrm.templates = getFeatTpls(relFeatTpls); } prm.fgPrm.relPrm.featureHashMod = featureHashMod; } prm.fgPrm.includeDp = CorpusHandler.getGoldOnlyAts().contains(AT.DEP_TREE); prm.fgPrm.includeSrl = CorpusHandler.getGoldOnlyAts().contains(AT.SRL); prm.fgPrm.includeRel = CorpusHandler.getGoldOnlyAts().contains(AT.REL_LABELS); // Feature extraction. prm.fePrm = fePrm; // Example construction and storage. prm.exPrm.cacheType = cacheType; prm.exPrm.gzipped = gzipCache; prm.exPrm.maxEntriesInMemory = maxEntriesInMemory; return prm; } private static ObsFeatureConjoinerPrm getObsFeatureConjoinerPrm() { ObsFeatureConjoinerPrm prm = new ObsFeatureConjoinerPrm(); prm.featCountCutoff = featCountCutoff; prm.includeUnsupportedFeatures = includeUnsupportedFeatures; return prm; } private static JointNlpFeatureExtractorPrm getJointNlpFeatureExtractorPrm() { // SRL Feature Extraction. SrlFeatureExtractorPrm srlFePrm = new SrlFeatureExtractorPrm(); srlFePrm.fePrm.biasOnly = biasOnly; srlFePrm.fePrm.useSimpleFeats = useSimpleFeats; srlFePrm.fePrm.useNaradFeats = useNaradFeats; srlFePrm.fePrm.useZhaoFeats = useZhaoFeats; srlFePrm.fePrm.useBjorkelundFeats = useBjorkelundFeats; srlFePrm.fePrm.useLexicalDepPathFeats = useLexicalDepPathFeats; srlFePrm.fePrm.useTemplates = useTemplates; srlFePrm.fePrm.soloTemplates = getFeatTpls(senseFeatTpls); srlFePrm.fePrm.pairTemplates = getFeatTpls(argFeatTpls); srlFePrm.featureHashMod = featureHashMod; // Dependency parsing Feature Extraction DepParseFeatureExtractorPrm dpFePrm = new DepParseFeatureExtractorPrm(); dpFePrm.biasOnly = biasOnly; dpFePrm.firstOrderTpls = getFeatTpls(dp1FeatTpls); dpFePrm.secondOrderTpls = getFeatTpls(dp2FeatTpls); dpFePrm.featureHashMod = featureHashMod; if (CorpusHandler.getGoldOnlyAts().contains(AT.SRL) && acl14DepFeats) { // This special case is only for historical consistency. dpFePrm.onlyTrueBias = false; dpFePrm.onlyTrueEdges = false; } dpFePrm.onlyFast = dpFastFeats; JointNlpFeatureExtractorPrm fePrm = new JointNlpFeatureExtractorPrm(); fePrm.srlFePrm = srlFePrm; fePrm.dpFePrm = dpFePrm; return fePrm; } /** * Gets feature templates from multiple files or resources. * @param featTpls A colon separated list of paths to feature template files or resources. * @return The feature templates from all the paths. */ private static List<FeatTemplate> getFeatTpls(String featTpls) { Collection<FeatTemplate> tpls = new LinkedHashSet<FeatTemplate>(); TemplateReader tr = new TemplateReader(); for (String path : featTpls.split(":")) { if (path.equals("coarse1") || path.equals("coarse2")) { List<FeatTemplate> coarseUnigramSet; if (path.equals("coarse1")) { coarseUnigramSet = TemplateSets.getCoarseUnigramSet1(); } else if (path.equals("coarse2")) { coarseUnigramSet = TemplateSets.getCoarseUnigramSet2(); } else { throw new IllegalStateException(); } tpls.addAll(coarseUnigramSet); } else { try { tr.readFromFile(path); } catch (IOException e) { try { tr.readFromResource(path); } catch (IOException e1) { throw new IllegalStateException("Unable to read templates as file or resource: " + path, e1); } } } } tpls.addAll(tr.getTemplates()); return new ArrayList<FeatTemplate>(tpls); } private static CorpusStatisticsPrm getCorpusStatisticsPrm() { CorpusStatisticsPrm prm = new CorpusStatisticsPrm(); prm.cutoff = cutoff; prm.language = CorpusHandler.language; prm.useGoldSyntax = CorpusHandler.useGoldSyntax; prm.normalizeWords = normalizeWords; return prm; } private static CrfTrainerPrm getCrfTrainerPrm() throws ParseException { FgInferencerFactory infPrm = getInfFactory(); CrfTrainerPrm prm = new CrfTrainerPrm(); prm.infFactory = infPrm; if (infPrm instanceof BeliefsModuleFactory) { // TODO: This is a temporary hack to which assumes we always use ErmaBp. prm.bFactory = (BeliefsModuleFactory) infPrm; } if (optimizer == Optimizer.LBFGS) { prm.optimizer = getMalletLbfgs(); prm.batchOptimizer = null; } else if (optimizer == Optimizer.QN) { prm.optimizer = getStanfordLbfgs(); prm.batchOptimizer = null; } else if (optimizer == Optimizer.SGD || optimizer == Optimizer.ASGD || optimizer == Optimizer.ADAGRAD || optimizer == Optimizer.ADADELTA) { prm.optimizer = null; SGDPrm sgdPrm = getSgdPrm(); if (optimizer == Optimizer.SGD){ BottouSchedulePrm boPrm = new BottouSchedulePrm(); boPrm.initialLr = sgdInitialLr; boPrm.lambda = 1.0 / l2variance; sgdPrm.sched = new BottouSchedule(boPrm); } else if (optimizer == Optimizer.ASGD){ BottouSchedulePrm boPrm = new BottouSchedulePrm(); boPrm.initialLr = sgdInitialLr; boPrm.lambda = 1.0 / l2variance; boPrm.power = 0.75; sgdPrm.sched = new BottouSchedule(boPrm); sgdPrm.averaging = true; } else if (optimizer == Optimizer.ADAGRAD){ AdaGradSchedulePrm adaGradPrm = new AdaGradSchedulePrm(); adaGradPrm.eta = adaGradEta; adaGradPrm.constantAddend = adaDeltaConstantAddend; sgdPrm.sched = new AdaGradSchedule(adaGradPrm); } else if (optimizer == Optimizer.ADADELTA){ AdaDeltaPrm adaDeltaPrm = new AdaDeltaPrm(); adaDeltaPrm.decayRate = adaDeltaDecayRate; adaDeltaPrm.constantAddend = adaDeltaConstantAddend; sgdPrm.sched = new AdaDelta(adaDeltaPrm); sgdPrm.autoSelectLr = false; } prm.batchOptimizer = new SGD(sgdPrm); } else if (optimizer == Optimizer.ADAGRAD_COMID) { AdaGradComidL2Prm sgdPrm = new AdaGradComidL2Prm(); setSgdPrm(sgdPrm); //TODO: sgdPrm.l1Lambda = l2Lambda; sgdPrm.l2Lambda = 1.0 / l2variance; sgdPrm.eta = adaGradEta; sgdPrm.constantAddend = adaDeltaConstantAddend; sgdPrm.sched = null; prm.optimizer = null; prm.batchOptimizer = new AdaGradComidL2(sgdPrm); } else if (optimizer == Optimizer.FOBOS) { SGDFobosPrm sgdPrm = new SGDFobosPrm(); setSgdPrm(sgdPrm); //TODO: sgdPrm.l1Lambda = l2Lambda; sgdPrm.l2Lambda = 1.0 / l2variance; BottouSchedulePrm boPrm = new BottouSchedulePrm(); boPrm.initialLr = sgdInitialLr; boPrm.lambda = 1.0 / l2variance; sgdPrm.sched = new BottouSchedule(boPrm); prm.optimizer = null; prm.batchOptimizer = new SGDFobos(sgdPrm); } else { throw new RuntimeException("Optimizer not supported: " + optimizer); } if (regularizer == RegularizerType.L2) { prm.regularizer = new L2(l2variance); } else if (regularizer == RegularizerType.NONE) { prm.regularizer = null; } else { throw new ParseException("Unsupported regularizer: " + regularizer); } prm.numThreads = threads; prm.useMseForValue = useMseForValue; prm.trainer = trainer; // TODO: add options for other loss functions. if (prm.trainer == Trainer.ERMA && CorpusHandler.getPredAts().equals(Lists.getList(AT.DEP_TREE))) { if (dpLoss == ErmaLoss.DP_DECODE_LOSS) { DepParseDecodeLossFactory lossPrm = new DepParseDecodeLossFactory(); lossPrm.annealMse = dpAnnealMse; lossPrm.startTemp = dpStartTemp; lossPrm.endTemp = dpEndTemp; prm.dlFactory = lossPrm; } else if (dpLoss == ErmaLoss.MSE) { prm.dlFactory = new MeanSquaredErrorFactory(); } else if (dpLoss == ErmaLoss.EXPECTED_RECALL) { prm.dlFactory = new ExpectedRecallFactory(); } } return prm; } private static edu.jhu.hlt.optimize.Optimizer<DifferentiableFunction> getMalletLbfgs() { MalletLBFGSPrm prm = new MalletLBFGSPrm(); prm.maxIterations = maxLbfgsIterations; return new MalletLBFGS(prm); } private static edu.jhu.hlt.optimize.Optimizer<DifferentiableFunction> getStanfordLbfgs() { return new StanfordQNMinimizer(maxLbfgsIterations); } private static SGDPrm getSgdPrm() { SGDPrm prm = new SGDPrm(); setSgdPrm(prm); return prm; } private static void setSgdPrm(SGDPrm prm) { prm.numPasses = sgdNumPasses; prm.batchSize = sgdBatchSize; prm.withReplacement = sgdWithRepl; prm.stopBy = stopTrainingBy; prm.autoSelectLr = sgdAutoSelectLr; prm.autoSelectFreq = sgdAutoSelecFreq; prm.computeValueOnNonFinalIter = sgdComputeValueOnNonFinalIter; prm.averaging = sgdAveraging; // Make sure we correctly set the schedule somewhere else. prm.sched = null; } private static FgInferencerFactory getInfFactory() throws ParseException { if (inference == Inference.BRUTE_FORCE) { BruteForceInferencerPrm prm = new BruteForceInferencerPrm(algebra.getAlgebra()); return prm; } else if (inference == Inference.BP) { ErmaBpPrm bpPrm = new ErmaBpPrm(); bpPrm.logDomain = logDomain; bpPrm.s = algebra.getAlgebra(); bpPrm.schedule = bpSchedule; bpPrm.updateOrder = bpUpdateOrder; bpPrm.normalizeMessages = normalizeMessages; bpPrm.maxIterations = bpMaxIterations; bpPrm.convergenceThreshold = bpConvergenceThreshold; bpPrm.keepTape = (trainer == Trainer.ERMA); if (bpDumpDir != null) { bpPrm.dumpDir = Paths.get(bpDumpDir.getAbsolutePath()); } return bpPrm; } else { throw new ParseException("Unsupported inference method: " + inference); } } private static JointNlpDecoderPrm getDecoderPrm() throws ParseException { MbrDecoderPrm mbrPrm = new MbrDecoderPrm(); mbrPrm.infFactory = getInfFactory(); mbrPrm.loss = Loss.L1; JointNlpDecoderPrm prm = new JointNlpDecoderPrm(); prm.mbrPrm = mbrPrm; return prm; } private static BrownClusterTaggerPrm getBrownCluterTaggerPrm() { BrownClusterTaggerPrm bcPrm = new BrownClusterTaggerPrm(); bcPrm.language = CorpusHandler.language; bcPrm.maxTagLength = bcMaxTagLength; return bcPrm; } private static EmbeddingsAnnotatorPrm getEmbeddingsAnnotatorPrm() { EmbeddingsAnnotatorPrm prm = new EmbeddingsAnnotatorPrm(); prm.embeddingsFile = embeddingsFile; prm.embNorm = embNorm; prm.embScalar= embScalar; return prm; } public static void main(String[] args) { int exitCode = 0; ArgParser parser = null; try { parser = new ArgParser(JointNlpRunner.class); parser.addClass(JointNlpRunner.class); parser.addClass(CorpusHandler.class); parser.addClass(RelationsOptions.class); parser.addClass(InsideOutsideDepParse.class); parser.addClass(ReporterManager.class); parser.parseArgs(args); ReporterManager.init(ReporterManager.reportOut, true); Prng.seed(seed); JointNlpRunner pipeline = new JointNlpRunner(); pipeline.run(); } catch (ParseException e1) { log.error(e1.getMessage()); if (parser != null) { parser.printUsage(); } exitCode = 1; } catch (Throwable t) { t.printStackTrace(); exitCode = 1; } finally { ReporterManager.close(); } System.exit(exitCode); } }
package edu.jhu.srl; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.log4j.Logger; import edu.jhu.data.concrete.SimpleAnnoSentenceCollection; import edu.jhu.data.conll.CoNLL09FileReader; import edu.jhu.data.conll.CoNLL09Sentence; import edu.jhu.data.conll.SrlGraph; import edu.jhu.data.conll.SrlGraph.SrlEdge; import edu.jhu.featurize.SentFeatureExtractor; import edu.jhu.featurize.SentFeatureExtractor.SentFeatureExtractorPrm; import edu.jhu.gm.Feature; import edu.jhu.gm.FeatureExtractor; import edu.jhu.gm.FgExample; import edu.jhu.gm.FgExamples; import edu.jhu.gm.ProjDepTreeFactor.LinkVar; import edu.jhu.gm.Var.VarType; import edu.jhu.gm.VarConfig; import edu.jhu.srl.SrlFactorGraph.RoleVar; import edu.jhu.srl.SrlFactorGraph.SrlFactorGraphPrm; import edu.jhu.srl.SrlFeatureExtractor.SrlFeatureExtractorPrm; import edu.jhu.util.Alphabet; import edu.jhu.util.CountingAlphabet; /** * Factory for FgExamples. * * @author mgormley * @author mmitchell */ public class SrlFgExamplesBuilder { public static class SrlFgExampleBuilderPrm { /* These provide default values during testing; otherwise, * values should be defined by SrlRunner. */ public SrlFactorGraphPrm fgPrm = new SrlFactorGraphPrm(); public SentFeatureExtractorPrm fePrm = new SentFeatureExtractorPrm(); public SrlFeatureExtractorPrm srlFePrm = new SrlFeatureExtractorPrm(); /** Whether to include unsupported features. */ public boolean includeUnsupportedFeatures = false; /** * Minimum number of times (inclusive) a feature must occur in training * to be included in the model. Ignored if non-positive. (Using this * cutoff implies that unsupported features will not be included.) */ public int featCountCutoff = -1; } private static final Logger log = Logger.getLogger(SrlFgExamplesBuilder.class); private SrlFgExampleBuilderPrm prm; private Alphabet<Feature> alphabet; private CorpusStatistics cs; public SrlFgExamplesBuilder(SrlFgExampleBuilderPrm prm, Alphabet<Feature> alphabet, CorpusStatistics cs) { this.prm = prm; this.alphabet = alphabet; this.cs = cs; } public FgExamples getData(SimpleAnnoSentenceCollection sents) { throw new RuntimeException("Not implemented"); } public FgExamples getData(CoNLL09FileReader reader) { List<CoNLL09Sentence> sents = reader.readAll(); return getData(sents); } public void preprocess(List<CoNLL09Sentence> sents) { if (!(alphabet.isGrowing() && prm.featCountCutoff > 0)) { // Skip this preprocessing step since it will have no effect. return; } CountingAlphabet<Feature> counter = new CountingAlphabet<Feature>(); Alphabet<String> obsAlphabet = new Alphabet<String>(); List<FeatureExtractor> featExts = new ArrayList<FeatureExtractor>(); for (int i=0; i<sents.size(); i++) { CoNLL09Sentence sent = sents.get(i); if (i % 1000 == 0 && i > 0) { log.debug("Preprocessed " + i + " examples..."); } // Precompute a few things. SrlGraph srlGraph = sent.getSrlGraph(); Set<Integer> knownPreds = getKnownPreds(srlGraph); // Construct the factor graph. SrlFactorGraph sfg = new SrlFactorGraph(prm.fgPrm, sent.size(), knownPreds, cs.roleStateNames); // Get the variable assignments given in the training data. VarConfig trainConfig = getTrainAssignment(sent, srlGraph, sfg); FgExample ex = new FgExample(sfg, trainConfig); // Create a feature extractor for this example. SentFeatureExtractor sentFeatExt = new SentFeatureExtractor(prm.fePrm, sent, cs, obsAlphabet); FeatureExtractor featExtractor = new SrlFeatureExtractor(prm.srlFePrm, sfg, counter, sentFeatExt); // So we don't have to compute the features again for this example. featExts.add(featExtractor); // Cache only the features observed in training data. ex.cacheLatFeats(sfg, trainConfig, featExtractor); } for (int i=0; i<counter.size(); i++) { int count = counter.lookupObjectCount(i); Feature feat = counter.lookupObject(i); if (count >= prm.featCountCutoff || feat.isBiasFeature()) { alphabet.lookupIndex(feat); } } alphabet.stopGrowth(); } public FgExamples getData(List<CoNLL09Sentence> sents) { preprocess(sents); Alphabet<String> obsAlphabet = new Alphabet<String>(); List<FeatureExtractor> featExts = new ArrayList<FeatureExtractor>(); FgExamples data = new FgExamples(alphabet); for (int i=0; i<sents.size(); i++) { CoNLL09Sentence sent = sents.get(i); if (i % 1000 == 0 && i > 0) { log.debug("Built " + i + " examples..."); } // Precompute a few things. SrlGraph srlGraph = sent.getSrlGraph(); Set<Integer> knownPreds = getKnownPreds(srlGraph); // Construct the factor graph. SrlFactorGraph sfg = new SrlFactorGraph(prm.fgPrm, sent.size(), knownPreds, cs.roleStateNames); // Get the variable assignments given in the training data. VarConfig trainConfig = getTrainAssignment(sent, srlGraph, sfg); FgExample ex = new FgExample(sfg, trainConfig); // Create a feature extractor for this example. SentFeatureExtractor sentFeatExt = new SentFeatureExtractor(prm.fePrm, sent, cs, obsAlphabet); FeatureExtractor featExtractor = new SrlFeatureExtractor(prm.srlFePrm, sfg, alphabet, sentFeatExt); // So we don't have to compute the features again for this example. featExts.add(featExtractor); // Cache only the features observed in training data. ex.cacheLatFeats(sfg, trainConfig, featExtractor); data.add(ex); } if (!prm.includeUnsupportedFeatures) { alphabet.stopGrowth(); } // Cache features for all the other variable assignments. for (int i=0; i<data.size(); i++) { if (i % 1000 == 0 && i > 0) { log.debug("Cached features for " + i + " examples..."); } FgExample ex = data.get(i); CoNLL09Sentence sent = sents.get(i); SrlGraph srlGraph = sent.getSrlGraph(); SrlFactorGraph sfg = (SrlFactorGraph) ex.getOriginalFactorGraph(); VarConfig trainConfig = getTrainAssignment(sent, srlGraph, sfg); FeatureExtractor featExtractor = featExts.get(i); ex.cacheLatPredFeats(sfg, trainConfig, featExtractor); } log.info("Num observation functions: " + obsAlphabet.size()); data.setSourceSentences(sents); return data; } private static Set<Integer> getKnownPreds(SrlGraph srlGraph) { List<SrlEdge> srlEdges = srlGraph.getEdges(); Set<Integer> knownPreds = new HashSet<Integer>(); // All the "Y"s for (SrlEdge e : srlEdges) { Integer a = e.getPred().getPosition(); knownPreds.add(a); } return knownPreds; } private VarConfig getTrainAssignment(CoNLL09Sentence sent, SrlGraph srlGraph, SrlFactorGraph sfg) { VarConfig vc = new VarConfig(); // Add all the training data assignments to the link variables, if they are not latent. // IMPORTANT NOTE: We include the case where the parent is the Wall node (position -1). int[] parents = cs.prm.useGoldSyntax ? sent.getParentsFromHead() : sent.getParentsFromPhead(); for (int i=-1; i<sent.size(); i++) { for (int j=0; j<sent.size(); j++) { if (j != i && sfg.getLinkVar(i, j) != null) { LinkVar linkVar = sfg.getLinkVar(i, j); if (linkVar.getType() != VarType.LATENT) { // Syntactic head, from dependency parse. int state; if (parents[j] != i) { state = LinkVar.FALSE; } else { state = LinkVar.TRUE; } vc.put(linkVar, state); } } } } // Add all the training data assignments to the role variables, if they are not latent. // First, just set all the role names to "_". for (int i=0; i<sent.size(); i++) { for (int j=0; j<sent.size(); j++) { RoleVar roleVar = sfg.getRoleVar(i, j); if (roleVar != null && roleVar.getType() != VarType.LATENT) { vc.put(roleVar, "_"); } } } // Then set the ones which are observed. for (SrlEdge edge : srlGraph.getEdges()) { int parent = edge.getPred().getPosition(); int child = edge.getArg().getPosition(); String roleName = edge.getLabel(); RoleVar roleVar = sfg.getRoleVar(parent, child); if (roleVar != null && roleVar.getType() != VarType.LATENT) { int roleNameIdx = roleVar.getState(roleName); // TODO: This isn't quite right...we should really store the actual role name here. if (roleNameIdx == -1) { vc.put(roleVar, CorpusStatistics.UNKNOWN_ROLE); } else { vc.put(roleVar, roleNameIdx); } } } return vc; } }
package main.java.engine.objects.tower; import java.awt.geom.Point2D; import java.io.Serializable; import java.util.Map; import main.java.engine.objects.TDObject; import main.java.engine.objects.monster.Monster; import main.java.engine.objects.projectile.Bomb; import main.java.engine.objects.projectile.DamageProjectile; import main.java.engine.objects.projectile.FreezeProjectile; import main.java.schema.tdobjects.TowerSchema; /** * * Towers that do not aim at particular monster(s) * but just shoot in all direction * */ public class SplashTower extends ShootingTower { public SplashTower(ITower baseTower, Map<String, Serializable> attributes) { super(baseTower, attributes); } @Override public void fireProjectile (double angle) { for (int i = 0; i < Bomb.BOMB_SPRAY_X.length; i++) { new DamageProjectile( ((SimpleTower) baseTower).centerCoordinate().getX(), ((SimpleTower) baseTower).centerCoordinate().getY(), Bomb.BOMB_SPRAY_X[i], Bomb.BOMB_SPRAY_Y[i], myDamage, myBulletImage); } } }
package gov.nasa.jpl.mbee; import java.util.ArrayList; import java.util.List; import gov.nasa.jpl.mbee.actions.systemsreasoner.CreateInstanceAction; import gov.nasa.jpl.mbee.actions.systemsreasoner.DespecializeAction; import gov.nasa.jpl.mbee.actions.systemsreasoner.SRAction; import gov.nasa.jpl.mbee.actions.systemsreasoner.ValidateAction; import gov.nasa.jpl.mbee.actions.systemsreasoner.SpecializeAction; import com.nomagic.actions.ActionsCategory; import com.nomagic.actions.ActionsManager; import com.nomagic.actions.NMAction; import com.nomagic.magicdraw.actions.ActionsGroups; import com.nomagic.magicdraw.actions.BrowserContextAMConfigurator; import com.nomagic.magicdraw.actions.DiagramContextAMConfigurator; import com.nomagic.magicdraw.actions.MDAction; import com.nomagic.magicdraw.actions.MDActionsCategory; import com.nomagic.magicdraw.ui.browser.Node; import com.nomagic.magicdraw.ui.browser.Tree; import com.nomagic.magicdraw.uml.symbols.DiagramPresentationElement; import com.nomagic.magicdraw.uml.symbols.PresentationElement; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Classifier; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Element; public class SRConfigurator implements BrowserContextAMConfigurator, DiagramContextAMConfigurator { ValidateAction validateAction = null; SpecializeAction specAction = null; DespecializeAction despecAction = null; //CopyAction copyAction = null; CreateInstanceAction instAction = null; @Override public int getPriority() { return 0; //medium } @Override public void configure(ActionsManager manager, Tree tree) { final List<Element> elements = new ArrayList<Element>(); for (final Node n : tree.getSelectedNodes()) { if (n.getUserObject() instanceof Element) { elements.add((Element) n.getUserObject()); } } configure(manager, elements); } @Override public void configure(ActionsManager manager, DiagramPresentationElement diagram, PresentationElement[] selected, PresentationElement requestor) { final List<Element> elements = new ArrayList<Element>(); for (final PresentationElement pe : selected) { if (pe.getElement() != null) { elements.add(pe.getElement()); } } configure(manager, elements); } protected void configure(ActionsManager manager, List<Element> elements) { // refresh the actions for every new click (or selection) validateAction = null; specAction = null; despecAction = null; //copyAction = null; instAction = null; ActionsCategory category = (ActionsCategory)manager.getActionFor("SRMain"); if (category == null) { category = new MDActionsCategory("SRMain", "Systems Reasoner", null, ActionsGroups.APPLICATION_RELATED); category.setNested(true); //manager.addCategory(0, category); } manager.removeCategory(category); if (elements.size() > 1) { category = handleMultipleNodes(category, manager, elements); } else if (elements.size() == 1) { category = handleSingleNode(category, manager, elements.get(0)); } else { return; } if (category == null) { return; } manager.addCategory(0, category); category.addAction(validateAction); category.addAction(specAction); category.addAction(despecAction); //category.addAction(copyAction); category.addAction(instAction); // Clear out the category of unused actions for (NMAction s: category.getActions()) { if (s == null) category.removeAction(s); } category.setUseActionForDisable(true); if (category.getActions().isEmpty()) { final MDAction mda = new MDAction(null, null, null, "null"); mda.updateState(); mda.setEnabled(false); category.addAction(mda); } } public ActionsCategory handleMultipleNodes(ActionsCategory category, ActionsManager manager, List<Element> elements) { ArrayList<Classifier> classes = new ArrayList<Classifier>(); for (Element element : elements) { if (element != null) { if (element instanceof Classifier) { classes.add((Classifier) element); } } } // if nothing in classes, disable category and return it if (classes.isEmpty()) { //category = disableCategory(category); return null; } // otherwise, add the classes to the ValidateAction action validateAction = new ValidateAction(classes); // if any of the classifiers are not editable, disable the validate for (Classifier clf: classes) { if (!(clf.isEditable())) { validateAction.disable(); } } // add the action to the actions category category.addAction(validateAction); specAction = new SpecializeAction(classes); category.addAction(specAction); despecAction = new DespecializeAction(classes); category.addAction(despecAction); return category; } public ActionsCategory handleSingleNode(ActionsCategory category, ActionsManager manager, Element element) { if (element == null) return null; // Disable all if not editable target, add error message if (!(element.isEditable())) { category = disableCategory(category); return category; } //copyAction = new CopyAction(target); // check target instanceof /*if (target instanceof Activity) { Activity active = (Activity) target; copyAction = new CopyAction(active); }*/ if (element instanceof Classifier) { Classifier classifier = (Classifier) element; validateAction = new ValidateAction(classifier); specAction = new SpecializeAction(classifier); despecAction = new DespecializeAction(classifier); //copyAction = new CopyAction(clazz); instAction = new CreateInstanceAction(classifier); if (classifier.getGeneralization().isEmpty()) { despecAction.disable("No Generalizations"); } } else { return null; } /*if (target instanceof Classifier) { Classifier clazzifier = (Classifier) target; copyAction = new CopyAction(clazzifier); }*/ return category; } public static ActionsCategory disableCategory(ActionsCategory category) { // once all the categories are disabled, the action category will be disabled // this is defined in the configure method: category.setNested(true); for (NMAction s: category.getActions()) { SRAction sra = (SRAction) s; sra.disable("Not Editable"); } return category; } }
package hudson.plugins.ec2; import java.io.IOException; import java.io.PrintStream; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import hudson.util.Secret; import jenkins.model.Jenkins; import jenkins.model.JenkinsLocationConfiguration; import jenkins.slaves.iterators.api.NodeIterator; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang.StringUtils; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.model.*; import hudson.Extension; import hudson.Util; import hudson.model.*; import hudson.model.Descriptor.FormException; import hudson.model.labels.LabelAtom; import hudson.plugins.ec2.util.DeviceMappingParser; import hudson.util.FormValidation; import hudson.util.ListBoxModel; /** * Template of {@link EC2AbstractSlave} to launch. * * @author Kohsuke Kawaguchi */ public class SlaveTemplate implements Describable<SlaveTemplate> { private static final Logger LOGGER = Logger.getLogger(SlaveTemplate.class.getName()); public String ami; public final String description; public final String zone; public final SpotConfiguration spotConfig; public final String securityGroups; public final String remoteFS; public final InstanceType type; public final boolean ebsOptimized; public final boolean monitoring; public final String labels; public final Node.Mode mode; public final String initScript; public final String tmpDir; public final String userData; public final String numExecutors; public final String remoteAdmin; public final String jvmopts; public final String subnetId; public final String idleTerminationMinutes; public final String iamInstanceProfile; public final boolean deleteRootOnTermination; public final boolean useEphemeralDevices; public final String customDeviceMapping; public int instanceCap; public final boolean stopOnTerminate; private final List<EC2Tag> tags; public final boolean usePrivateDnsName; public final boolean associatePublicIp; protected transient EC2Cloud parent; public final boolean useDedicatedTenancy; public AMITypeData amiType; public int launchTimeout; public boolean connectBySSHProcess; public final boolean connectUsingPublicIp; private transient/* almost final */Set<LabelAtom> labelSet; private transient/* almost final */Set<String> securityGroupSet; /* * Necessary to handle reading from old configurations. The UnixData object is created in readResolve() */ @Deprecated public transient String sshPort; @Deprecated public transient String rootCommandPrefix; @Deprecated public transient String slaveCommandPrefix; @DataBoundConstructor public SlaveTemplate(String ami, String zone, SpotConfiguration spotConfig, String securityGroups, String remoteFS, InstanceType type, boolean ebsOptimized, String labelString, Node.Mode mode, String description, String initScript, String tmpDir, String userData, String numExecutors, String remoteAdmin, AMITypeData amiType, String jvmopts, boolean stopOnTerminate, String subnetId, List<EC2Tag> tags, String idleTerminationMinutes, boolean usePrivateDnsName, String instanceCapStr, String iamInstanceProfile, boolean deleteRootOnTermination, boolean useEphemeralDevices, boolean useDedicatedTenancy, String launchTimeoutStr, boolean associatePublicIp, String customDeviceMapping, boolean connectBySSHProcess, boolean connectUsingPublicIp, boolean monitoring) { if(StringUtils.isNotBlank(remoteAdmin) || StringUtils.isNotBlank(jvmopts) || StringUtils.isNotBlank(tmpDir)){ LOGGER.log(Level.FINE, "As remoteAdmin, jvmopts or tmpDir is not blank, we must ensure the user has RUN_SCRIPTS rights."); Jenkins j = Jenkins.getInstance(); if(j != null){ j.checkPermission(Jenkins.RUN_SCRIPTS); } } this.ami = ami; this.zone = zone; this.spotConfig = spotConfig; this.securityGroups = securityGroups; this.remoteFS = remoteFS; this.amiType = amiType; this.type = type; this.ebsOptimized = ebsOptimized; this.labels = Util.fixNull(labelString); this.mode = mode != null ? mode : Node.Mode.NORMAL; this.description = description; this.initScript = initScript; this.tmpDir = tmpDir; this.userData = StringUtils.trimToEmpty(userData); this.numExecutors = Util.fixNull(numExecutors).trim(); this.remoteAdmin = remoteAdmin; this.jvmopts = jvmopts; this.stopOnTerminate = stopOnTerminate; this.subnetId = subnetId; this.tags = tags; this.idleTerminationMinutes = idleTerminationMinutes; this.usePrivateDnsName = usePrivateDnsName; this.associatePublicIp = associatePublicIp; this.connectUsingPublicIp = connectUsingPublicIp; this.useDedicatedTenancy = useDedicatedTenancy; this.connectBySSHProcess = connectBySSHProcess; this.monitoring = monitoring; if (null == instanceCapStr || instanceCapStr.isEmpty()) { this.instanceCap = Integer.MAX_VALUE; } else { this.instanceCap = Integer.parseInt(instanceCapStr); } try { this.launchTimeout = Integer.parseInt(launchTimeoutStr); } catch (NumberFormatException nfe) { this.launchTimeout = Integer.MAX_VALUE; } this.iamInstanceProfile = iamInstanceProfile; this.deleteRootOnTermination = deleteRootOnTermination; this.useEphemeralDevices = useEphemeralDevices; this.customDeviceMapping = customDeviceMapping; readResolve(); // initialize } public SlaveTemplate(String ami, String zone, SpotConfiguration spotConfig, String securityGroups, String remoteFS, InstanceType type, boolean ebsOptimized, String labelString, Node.Mode mode, String description, String initScript, String tmpDir, String userData, String numExecutors, String remoteAdmin, AMITypeData amiType, String jvmopts, boolean stopOnTerminate, String subnetId, List<EC2Tag> tags, String idleTerminationMinutes, boolean usePrivateDnsName, String instanceCapStr, String iamInstanceProfile, boolean deleteRootOnTermination, boolean useEphemeralDevices, boolean useDedicatedTenancy, String launchTimeoutStr, boolean associatePublicIp, String customDeviceMapping, boolean connectBySSHProcess, boolean connectUsingPublicIp) { this(ami, zone, spotConfig, securityGroups, remoteFS, type, ebsOptimized, labelString, mode, description, initScript, tmpDir, userData, numExecutors, remoteAdmin, amiType, jvmopts, stopOnTerminate, subnetId, tags, idleTerminationMinutes, usePrivateDnsName, instanceCapStr, iamInstanceProfile, false, useEphemeralDevices, useDedicatedTenancy, launchTimeoutStr, associatePublicIp, customDeviceMapping, connectBySSHProcess, connectUsingPublicIp, false); } public SlaveTemplate(String ami, String zone, SpotConfiguration spotConfig, String securityGroups, String remoteFS, InstanceType type, boolean ebsOptimized, String labelString, Node.Mode mode, String description, String initScript, String tmpDir, String userData, String numExecutors, String remoteAdmin, AMITypeData amiType, String jvmopts, boolean stopOnTerminate, String subnetId, List<EC2Tag> tags, String idleTerminationMinutes, boolean usePrivateDnsName, String instanceCapStr, String iamInstanceProfile, boolean useEphemeralDevices, boolean useDedicatedTenancy, String launchTimeoutStr, boolean associatePublicIp, String customDeviceMapping, boolean connectBySSHProcess) { this(ami, zone, spotConfig, securityGroups, remoteFS, type, ebsOptimized, labelString, mode, description, initScript, tmpDir, userData, numExecutors, remoteAdmin, amiType, jvmopts, stopOnTerminate, subnetId, tags, idleTerminationMinutes, usePrivateDnsName, instanceCapStr, iamInstanceProfile, false, useEphemeralDevices, useDedicatedTenancy, launchTimeoutStr, associatePublicIp, customDeviceMapping, connectBySSHProcess, false); } public SlaveTemplate(String ami, String zone, SpotConfiguration spotConfig, String securityGroups, String remoteFS, InstanceType type, boolean ebsOptimized, String labelString, Node.Mode mode, String description, String initScript, String tmpDir, String userData, String numExecutors, String remoteAdmin, AMITypeData amiType, String jvmopts, boolean stopOnTerminate, String subnetId, List<EC2Tag> tags, String idleTerminationMinutes, boolean usePrivateDnsName, String instanceCapStr, String iamInstanceProfile, boolean useEphemeralDevices, boolean useDedicatedTenancy, String launchTimeoutStr, boolean associatePublicIp, String customDeviceMapping) { this(ami, zone, spotConfig, securityGroups, remoteFS, type, ebsOptimized, labelString, mode, description, initScript, tmpDir, userData, numExecutors, remoteAdmin, amiType, jvmopts, stopOnTerminate, subnetId, tags, idleTerminationMinutes, usePrivateDnsName, instanceCapStr, iamInstanceProfile, useEphemeralDevices, useDedicatedTenancy, launchTimeoutStr, associatePublicIp, customDeviceMapping, false); } /** * Backward compatible constructor for reloading previous version data */ public SlaveTemplate(String ami, String zone, SpotConfiguration spotConfig, String securityGroups, String remoteFS, String sshPort, InstanceType type, boolean ebsOptimized, String labelString, Node.Mode mode, String description, String initScript, String tmpDir, String userData, String numExecutors, String remoteAdmin, String rootCommandPrefix, String slaveCommandPrefix, String jvmopts, boolean stopOnTerminate, String subnetId, List<EC2Tag> tags, String idleTerminationMinutes, boolean usePrivateDnsName, String instanceCapStr, String iamInstanceProfile, boolean useEphemeralDevices, String launchTimeoutStr) { this(ami, zone, spotConfig, securityGroups, remoteFS, type, ebsOptimized, labelString, mode, description, initScript, tmpDir, userData, numExecutors, remoteAdmin, new UnixData(rootCommandPrefix, slaveCommandPrefix, sshPort), jvmopts, stopOnTerminate, subnetId, tags, idleTerminationMinutes, usePrivateDnsName, instanceCapStr, iamInstanceProfile, useEphemeralDevices, false, launchTimeoutStr, false, null); } public boolean isConnectBySSHProcess() { // See // src/main/resources/hudson/plugins/ec2/SlaveTemplate/help-connectBySSHProcess.html return connectBySSHProcess; } public EC2Cloud getParent() { return parent; } public String getLabelString() { return labels; } public Node.Mode getMode() { return mode; } public String getDisplayName() { return description + " (" + ami + ")"; } String getZone() { return zone; } public String getSecurityGroupString() { return securityGroups; } public Set<String> getSecurityGroupSet() { return securityGroupSet; } public Set<String> parseSecurityGroups() { if (securityGroups == null || "".equals(securityGroups.trim())) { return Collections.emptySet(); } else { return new HashSet<String>(Arrays.asList(securityGroups.split("\\s*,\\s*"))); } } public int getNumExecutors() { try { return Integer.parseInt(numExecutors); } catch (NumberFormatException e) { return EC2AbstractSlave.toNumExecutors(type); } } public int getSshPort() { try { String sshPort = ""; if (amiType.isUnix()) { sshPort = ((UnixData) amiType).getSshPort(); } return Integer.parseInt(sshPort); } catch (NumberFormatException e) { return 22; } } public String getRemoteAdmin() { return remoteAdmin; } public String getRootCommandPrefix() { return amiType.isUnix() ? ((UnixData) amiType).getRootCommandPrefix() : ""; } public String getSlaveCommandPrefix() { return amiType.isUnix() ? ((UnixData) amiType).getSlaveCommandPrefix() : ""; } public String getSubnetId() { return subnetId; } public boolean getAssociatePublicIp() { return associatePublicIp; } public boolean isConnectUsingPublicIp() { return connectUsingPublicIp; } public List<EC2Tag> getTags() { if (null == tags) return null; return Collections.unmodifiableList(tags); } public String getidleTerminationMinutes() { return idleTerminationMinutes; } public boolean getUseDedicatedTenancy() { return useDedicatedTenancy; } public Set<LabelAtom> getLabelSet() { return labelSet; } public String getAmi() { return ami; } public void setAmi(String ami) { this.ami = ami; } public AMITypeData getAmiType() { return amiType; } public void setAmiType(AMITypeData amiType) { this.amiType = amiType; } public int getInstanceCap() { return instanceCap; } public String getInstanceCapStr() { if (instanceCap == Integer.MAX_VALUE) { return ""; } else { return String.valueOf(instanceCap); } } public String getSpotMaxBidPrice() { if (spotConfig == null) return null; return SpotConfiguration.normalizeBid(spotConfig.spotMaxBidPrice); } public String getIamInstanceProfile() { return iamInstanceProfile; } @Override public String toString() { return "SlaveTemplate{" + "ami='" + ami + '\'' + ", labels='" + labels + '\'' + '}'; } public enum ProvisionOptions { ALLOW_CREATE, FORCE_CREATE } /** * Provisions a new EC2 slave or starts a previously stopped on-demand instance. * * @return always non-null. This needs to be then added to {@link Hudson#addNode(Node)}. */ public List<EC2AbstractSlave> provision(int number, EnumSet<ProvisionOptions> provisionOptions) throws AmazonClientException, IOException { if (this.spotConfig != null) { if (provisionOptions.contains(ProvisionOptions.ALLOW_CREATE) || provisionOptions.contains(ProvisionOptions.FORCE_CREATE)) return provisionSpot(number); return null; } return provisionOndemand(number, provisionOptions); } /** * Safely we can pickup only instance that is not known by Jenkins at all. */ private boolean checkInstance(Instance instance) { for (EC2AbstractSlave node : NodeIterator.nodes(EC2AbstractSlave.class)) { if (node.getInstanceId().equals(instance.getInstanceId())) { logInstanceCheck(instance, ". false - found existing corresponding Jenkins slave: " + node.getInstanceId()); return false; } } logInstanceCheck(instance, " true - Instance is not connected to Jenkins"); return true; } private void logInstanceCheck(Instance instance, String message) { logProvisionInfo("checkInstance: " + instance.getInstanceId() + "." + message); } private boolean isSameIamInstanceProfile(Instance instance) { return StringUtils.isBlank(getIamInstanceProfile()) || (instance.getIamInstanceProfile() != null && instance.getIamInstanceProfile().getArn().equals(getIamInstanceProfile())); } private boolean isTerminatingOrShuttindDown(String instanceStateName) { return instanceStateName.equalsIgnoreCase(InstanceStateName.Terminated.toString()) || instanceStateName.equalsIgnoreCase(InstanceStateName.ShuttingDown.toString()); } private void logProvisionInfo(String message) { LOGGER.info(this + ". " + message); } private HashSet<Tag> getCustomInstanceTags(String ec2SlaveType, List<Filter> diFilters){ boolean hasCustomTypeTag = false; boolean hasJenkinsServerUrlTag = false; HashSet<Tag> instTags = null; if (tags != null && !tags.isEmpty()) { instTags = new HashSet<Tag>(); for (EC2Tag t : tags) { instTags.add(new Tag(t.getName(), t.getValue())); if (diFilters != null){ diFilters.add(new Filter("tag:" + t.getName()).withValues(t.getValue())); } if (StringUtils.equals(t.getName(), EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE)) { hasCustomTypeTag = true; } if (StringUtils.equals(t.getName(), EC2Tag.TAG_NAME_JENKINS_SERVER_URL)) { hasJenkinsServerUrlTag = true; } } } if (!hasCustomTypeTag) { if (instTags == null) { instTags = new HashSet<Tag>(); } // Append template description as well to identify slaves provisioned per template instTags.add(new Tag(EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE, EC2Cloud.getSlaveTypeTagValue(ec2SlaveType, description))); } if (!hasJenkinsServerUrlTag) { if (instTags == null) { instTags = new HashSet<Tag>(); } // Append jenkins server url to identify slaves provisioned per jenkins server instTags.add(new Tag(EC2Tag.TAG_NAME_JENKINS_SERVER_URL, JenkinsLocationConfiguration.get().getUrl())); } return instTags; } /** * Provisions an On-demand EC2 slave by launching a new instance or starting a previously-stopped instance. */ private List<EC2AbstractSlave> provisionOndemand(int number, EnumSet<ProvisionOptions> provisionOptions) throws AmazonClientException, IOException { AmazonEC2 ec2 = getParent().connect(); logProvisionInfo("Considering launching"); RunInstancesRequest riRequest = new RunInstancesRequest(ami, 1, number).withInstanceType(type); riRequest.setEbsOptimized(ebsOptimized); riRequest.setMonitoring(monitoring); setupBlockDeviceMappings(riRequest.getBlockDeviceMappings()); if(stopOnTerminate){ riRequest.setInstanceInitiatedShutdownBehavior(ShutdownBehavior.Stop); logProvisionInfo("Setting Instance Initiated Shutdown Behavior : ShutdownBehavior.Stop"); }else{ riRequest.setInstanceInitiatedShutdownBehavior(ShutdownBehavior.Terminate); logProvisionInfo("Setting Instance Initiated Shutdown Behavior : ShutdownBehavior.Terminate"); } List<Filter> diFilters = new ArrayList<Filter>(); diFilters.add(new Filter("image-id").withValues(ami)); diFilters.add(new Filter("instance-type").withValues(type.toString())); KeyPair keyPair = getKeyPair(ec2); riRequest.setUserData(Base64.encodeBase64String(userData.getBytes(StandardCharsets.UTF_8))); riRequest.setKeyName(keyPair.getKeyName()); diFilters.add(new Filter("key-name").withValues(keyPair.getKeyName())); if (StringUtils.isNotBlank(getZone())) { Placement placement = new Placement(getZone()); if (getUseDedicatedTenancy()) { placement.setTenancy("dedicated"); } riRequest.setPlacement(placement); diFilters.add(new Filter("availability-zone").withValues(getZone())); } InstanceNetworkInterfaceSpecification net = new InstanceNetworkInterfaceSpecification(); if (StringUtils.isNotBlank(getSubnetId())) { if (getAssociatePublicIp()) { net.setSubnetId(getSubnetId()); } else { riRequest.setSubnetId(getSubnetId()); } diFilters.add(new Filter("subnet-id").withValues(getSubnetId())); /* * If we have a subnet ID then we can only use VPC security groups */ if (!securityGroupSet.isEmpty()) { List<String> groupIds = getEc2SecurityGroups(ec2); HashSet<Tag> instTags = getCustomInstanceTags(EC2Cloud.EC2_SLAVE_TYPE_DEMAND, diFilters); } } if (getAssociatePublicIp()) { net.setAssociatePublicIpAddress(true); net.setDeviceIndex(0); riRequest.withNetworkInterfaces(net); } HashSet<Tag> instTags = buildTags(EC2Cloud.EC2_SLAVE_TYPE_DEMAND); for (Tag tag : instTags) { diFilters.add(new Filter("tag:" + tag.getKey()).withValues(tag.getValue())); } DescribeInstancesRequest diRequest = new DescribeInstancesRequest(); diRequest.setFilters(diFilters); logProvisionInfo("Looking for existing instances with describe-instance: " + diRequest); DescribeInstancesResult diResult = ec2.describeInstances(diRequest); List<Instance> orphans = findOrphans(diResult, number); if (orphans.isEmpty() && !provisionOptions.contains(ProvisionOptions.FORCE_CREATE) && !provisionOptions.contains(ProvisionOptions.ALLOW_CREATE)) { logProvisionInfo("No existing instance found - but cannot create new instance"); return null; } wakeOrphansUp(ec2, orphans); if (orphans.size() == number) { return toSlaves(orphans); } riRequest.setMaxCount(number - orphans.size()); if (StringUtils.isNotBlank(getIamInstanceProfile())) { riRequest.setIamInstanceProfile(new IamInstanceProfileSpecification().withArn(getIamInstanceProfile())); } TagSpecification tagSpecification = new TagSpecification(); tagSpecification.setResourceType(ResourceType.Instance); tagSpecification.setTags(instTags); Set<TagSpecification> tagSpecifications = Collections.singleton(tagSpecification); riRequest.setTagSpecifications(tagSpecifications); // Have to create a new instance List<Instance> newInstances = ec2.runInstances(riRequest).getReservation().getInstances(); if (newInstances.isEmpty()) { logProvisionInfo("No new instances were created"); } newInstances.addAll(orphans); return toSlaves(newInstances); } private void wakeOrphansUp(AmazonEC2 ec2, List<Instance> orphans) { List<String> instances = new ArrayList<>(); for(Instance instance : orphans) { if (instance.getState().getName().equalsIgnoreCase(InstanceStateName.Stopping.toString()) || instance.getState().getName().equalsIgnoreCase(InstanceStateName.Stopped.toString())) { logProvisionInfo("Found stopped instances - will start it: " + instance); instances.add(instance.getInstanceId()); } else { // Should be pending or running at this point, just let it come up logProvisionInfo("Found existing pending or running: " + instance.getState().getName() + " instance: " + instance); } } if (!instances.isEmpty()) { StartInstancesRequest siRequest = new StartInstancesRequest(instances); StartInstancesResult siResult = ec2.startInstances(siRequest); logProvisionInfo("Result of starting stopped instances:" + siResult); } } private List<EC2AbstractSlave> toSlaves(List<Instance> newInstances) throws IOException { try { List<EC2AbstractSlave> slaves = new ArrayList<>(newInstances.size()); for (Instance instance : newInstances) { slaves.add(newOndemandSlave(instance)); logProvisionInfo("Return instance: " + instance); } return slaves; } catch (FormException e) { throw new AssertionError(e); // we should have discovered all // configuration issues upfront } } private List<Instance> findOrphans(DescribeInstancesResult diResult, int number) { List<Instance> orphans = new ArrayList<>(); int count = 0; for (Reservation reservation : diResult.getReservations()) { for (Instance instance : reservation.getInstances()) { if (!isSameIamInstanceProfile(instance)) { logInstanceCheck(instance, ". false - IAM Instance profile does not match: " + instance.getIamInstanceProfile()); continue; } if (isTerminatingOrShuttindDown(instance.getState().getName())) { logInstanceCheck(instance, ". false - Instance is terminated or shutting down"); continue; } if (checkInstance(instance)) { logProvisionInfo("Found existing instance: " + instance); orphans.add(instance); count++; } if (count == number) { return orphans; } } } return orphans; } private void setupRootDevice(List<BlockDeviceMapping> deviceMappings) { if (deleteRootOnTermination && getImage().getRootDeviceType().equals("ebs")) { // get the root device (only one expected in the blockmappings) final List<BlockDeviceMapping> rootDeviceMappings = getAmiBlockDeviceMappings(); BlockDeviceMapping rootMapping = null; for (final BlockDeviceMapping deviceMapping : rootDeviceMappings) { System.out.println("AMI had " + deviceMapping.getDeviceName()); System.out.println(deviceMapping.getEbs()); rootMapping = deviceMapping; break; } // Check if the root device is already in the mapping and update it for (final BlockDeviceMapping mapping : deviceMappings) { System.out.println("Request had " + mapping.getDeviceName()); if (rootMapping.getDeviceName().equals(mapping.getDeviceName())) { mapping.getEbs().setDeleteOnTermination(Boolean.TRUE); return; } } // Create a shadow of the AMI mapping (doesn't like reusing rootMapping directly) BlockDeviceMapping newMapping = new BlockDeviceMapping().withDeviceName(rootMapping.getDeviceName()); EbsBlockDevice newEbs = new EbsBlockDevice(); newEbs.setDeleteOnTermination(Boolean.TRUE); newMapping.setEbs(newEbs); deviceMappings.add(0, newMapping); } } private List<BlockDeviceMapping> getNewEphemeralDeviceMapping() { final List<BlockDeviceMapping> oldDeviceMapping = getAmiBlockDeviceMappings(); final Set<String> occupiedDevices = new HashSet<String>(); for (final BlockDeviceMapping mapping : oldDeviceMapping) { occupiedDevices.add(mapping.getDeviceName()); } final List<String> available = new ArrayList<String>( Arrays.asList("ephemeral0", "ephemeral1", "ephemeral2", "ephemeral3")); final List<BlockDeviceMapping> newDeviceMapping = new ArrayList<BlockDeviceMapping>(4); for (char suffix = 'b'; suffix <= 'z' && !available.isEmpty(); suffix++) { final String deviceName = String.format("/dev/xvd%s", suffix); if (occupiedDevices.contains(deviceName)) continue; final BlockDeviceMapping newMapping = new BlockDeviceMapping().withDeviceName(deviceName).withVirtualName( available.get(0)); newDeviceMapping.add(newMapping); available.remove(0); } return newDeviceMapping; } private void setupEphemeralDeviceMapping(List<BlockDeviceMapping> deviceMappings) { // Don't wipe out pre-existing mappings deviceMappings.addAll(getNewEphemeralDeviceMapping()); } private List<BlockDeviceMapping> getAmiBlockDeviceMappings() { return getImage().getBlockDeviceMappings(); } private Image getImage() { DescribeImagesRequest request = new DescribeImagesRequest().withImageIds(ami); for (final Image image : getParent().connect().describeImages(request).getImages()) { if (ami.equals(image.getImageId())) { return image; } } throw new AmazonClientException("Unable to find AMI " + ami); } private void setupCustomDeviceMapping(List<BlockDeviceMapping> deviceMappings) { if (StringUtils.isNotBlank(customDeviceMapping)) { deviceMappings.addAll(DeviceMappingParser.parse(customDeviceMapping)); } } /** * Provision a new slave for an EC2 spot instance to call back to Jenkins */ private List<EC2AbstractSlave> provisionSpot(int number) throws AmazonClientException, IOException { AmazonEC2 ec2 = getParent().connect(); try { LOGGER.info("Launching " + ami + " for template " + description); KeyPair keyPair = getKeyPair(ec2); RequestSpotInstancesRequest spotRequest = new RequestSpotInstancesRequest(); // Validate spot bid before making the request if (getSpotMaxBidPrice() == null) { throw new AmazonClientException("Invalid Spot price specified: " + getSpotMaxBidPrice()); } spotRequest.setSpotPrice(getSpotMaxBidPrice()); spotRequest.setInstanceCount(number); LaunchSpecification launchSpecification = new LaunchSpecification(); launchSpecification.setImageId(ami); launchSpecification.setInstanceType(type); launchSpecification.setEbsOptimized(ebsOptimized); launchSpecification.setMonitoringEnabled(monitoring); if (StringUtils.isNotBlank(getZone())) { SpotPlacement placement = new SpotPlacement(getZone()); launchSpecification.setPlacement(placement); } InstanceNetworkInterfaceSpecification net = new InstanceNetworkInterfaceSpecification(); if (StringUtils.isNotBlank(getSubnetId())) { if (getAssociatePublicIp()) { net.setSubnetId(getSubnetId()); } else { launchSpecification.setSubnetId(getSubnetId()); } /* * If we have a subnet ID then we can only use VPC security groups */ if (!securityGroupSet.isEmpty()) { List<String> groupIds = getEc2SecurityGroups(ec2); if (!groupIds.isEmpty()) { if (getAssociatePublicIp()) { net.setGroups(groupIds); } else { ArrayList<GroupIdentifier> groups = new ArrayList<GroupIdentifier>(); for (String group_id : groupIds) { GroupIdentifier group = new GroupIdentifier(); group.setGroupId(group_id); groups.add(group); } if (!groups.isEmpty()) launchSpecification.setAllSecurityGroups(groups); } } } } else { /* No subnet: we can use standard security groups by name */ if (!securityGroupSet.isEmpty()) { launchSpecification.setSecurityGroups(securityGroupSet); } } String userDataString = Base64.encodeBase64String(userData.getBytes(StandardCharsets.UTF_8)); launchSpecification.setUserData(userDataString); launchSpecification.setKeyName(keyPair.getKeyName()); launchSpecification.setInstanceType(type.toString()); if (getAssociatePublicIp()) { net.setAssociatePublicIpAddress(true); net.setDeviceIndex(0); launchSpecification.withNetworkInterfaces(net); } HashSet<Tag> instTags = getCustomInstanceTags(EC2Cloud.EC2_SLAVE_TYPE_SPOT, null); if (StringUtils.isNotBlank(getIamInstanceProfile())) { launchSpecification.setIamInstanceProfile(new IamInstanceProfileSpecification().withArn(getIamInstanceProfile())); } setupBlockDeviceMappings(launchSpecification.getBlockDeviceMappings()); spotRequest.setLaunchSpecification(launchSpecification); // Make the request for a new Spot instance RequestSpotInstancesResult reqResult = ec2.requestSpotInstances(spotRequest); List<SpotInstanceRequest> reqInstances = reqResult.getSpotInstanceRequests(); if (reqInstances.isEmpty()) { throw new AmazonClientException("No spot instances found"); } List<EC2AbstractSlave> slaves = new ArrayList<>(reqInstances.size()); for(SpotInstanceRequest spotInstReq : reqInstances) { if (spotInstReq == null) { throw new AmazonClientException("Spot instance request is null"); } String slaveName = spotInstReq.getSpotInstanceRequestId(); // Now that we have our Spot request, we can set tags on it updateRemoteTags(ec2, instTags, "InvalidSpotInstanceRequestID.NotFound", spotInstReq.getSpotInstanceRequestId()); // That was a remote request - we should also update our local instance data spotInstReq.setTags(instTags); LOGGER.info("Spot instance id in provision: " + spotInstReq.getSpotInstanceRequestId()); slaves.add(newSpotSlave(spotInstReq, slaveName)); } return slaves; } catch (FormException e) { throw new AssertionError(); // we should have discovered all // configuration issues upfront } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } } private void setupBlockDeviceMappings(List<BlockDeviceMapping> blockDeviceMappings) { setupRootDevice(blockDeviceMappings); if (useEphemeralDevices) { setupEphemeralDeviceMapping(blockDeviceMappings); } else { setupCustomDeviceMapping(blockDeviceMappings); } } private HashSet<Tag> buildTags(String slaveType) { boolean hasCustomTypeTag = false; HashSet<Tag> instTags = new HashSet<Tag>(); if (tags != null && !tags.isEmpty()) { instTags = new HashSet<Tag>(); for (EC2Tag t : tags) { instTags.add(new Tag(t.getName(), t.getValue())); if (StringUtils.equals(t.getName(), EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE)) { hasCustomTypeTag = true; } } } if (!hasCustomTypeTag) { instTags.add(new Tag(EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE, EC2Cloud.getSlaveTypeTagValue( slaveType, description))); } return instTags; } protected EC2OndemandSlave newOndemandSlave(Instance inst) throws FormException, IOException { return new EC2OndemandSlave(inst.getInstanceId(), description, remoteFS, getNumExecutors(), labels, mode, initScript, tmpDir, remoteAdmin, jvmopts, stopOnTerminate, idleTerminationMinutes, inst.getPublicDnsName(), inst.getPrivateDnsName(), EC2Tag.fromAmazonTags(inst.getTags()), parent.name, usePrivateDnsName, useDedicatedTenancy, getLaunchTimeout(), amiType); } protected EC2SpotSlave newSpotSlave(SpotInstanceRequest sir, String name) throws FormException, IOException { return new EC2SpotSlave(name, sir.getSpotInstanceRequestId(), description, remoteFS, getNumExecutors(), mode, initScript, tmpDir, labels, remoteAdmin, jvmopts, idleTerminationMinutes, EC2Tag.fromAmazonTags(sir.getTags()), parent.name, usePrivateDnsName, getLaunchTimeout(), amiType); } /** * Get a KeyPair from the configured information for the slave template */ private KeyPair getKeyPair(AmazonEC2 ec2) throws IOException, AmazonClientException { KeyPair keyPair = parent.getPrivateKey().find(ec2); if (keyPair == null) { throw new AmazonClientException("No matching keypair found on EC2. Is the EC2 private key a valid one?"); } return keyPair; } /** * Update the tags stored in EC2 with the specified information. Re-try 5 times if instances isn't up by * catchErrorCode - e.g. InvalidSpotInstanceRequestID.NotFound or InvalidInstanceRequestID.NotFound * * @param ec2 * @param instTags * @param catchErrorCode * @param params * @throws InterruptedException */ private void updateRemoteTags(AmazonEC2 ec2, Collection<Tag> instTags, String catchErrorCode, String... params) throws InterruptedException { for (int i = 0; i < 5; i++) { try { CreateTagsRequest tagRequest = new CreateTagsRequest(); tagRequest.withResources(params).setTags(instTags); ec2.createTags(tagRequest); break; } catch (AmazonServiceException e) { if (e.getErrorCode().equals(catchErrorCode)) { Thread.sleep(5000); continue; } LOGGER.log(Level.SEVERE, e.getErrorMessage(), e); } } } /** * Get a list of security group ids for the slave */ private List<String> getEc2SecurityGroups(AmazonEC2 ec2) throws AmazonClientException { List<String> groupIds = new ArrayList<String>(); DescribeSecurityGroupsResult groupResult = getSecurityGroupsBy("group-name", securityGroupSet, ec2); if (groupResult.getSecurityGroups().size() == 0) { groupResult = getSecurityGroupsBy("group-id", securityGroupSet, ec2); } for (SecurityGroup group : groupResult.getSecurityGroups()) { if (group.getVpcId() != null && !group.getVpcId().isEmpty()) { List<Filter> filters = new ArrayList<Filter>(); filters.add(new Filter("vpc-id").withValues(group.getVpcId())); filters.add(new Filter("state").withValues("available")); filters.add(new Filter("subnet-id").withValues(getSubnetId())); DescribeSubnetsRequest subnetReq = new DescribeSubnetsRequest(); subnetReq.withFilters(filters); DescribeSubnetsResult subnetResult = ec2.describeSubnets(subnetReq); List<Subnet> subnets = subnetResult.getSubnets(); if (subnets != null && !subnets.isEmpty()) { groupIds.add(group.getGroupId()); } } } if (securityGroupSet.size() != groupIds.size()) { throw new AmazonClientException("Security groups must all be VPC security groups to work in a VPC context"); } return groupIds; } private DescribeSecurityGroupsResult getSecurityGroupsBy(String filterName, Set<String> filterValues, AmazonEC2 ec2) { DescribeSecurityGroupsRequest groupReq = new DescribeSecurityGroupsRequest(); groupReq.withFilters(new Filter(filterName).withValues(filterValues)); return ec2.describeSecurityGroups(groupReq); } /** * Provisions a new EC2 slave based on the currently running instance on EC2, instead of starting a new one. */ public EC2AbstractSlave attach(String instanceId, TaskListener listener) throws AmazonClientException, IOException { PrintStream logger = listener.getLogger(); AmazonEC2 ec2 = getParent().connect(); try { logger.println("Attaching to " + instanceId); LOGGER.info("Attaching to " + instanceId); DescribeInstancesRequest request = new DescribeInstancesRequest(); request.setInstanceIds(Collections.singletonList(instanceId)); Instance inst = ec2.describeInstances(request).getReservations().get(0).getInstances().get(0); return newOndemandSlave(inst); } catch (FormException e) { throw new AssertionError(); // we should have discovered all // configuration issues upfront } } /** * Initializes data structure that we don't persist. */ protected Object readResolve() { Jenkins.getInstance().checkPermission(Jenkins.RUN_SCRIPTS); labelSet = Label.parse(labels); securityGroupSet = parseSecurityGroups(); /** * In releases of this plugin prior to 1.18, template-specific instance caps could be configured but were not * enforced. As a result, it was possible to have the instance cap for a template be configured to 0 (zero) with * no ill effects. Starting with version 1.18, template-specific instance caps are enforced, so if a * configuration has a cap of zero for a template, no instances will be launched from that template. Since there * is no practical value of intentionally setting the cap to zero, this block will override such a setting to a * value that means 'no cap'. */ if (instanceCap == 0) { instanceCap = Integer.MAX_VALUE; } if (amiType == null) { amiType = new UnixData(rootCommandPrefix, slaveCommandPrefix, sshPort); } return this; } public Descriptor<SlaveTemplate> getDescriptor() { return Jenkins.getInstance().getDescriptor(getClass()); } public int getLaunchTimeout() { return launchTimeout <= 0 ? Integer.MAX_VALUE : launchTimeout; } public String getLaunchTimeoutStr() { if (launchTimeout == Integer.MAX_VALUE) { return ""; } else { return String.valueOf(launchTimeout); } } public boolean isWindowsSlave() { return amiType.isWindows(); } public boolean isUnixSlave() { return amiType.isUnix(); } public Secret getAdminPassword() { return amiType.isWindows() ? ((WindowsData) amiType).getPassword() : Secret.fromString(""); } public boolean isUseHTTPS() { return amiType.isWindows() && ((WindowsData) amiType).isUseHTTPS(); } @Extension public static final class DescriptorImpl extends Descriptor<SlaveTemplate> { @Override public String getDisplayName() { return null; } public List<Descriptor<AMITypeData>> getAMITypeDescriptors() { return Jenkins.getInstance().<AMITypeData, Descriptor<AMITypeData>> getDescriptorList(AMITypeData.class); } /** * Since this shares much of the configuration with {@link EC2Computer}, check its help page, too. */ @Override public String getHelpFile(String fieldName) { String p = super.getHelpFile(fieldName); if (p == null) p = Jenkins.getInstance().getDescriptor(EC2OndemandSlave.class).getHelpFile(fieldName); if (p == null) p = Jenkins.getInstance().getDescriptor(EC2SpotSlave.class).getHelpFile(fieldName); return p; } @Restricted(NoExternalUse.class) public FormValidation doCheckRemoteAdmin(@QueryParameter String value){ if(StringUtils.isBlank(value) || Jenkins.getInstance().hasPermission(Jenkins.RUN_SCRIPTS)){ return FormValidation.ok(); }else{ return FormValidation.error(Messages.General_MissingPermission()); } } @Restricted(NoExternalUse.class) public FormValidation doCheckTmpDir(@QueryParameter String value){ if(StringUtils.isBlank(value) || Jenkins.getInstance().hasPermission(Jenkins.RUN_SCRIPTS)){ return FormValidation.ok(); }else{ return FormValidation.error(Messages.General_MissingPermission()); } } @Restricted(NoExternalUse.class) public FormValidation doCheckJvmopts(@QueryParameter String value){ if(StringUtils.isBlank(value) || Jenkins.getInstance().hasPermission(Jenkins.RUN_SCRIPTS)){ return FormValidation.ok(); }else{ return FormValidation.error(Messages.General_MissingPermission()); } } /*** * Check that the AMI requested is available in the cloud and can be used. */ public FormValidation doValidateAmi(@QueryParameter boolean useInstanceProfileForCredentials, @QueryParameter String credentialsId, @QueryParameter String ec2endpoint, @QueryParameter String region, final @QueryParameter String ami) throws IOException { AWSCredentialsProvider credentialsProvider = EC2Cloud.createCredentialsProvider(useInstanceProfileForCredentials, credentialsId); AmazonEC2 ec2; if (region != null) { ec2 = EC2Cloud.connect(credentialsProvider, AmazonEC2Cloud.getEc2EndpointUrl(region)); } else { ec2 = EC2Cloud.connect(credentialsProvider, new URL(ec2endpoint)); } if (ec2 != null) { try { List<String> images = new LinkedList<String>(); images.add(ami); List<String> owners = new LinkedList<String>(); List<String> users = new LinkedList<String>(); DescribeImagesRequest request = new DescribeImagesRequest(); request.setImageIds(images); request.setOwners(owners); request.setExecutableUsers(users); List<Image> img = ec2.describeImages(request).getImages(); if (img == null || img.isEmpty()) { // de-registered AMI causes an empty list to be // returned. so be defensive // against other possibilities return FormValidation.error("No such AMI, or not usable with this accessId: " + ami); } String ownerAlias = img.get(0).getImageOwnerAlias(); return FormValidation.ok(img.get(0).getImageLocation() + (ownerAlias != null ? " by " + ownerAlias : "")); } catch (AmazonClientException e) { return FormValidation.error(e.getMessage()); } } else return FormValidation.ok(); // can't test } public FormValidation doCheckLabelString(@QueryParameter String value, @QueryParameter Node.Mode mode) { if (mode == Node.Mode.EXCLUSIVE && (value == null || value.trim().isEmpty())) { return FormValidation.warning("You may want to assign labels to this node;" + " it's marked to only run jobs that are exclusively tied to itself or a label."); } return FormValidation.ok(); } public FormValidation doCheckIdleTerminationMinutes(@QueryParameter String value) { if (value == null || value.trim().isEmpty()) return FormValidation.ok(); try { int val = Integer.parseInt(value); if (val >= -59) return FormValidation.ok(); } catch (NumberFormatException nfe) { } return FormValidation.error("Idle Termination time must be a greater than -59 (or null)"); } public FormValidation doCheckInstanceCapStr(@QueryParameter String value) { if (value == null || value.trim().isEmpty()) return FormValidation.ok(); try { int val = Integer.parseInt(value); if (val > 0) return FormValidation.ok(); } catch (NumberFormatException nfe) { } return FormValidation.error("InstanceCap must be a non-negative integer (or null)"); } public FormValidation doCheckLaunchTimeoutStr(@QueryParameter String value) { if (value == null || value.trim().isEmpty()) return FormValidation.ok(); try { int val = Integer.parseInt(value); if (val >= 0) return FormValidation.ok(); } catch (NumberFormatException nfe) { } return FormValidation.error("Launch Timeout must be a non-negative integer (or null)"); } public ListBoxModel doFillZoneItems(@QueryParameter boolean useInstanceProfileForCredentials, @QueryParameter String credentialsId, @QueryParameter String region) throws IOException, ServletException { AWSCredentialsProvider credentialsProvider = EC2Cloud.createCredentialsProvider(useInstanceProfileForCredentials, credentialsId); return EC2AbstractSlave.fillZoneItems(credentialsProvider, region); } /* * Validate the Spot Max Bid Price to ensure that it is a floating point number >= .001 */ public FormValidation doCheckSpotMaxBidPrice(@QueryParameter String spotMaxBidPrice) { if (SpotConfiguration.normalizeBid(spotMaxBidPrice) != null) { return FormValidation.ok(); } return FormValidation.error("Not a correct bid price"); } // Retrieve the availability zones for the region private ArrayList<String> getAvailabilityZones(AmazonEC2 ec2) { ArrayList<String> availabilityZones = new ArrayList<String>(); DescribeAvailabilityZonesResult zones = ec2.describeAvailabilityZones(); List<AvailabilityZone> zoneList = zones.getAvailabilityZones(); for (AvailabilityZone z : zoneList) { availabilityZones.add(z.getZoneName()); } return availabilityZones; } /* * Check the current Spot price of the selected instance type for the selected region */ public FormValidation doCurrentSpotPrice(@QueryParameter boolean useInstanceProfileForCredentials, @QueryParameter String credentialsId, @QueryParameter String region, @QueryParameter String type, @QueryParameter String zone) throws IOException, ServletException { String cp = ""; String zoneStr = ""; // Connect to the EC2 cloud with the access id, secret key, and // region queried from the created cloud AWSCredentialsProvider credentialsProvider = EC2Cloud.createCredentialsProvider(useInstanceProfileForCredentials, credentialsId); AmazonEC2 ec2 = EC2Cloud.connect(credentialsProvider, AmazonEC2Cloud.getEc2EndpointUrl(region)); if (ec2 != null) { try { // Build a new price history request with the currently // selected type DescribeSpotPriceHistoryRequest request = new DescribeSpotPriceHistoryRequest(); // If a zone is specified, set the availability zone in the // request // Else, proceed with no availability zone which will result // with the cheapest Spot price if (getAvailabilityZones(ec2).contains(zone)) { request.setAvailabilityZone(zone); zoneStr = zone + " availability zone"; } else { zoneStr = region + " region"; } /* * Iterate through the AWS instance types to see if can find a match for the databound String type. * This is necessary because the AWS API needs the instance type string formatted a particular way * to retrieve prices and the form gives us the strings in a different format. For example "T1Micro" * vs "t1.micro". */ InstanceType ec2Type = null; for (InstanceType it : InstanceType.values()) { if (it.name().equals(type)) { ec2Type = it; break; } } /* * If the type string cannot be matched with an instance type, throw a Form error */ if (ec2Type == null) { return FormValidation.error("Could not resolve instance type: " + type); } Collection<String> instanceType = new ArrayList<String>(); instanceType.add(ec2Type.toString()); request.setInstanceTypes(instanceType); request.setStartTime(new Date()); // Retrieve the price history request result and store the // current price DescribeSpotPriceHistoryResult result = ec2.describeSpotPriceHistory(request); if (!result.getSpotPriceHistory().isEmpty()) { SpotPrice currentPrice = result.getSpotPriceHistory().get(0); cp = currentPrice.getSpotPrice(); } } catch (AmazonServiceException e) { return FormValidation.error(e.getMessage()); } } /* * If we could not return the current price of the instance display an error Else, remove the additional * zeros from the current price and return it to the interface in the form of a message */ if (cp.isEmpty()) { return FormValidation.error("Could not retrieve current Spot price"); } else { cp = cp.substring(0, cp.length() - 3); return FormValidation.ok("The current Spot price for a " + type + " in the " + zoneStr + " is $" + cp); } } } }
package hudson.plugins.tasks; import hudson.XmlFile; import hudson.model.Build; import hudson.model.ModelObject; import hudson.plugins.tasks.Task.Priority; import hudson.util.StringConverter2; import hudson.util.XStream2; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.lang.StringUtils; import com.thoughtworks.xstream.XStream; import edu.umd.cs.findbugs.annotations.SuppressWarnings; /** * Represents the results of the task scanner. One instance of this class is persisted for * each build via an XML file. * * @author Ulli Hafner */ public class TasksResult implements ModelObject, Serializable { /** Unique identifier of this class. */ private static final long serialVersionUID = -344808345805935004L; /** Error logger. */ private static final Logger LOGGER = Logger.getLogger(TasksResult.class.getName()); /** Serialization provider. */ private static final XStream XSTREAM = new XStream2(); static { XSTREAM.alias("project", JavaProject.class); XSTREAM.registerConverter(new StringConverter2(), 100); } /** The current build as owner of this action. */ @SuppressWarnings("Se") private final Build<?, ?> owner; /** The parsed FindBugs result. */ @SuppressWarnings("Se") private transient WeakReference<JavaProject> project; /** The number of tasks in this build. */ private final int numberOfTasks; /** Difference between this and the previous build. */ private final int delta; /** The number of high priority tasks in this build. */ private final int highPriorityTasks; /** The number of low priority tasks in this build. */ private final int lowPriorityTasks; /** The number of normal priority tasks in this build. */ private final int normalPriorityTasks; /** Tag identifiers indicating high priority. */ private final String high; /** Tag identifiers indicating normal priority. */ private final String normal; /** Tag identifiers indicating low priority. */ private final String low; /** * Creates a new instance of <code>TasksResult</code>. * * @param build * the current build as owner of this action * @param project * the parsed FindBugs result * @param high * tag identifiers indicating high priority * @param normal * tag identifiers indicating normal priority * @param low * tag identifiers indicating low priority */ public TasksResult(final Build<?, ?> build, final JavaProject project, final String high, final String normal, final String low) { this(build, project, project.getNumberOfTasks(), high, normal, low); } /** * Creates a new instance of <code>TasksResult</code>. * * @param build the current build as owner of this action * @param project the parsed FindBugs result * @param previousNumberOfTasks the previous number of open tasks * @param high * tag identifiers indicating high priority * @param normal * tag identifiers indicating normal priority * @param low * tag identifiers indicating low priority */ public TasksResult(final Build<?, ?> build, final JavaProject project, final int previousNumberOfTasks, final String high, final String normal, final String low) { owner = build; highPriorityTasks = project.getNumberOfTasks(Priority.HIGH); lowPriorityTasks = project.getNumberOfTasks(Priority.LOW); normalPriorityTasks = project.getNumberOfTasks(Priority.NORMAL); numberOfTasks = project.getNumberOfTasks(); this.project = new WeakReference<JavaProject>(project); delta = numberOfTasks - previousNumberOfTasks; this.high = high; this.normal = normal; this.low = low; try { getDataFile().write(project); } catch (IOException exception) { LOGGER.log(Level.WARNING, "Failed to serialize the open tasks result.", exception); } } /** {@inheritDoc} */ public String getDisplayName() { return "Open Tasks"; } /** * Returns the owner. * * @return the owner */ public Build<?, ?> getOwner() { return owner; } /** * Gets the number of tasks. * * @return the number of tasks */ public int getNumberOfTasks() { return numberOfTasks; } /** * Returns the number of tasks with the specified priority. * * @param priority the priority * * @return the number of tasks with the specified priority */ public int getNumberOfTasks(final String priority) { Priority converted = Priority.valueOf(StringUtils.upperCase(priority)); if (converted == Priority.HIGH) { return highPriorityTasks; } else if (converted == Priority.NORMAL) { return normalPriorityTasks; } else { return lowPriorityTasks; } } /** * Returns the highPriorityTasks. * * @return the highPriorityTasks */ public int getNumberOfHighPriorityTasks() { return highPriorityTasks; } /** * Returns the lowPriorityTasks. * * @return the lowPriorityTasks */ public int getNumberOfLowPriorityTasks() { return lowPriorityTasks; } /** * Returns the normalPriorityTasks. * * @return the normalPriorityTasks */ public int getNumberOfNormalPriorityTasks() { return normalPriorityTasks; } /** * Returns the delta. * * @return the delta */ public int getDelta() { return delta; } /** * Returns the associated project of this result. * * @return the associated project of this result. */ public JavaProject getProject() { if (project == null) { loadResult(); } JavaProject result = project.get(); if (result == null) { loadResult(); } return project.get(); } /** * Loads the FindBugs results and wraps them in a weak reference that might * get removed by the garbage collector. */ private void loadResult() { JavaProject result; try { result = (JavaProject)getDataFile().read(); } catch (IOException exception) { LOGGER.log(Level.WARNING, "Failed to load " + getDataFile(), exception); result = new JavaProject(); } project = new WeakReference<JavaProject>(result); } /** * Returns the serialization file. * * @return the serialization file. */ private XmlFile getDataFile() { return new XmlFile(XSTREAM, new File(owner.getRootDir(), "openTasks.xml")); } /** * Returns the tags for the specified priority. * * @param priority * the priority * @return the tags for priority high */ public String getTags(final String priority) { Priority converted = Priority.valueOf(StringUtils.upperCase(priority)); if (converted == Priority.HIGH) { return high; } else if (converted == Priority.NORMAL) { return normal; } else { return low; } } /** * Returns the defined priorities. * * @return the defined priorities. */ public List<String> getPriorities() { ArrayList<String> priorities = new ArrayList<String>(); if (StringUtils.isNotEmpty(high)) { priorities.add(StringUtils.capitalize(StringUtils.lowerCase(Priority.HIGH.name()))); } if (StringUtils.isNotEmpty(normal)) { priorities.add(StringUtils.capitalize(StringUtils.lowerCase(Priority.NORMAL.name()))); } if (StringUtils.isNotEmpty(low)) { priorities.add(StringUtils.capitalize(StringUtils.lowerCase(Priority.LOW.name()))); } return priorities; } /** * Returns whether this result belongs to the last build. * * @return <code>true</code> if this result belongs to the last build */ public boolean isCurrent() { return owner.getProject().getLastBuild().number == owner.number; } }
package innovimax.mixthem.arguments; import java.util.EnumSet; /** * <p>This is a detailed enumeration of rules used to mix files.</p> * <p>Some rules may not be implemented yet.<.p> * <p>(Also used to print usage.)</p> * @author Innovimax * @version 1.0 */ public enum Rule { FILE_1("1", "1", "will output file1", true, EnumSet.noneOf(RuleParam.class), EnumSet.of(FileMode.CHAR, Mode.BYTE)), FILE_2("2", "2", "will output file2", true, EnumSet.noneOf(RuleParam.class), EnumSet.of(FileMode.CHAR, Mode.BYTE)), ADD("+", "add", "will output file1+file2+...+fileN", true, EnumSet.of(RuleParam.ADD_FILES), EnumSet.of(FileMode.CHAR, Mode.BYTE)), ALT_LINE("alt-line", "altline", "will output one line of each starting with first line of file1", true, EnumSet.noneOf(RuleParam.class), EnumSet.of(FileMode.CHAR)), ALT_CHAR("alt-char", "altchar", "will output one char of each starting with first char of file1", true, EnumSet.noneOf(RuleParam.class), EnumSet.of(FileMode.CHAR)), ALT_BYTE("alt-byte", "altbyte", "will output one byte of each starting with first byte of file1", true, EnumSet.noneOf(RuleParam.class), EnumSet.of(FileMode.BYTE)), RANDOM_ALT_LINE("random-alt-line", "random-altline", "will output one line of each code randomly based on a seed for reproducability", true, EnumSet.of(RuleParam.RANDOM_SEED), EnumSet.of(FileMode.CHAR)), RANDOM_ALT_CHAR("random-alt-char", "random-altchar", "will output one char of each code randomly based on a seed for reproducability", true, EnumSet.of(RuleParam.RANDOM_SEED), EnumSet.of(FileMode.CHAR)), RANDOM_ALT_BYTE("random-alt-byte", "random-altbyte", "will output one byte of each code randomly based on a seed for reproducability", true, EnumSet.of(RuleParam.RANDOM_SEED), EnumSet.of(FileMode.BYTE)), JOIN("join", "join", "will output merging of lines that have common occurrence", true, EnumSet.of(RuleParam.JOIN_COLS), EnumSet.of(FileMode.CHAR)), ZIP_LINE("zip-line", "zipline", "will output zip of line from file1 and file2 to fileN", true, EnumSet.of(RuleParam.ZIP_SEP), EnumSet.of(FileMode.CHAR)), ZIP_CHAR("zip-char", "zipchar", "will output zip of char from file1 and file2 to fileN", true, EnumSet.of(RuleParam.ZIP_SEP), EnumSet.of(FileMode.CHAR)), ZIP_CELL("zip-cell", "zipcell", "will output zip of cell from file1 and file2 to fileN", true, EnumSet.of(RuleParam.ZIP_SEP), EnumSet.of(FileMode.CHAR)); private final String name, extension, description; private final boolean implemented; private final EnumSet<RuleParam> params; private final EnumSet<FileMode> fileModes; private Rule(final Sting name, final String extension, final String description, final boolean implemented, final EnumSet<RuleParam> params, final EnumSet<FileMode> fileModes) { this.name = name; this.extension = extension; this.description = description; this.implemented = implemented; this.params = params; this.fileModes = fileModes; } /** * Returns true if the rule is currently implemented. * @return True if the rule is currently implemented */ public boolean isImplemented() { return this.implemented; } /** * Returns the name of this rule on command line. * @return The name of the rule on command line */ public String getName() { return this.name; } /** * Returns the file extension used for outputting. * @return The file extension for the rule */ public String getExtension() { return this.extension; } /** * Returns the description of this rule. * @return The description of the rule */ public String getDescription() { return this.description; } /** * Returns an iterator over the additional parameters in this rule. * @return An iterator over the additional parameters in this rule */ public Iterable<RuleParam> getParams() { return this.params; } /** * Returns true if the rule accept the file mode. * @return True if the rule accept the file mode */ public boolean acceptFileMode(final FileMode fileMode) { return fileModes.contains(fileMode); } /** * Finds the Rule object correponding to a name * @param name The name of the rule in command line * @param mode The running {@link Mode) * @return The {@link Rule} object */ public static Rule findByName(final String name, final FileMode fileMode) { for(Rule rule : values()){ if (rule.getName().equals(name) && rule.acceptFileMode(fileMode)) { return rule; } } return null; } }
package io.github.ledge.client; import io.github.ledge.engine.GameEngine; import io.github.ledge.engine.GameRegistry; import io.github.ledge.engine.component.DisplayDevice; import io.github.ledge.engine.state.GameState; import io.github.ledge.input.InputSystem; import io.github.ledge.render.tesselator.DrawMode; import static org.lwjgl.opengl.GL11.*; public class TestState implements GameState { private InputSystem inputSystem; public TestState() { } @Override public void init(GameEngine engine) { this.inputSystem = GameRegistry.get(InputSystem.class); } private void initGl() { glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); } @Override public void update(float v) { // Update logic etc } private int x; private int y; @Override public void render(float v) { GameRegistry.get(DisplayDevice.class).prepareToRender(); x++; y++; glRotatef(x, 1.0f, 0.0f, 0.0f); glRotatef(y, 0.0f, 1.0f, 0.0f); glColor3f(1, 0, 0); glBegin(DrawMode.QUADS.mode()); // top glColor3f(0.0f,1.0f,0.0f); glVertex3f( 0.5f, 0.5f,-0.5f); glVertex3f(-0.5f, 0.5f,-0.5f); glVertex3f(-0.5f, 0.5f, 0.5f); glVertex3f( 0.5f, 0.5f, 0.5f); // bottom glColor3f(1.0f,1.0f,0.0f); glVertex3f( 0.5f,-0.5f, 0.5f); glVertex3f(-0.5f,-0.5f, 0.5f); glVertex3f(-0.5f,-0.5f,-0.5f); glVertex3f( 0.5f,-0.5f,-0.5f); // front glColor3f(1.0f,0.0f,0.0f); glVertex3f( 0.5f, 0.5f, 0.5f); glVertex3f(-0.5f, 0.5f, 0.5f); glVertex3f(-0.5f,-0.5f, 0.5f); glVertex3f( 0.5f,-0.5f, 0.5f); // back glColor3f(1.0f,1.0f,0.0f); glVertex3f( 0.5f,-0.5f,-0.5f); glVertex3f(-0.5f,-0.5f,-0.5f); glVertex3f(-0.5f, 0.5f,-0.5f); glVertex3f( 0.5f, 0.5f,-0.5f); // left glColor3f(0.0f,0.0f,1.0f); glVertex3f(-0.5f, 0.5f, 0.5f); glVertex3f(-0.5f, 0.5f,-0.5f); glVertex3f(-0.5f,-0.5f,-0.5f); glVertex3f(-0.5f,-0.5f, 0.5f); // right glColor3f(1.0f,0.0f,1.0f); glVertex3f( 0.5f, 0.5f,-0.5f); glVertex3f( 0.5f, 0.5f, 0.5f); glVertex3f( 0.5f,-0.5f, 0.5f); glVertex3f( 0.5f,-0.5f,-0.5f); glEnd(); } @Override public void handleInput(float delta) { this.inputSystem.update(delta); } @Override public void dispose() { this.inputSystem = null; } }
package io.luna.game.event; import io.luna.game.model.mobile.Player; import scala.Function2; import scala.Unit; public final class EventListener<E extends Event> { /** * The wrapped listener function. */ private final Function2<E, Player, Unit> function; /** * Creates a new {@link EventListener}. * * @param function The wrapped listener function. */ public EventListener(Function2<E, Player, Unit> function) { this.function = function; } /** * @return The wrapped listener function. */ public Function2<E, Player, Unit> getFunction() { return function; } }
package javax.jmdns.impl; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import javax.jmdns.ServiceEvent; import javax.jmdns.ServiceInfo; import javax.jmdns.impl.DNSRecord.Pointer; import javax.jmdns.impl.DNSRecord.Service; import javax.jmdns.impl.DNSRecord.Text; import javax.jmdns.impl.constants.DNSRecordClass; import javax.jmdns.impl.constants.DNSRecordType; import javax.jmdns.impl.constants.DNSState; import javax.jmdns.impl.tasks.DNSTask; /** * JmDNS service information. * * @author Arthur van Hoff, Jeff Sonstein, Werner Randelshofer */ public class ServiceInfoImpl extends ServiceInfo implements DNSListener, DNSStatefulObject { private static Logger logger = Logger.getLogger(ServiceInfoImpl.class.getName()); private String _domain; private String _protocol; private String _application; private String _name; private String _subtype; private String _server; private int _port; private int _weight; private int _priority; private byte _text[]; private Map<String, byte[]> _props; private final Set<Inet4Address> _ipv4Addresses; private final Set<Inet6Address> _ipv6Addresses; private transient String _key; private boolean _persistent; private boolean _needTextAnnouncing; private final ServiceInfoState _state; private Delegate _delegate; public static interface Delegate { public void textValueUpdated(ServiceInfo target, byte[] value); } private final static class ServiceInfoState extends DNSStatefulObject.DefaultImplementation { private static final long serialVersionUID = 1104131034952196820L; private final ServiceInfoImpl _info; /** * @param info */ public ServiceInfoState(ServiceInfoImpl info) { super(); _info = info; } @Override protected void setTask(DNSTask task) { super.setTask(task); if ((this._task == null) && _info.needTextAnnouncing()) { this.lock(); try { if ((this._task == null) && _info.needTextAnnouncing()) { if (this._state.isAnnounced()) { this.setState(DNSState.ANNOUNCING_1); if (this.getDns() != null) { this.getDns().startAnnouncer(); } } _info.setNeedTextAnnouncing(false); } } finally { this.unlock(); } } } @Override public void setDns(JmDNSImpl dns) { super.setDns(dns); } } /** * @param type * @param name * @param subtype * @param port * @param weight * @param priority * @param persistent * @param text * @see javax.jmdns.ServiceInfo#create(String, String, int, int, int, String) */ public ServiceInfoImpl(String type, String name, String subtype, int port, int weight, int priority, boolean persistent, String text) { this(ServiceInfoImpl.decodeQualifiedNameMap(type, name, subtype), port, weight, priority, persistent, (byte[]) null); _server = text; try { ByteArrayOutputStream out = new ByteArrayOutputStream(text.length()); writeUTF(out, text); this._text = out.toByteArray(); } catch (IOException e) { throw new RuntimeException("unexpected exception: " + e); } } /** * @param type * @param name * @param subtype * @param port * @param weight * @param priority * @param persistent * @param props * @see javax.jmdns.ServiceInfo#create(String, String, int, int, int, Map) */ public ServiceInfoImpl(String type, String name, String subtype, int port, int weight, int priority, boolean persistent, Map<String, ?> props) { this(ServiceInfoImpl.decodeQualifiedNameMap(type, name, subtype), port, weight, priority, persistent, textFromProperties(props)); } /** * @param type * @param name * @param subtype * @param port * @param weight * @param priority * @param persistent * @param text * @see javax.jmdns.ServiceInfo#create(String, String, int, int, int, byte[]) */ public ServiceInfoImpl(String type, String name, String subtype, int port, int weight, int priority, boolean persistent, byte text[]) { this(ServiceInfoImpl.decodeQualifiedNameMap(type, name, subtype), port, weight, priority, persistent, text); } public ServiceInfoImpl(Map<Fields, String> qualifiedNameMap, int port, int weight, int priority, boolean persistent, Map<String, ?> props) { this(qualifiedNameMap, port, weight, priority, persistent, textFromProperties(props)); } ServiceInfoImpl(Map<Fields, String> qualifiedNameMap, int port, int weight, int priority, boolean persistent, String text) { this(qualifiedNameMap, port, weight, priority, persistent, (byte[]) null); _server = text; try { ByteArrayOutputStream out = new ByteArrayOutputStream(text.length()); writeUTF(out, text); this._text = out.toByteArray(); } catch (IOException e) { throw new RuntimeException("unexpected exception: " + e); } } ServiceInfoImpl(Map<Fields, String> qualifiedNameMap, int port, int weight, int priority, boolean persistent, byte text[]) { Map<Fields, String> map = ServiceInfoImpl.checkQualifiedNameMap(qualifiedNameMap); this._domain = map.get(Fields.Domain); this._protocol = map.get(Fields.Protocol); this._application = map.get(Fields.Application); this._name = map.get(Fields.Instance); this._subtype = map.get(Fields.Subtype); this._port = port; this._weight = weight; this._priority = priority; this._text = text; this.setNeedTextAnnouncing(false); this._state = new ServiceInfoState(this); this._persistent = persistent; this._ipv4Addresses = Collections.synchronizedSet(new LinkedHashSet<Inet4Address>()); this._ipv6Addresses = Collections.synchronizedSet(new LinkedHashSet<Inet6Address>()); } /** * During recovery we need to duplicate service info to reregister them * * @param info */ ServiceInfoImpl(ServiceInfo info) { this._ipv4Addresses = Collections.synchronizedSet(new LinkedHashSet<Inet4Address>()); this._ipv6Addresses = Collections.synchronizedSet(new LinkedHashSet<Inet6Address>()); if (info != null) { this._domain = info.getDomain(); this._protocol = info.getProtocol(); this._application = info.getApplication(); this._name = info.getName(); this._subtype = info.getSubtype(); this._port = info.getPort(); this._weight = info.getWeight(); this._priority = info.getPriority(); this._text = info.getTextBytes(); this._persistent = info.isPersistent(); Inet6Address[] ipv6Addresses = info.getInet6Addresses(); for (Inet6Address address : ipv6Addresses) { this._ipv6Addresses.add(address); } Inet4Address[] ipv4Addresses = info.getInet4Addresses(); for (Inet4Address address : ipv4Addresses) { this._ipv4Addresses.add(address); } } this._state = new ServiceInfoState(this); } public static Map<Fields, String> decodeQualifiedNameMap(String type, String name, String subtype) { Map<Fields, String> qualifiedNameMap = decodeQualifiedNameMapForType(type); qualifiedNameMap.put(Fields.Instance, name); qualifiedNameMap.put(Fields.Subtype, subtype); return checkQualifiedNameMap(qualifiedNameMap); } public static Map<Fields, String> decodeQualifiedNameMapForType(String type) { int index; String casePreservedType = type; String aType = type.toLowerCase(); String application = aType; String protocol = ""; String subtype = ""; String name = ""; String domain = ""; if (aType.contains("in-addr.arpa") || aType.contains("ip6.arpa")) { index = (aType.contains("in-addr.arpa") ? aType.indexOf("in-addr.arpa") : aType.indexOf("ip6.arpa")); name = removeSeparators(casePreservedType.substring(0, index)); domain = casePreservedType.substring(index); application = ""; } else if ((!aType.contains("_")) && aType.contains(".")) { index = aType.indexOf('.'); name = removeSeparators(casePreservedType.substring(0, index)); domain = removeSeparators(casePreservedType.substring(index)); application = ""; } else { // First remove the name if it there. if (!aType.startsWith("_") || aType.startsWith("_services")) { index = aType.indexOf('.'); if (index > 0) { // We need to preserve the case for the user readable name. name = casePreservedType.substring(0, index); if (index + 1 < aType.length()) { aType = aType.substring(index + 1); casePreservedType = casePreservedType.substring(index + 1); } } } index = aType.lastIndexOf("._"); if (index > 0) { int start = index + 2; int end = aType.indexOf('.', start); protocol = casePreservedType.substring(start, end); } if (protocol.length() > 0) { index = aType.indexOf("_" + protocol.toLowerCase() + "."); int start = index + protocol.length() + 2; int end = aType.length() - (aType.endsWith(".") ? 1 : 0); if (end > start) { domain = casePreservedType.substring(start, end); } if (index > 0) { application = casePreservedType.substring(0, index - 1); } else { application = ""; } } index = application.toLowerCase().indexOf("._sub"); if (index > 0) { int start = index + 5; subtype = removeSeparators(application.substring(0, index)); application = application.substring(start); } } final Map<Fields, String> qualifiedNameMap = new HashMap<Fields, String>(5); qualifiedNameMap.put(Fields.Domain, removeSeparators(domain)); qualifiedNameMap.put(Fields.Protocol, protocol); qualifiedNameMap.put(Fields.Application, removeSeparators(application)); qualifiedNameMap.put(Fields.Instance, name); qualifiedNameMap.put(Fields.Subtype, subtype); return qualifiedNameMap; } protected static Map<Fields, String> checkQualifiedNameMap(Map<Fields, String> qualifiedNameMap) { Map<Fields, String> checkedQualifiedNameMap = new HashMap<Fields, String>(5); // Optional domain String domain = (qualifiedNameMap.containsKey(Fields.Domain) ? qualifiedNameMap.get(Fields.Domain) : "local"); if ((domain == null) || (domain.length() == 0)) { domain = "local"; } domain = removeSeparators(domain); checkedQualifiedNameMap.put(Fields.Domain, domain); // Optional protocol String protocol = (qualifiedNameMap.containsKey(Fields.Protocol) ? qualifiedNameMap.get(Fields.Protocol) : "tcp"); if ((protocol == null) || (protocol.length() == 0)) { protocol = "tcp"; } protocol = removeSeparators(protocol); checkedQualifiedNameMap.put(Fields.Protocol, protocol); // Application String application = (qualifiedNameMap.containsKey(Fields.Application) ? qualifiedNameMap.get(Fields.Application) : ""); if ((application == null) || (application.length() == 0)) { application = ""; } application = removeSeparators(application); checkedQualifiedNameMap.put(Fields.Application, application); // Instance String instance = (qualifiedNameMap.containsKey(Fields.Instance) ? qualifiedNameMap.get(Fields.Instance) : ""); if ((instance == null) || (instance.length() == 0)) { instance = ""; } instance = removeSeparators(instance); checkedQualifiedNameMap.put(Fields.Instance, instance); // Optional Subtype String subtype = (qualifiedNameMap.containsKey(Fields.Subtype) ? qualifiedNameMap.get(Fields.Subtype) : ""); if ((subtype == null) || (subtype.length() == 0)) { subtype = ""; } subtype = removeSeparators(subtype); checkedQualifiedNameMap.put(Fields.Subtype, subtype); return checkedQualifiedNameMap; } private static String removeSeparators(String name) { if (name == null) { return ""; } String newName = name.trim(); if (newName.startsWith(".")) { newName = newName.substring(1); } if (newName.startsWith("_")) { newName = newName.substring(1); } if (newName.endsWith(".")) { newName = newName.substring(0, newName.length() - 1); } return newName; } /** * {@inheritDoc} */ @Override public String getType() { String domain = this.getDomain(); String protocol = this.getProtocol(); String application = this.getApplication(); return (application.length() > 0 ? "_" + application + "." : "") + (protocol.length() > 0 ? "_" + protocol + "." : "") + domain + "."; } /** * {@inheritDoc} */ @Override public String getTypeWithSubtype() { String subtype = this.getSubtype(); return (subtype.length() > 0 ? "_" + subtype.toLowerCase() + "._sub." : "") + this.getType(); } /** * {@inheritDoc} */ @Override public String getName() { return (_name != null ? _name : ""); } /** * {@inheritDoc} */ @Override public String getKey() { if (this._key == null) { this._key = this.getQualifiedName().toLowerCase(); } return this._key; } /** * Sets the service instance name. * * @param name * unqualified service instance name, such as <code>foobar</code> */ void setName(String name) { this._name = name; this._key = null; } /** * {@inheritDoc} */ @Override public String getQualifiedName() { String domain = this.getDomain(); String protocol = this.getProtocol(); String application = this.getApplication(); String instance = this.getName(); // String subtype = this.getSubtype(); // return (instance.length() > 0 ? instance + "." : "") + (application.length() > 0 ? "_" + application + "." : "") + (protocol.length() > 0 ? "_" + protocol + (subtype.length() > 0 ? ",_" + subtype.toLowerCase() + "." : ".") : "") + domain return (instance.length() > 0 ? instance + "." : "") + (application.length() > 0 ? "_" + application + "." : "") + (protocol.length() > 0 ? "_" + protocol + "." : "") + domain + "."; } /** * @see javax.jmdns.ServiceInfo#getServer() */ @Override public String getServer() { return (_server != null ? _server : ""); } /** * @param server * the server to set */ void setServer(String server) { this._server = server; } /** * {@inheritDoc} */ @Deprecated @Override public String getHostAddress() { String[] names = this.getHostAddresses(); return (names.length > 0 ? names[0] : ""); } /** * {@inheritDoc} */ @Override public String[] getHostAddresses() { Inet4Address[] ip4Aaddresses = this.getInet4Addresses(); Inet6Address[] ip6Aaddresses = this.getInet6Addresses(); String[] names = new String[ip4Aaddresses.length + ip6Aaddresses.length]; for (int i = 0; i < ip4Aaddresses.length; i++) { names[i] = ip4Aaddresses[i].getHostAddress(); } for (int i = 0; i < ip6Aaddresses.length; i++) { names[i + ip4Aaddresses.length] = "[" + ip6Aaddresses[i].getHostAddress() + "]"; } return names; } /** * @param addr * the addr to add */ void addAddress(Inet4Address addr) { _ipv4Addresses.add(addr); } /** * @param addr * the addr to add */ void addAddress(Inet6Address addr) { _ipv6Addresses.add(addr); } /** * {@inheritDoc} */ @Deprecated @Override public InetAddress getAddress() { return this.getInetAddress(); } /** * {@inheritDoc} */ @Deprecated @Override public InetAddress getInetAddress() { InetAddress[] addresses = this.getInetAddresses(); return (addresses.length > 0 ? addresses[0] : null); } /** * {@inheritDoc} */ @Deprecated @Override public Inet4Address getInet4Address() { Inet4Address[] addresses = this.getInet4Addresses(); return (addresses.length > 0 ? addresses[0] : null); } /** * {@inheritDoc} */ @Deprecated @Override public Inet6Address getInet6Address() { Inet6Address[] addresses = this.getInet6Addresses(); return (addresses.length > 0 ? addresses[0] : null); } /* * (non-Javadoc) * @see javax.jmdns.ServiceInfo#getInetAddresses() */ @Override public InetAddress[] getInetAddresses() { List<InetAddress> aList = new ArrayList<InetAddress>(_ipv4Addresses.size() + _ipv6Addresses.size()); aList.addAll(_ipv4Addresses); aList.addAll(_ipv6Addresses); return aList.toArray(new InetAddress[aList.size()]); } /* * (non-Javadoc) * @see javax.jmdns.ServiceInfo#getInet4Addresses() */ @Override public Inet4Address[] getInet4Addresses() { return _ipv4Addresses.toArray(new Inet4Address[_ipv4Addresses.size()]); } /* * (non-Javadoc) * @see javax.jmdns.ServiceInfo#getInet6Addresses() */ @Override public Inet6Address[] getInet6Addresses() { return _ipv6Addresses.toArray(new Inet6Address[_ipv6Addresses.size()]); } /** * @see javax.jmdns.ServiceInfo#getPort() */ @Override public int getPort() { return _port; } /** * @see javax.jmdns.ServiceInfo#getPriority() */ @Override public int getPriority() { return _priority; } /** * @see javax.jmdns.ServiceInfo#getWeight() */ @Override public int getWeight() { return _weight; } /** * @see javax.jmdns.ServiceInfo#getTextBytes() */ @Override public byte[] getTextBytes() { return (this._text != null && this._text.length > 0 ? this._text : DNSRecord.EMPTY_TXT); } /** * {@inheritDoc} */ @Deprecated @Override public String getTextString() { Map<String, byte[]> properties = this.getProperties(); for (String key : properties.keySet()) { byte[] value = properties.get(key); if ((value != null) && (value.length > 0)) { return key + "=" + new String(value); } return key; } return ""; } /* * (non-Javadoc) * @see javax.jmdns.ServiceInfo#getURL() */ @Deprecated @Override public String getURL() { return this.getURL("http"); } /* * (non-Javadoc) * @see javax.jmdns.ServiceInfo#getURLs() */ @Override public String[] getURLs() { return this.getURLs("http"); } /* * (non-Javadoc) * @see javax.jmdns.ServiceInfo#getURL(java.lang.String) */ @Deprecated @Override public String getURL(String protocol) { String[] urls = this.getURLs(protocol); return (urls.length > 0 ? urls[0] : protocol + "://null:" + getPort()); } /* * (non-Javadoc) * @see javax.jmdns.ServiceInfo#getURLs(java.lang.String) */ @Override public String[] getURLs(String protocol) { InetAddress[] addresses = this.getInetAddresses(); String[] urls = new String[addresses.length]; for (int i = 0; i < addresses.length; i++) { String url = protocol + "://" + addresses[i].getHostAddress() + ":" + getPort(); String path = getPropertyString("path"); if (path != null) { if (path.indexOf(": url = path; } else { url += path.startsWith("/") ? path : "/" + path; } } urls[i] = url; } return urls; } /** * {@inheritDoc} */ @Override public synchronized byte[] getPropertyBytes(String name) { return this.getProperties().get(name); } /** * {@inheritDoc} */ @Override public synchronized String getPropertyString(String name) { byte data[] = this.getProperties().get(name); if (data == null) { return null; } if (data == NO_VALUE) { return "true"; } return readUTF(data, 0, data.length); } /** * {@inheritDoc} */ @Override public Enumeration<String> getPropertyNames() { Map<String, byte[]> properties = this.getProperties(); Collection<String> names = (properties != null ? properties.keySet() : Collections.<String> emptySet()); return new Vector<String>(names).elements(); } /** * {@inheritDoc} */ @Override public String getApplication() { return (_application != null ? _application : ""); } /** * {@inheritDoc} */ @Override public String getDomain() { return (_domain != null ? _domain : "local"); } /** * {@inheritDoc} */ @Override public String getProtocol() { return (_protocol != null ? _protocol : "tcp"); } /** * {@inheritDoc} */ @Override public String getSubtype() { return (_subtype != null ? _subtype : ""); } /** * {@inheritDoc} */ @Override public Map<Fields, String> getQualifiedNameMap() { Map<Fields, String> map = new HashMap<Fields, String>(5); map.put(Fields.Domain, this.getDomain()); map.put(Fields.Protocol, this.getProtocol()); map.put(Fields.Application, this.getApplication()); map.put(Fields.Instance, this.getName()); map.put(Fields.Subtype, this.getSubtype()); return map; } /** * Write a UTF string with a length to a stream. */ static void writeUTF(OutputStream out, String str) throws IOException { for (int i = 0, len = str.length(); i < len; i++) { int c = str.charAt(i); if ((c >= 0x0001) && (c <= 0x007F)) { out.write(c); } else { if (c > 0x07FF) { out.write(0xE0 | ((c >> 12) & 0x0F)); out.write(0x80 | ((c >> 6) & 0x3F)); out.write(0x80 | ((c >> 0) & 0x3F)); } else { out.write(0xC0 | ((c >> 6) & 0x1F)); out.write(0x80 | ((c >> 0) & 0x3F)); } } } } /** * Read data bytes as a UTF stream. */ String readUTF(byte data[], int off, int len) { int offset = off; StringBuffer buf = new StringBuffer(); for (int end = offset + len; offset < end;) { int ch = data[offset++] & 0xFF; switch (ch >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: // 0xxxxxxx break; case 12: case 13: if (offset >= len) { return null; } // 110x xxxx 10xx xxxx ch = ((ch & 0x1F) << 6) | (data[offset++] & 0x3F); break; case 14: if (offset + 2 >= len) { return null; } // 1110 xxxx 10xx xxxx 10xx xxxx ch = ((ch & 0x0f) << 12) | ((data[offset++] & 0x3F) << 6) | (data[offset++] & 0x3F); break; default: if (offset + 1 >= len) { return null; } // 10xx xxxx, 1111 xxxx ch = ((ch & 0x3F) << 4) | (data[offset++] & 0x0f); break; } buf.append((char) ch); } return buf.toString(); } synchronized Map<String, byte[]> getProperties() { if ((_props == null) && (this.getTextBytes() != null)) { Hashtable<String, byte[]> properties = new Hashtable<String, byte[]>(); try { int off = 0; while (off < getTextBytes().length) { // length of the next key value pair int len = getTextBytes()[off++] & 0xFF; if ((len == 0) || (off + len > getTextBytes().length)) { properties.clear(); break; } // look for the '=' int i = 0; for (; (i < len) && (getTextBytes()[off + i] != '='); i++) { /* Stub */ } // get the property name String name = readUTF(getTextBytes(), off, i); if (name == null) { properties.clear(); break; } if (i == len) { properties.put(name, NO_VALUE); } else { byte value[] = new byte[len - ++i]; System.arraycopy(getTextBytes(), off + i, value, 0, len - i); properties.put(name, value); off += len; } } } catch (Exception exception) { // We should get better logging. logger.log(Level.WARNING, "Malformed TXT Field ", exception); } this._props = properties; } return (_props != null ? _props : Collections.<String, byte[]> emptyMap()); } /** * JmDNS callback to update a DNS record. * * @param dnsCache * @param now * @param rec */ @Override public void updateRecord(DNSCache dnsCache, long now, DNSEntry rec) { if ((rec instanceof DNSRecord) && !rec.isExpired(now)) { boolean serviceUpdated = false; switch (rec.getRecordType()) { case TYPE_A: // IPv4 if (rec.getName().equalsIgnoreCase(this.getServer())) { _ipv4Addresses.add((Inet4Address) ((DNSRecord.Address) rec).getAddress()); serviceUpdated = true; } break; case TYPE_AAAA: // IPv6 if (rec.getName().equalsIgnoreCase(this.getServer())) { _ipv6Addresses.add((Inet6Address) ((DNSRecord.Address) rec).getAddress()); serviceUpdated = true; } break; case TYPE_SRV: if (rec.getName().equalsIgnoreCase(this.getQualifiedName())) { DNSRecord.Service srv = (DNSRecord.Service) rec; boolean serverChanged = (_server == null) || !_server.equalsIgnoreCase(srv.getServer()); _server = srv.getServer(); _port = srv.getPort(); _weight = srv.getWeight(); _priority = srv.getPriority(); if (serverChanged) { _ipv4Addresses.clear(); _ipv6Addresses.clear(); for (DNSEntry entry : dnsCache.getDNSEntryList(_server, DNSRecordType.TYPE_A, DNSRecordClass.CLASS_IN)) { this.updateRecord(dnsCache, now, entry); } for (DNSEntry entry : dnsCache.getDNSEntryList(_server, DNSRecordType.TYPE_AAAA, DNSRecordClass.CLASS_IN)) { this.updateRecord(dnsCache, now, entry); } // We do not want to trigger the listener in this case as it will be triggered if the address resolves. } else { serviceUpdated = true; } } break; case TYPE_TXT: if (rec.getName().equalsIgnoreCase(this.getQualifiedName())) { DNSRecord.Text txt = (DNSRecord.Text) rec; _text = txt.getText(); _props = null; // set it null for apply update text data serviceUpdated = true; } break; case TYPE_PTR: if ((this.getSubtype().length() == 0) && (rec.getSubtype().length() != 0)) { _subtype = rec.getSubtype(); serviceUpdated = true; } break; default: break; } if (serviceUpdated && this.hasData()) { JmDNSImpl dns = this.getDns(); if (dns != null) { ServiceEvent event = ((DNSRecord) rec).getServiceEvent(dns); event = new ServiceEventImpl(dns, event.getType(), event.getName(), this); dns.handleServiceResolved(event); } } // This is done, to notify the wait loop in method JmDNS.waitForInfoData(ServiceInfo info, int timeout); synchronized (this) { this.notifyAll(); } } } /** * Returns true if the service info is filled with data. * * @return <code>true</code> if the service info has data, <code>false</code> otherwise. */ @Override public synchronized boolean hasData() { return this.getServer() != null && this.hasInetAddress() && this.getTextBytes() != null && this.getTextBytes().length > 0; // return this.getServer() != null && (this.getAddress() != null || (this.getTextBytes() != null && this.getTextBytes().length > 0)); } private final boolean hasInetAddress() { return _ipv4Addresses.size() > 0 || _ipv6Addresses.size() > 0; } // State machine /** * {@inheritDoc} */ @Override public boolean advanceState(DNSTask task) { return _state.advanceState(task); } /** * {@inheritDoc} */ @Override public boolean revertState() { return _state.revertState(); } /** * {@inheritDoc} */ @Override public boolean cancelState() { return _state.cancelState(); } /** * {@inheritDoc} */ @Override public boolean closeState() { return this._state.closeState(); } /** * {@inheritDoc} */ @Override public boolean recoverState() { return this._state.recoverState(); } /** * {@inheritDoc} */ @Override public void removeAssociationWithTask(DNSTask task) { _state.removeAssociationWithTask(task); } /** * {@inheritDoc} */ @Override public void associateWithTask(DNSTask task, DNSState state) { _state.associateWithTask(task, state); } /** * {@inheritDoc} */ @Override public boolean isAssociatedWithTask(DNSTask task, DNSState state) { return _state.isAssociatedWithTask(task, state); } /** * {@inheritDoc} */ @Override public boolean isProbing() { return _state.isProbing(); } /** * {@inheritDoc} */ @Override public boolean isAnnouncing() { return _state.isAnnouncing(); } /** * {@inheritDoc} */ @Override public boolean isAnnounced() { return _state.isAnnounced(); } /** * {@inheritDoc} */ @Override public boolean isCanceling() { return this._state.isCanceling(); } /** * {@inheritDoc} */ @Override public boolean isCanceled() { return _state.isCanceled(); } /** * {@inheritDoc} */ @Override public boolean isClosing() { return _state.isClosing(); } /** * {@inheritDoc} */ @Override public boolean isClosed() { return _state.isClosed(); } /** * {@inheritDoc} */ @Override public boolean waitForAnnounced(long timeout) { return _state.waitForAnnounced(timeout); } /** * {@inheritDoc} */ @Override public boolean waitForCanceled(long timeout) { return _state.waitForCanceled(timeout); } /** * {@inheritDoc} */ @Override public int hashCode() { return getQualifiedName().hashCode(); } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { return (obj instanceof ServiceInfoImpl) && getQualifiedName().equals(((ServiceInfoImpl) obj).getQualifiedName()); } /** * {@inheritDoc} */ @Override public String getNiceTextString() { StringBuffer buf = new StringBuffer(); for (int i = 0, len = this.getTextBytes().length; i < len; i++) { if (i >= 200) { buf.append("..."); break; } int ch = getTextBytes()[i] & 0xFF; if ((ch < ' ') || (ch > 127)) { buf.append("\\0"); buf.append(Integer.toString(ch, 8)); } else { buf.append((char) ch); } } return buf.toString(); } /* * (non-Javadoc) * @see javax.jmdns.ServiceInfo#clone() */ @Override public ServiceInfoImpl clone() { ServiceInfoImpl serviceInfo = new ServiceInfoImpl(this.getQualifiedNameMap(), _port, _weight, _priority, _persistent, _text); Inet6Address[] ipv6Addresses = this.getInet6Addresses(); for (Inet6Address address : ipv6Addresses) { serviceInfo._ipv6Addresses.add(address); } Inet4Address[] ipv4Addresses = this.getInet4Addresses(); for (Inet4Address address : ipv4Addresses) { serviceInfo._ipv4Addresses.add(address); } return serviceInfo; } /** * {@inheritDoc} */ @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append("[" + this.getClass().getSimpleName() + "@" + System.identityHashCode(this) + " "); buf.append("name: '"); buf.append((this.getName().length() > 0 ? this.getName() + "." : "") + this.getTypeWithSubtype()); buf.append("' address: '"); InetAddress[] addresses = this.getInetAddresses(); if (addresses.length > 0) { for (InetAddress address : addresses) { buf.append(address); buf.append(':'); buf.append(this.getPort()); buf.append(' '); } } else { buf.append("(null):"); buf.append(this.getPort()); } buf.append("' status: '"); buf.append(_state.toString()); buf.append(this.isPersistent() ? "' is persistent," : "',"); buf.append(" has "); buf.append(this.hasData() ? "" : "NO "); buf.append("data"); if (this.getTextBytes().length > 0) { // buf.append("\n"); // buf.append(this.getNiceTextString()); Map<String, byte[]> properties = this.getProperties(); if (!properties.isEmpty()) { buf.append("\n"); for (String key : properties.keySet()) { buf.append("\t" + key + ": " + new String(properties.get(key)) + "\n"); } } else { buf.append(" empty"); } } buf.append(']'); return buf.toString(); } public Collection<DNSRecord> answers(boolean unique, int ttl, HostInfo localHost) { List<DNSRecord> list = new ArrayList<DNSRecord>(); if (this.getSubtype().length() > 0) { list.add(new Pointer(this.getTypeWithSubtype(), DNSRecordClass.CLASS_IN, DNSRecordClass.NOT_UNIQUE, ttl, this.getQualifiedName())); } list.add(new Pointer(this.getType(), DNSRecordClass.CLASS_IN, DNSRecordClass.NOT_UNIQUE, ttl, this.getQualifiedName())); list.add(new Service(this.getQualifiedName(), DNSRecordClass.CLASS_IN, unique, ttl, _priority, _weight, _port, localHost.getName())); list.add(new Text(this.getQualifiedName(), DNSRecordClass.CLASS_IN, unique, ttl, this.getTextBytes())); return list; } /** * {@inheritDoc} */ @Override public void setText(byte[] text) throws IllegalStateException { synchronized (this) { this._text = text; this._props = null; this.setNeedTextAnnouncing(true); } } /** * {@inheritDoc} */ @Override public void setText(Map<String, ?> props) throws IllegalStateException { this.setText(textFromProperties(props)); } /** * This is used internally by the framework * * @param text */ void _setText(byte[] text) { this._text = text; this._props = null; } private static byte[] textFromProperties(Map<String, ?> props) { byte[] text = null; if (props != null) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(256); for (String key : props.keySet()) { Object val = props.get(key); ByteArrayOutputStream out2 = new ByteArrayOutputStream(100); writeUTF(out2, key); if (val == null) { // Skip } else if (val instanceof String) { out2.write('='); writeUTF(out2, (String) val); } else if (val instanceof byte[]) { byte[] bval = (byte[]) val; if (bval.length > 0) { out2.write('='); out2.write(bval, 0, bval.length); } else { val = null; } } else { throw new IllegalArgumentException("invalid property value: " + val); } byte data[] = out2.toByteArray(); if (data.length > 255) { throw new IOException("Cannot have individual values larger that 255 chars. Offending value: " + key + (val != null ? "" : "=" + val)); } out.write((byte) data.length); out.write(data, 0, data.length); } text = out.toByteArray(); } catch (IOException e) { throw new RuntimeException("unexpected exception: " + e); } } return (text != null && text.length > 0 ? text : DNSRecord.EMPTY_TXT); } public void setDns(JmDNSImpl dns) { this._state.setDns(dns); } /** * {@inheritDoc} */ @Override public JmDNSImpl getDns() { return this._state.getDns(); } /** * {@inheritDoc} */ @Override public boolean isPersistent() { return _persistent; } /** * @param needTextAnnouncing * the needTextAnnouncing to set */ public void setNeedTextAnnouncing(boolean needTextAnnouncing) { this._needTextAnnouncing = needTextAnnouncing; if (this._needTextAnnouncing) { _state.setTask(null); } } /** * @return the needTextAnnouncing */ public boolean needTextAnnouncing() { return _needTextAnnouncing; } /** * @return the delegate */ Delegate getDelegate() { return this._delegate; } /** * @param delegate * the delegate to set */ void setDelegate(Delegate delegate) { this._delegate = delegate; } }
package jenkins.plugins.play; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import jenkins.model.Jenkins; import jenkins.plugins.play.commands.PlayCommand; import jenkins.plugins.play.version.Play1x; import jenkins.plugins.play.version.PlayVersion; import jenkins.plugins.play.version.PlayVersionDescriptor; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import hudson.Extension; import hudson.Launcher; import hudson.Proc; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.BuildListener; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.Builder; import hudson.util.FormValidation; /** * Provides the several of the functionalities of Play!Framework in a Jenkins * plugin. This class is responsible for the Play!Framework module in the job * configuration. * */ public class PlayBuilder extends Builder { /** The Play installation path selected by the user. */ private final String playToolHome; /** Absolute or relative project path. */ private final String projectPath; /** Play version used in the job. Indicates the command set available. */ private PlayVersion playVersion; /** * Constructor used by Jenkins to handle the Play! job. * * @param playToolHome Path of Play! installation. * @param projectPath Project path. * @param playVersion Play version. */ @DataBoundConstructor public PlayBuilder(String playToolHome, String projectPath, PlayVersion playVersion) { this.playToolHome = playToolHome; this.projectPath = projectPath; this.playVersion = playVersion; } /** * Get the path of the Play! installation. * * @return the playToolHome */ public String getPlayToolHome() { return playToolHome; } /** * Get the project path. * * @return the projectPath */ public String getProjectPath() { return projectPath; } /** * @return the Play version. */ public final PlayVersion getPlayVersion() { return playVersion; } /** * Get the complete path of the Play! executable. First looks for a 'play' executable, then 'activator'. * * @param playToolHome Path of the Play tool home. * @return the Play! executable path. */ public static File getPlayExecutable(String playToolHome) { // Try play executable first File playExecutable = new File(playToolHome + "/play"); if (playExecutable.exists()) return playExecutable; // Try activator executable playExecutable = new File(playToolHome + "/activator"); if (playExecutable.exists()) return playExecutable; // There is no potential executor here. Return null. return null; } /* * (non-Javadoc) * * @see hudson.tasks.Builder#getDescriptor() */ @Override public PlayDescriptor getDescriptor() { return (PlayDescriptor) super.getDescriptor(); } /** * Generate the list of command parameters according to the user selection * on Jenkins interface. * * @return List of parameters */ public List<String> generatePlayParameters() { List<String> commandParameters = new ArrayList<String>(); // This parameter is always present to remove color formatting // characters from the output. (Except for Play 1.x) if (!(this.playVersion instanceof Play1x)) commandParameters.add("-Dsbt.log.noformat=true"); // add extension actions to command-line one by one for (PlayCommand playExt : this.playVersion.getCommands()) { // Every command parameter can be surrounded by quotes, have them // additional parameters or not. // HOWEVER, the launcher already adds quotes automatically // whenever the parameter is composed of two or more strings. // Therefore, no need to add the quotes here. String command = playExt.getCommand() + " " + playExt.getParameter(); // Trim the String to remove leading and trailing whitespace (just // esthetical reason) // Add generated parameter to the array of parameters commandParameters.add(command.trim()); } return commandParameters; } /* * (non-Javadoc) * * @see * hudson.tasks.BuildStepCompatibilityLayer#perform(hudson.model.AbstractBuild * , hudson.Launcher, hudson.model.BuildListener) */ @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { // Create file from play path String File playExecutable = PlayBuilder.getPlayExecutable(this.playToolHome); // Check if play executable exists if (playExecutable == null) { return false; } // Create file from project path String File projectFile = new File(this.getProjectPath()); // Check if project folder exists if (!projectFile.exists()) { listener.getLogger().println("ERROR! Project path not found!"); return false; } // Creates the complete list of parameters including goals List<String> commandParameters = generatePlayParameters(); // Validated that there are commands set up if (commandParameters == null) { listener.getLogger().println("ERROR! No commands were provided."); return false; } for (String comm : commandParameters) { listener.getLogger().println("Command detected: " + comm); } // Play 1.x is not able to execute several commands in sequence. // Instead, it should call the 'play' executable for every command // separately. if (this.getPlayVersion() instanceof Play1x) { // For each command... for (String comm : commandParameters) { // In Play1x, commands should not have quotes. Since the // launcher automatically adds quotes if the command contains // whitespace, it is necessary to split the command in the // whitespaces first and provide them to the launcher as an // array. // ... run it in a new process. Proc proc = launcher .launch() .cmds(playExecutable, comm.split(" ")) .pwd(this.getProjectPath()) .writeStdin().stdout(listener.getLogger()) .stderr(listener.getLogger()).start(); int result = proc.join(); // Immediately stop the build process when a command results in error. if (result != 0) { listener.getLogger().println("ERROR! Failed to execute the Play! command."); return false; } } // Every command ran successfully return true; } // Play 2.x (sbt) is able to execute all commands at once else { // Launch Play!Framework Proc proc = launcher .launch() .cmds(playExecutable, commandParameters.toArray(new String[commandParameters.size()])) .pwd(this.getProjectPath()) .writeStdin().stdout(listener.getLogger()) .stderr(listener.getLogger()).start(); return proc.join() == 0; } } /** * Descriptor to capture and validate fields from the interface. */ @Extension public static class PlayDescriptor extends BuildStepDescriptor<Builder> { /** * Descriptor constructor. */ public PlayDescriptor() { load(); } public PlayDescriptor(Class<? extends Builder> clazz) { super(clazz); load(); } /* * (non-Javadoc) * * @see hudson.tasks.BuildStepDescriptor#isApplicable(java.lang.Class) */ @Override public boolean isApplicable(Class<? extends AbstractProject> jobType) { return true; } /* * (non-Javadoc) * * @see hudson.model.Descriptor#getDisplayName() */ @Override public String getDisplayName() { return "Invoke Play!Framework"; } /** * Get available Play! installations. * * @return Array of Play installations */ public PlayInstallation[] getInstallations() { return Jenkins.getInstance() .getDescriptorByType(PlayInstallation.PlayToolDescriptor.class) .getInstallations(); } /** * Retrieve list of Play! versions. * @return */ public List<PlayVersionDescriptor> getPlayVersion() { return Jenkins.getInstance().getDescriptorList(PlayVersion.class); } /** * Check if the project path field is not empty and exists. * * @param projectPath * Project path * @return Form validation */ public FormValidation doCheckProjectPath( @QueryParameter String projectPath) { // If field is empty, call the required validator if (projectPath.isEmpty()) return FormValidation.validateRequired(projectPath); // Otherwise, check if the project path is valid File projectPathDir = new File(projectPath); if (!projectPathDir.exists()) return FormValidation.error("Project path has not been found!"); return FormValidation.ok(); } } }
package local.jniGenerator; import java.lang.reflect.Method; import java.lang.reflect.Modifier; public class MethodWrapper { public MethodWrapper(Method method) { this.method = method; } public String getName() { return method.getName(); } public static String getMethodSignature(Method method) { String result = "("; for (Class<?> paramClass : method.getParameterTypes()) { result += TypeWrapper.getTypeSignature(paramClass); } result += ")" + TypeWrapper.getTypeSignature(method.getReturnType()); return result; } public String getMethodSignature() { return getMethodSignature(method); } public boolean isStatic() { return Modifier.isStatic(method.getModifiers()); } private final Method method; }
package logbook.api; import java.util.List; import java.util.Map; import javax.json.JsonArray; import javax.json.JsonObject; import logbook.bean.DeckPort; import logbook.bean.DeckPortCollection; import logbook.bean.Ship; import logbook.bean.ShipCollection; import logbook.internal.JsonHelper; import logbook.proxy.RequestMetaData; import logbook.proxy.ResponseMetaData; /** * /kcsapi/api_get_member/ship_deck * */ @API("/kcsapi/api_get_member/ship_deck") public class ApiGetMemberShipDeck implements APIListenerSpi { @Override public void accept(JsonObject json, RequestMetaData req, ResponseMetaData res) { JsonObject data = json.getJsonObject("api_data"); if (data != null) { this.apiShipData(data.getJsonArray("api_ship_data")); this.apiDeckData(data.getJsonArray("api_deck_data")); } } /** * api_data.api_ship_data * * @param array api_ship_data */ private void apiShipData(JsonArray array) { Map<Integer, Ship> map = ShipCollection.get() .getShipMap(); map.putAll(JsonHelper.toMap(array, Ship::getId, Ship::toShip)); } /** * api_data.api_deck_data * * @param array api_deck_data */ private void apiDeckData(JsonArray array) { List<DeckPort> list = DeckPortCollection.get() .getDeckPorts(); List<DeckPort> newList = JsonHelper.toList(array, DeckPort::toDeckPort); for (DeckPort newPort : newList) { list.replaceAll(e -> { if (e.getId().equals(newPort.getId())) { return newPort; } return e; }); } } }
package me.dinowernli.grpc.polyglot; import java.util.logging.LogManager; import com.google.protobuf.DescriptorProtos.FileDescriptorSet; import me.dinowernli.grpc.polyglot.command.ServiceCall; import me.dinowernli.grpc.polyglot.command.ServiceList; import me.dinowernli.grpc.polyglot.config.CommandLineArgs; import me.dinowernli.grpc.polyglot.config.ConfigurationLoader; import me.dinowernli.grpc.polyglot.io.Output; import me.dinowernli.grpc.polyglot.protobuf.ProtocInvoker; import me.dinowernli.grpc.polyglot.protobuf.ProtocInvoker.ProtocInvocationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.bridge.SLF4JBridgeHandler; import polyglot.ConfigProto.Configuration; import polyglot.ConfigProto.ProtoConfiguration; public class Main { private static final Logger logger = LoggerFactory.getLogger(Main.class); private static final String VERSION = "1.3.0+dev"; public static void main(String[] args) { // Fix the logging setup. setupJavaUtilLogging(); logger.info("Polyglot version: " + VERSION); final CommandLineArgs arguments; try { arguments = CommandLineArgs.parse(args); } catch (RuntimeException e) { logger.info("Unable to parse flags", e); return; } // Catch the help case. if (arguments.isHelp()) { logger.info("Usage: " + CommandLineArgs.getUsage()); return; } ConfigurationLoader configLoader = arguments.configSetPath().isPresent() ? ConfigurationLoader.forFile(arguments.configSetPath().get()) : ConfigurationLoader.forDefaultConfigSet(); configLoader = configLoader.withOverrides(arguments); Configuration config = arguments.configName().isPresent() ? configLoader.getNamedConfiguration(arguments.configName().get()) : configLoader.getDefaultConfiguration(); logger.info("Loaded configuration: " + config.getName()); FileDescriptorSet fileDescriptorSet = getFileDescriptorSet(config.getProtoConfig()); String command; if (arguments.command().isPresent()) { command = arguments.command().get(); } else { logger.warn("Missing --command flag - defaulting to 'call' (but please update your args)"); command = CommandLineArgs.CALL_COMMAND; } try(Output commandLineOutput = Output.forConfiguration(config.getOutputConfig())) { switch (command) { case CommandLineArgs.LIST_SERVICES_COMMAND: ServiceList.listServices( commandLineOutput, fileDescriptorSet, config.getProtoConfig().getProtoDiscoveryRoot(), arguments.serviceFilter(), arguments.methodFilter(), arguments.withMessage()); break; case CommandLineArgs.CALL_COMMAND: ServiceCall.callEndpoint( commandLineOutput, fileDescriptorSet, arguments.endpoint(), arguments.fullMethod(), arguments.protoDiscoveryRoot(), arguments.configSetPath(), arguments.additionalProtocIncludes(), config.getCallConfig()); break; default: logger.warn("Unknown command: " + arguments.command().get()); } } catch (Exception e) { throw new RuntimeException("Caught exception during command execution", e); } } /** Invokes protoc and returns a {@link FileDescriptorSet} used for discovery. */ private static FileDescriptorSet getFileDescriptorSet(ProtoConfiguration protoConfig) { try { return ProtocInvoker.forConfig(protoConfig).invoke(); } catch (ProtocInvocationException e) { throw new RuntimeException("Failed to invoke the protoc binary", e); } } /** Redirects the output of standard java loggers to our slf4j handler. */ private static void setupJavaUtilLogging() { LogManager.getLogManager().reset(); SLF4JBridgeHandler.removeHandlersForRootLogger(); SLF4JBridgeHandler.install(); } }
package me.hugmanrique.pokedata.maps; import lombok.Getter; import lombok.ToString; import me.hugmanrique.pokedata.Data; import me.hugmanrique.pokedata.connections.ConnectionData; import me.hugmanrique.pokedata.loaders.ROMData; import me.hugmanrique.pokedata.maps.banks.BankLoader; import me.hugmanrique.pokedata.sprites.SpritesHeader; import me.hugmanrique.pokedata.sprites.exits.SpritesExitManager; import me.hugmanrique.pokedata.sprites.npcs.SpritesNPCManager; import me.hugmanrique.pokedata.sprites.signs.SpritesSignManager; import me.hugmanrique.pokedata.sprites.triggers.TriggerManager; import me.hugmanrique.pokedata.utils.BitConverter; import me.hugmanrique.pokedata.roms.ROM; @Getter @ToString public class Map extends Data { private MapHeader header; private ConnectionData connections; private SpritesHeader sprites; private SpritesNPCManager npcManager; private SpritesSignManager signManager; private TriggerManager triggerManager; private SpritesExitManager exitManager; public Map(ROM rom) { header = new MapHeader(rom); rom.seek(BitConverter.shortenPointer(header.getConnectPtr())); connections = new ConnectionData(rom); // Sprites loading /*rom.seek((int) header.getSpritesPtr() & 0x1FFFFFF); sprites = new SpritesHeader(rom); npcManager = new SpritesNPCManager(rom, (int) sprites.getNpcPtr(), sprites.getNpcAmount()); signManager = new SpritesSignManager(rom, (int) sprites.getSignsPtr(), sprites.getSignsAmount()); triggerManager = new TriggerManager(rom, (int) sprites.getTriggersPtr(), sprites.getTriggersAmount()); exitManager = new SpritesExitManager(rom, (int) sprites.getExitsPtr(), sprites.getExitsAmount());*/ } public static Map load(ROM rom, ROMData data, int bank, int id) { int pointer = BankLoader.getMapHeaderPointer(rom, data, bank, id); rom.seek(pointer); Map map = new Map(rom); injectMapName(rom, data, map); return map; } private static void injectMapName(ROM rom, ROMData data, Map map) { byte labelId = map.getHeader().getLabelId(); int offset; // Switch depending on the engine version if (rom.getGame().isElements()) { offset = data.getMapLabelData() + (labelId - 0x58) * 4; } else { // TODO Will cause issues with custom games offset = data.getMapLabelData() + (labelId * 8) + 4; } int namePointer = rom.getPointerAsInt(offset); String name = rom.readPokeText(namePointer, -1); map.setHeaderName(name); } private void setHeaderName(String name) { getHeader().setName(name); } }
package me.otisdiver.otisarena; import org.bukkit.Bukkit; import org.bukkit.plugin.java.JavaPlugin; import me.otisdiver.otisarena.event.ClickHandler; import me.otisdiver.otisarena.event.GameDeath; import me.otisdiver.otisarena.event.JoinQuit; import me.otisdiver.otisarena.event.LobbyGuard; import me.otisdiver.otisarena.event.StartingCanceller; import me.otisdiver.otisarena.event.WorldGuard; import me.otisdiver.otisarena.game.Game; import me.otisdiver.otisarena.task.kit.Ability; import me.otisdiver.otisarena.utils.ConfigUtils; public class OtisArena extends JavaPlugin { private Game game; @Override public void onEnable() { // instantiate the game class game = new Game(this); // register commands Bukkit.getPluginCommand("endgame").setExecutor(new Commander(this)); // load various static classes ConfigUtils.initiate(this); Ability.initiate(this); // register event listeners new JoinQuit(this); new StartingCanceller(this); new GameDeath(this); new LobbyGuard(this); new WorldGuard(this); new ClickHandler(this); } @Override public void onDisable() { // clear static initializations ConfigUtils.reset(); Ability.reset(); } public Game getGame() { return game; } }
package ml.duncte123.skybot; import net.dv8tion.jda.bot.sharding.ShardManager; import net.dv8tion.jda.core.JDA; import net.dv8tion.jda.core.JDA.ShardInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; class ShardWatcher { private final long[] pings; private final Logger logger = LoggerFactory.getLogger(ShardWatcher.class); ShardWatcher(SkyBot skyBot) { final ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); final int totalShards = skyBot.getShardManager().getShardsTotal(); this.pings = new long[totalShards]; service.scheduleAtFixedRate(this::checkShards,10, 10, TimeUnit.MINUTES); } private void checkShards() { final ShardManager shardManager = SkyBot.getInstance().getShardManager(); logger.debug("Checking shards"); for (final JDA shard : shardManager.getShardCache()) { final ShardInfo info = shard.getShardInfo(); final long ping = shard.getPing(); final long oldPing = this.pings[info.getShardId()]; if (oldPing != ping) { this.pings[info.getShardId()] = ping; } else { logger.warn("{} is possibly down", info); } } logger.debug("Checking done"); } }
package name.kevinross.tool; import android.app.ActivityThread; import android.content.Context; import android.os.Debug; import android.os.Looper; import android.os.UserHandle; import android.os.Process; import joptsimple.OptionParser; import joptsimple.OptionSet; /** * Abstract class that facilitates debugging of non-android-app java code. Extend this and * implement AbstractTool#run(String[]) as the entry point for tool code. */ public abstract class AbstractTool { private boolean willWaitForDebugger = false; private String[] args = new String[]{}; private Context thisContext = null; protected Context getContext() { return thisContext; } public AbstractTool() { Process.setArgV0(this.getClass().getName()); ReflectionUtil.invokes().on(android.ddm.DdmHandleAppName.class). name("setAppName"). of(String.class, int.class). using(this.getClass().getName(), UserHandle.myUserId()). swallow().invoke(); } public void setWaitForDebugger(boolean willWait) { willWaitForDebugger = willWait; } public void setArgs(String[] args) { this.args = args; } public void setContext(Context ctx) { thisContext = ctx; } public void start() { if (willWaitForDebugger) { Debug.waitForDebugger(); } OptionParser parser = getArgParser(); if (parser != null) { run(parser.parse(this.args)); } else { run(args); } } protected void run(String[] args) { throw new RuntimeException("subclass must implement this if no arg parser is to be used"); } protected void run(OptionSet parser) { throw new RuntimeException("subclass must implement this if getArgParser is used"); } protected OptionParser getArgParser() { return null; } }
package net.imagej.legacy; import org.scijava.command.Command; import org.scijava.menu.MenuConstants; import org.scijava.options.OptionsPlugin; import org.scijava.plugin.Menu; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; /** * Allows the setting and persisting of options relevant to ImageJ2, in ImageJ1. * Not displayed in the IJ2 UI. * * @author Mark Hiner */ @Plugin(type = Command.class, visible = false, label = "ImageJ2 Options", menu = { @Menu(label = MenuConstants.EDIT_LABEL, weight = MenuConstants.EDIT_WEIGHT, mnemonic = MenuConstants.EDIT_MNEMONIC), @Menu(label = "Options"), @Menu(label = "ImageJ2") }) public class ImageJ2Options extends OptionsPlugin implements Command { // Constants for field lookup public static final String USE_SCIFIO = "useSCIFIO"; // Fields /** * If true, SCIFIO will be used during {@code File > Open} IJ1 calls. */ @Parameter(label = "Use SCIFIO for File > Open") private Boolean useSCIFIO = true; @Parameter(persist = false) private DefaultLegacyService legacyService; // -- Option accessors -- public Boolean isUseSCIFIO() { return useSCIFIO; } }
package net.openhft.chronicle.core; public enum Maths { ; /** * Numbers larger than this are whole numbers due to representation error. */ private static final double WHOLE_NUMBER = 1L << 53; private static final int K0 = 0x6d0f27bd; private static final int M0 = 0x5bc80bad; private static final int M1 = 0xea7585d7; private static final int M2 = 0x7a646e19; private static final int M3 = 0x855dd4db; /** * Performs a round which is accurate to within 1 ulp. i.e. for values very close to 0.5 it * might be rounded up or down. This is a pragmatic choice for performance reasons as it is * assumed you are not working on the edge of the precision of double. * * @param d value to round * @return rounded value */ public static double round2(double d) { final double factor = 1e2; return d > WHOLE_NUMBER || d < -WHOLE_NUMBER ? d : (long) (d < 0 ? d * factor - 0.5 : d * factor + 0.5) / factor; } /** * Performs a round which is accurate to within 1 ulp. i.e. for values very close to 0.5 it * might be rounded up or down. This is a pragmatic choice for performance reasons as it is * assumed you are not working on the edge of the precision of double. * * @param d value to round * @return rounded value */ public static double round4(double d) { final double factor = 1e4; return d > Long.MAX_VALUE / factor || d < -Long.MAX_VALUE / factor ? d : (long) (d < 0 ? d * factor - 0.5 : d * factor + 0.5) / factor; } /** * Performs a round which is accurate to within 1 ulp. i.e. for values very close to 0.5 it * might be rounded up or down. This is a pragmatic choice for performance reasons as it is * assumed you are not working on the edge of the precision of double. * * @param d value to round * @return rounded value */ public static double round6(double d) { final double factor = 1e6; return d > Long.MAX_VALUE / factor || d < -Long.MAX_VALUE / factor ? d : (long) (d < 0 ? d * factor - 0.5 : d * factor + 0.5) / factor; } /** * Performs a round which is accurate to within 1 ulp. i.e. for values very close to 0.5 it * might be rounded up or down. This is a pragmatic choice for performance reasons as it is * assumed you are not working on the edge of the precision of double. * * @param d value to round * @return rounded value */ public static double round8(double d) { final double factor = 1e8; return d > Long.MAX_VALUE / factor || d < -Long.MAX_VALUE / factor ? d : (long) (d < 0 ? d * factor - 0.5 : d * factor + 0.5) / factor; } public static int nextPower2(int n, int min) throws IllegalArgumentException { return (int) Math.min(1 << 30, nextPower2((long) n, (long) min)); } public static long nextPower2(long n, long min) throws IllegalArgumentException { if (!isPowerOf2(min)) throw new IllegalArgumentException(min+" must be a power of 2"); if (n < min) return min; if (isPowerOf2(n)) return n; long i = min; while (i < n) { i *= 2; if (i <= 0) return 1L << 62; } return i; } static boolean isPowerOf2(long n) { return Long.bitCount(n) == 1; } public static int hash32(CharSequence cs) { long h = hash64(cs); h ^= h >> 32; return (int) h; } public static int hash32(long l0) { long h = hash64(l0); h ^= h >> 32; return (int) h; } public static long hash64(CharSequence cs) { long hash = 0; for (int i = 0; i < cs.length(); i++) hash = hash * 841248317 + cs.charAt(i); return agitate(hash); } public static int intLog2(long num) { long l = Double.doubleToRawLongBits((double) num); return (int) ((l >> 52) - 1023L); } public static byte toInt8(long x) throws IllegalArgumentException { if ((byte) x == x) return (byte) x; throw new IllegalArgumentException("Byte " + x + " out of range"); } public static short toInt16(long x) throws IllegalArgumentException { if ((short) x == x) return (short) x; throw new IllegalArgumentException("Short " + x + " out of range"); } public static int toInt32(long x, String msg) throws IllegalArgumentException { if ((int) x == x) return (int) x; throw new IllegalArgumentException(String.format(msg, x)); } public static int toInt32(long x) throws IllegalArgumentException { if ((int) x == x) return (int) x; throw new IllegalArgumentException("Int " + x + " out of range"); } public static short toUInt8(long x) throws IllegalArgumentException { if ((x & 0xFF) == x) return (short) x; throw new IllegalArgumentException("Unsigned Byte " + x + " out of range"); } public static int toUInt16(long x) throws IllegalArgumentException { if ((x & 0xFFFF) == x) return (int) x; throw new IllegalArgumentException("Unsigned Short " + x + " out of range"); } public static int toUInt31(long x) throws IllegalArgumentException { if ((x & 0x7FFFFFFFL) == x) return (int) x; throw new IllegalArgumentException("Unsigned Int 31-bit " + x + " out of range"); } public static long toUInt32(long x) throws IllegalArgumentException { if ((x & 0xFFFFFFFFL) == x) return x; throw new IllegalArgumentException("Unsigned Int " + x + " out of range"); } public static long agitate(long l) { l += l >>> 22; l ^= Long.rotateRight(l, 17); return l; } /** * A simple hashing algorithm for a 64-bit value * * @param l0 to hash * @return hash value. */ public static long hash64(long l0) { int l0a = (int) (l0 >> 32); long h0 = l0 * M0 + l0a * M1; return agitate(h0); } /** * A simple hashing algorithm for a 128-bit value * * @param l0 to hash * @param l1 to hash * @return hash value. */ public static long hash64(long l0, long l1) { int l0a = (int) (l0 >> 32); int l1a = (int) (l1 >> 32); long h0 = (l0 + l1a) * M0; long h1 = (l1 + l0a) * M1; return agitate(h0) ^ agitate(h1); } }
package org.clafer.ir.analysis; import gnu.trove.iterator.TIntIterator; import gnu.trove.set.TIntSet; import gnu.trove.set.hash.TIntHashSet; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.clafer.collection.DisjointSets; import org.clafer.collection.Pair; import org.clafer.collection.Triple; import org.clafer.ir.IrAdd; import org.clafer.ir.IrAllDifferent; import org.clafer.ir.IrArrayToSet; import org.clafer.ir.IrBoolChannel; import org.clafer.ir.IrBoolDomain; import org.clafer.ir.IrBoolExpr; import org.clafer.ir.IrBoolExprVisitorAdapter; import org.clafer.ir.IrBoolVar; import org.clafer.ir.IrCard; import org.clafer.ir.IrCompare; import org.clafer.ir.IrDomain; import org.clafer.ir.IrElement; import org.clafer.ir.IrFilterString; import org.clafer.ir.IrIfOnlyIf; import org.clafer.ir.IrIntChannel; import org.clafer.ir.IrIntExpr; import org.clafer.ir.IrIntVar; import org.clafer.ir.IrJoinFunction; import org.clafer.ir.IrJoinRelation; import org.clafer.ir.IrMember; import org.clafer.ir.IrMinus; import org.clafer.ir.IrModule; import org.clafer.ir.IrNot; import org.clafer.ir.IrNotMember; import org.clafer.ir.IrNotWithin; import org.clafer.ir.IrOffset; import org.clafer.ir.IrRewriter; import org.clafer.ir.IrSelectN; import org.clafer.ir.IrSetExpr; import org.clafer.ir.IrSetTest; import org.clafer.ir.IrSetUnion; import org.clafer.ir.IrSetVar; import org.clafer.ir.IrSingleton; import org.clafer.ir.IrSortSets; import org.clafer.ir.IrSortStrings; import org.clafer.ir.IrSortStringsChannel; import org.clafer.ir.IrSubsetEq; import org.clafer.ir.IrUtil; import org.clafer.ir.IrWithin; import static org.clafer.ir.Irs.*; /** * @author jimmy */ public class Coalescer { private Coalescer() { } public static Triple<Map<IrIntVar, IrIntVar>, Map<IrSetVar, IrSetVar>, IrModule> coalesce(IrModule module) { Pair<DisjointSets<IrIntVar>, DisjointSets<IrSetVar>> graphs = findEquivalences(module.getConstraints()); DisjointSets<IrIntVar> intGraph = graphs.getFst(); DisjointSets<IrSetVar> setGraph = graphs.getSnd(); Map<IrIntVar, IrIntVar> coalescedInts = new HashMap<>(); Map<IrSetVar, IrSetVar> coalescedSets = new HashMap<>(); for (Set<IrIntVar> component : intGraph.connectedComponents()) { if (component.size() > 1) { Iterator<IrIntVar> iter = component.iterator(); IrIntVar var = iter.next(); StringBuilder name = new StringBuilder().append(var.getName()); IrDomain domain = var.getDomain(); while (iter.hasNext()) { var = iter.next(); name.append(';').append(var.getName()); domain = IrUtil.intersection(domain, var.getDomain()); } if (domain.isEmpty()) { // Model is unsatisfiable. Compile anyways? } else { IrIntVar coalesced = domainInt(name.toString(), domain); for (IrIntVar coalesce : component) { if (!coalesced.equals(coalesce)) { coalescedInts.put(coalesce, coalesced); } } } } } for (Set<IrSetVar> component : setGraph.connectedComponents()) { if (component.size() > 1) { Iterator<IrSetVar> iter = component.iterator(); IrSetVar var = iter.next(); StringBuilder name = new StringBuilder().append(var.getName()); IrDomain env = var.getEnv(); IrDomain ker = var.getKer(); IrDomain card = var.getCard(); while (iter.hasNext()) { var = iter.next(); name.append(';').append(var.getName()); env = IrUtil.intersection(env, var.getEnv()); ker = IrUtil.union(ker, var.getKer()); card = IrUtil.intersection(card, var.getCard()); } IrSetVar coalesced = newSet(name.toString(), env, ker, card); if (coalesced != null) { for (IrSetVar coalesce : component) { if (!coalesced.equals(coalesce)) { coalescedSets.put(coalesce, coalesced); } } } } } return new Triple<>( coalescedInts, coalescedSets, new CoalesceRewriter(coalescedInts, coalescedSets).rewrite(module, null)); } private static IrSetVar newSet(String name, IrDomain env, IrDomain ker, IrDomain card) { if (!IrUtil.isSubsetOf(ker, env) || ker.size() > env.size()) { // Model is unsatisfiable. Compile anyways? } else { IrDomain boundCard = IrUtil.intersection(boundDomain(ker.size(), env.size()), card); if (boundCard.isEmpty()) { // Model is unsatisfiable. Compile anyways? } else { return set(name.toString(), env, ker, boundCard); } } return null; } private static Pair<DisjointSets<IrIntVar>, DisjointSets<IrSetVar>> findEquivalences(Iterable<IrBoolExpr> constraints) { DisjointSets<IrIntVar> intGraph = new DisjointSets<>(); DisjointSets<IrSetVar> setGraph = new DisjointSets<>(); EquivalenceFinder finder = new EquivalenceFinder(intGraph, setGraph); for (IrBoolExpr constraint : constraints) { constraint.accept(finder, null); } return new Pair<>(intGraph, setGraph); } private static class EquivalenceFinder extends IrBoolExprVisitorAdapter<Void, Void> { private final DisjointSets<IrIntVar> intGraph; private final DisjointSets<IrSetVar> setGraph; private final Map<IrSetVar, IrIntVar> duplicates = new HashMap<>(); private EquivalenceFinder(DisjointSets<IrIntVar> intGraph, DisjointSets<IrSetVar> setGraph) { this.intGraph = intGraph; this.setGraph = setGraph; } @Override public Void visit(IrBoolVar ir, Void a) { if (IrBoolDomain.BoolDomain.equals(ir.getDomain())) { intGraph.union(ir, True); } return null; } @Override public Void visit(IrNot ir, Void a) { propagateInt(FalseDomain, ir.getExpr()); return null; } @Override public Void visit(IrIfOnlyIf ir, Void a) { propagateEqual(ir.getLeft(), ir.getRight()); return null; } @Override public Void visit(IrWithin ir, Void a) { propagateInt(ir.getRange(), ir.getValue()); return null; } @Override public Void visit(IrNotWithin ir, Void a) { propagateInt(IrUtil.difference(ir.getValue().getDomain(), ir.getRange()), ir.getValue()); return null; } @Override public Void visit(IrCompare ir, Void a) { IrIntExpr left = ir.getLeft(); IrIntExpr right = ir.getRight(); switch (ir.getOp()) { case Equal: propagateEqual(left, right); break; case NotEqual: propagateNotEqual(left, right); break; case LessThan: propagateLessThan(left, right); break; case LessThanEqual: propagateLessThanEqual(left, right); break; } return null; } @Override public Void visit(IrSetTest ir, Void a) { IrSetExpr left = ir.getLeft(); IrSetExpr right = ir.getRight(); if (IrSetTest.Op.Equal.equals(ir.getOp())) { if (left instanceof IrSetVar && right instanceof IrSetVar) { setGraph.union((IrSetVar) left, (IrSetVar) right); } else { propagateSet(new PartialSet(left.getEnv(), left.getKer(), left.getCard()), right); propagateSet(new PartialSet(right.getEnv(), right.getKer(), right.getCard()), left); } } return null; } @Override public Void visit(IrMember ir, Void a) { IrIntExpr element = ir.getElement(); IrSetExpr set = ir.getSet(); propagateInt(set.getEnv(), element); IrDomain ker = null; Integer constant = IrUtil.getConstant(element); if (constant != null && !set.getKer().contains(constant)) { ker = IrUtil.add(set.getKer(), constant); } IrDomain card = null; if (set.getCard().getLowBound() == 0) { card = IrUtil.remove(set.getCard(), 0); } if (ker != null || card != null) { propagateSet(new PartialSet(null, ker, card), set); } return null; } @Override public Void visit(IrNotMember ir, Void a) { IrIntExpr element = ir.getElement(); IrSetExpr set = ir.getSet(); IrDomain domain = IrUtil.difference(element.getDomain(), set.getKer()); propagateInt(domain, element); Integer constant = IrUtil.getConstant(element); if (constant != null && set.getEnv().contains(constant)) { propagateEnv(IrUtil.remove(set.getEnv(), constant), set); } return null; } @Override public Void visit(IrBoolChannel ir, Void a) { IrBoolExpr[] bools = ir.getBools(); IrSetExpr set = ir.getSet(); IrDomain env = set.getEnv(); IrDomain ker = set.getKer(); TIntHashSet trues = new TIntHashSet(ker.size()); TIntHashSet notFalses = new TIntHashSet(env.size()); env.transferTo(notFalses); boolean changed = false; for (int i = 0; i < bools.length; i++) { if (bools[i] instanceof IrBoolVar && !IrUtil.isConstant(bools[i])) { if (!env.contains(i)) { intGraph.union((IrBoolVar) bools[i], False); } else if (ker.contains(i)) { intGraph.union((IrBoolVar) bools[i], True); } } if (IrUtil.isTrue(ir)) { changed |= trues.add(i); } if (IrUtil.isFalse(bools[i])) { changed |= notFalses.remove(i); } } if (changed) { propagateSet(new PartialSet(enumDomain(notFalses), enumDomain(trues), null), set); } return null; } @Override public Void visit(IrIntChannel ir, Void a) { IrIntExpr[] ints = ir.getInts(); IrSetExpr[] sets = ir.getSets(); TIntSet kers = new TIntHashSet(); for (int i = 0; i < ints.length; i++) { TIntSet domain = new TIntHashSet(); for (int j = 0; j < sets.length; j++) { if (sets[j].getEnv().contains(i)) { domain.add(j); } } propagateInt(enumDomain(domain), ints[i]); } int lowCards = 0; int highCards = 0; for (IrSetExpr set : sets) { set.getKer().transferTo(kers); lowCards += set.getCard().getLowBound(); highCards += set.getCard().getHighBound(); } for (int i = 0; i < sets.length; i++) { TIntSet env = new TIntHashSet(); TIntSet ker = new TIntHashSet(); for (int j = 0; j < ints.length; j++) { if (ints[j].getDomain().contains(i)) { env.add(j); if (ints[j].getDomain().size() == 1) { ker.add(j); } } } env.removeAll(kers); sets[i].getKer().transferTo(env); IrDomain card = boundDomain( ints.length - highCards + sets[i].getCard().getHighBound(), ints.length - lowCards + sets[i].getCard().getLowBound()); propagateSet(new PartialSet(enumDomain(env), enumDomain(ker), card), sets[i]); } return null; } @Override public Void visit(IrSortSets ir, Void a) { int low = 0; int high = 0; for (IrSetExpr set : ir.getSets()) { IrDomain card = set.getCard(); int newLow = low + card.getLowBound(); int newHigh = high + card.getHighBound(); IrDomain env = boundDomain(low, newHigh - 1); IrDomain ker = high < newLow ? boundDomain(high, newLow - 1) : null; propagateSet(new PartialSet(env, ker, null), set); low = newLow; high = newHigh; } return null; } @Override public Void visit(IrSortStrings ir, Void a) { IrIntExpr[][] strings = ir.getStrings(); for (int i = 0; i < strings.length - 1; i++) { propagateLessThanEqualString(strings[i], strings[i + 1]); } return null; } @Override public Void visit(IrSortStringsChannel ir, Void a) { IrIntExpr[][] strings = ir.getStrings(); IrIntExpr[] ints = ir.getInts(); for (int i = 0; i < strings.length; i++) { for (int j = i + 1; j < strings.length; j++) { switch (IrUtil.compareString(strings[i], strings[j])) { case EQ: propagateEqual(ints[i], ints[j]); break; case LT: propagateLessThan(ints[i], ints[j]); break; case LE: propagateLessThanEqual(ints[i], ints[j]); break; case GT: propagateLessThan(ints[j], ints[i]); break; case GE: propagateLessThanEqual(ints[j], ints[i]); break; } } } for (int i = 0; i < ints.length; i++) { for (int j = i + 1; j < ints.length; j++) { switch (IrUtil.compare(ints[i], ints[j])) { case EQ: propagateEqualString(strings[i], strings[j]); break; case LT: propagateLessThanString(strings[i], strings[j]); break; case LE: propagateLessThanEqualString(strings[i], strings[j]); break; case GT: propagateLessThanString(strings[j], strings[i]); break; case GE: propagateLessThanEqualString(strings[j], strings[i]); break; } } } return null; } @Override public Void visit(IrAllDifferent ir, Void a) { IrIntExpr[] operands = ir.getOperands(); for (int i = 0; i < operands.length; i++) { for (int j = i + 1; j > operands.length; j++) { propagateNotEqual(operands[i], operands[j]); } } return null; } @Override public Void visit(IrSelectN ir, Void a) { IrBoolExpr[] bools = ir.getBools(); IrIntExpr n = ir.getN(); for (int i = 0; i < bools.length; i++) { if (IrUtil.isTrue(bools[i]) && i >= n.getDomain().getLowBound()) { propagateInt(boundDomain(i + 1, bools.length), n); } else if (IrUtil.isFalse(bools[i]) && i < n.getDomain().getHighBound()) { propagateInt(boundDomain(0, i), n); } } for (int i = 0; i < n.getDomain().getLowBound(); i++) { propagateInt(TrueDomain, bools[i]); } for (int i = n.getDomain().getHighBound(); i < bools.length; i++) { propagateInt(FalseDomain, bools[i]); } return null; } @Override public Void visit(IrSubsetEq ir, Void a) { IrSetExpr sub = ir.getSubset(); IrSetExpr sup = ir.getSuperset(); propagateSet(new PartialSet(sup.getEnv(), null, sup.getCard()), sub); propagateSet(new PartialSet(null, sub.getKer(), IrUtil.boundLow(sup.getCard(), sub.getCard().getLowBound())), sub); return null; } @Override public Void visit(IrFilterString ir, Void a) { TIntIterator iter = ir.getSet().getEnv().iterator(); int i = 0; while (iter.hasNext()) { int env = iter.next(); if (!ir.getSet().getKer().contains(env)) { break; } IrIntExpr string = ir.getString()[env - ir.getOffset()]; IrIntExpr result = ir.getResult()[i]; propagateEqual(string, result); i++; } return null; } private void propagateEqual(IrIntExpr left, IrIntExpr right) { Pair<IrIntExpr, IrSetVar> cardinality = AnalysisUtil.getAssignCardinality(left, right); if (cardinality != null) { IrIntExpr cardExpr = cardinality.getFst(); IrSetVar setVar = cardinality.getSnd(); if (cardExpr instanceof IrIntVar) { IrIntVar cardVar = (IrIntVar) cardExpr; IrIntVar duplicate = duplicates.put(setVar, cardVar); if (duplicate != null) { intGraph.union(cardVar, duplicate); return; } } } if (left instanceof IrIntVar && right instanceof IrIntVar) { intGraph.union((IrIntVar) left, (IrIntVar) right); } else { propagateInt(left.getDomain(), right); propagateInt(right.getDomain(), left); } } private void propagateEqualString(IrIntExpr[] a, IrIntExpr[] b) { for (int i = 0; i < a.length; i++) { propagateEqual(a[i], b[i]); } } private void propagateNotEqual(IrIntExpr left, IrIntExpr right) { Integer constant = IrUtil.getConstant(left); if (constant != null) { IrDomain minus = IrUtil.remove(right.getDomain(), constant); propagateInt(minus, right); } constant = IrUtil.getConstant(right); if (constant != null) { IrDomain minus = IrUtil.remove(left.getDomain(), constant); propagateInt(minus, left); } } private void propagateLessThan(IrIntExpr left, IrIntExpr right) { IrDomain leftDomain = left.getDomain(); IrDomain rightDomain = right.getDomain(); if (leftDomain.getHighBound() >= rightDomain.getHighBound()) { propagateInt(IrUtil.boundHigh(leftDomain, rightDomain.getHighBound() - 1), left); } if (rightDomain.getLowBound() <= leftDomain.getLowBound()) { propagateInt(IrUtil.boundLow(rightDomain, leftDomain.getLowBound() + 1), right); } } private void propagateLessThanString(IrIntExpr[] a, IrIntExpr[] b) { for (int x = 0; x < a.length - 1; x++) { switch (IrUtil.compare(a[x], b[x])) { case LT: case LE: case UNKNOWN: return; case GT: case GE: equal(a[x], b[x]); break; } } // All equal except for the last character. propagateLessThan(a[a.length - 1], b[a.length - 1]); } private void propagateLessThanEqual(IrIntExpr left, IrIntExpr right) { IrDomain leftDomain = left.getDomain(); IrDomain rightDomain = right.getDomain(); if (leftDomain.getHighBound() > rightDomain.getHighBound()) { propagateInt(IrUtil.boundHigh(left.getDomain(), right.getDomain().getHighBound()), left); } if (rightDomain.getLowBound() < leftDomain.getLowBound()) { propagateInt(IrUtil.boundLow(right.getDomain(), left.getDomain().getLowBound()), right); } } private void propagateLessThanEqualString(IrIntExpr[] a, IrIntExpr[] b) { for (int x = 0; x < a.length; x++) { IrUtil.Ordering charOrd = IrUtil.compare(a[x], b[x]); if (!IrUtil.Ordering.EQ.equals(charOrd)) { propagateLessThanEqual(a[x], b[x]); } } // The two strings are equal. } private void propagateInt(IrDomain left, IrIntExpr right) { if (IrUtil.isSubsetOf(right.getDomain(), left)) { return; } if (right instanceof IrIntVar) { IrDomain domain = IrUtil.intersection(left, right.getDomain()); intGraph.union((IrIntVar) right, domainInt("domain" + domain, domain)); } else if (right instanceof IrMinus) { propagateInt(IrUtil.minus(left), ((IrMinus) right).getExpr()); } else if (right instanceof IrCard) { propagateCard(left, ((IrCard) right).getSet()); } else if (right instanceof IrAdd) { IrAdd add = (IrAdd) right; IrIntExpr[] addends = add.getAddends(); if (addends.length == 1) { propagateInt(IrUtil.offset(left, -add.getOffset()), addends[0]); } } else if (right instanceof IrElement) { IrElement element = (IrElement) right; TIntHashSet domain = new TIntHashSet(element.getIndex().getDomain().size()); TIntIterator iter = element.getIndex().getDomain().iterator(); while (iter.hasNext()) { int val = iter.next(); if (IrUtil.intersects(left, element.getArray()[val].getDomain())) { domain.add(val); } } propagateInt(enumDomain(domain), element.getIndex()); } } private void propagateSet(PartialSet left, IrSetExpr right) { left.updateMask(right.getEnv(), right.getKer(), right.getCard()); if (left.hasMask()) { if (right instanceof IrSetVar) { propagateSetVar(left, (IrSetVar) right); } else if (right instanceof IrSingleton) { propagateSingleton(left, (IrSingleton) right); } else if (right instanceof IrArrayToSet) { propagateArrayToSet(left, (IrArrayToSet) right); } else if (right instanceof IrJoinRelation) { propagateJoinRelation(left, (IrJoinRelation) right); } else if (right instanceof IrJoinFunction) { propagateJoinFunction(left, (IrJoinFunction) right); } else if (right instanceof IrSetUnion) { propagateSetUnion(left, (IrSetUnion) right); } else if (right instanceof IrOffset) { propagateOffset(left, (IrOffset) right); } } } private void propagateSetVar(PartialSet left, IrSetVar right) { IrDomain env = right.getEnv(); IrDomain ker = right.getKer(); IrDomain card = right.getCard(); if (left.isEnvMask()) { env = left.getEnv(); } if (left.isKerMask()) { ker = left.getKer(); } if (left.isCardMask()) { card = left.getCard(); } IrSetVar set = newSet(left.toString(), env, ker, card); if (set != null) { setGraph.union(right, set); } } private void propagateSingleton(PartialSet left, IrSingleton right) { if (left.isKerMask()) { IrDomain ker = left.getKer(); if (ker.size() == 1) { propagateInt(ker, right.getValue()); } } else if (left.isEnvMask()) { IrDomain env = left.getEnv(); propagateInt(env, right.getValue()); } } private void propagateArrayToSet(PartialSet left, IrArrayToSet right) { if (left.isEnvMask()) { IrDomain env = left.getEnv(); for (IrIntExpr child : right.getArray()) { propagateInt(env, child); } } } private void propagateJoinRelation(PartialSet left, IrJoinRelation right) { if (right.isInjective()) { if (left.isEnvMask() || left.isCardMask()) { IrDomain env = left.getEnv(); IrDomain card = left.isCardMask() ? boundDomain(0, left.getCard().getHighBound()) : null; TIntIterator iter = right.getTake().getKer().iterator(); PartialSet set = new PartialSet(env, null, card); while (iter.hasNext()) { propagateSet(set, right.getChildren()[iter.next()]); } } if (left.isCardMask()) { IrSetExpr take = right.getTake(); IrSetExpr[] children = right.getChildren(); int lb = left.getCard().getLowBound(); int ub = left.getCard().getHighBound(); int[] envLbs = new int[take.getEnv().size() - take.getKer().size()]; int[] envUbs = new int[envLbs.length]; int kerMinCard = 0; int kerMaxCard = 0; int env = 0; TIntIterator iter = take.getEnv().iterator(); while (iter.hasNext()) { int i = iter.next(); if (take.getKer().contains(i)) { kerMinCard += children[i].getCard().getLowBound(); kerMaxCard += children[i].getCard().getHighBound(); } else { envLbs[env] = children[i].getCard().getLowBound(); envUbs[env] = children[i].getCard().getHighBound(); env++; } } Arrays.sort(envLbs); Arrays.sort(envUbs); int i; for (i = 0; i < envLbs.length && (kerMinCard < ub || envLbs[i] == 0); i++) { kerMinCard += envLbs[i]; } int high = i + take.getKer().size(); for (i = envUbs.length - 1; i >= 0 && kerMaxCard < lb; i kerMaxCard += envUbs[i]; } int low = envUbs.length - 1 - i + take.getKer().size(); if (low > take.getCard().getLowBound() || high < take.getCard().getHighBound()) { propagateCard(boundDomain(low, high), take); } } } } private void propagateJoinFunction(PartialSet left, IrJoinFunction right) { if (left.isEnvMask()) { IrDomain env = left.getEnv(); TIntIterator iter = right.getTake().getKer().iterator(); while (iter.hasNext()) { propagateInt(env, right.getRefs()[iter.next()]); } } if (left.isCardMask()) { IrDomain card = left.getCard(); IrSetExpr take = right.getTake(); int low = Math.max(take.getKer().size(), card.getLowBound()); int high = Math.min(take.getEnv().size(), right.hasGlobalCardinality() ? card.getHighBound() * right.getGlobalCardinality() : take.getCard().getHighBound()); if (low > take.getCard().getLowBound() || high < take.getCard().getHighBound()) { propagateCard(boundDomain(low, high), take); } } } private void propagateSetUnion(PartialSet left, IrSetUnion right) { if (left.isEnvMask() || left.isCardMask()) { IrSetExpr[] operands = right.getOperands(); IrDomain env = left.getEnv(); if (right.isDisjoint() && left.isCardMask()) { int lowCards = 0; int highCards = 0; for (IrSetExpr operand : operands) { lowCards += operand.getCard().getLowBound(); highCards += operand.getCard().getHighBound(); } for (IrSetExpr operand : operands) { IrDomain card = boundDomain( left.getCard().getLowBound() - highCards + operand.getCard().getHighBound(), left.getCard().getHighBound() - lowCards + operand.getCard().getLowBound()); PartialSet set = new PartialSet(env, null, card); propagateSet(set, operand); } } else { IrDomain card = left.isCardMask() ? boundDomain(0, left.getCard().getHighBound()) : null; PartialSet set = new PartialSet(env, null, card); for (IrSetExpr operand : operands) { propagateSet(set, operand); } } } } private void propagateOffset(PartialSet left, IrOffset right) { int offset = right.getOffset(); IrDomain env = left.isEnvMask() ? IrUtil.offset(left.getEnv(), offset) : null; IrDomain ker = left.isKerMask() ? IrUtil.offset(left.getKer(), offset) : null; IrDomain card = left.isCardMask() ? left.getCard() : null; propagateSet(new PartialSet(env, ker, card), right.getSet()); } private void propagateEnv(IrDomain left, IrSetExpr right) { propagateSet(env(left), right); } private void propagateKer(IrDomain left, IrSetExpr right) { propagateSet(ker(left), right); } private void propagateCard(IrDomain left, IrSetExpr right) { propagateSet(card(left), right); } } private static class CoalesceRewriter extends IrRewriter<Void> { private final Map<IrIntVar, IrIntVar> coalescedInts; private final Map<IrSetVar, IrSetVar> coalescedSets; CoalesceRewriter(Map<IrIntVar, IrIntVar> coalescedInts, Map<IrSetVar, IrSetVar> coalescedSets) { this.coalescedInts = coalescedInts; this.coalescedSets = coalescedSets; } @Override public IrBoolVar visit(IrBoolVar ir, Void a) { IrBoolVar var = (IrBoolVar) coalescedInts.get(ir); return var == null ? ir : var; } @Override public IrIntVar visit(IrIntVar ir, Void a) { IrIntVar var = coalescedInts.get(ir); return var == null ? ir : var; } @Override public IrSetVar visit(IrSetVar ir, Void a) { IrSetVar var = coalescedSets.get(ir); return var == null ? ir : var; } } private static PartialSet env(IrDomain env) { return new PartialSet(env, null, null); } private static PartialSet ker(IrDomain ker) { return new PartialSet(null, ker, null); } private static PartialSet card(IrDomain card) { return new PartialSet(null, null, card); } private static class PartialSet { private final IrDomain env; private final IrDomain ker; private final IrDomain card; private byte mask; PartialSet(IrDomain env, IrDomain ker, IrDomain card) { assert env != null || ker != null || card != null; this.env = env; this.ker = ker; this.card = card; } IrDomain getEnv() { return env; } IrDomain getKer() { return ker; } IrDomain getCard() { return card; } boolean isEnvMask() { return (mask & 1) == 1; } boolean isKerMask() { return (mask & 2) == 2; } boolean isCardMask() { return (mask & 4) == 4; } boolean hasMask() { return mask != 0; } void updateMask(IrDomain env, IrDomain ker, IrDomain card) { if (this.env != null && !IrUtil.isSubsetOf(env, this.env)) { mask |= 1; } if (this.ker != null && !IrUtil.isSubsetOf(this.ker, ker)) { mask |= 2; } if (this.card != null && !IrUtil.isSubsetOf(card, this.card)) { mask |= 4; } } @Override public String toString() { return (env != null ? "env=" + env : "") + (ker != null ? "ker=" + ker : "") + (card != null ? "card=" + card : ""); } } }
package org.decimal4j.util; import java.math.RoundingMode; import java.util.Objects; import org.decimal4j.api.DecimalArithmetic; import org.decimal4j.scale.ScaleMetrics; import org.decimal4j.scale.Scales; /** * Utility class to round double values to an arbitrary decimal precision between 0 and 18. The rounding is efficient * and garbage free. */ public final class DoubleRounder { private final ScaleMetrics scaleMetrics; private final double ulp; public DoubleRounder(int precision) { this(toScaleMetrics(precision)); } /** * Creates a rounder with the given scale metrics defining the decimal precision. * * @param scaleMetrics * the scale metrics determining the rounding precision * @throws NullPointerException * if scale metrics is null */ public DoubleRounder(ScaleMetrics scaleMetrics) { this.scaleMetrics = Objects.requireNonNull(scaleMetrics, "scaleMetrics cannot be null"); this.ulp = scaleMetrics.getRoundingHalfEvenArithmetic().toDouble(1); } /** * Returns the precision of this rounder, a value between zero and 18. * * @return this rounder's decimal precision */ public int getPrecision() { return scaleMetrics.getScale(); } /** * Rounds the given double value to the decimal precision of this rounder using {@link RoundingMode#HALF_UP HALF_UP} * rounding. * * @param value * the value to round * @return the rounded value * @see #getPrecision() */ public double round(double value) { return round(value, scaleMetrics.getDefaultArithmetic(), scaleMetrics.getRoundingHalfEvenArithmetic(), ulp); } /** * Rounds the given double value to the decimal precision of this rounder using the specified rounding mode. * * @param value * the value to round * @param roundingMode * the rounding mode indicating how the least significant returned decimal digit of the result is to be * calculated * @return the rounded value * @see #getPrecision() */ public double round(double value, RoundingMode roundingMode) { return round(value, roundingMode, scaleMetrics.getRoundingHalfEvenArithmetic(), ulp); } /** * Returns a hash code for this <tt>DoubleRounder</tt> instance. * * @return a hash code value for this object. */ @Override public int hashCode() { return scaleMetrics.hashCode(); } /** * Returns true if {@code obj} is a <tt>DoubleRounder</tt> with the same precision as {@code this} rounder instance. * * @param obj * the reference object with which to compare * @return true for a double rounder with the same precision as this instance */ @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj == null) return false; if (obj instanceof DoubleRounder) { return scaleMetrics.equals(((DoubleRounder) obj).scaleMetrics); } return false; } /** * Returns a string consisting of the simple class name and the precision. * * @return a string like "DoubleRounder[precision=7]" */ @Override public String toString() { return "DoubleRounder[precision=" + getPrecision() + "]"; } /** * Rounds the given double value to the specified decimal {@code precision} using {@link RoundingMode#HALF_UP * HALF_UP} rounding. * * @param value * the value to round * @param precision * the decimal precision to round to (aka decimal places) * @return the rounded value */ public static final double round(double value, int precision) { final ScaleMetrics sm = toScaleMetrics(precision); final DecimalArithmetic halfEvenArith = sm.getRoundingHalfEvenArithmetic(); return round(value, sm.getDefaultArithmetic(), halfEvenArith, halfEvenArith.toDouble(1)); } /** * Rounds the given double value to the specified decimal {@code precision} using the specified rounding mode. * * @param value * the value to round * @param precision * the decimal precision to round to (aka decimal places) * @param roundingMode * the rounding mode indicating how the least significant returned decimal digit of the result is to be * calculated * @return the rounded value */ public static final double round(double value, int precision, RoundingMode roundingMode) { final ScaleMetrics sm = toScaleMetrics(precision); final DecimalArithmetic halfEvenArith = sm.getRoundingHalfEvenArithmetic(); return round(value, roundingMode, halfEvenArith, halfEvenArith.toDouble(1)); } private static final double round(double value, RoundingMode roundingMode, DecimalArithmetic halfEvenArith, double ulp) { if (roundingMode == RoundingMode.UNNECESSARY) { return checkRoundingUnnecessary(value, halfEvenArith, ulp); } return round(value, halfEvenArith.deriveArithmetic(roundingMode), halfEvenArith, ulp); } private static final double round(double value, DecimalArithmetic roundingArith, DecimalArithmetic halfEvenArith, double ulp) { if (!isFinite(value) || 2 * ulp <= Math.ulp(value)) { return value; } final long uDecimal = roundingArith.fromDouble(value); return halfEvenArith.toDouble(uDecimal); } private static final double checkRoundingUnnecessary(double value, DecimalArithmetic halfEvenArith, double ulp) { if (isFinite(value) && 2 * ulp > Math.ulp(value)) { final long uDecimal = halfEvenArith.fromDouble(value); if (halfEvenArith.toDouble(uDecimal) != value) { throw new ArithmeticException( "Rounding necessary for precision " + halfEvenArith.getScale() + ": " + value); } } return value; } private static final ScaleMetrics toScaleMetrics(int precision) { if (precision < Scales.MIN_SCALE | precision > Scales.MAX_SCALE) { throw new IllegalArgumentException( "Precision must be in [" + Scales.MIN_SCALE + "," + Scales.MAX_SCALE + "] but was " + precision); } return Scales.getScaleMetrics(precision); } /** * Java-7 port of {@link Double#isFinite(double)}. * <p> * Returns {@code true} if the argument is a finite floating-point value; returns {@code false} otherwise (for NaN * and infinity arguments). * * @param d * the {@code double} value to be tested * @return {@code true} if the argument is a finite floating-point value, {@code false} otherwise. * @see Double#isFinite(double) */ private static boolean isFinite(double d) { return Math.abs(d) <= Double.MAX_VALUE; } }
package org.homer.versioner.core; import org.apache.commons.lang3.tuple.Pair; import org.homer.versioner.core.exception.VersionerCoreException; import org.homer.versioner.core.output.NodeOutput; import org.homer.versioner.core.output.RelationshipOutput; import org.neo4j.graphdb.*; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import java.util.stream.StreamSupport; /** * Utility class, it contains some common utility methods and constants */ public class Utility { public static final String STATE_LABEL = "State"; public static final String CURRENT_TYPE = "CURRENT"; public static final String HAS_STATE_TYPE = "HAS_STATE"; public static final String PREVIOUS_TYPE = "PREVIOUS"; public static final String ROLLBACK_TYPE = "ROLLBACK"; public static final String FOR_TYPE = "FOR"; public static final String DATE_PROP = "date"; public static final String START_DATE_PROP = "startDate"; public static final String END_DATE_PROP = "endDate"; public static final String LOGGER_TAG = "[graph-versioner] - "; /* DIFF OPERATIONS */ public static final String DIFF_OPERATION_REMOVE = "REMOVE"; public static final String DIFF_OPERATION_ADD = "ADD"; public static final String DIFF_OPERATION_UPDATE = "UPDATE"; public static final List<String> DIFF_OPERATIONS_SORTING = Arrays.asList(DIFF_OPERATION_REMOVE, DIFF_OPERATION_UPDATE, DIFF_OPERATION_ADD); public static final List<String> SYSTEM_RELS = Arrays.asList(CURRENT_TYPE, HAS_STATE_TYPE, PREVIOUS_TYPE, ROLLBACK_TYPE); /** * Sets a {@link Map} of properties to a {@link Node} * * @param node passed node * @param props properties to be set * @return a node with properties */ public static Node setProperties(Node node, Map<String, Object> props) { props.forEach(node::setProperty); return node; } /** * Sets a {@link List} of label names into a {@link Label[]} * * @param labelNames a {@link List} of label names * @return {@link Label[]} */ public static Label[] asLabels(List<String> labelNames) { Label[] result; if (Objects.isNull(labelNames)) { result = new Label[0]; } else { result = labelNames.stream().filter(Objects::nonNull).map(Label::label).toArray(Label[]::new); } return result; } public static Label[] asLabels(Iterable<Label> labelsIterable) { List<String> labelNames = new ArrayList<>(); Spliterator<Label> labelsIterator = labelsIterable.spliterator(); StreamSupport.stream(labelsIterator, false).forEach(label -> labelNames.add(label.name())); return asLabels(labelNames); } /** * Sets a {@link String} as a singleton Array {@link Label[]} * * @param labelName a {@link String} representing the unique label * @return {@link Label[]} */ public static Label[] asLabels(String labelName) { return new Label[]{Label.label(labelName)}; } /** * Creates a new node copying properties and asLabels form a given one * * @param db a {@link GraphDatabaseService} representing the database where the node will be created * @param node a {@link Node} representing the node to clone * @return {@link Node} */ public static Node cloneNode(GraphDatabaseService db, Node node) { List<String> labelNames = new ArrayList<>(); Spliterator<Label> labelsIterator = node.getLabels().spliterator(); StreamSupport.stream(labelsIterator, false).forEach(label -> labelNames.add(label.name())); return setProperties(db.createNode(asLabels(labelNames)), node.getAllProperties()); } /** * Updates an Entity node CURRENT State with the new current one, it will handle all the * HAS_STATE / CURRENT / PREVIOUS relationships creation/update * * @param entity a {@link Node} representing the Entity * @param instantDate the new current State date * @param currentRelationship a {@link Relationship} representing the current CURRENT relationship * @param currentState a {@link Node} representing the current State * @param currentDate the current State date * @param result a {@link Node} representing the new current State * @return {@link Node} */ public static Node currentStateUpdate(Node entity, LocalDateTime instantDate, Relationship currentRelationship, Node currentState, LocalDateTime currentDate, Node result) { // Creating PREVIOUS relationship between the current and the new State result.createRelationshipTo(currentState, RelationshipType.withName(PREVIOUS_TYPE)).setProperty(DATE_PROP, currentDate); // Updating the HAS_STATE rel for the current node, adding endDate currentState.getRelationships(RelationshipType.withName(HAS_STATE_TYPE), Direction.INCOMING) .forEach(hasStatusRel -> hasStatusRel.setProperty(END_DATE_PROP, instantDate)); // Refactoring current relationship and adding the new ones currentRelationship.delete(); // Connecting the new current state to the Entity addCurrentState(result, entity, instantDate); return result; } /** * Connects a new State {@link Node} as the Current one, to the given Entity * * @param state a {@link Node} representing the new current State * @param entity a {@link Node} representing the Entity * @param instantDate the new current State date */ public static void addCurrentState(Node state, Node entity, LocalDateTime instantDate) { entity.createRelationshipTo(state, RelationshipType.withName(CURRENT_TYPE)).setProperty(DATE_PROP, instantDate); entity.createRelationshipTo(state, RelationshipType.withName(HAS_STATE_TYPE)).setProperty(START_DATE_PROP, instantDate); } /** * Checks if the given entity is related through the HAS_STATE relationship with the given node * * @param entity a {@link Node} representing the Entity * @param state a {@link Node} representing the State * @return {@link Boolean} result */ public static void checkRelationship(Node entity, Node state) throws VersionerCoreException { Spliterator<Relationship> stateRelIterator = state.getRelationships(RelationshipType.withName(Utility.HAS_STATE_TYPE), Direction.INCOMING).spliterator(); StreamSupport.stream(stateRelIterator, false).map(hasStateRel -> { Node maybeEntity = hasStateRel.getStartNode(); if (maybeEntity.getId() != entity.getId()) { throw new VersionerCoreException("Can't patch the given entity, because the given State is owned by another entity."); } return true; }).findFirst().orElseGet(() -> { throw new VersionerCoreException("Can't find any entity node relate to the given State."); }); } /** * Converts the nodes to a stream of {@link NodeOutput} * * @param nodes a {@link List} of {@link Node} that will be converted to stream and mapped into {@link NodeOutput} * @return {@link Stream} streamOfNodes */ public static Stream<NodeOutput> streamOfNodes(Node... nodes) { return Stream.of(nodes).map(NodeOutput::new); } /** * Converts the relationships to a stream of {@link RelationshipOutput} * * @param relationships a {@link List} of {@link Relationship} that will be converted to stream and mapped into {@link RelationshipOutput} * @return */ public static Stream<RelationshipOutput> streamOfRelationships(Relationship... relationships) { return Stream.of(relationships).map(RelationshipOutput::new); } /** * Sets the date to the current dateTime if it's null * * @param date a {@link LocalDateTime} representing the milliseconds of the date * @return {@link LocalDateTime} milliseconds of the processed date */ public static LocalDateTime defaultToNow(LocalDateTime date) { return (date == null) ? convertEpochToLocalDateTime(Calendar.getInstance().getTimeInMillis()) : date; } /** * Checks that the given node is a Versioner Entity, otherwise throws an exception * * @param node the {@link Node} to check * @throws VersionerCoreException */ public static void isEntityOrThrowException(Node node) { streamOfIterable(node.getRelationships(RelationshipType.withName(CURRENT_TYPE), Direction.OUTGOING)).findAny() .map(ignored -> streamOfIterable(node.getRelationships(RelationshipType.withName("R"), Direction.INCOMING)).findAny()) .orElseThrow(() -> new VersionerCoreException("The given node is not a Versioner Core Entity")); } public static <T> Stream<T> streamOfIterable(Iterable<T> iterable) { return StreamSupport.stream(iterable.spliterator(), false); } public static List<String> getStateLabels(String label) { return Stream.of(Utility.STATE_LABEL, label) .filter(l -> Objects.nonNull(l) && !l.isEmpty()) .collect(Collectors.toList()); } public static Optional<Relationship> getCurrentRelationship(Node entity) { return streamOfIterable(entity.getRelationships(RelationshipType.withName(CURRENT_TYPE), Direction.OUTGOING)) .findFirst(); } public static Optional<Node> getCurrentState(Node entity) { return streamOfIterable(entity.getRelationships(RelationshipType.withName(CURRENT_TYPE), Direction.OUTGOING)).map(relationship -> relationship.getEndNode()).findFirst(); } public static LocalDateTime convertEpochToLocalDateTime(Long epochDateTime) { return Instant.ofEpochMilli(epochDateTime).atZone(ZoneId.systemDefault()).toLocalDateTime(); } public static <A, B> List<org.apache.commons.lang3.tuple.Pair<A, B>> zip(List<A> listA, List<B> listB) { return IntStream.range(0, listA.size()) .mapToObj(i -> Pair.of(listA.get(i), listB.get(i))) .collect(Collectors.toList()); } public static boolean isSystemType(String type) { return SYSTEM_RELS.contains(type); } }
package org.lantern.loggly; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Date; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.codehaus.jackson.annotate.JsonIgnore; import org.lantern.JsonUtils; public class LogglyMessage { private static final Sanitizer[] SANITIZERS = new Sanitizer[] { new IPv4Sanitizer(), new EmailSanitizer() }; private String reporterId; private String message; private Date occurredAt; private String locationInfo; private Throwable throwable; private String throwableOrigin; private String stackTrace; private Object extra; private AtomicInteger nSimilarSuppressed = new AtomicInteger(0); public LogglyMessage(String reporterId, String message, Date occurredAt) { this.reporterId = reporterId; this.message = message; this.occurredAt = occurredAt; } public String getReporterId() { return reporterId; } public String getMessage() { return message; } public Date getOccurredAt() { return occurredAt; } /** * Sanitizes {@link #message}, {@link #stackTrace}, and {@link #extra} * to obscure sensitive data. {@link #extra} must be JSON-serializable. * * @return this */ public LogglyMessage sanitized() { if (message != null) { message = sanitize(message); } if (stackTrace != null) { stackTrace = sanitize(stackTrace); } if (extra != null) { String json = JsonUtils.jsonify(extra); json = sanitize(json); this.setExtraFromJson(json); } return this; } public String getLocationInfo() { return locationInfo; } public void setLocationInfo(String locationInfo) { this.locationInfo = locationInfo; } @JsonIgnore public Throwable getThrowable() { return throwable; } public LogglyMessage setThrowable(Throwable throwable) { this.throwable = throwable; if (throwable == null) { stackTrace = null; throwableOrigin = null; } else { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); throwable.printStackTrace(pw); pw.close(); stackTrace = sw.getBuffer().toString(); throwableOrigin = throwable.getStackTrace()[0].toString(); } return this; } /** * Returns a key that uniquely identifies this message. * * @return */ public String getKey() { if (locationInfo != null) { return locationInfo; } else { return throwableOrigin; } } public Object getExtra() { return extra; } public LogglyMessage setExtra(Object extra) { this.extra = extra; return this; } public LogglyMessage setExtraFromJson(String json) { this.extra = json != null ? JsonUtils.decode(json, Map.class) : null; return this; } public String getStackTrace() { return stackTrace; } public int getnSimilarSuppressed() { return nSimilarSuppressed.get(); } public LogglyMessage incrementNsimilarSuppressed() { this.nSimilarSuppressed.incrementAndGet(); return this; } public LogglyMessage setnSimilarSuppressed(int nSimilarSuppressed) { this.nSimilarSuppressed.set(nSimilarSuppressed); return this; } /** * Applies all {@link #SANITIZERS}s to the original string. * * @param original * @return */ private static String sanitize(String original) { if (original == null || original.length() == 0) { return original; } String result = original; for (Sanitizer filter : SANITIZERS) { result = filter.sanitize(result); } return result; } private static interface Sanitizer { /** * Sanitize the given original string. * * @param original * @return the sanitized string */ String sanitize(String original); } /** * Sanitizer that sanitizes content by replacing occurrences of a regex with * a static string. */ private static class RegexSanitizer implements Sanitizer { private final Pattern pattern; private final String replacement; /** * * @param regex * the regex * @param replacement * the string with which to replace occurrences of the regex */ public RegexSanitizer(String regex, String replacement) { super(); this.pattern = Pattern.compile(regex); this.replacement = replacement; } @Override public String sanitize(String original) { Matcher matcher = pattern.matcher(original); StringBuffer result = new StringBuffer(); while (matcher.find()) { matcher.appendReplacement(result, replacement); } matcher.appendTail(result); return result.toString(); } } /** * A {@link Sanitizer} that replaces everything that looks like an IPv4 * address with ???.???.???.???. */ private static class IPv4Sanitizer extends RegexSanitizer { private static final String IP_REGEX = "(?:[0-9]{1,3}\\.){3}[0-9]{1,3}"; // TODO (see [1] below) private static final String IP_REPLACEMENT = "<IP hidden>"; public IPv4Sanitizer() { super(IP_REGEX, IP_REPLACEMENT); } } /** * A {@link Sanitizer} that replaces everything that looks like an email * address with <email hidden>. */ private static class EmailSanitizer extends RegexSanitizer { private static final String EMAIL_REGEX = "[a-zA-Z0-9._%+-]+@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,}"; // TODO (see [1] below) private static final String EMAIL_REPLACEMENT = "<email hidden>"; public EmailSanitizer() { super(EMAIL_REGEX, EMAIL_REPLACEMENT); } } // [1] Maybe these should be moved to LanternConstants. // Would also be nice if the frontend could share these kinds of constants with the backend, // since currently they're being duplicated. public static void main(String[] args) throws Exception { // Testing LogglyMessage msg = new LogglyMessage("reporter", "This message contains a dummy IP address (12.34.56.789) " + "and two emails: a@foo.com and b@bar.com.", new Date()) .setExtraFromJson("{\"key\": \"email! c@qux.co.uk! IP? 123.45.67.89?\", \"otherKey\": 5}"); msg = msg.sanitized(); System.out.println(msg.getMessage()); System.out.println(msg.getExtra()); } }
package org.lightmare.deploy; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.ejb.Local; import javax.ejb.Remote; import javax.ejb.Stateless; import org.apache.log4j.Logger; import org.lightmare.cache.ArchiveData; import org.lightmare.cache.DeployData; import org.lightmare.cache.DeploymentDirectory; import org.lightmare.cache.MetaContainer; import org.lightmare.cache.RestContainer; import org.lightmare.cache.TmpResources; import org.lightmare.config.ConfigKeys; import org.lightmare.config.Configuration; import org.lightmare.deploy.fs.Watcher; import org.lightmare.jpa.datasource.Initializer; import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType; import org.lightmare.libraries.LibraryLoader; import org.lightmare.remote.rpc.RPCall; import org.lightmare.remote.rpc.RpcListener; import org.lightmare.rest.providers.RestProvider; import org.lightmare.scannotation.AnnotationDB; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.LogUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.fs.FileUtils; import org.lightmare.utils.fs.WatchUtils; import org.lightmare.utils.fs.codecs.ArchiveUtils; import org.lightmare.utils.shutdown.ShutDown; /** * Determines and saves in cache EJB beans {@link org.lightmare.cache.MetaData} * on startup * * @author Levan * @since 0.0.45-SNAPSHOT */ public class MetaCreator { // Annotation scanner implementation for scanning at atartup private static AnnotationDB annotationDB; // Cached temporal resources for clean after deployment private TmpResources tmpResources; // Checks if needed await for EJB deployments private boolean await; // Blocker for deployments connections or beans private CountDownLatch blocker; // Data for cache at deploy time private Map<String, ArchiveUtils> aggregateds = new WeakHashMap<String, ArchiveUtils>(); // Caches archive by URL for deployment private Map<URL, ArchiveData> archivesURLs; // Caches class file URLs by class names private Map<String, URL> classOwnersURL; // Caches deployment data meta information for file URL instance private Map<URL, DeployData> realURL; // Class loader for each deployment private ClassLoader current; // Configuration for appropriate archives URLs private Configuration configuration; // Lock for deployment and directory scanning private final Lock scannerLock = new ReentrantLock(); // Lock for MetaCreator initialization private static final Lock LOCK = new ReentrantLock(); private static final Logger LOG = Logger.getLogger(MetaCreator.class); private MetaCreator() { tmpResources = new TmpResources(); ShutDown.setHook(tmpResources); } /** * Initializes {@link MetaCreator} instance if it is not cached yet * * @return {@link MetaCreator} */ private static MetaCreator initCreator() { MetaCreator creator = MetaContainer.getCreator(); if (creator == null) { creator = new MetaCreator(); MetaContainer.setCreator(creator); } return creator; } /** * Gets cached {@link MetaCreator} instance if such not exists creates new * * @return {@link MetaCreator} */ private static MetaCreator get() { MetaCreator creator = MetaContainer.getCreator(); if (creator == null) { // Locks to provide singularity of MetaCreator instance ObjectUtils.lock(LOCK); try { creator = initCreator(); } finally { ObjectUtils.unlock(LOCK); } } return creator; } /** * Gets {@link Configuration} instance for passed {@link URL} array of * archives * * @param archives */ private void configure(URL[] archives) { if (configuration == null && CollectionUtils.valid(archives)) { configuration = MetaContainer.getConfig(archives); } } public AnnotationDB getAnnotationDB() { return annotationDB; } public Map<String, ArchiveUtils> getAggregateds() { return aggregateds; } /** * Caches each archive by it's {@link URL} for deployment * * @param ejbURLs * @param archiveData */ private void fillArchiveURLs(Collection<URL> ejbURLs, ArchiveData archiveData, DeployData deployData) { for (URL ejbURL : ejbURLs) { archivesURLs.put(ejbURL, archiveData); realURL.put(ejbURL, deployData); } } /** * Caches each archive by it's {@link URL} for deployment and creates fill * {@link URL} array for scanning and finding {@link javax.ejb.Stateless} * annotated classes * * @param archive * @param modifiedArchives * @throws IOException */ private void fillArchiveURLs(URL archive, List<URL> modifiedArchives) throws IOException { ArchiveUtils ioUtils = ArchiveUtils.getAppropriatedType(archive); if (ObjectUtils.notNull(ioUtils)) { ioUtils.scan(configuration.isPersXmlFromJar()); List<URL> ejbURLs = ioUtils.getEjbURLs(); modifiedArchives.addAll(ejbURLs); ArchiveData archiveData = new ArchiveData(); archiveData.setIoUtils(ioUtils); DeployData deployData = new DeployData(); deployData.setType(ioUtils.getType()); deployData.setUrl(archive); if (ejbURLs.isEmpty()) { archivesURLs.put(archive, archiveData); realURL.put(archive, deployData); } else { fillArchiveURLs(ejbURLs, archiveData, deployData); } } } /** * Gets {@link URL} array for all classes and jar libraries within archive * file for class loading policy * * @param archives * @return {@link URL}[] * @throws IOException */ private URL[] getFullArchives(URL[] archives) throws IOException { List<URL> modifiedArchives = new ArrayList<URL>(); for (URL archive : archives) { fillArchiveURLs(archive, modifiedArchives); } return CollectionUtils.toArray(modifiedArchives, URL.class); } /** * Awaits for {@link Future} tasks if it set so by configuration * * @param future */ private void awaitDeployment(Future<String> future) { if (await) { try { String nameFromFuture = future.get(); LogUtils.info(LOG, "Deploy processing of %s finished", nameFromFuture); } catch (InterruptedException ex) { LOG.error(ex.getMessage(), ex); } catch (ExecutionException ex) { LOG.error(ex.getMessage(), ex); } } } /** * Awaits for {@link CountDownLatch} of deployments */ private void awaitDeployments() { try { blocker.await(); } catch (InterruptedException ex) { LOG.error(ex); } } /** * Starts bean deployment process for bean name * * @param beanName * @throws IOException */ private void deployBean(String beanName) throws IOException { URL currentURL = classOwnersURL.get(beanName); ArchiveData archiveData = archivesURLs.get(currentURL); if (archiveData == null) { archiveData = new ArchiveData(); } ArchiveUtils ioUtils = archiveData.getIoUtils(); if (ioUtils == null) { ioUtils = ArchiveUtils.getAppropriatedType(currentURL); archiveData.setIoUtils(ioUtils); } ClassLoader loader = archiveData.getLoader(); // Finds appropriated ClassLoader if needed and or creates new one List<File> tmpFiles = null; if (ObjectUtils.notNull(ioUtils)) { if (loader == null) { if (ioUtils.notExecuted()) { ioUtils.scan(configuration.isPersXmlFromJar()); } URL[] libURLs = ioUtils.getURLs(); loader = LibraryLoader.initializeLoader(libURLs); archiveData.setLoader(loader); } tmpFiles = ioUtils.getTmpFiles(); aggregateds.put(beanName, ioUtils); } // Archive file url which contains this bean DeployData deployData; if (CollectionUtils.valid(realURL)) { deployData = realURL.get(currentURL); } else { deployData = null; } // Initializes and fills BeanLoader.BeanParameters class to deploy // stateless EJB bean BeanLoader.BeanParameters parameters = new BeanLoader.BeanParameters(); parameters.creator = this; parameters.className = beanName; parameters.loader = loader; parameters.tmpFiles = tmpFiles; parameters.blocker = blocker; parameters.deployData = deployData; parameters.configuration = configuration; Future<String> future = BeanLoader.loadBean(parameters); awaitDeployment(future); if (CollectionUtils.valid(tmpFiles)) { tmpResources.addFile(tmpFiles); } } /** * Deploys single bean by class name * * @param beanNames */ private void deployBeans(Set<String> beanNames) { blocker = new CountDownLatch(beanNames.size()); for (String beanName : beanNames) { LogUtils.info(LOG, "Deploing bean %s", beanName); try { deployBean(beanName); } catch (IOException ex) { LogUtils.error(LOG, ex, "Could not deploy bean %s cause", beanName, ex.getMessage()); } } awaitDeployments(); if (RestContainer.hasRest()) { RestProvider.reload(); } boolean hotDeployment = configuration.isHotDeployment(); boolean watchStatus = configuration.isWatchStatus(); if (hotDeployment && ObjectUtils.notTrue(watchStatus)) { Watcher.startWatch(); watchStatus = Boolean.TRUE; } } /** * Scan application for find all {@link javax.ejb.Stateless} beans and * {@link Remote} or {@link Local} proxy interfaces * * @param archives * @throws IOException * @throws ClassNotFoundException */ public void scanForBeans(URL[] archives) throws IOException { ObjectUtils.lock(scannerLock); try { configure(archives); // starts RPC server if configured as remote and server if (configuration.isRemote() && Configuration.isServer()) { RpcListener.startServer(configuration); } else if (configuration.isRemote()) { RPCall.configure(configuration); } String[] libraryPaths = configuration.getLibraryPaths(); // Loads libraries from specified path if (ObjectUtils.notNull(libraryPaths)) { LibraryLoader.loadLibraries(libraryPaths); } // Gets and caches class loader current = LibraryLoader.getContextClassLoader(); archivesURLs = new WeakHashMap<URL, ArchiveData>(); if (CollectionUtils.valid(archives)) { realURL = new WeakHashMap<URL, DeployData>(); } URL[] fullArchives = getFullArchives(archives); annotationDB = new AnnotationDB(); annotationDB.setScanFieldAnnotations(Boolean.FALSE); annotationDB.setScanParameterAnnotations(Boolean.FALSE); annotationDB.setScanMethodAnnotations(Boolean.FALSE); annotationDB.scanArchives(fullArchives); Set<String> beanNames = annotationDB.getAnnotationIndex().get( Stateless.class.getName()); classOwnersURL = annotationDB.getClassOwnersURLs(); Initializer.initializeDataSources(configuration); if (CollectionUtils.valid(beanNames)) { deployBeans(beanNames); } } finally { // Caches configuration MetaContainer.putConfig(archives, configuration); // clears cached resources clear(); // gets rid from all created temporary files tmpResources.removeTempFiles(); ObjectUtils.unlock(scannerLock); } } /** * Scan application for find all {@link javax.ejb.Stateless} beans and * {@link Remote} or {@link Local} proxy interfaces * * @throws ClassNotFoundException * @throws IOException */ public void scanForBeans(File[] jars) throws IOException { List<URL> urlList = new ArrayList<URL>(); URL url; for (File file : jars) { url = file.toURI().toURL(); urlList.add(url); } URL[] archives = CollectionUtils.toArray(urlList, URL.class); scanForBeans(archives); } /** * Scan application for find all {@link javax.ejb.Stateless} beans and * {@link Remote} or {@link Local} proxy interfaces * * @throws ClassNotFoundException * @throws IOException */ public void scanForBeans(String... paths) throws IOException { if (CollectionUtils.invalid(paths) && CollectionUtils.valid(configuration.getDeploymentPath())) { Set<DeploymentDirectory> deployments = configuration .getDeploymentPath(); List<String> pathList = new ArrayList<String>(); File deployFile; for (DeploymentDirectory deployment : deployments) { deployFile = new File(deployment.getPath()); if (deployment.isScan()) { String[] subDeployments = deployFile.list(); if (CollectionUtils.valid(subDeployments)) { pathList.addAll(Arrays.asList(subDeployments)); } } } paths = CollectionUtils.toArray(pathList, String.class); } List<URL> urlList = new ArrayList<URL>(); List<URL> archive; for (String path : paths) { archive = FileUtils.toURLWithClasspath(path); urlList.addAll(archive); } URL[] archives = CollectionUtils.toArray(urlList, URL.class); scanForBeans(archives); } public ClassLoader getCurrent() { return current; } /** * Clears all locally cached data */ public void clear() { boolean locked = Boolean.FALSE; while (ObjectUtils.notTrue(locked)) { // Tries to lock for avoid concurrent modification locked = ObjectUtils.tryLock(scannerLock); if (locked) { try { if (CollectionUtils.valid(realURL)) { realURL.clear(); realURL = null; } if (CollectionUtils.valid(aggregateds)) { aggregateds.clear(); } if (CollectionUtils.valid(archivesURLs)) { archivesURLs.clear(); archivesURLs = null; } if (CollectionUtils.valid(classOwnersURL)) { classOwnersURL.clear(); classOwnersURL = null; } configuration = null; } finally { ObjectUtils.unlock(scannerLock); } } } } /** * Closes all connections clears all caches * * @throws IOException */ public static void close() throws IOException { ShutDown.clearAll(); } /** * Builder class to provide properties for lightmare application and * initialize {@link MetaCreator} instance * * @author levan * @since 0.0.45-SNAPSHOT */ public static class Builder { private MetaCreator creator; public Builder(boolean cloneConfiguration) throws IOException { creator = MetaCreator.get(); Configuration config = creator.configuration; if (cloneConfiguration && ObjectUtils.notNull(config)) { try { creator.configuration = (Configuration) config.clone(); } catch (CloneNotSupportedException ex) { throw new IOException(ex); } } else { creator.configuration = new Configuration(); } } public Builder() throws IOException { this(Boolean.FALSE); } public Builder(Map<Object, Object> configuration) throws IOException { this(); creator.configuration.configure(configuration); } public Builder(String path) throws IOException { this(); creator.configuration.configure(path); } /** * Configures persistence for cached properties * * @return {@link Map}<code><Object, Object></code> */ private Map<Object, Object> initPersistenceProperties() { Map<Object, Object> persistenceProperties = creator.configuration .getPersistenceProperties(); if (persistenceProperties == null) { persistenceProperties = new HashMap<Object, Object>(); creator.configuration .setPersistenceProperties(persistenceProperties); } return persistenceProperties; } /** * Sets additional persistence properties * * @param properties * @return {@link Builder} */ public Builder setPersistenceProperties(Map<String, String> properties) { if (CollectionUtils.valid(properties)) { Map<Object, Object> persistenceProperties = initPersistenceProperties(); persistenceProperties.putAll(properties); } return this; } /** * Adds instant persistence property * * @param key * @param property * @return {@link Builder} */ public Builder addPersistenceProperty(String key, String property) { Map<Object, Object> persistenceProperties = initPersistenceProperties(); persistenceProperties.put(key, property); return this; } /** * Adds property to scan for {@link javax.persistence.Entity} annotated * classes from deployed archives * * @param scanForEnt * @return {@link Builder} */ public Builder setScanForEntities(boolean scanForEnt) { creator.configuration.setScanForEntities(scanForEnt); return this; } /** * Adds property to use only {@link org.lightmare.annotations.UnitName} * annotated entities for which * {@link org.lightmare.annotations.UnitName#value()} matches passed * unit name * * @param unitName * @return {@link Builder} */ public Builder setUnitName(String unitName) { creator.configuration.setAnnotatedUnitName(unitName); return this; } /** * Sets path for persistence.xml file * * @param path * @return {@link Builder} */ public Builder setPersXmlPath(String path) { creator.configuration.setPersXmlPath(path); creator.configuration.setScanArchives(Boolean.FALSE); return this; } /** * Adds path for additional libraries to load at start time * * @param libPaths * @return {@link Builder} */ public Builder setLibraryPath(String... libPaths) { creator.configuration.setLibraryPaths(libPaths); return this; } /** * Sets boolean checker to scan persistence.xml files from appropriated * jar files * * @param xmlFromJar * @return {@link Builder} */ public Builder setXmlFromJar(boolean xmlFromJar) { creator.configuration.setPersXmlFromJar(xmlFromJar); return this; } /** * Sets boolean checker to swap jta data source value with non jta data * source value * * @param swapDataSource * @return {@link Builder} */ public Builder setSwapDataSource(boolean swapDataSource) { creator.configuration.setSwapDataSource(swapDataSource); return this; } /** * Adds path for data source file * * @param dataSourcePath * @return {@link Builder} */ public Builder addDataSourcePath(String dataSourcePath) { creator.configuration.addDataSourcePath(dataSourcePath); return this; } /** * This method is deprecated should use * {@link MetaCreator.Builder#addDataSourcePath(String)} instead * * @param dataSourcePath * @return {@link MetaCreator.Builder} */ @Deprecated public Builder setDataSourcePath(String dataSourcePath) { creator.configuration.addDataSourcePath(dataSourcePath); return this; } /** * Sets boolean checker to scan {@link javax.persistence.Entity} * annotated classes from appropriated deployed archive files * * @param scanArchives * @return {@link Builder} */ public Builder setScanArchives(boolean scanArchives) { creator.configuration.setScanArchives(scanArchives); return this; } /** * Sets boolean checker to block deployment processes * * @param await * @return {@link Builder} */ public Builder setAwaitDeploiment(boolean await) { creator.await = await; return this; } /** * Sets property is server or not in embedded mode * * @param remote * @return {@link Builder} */ public Builder setRemote(boolean remote) { creator.configuration.setRemote(remote); return this; } /** * Sets property is application server or just client for other remote * server * * @param server * @return {@link Builder} */ public Builder setServer(boolean server) { Configuration.setServer(server); creator.configuration.setClient(ObjectUtils.notTrue(server)); return this; } /** * Sets boolean check is application in just client mode or not * * @param client * @return {@link Builder} */ public Builder setClient(boolean client) { creator.configuration.setClient(client); Configuration.setServer(ObjectUtils.notTrue(client)); return this; } /** * To add any additional property * * @param key * @param property * @return {@link Builder} */ public Builder setProperty(String key, String property) { creator.configuration.putValue(key, property); return this; } /** * To add remote control check * * @param remoteControl * @return {@link Builder} */ public Builder setRemoteControl(boolean remoteControl) { Configuration.setRemoteControl(remoteControl); return this; } /** * File path for administrator user name and password * * @param property * @return {@link Builder} */ public Builder setAdminUsersPth(String property) { Configuration.setAdminUsersPath(property); return this; } /** * Sets specific IP address in case when application is in remote server * mode * * @param property * @return {@link Builder} */ public Builder setIpAddress(String property) { creator.configuration.putValue(ConfigKeys.IP_ADDRESS.key, property); return this; } /** * Sets specific port in case when application is in remote server mode * * @param property * @return {@link Builder} */ public Builder setPort(String property) { creator.configuration.putValue(ConfigKeys.PORT.key, property); return this; } /** * Sets amount for network master threads in case when application is in * remote server mode * * @param property * @return {@link Builder} */ public Builder setMasterThreads(String property) { creator.configuration.putValue(ConfigKeys.BOSS_POOL.key, property); return this; } /** * Sets amount of worker threads in case when application is in remote * server mode * * @param property * @return {@link Builder} */ public Builder setWorkerThreads(String property) { creator.configuration .putValue(ConfigKeys.WORKER_POOL.key, property); return this; } /** * Adds deploy file path to application with boolean checker if file is * directory to scan this directory for deployment files list * * @param deploymentPath * @param scan * @return {@link Builder} */ public Builder addDeploymentPath(String deploymentPath, boolean scan) { String clearPath = WatchUtils.clearPath(deploymentPath); creator.configuration.addDeploymentPath(clearPath, scan); return this; } /** * Adds deploy file path to application * * @param deploymentPath * @return {@link Builder} */ public Builder addDeploymentPath(String deploymentPath) { addDeploymentPath(deploymentPath, Boolean.FALSE); return this; } /** * Adds timeout for connection in case when application is in remote * server or client mode * * @param property * @return {@link Builder} */ public Builder setTimeout(String property) { creator.configuration.putValue(ConfigKeys.CONNECTION_TIMEOUT.key, property); return this; } /** * Adds boolean check if application is using pooled data source * * @param dsPooledType * @return {@link Builder} */ public Builder setDataSourcePooledType(boolean dsPooledType) { creator.configuration.setDataSourcePooledType(dsPooledType); return this; } /** * Sets which data source pool provider should use application by * {@link PoolProviderType} parameter * * @param poolProviderType * @return {@link Builder} */ public Builder setPoolProviderType(PoolProviderType poolProviderType) { creator.configuration.setPoolProviderType(poolProviderType); return this; } /** * Sets path for data source pool additional properties * * @param path * @return {@link Builder} */ public Builder setPoolPropertiesPath(String path) { creator.configuration.setPoolPropertiesPath(path); return this; } /** * Sets data source pool additional properties * * @param properties * @return {@link Builder} */ public Builder setPoolProperties( Map<? extends Object, ? extends Object> properties) { creator.configuration.setPoolProperties(properties); return this; } /** * Adds instance property for pooled data source * * @param key * @param value * @return {@link Builder} */ public Builder addPoolProperty(Object key, Object value) { creator.configuration.addPoolProperty(key, value); return this; } /** * Sets boolean check is application in hot deployment (with watch * service on deployment directories) or not * * @param hotDeployment * @return {@link Builder} */ public Builder setHotDeployment(boolean hotDeployment) { creator.configuration.setHotDeployment(hotDeployment); return this; } /** * Adds additional parameters from passed {@link Map} to existing * configuration * * @param configuration * @return */ public Builder addConfiguration(Map<Object, Object> configuration) { creator.configuration.configure(configuration); return this; } public MetaCreator build() throws IOException { creator.configuration.configure(); LOG.info("Lightmare application starts working"); return creator; } } }
package org.lightmare.deploy; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.ejb.Local; import javax.ejb.Remote; import javax.ejb.Stateless; import org.apache.log4j.Logger; import org.lightmare.cache.ArchiveData; import org.lightmare.cache.DeployData; import org.lightmare.cache.DeploymentDirectory; import org.lightmare.cache.MetaContainer; import org.lightmare.cache.RestContainer; import org.lightmare.cache.TmpResources; import org.lightmare.config.ConfigKeys; import org.lightmare.config.Configuration; import org.lightmare.deploy.fs.Watcher; import org.lightmare.jpa.datasource.Initializer; import org.lightmare.jpa.datasource.PoolConfig.PoolProviderType; import org.lightmare.libraries.LibraryLoader; import org.lightmare.remote.rpc.RPCall; import org.lightmare.remote.rpc.RpcListener; import org.lightmare.rest.providers.RestProvider; import org.lightmare.scannotation.AnnotationDB; import org.lightmare.utils.AbstractIOUtils; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.LogUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.fs.FileUtils; import org.lightmare.utils.fs.WatchUtils; import org.lightmare.utils.shutdown.ShutDown; /** * Determines and saves in cache EJB beans {@link org.lightmare.cache.MetaData} * on startup * * @author Levan * */ public class MetaCreator { private static AnnotationDB annotationDB; // Cached temporal resources for clean after deployment private TmpResources tmpResources; private boolean await; // Blocker for deployments connections or beans private CountDownLatch blocker; // Data for cache at deploy time private Map<String, AbstractIOUtils> aggregateds = new HashMap<String, AbstractIOUtils>(); private Map<URL, ArchiveData> archivesURLs; private Map<String, URL> classOwnersURL; private Map<URL, DeployData> realURL; private ClassLoader current; // Configuration for appropriate archives URLs private Configuration configuration; // Lock for deployment and directory scanning private final Lock scannerLock = new ReentrantLock(); // Lock for MetaCreator initialization private static final Lock LOCK = new ReentrantLock(); private static final Logger LOG = Logger.getLogger(MetaCreator.class); private MetaCreator() { tmpResources = new TmpResources(); ShutDown.setHook(tmpResources); } private static MetaCreator get() { MetaCreator creator = MetaContainer.getCreator(); if (creator == null) { LOCK.lock(); try { if (creator == null) { creator = new MetaCreator(); MetaContainer.setCreator(creator); } } finally { LOCK.unlock(); } } return creator; } private void configure(URL[] archives) { if (configuration == null && CollectionUtils.available(archives)) { configuration = MetaContainer.getConfig(archives); } } public AnnotationDB getAnnotationDB() { return annotationDB; } public Map<String, AbstractIOUtils> getAggregateds() { return aggregateds; } /** * Caches each archive by it's {@link URL} for deployment * * @param ejbURLs * @param archiveData */ private void fillArchiveURLs(Collection<URL> ejbURLs, ArchiveData archiveData, DeployData deployData) { for (URL ejbURL : ejbURLs) { archivesURLs.put(ejbURL, archiveData); realURL.put(ejbURL, deployData); } } /** * Caches each archive by it's {@link URL} for deployment and creates fill * {@link URL} array for scanning and finding {@link javax.ejb.Stateless} * annotated classes * * @param archive * @param modifiedArchives * @throws IOException */ private void fillArchiveURLs(URL archive, List<URL> modifiedArchives) throws IOException { AbstractIOUtils ioUtils = AbstractIOUtils.getAppropriatedType(archive); if (ObjectUtils.notNull(ioUtils)) { ioUtils.scan(configuration.isPersXmlFromJar()); List<URL> ejbURLs = ioUtils.getEjbURLs(); modifiedArchives.addAll(ejbURLs); ArchiveData archiveData = new ArchiveData(); archiveData.setIoUtils(ioUtils); DeployData deployData = new DeployData(); deployData.setType(ioUtils.getType()); deployData.setUrl(archive); if (ejbURLs.isEmpty()) { archivesURLs.put(archive, archiveData); realURL.put(archive, deployData); } else { fillArchiveURLs(ejbURLs, archiveData, deployData); } } } /** * Gets {@link URL} array for all classes and jar libraries within archive * file for class loading policy * * @param archives * @return {@link URL}[] * @throws IOException */ private URL[] getFullArchives(URL[] archives) throws IOException { List<URL> modifiedArchives = new ArrayList<URL>(); for (URL archive : archives) { fillArchiveURLs(archive, modifiedArchives); } return CollectionUtils.toArray(modifiedArchives, URL.class); } /** * Awaits for {@link Future} tasks if it set so by configuration * * @param future */ private void awaitDeployment(Future<String> future) { if (await) { try { String nameFromFuture = future.get(); LogUtils.info(LOG, "Deploy processing of %s finished", nameFromFuture); } catch (InterruptedException ex) { LOG.error(ex.getMessage(), ex); } catch (ExecutionException ex) { LOG.error(ex.getMessage(), ex); } } } /** * Awaits for {@link CountDownLatch} of deployments */ private void awaitDeployments() { try { blocker.await(); } catch (InterruptedException ex) { LOG.error(ex); } } /** * Starts bean deployment process for bean name * * @param beanName * @throws IOException */ private void deployBean(String beanName) throws IOException { URL currentURL = classOwnersURL.get(beanName); ArchiveData archiveData = archivesURLs.get(currentURL); if (archiveData == null) { archiveData = new ArchiveData(); } AbstractIOUtils ioUtils = archiveData.getIoUtils(); if (ioUtils == null) { ioUtils = AbstractIOUtils.getAppropriatedType(currentURL); archiveData.setIoUtils(ioUtils); } ClassLoader loader = archiveData.getLoader(); // Finds appropriated ClassLoader if needed and or creates new one List<File> tmpFiles = null; if (ObjectUtils.notNull(ioUtils)) { if (loader == null) { if (ioUtils.notExecuted()) { ioUtils.scan(configuration.isPersXmlFromJar()); } URL[] libURLs = ioUtils.getURLs(); loader = LibraryLoader.initializeLoader(libURLs); archiveData.setLoader(loader); } tmpFiles = ioUtils.getTmpFiles(); aggregateds.put(beanName, ioUtils); } // Archive file url which contains this bean DeployData deployData; if (CollectionUtils.available(realURL)) { deployData = realURL.get(currentURL); } else { deployData = null; } // Initializes and fills BeanLoader.BeanParameters class to deploy // stateless EJB bean BeanLoader.BeanParameters parameters = new BeanLoader.BeanParameters(); parameters.creator = this; parameters.className = beanName; parameters.loader = loader; parameters.tmpFiles = tmpFiles; parameters.blocker = blocker; parameters.deployData = deployData; parameters.configuration = configuration; Future<String> future = BeanLoader.loadBean(parameters); awaitDeployment(future); if (ObjectUtils.available(tmpFiles)) { tmpResources.addFile(tmpFiles); } } /** * Deploys single bean by class name * * @param beanNames */ private void deployBeans(Set<String> beanNames) { blocker = new CountDownLatch(beanNames.size()); for (String beanName : beanNames) { LogUtils.info(LOG, "Deploing bean %s", beanName); try { deployBean(beanName); } catch (IOException ex) { LogUtils.error(LOG, ex, "Could not deploy bean %s cause", beanName, ex.getMessage()); } } awaitDeployments(); if (RestContainer.hasRest()) { RestProvider.reload(); } boolean hotDeployment = configuration.isHotDeployment(); boolean watchStatus = configuration.isWatchStatus(); if (hotDeployment && ObjectUtils.notTrue(watchStatus)) { Watcher.startWatch(); watchStatus = Boolean.TRUE; } } /** * Scan application for find all {@link javax.ejb.Stateless} beans and * {@link Remote} or {@link Local} proxy interfaces * * @param archives * @throws IOException * @throws ClassNotFoundException */ public void scanForBeans(URL[] archives) throws IOException { scannerLock.lock(); try { configure(archives); // starts RPC server if configured as remote and server if (configuration.isRemote() && Configuration.isServer()) { RpcListener.startServer(configuration); } else if (configuration.isRemote()) { RPCall.configure(configuration); } String[] libraryPaths = configuration.getLibraryPaths(); // Loads libraries from specified path if (ObjectUtils.notNull(libraryPaths)) { LibraryLoader.loadLibraries(libraryPaths); } // Gets and caches class loader current = LibraryLoader.getContextClassLoader(); archivesURLs = new HashMap<URL, ArchiveData>(); if (ObjectUtils.available(archives)) { realURL = new HashMap<URL, DeployData>(); } URL[] fullArchives = getFullArchives(archives); annotationDB = new AnnotationDB(); annotationDB.setScanFieldAnnotations(Boolean.FALSE); annotationDB.setScanParameterAnnotations(Boolean.FALSE); annotationDB.setScanMethodAnnotations(Boolean.FALSE); annotationDB.scanArchives(fullArchives); Set<String> beanNames = annotationDB.getAnnotationIndex().get( Stateless.class.getName()); classOwnersURL = annotationDB.getClassOwnersURLs(); Initializer.initializeDataSources(configuration); if (ObjectUtils.available(beanNames)) { deployBeans(beanNames); } } finally { // Caches configuration MetaContainer.putConfig(archives, configuration); // clears cached resources clear(); // gets rid from all created temporary files tmpResources.removeTempFiles(); scannerLock.unlock(); } } /** * Scan application for find all {@link javax.ejb.Stateless} beans and * {@link Remote} or {@link Local} proxy interfaces * * @throws ClassNotFoundException * @throws IOException */ public void scanForBeans(File[] jars) throws IOException { List<URL> urlList = new ArrayList<URL>(); URL url; for (File file : jars) { url = file.toURI().toURL(); urlList.add(url); } URL[] archives = CollectionUtils.toArray(urlList, URL.class); scanForBeans(archives); } /** * Scan application for find all {@link javax.ejb.Stateless} beans and * {@link Remote} or {@link Local} proxy interfaces * * @throws ClassNotFoundException * @throws IOException */ public void scanForBeans(String... paths) throws IOException { if (ObjectUtils.notAvailable(paths) && ObjectUtils.available(configuration.getDeploymentPath())) { Set<DeploymentDirectory> deployments = configuration .getDeploymentPath(); List<String> pathList = new ArrayList<String>(); File deployFile; for (DeploymentDirectory deployment : deployments) { deployFile = new File(deployment.getPath()); if (deployment.isScan()) { String[] subDeployments = deployFile.list(); if (ObjectUtils.available(subDeployments)) { pathList.addAll(Arrays.asList(subDeployments)); } } } paths = CollectionUtils.toArray(pathList, String.class); } List<URL> urlList = new ArrayList<URL>(); List<URL> archive; for (String path : paths) { archive = FileUtils.toURLWithClasspath(path); urlList.addAll(archive); } URL[] archives = CollectionUtils.toArray(urlList, URL.class); scanForBeans(archives); } public ClassLoader getCurrent() { return current; } /** * Clears all locally cached data */ public void clear() { boolean locked = scannerLock.tryLock(); while (ObjectUtils.notTrue(locked)) { locked = scannerLock.tryLock(); } if (locked) { try { if (ObjectUtils.available(realURL)) { realURL.clear(); realURL = null; } if (ObjectUtils.available(aggregateds)) { aggregateds.clear(); } if (ObjectUtils.available(archivesURLs)) { archivesURLs.clear(); archivesURLs = null; } if (ObjectUtils.available(classOwnersURL)) { classOwnersURL.clear(); classOwnersURL = null; } configuration = null; } finally { scannerLock.unlock(); } } } /** * Closes all connections clears all caches * * @throws IOException */ public static void close() throws IOException { ShutDown.clearAll(); } /** * Builder class to provide properties for lightmare application and * initialize {@link MetaCreator} instance * * @author levan * */ public static class Builder { private MetaCreator creator; public Builder(boolean cloneConfiguration) throws IOException { creator = MetaCreator.get(); Configuration config = creator.configuration; if (cloneConfiguration && ObjectUtils.notNull(config)) { try { creator.configuration = (Configuration) config.clone(); } catch (CloneNotSupportedException ex) { throw new IOException(ex); } } else { creator.configuration = new Configuration(); } } public Builder() throws IOException { this(Boolean.FALSE); } public Builder(Map<Object, Object> configuration) throws IOException { this(); creator.configuration.configure(configuration); } public Builder(String path) throws IOException { this(); creator.configuration.configure(path); } private Map<Object, Object> initPersistenceProperties() { Map<Object, Object> persistenceProperties = creator.configuration .getPersistenceProperties(); if (persistenceProperties == null) { persistenceProperties = new HashMap<Object, Object>(); creator.configuration .setPersistenceProperties(persistenceProperties); } return persistenceProperties; } /** * Sets additional persistence properties * * @param properties * @return {@link Builder} */ public Builder setPersistenceProperties(Map<String, String> properties) { if (ObjectUtils.available(properties)) { Map<Object, Object> persistenceProperties = initPersistenceProperties(); persistenceProperties.putAll(properties); } return this; } /** * Adds instant persistence property * * @param key * @param property * @return {@link Builder} */ public Builder addPersistenceProperty(String key, String property) { Map<Object, Object> persistenceProperties = initPersistenceProperties(); persistenceProperties.put(key, property); return this; } /** * Adds property to scan for {@link javax.persistence.Entity} annotated * classes from deployed archives * * @param scanForEnt * @return {@link Builder} */ public Builder setScanForEntities(boolean scanForEnt) { creator.configuration.setScanForEntities(scanForEnt); return this; } /** * Adds property to use only {@link org.lightmare.annotations.UnitName} * annotated entities for which * {@link org.lightmare.annotations.UnitName#value()} matches passed * unit name * * @param unitName * @return {@link Builder} */ public Builder setUnitName(String unitName) { creator.configuration.setAnnotatedUnitName(unitName); return this; } /** * Sets path for persistence.xml file * * @param path * @return {@link Builder} */ public Builder setPersXmlPath(String path) { creator.configuration.setPersXmlPath(path); creator.configuration.setScanArchives(Boolean.FALSE); return this; } /** * Adds path for additional libraries to load at start time * * @param libPaths * @return {@link Builder} */ public Builder setLibraryPath(String... libPaths) { creator.configuration.setLibraryPaths(libPaths); return this; } /** * Sets boolean checker to scan persistence.xml files from appropriated * jar files * * @param xmlFromJar * @return {@link Builder} */ public Builder setXmlFromJar(boolean xmlFromJar) { creator.configuration.setPersXmlFromJar(xmlFromJar); return this; } /** * Sets boolean checker to swap jta data source value with non jta data * source value * * @param swapDataSource * @return {@link Builder} */ public Builder setSwapDataSource(boolean swapDataSource) { creator.configuration.setSwapDataSource(swapDataSource); return this; } /** * Adds path for data source file * * @param dataSourcePath * @return {@link Builder} */ public Builder addDataSourcePath(String dataSourcePath) { creator.configuration.addDataSourcePath(dataSourcePath); return this; } /** * This method is deprecated should use * {@link MetaCreator.Builder#addDataSourcePath(String)} instead * * @param dataSourcePath * @return {@link MetaCreator.Builder} */ @Deprecated public Builder setDataSourcePath(String dataSourcePath) { creator.configuration.addDataSourcePath(dataSourcePath); return this; } /** * Sets boolean checker to scan {@link javax.persistence.Entity} * annotated classes from appropriated deployed archive files * * @param scanArchives * @return {@link Builder} */ public Builder setScanArchives(boolean scanArchives) { creator.configuration.setScanArchives(scanArchives); return this; } /** * Sets boolean checker to block deployment processes * * @param await * @return {@link Builder} */ public Builder setAwaitDeploiment(boolean await) { creator.await = await; return this; } /** * Sets property is server or not in embedded mode * * @param remote * @return {@link Builder} */ public Builder setRemote(boolean remote) { creator.configuration.setRemote(remote); return this; } /** * Sets property is application server or just client for other remote * server * * @param server * @return {@link Builder} */ public Builder setServer(boolean server) { Configuration.setServer(server); creator.configuration.setClient(ObjectUtils.notTrue(server)); return this; } /** * Sets boolean check is application in just client mode or not * * @param client * @return {@link Builder} */ public Builder setClient(boolean client) { creator.configuration.setClient(client); Configuration.setServer(ObjectUtils.notTrue(client)); return this; } /** * To add any additional property * * @param key * @param property * @return {@link Builder} */ public Builder setProperty(String key, String property) { creator.configuration.putValue(key, property); return this; } /** * File path for administrator user name and password * * @param property * @return {@link Builder} */ public Builder setAdminUsersPth(String property) { Configuration.setAdminUsersPath(property); return this; } /** * Sets specific IP address in case when application is in remote server * mode * * @param property * @return {@link Builder} */ public Builder setIpAddress(String property) { creator.configuration.putValue(ConfigKeys.IP_ADDRESS.key, property); return this; } /** * Sets specific port in case when application is in remote server mode * * @param property * @return {@link Builder} */ public Builder setPort(String property) { creator.configuration.putValue(ConfigKeys.PORT.key, property); return this; } /** * Sets amount for network master threads in case when application is in * remote server mode * * @param property * @return {@link Builder} */ public Builder setMasterThreads(String property) { creator.configuration.putValue(ConfigKeys.BOSS_POOL.key, property); return this; } /** * Sets amount of worker threads in case when application is in remote * server mode * * @param property * @return {@link Builder} */ public Builder setWorkerThreads(String property) { creator.configuration .putValue(ConfigKeys.WORKER_POOL.key, property); return this; } /** * Adds deploy file path to application with boolean checker if file is * directory to scan this directory for deployment files list * * @param deploymentPath * @param scan * @return {@link Builder} */ public Builder addDeploymentPath(String deploymentPath, boolean scan) { String clearPath = WatchUtils.clearPath(deploymentPath); creator.configuration.addDeploymentPath(clearPath, scan); return this; } /** * Adds deploy file path to application * * @param deploymentPath * @return {@link Builder} */ public Builder addDeploymentPath(String deploymentPath) { addDeploymentPath(deploymentPath, Boolean.FALSE); return this; } /** * Adds timeout for connection in case when application is in remote * server or client mode * * @param property * @return {@link Builder} */ public Builder setTimeout(String property) { creator.configuration.putValue(ConfigKeys.CONNECTION_TIMEOUT.key, property); return this; } /** * Adds boolean check if application is using pooled data source * * @param dsPooledType * @return {@link Builder} */ public Builder setDataSourcePooledType(boolean dsPooledType) { creator.configuration.setDataSourcePooledType(dsPooledType); return this; } /** * Sets which data source pool provider should use application by * {@link PoolProviderType} parameter * * @param poolProviderType * @return {@link Builder} */ public Builder setPoolProviderType(PoolProviderType poolProviderType) { creator.configuration.setPoolProviderType(poolProviderType); return this; } /** * Sets path for data source pool additional properties * * @param path * @return {@link Builder} */ public Builder setPoolPropertiesPath(String path) { creator.configuration.setPoolPropertiesPath(path); return this; } /** * Sets data source pool additional properties * * @param properties * @return {@link Builder} */ public Builder setPoolProperties( Map<? extends Object, ? extends Object> properties) { creator.configuration.setPoolProperties(properties); return this; } /** * Adds instance property for pooled data source * * @param key * @param value * @return {@link Builder} */ public Builder addPoolProperty(Object key, Object value) { creator.configuration.addPoolProperty(key, value); return this; } /** * Sets boolean check is application in hot deployment (with watch * service on deployment directories) or not * * @param hotDeployment * @return {@link Builder} */ public Builder setHotDeployment(boolean hotDeployment) { creator.configuration.setHotDeployment(hotDeployment); return this; } /** * Adds additional parameters from passed {@link Map} to existing * configuration * * @param configuration * @return */ public Builder addConfiguration(Map<Object, Object> configuration) { creator.configuration.configure(configuration); return this; } public MetaCreator build() throws IOException { creator.configuration.configure(); LOG.info("Lightmare application starts working"); return creator; } } }
package org.osjava.norbert; import java.io.IOException; import java.io.StringReader; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; import java.net.URL; import java.net.URLDecoder; import java.net.MalformedURLException; import java.net.HttpURLConnection; import java.net.URLConnection; public class NoRobotClient { private String userAgent; private RulesEngine rules; private RulesEngine wildcardRules; private URL baseUrl; private boolean existsRobots; private boolean wildcardsAllowed; /** * Create a Client for a particular user-agent name. * * @param userAgent name for the robot */ public NoRobotClient(String userAgent) { this.userAgent = userAgent; existsRobots = false; wildcardsAllowed = false; } public void setWildcardsAllowed(boolean allowed) { wildcardsAllowed = allowed; } public static URL getBaseURL(URL baseUrl) { if (!"file".equals(baseUrl.getProtocol())) { String strBaseUrl = rewriteBaseURL(baseUrl.toExternalForm()); if ("".equals(strBaseUrl)) return null; try { return new URL(strBaseUrl); } catch(Exception e) { return null; } } else { return baseUrl; } } public static String rewriteBaseURL(String str) { try { URL url = new URL(str); String ret = url.getProtocol() + "://" + url.getHost(); if (!"-1".equals(String.valueOf(url.getPort()))) if ( !(("http".equals(url.getProtocol())) && ("80".equals(String.valueOf(url.getPort())))) && !(("https".equals(url.getProtocol())) && ("443".equals(String.valueOf(url.getPort())))) ) { ret += ":" + url.getPort(); } ret += "/"; return ret; } catch (Exception e) {} return ""; } /** * Head to a website and suck in their robots.txt file. * Note that the URL passed in is for the website and does * not include the robots.txt file itself. * * @param baseUrl of the site */ public void parse(URL baseUrl) throws NoRobotException { this.rules = new RulesEngine(); //this.baseUrl = getBaseURL(baseUrl); URL txtUrl = null; try { // fetch baseUrl+"robots.txt" txtUrl = new URL(baseUrl, "robots.txt"); } catch(MalformedURLException murle) { throw new NoRobotException("Bad URL: "+baseUrl+", robots.txt. ", murle); } String txt = null; try { txt = loadContent(txtUrl, this.userAgent); if(txt == null) { throw new NoRobotException("No content found for: "+txtUrl); } } catch(IOException ioe) { throw new NoRobotException("Unable to get robots.txt content for: "+txtUrl, ioe); } try { parseText(baseUrl, txt); } catch(NoRobotException nre) { throw new NoRobotException("Problem while parsing "+txtUrl, nre); } } public void parseText(URL baseUrl, String txt) throws NoRobotException { this.baseUrl = getBaseURL(baseUrl); this.rules = parseTextForUserAgent(txt, this.userAgent); this.wildcardRules = parseTextForUserAgent(txt, "*"); existsRobots = true; } private RulesEngine parseTextForUserAgent(String txt, String userAgent) throws NoRobotException { RulesEngine engine = new RulesEngine(); // Classic basic parser style, read an element at a time, // changing a state variable [parsingAllowBlock] // take each line, one at a time BufferedReader rdr = new BufferedReader( new StringReader(txt) ); String line = ""; String value = null; boolean parsingAllowBlock = false; try { while( (line = rdr.readLine()) != null ) { // trim whitespace from either side line = line.trim(); //change the line's string to new lowercase string //add this line to store the text after exchanging all of the line's text to lowercase. String lineToLowerCase=line.toLowerCase(); // ignore startsWith(' if(line.startsWith(" continue; } // if User-agent == userAgent // record the rest up until end or next User-agent // then quit (? check spec) if(lineToLowerCase.startsWith("user-agent:")) { if(parsingAllowBlock) { // we've just finished reading allows/disallows if(engine.isEmpty()) { // multiple user agents in a line, let's // wait til we get rules continue; } else { break; } } value = line.substring("User-agent:".length()).trim(); if(value.equalsIgnoreCase(userAgent)) { parsingAllowBlock = true; continue; } } else { // if not, then store if we're currently the user agent if(parsingAllowBlock) { if(lineToLowerCase.startsWith("allow:")) { value = line.substring("Allow:".length()).trim(); value = URLDecoder.decode(value, "UTF-8"); engine.allowPath( value, wildcardsAllowed ); } else if(lineToLowerCase.startsWith("disallow:")) { value = line.substring("Disallow:".length()).trim(); value = URLDecoder.decode(value, "UTF-8"); engine.disallowPath( value, wildcardsAllowed ); } else { // ignore continue; } } else { // ignore continue; } } } } catch (IOException ioe) { // As this is parsing a String, it should not have an IOE throw new NoRobotException("Problem while parsing text. ", ioe); } return engine; } public boolean isUrlAllowed(URL url) throws IllegalStateException, IllegalArgumentException { if (!existsRobots) return true; if(rules == null) { throw new IllegalStateException("You must call parse before you call this method. "); } String hostBaseUrl = baseUrl.getHost(); if (hostBaseUrl.indexOf(".") == hostBaseUrl.lastIndexOf(".")) { hostBaseUrl = "www." + hostBaseUrl; } String hostUrl = url.getHost(); if (hostUrl.indexOf(".") == hostUrl.lastIndexOf(".")) { hostUrl = "www." + hostUrl; } if (!hostBaseUrl.equals(hostUrl) || baseUrl.getPort() != url.getPort() || !baseUrl.getProtocol().equals(url.getProtocol())) { return true; // ", for this robots.txt: "+this.baseUrl.toExternalForm()); } String urlStr; try { urlStr = url.toExternalForm().substring( this.baseUrl.toExternalForm().length() - 1); if("/robots.txt".equals(urlStr)) { return true; } urlStr = URLDecoder.decode( urlStr, "UTF-8" ); } catch(Exception e) { //e.printStackTrace(); return true; } Boolean allowed = this.rules.isAllowed( urlStr ); if(allowed == null) { allowed = this.wildcardRules.isAllowed( urlStr ); } if(allowed == null) { allowed = Boolean.TRUE; } return allowed.booleanValue(); } // INLINE: as such from genjava/gj-core's net package. Simple method // stolen from Payload too. private static String loadContent(URL url, String userAgent) throws IOException { URLConnection urlConn = url.openConnection(); if(urlConn instanceof HttpURLConnection) { if(userAgent != null) { ((HttpURLConnection)urlConn).addRequestProperty("User-Agent", userAgent); } } InputStream in = urlConn.getInputStream(); BufferedReader rdr = new BufferedReader(new InputStreamReader(in)); StringBuffer buffer = new StringBuffer(); String line = ""; while( (line = rdr.readLine()) != null) { buffer.append(line); buffer.append("\n"); } in.close(); return buffer.toString(); } }
package org.psjava.ds.array; import java.util.Iterator; import org.psjava.javautil.EqualityTester; import org.psjava.javautil.IterableEqualityTester; import org.psjava.javautil.IterableHash; import org.psjava.javautil.IterableToString; import org.psjava.javautil.StrictEqualityTester; public class DynamicArray<T> implements MutableArray<T>, EqualityTester<Array<T>> { public static <T> DynamicArray<T> create() { return new DynamicArray<T>(); } private T[] a; private int asize; @SuppressWarnings("unchecked") public DynamicArray() { asize = 0; a = (T[])new Object[1]; } @Override public T get(int index) { return a[index]; } @Override public void set(int index, T value) { a[index] = value; } @Override public int size() { return asize; } public void clear() { asize = 0; } @SuppressWarnings("unchecked") public void reserve(int size) { if(a.length < size) { T[] na = (T[])new Object[size]; for(int i=0;i<a.length;i++) na[i] = a[i]; a = na; } } @SuppressWarnings("unchecked") public void addToLast(T value) { if(a.length == asize) { T[] ta = (T[])new Object[asize*2]; for(int i=0;i<asize;i++) ta[i] = a[i]; a =ta; } a[asize++] = value; } public T removeLast() { T r = a[asize - 1]; a[--asize] = null; return r; } @Override public boolean equals(Object obj) { return StrictEqualityTester.areEqual(this, obj, this); } @Override public boolean areEqual(Array<T> o1, Array<T> o2) { return IterableEqualityTester.areEqual(o1, o2); } @Override public int hashCode() { return IterableHash.hash(this); } @Override public final boolean isEmpty() { return asize == 0; } @Override public final Iterator<T> iterator() { return ArrayIterator.create(this); } @Override public final String toString() { return IterableToString.toString(this); } }
package ru.r2cloud.jradio.sink; import java.awt.image.BufferedImage; import java.io.EOFException; import java.io.IOException; import org.jtransforms.fft.FloatFFT_1D; import ru.r2cloud.jradio.source.WavFileSource; public class Waterfall { private final int d_fftsize; private final FloatFFT_1D fft; private final int numRowsPerSecond; private final WaterfallPalette palette = new WaterfallPalette(0.0f, -160.0f, 0x000000, 0x0000e7, 0x0094ff, 0x00ffb8, 0x2eff00, 0xffff00, 0xff8800, 0xff0000, 0xff007c); public Waterfall(int numRowsPerSecond, int width) { this.d_fftsize = width; this.fft = new FloatFFT_1D(d_fftsize); this.numRowsPerSecond = numRowsPerSecond; } public BufferedImage process(WavFileSource source) throws IOException { int maxPossibleNumberOfBlocksPerRow = (int) (source.getFormat().getSampleRate() / numRowsPerSecond); // requested number of rows might be more than available in fft. adjust // height if (maxPossibleNumberOfBlocksPerRow < d_fftsize) { maxPossibleNumberOfBlocksPerRow = d_fftsize; } int height = (int) (source.getFrameLength() / maxPossibleNumberOfBlocksPerRow); BufferedImage image = new BufferedImage(d_fftsize, height, BufferedImage.TYPE_INT_RGB); int skipOnEveryRow = maxPossibleNumberOfBlocksPerRow - d_fftsize; float iNormalizationFactor = (float) 1 / d_fftsize; float[] previousBuf = null; float[] fftBuf = new float[d_fftsize * 2]; float[] fftResult = new float[d_fftsize]; int currentRow = 0; // skip samples which were not fitted into height. while (currentRow < height) { try { for (int i = 0; i < fftBuf.length; i += 2) { fftBuf[i] = source.readFloat(); if (source.getFormat().getChannels() == 2) { fftBuf[i + 1] = source.readFloat(); } else { fftBuf[i + 1] = 0.0f; } } // TODO apply windowing function to the previous data previousBuf = fftBuf; fft.complexForward(previousBuf); for (int i = 0, j = 0; i < previousBuf.length; i += 2, j++) { float real = previousBuf[i] * iNormalizationFactor; float img = previousBuf[i + 1] * iNormalizationFactor; fftResult[j] = (float) (10.0 * Math.log10((real * real) + (img * img) + 1e-20)); } int length = d_fftsize / 2; float[] tmp = new float[length]; System.arraycopy(fftResult, 0, tmp, 0, length); System.arraycopy(fftResult, length, fftResult, 0, fftResult.length - length); System.arraycopy(tmp, 0, fftResult, fftResult.length - length, length); for (int i = 0; i < fftResult.length; i++) { image.setRGB(i, height - currentRow - 1, palette.getRGB(fftResult[i])); } currentRow++; for (int i = 0; i < skipOnEveryRow; i++) { source.readFloat(); if (source.getFormat().getChannels() == 2) { source.readFloat(); } } } catch (EOFException e) { break; } } return image; } }
package scrum.server.project; import java.util.Set; import scrum.server.admin.User; import scrum.server.common.Numbered; import scrum.server.estimation.RequirementEstimationVote; import scrum.server.estimation.RequirementEstimationVoteDao; import scrum.server.sprint.Task; import scrum.server.sprint.TaskDao; public class Requirement extends GRequirement implements Numbered { private static TaskDao taskDao; private static RequirementEstimationVoteDao requirementEstimationVoteDao; public static void setRequirementEstimationVoteDao(RequirementEstimationVoteDao requirementEstimationVoteDao) { Requirement.requirementEstimationVoteDao = requirementEstimationVoteDao; } public static void setTaskDao(TaskDao taskDao) { Requirement.taskDao = taskDao; } public boolean isInCurrentSprint() { if (!isSprintSet()) return false; return isSprint(getProject().getCurrentSprint()); } public void initializeEstimationVotes() { for (User user : getProject().getTeamMembers()) { RequirementEstimationVote vote = getEstimationVote(user); if (vote == null) vote = requirementEstimationVoteDao.postVote(this, user); vote.setEstimatedWork(null); } } private RequirementEstimationVote getEstimationVote(User user) { return requirementEstimationVoteDao.getRequirementEstimationVoteByUser(this, user); } public Set<RequirementEstimationVote> getEstimationVotes() { return requirementEstimationVoteDao.getRequirementEstimationVotesByRequirement(this); } public void clearEstimationVotes() { for (RequirementEstimationVote vote : getEstimationVotes()) { requirementEstimationVoteDao.deleteEntity(vote); } } public boolean isTasksClosed() { for (Task task : getTasks()) { if (!task.isClosed()) return false; } return true; } public String getReferenceAndLabel() { return getReference() + " " + getLabel(); } public String getReference() { return scrum.client.project.Requirement.REFERENCE_PREFIX + getNumber(); } public void updateNumber() { if (getNumber() == 0) setNumber(getProject().generateRequirementNumber()); } @Override public void ensureIntegrity() { super.ensureIntegrity(); updateNumber(); // delete estimation votes when closed or in sprint if (isClosed() || isSprintSet()) clearEstimationVotes(); // delete when closed and older than 4 weeks if (isClosed() && getLastModified().getPeriodToNow().toWeeks() > 4) getDao().deleteEntity(this); } public Set<Task> getTasks() { return taskDao.getTasksByRequirement(this); } public boolean isVisibleFor(User user) { return getProject().isVisibleFor(user); } @Override public String toString() { return getReferenceAndLabel(); } }
package seedu.address.model; import java.util.Set; import java.util.logging.Logger; import javafx.collections.transformation.FilteredList; import seedu.address.commons.core.ComponentManager; import seedu.address.commons.core.LogsCenter; import seedu.address.commons.core.UnmodifiableObservableList; import seedu.address.commons.events.model.DueueChangedEvent; import seedu.address.commons.util.CollectionUtil; import seedu.address.commons.util.StringUtil; import seedu.address.model.task.ReadOnlyTask; import seedu.address.model.task.Task; import seedu.address.model.task.UniqueTaskList; import seedu.address.model.task.UniqueTaskList.DuplicateTaskException; import seedu.address.model.task.UniqueTaskList.TaskNotFoundException; import seedu.address.model.tasklist.TaskList; import seedu.address.model.tasklist.UniqueListList; /** * Represents the in-memory model of the address book data. * All changes to any model should be synchronized. */ public class ModelManager extends ComponentManager implements Model { private static final Logger logger = LogsCenter.getLogger(ModelManager.class); private final TaskManager taskManager; private final FilteredList<ReadOnlyTask> filteredTasks; private final FilteredList<TaskList> filteredLists; /** * Initializes a ModelManager with the given taskManager and userPrefs. */ public ModelManager(ReadOnlyTaskManager taskManager, UserPrefs userPrefs) { super(); assert !CollectionUtil.isAnyNull(taskManager, userPrefs); logger.fine("Initializing with address book: " + taskManager + " and user prefs " + userPrefs); this.taskManager = new TaskManager(taskManager); filteredTasks = new FilteredList<>(this.taskManager.getTaskList()); filteredLists = new FilteredList<>(this.taskManager.getListList()); } public ModelManager() { this(new TaskManager(), new UserPrefs()); } @Override public void resetData(ReadOnlyTaskManager newData) { taskManager.resetData(newData); indicateTaskManagerChanged(); } @Override public ReadOnlyTaskManager getTaskManager() { return taskManager; } /** Raises an event to indicate the model has changed */ private void indicateTaskManagerChanged() { raise(new DueueChangedEvent(taskManager)); } @Override public synchronized void deleteTask(ReadOnlyTask target) throws TaskNotFoundException { taskManager.removeTask(target); indicateTaskManagerChanged(); } @Override public synchronized void addTask(Task task) throws DuplicateTaskException { taskManager.addTask(task); updateFilteredListToShowAllTasks(); indicateTaskManagerChanged(); } @Override public void updateTask(int filteredTaskListIndex, ReadOnlyTask editedTask) throws UniqueTaskList.DuplicateTaskException { assert editedTask != null; int taskManagerIndex = filteredTasks.getSourceIndex(filteredTaskListIndex); taskManager.updateTask(taskManagerIndex, editedTask); indicateTaskManagerChanged(); } @Override public synchronized void addList(TaskList list) throws UniqueListList.DuplicateListException { assert list != null; taskManager.addList(list); updateFilteredListToShowAllLists(); indicateTaskManagerChanged(); } @Override public synchronized void removeList(TaskList target) throws UniqueListList.ListNotFoundException { taskManager.removeList(target); indicateTaskManagerChanged(); } @Override public void updateList(int filteredListListIndex, TaskList editedList) throws UniqueListList.DuplicateListException { assert editedList != null; int taskManagerIndex = filteredLists.getSourceIndex(filteredListListIndex); taskManager.updateList(taskManagerIndex, editedList); indicateTaskManagerChanged(); } @Override public UnmodifiableObservableList<ReadOnlyTask> getFilteredTaskList() { return new UnmodifiableObservableList<>(filteredTasks); } @Override public void updateFilteredListToShowAllTasks() { filteredTasks.setPredicate(null); } @Override public void updateFilteredTaskList(Set<String> keywords) { updateFilteredTaskList(new PredicateExpression(new NameQualifier(keywords))); } private void updateFilteredTaskList(Expression expression) { filteredTasks.setPredicate(expression::satisfies); } @Override public void updateFilteredTaskListGivenListName(Set<String> keywords) { updateFilteredTaskList(new PredicateExpression(new TagQualifier(keywords))); } @Override public UnmodifiableObservableList<TaskList> getFilteredListList() { return new UnmodifiableObservableList<>(filteredLists); } @Override public void updateFilteredListToShowAllLists() { filteredLists.setPredicate(null); } @Override public void updateFilteredListList(Set<String> keywords) { updateFilteredListList(new PredicateExpression(new NameQualifier(keywords))); } private void updateFilteredListList(Expression expression) { filteredLists.setPredicate(expression::satisfies); } interface Expression { boolean satisfies(ReadOnlyTask task); boolean satisfies(TaskList list); String toString(); } private class PredicateExpression implements Expression { private final Qualifier qualifier; PredicateExpression(Qualifier qualifier) { this.qualifier = qualifier; } @Override public boolean satisfies(ReadOnlyTask task) { return qualifier.run(task); } @Override public boolean satisfies(TaskList list){ return qualifier.run(list); } @Override public String toString() { return qualifier.toString(); } } interface Qualifier { boolean run(ReadOnlyTask task); boolean run(TaskList list); String toString(); } private class NameQualifier implements Qualifier { private Set<String> nameKeyWords; NameQualifier(Set<String> nameKeyWords) { this.nameKeyWords = nameKeyWords; } @Override public boolean run(ReadOnlyTask task) { return nameKeyWords.stream() .filter(keyword -> StringUtil.containsWordIgnoreCase(task.getName().fullName, keyword)) .findAny() .isPresent(); } @Override public boolean run(TaskList list) { return nameKeyWords.stream() .filter(keyword -> StringUtil.containsWordIgnoreCase(list.getName(), keyword)) .findAny() .isPresent(); } @Override public String toString() { return "name=" + String.join(", ", nameKeyWords); } } private class TagQualifier implements Qualifier { private Set<String> tagKeyWords; TagQualifier(Set<String> tagKeyWords) { this.tagKeyWords = tagKeyWords; } @Override public boolean run(ReadOnlyTask task) { return tagKeyWords.stream() .filter(keyword -> StringUtil.containsWordIgnoreCase(task.getTag().getName(), keyword)) .findAny() .isPresent(); } @Override public boolean run(TaskList list) { return false; } @Override public String toString() { return "name=" + String.join(", ", tagKeyWords); } } }
package seedu.address.ui; import com.google.common.eventbus.Subscribe; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.GridPane; import javafx.stage.Stage; import org.controlsfx.control.StatusBar; import seedu.address.commons.core.LogsCenter; import seedu.address.commons.events.model.TaskBookChangedEvent; import seedu.address.commons.events.storage.StorageDataPathChangedEvent; import seedu.address.commons.util.FxViewUtil; import java.util.Date; import java.util.logging.Logger; /** * A ui for the status bar that is displayed at the footer of the application. */ public class StatusBarFooter extends UiPart { private static final Logger logger = LogsCenter.getLogger(StatusBarFooter.class); private StatusBar syncStatus; private StatusBar saveLocationStatus; private GridPane mainPane; @FXML private AnchorPane saveLocStatusBarPane; @FXML private AnchorPane syncStatusBarPane; private AnchorPane placeHolder; private static final String FXML = "StatusBarFooter.fxml"; public static StatusBarFooter load(Stage stage, AnchorPane placeHolder, String saveLocation) { StatusBarFooter statusBarFooter = UiPartLoader.loadUiPart(stage, placeHolder, new StatusBarFooter()); statusBarFooter.configure(saveLocation); return statusBarFooter; } public void configure(String saveLocation) { addMainPane(); addSyncStatus(); setSyncStatus("Not updated yet in this session"); addSaveLocation(); setSaveLocation("./" + saveLocation); registerAsAnEventHandler(this); } private void addMainPane() { FxViewUtil.applyAnchorBoundaryParameters(mainPane, 0.0, 0.0, 0.0, 0.0); placeHolder.getChildren().add(mainPane); } private void setSaveLocation(String location) { this.saveLocationStatus.setText(location); } private void addSaveLocation() { this.saveLocationStatus = new StatusBar(); FxViewUtil.applyAnchorBoundaryParameters(saveLocationStatus, 0.0, 0.0, 0.0, 0.0); saveLocStatusBarPane.getChildren().add(saveLocationStatus); } private void setSyncStatus(String status) { this.syncStatus.setText(status); } private void addSyncStatus() { this.syncStatus = new StatusBar(); FxViewUtil.applyAnchorBoundaryParameters(syncStatus, 0.0, 0.0, 0.0, 0.0); syncStatusBarPane.getChildren().add(syncStatus); } @Override public void setNode(Node node) { mainPane = (GridPane) node; } @Override public void setPlaceholder(AnchorPane placeholder) { this.placeHolder = placeholder; } @Override public String getFxmlPath() { return FXML; } @Subscribe public void handleTaskBookChangedEvent(TaskBookChangedEvent tbce) { String lastUpdated = (new Date()).toString(); logger.info(LogsCenter.getEventHandlingLogMessage(tbce, "Setting last updated status to " + lastUpdated)); setSyncStatus("Last Updated: " + lastUpdated); } //@@author A0139528W @Subscribe public void handleStorageDataChangedEvent(StorageDataPathChangedEvent event) { logger.info(LogsCenter.getEventHandlingLogMessage(event, "Saving task.xml in a new location.")); setSaveLocation(event.newDataPath); } //@@author }
package serverHandlers; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.util.Date; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; public class TimeClientHandler extends ChannelInboundHandlerAdapter { private static final Logger LOG = LogManager.getLogger(TimeClientHandler.class); private ByteBuf content; private ChannelHandlerContext ctx; @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { this.ctx = ctx; sendMessage("Join me!!"); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ByteBuf in = (ByteBuf) msg; String requestMsg =in.toString(StandardCharsets.UTF_8 ); String response = handleClientRequest(requestMsg); ctx.write(Unpooled.copiedBuffer(response+"\r\n", StandardCharsets.UTF_8)); ctx.flush(); } private String handleClientRequest(String requestMsg) { // LOG.info("handleClientRequest:"+requestMsg); if(requestMsg.contains("OK")){ //add the ip:port to the group member list; // String[] arr = requestMsg.split(":"); // InetSocketAddress addr = new InetSocketAddress(arr[1].trim(), Integer.parseInt(arr[2].trim())); // server.addMemberToList(addr); LOG.info("Client rreceived OK!!"); return ""; } return "..."; } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } private void sendMessage(String msg) { // TODO Auto-generated method stub ctx.writeAndFlush(Unpooled.copiedBuffer(msg+"\r\n", StandardCharsets.UTF_8)).addListener(listener1); } private final ChannelFutureListener listener1 = new ChannelFutureListener(){ public void operationComplete(ChannelFuture future) throws Exception { if(future.isSuccess()){ LOG.info("in listener1. op complete success"); } else{ future.cause().printStackTrace(); future.channel().close(); } } }; }
package tamaized.aov.registry; import net.minecraft.potion.Potion; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.registries.ObjectHolder; import tamaized.aov.AoV; import tamaized.aov.common.potion.PotionAid; import tamaized.aov.common.potion.PotionBalance; import tamaized.aov.common.potion.PotionColdChill; import tamaized.aov.common.potion.PotionEwer; import tamaized.aov.common.potion.PotionNaturesBounty; import tamaized.aov.common.potion.PotionSlowFall; import tamaized.aov.common.potion.PotionSpear; import tamaized.aov.common.potion.PotionSpire; import tamaized.aov.common.potion.PotionStalwartPact; @ObjectHolder(AoV.MODID) @Mod.EventBusSubscriber(modid = AoV.MODID, bus = Mod.EventBusSubscriber.Bus.MOD) public class AoVPotions { public static Potion aid; public static Potion shieldOfFaith; public static Potion zeal; public static Potion stalwartPact; public static Potion slowFall; public static Potion spear; public static Potion ewer; public static Potion spire; public static Potion balance; public static Potion naturesBounty; public static Potion coldChill; @SubscribeEvent public static void registerPotions(RegistryEvent.Register<Potion> event) { event.getRegistry().registerAll( aid = new PotionAid("aid"), shieldOfFaith = new PotionAid("shieldoffaith"), zeal = new PotionAid("zeal"), stalwartPact = new PotionStalwartPact("stalwartpact"), slowFall = new PotionSlowFall("slowfall"), spear = new PotionSpear("spear"), ewer = new PotionEwer("ewer"), spire = new PotionSpire("spire"), balance = new PotionBalance("balance"), naturesBounty = new PotionNaturesBounty("naturesbounty"), coldChill = new PotionColdChill("coldchill") ); } }
public class Dwarf{ private int vida; private String name; private int xp = 0; private Status status; private Inventario inventario; private DataTerceiraEra dataNasc = new DataTerceiraEra(1,1,1); public Dwarf(String name){ this.name = name; this.vida = 110; this.status = status.VIVO; this.inventario = new Inventario(); } public Dwarf(String name, DataTerceiraEra dte){ this(name); this.dataNasc = dte; } public void perdeVida(){ double numeroSorte = getNumeroSorte(); if(numeroSorte < 0){ xp += 2; return; } else if(numeroSorte <= 100) return; else{ int vidaAposFlechada = vida - 10; if(vidaAposFlechada == 0) status = status.MORTO; if(vida > 0) vida -= 10; } } public double getNumeroSorte(){ double numeroSorte = 101; boolean ehBissexto = dataNasc.ehBissexto(); boolean vidaEntreOitentaENoventa = this.vida >= 80 && this.vida <=90; boolean nameEhSeixasOuMeireles = this.name != null && (this.name.equals("Seixas") || this.name.equals("Meireles")); return ehBissexto ? vidaEntreOitentaENoventa ? -33 * 101 : numeroSorte : nameEhSeixasOuMeireles ? (33 * 101) % 100 : numeroSorte; } public void adicionarItem(Item item){ this.inventario.addItem(item); } public void perderItem(Item item){ this.inventario.removerItem(item); } public int getXp(){return this.xp;} public Inventario getInventario(){return this.inventario;} public Status getStatus(){return this.status;} public String getName(){return this.name;} public int getVida(){return this.vida;} public DataTerceiraEra getDataNasc(){return this.dataNasc;} }
package net.formula97.andorid.car_kei_bo; import java.math.BigDecimal; import java.util.Calendar; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; /** * @author kazutoshi * DB * * Cursor * Cursor#close() * # Cursor!!.... * */ public class DbManager extends SQLiteOpenHelper { private static final String DATABASE_NAME = "fuel_mileage.db"; private static final int DB_VERSION = 1; private static final String LUB_MASTER = "LUB_MASTER"; private static final String COSTS_MASTER = "COSTS_MASTER"; private static final String CAR_MASTER = "CAR_MASTER"; public DbManager(Context context) { super(context, DATABASE_NAME, null, DB_VERSION); // TODO } /** * CAR_IDLUB_MASTER * @param db SQLiteDatabaseDB * @param carId intCAR_ID * @param amountOfOil long * @param tripMeter double * @param unitPrice double * @param comments String * @param gregolianDay Calendar * @return longinsertrowId-1SQLException */ protected long addMileageById (SQLiteDatabase db, int carId, double amountOfOil, double tripMeter, double unitPrice, String comments, Calendar gregolianDay) { long result = 0; ContentValues value = new ContentValues(); value.put("CAR_ID", carId); // Calendar DateManager dm = new DateManager(); double julianDay = dm.toJulianDay(gregolianDay); value.put("REFUEL_DATE", julianDay); value.put("LUB_AMOUNT", amountOfOil); value.put("UNIT_PRICE", unitPrice); value.put("TRIPMETER", tripMeter); value.put("COMMENTS", comments); db.beginTransaction(); try { // insertOrThrowINSERT result = db.insertOrThrow(LUB_MASTER, null, value); db.setTransactionSuccessful(); } catch (SQLException e) { Log.e(DATABASE_NAME, "Car record insert failed, "); } finally { // INSERTendTransaction() db.endTransaction(); } return result; } /** * * ....(^^;) * @param db SQLiteDatabaseDB * @param carName String * @param isDefaultCar boolean * @param priceUnit String * @param distanceUnit String * @param volumeUnit String * @return longinsertrowId-1SQLException */ protected long addNewCar(SQLiteDatabase db, String carName, boolean isDefaultCar, String priceUnit, String distanceUnit, String volumeUnit) { // insertOrThrow()0 long result = 0; ContentValues value = new ContentValues(); value.put("CAR_NAME", carName); // defaultCartrue10put if (isDefaultCar == true) { value.put("DEFAULT_FLAG", 1); } else { value.put("DEFAULT_FLAG", 0); } value.put("PRICEUNIT", priceUnit); value.put("DISTANCEUNIT", distanceUnit); value.put("VOLUMEUNIT", volumeUnit); value.put("FUELMILEAGE_LABEL", distanceUnit + "/" + volumeUnit); value.put("RUNNINGCOST_LABEL", priceUnit + "/" + distanceUnit); db.beginTransaction(); try { // insertOrThrowINSERT result = db.insertOrThrow(CAR_MASTER, null, value); db.setTransactionSuccessful(); } catch (SQLException e) { Log.e(DATABASE_NAME, "Car record insert failed, "); } finally { // INSERTendTransaction() db.endTransaction(); } return result; } /** * * @param db SQLiteDatabaseDB * @param carId intcarId * @return intUpdate */ protected int changeDefaultCar(SQLiteDatabase db, int carId) { ContentValues cv = new ContentValues(); String where = "CAR_ID = ?"; String[] args = {String.valueOf(carId)}; int result; db.beginTransaction(); try { cv.put("DEFAULT_FLAG", 0); result = db.update(CAR_MASTER, cv, null, null); // carId cv.clear(); cv.put("DEFAULT_FLAG", 1); result = db.update(CAR_MASTER, cv, where, args); db.setTransactionSuccessful(); } finally { // setTransactionSuccessful() // endTransaction() db.endTransaction(); } return result; } /** * * @param db SQLiteDatabaseDB * @return intUpdate */ protected int clearAllDefaultFlags(SQLiteDatabase db) { ContentValues cv = new ContentValues(); int result; db.beginTransaction(); try { cv.put("DEFAULT_FLAG", 0); result = db.update(CAR_MASTER, cv, null, null); db.setTransactionSuccessful(); } finally { // setTransactionSuccessful() // endTransaction() db.endTransaction(); } return result; } /** * CAR_ID * @param db SQLiteDatabaseDB * @param carId intCAR_ID * @return int */ protected int deleteCarById(SQLiteDatabase db, int carId) { int result; // delete String table = CAR_MASTER; String where = "CAR_ID = ?"; String[] args = {String.valueOf(carId)}; result = db.delete(table, where, args); return result; } /** * CAR_ID * @param db SQLiteDatabaseDB * @param carId intCAR_ID * @return int */ protected int deleteCostsByCarId(SQLiteDatabase db, int carId) { int result; // delete String table = COSTS_MASTER; String where = "CAR_ID = ?"; String[] args = {String.valueOf(carId)}; result = db.delete(table, where, args); return result; } /** * CAR_ID * @param db SQLiteDatabaseDB * @param carId intCAR_ID * @return int */ protected int deleteLubsByCarId(SQLiteDatabase db, int carId) { int result; // delete String table = LUB_MASTER; String where = "CAR_ID = ?"; String[] args = {String.valueOf(carId)}; result = db.delete(table, where, args); return result; } /** * CAR_IDCAR_NAME * @param db SQLiteDatabaseDB * @param carId intcarId * @return StringcarId */ protected String findCarNameById(SQLiteDatabase db, int carId) { String sRet; Cursor q; String[] columns = {"CAR_NAME"}; String where = "CAR_ID = ?"; // CAR_IDintquery()String[]valueOf()String String[] args = {String.valueOf(carId)}; q = db.query(CAR_MASTER, columns, where, args, null, null, null); q.moveToFirst(); sRet = q.getString(0); q.close(); return sRet; } /** * CAR_ID * @param db SQLiteDatabaseDB * @param carName String * @return intcarId */ protected int getCarId(SQLiteDatabase db, String carName) { int iRet; Cursor q; String[] columns = {"CAR_ID"}; String where = "CAR_NAME = ?"; String[] args = {carName}; q = db.query(CAR_MASTER, columns, where, args, null, null, null); q.moveToFirst(); iRet = q.getInt(0); q.close(); return iRet; } /** * * @param db SQLiteDatabaseDB * @return CursorCursorCursor#close() */ protected Cursor getCarList(SQLiteDatabase db) { Cursor q; String[] columns = {"CAR_ID AS _id", "CAR_NAME", "CURRENT_FUEL_MILEAGE", "FUELMILEAGE_LABEL", "CURRENT_RUNNING_COST", "RUNNINGCOST_LABEL"}; //String where = "CAR_ID = ?"; //String[] args = {String.valueOf(1)}; //String groupBy = "" //String having = "" String orderBy = "CAR_ID"; q = db.query(CAR_MASTER, columns, null, null, null, null, orderBy); q.moveToFirst(); return q; } /** * CAR_ID * @param db SQLiteDatabase * @param carId * @return */ protected String getCarNameById (SQLiteDatabase db, int carId) { String sRet; Cursor q; String[] columns = {"CAR_NAME"}; String where = "CAR_ID = ?"; // DEFAULT_FLAG=1query()String[]valueOf()String String[] args = {String.valueOf(carId)}; q = db.query(CAR_MASTER, columns, where, args, null, null, null); q.moveToFirst(); sRet = q.getString(0); Log.i(CAR_MASTER, "Found specified car : " + sRet + " , related to CAR_ID : " + String.valueOf(carId)); q.close(); return sRet; } /** * * @param db SQLiteDatabaseDB * @return CursorCursorCursor#close() */ protected Cursor getCarNameList(SQLiteDatabase db) { Cursor q; String[] columns = {"CAR_ID AS _id", "CAR_NAME"}; //String where = "CAR_ID = ?"; //String[] args = {String.valueOf(1)}; //String groupBy = "" //String having = "" String orderBy = "CAR_ID"; q = db.query(CAR_MASTER, columns, null, null, null, null, orderBy); q.moveToFirst(); return q; } /** * CAR_ID * @param db SQLiteDatabaseDB * @return intcarId */ protected int getDefaultCarId(SQLiteDatabase db) { int iRet; Cursor q; String[] columns = {"CAR_ID"}; String where = "DEFAULT_FLAG = ?"; // DEFAULT_FLAG=1query()String[]valueOf()String String[] args = {String.valueOf(1)}; q = db.query(CAR_MASTER, columns, where, args, null, null, null); q.moveToFirst(); iRet = q.getInt(0); q.close(); return iRet; } /** * CAR_NAME * @param db SQLiteDatabaseDB * @return String */ protected String getDefaultCarName(SQLiteDatabase db) { String sRet; Cursor q; String[] columns = {"CAR_NAME"}; String where = "DEFAULT_FLAG = ?"; // DEFAULT_FLAG=1query()String[]valueOf()String String[] args = {String.valueOf(1)}; q = db.query(CAR_MASTER, columns, where, args, null, null, null); q.moveToFirst(); sRet = q.getString(0); Log.i(CAR_MASTER, "Found default car : " + sRet); q.close(); return sRet; } /** * CAR_ID * @param db SQLiteDatabaseDB * @param carId intCAR_ID * @return String */ protected String getDistanceUnitById(SQLiteDatabase db, int carId) { Cursor q; String[] columns = {"DISTANCEUNIT"}; String where = "CAR_ID = ?"; String[] args = {String.valueOf(carId)}; //String groupBy = "" //String having = "" //String orderBy = "CAR_ID"; q = db.query(CAR_MASTER, columns, where, args, null, null, null); q.moveToFirst(); String unit = q.getString(0); q.close(); return unit; } /** * CAR_ID * @param db SQLiteDatabaseDB * @param carId intCAR_ID * @return String */ protected String getFuelmileageLabelById(SQLiteDatabase db, int carId) { Cursor q; String[] columns = {"FUELMILEAGE_LABEL"}; String where = "CAR_ID = ?"; String[] args = {String.valueOf(carId)}; //String groupBy = "" //String having = "" //String orderBy = "CAR_ID"; q = db.query(CAR_MASTER, columns, where, args, null, null, null); q.moveToFirst(); String unit = q.getString(0); q.close(); return unit; } /** * CAR_ID * @param db SQLiteDatabaseDB * @param carId intCAR_ID * @return String */ protected String getPriceUnitById(SQLiteDatabase db, int carId) { Cursor q; String[] columns = {"PRICEUNIT"}; String where = "CAR_ID = ?"; String[] args = {String.valueOf(carId)}; //String groupBy = "" //String having = "" //String orderBy = "CAR_ID"; q = db.query(CAR_MASTER, columns, where, args, null, null, null); q.moveToFirst(); String unit = q.getString(0); q.close(); return unit; } /** * CAR_ID * @param db SQLiteDatabaseDB * @param carId intCAR_ID * @return String */ protected String getRunningcostLabelById(SQLiteDatabase db, int carId) { Cursor q; String[] columns = {"RUNNINGCOST_LABEL"}; String where = "CAR_ID = ?"; String[] args = {String.valueOf(carId)}; //String groupBy = "" //String having = "" //String orderBy = "CAR_ID"; q = db.query(CAR_MASTER, columns, where, args, null, null, null); q.moveToFirst(); String unit = q.getString(0); q.close(); return unit; } /** * CAR_ID * @param db SQLiteDatabaseDB * @param carId intCAR_ID * @return String */ protected String getVolumeUnitById(SQLiteDatabase db, int carId) { Cursor q; String[] columns = {"VOLUMEUNIT"}; String where = "CAR_ID = ?"; String[] args = {String.valueOf(carId)}; //String groupBy = "" //String having = "" //String orderBy = "CAR_ID"; q = db.query(CAR_MASTER, columns, where, args, null, null, null); q.moveToFirst(); String unit = q.getString(0); q.close(); return unit; } /** * CAR_MASTER * (^^; * @param db SQLiteDatabaseDB * @return booleantruefalse */ protected boolean hasCarRecords(SQLiteDatabase db) { // getCount() int iRet; Cursor q; q = db.query(CAR_MASTER, null, null, null, null, null, null); q.moveToFirst(); iRet = q.getCount(); q.close(); if (iRet == 0) { return false; } else { return true; } } /** * COSTS_MASTER * (^^; * @param db SQLiteDatabaseDB * @return booleantruefalse */ protected boolean hasCostsRecords(SQLiteDatabase db) { // getCount() int iRet; Cursor q; q = db.query(COSTS_MASTER, null, null, null, null, null, null); q.moveToFirst(); iRet = q.getCount(); q.close(); if (iRet == 0) { return false; } else { return true; } } /** * LUB_MASTER * (^^; * @param db SQLiteDatabaseDB * @return booleantruefalse */ protected boolean hasLubRecords(SQLiteDatabase db) { // getCount() int iRet; Cursor q; q = db.query(LUB_MASTER, null, null, null, null, null, null); q.moveToFirst(); iRet = q.getCount(); q.close(); if (iRet == 0) { return false; } else { return true; } } protected boolean hasLubRecords(SQLiteDatabase db, int carId) { boolean ret = false; Cursor q; // SQL String selection = "CAR_ID = ?"; String[] selectionArgs = {String.valueOf(carId)}; String groupBy = null; String having = null; String orderBy = null; String[] columns = null; q = db.query(LUB_MASTER, columns, selection, selectionArgs, groupBy, having, orderBy); q.moveToFirst(); if (q.getCount() > 0) { ret = true; } q.close(); return ret; } /** * * * @param db SQLiteDatabaseDB * @return booleantruefalse */ protected boolean isExistDefaultCarFlag(SQLiteDatabase db) { Cursor q; //String[] columns = {"DEFAULT_FLAG"}; String where = "DEFAULT_FLAG = ?"; String[] args = {"1"}; q = db.query(CAR_MASTER, null, where, args, null, null, null); q.moveToFirst(); int defaultFlag = q.getCount(); q.close(); if (defaultFlag == 0) { return false; } else { return true; } } /** * * * @param db SQLiteDatabaseDB * @param carId intcarId * @return booleantruefalse */ protected boolean isExistDefaultCarFlag(SQLiteDatabase db, int carId) { Cursor q; String[] columns = {"DEFAULT_FLAG"}; String where = "CAR_ID = ?"; // CAR_IDintquery()String[]valueOf()String String[] args = {String.valueOf(carId)}; q = db.query(CAR_MASTER, columns, where, args, null, null, null); q.moveToFirst(); int defaultFlag = q.getInt(0); q.close(); if (defaultFlag == 0) { return false; } else { return true; } } /** * * * @param db SQLiteDatabaseDB * @param carName String * @return booleantruefalse */ protected boolean isExistSameNameCar(SQLiteDatabase db, String carName) { Cursor q; String[] columns = {"CAR_NAME"}; String where = "CAR_NAME = ?"; String[] args = {carName}; q = db.query(CAR_MASTER, columns, where, args, null, null, null); q.moveToFirst(); int count = q.getCount(); q.close(); // 0falsetrue if (count == 0) { return false; } else { return true; } } /** * DBDDL * @see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase) * @param db SQLiteDatabaseDB */ @Override public void onCreate(SQLiteDatabase db) { String create_lub_master; String create_costs_master; String create_car_master; // DDL // LUB_MASTER create_lub_master = "CREATE TABLE IF NOT EXISTS LUB_MASTER " + "(RECORD_ID INTEGER PRIMARY KEY AUTOINCREMENT, " + "REFUEL_DATE REAL, " + "CAR_ID INTEGER, " + "LUB_AMOUNT REAL DEFAULT 0, " + "UNIT_PRICE REAL DEFAULT 0, " + "TRIPMETER REAL DEFAULT 0, " + "COMMENTS TEXT);"; // COSTS_MASTER create_costs_master = "CREATE TABLE IF NOT EXISTS COSTS_MASTER " + "(RECORD_ID INTEGER PRIMARY KEY AUTOINCREMENT, " + "CAR_ID INTEGER, " + "REFUEL_DATE REAL, " + "RUNNING_COST REAL DEFAULT 0);"; // CAR_MASTER create_car_master = "CREATE TABLE IF NOT EXISTS CAR_MASTER " + "(CAR_ID INTEGER PRIMARY KEY AUTOINCREMENT, " + "CAR_NAME TEXT, " + "DEFAULT_FLAG INTEGER DEFAULT 0, " + "CURRENT_FUEL_MILEAGE REAL DEFAULT 0, " + "CURRENT_RUNNING_COST REAL DEFAULT 0, " + "PRICEUNIT TEXT, " + "DISTANCEUNIT TEXT, " + "VOLUMEUNIT TEXT, " + "FUELMILEAGE_LABEL TEXT, " + "RUNNINGCOST_LABEL TEXT);"; // DDLexecSQL db.execSQL(create_lub_master); db.execSQL(create_costs_master); db.execSQL(create_car_master); } /** * DBDB * * * * @see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int) * @param db SQLiteDatabaseDB * @param oldVersion intDB * @param newVersion intDB */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO // ALTER TABLE Log.w("Car-Kei-Bo", "Updating database, which will destroy all old data.(for testing)"); db.execSQL("DROP TABLE IF EXISTS LUB_MASTER;"); db.execSQL("DROP TABLE IF EXISTS COSTS_MASTER;"); db.execSQL("DROP TABLE IF EXISTS CAR_MASTER;"); // onCreate() onCreate(db); } /** * * @param db SQLiteDatabaseDB */ protected void reorgDb(SQLiteDatabase db) { db.execSQL("vacuum"); } /** * CAR_ID * @param db SQLiteDatabaseDB * @param carId intCAR_ID * @param invertOrder truefalse * @return Cursor */ protected Cursor getRefuelRecordsById(SQLiteDatabase db, int carId, boolean invertOrder) { Cursor q; String order; if (invertOrder) { order = "DESC"; } else { order = ""; } // rawQuerySQL // CursorAdapter_id // RECORD_ID_id q = db.rawQuery("SELECT LUB_MASTER.RECORD_ID as _id, datetime(LUB_MASTER.REFUEL_DATE) as DATE_OF_REFUEL," + " LUB_MASTER.LUB_AMOUNT, CAR_MASTER.VOLUMEUNIT FROM LUB_MASTER, CAR_MASTER" + " WHERE LUB_MASTER.CAR_ID = CAR_MASTER.CAR_ID" + " AND LUB_MASTER.CAR_ID = " + String.valueOf(carId) + " ORDER BY LUB_MASTER.REFUEL_DATE " + order + ";", null); q.moveToFirst(); return q; } /** * COSTS_MASTER * @param carId intCAR_ID * @param db SQLiteDatabaseDB * @param runningCosts * @param gregorianDay * @return */ protected long addRunningCostRecord(SQLiteDatabase db, int carId, double runningCosts, Calendar gregorianDay) { long ret = 0; // Calendar DateManager dmngr = new DateManager(); double julianDay = dmngr.toJulianDay(gregorianDay); ContentValues values = new ContentValues(); values.put("CAR_ID", carId); values.put("REFUEL_DATE", julianDay); values.put("RUNNING_COST", runningCosts); db.beginTransaction(); try { ret = db.insertOrThrow(COSTS_MASTER, null, values); db.setTransactionSuccessful(); } catch (SQLException sqle) { Log.e("addRunningCostRecord", "SQLException occured, update failed"); } catch (Exception e) { Log.e("addRunningCostRecord", "Other Exception occured, update failed"); } finally { db.endTransaction(); } return ret; } /** * CAR_ID * * @param db SQLiteDatabaseDB * @param carId intCAR_ID * @return intUPDATE(1) */ protected int updateCurrentFuelMileageById(SQLiteDatabase db, int carId) { int ret = 0; Cursor qOil, qDst; // SQL String selection = "CAR_ID = ?"; String[] selectionArgs = {String.valueOf(carId)}; String groupBy = null; String having = null; String orderBy = null; String[] clmsOil = {"sum(LUB_AMOUNT)"}; qOil = db.query(LUB_MASTER, clmsOil, selection, selectionArgs, groupBy, having, orderBy); qOil.moveToFirst(); double totalOil = qOil.getDouble(0); qOil.close(); String[] clmsDst = {"sum(TRIPMETER)"}; qDst = db.query(LUB_MASTER, clmsDst, selection, selectionArgs, groupBy, having, orderBy); qDst.moveToFirst(); double totalDst = qDst.getDouble(0); qDst.close(); double cur = totalDst / totalOil; BigDecimal bd = new BigDecimal(cur); double current = bd.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); // CAR_MASTER.CURRENT_FUEL_MILEAGE ContentValues values = new ContentValues(); values.put("CURRENT_FUEL_MILEAGE", current); String whereClause = "CAR_ID = ?"; String[] whereArgs = {String.valueOf(carId)}; db.beginTransaction(); try { ret = db.update(CAR_MASTER, values, whereClause, whereArgs); db.setTransactionSuccessful(); } catch (SQLException sqle) { Log.e("updateCurrentFuelMileageById", "SQLException occured, update failed"); } catch (Exception e) { Log.e("updateCurrentFuelMileageById", "Other Exception occured, update failed"); } finally { db.endTransaction(); } return ret; } /** * * * @param db SQLiteDatabaseDB * @param carId intCAR_ID * @return intUPDATE */ protected int updateCurrentRunningCostById(SQLiteDatabase db, int carId) { int ret = 0; Cursor qOil, qDst, qPrice; // SQL String selection = "CAR_ID = ?"; String[] selectionArgs = {String.valueOf(carId)}; String groupBy = null; String having = null; String orderBy = null; String[] clmsPrice = {"avg(UNIT_PRICE)"}; qPrice = db.query(LUB_MASTER, clmsPrice, selection, selectionArgs, groupBy, having, orderBy); qPrice.moveToFirst(); double avgPrice = qPrice.getDouble(0); qPrice.close(); String[] clmsOil = {"sum(LUB_AMOUNT)"}; qOil = db.query(LUB_MASTER, clmsOil, selection, selectionArgs, groupBy, having, orderBy); qOil.moveToFirst(); double totalOil = qOil.getDouble(0); qOil.close(); String[] clmsDst = {"sum(TRIPMETER)"}; qDst = db.query(LUB_MASTER, clmsDst, selection, selectionArgs, groupBy, having, orderBy); qDst.moveToFirst(); double totalDst = qDst.getDouble(0); qDst.close(); double cur = totalOil * avgPrice / totalDst; BigDecimal bd = new BigDecimal(cur); double current = bd.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); // CAR_MASTER.CURRENT_RUNNING_COST ContentValues values = new ContentValues(); values.put("CURRENT_RUNNING_COST", current); String whereClause = "CAR_ID = ?"; String[] whereArgs = {String.valueOf(carId)}; db.beginTransaction(); try { ret = db.update(CAR_MASTER, values, whereClause, whereArgs); db.setTransactionSuccessful(); } catch (SQLException sqle) { Log.e("updateCurrentRunningCostById", "SQLException occured, update failed"); } catch (Exception e) { Log.e("updateCurrentRunningCostById", "Other Exception occured, update failed"); } finally { db.endTransaction(); } return ret; } /** * * @param db SQLiteDatabaseDB * @param carId intCAR_ID * @return double */ protected double getCurrentMileageById (SQLiteDatabase db, int carId) { double ret = 0; Cursor q; // SQL String selection = "CAR_ID = ?"; String[] selectionArgs = {String.valueOf(carId)}; String groupBy = null; String having = null; String orderBy = null; String[] columns = {"CURRENT_FUEL_MILEAGE"}; q = db.query(CAR_MASTER, columns, selection, selectionArgs, groupBy, having, orderBy); q.moveToFirst(); ret = q.getDouble(0); q.close(); return ret; } /** * * @param db SQLiteDatabaseDB * @param carId intCAR_ID * @return double */ protected double getCurrentRunningCostById (SQLiteDatabase db, int carId) { double ret = 0; Cursor q; // SQL String selection = "CAR_ID = ?"; String[] selectionArgs = {String.valueOf(carId)}; String groupBy = null; String having = null; String orderBy = null; String[] columns = {"CURRENT_RUNNING_COST"}; q = db.query(CAR_MASTER, columns, selection, selectionArgs, groupBy, having, orderBy); q.moveToFirst(); ret = q.getDouble(0); q.close(); return ret; } /** * * @param db SQLiteDatabaseDB * @param carId intCAR_ID * @param rowId int * @return Cursor */ protected Cursor getRefuelRecordById (SQLiteDatabase db, int carId, int rowId) { Cursor ret; // rawQuery String sql = "SELECT * FROM LUB_MASTER " + "WHERE CAR_ID = " + String.valueOf(carId) + " " + "AND RECORD_ID = " + String.valueOf(rowId) + ";"; ret = db.rawQuery(sql, null); ret.moveToFirst(); return ret; } /** * * @param db SQLiteDatabaseDB * @param carId intCAR_ID * @param startJd double * @param endJd double * @return float */ protected float getSubtotalOfRefuelById(SQLiteDatabase db, int carId, double startJd, double endJd) { float ret = 0; Cursor q; // SQL String sql = "SELECT SUM(LUB_AMOUNT) FROM LUB_MASTER " + "WHERE CAR_ID = " + String.valueOf(carId) + " " + "AND REFUEL_DATE BETWEEN " + String.valueOf(startJd) + " AND " + String.valueOf(endJd) + ";"; q = db.rawQuery(sql, null); q.moveToFirst(); // Cursor ret = q.getFloat(0); q.close(); return ret; } /** * * @param db SQLiteDatabaseDB * @param carId SQLiteDatabaseDB * @return float */ protected float getTotalOfRefuelById(SQLiteDatabase db, int carId) { float ret = 0; Cursor q; // SQL String selection = "CAR_ID = ?"; String[] selectionArgs = {String.valueOf(carId)}; String groupBy = null; String having = null; String orderBy = null; String[] columns = {"SUM(LUB_AMOUNT)"}; q = db.query(LUB_MASTER, columns, selection, selectionArgs, groupBy, having, orderBy); q.moveToFirst(); // Cursor ret = q.getFloat(0); q.close(); return ret; } /** * 0 * @param db SQLiteDatabaseDB * @param carId intCAR_ID * @param startJd double * @param endJd double * @return float */ protected float getSubtotalOfMileageById(SQLiteDatabase db, int carId, double startJd, double endJd) { float ret = 0; Cursor q; // SQL String sql = "SELECT SUM(LUB_AMOUNT), SUM(TRIPMETER), AVG(UNIT_PRICE) FROM LUB_MASTER " + "WHERE CAR_ID = " + String.valueOf(carId) + " " + "AND TRIPMETER > 0 " + "AND REFUEL_DATE BETWEEN " + String.valueOf(startJd) + " AND " + String.valueOf(endJd) + ";"; q = db.rawQuery(sql, null); q.moveToFirst(); // CursorCursor float lubAmount = q.getFloat(0); float trip = q.getFloat(1); float price = q.getFloat(2); q.close(); ret = trip / lubAmount * price; return ret; } /** * 0 * @param db SQLiteDatabaseDB * @param carId intCAR_ID * @param startJd double * @param endJd double * @return float */ protected float getSubtotalOfRunningCostsById(SQLiteDatabase db, int carId, double startJd, double endJd) { float ret = 0; Cursor q; // SQL String sql = "SELECT SUM(LUB_AMOUNT), SUM(TRIPMETER), AVG(UNIT_PRICE) FROM LUB_MASTER " + "WHERE CAR_ID = " + String.valueOf(carId) + " " + "AND TRIPMETER > 0 " + "AND REFUEL_DATE BETWEEN " + String.valueOf(startJd) + " AND " + String.valueOf(endJd) + ";"; q = db.rawQuery(sql, null); q.moveToFirst(); // CursorCursor float lubAmount = q.getFloat(0); float trip = q.getFloat(1); float price = q.getFloat(2); q.close(); ret = lubAmount * price / trip; return ret; } /** * * @param db SQLiteDatabaseDB * @param carId intCAR_ID * @return */ protected double getOldestRefuelDateById(SQLiteDatabase db, int carId) { double ret = 0; Cursor q; // SQL String selection = "CAR_ID = ?"; String[] selectionArgs = {String.valueOf(carId)}; String groupBy = null; String having = null; String orderBy = null; String[] columns = {"MIN(REFUEL_DATE)"}; q = db.query(LUB_MASTER, columns, selection, selectionArgs, groupBy, having, orderBy); q.moveToFirst(); ret = q.getDouble(0); q.close(); return ret; } /** * * @param db SQLiteDatabaseDB * @param carId intCAR_ID * @return */ protected double getLatestRefuelDateById(SQLiteDatabase db, int carId) { double ret = 0; Cursor q; // SQL String selection = "CAR_ID = ?"; String[] selectionArgs = {String.valueOf(carId)}; String groupBy = null; String having = null; String orderBy = null; String[] columns = {"MAX(REFUEL_DATE)"}; q = db.query(LUB_MASTER, columns, selection, selectionArgs, groupBy, having, orderBy); q.moveToFirst(); ret = q.getDouble(0); q.close(); return ret; } protected int updateRefuelRecordById(SQLiteDatabase db, int carId ) { int ret = 0; return ret; } }
package net.qldarch.search.update; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.apache.lucene.index.IndexWriter; import lombok.AllArgsConstructor; import net.qldarch.archobj.ArchObj; import net.qldarch.interview.Interview; import net.qldarch.interview.Utterance; @AllArgsConstructor public class UpdateArchObjJob extends CancelableIndexUpdateJob { private ArchObj archobj; @Override public void run(IndexWriter writer) { if(archobj != null) { try { if(!isCanceled()) { new DeleteDocumentJob(archobj.getId().toString(), archobj.getType().toString()).run(writer); Map<String, Object> m = archobj.asMap(); m.put("category", "archobj"); if(archobj instanceof Interview) { final Set<Utterance> transcript = ((Interview)archobj).getTranscript(); if(transcript != null) { final String text = transcript.stream().map( Utterance::getTranscript).collect(Collectors.joining(" ")); m.put("all", text); } } writer.addDocument(DocumentUtils.createDocument(m)); } } catch(Exception e) { throw new RuntimeException("failed to update index with archive object "+archobj.getId(), e); } } } }
package openblocks.common.tileentity; import java.util.List; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.MathHelper; import net.minecraft.util.Vec3; import net.minecraftforge.common.ForgeDirection; import openblocks.common.api.IAwareTile; import openblocks.sync.ISyncableObject; import openblocks.sync.SyncableFloat; public class TileEntityFan extends NetworkedTileEntity implements IAwareTile { private SyncableFloat angle = new SyncableFloat(0.0f); public enum Keys { angle } public TileEntityFan() { addSyncedObject(Keys.angle, angle); } @Override public void updateEntity() { @SuppressWarnings("unchecked") List<Entity> entities = worldObj.getEntitiesWithinAABB(Entity.class, getEntitySearchBoundingBox()); Vec3 blockPos = getBlockPosition(); for (Entity entity : entities) { if (entity.isSneaking()) { continue; } Vec3 entityPos = getEntityPosition(entity); Vec3 basePos = getConeBaseCenter(); double dX = entityPos.xCoord - blockPos.xCoord; double dY = entityPos.yCoord - blockPos.yCoord; double dZ = entityPos.zCoord - blockPos.zCoord; double dist = MathHelper.sqrt_double(dX * dX + dZ * dZ); if (isLyingInCone(entityPos, blockPos, basePos, 1.7f) || dist < 1.2) { double yaw = Math.toRadians(getAngle()); double f1 = MathHelper.cos((float)-yaw); double f2 = MathHelper.sin((float)-yaw); Vec3 directionVec = worldObj.getWorldVec3Pool().getVecFromPool(f2, 0, f1); double force = (1.0 - (dist / 10.0)) * 1.4; entity.motionX -= force * directionVec.xCoord * 0.05; entity.motionZ -= force * directionVec.zCoord * 0.05; } } } public Vec3 getEntityPosition(Entity entity) { return worldObj.getWorldVec3Pool().getVecFromPool(entity.posX, entity.posY, entity.posZ); } public Vec3 getConeBaseCenter() { double angle = Math.toRadians(getAngle()-90); return worldObj.getWorldVec3Pool().getVecFromPool(xCoord + 0.5 + (Math.cos(angle) * 10), yCoord + 0.5, zCoord + 0.5 + (Math.sin(angle) * 10)); } public Vec3 getBlockPosition() { return worldObj.getWorldVec3Pool().getVecFromPool(xCoord + 0.5, yCoord + 0.5, zCoord + 0.5); } public AxisAlignedBB getEntitySearchBoundingBox() { AxisAlignedBB boundingBox = AxisAlignedBB.getAABBPool().getAABB(xCoord, yCoord - 4, zCoord, xCoord + 1, yCoord + 5, zCoord + 1); return boundingBox.expand(10.0, 10.0, 10.0); } public boolean isLyingInCone(Vec3 point, Vec3 t, Vec3 b, float aperture) { float halfAperture = aperture / 2.f; Vec3 apexToXVect = dif(t, point); Vec3 axisVect = dif(t, b); boolean isInInfiniteCone = apexToXVect.dotProduct(axisVect) / apexToXVect.lengthVector() / axisVect.lengthVector() > Math.cos(halfAperture); if (!isInInfiniteCone) return false; boolean isUnderRoundCap = apexToXVect.dotProduct(axisVect) / axisVect.lengthVector() < axisVect.lengthVector(); return isUnderRoundCap; } static public Vec3 dif(Vec3 a, Vec3 b) { return Vec3.createVectorHelper( a.xCoord - b.xCoord, a.yCoord - b.yCoord, a.zCoord - b.zCoord ); } @Override public void onBlockBroken() { // TODO Auto-generated method stub } @Override public void onBlockAdded() { // TODO Auto-generated method stub } @Override public boolean onBlockActivated(EntityPlayer player, int side, float hitX, float hitY, float hitZ) { // TODO Auto-generated method stub return false; } @Override public void onNeighbourChanged(int blockId) { // TODO Auto-generated method stub } @Override public void onBlockPlacedBy(EntityPlayer player, ForgeDirection side, ItemStack stack, float hitX, float hitY, float hitZ) { angle.setValue(player.rotationYawHead); sync(); } @Override public boolean onBlockEventReceived(int eventId, int eventParam) { // TODO Auto-generated method stub return false; } @Override public void onSynced(List<ISyncableObject> changes) { // TODO Auto-generated method stub } public float getAngle() { return angle.getValue(); } @Override public void writeToNBT(NBTTagCompound nbt) { super.writeToNBT(nbt); angle.writeToNBT(nbt, "angle"); } @Override public void readFromNBT(NBTTagCompound nbt) { super.readFromNBT(nbt); angle.readFromNBT(nbt, "angle"); } }
package org.anddev.andengine.entity.primitive; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; import org.anddev.andengine.collision.LineCollisionChecker; import org.anddev.andengine.collision.ShapeCollisionChecker; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.entity.shape.GLShape; import org.anddev.andengine.entity.shape.IShape; import org.anddev.andengine.opengl.buffer.BufferObjectManager; import org.anddev.andengine.opengl.util.GLHelper; import org.anddev.andengine.opengl.vertex.LineVertexBuffer; /** * @author Nicolas Gramlich * @since 09:50:36 - 04.04.2010 */ public class Line extends GLShape { // Constants private static final float LINEWIDTH_DEFAULT = 1.0f; // Fields protected float mX2; protected float mY2; private float mLineWidth; private final LineVertexBuffer mLineVertexBuffer; // Constructors public Line(final float pX1, final float pY1, final float pX2, final float pY2) { this(pX1, pY1, pX2, pY2, LINEWIDTH_DEFAULT); } public Line(final float pX1, final float pY1, final float pX2, final float pY2, final float pLineWidth) { super(pX1, pY1); this.mX2 = pX2; this.mY2 = pY2; this.mLineWidth = pLineWidth; this.mLineVertexBuffer = new LineVertexBuffer(GL11.GL_STATIC_DRAW); BufferObjectManager.getActiveInstance().loadBufferObject(this.mLineVertexBuffer); this.updateVertexBuffer(); final float width = this.getWidth(); final float height = this.getHeight(); this.mRotationCenterX = width * 0.5f; this.mRotationCenterY = height * 0.5f; this.mScaleCenterX = this.mRotationCenterX; this.mScaleCenterY = this.mRotationCenterY; } // Getter & Setter /** * Instead use {@link Line#getX1()} or {@link Line#getX2()}. */ @Override @Deprecated public float getX() { return super.getX(); } /** * Instead use {@link Line#getY1()} or {@link Line#getY2()}. */ @Override @Deprecated public float getY() { return super.getY(); } public float getX1() { return super.getX(); } public float getY1() { return super.getY(); } public float getX2() { return this.mX2; } public float getY2() { return this.mY2; } public float getLineWidth() { return this.mLineWidth; } public void setLineWidth(final float pLineWidth) { this.mLineWidth = pLineWidth; } @Override public float getBaseHeight() { return this.mY2 - this.mY; } @Override public float getBaseWidth() { return this.mX2 - this.mX; } @Override public float getHeight() { return this.mY2 - this.mY; } @Override public float getWidth() { return this.mX2 - this.mX; } /** * Instead use {@link Line#setPosition(float, float, float, float)}. */ @Deprecated @Override public void setPosition(final float pX, final float pY) { final float dX = this.mX - pX; final float dY = this.mY - pY; super.setPosition(pX, pY); this.mX2 += dX; this.mY2 += dY; } public void setPosition(final float pX1, final float pY1, final float pX2, final float pY2) { this.mX2 = pX2; this.mY2 = pY2; super.setPosition(pX1, pY1); this.updateVertexBuffer(); } // Methods for/from SuperClass/Interfaces @Override protected void onInitDraw(final GL10 pGL) { super.onInitDraw(pGL); GLHelper.disableTextures(pGL); GLHelper.disableTexCoordArray(pGL); GLHelper.lineWidth(pGL, this.mLineWidth); } @Override public LineVertexBuffer getVertexBuffer() { return this.mLineVertexBuffer; } @Override protected void onUpdateVertexBuffer() { this.mLineVertexBuffer.update(0, 0, this.mX2 - this.mX, this.mY2 - this.mY); } @Override protected void drawVertices(final GL10 pGL, final Camera pCamera) { pGL.glDrawArrays(GL10.GL_LINES, 0, LineVertexBuffer.VERTICES_PER_LINE); } @Override public float[] getSceneCenterCoordinates() { return ShapeCollisionChecker.convertLocalToSceneCoordinates(this, (this.mX + this.mX2) * 0.5f, (this.mY + this.mY2) * 0.5f); } @Override @Deprecated public boolean contains(final float pX, final float pY) { return false; } @Override @Deprecated public float[] convertSceneToLocalCoordinates(final float pX, final float pY) { return null; } @Override @Deprecated public float[] convertLocalToSceneCoordinates(final float pX, final float pY) { return null; } @Override public boolean collidesWith(final IShape pOtherShape) { if(pOtherShape instanceof Line) { final Line otherLine = (Line)pOtherShape; return LineCollisionChecker.checkLineCollision(this.mX, this.mY, this.mX2, this.mY2, otherLine.mX, otherLine.mY, otherLine.mX2, otherLine.mY2); } else { return false; } } // Methods // Inner and Anonymous Classes }
package org.appwork.utils.swing.dialog; import java.awt.Color; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.Window; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.IOException; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import org.appwork.utils.ImageProvider.ImageProvider; import org.appwork.utils.formatter.TimeFormatter; import org.appwork.utils.locale.APPWORKUTILS; import org.appwork.utils.logging.Log; import org.appwork.utils.swing.EDTHelper; public abstract class TimerDialog { protected class InternDialog extends JDialog { private static final long serialVersionUID = 1L; public InternDialog() { super(parentFrame, ModalityType.TOOLKIT_MODAL); } @Override public void dispose() { TimerDialog.this.dispose(); super.dispose(); } @Override public Dimension getPreferredSize() { return TimerDialog.this.getPreferredSize(); } public Dimension getRealPreferredSize() { return super.getPreferredSize(); } public void realDispose() { super.dispose(); } } private static final long serialVersionUID = -7551772010164684078L; /** * Timer Thread to count down the {@link #counter} */ protected Thread timer; /** * Current timer value */ protected int counter; /** * Label to display the timervalue */ protected JLabel timerLbl; protected Window parentFrame; private InternDialog dialog; private Dimension preferredSize; public TimerDialog(final Window parentframe) { // super(parentframe, ModalityType.TOOLKIT_MODAL); parentFrame = parentframe; // avoids always On Top BUg if (parentframe != null) { parentframe.setAlwaysOnTop(true); parentframe.setAlwaysOnTop(false); } } /** * interrupts the timer countdown */ public void cancel() { if (timer != null) { timer.interrupt(); timer = null; timerLbl.setEnabled(false); } } protected void dispose() { getDialog().realDispose(); } /** * @return */ protected Color getBackground() { // TODO Auto-generated method stub return getDialog().getBackground(); } protected InternDialog getDialog() { if (dialog == null) { throw new NullPointerException("Call #org.appwork.utils.swing.dialog.AbstractDialog.displayDialog() first"); } return dialog; } /** * override this if you want to set a special height * * @return */ protected int getPreferredHeight() { // TODO Auto-generated method stub return -1; } /** * @return */ public Dimension getPreferredSize() { final Dimension pref = getDialog().getRealPreferredSize(); int w = getPreferredWidth(); int h = getPreferredHeight(); if (w <= 0) { w = pref.width; } if (h <= 0) { h = pref.height; } try { if (Dialog.getInstance().getParentOwner() != null && Dialog.getInstance().getParentOwner().isVisible()) { return new Dimension(Math.min(Dialog.getInstance().getParentOwner().getWidth(), w), Math.min(Dialog.getInstance().getParentOwner().getHeight(), h)); } else { return new Dimension(Math.min((int) (Toolkit.getDefaultToolkit().getScreenSize().width * 0.75), w), Math.min((int) (Toolkit.getDefaultToolkit().getScreenSize().height * 0.75), h)); } } catch (final Throwable e) { return pref; } } /** * overwride this to set a special width * * @return */ protected int getPreferredWidth() { // TODO Auto-generated method stub return -1; } protected void initTimer(final int time) { counter = time; timer = new Thread() { @Override public void run() { try { // sleep while dialog is invisible while (!isVisible()) { try { Thread.sleep(200); } catch (final InterruptedException e) { break; } } int count = counter; while (--count >= 0) { if (!isVisible()) { return; } if (timer == null) { return; } final String left = TimeFormatter.formatSeconds(count, 0); new EDTHelper<Object>() { @Override public Object edtRun() { timerLbl.setText(left); return null; } }.start(); Thread.sleep(1000); if (counter < 0) { return; } if (!isVisible()) { return; } } if (counter < 0) { return; } if (!isInterrupted()) { onTimeout(); } } catch (final InterruptedException e) { return; } } }; timer.start(); } /** * @return */ protected boolean isVisible() { // TODO Auto-generated method stub return getDialog().isVisible(); } protected void layoutDialog() { dialog = new InternDialog(); if (preferredSize != null) { dialog.setPreferredSize(preferredSize); } timerLbl = new JLabel(TimeFormatter.formatSeconds(Dialog.getInstance().getCountdownTime(), 0)); timerLbl.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(final MouseEvent e) { cancel(); timerLbl.removeMouseListener(this); } }); timerLbl.setToolTipText(APPWORKUTILS.TIMERDIALOG_TOOLTIP_TIMERLABEL.s()); try { timerLbl.setIcon(ImageProvider.getImageIcon("cancel", 16, 16, true)); } catch (final IOException e1) { Log.exception(e1); } } protected abstract void onTimeout(); public void pack() { getDialog().pack(); } public void requestFocus() { getDialog().requestFocus(); } protected void setAlwaysOnTop(final boolean b) { getDialog().setAlwaysOnTop(b); } protected void setDefaultCloseOperation(final int doNothingOnClose) { getDialog().setDefaultCloseOperation(doNothingOnClose); } protected void setMinimumSize(final Dimension dimension) { getDialog().setMinimumSize(dimension); } /** * @param dimension */ public void setPreferredSize(final Dimension dimension) { try { getDialog().setPreferredSize(dimension); } catch (final NullPointerException e) { preferredSize = dimension; } } protected void setResizable(final boolean b) { getDialog().setResizable(b); } /** * @param b */ public void setVisible(final boolean b) { getDialog().setVisible(b); } }
package org.biojava.bio.seq.io; import java.util.*; import java.io.*; import org.biojava.utils.*; import org.biojava.bio.*; import org.biojava.bio.symbol.*; import org.biojava.bio.seq.*; import org.biojava.bio.seq.impl.*; /** * Basic SequenceBuilder implementation which accumulates all * notified information. Subclass this to implement specific * Sequence implementations. * * @author Thomas Down * @author David Huen (modified SimpleSequence to make this) * @version 1.2 [newio proposal] */ public abstract class SequenceBuilderBase implements SequenceBuilder { public static Object ERROR_FEATURES_PROPERTY = SequenceBuilderBase.class + "ERROR_FEATURES_PROPERTY"; // State protected String name; protected String uri; protected Annotation annotation; private Set rootFeatures; private List featureStack; protected Sequence seq; { annotation = new SimpleAnnotation(); rootFeatures = new HashSet(); featureStack = new ArrayList(); // slBuilder = new ChunkedSymbolListBuilder(); } // SeqIOListener public void startSequence() { } public void endSequence() { } public void setName(String name) { this.name = name; } public void setURI(String uri) { this.uri = uri; } public abstract void addSymbols(Alphabet alpha, Symbol[] syms, int pos, int len) throws IllegalAlphabetException; /** * Add an annotation-bundle entry to the sequence. If the annotation key * isn't currently defined, the value is added directly. Otherwise: * * <ul> * <li> If the current value implements the Collection interface, * the new value is added to that collection. </li> * <li> Otherwise, the current value is replaced by a List object * containing the old value then the new value in that order. </li> * </ul> */ public void addSequenceProperty(Object key, Object value) { addProperty(annotation, key, value); } public void startFeature(Feature.Template templ) { TemplateWithChildren t2 = new TemplateWithChildren(); t2.template = templ; if(templ.annotation == Annotation.EMPTY_ANNOTATION) { templ.annotation = new SmallAnnotation(); } int stackSize = featureStack.size(); if (stackSize == 0) { rootFeatures.add(t2); } else { TemplateWithChildren parent = (TemplateWithChildren) featureStack.get(stackSize - 1); if (parent.children == null) parent.children = new HashSet(); parent.children.add(t2); } featureStack.add(t2); } /** * Add an annotation-bundle entry to the feature. If the annotation key * isn't currently defined, the value is added directly. Otherwise: * * <ul> * <li> If the current value implements the Collection interface, * the new value is added to that collection. </li> * <li> Otherwise, the current value is replaced by a List object * containing the old value then the new value in that order. </li> * </ul> */ public void addFeatureProperty(Object key, Object value) throws ParseException { try { int stackSize = featureStack.size(); TemplateWithChildren top = (TemplateWithChildren) featureStack.get(stackSize - 1); addProperty(top.template.annotation, key, value); } catch (IndexOutOfBoundsException ioobe) { throw new ParseException( ioobe, "Attempted to add annotation to a feature when no startFeature " + "had been invoked" ); } } public void endFeature() { if (featureStack.size() == 0) throw new BioError("Assertion failed: Not within a feature"); featureStack.remove(featureStack.size() - 1); } public Sequence makeSequence() { // SymbolList symbols = slBuilder.makeSymbolList(); // Sequence seq = new SimpleSequence(symbols, uri, name, annotation); try { for (Iterator i = rootFeatures.iterator(); i.hasNext(); ) { TemplateWithChildren twc = (TemplateWithChildren) i.next(); try { Feature f = seq.createFeature(twc.template); if (twc.children != null) { makeChildFeatures(f, twc.children); } } catch (Exception e) { // fixme: we should do something more sensible with this error e.printStackTrace(); Set errFeatures; Annotation ann = seq.getAnnotation(); if(ann.containsProperty(ERROR_FEATURES_PROPERTY)) { errFeatures = (Set) ann.getProperty(ERROR_FEATURES_PROPERTY); } else { ann.setProperty( ERROR_FEATURES_PROPERTY, errFeatures = new HashSet() ); } errFeatures.add(twc); } } } catch (Exception ex) { throw new BioError(ex, "Couldn't create feature"); } return seq; } private void makeChildFeatures(Feature parent, Set children) throws Exception { for (Iterator i = children.iterator(); i.hasNext(); ) { TemplateWithChildren twc = (TemplateWithChildren) i.next(); Feature f = parent.createFeature(twc.template); if (twc.children != null) { makeChildFeatures(f, twc.children); } } } protected void addProperty(Annotation ann, Object key, Object value) { if (value == null) return; Object oldValue = null; Object newValue = value; if(ann.containsProperty(key)) { oldValue = ann.getProperty(key); } if (oldValue != null) { if (oldValue instanceof Collection) { ((Collection) oldValue).add(newValue); newValue = oldValue; } else { List nvList = new ArrayList(); nvList.add(oldValue); nvList.add(newValue); newValue = nvList; } } try { ann.setProperty(key, newValue); } catch (ChangeVetoException ex) { throw new BioError(ex, "Annotation should be modifiable"); } } private static class TemplateWithChildren { Feature.Template template; Set children; } }
package org.concord.data.state; import java.awt.BorderLayout; import java.awt.Color; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import org.concord.data.ui.DataColumnDescription; import org.concord.data.ui.DataTableModel; import org.concord.data.ui.DataTablePanel; import org.concord.framework.data.stream.DataStore; import org.concord.framework.otrunk.OTControllerService; import org.concord.framework.otrunk.OTObject; import org.concord.framework.otrunk.OTObjectList; import org.concord.framework.otrunk.view.AbstractOTJComponentView; /** * * @author sfentress * */ public class OTDataTableEditView extends AbstractOTJComponentView { protected OTDataTable otTable; protected OTControllerService controllerService; private DataStore dataStore; private OTDataStore otDataStore; private DataTablePanel table; private JPanel tableWrapper; private JPanel titlesPanel; /** * @see org.concord.framework.otrunk.view.OTJComponentView#getComponent(org.concord.framework.otrunk.OTObject) */ public JComponent getComponent(OTObject otObject) { otTable = (OTDataTable)otObject; controllerService = createControllerService(); table = new DataTablePanel(); otDataStore = otTable.getDataStore(); dataStore = (DataStore) controllerService.getRealObject(otDataStore); table.getTableModel().addDataStore(dataStore); //can always add values table.getTableModel().setShowLastRowForAddingNew(true); updateOTColumns(table.getTableModel(), dataStore, otTable.getColumns()); tableWrapper = new JPanel(new BorderLayout()); tableWrapper.add(table, BorderLayout.CENTER); JPanel optionsPanel = new JPanel(new FlowLayout(FlowLayout.LEADING)); JLabel numColumnsLabel = new JLabel("Number of columns: "); final JTextField numColumnsField = new JTextField(""+dataStore.getTotalNumChannels()); JButton updateButton = new JButton("Update"); updateButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { System.out.println("action"); int numColumns = Integer.parseInt(numColumnsField.getText()); otDataStore.setNumberChannels(numColumns); update(); }}); JLabel warningLabel = new JLabel("Warning: this will remove existing data"); optionsPanel.add(numColumnsLabel); optionsPanel.add(numColumnsField); optionsPanel.add(updateButton); optionsPanel.add(warningLabel); JPanel lockedPanel = new JPanel(); for (int i = 0; i < otDataStore.getNumberChannels(); i++) { final int columnNumber = i; final JCheckBox lockedBox = new JCheckBox(); if (table.getTableModel().getDataColumn(dataStore, columnNumber).isLocked()){ lockedBox.setSelected(true); } lockedBox.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent arg0) { OTDataChannelDescription otChannelDesc = (OTDataChannelDescription) otDataStore.getChannelDescriptions().get(columnNumber); if (lockedBox.isSelected()){ otChannelDesc.setLocked(true); // set locked directly on the tablemodel here, so authors have immediate feedback // without reloading the model table.getTableModel().getDataColumn(dataStore, columnNumber).setLocked(true); } else { otChannelDesc.setLocked(false); table.getTableModel().getDataColumn(dataStore, columnNumber).setLocked(false); } }}); lockedPanel.add(lockedBox); lockedPanel.add(Box.createGlue()); } JPanel bottomPanel = new JPanel(); bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.Y_AXIS)); bottomPanel.add(lockedPanel); bottomPanel.add(optionsPanel); tableWrapper.add(bottomPanel, BorderLayout.SOUTH); createTitles(); return tableWrapper; } private void update(){ table.getTableModel().removeDataStore(dataStore); otDataStore = otTable.getDataStore(); dataStore = (DataStore) controllerService.getRealObject(otDataStore); table.getTableModel().addDataStore(dataStore); //can always add values table.getTableModel().setShowLastRowForAddingNew(true); updateOTColumns(table.getTableModel(), dataStore, otTable.getColumns()); tableWrapper.remove(titlesPanel); createTitles(); } private void createTitles(){ titlesPanel = new JPanel(); for (int i = 0; i < dataStore.getTotalNumChannels(); i++) { String title = ""; if (dataStore.getDataChannelDescription(i) != null){ title = dataStore.getDataChannelDescription(i).getName(); } final JTextField titleField = new JTextField(title); titleField.setColumns(4); final int index = i; titleField.addFocusListener(new FocusListener(){ public void focusGained(FocusEvent arg0) { // TODO Auto-generated method stub } public void focusLost(FocusEvent arg0) { otDataStore = otTable.getDataStore(); String title = titleField.getText(); if (otDataStore.getChannelDescriptions().size() > index && otDataStore.getChannelDescriptions().get(index) != null){ otDataStore.getChannelDescriptions().get(index).setName(title); } else { OTDataChannelDescription channelDescription; try { channelDescription = (OTDataChannelDescription) otDataStore.getOTObjectService().createObject(OTDataChannelDescription.class); channelDescription.setName(title); channelDescription.setNumericData(false); otDataStore.getChannelDescriptions().add(channelDescription); } catch (Exception e) { e.printStackTrace(); } } update(); }}); titlesPanel.add(titleField); } tableWrapper.add(titlesPanel, BorderLayout.NORTH); } /** * @param dataStore * @param columns */ protected void updateOTColumns(DataTableModel tableModel, DataStore dataStore, OTObjectList columns) { for (int i = 0; i < columns.size(); i++){ OTDataColumnDescription otColDesc = (OTDataColumnDescription)columns.get(i); if (otColDesc == null) continue; DataColumnDescription colDesc = tableModel.getDataColumn(dataStore, i); String label = otColDesc.getLabel(); if (label != null){ colDesc.setLabel(label); } if (otColDesc.isResourceSet("color")){ colDesc.setColor(new Color(otColDesc.getColor())); } } tableModel.fireTableStructureChanged(); } /** * @see org.concord.framework.otrunk.view.OTJComponentView#viewClosed() */ public void viewClosed() { controllerService.dispose(); } }
package org.concord.view; import java.awt.BorderLayout; import java.awt.Color; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.Hashtable; import java.util.Vector; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.UIManager; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import org.concord.framework.util.CheckedColorTreeModel; import org.concord.swing.CCJCheckBoxRenderer; import org.concord.swing.CCJCheckBoxTree; /** * * CheckedColorTreeControler * Class name and description * * This class can be used to create a tree view of a model that * implements CheckedColorTreeModel. This could still use a bit * more refactoring. It maintains a separate object graph to represent * the tree nodes, this could be eliminated. * * Date created: Apr 27, 2006 * * @author scott<p> * */ public class CheckedColorTreeControler { CheckedColorTreeModel treeModel; CCJCheckBoxTree cTree = new CCJCheckBoxTree("Tree Root"); TreePath lastSelectedPath; Hashtable nodeGraphableMap = new Hashtable(); Vector checkedTreeNodes = new Vector(); AbstractAction newDataSetAction; AbstractAction deleteDataSetAction; AbstractAction renameAction; AbstractAction clearAction; JPanel treePanel; JPanel controlPanel; public JComponent setup(CheckedColorTreeModel customTreeModel, boolean showNew) { treeModel = customTreeModel; createActions(); cTree.setCellRenderer(new CCJCheckBoxRenderer()); cTree.setRootVisible(false); Vector initialItems = treeModel.getItems(null); for(int i=0; i<initialItems.size(); i++){ Object item = initialItems.get(i); String name = treeModel.getItemLabel(item); Color color = treeModel.getItemColor(item); CCJCheckBoxTree.NodeHolder nodeHolder = new CCJCheckBoxTree.NodeHolder(name, true, color); cTree.setSelectionPath(null); cTree.addObject(nodeHolder); nodeGraphableMap.put(nodeHolder, item); } TreeNode rootNode = cTree.getRootNode(); if(rootNode.getChildCount() > 1) { lastSelectedPath = cTree.getPathForRow(0); cTree.setSelectionPath(lastSelectedPath); DefaultMutableTreeNode node = (DefaultMutableTreeNode)cTree.getLastSelectedPathComponent(); CCJCheckBoxTree.NodeHolder holder = (CCJCheckBoxTree.NodeHolder)node.getUserObject(); Object selectedItem = nodeGraphableMap.get(holder); treeModel.setSelectedItem(selectedItem, true); } treePanel = new JPanel(); treePanel.setLayout(new BorderLayout()); controlPanel = new JPanel(); controlPanel.setLayout(new GridLayout(3,1)); JButton bNew = new JButton(newDataSetAction); JButton bDelete = new JButton(deleteDataSetAction); JButton bRename = new JButton(renameAction); if(showNew){ controlPanel.add(bNew); } controlPanel.add(bDelete); controlPanel.add(bRename); bNew.setOpaque(false); bDelete.setOpaque(false); bRename.setOpaque(false); controlPanel.setBackground(Color.WHITE); treePanel.setBackground(UIManager.getColor("Tree.textBackground")); treePanel.add(cTree, BorderLayout.CENTER); treePanel.add(controlPanel, BorderLayout.NORTH); cTree.addTreeSelectionListener(tsl); cTree.addMouseListener(ml); return treePanel; } private void createActions() { newDataSetAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { addNewItem(); } }; newDataSetAction.putValue(Action.NAME, "New"); deleteDataSetAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { removeNode(); } }; deleteDataSetAction.putValue(Action.NAME, "Delete"); renameAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { renameNode(); } }; renameAction.putValue(Action.NAME, "Rename"); } private void renameNode() { String newLabel = cTree.renameCurrentNode(); DefaultMutableTreeNode node = (DefaultMutableTreeNode) cTree.getLastSelectedPathComponent(); CCJCheckBoxTree.NodeHolder holder = (CCJCheckBoxTree.NodeHolder)node.getUserObject(); Object item = nodeGraphableMap.get(holder); if(item != null && newLabel != null && newLabel.trim().length() > 0) { treeModel.setItemLabel(item, newLabel); } } MouseAdapter ml = new MouseAdapter() { public void mouseReleased(MouseEvent e) { TreePath newSelectedPath = cTree.getSelectionPath(); if(newSelectedPath != null) { DefaultMutableTreeNode node = (DefaultMutableTreeNode)newSelectedPath.getLastPathComponent(); CCJCheckBoxTree.NodeHolder nodeHolder = (CCJCheckBoxTree.NodeHolder)node.getUserObject(); Object item = nodeGraphableMap.get(nodeHolder); treeModel.setSelectedItem(item, nodeHolder.checked); } if(e.getClickCount() == 2) { renameNode(); } updateItemCheckState(); treeModel.updateItems(); } }; TreeSelectionListener tsl = new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { if(e.getSource() == cTree) { TreePath newSelectedPath = cTree.getSelectionPath(); if(newSelectedPath != null && newSelectedPath != lastSelectedPath) { lastSelectedPath = newSelectedPath; DefaultMutableTreeNode node = (DefaultMutableTreeNode)lastSelectedPath.getLastPathComponent(); CCJCheckBoxTree.NodeHolder nodeHolder = (CCJCheckBoxTree.NodeHolder)node.getUserObject(); Object item = nodeGraphableMap.get(nodeHolder); treeModel.setSelectedItem(item, nodeHolder.checked); } else { treeModel.setSelectedItem(null, false); } } } }; private void addNewItem() { // name of new node String prompt = "Enter name of the new " + treeModel.getItemTypeName(); String name = JOptionPane.showInputDialog(null, prompt); if(name == null || name.trim().length() == 0) return; // get color of new node Color color = treeModel.getNewColor(); // add new node to tree if not null cTree.removeTreeSelectionListener(tsl); cTree.setSelectionPath(null); CCJCheckBoxTree.NodeHolder newNodeHolder = new CCJCheckBoxTree.NodeHolder(name, true, color); cTree.addObject(newNodeHolder); cTree.setSelectionPath(lastSelectedPath); cTree.addTreeSelectionListener(tsl); Object item = treeModel. addItem(null, name, color); nodeGraphableMap.put(newNodeHolder, item); //select the new created datastore cTree.setSelectionRow(cTree.getRowCount()-1); } /** * remove node from tree, also removes datagraphable from datagraph, * key-value pair from hashmap, color related to that node also removed. * */ private void removeNode() { cTree.removeTreeSelectionListener(tsl); Object obj = cTree.removeCurrentNode(); cTree.addTreeSelectionListener(tsl); //System.out.println(obj + " removed from tree"); if(obj != null) { Object item = nodeGraphableMap.get(obj); nodeGraphableMap.remove(obj); treeModel.removeItem(null, item); if(checkedTreeNodes.contains(obj))checkedTreeNodes.removeElement(obj); //System.out.println(dataGraphable + " removed too"); } treeModel.setSelectedItem(null, false); } private void updateItemCheckState() { checkedTreeNodes = cTree.getCheckedNodes(); Vector allNodes = cTree.getAllNodes(); int size = allNodes.size(); for(int i = 0; i < size; i ++) { Object obj = allNodes.elementAt(i); Object item = nodeGraphableMap.get(obj); if(item != null) { if(checkedTreeNodes.contains(obj)) { treeModel.setItemChecked(item, true); } else { treeModel.setItemChecked(item, false); } } } } /** * Completely refresh the view * */ public void refresh() { if(cTree != null && treePanel != null) { treePanel.remove(cTree); } nodeGraphableMap.clear(); cTree = new CCJCheckBoxTree("Tree Root"); cTree.setCellRenderer(new CCJCheckBoxRenderer()); cTree.setRootVisible(false); Vector initialItems = treeModel.getItems(null); for(int i=0; i<initialItems.size(); i++){ Object item = initialItems.get(i); String name = treeModel.getItemLabel(item); Color color = treeModel.getItemColor(item); CCJCheckBoxTree.NodeHolder nodeHolder = new CCJCheckBoxTree.NodeHolder(name, true, color); cTree.setSelectionPath(null); cTree.addObject(nodeHolder); nodeGraphableMap.put(nodeHolder, item); } TreeNode rootNode = cTree.getRootNode(); if(rootNode.getChildCount() >= 1) { lastSelectedPath = cTree.getPathForRow(0); cTree.setSelectionPath(lastSelectedPath); DefaultMutableTreeNode node = (DefaultMutableTreeNode)cTree.getLastSelectedPathComponent(); CCJCheckBoxTree.NodeHolder holder = (CCJCheckBoxTree.NodeHolder)node.getUserObject(); Object selectedItem = nodeGraphableMap.get(holder); treeModel.setSelectedItem(selectedItem, true); } cTree.addTreeSelectionListener(tsl); cTree.addMouseListener(ml); treePanel.add(cTree, BorderLayout.CENTER); // I don't understand this. By calling the add method I would have // expected treePanel to automatically call validate or invalidate // invalidate doesn't actually work here // The only thing that I found works here is to call validate, that forces // the treePanel to relayout the components, otherwise the cTree ends up // behind the controlPanel. treePanel.validate(); } public void setSelectedRow(int row) { lastSelectedPath = cTree.getPathForRow(row); cTree.setSelectionPath(lastSelectedPath); DefaultMutableTreeNode node = (DefaultMutableTreeNode)cTree.getLastSelectedPathComponent(); CCJCheckBoxTree.NodeHolder holder = (CCJCheckBoxTree.NodeHolder)node.getUserObject(); Object selectedItem = nodeGraphableMap.get(holder); treeModel.setSelectedItem(selectedItem, true); } }
package org.ensembl.healthcheck.testgroup; import org.ensembl.healthcheck.GroupOfTests; import org.ensembl.healthcheck.testcase.eg_core.NoRepeatFeatures; import org.ensembl.healthcheck.testcase.eg_core.SeqRegionLength; import org.ensembl.healthcheck.testcase.generic.MySQLStorageEngine; public class EGCommon extends GroupOfTests { public EGCommon() { addTest( MySQLStorageEngine.class, SeqRegionLength.class, NoRepeatFeatures.class ); } }
package org.nees.buffalo.rdv.ui; import java.awt.Color; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.ActionMap; import javax.swing.BorderFactory; import javax.swing.InputMap; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.KeyStroke; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nees.buffalo.rdv.DataPanelManager; import org.nees.buffalo.rdv.rbnb.RBNBController; import java.util.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.text.ParseException; public class JumpDateTimeDialog extends JDialog { static Log log = LogFactory.getLog(JumpDateTimeDialog.class.getName()); RBNBController rbnb; DataPanelManager dataPanelManager; Date defaultDate; JLabel headerLabel; JLabel dateLable; JTextField dateTextField; JLabel timeLabel; JTextField timeTextField; JButton jumpButton; JButton cancelButton; JLabel dateLabelExample; JLabel timeLabelExample; JLabel errorLabel; /** Format to use to display the date property. */ private static final DateFormat DATE_FORMAT = new SimpleDateFormat("MM-dd-yyyy"); private static final DateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss z"); public JumpDateTimeDialog(JFrame owner, RBNBController rbnbController, DataPanelManager dataPanelManager) { super(owner, true); this.rbnb = rbnbController; this.dataPanelManager = dataPanelManager; defaultDate = new Date(((long)(rbnb.getLocation()*1000))); setDefaultCloseOperation(DISPOSE_ON_CLOSE); setTitle("Go to Date Time location"); JPanel container = new JPanel(); setContentPane(container); InputMap inputMap = container.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); ActionMap actionMap = container.getActionMap(); container.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.weighty = 1; c.gridwidth = 1; c.gridheight = 1; c.ipadx = 0; c.ipady = 0; headerLabel = new JLabel("Please enter the date and time for location data."); headerLabel.setBackground(Color.white); headerLabel.setOpaque(true); headerLabel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createMatteBorder(0,0,1,0,Color.gray), BorderFactory.createEmptyBorder(10,10,10,10))); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 0; c.gridx = 0; c.gridy = 0; c.gridwidth = 2; c.anchor = GridBagConstraints.NORTHEAST; c.insets = new Insets(0,0,0,0); container.add(headerLabel, c); c.gridwidth = 1; errorLabel = new JLabel(); c.weightx = 0; c.gridx = 0; c.gridy = 1; c.gridwidth = 2; container.add(errorLabel, c); dateLabelExample = new JLabel("Date Format: mm-dd-yyyy"); dateLabelExample.setForeground(Color.BLUE); dateLabelExample.setOpaque(true); c.weightx = 0; c.gridx = 0; c.gridy = 2; c.gridwidth = 2; c.insets = new Insets(10,10,10,5); container.add(dateLabelExample, c); dateLable = new JLabel("Date:"); c.weightx = 0; c.gridx = 0; c.gridy = 3; container.add(dateLable, c); dateTextField = new JTextField(DATE_FORMAT.format(defaultDate), 10); c.weightx = 0; c.gridx = 1; c.gridy = 3; container.add(dateTextField, c); timeLabelExample = new JLabel("Time Format: hh:mm:ss PDT(EDT or GMT)"); timeLabelExample.setForeground(Color.BLUE); timeLabelExample.setOpaque(true); c.weightx = 0; c.gridx = 0; c.gridy = 4; c.gridwidth = 2; container.add(timeLabelExample, c); timeLabel = new JLabel("Time:"); c.weightx = 0; c.gridx = 0; c.gridy = 5; c.gridwidth = 1; container.add(timeLabel, c); timeTextField = new JTextField(TIME_FORMAT.format(defaultDate), 10); c.weightx = 0; c.gridx = 1; c.gridy = 5; c.gridwidth = 1; container.add(timeTextField, c); JPanel buttonPanel = new JPanel(); Action jumpLocationAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { jumpLocation(); } }; jumpLocationAction.putValue(Action.NAME, "Jump Location"); inputMap.put(KeyStroke.getKeyStroke("ENTER"), "jumpLocation"); actionMap.put("jumpLocation", jumpLocationAction); jumpButton = new JButton(jumpLocationAction); buttonPanel.add(jumpButton); Action cancelAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { cancel(); } }; cancelAction.putValue(Action.NAME, "Cancel"); inputMap.put(KeyStroke.getKeyStroke("ESCAPE"), "cancel"); actionMap.put("cancel", cancelAction); cancelButton = new JButton(cancelAction); buttonPanel.add(cancelButton); c.fill = GridBagConstraints.NONE; c.weightx = 0; c.gridx = 0; c.gridy = 6; c.gridwidth = 2; c.anchor = GridBagConstraints.LINE_END; c.insets = new Insets(0,10,10,5); container.add(buttonPanel, c); pack(); setLocationByPlatform(true); setVisible(true); } public void setVisible(boolean visible) { if (visible) { dateTextField.requestFocusInWindow(); // dateTextField.setSelectionStart(0); // dateTextField.setSelectionEnd(dateTextField.getText().length()); } super.setVisible(visible); } private void jumpLocation() { String strDateLocation; String strTimeLocation; String dateAndTime; Date dateLocation; try { SimpleDateFormat df = new SimpleDateFormat("MM-dd-yyyy"); df.setLenient(false); // this is important! strDateLocation = dateTextField.getText().trim(); dateLocation = df.parse(strDateLocation); df = new SimpleDateFormat("HH:mm:ss z"); df.setLenient(false); strTimeLocation = timeTextField.getText().trim(); dateLocation = df.parse(strTimeLocation); df = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss z"); //create a formatter to append time to date with space in between dateAndTime = strDateLocation + " " + strTimeLocation; dateLocation = df.parse(dateAndTime); double secondsLocation = dateLocation.getTime() / 1000; // convert to seconds rbnb.setLocation(secondsLocation); dispose(); } catch (Exception e) { errorLabel.setForeground(Color.RED); errorLabel.setText("Error: invalid date. Please try again!"); timeLabel.setForeground(Color.RED); timeTextField.setText(TIME_FORMAT.format(defaultDate)); dateLable.setForeground(Color.RED); dateTextField.setText(DATE_FORMAT.format(defaultDate)); dateTextField.requestFocusInWindow(); } } private void cancel() { dispose(); } }
package org.nees.buffalo.rdv.ui; import java.awt.Color; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.ActionMap; import javax.swing.BorderFactory; import javax.swing.InputMap; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.KeyStroke; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nees.buffalo.rdv.rbnb.RBNBController; import java.util.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; public class JumpDateTimeDialog extends JDialog { static Log log = LogFactory.getLog(JumpDateTimeDialog.class.getName()); RBNBController rbnb; Date defaultDate; JLabel headerLabel; JLabel dateLable; JTextField dateTextField; JLabel timeLabel; JTextField timeTextField; JButton jumpButton; JButton cancelButton; JLabel dateLabelExample; JLabel timeLabelExample; JLabel errorLabel; /** Format to use to display the date property. */ private static final DateFormat DATE_FORMAT = new SimpleDateFormat("MM-dd-yyyy"); private static final DateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss z"); public JumpDateTimeDialog(RBNBController rbnbController) { this(null, rbnbController); } public JumpDateTimeDialog(JFrame owner, RBNBController rbnbController) { super(owner, true); this.rbnb = rbnbController; defaultDate = new Date(((long)(rbnb.getLocation()*1000))); setDefaultCloseOperation(DISPOSE_ON_CLOSE); setTitle("Go to time"); JPanel container = new JPanel(); setContentPane(container); InputMap inputMap = container.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); ActionMap actionMap = container.getActionMap(); container.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.weighty = 0; c.gridheight = 1; c.ipadx = 0; c.ipady = 0; headerLabel = new JLabel("<html>Please enter the date and time to go to. " + "Enter the date using the <br>mm-dd-yyyy format and the time using " + "the hh:mm:ss z format.</html>"); headerLabel.setBackground(Color.white); headerLabel.setOpaque(true); headerLabel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createMatteBorder(0,0,1,0,Color.gray), BorderFactory.createEmptyBorder(10,10,10,10))); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 0; c.gridx = 0; c.gridy = 0; c.gridwidth = 2; c.anchor = GridBagConstraints.NORTHEAST; c.insets = new Insets(0,0,0,0); container.add(headerLabel, c); errorLabel = new JLabel(); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 0; c.gridx = 0; c.gridy = 1; c.gridwidth = 2; c.insets = new Insets(10,10,0,10); container.add(errorLabel, c); c.gridwidth = 1; dateLable = new JLabel("Date:"); c.fill = GridBagConstraints.NONE; c.weightx = 0; c.gridx = 0; c.gridy = 2; c.anchor = GridBagConstraints.NORTHEAST; c.insets = new Insets(10,10,10,5); container.add(dateLable, c); dateTextField = new JTextField(DATE_FORMAT.format(defaultDate), 10); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1; c.gridx = 1; c.gridy = 2; c.anchor = GridBagConstraints.NORTHWEST; c.insets = new Insets(10,0,10,10); container.add(dateTextField, c); timeLabel = new JLabel("Time:"); c.fill = GridBagConstraints.NONE; c.weightx = 0; c.gridx = 0; c.gridy = 3; c.anchor = GridBagConstraints.NORTHEAST; c.insets = new Insets(0,10,10,5); container.add(timeLabel, c); timeTextField = new JTextField(TIME_FORMAT.format(defaultDate), 10); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1; c.gridx = 1; c.gridy = 3; c.anchor = GridBagConstraints.NORTHWEST; c.insets = new Insets(0,0,10,10); container.add(timeTextField, c); JPanel buttonPanel = new JPanel(); Action jumpLocationAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { jumpLocation(); } }; jumpLocationAction.putValue(Action.NAME, "Go to location"); inputMap.put(KeyStroke.getKeyStroke("ENTER"), "jumpLocation"); actionMap.put("jumpLocation", jumpLocationAction); jumpButton = new JButton(jumpLocationAction); buttonPanel.add(jumpButton); Action cancelAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { cancel(); } }; cancelAction.putValue(Action.NAME, "Cancel"); inputMap.put(KeyStroke.getKeyStroke("ESCAPE"), "cancel"); actionMap.put("cancel", cancelAction); cancelButton = new JButton(cancelAction); buttonPanel.add(cancelButton); c.fill = GridBagConstraints.NONE; c.weightx = 0; c.weighty = 1; c.gridx = 0; c.gridy = 4; c.gridwidth = 2; c.anchor = GridBagConstraints.LINE_END; c.insets = new Insets(0,10,10,5); container.add(buttonPanel, c); pack(); setLocationByPlatform(true); setVisible(true); } public void setVisible(boolean visible) { if (visible) { dateTextField.requestFocusInWindow(); } super.setVisible(visible); } private void jumpLocation() { String strDateLocation; String strTimeLocation; String dateAndTime; Date dateLocation; try { SimpleDateFormat df = new SimpleDateFormat("MM-dd-yyyy"); df.setLenient(false); // this is important! strDateLocation = dateTextField.getText().trim(); dateLocation = df.parse(strDateLocation); df = new SimpleDateFormat("HH:mm:ss z"); df.setLenient(false); strTimeLocation = timeTextField.getText().trim(); dateLocation = df.parse(strTimeLocation); df = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss z"); //create a formatter to append time to date with space in between dateAndTime = strDateLocation + " " + strTimeLocation; dateLocation = df.parse(dateAndTime); double secondsLocation = dateLocation.getTime() / 1000; // convert to seconds rbnb.setLocation(secondsLocation); dispose(); } catch (Exception e) { errorLabel.setForeground(Color.RED); errorLabel.setText("Error: invalid date. Please try again!"); timeLabel.setForeground(Color.RED); timeTextField.setText(TIME_FORMAT.format(defaultDate)); dateLable.setForeground(Color.RED); dateTextField.setText(DATE_FORMAT.format(defaultDate)); dateTextField.requestFocusInWindow(); pack(); } } private void cancel() { dispose(); } }
package org.pentaho.di.core.row; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.math.BigDecimal; import java.net.SocketTimeoutException; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import org.pentaho.di.compatibility.Value; import org.pentaho.di.core.exception.KettleEOFException; import org.pentaho.di.core.exception.KettleFileException; import org.pentaho.di.core.exception.KettleValueException; import org.w3c.dom.Node; public interface ValueMetaInterface extends Cloneable { /** Value type indicating that the value has no type set */ public static final int TYPE_NONE = 0; /** Value type indicating that the value contains a floating point double precision number. */ public static final int TYPE_NUMBER = 1; /** Value type indicating that the value contains a text String. */ public static final int TYPE_STRING = 2; /** Value type indicating that the value contains a Date. */ public static final int TYPE_DATE = 3; /** Value type indicating that the value contains a boolean. */ public static final int TYPE_BOOLEAN = 4; /** Value type indicating that the value contains a long integer. */ public static final int TYPE_INTEGER = 5; /** Value type indicating that the value contains a floating point precision number with arbitrary precision. */ public static final int TYPE_BIGNUMBER = 6; /** Value type indicating that the value contains an Object. */ public static final int TYPE_SERIALIZABLE= 7; /** Value type indicating that the value contains binary data: BLOB, CLOB, ... */ public static final int TYPE_BINARY = 8; public static final String[] typeCodes = new String[] { "-", "Number", "String", "Date", "Boolean", "Integer", "BigNumber", "Serializable", "Binary", }; /** The storage type is the same as the indicated value type */ public static final int STORAGE_TYPE_NORMAL = 0; /** The storage type is binary: read from text but not yet converted to the requested target data type, for lazy conversions. */ public static final int STORAGE_TYPE_BINARY_STRING = 1; /** The storage type is indexed. This means that the value is a simple integer index referencing the values in getIndex() */ public static final int STORAGE_TYPE_INDEXED = 2; public static final String[] storageTypeCodes = new String[] { "normal", "binary-string", "indexed", }; /** Indicating that the rows are not sorted on this key */ public static final int SORT_TYPE_NOT_SORTED = 0; /** Indicating that the rows are not sorted ascending on this key */ public static final int SORT_TYPE_ASCENDING = 1; /** Indicating that the rows are sorted descending on this key */ public static final int SORT_TYPE_DESCENDING = 2; public static final String[] sortTypeCodes = new String[] { "none", "ascending", "descending", }; /** Indicating that the string content should NOT be trimmed if conversion is to occur to another data type */ public static final int TRIM_TYPE_NONE = 0; /** Indicating that the string content should be LEFT trimmed if conversion is to occur to another data type */ public static final int TRIM_TYPE_LEFT = 1; /** Indicating that the string content should be RIGHT trimmed if conversion is to occur to another data type */ public static final int TRIM_TYPE_RIGHT = 2; /** Indicating that the string content should be LEFT AND RIGHT trimmed if conversion is to occur to another data type */ public static final int TRIM_TYPE_BOTH = 3; /** Default integer length for hardcoded metadata integers */ public static final int DEFAULT_INTEGER_LENGTH = 10; public String getName(); public void setName(String name); public int getLength(); public void setLength(int length); public int getPrecision(); public void setPrecision(int precision); public void setLength(int length, int precision); public String getOrigin(); public void setOrigin(String origin); public String getComments(); public void setComments(String comments); public int getType(); public void setType(int type); public int getStorageType(); public void setStorageType(int storageType); public int getTrimType(); public void setTrimType(int trimType); public Object[] getIndex(); public void setIndex(Object[] index); public boolean isStorageNormal(); public boolean isStorageIndexed(); public boolean isStorageBinaryString(); public String getConversionMask(); public void setConversionMask(String conversionMask); public String getDecimalSymbol(); public void setDecimalSymbol(String decimalSymbol); public String getGroupingSymbol(); public void setGroupingSymbol(String groupingSymbol); public String getCurrencySymbol(); public void setCurrencySymbol(String currencySymbol); public SimpleDateFormat getDateFormat(); public DecimalFormat getDecimalFormat(); public String getStringEncoding(); public void setStringEncoding(String stringEncoding); /** * @return true if the String encoding used (storage) is single byte encoded. */ public boolean isSingleByteEncoding(); /** * Determine if an object is null. * This is the case if data==null or if it's an empty string. * @param data the object to test * @return true if the object is considered null. */ public boolean isNull(Object data); /** * @return the caseInsensitive */ public boolean isCaseInsensitive(); /** * @param caseInsensitive the caseInsensitive to set */ public void setCaseInsensitive(boolean caseInsensitive); /** * @return the sortedDescending */ public boolean isSortedDescending(); /** * @param sortedDescending the sortedDescending to set */ public void setSortedDescending(boolean sortedDescending); /** * @return true if output padding is enabled (padding to specified length) */ public boolean isOutputPaddingEnabled(); /** * @param outputPaddingEnabled Set to true if output padding is to be enabled (padding to specified length) */ public void setOutputPaddingEnabled(boolean outputPaddingEnabled); /** * @return true if this is a large text field (CLOB, TEXT) with arbitrary length. */ public boolean isLargeTextField(); /** * @param largeTextField Set to true if this is to be a large text field (CLOB, TEXT) with arbitrary length. */ public void setLargeTextField(boolean largeTextField); /** * @return true if the the date formatting (parsing) is to be lenient */ public boolean isDateFormatLenient(); /** * @param dateFormatLenient true if the the date formatting (parsing) is to be set to lenient */ public void setDateFormatLenient(boolean dateFormatLenient); /** * @return the date format locale */ public Locale getDateFormatLocale(); /** * @param dateFormatLocale the date format locale to set */ public void setDateFormatLocale(Locale dateFormatLocale); /* Conversion methods */ public Object cloneValueData(Object object) throws KettleValueException; /** Convert the supplied data to a String */ public String getString(Object object) throws KettleValueException; /** convert the supplied data to a binary string representation (for writing text) */ public byte[] getBinaryString(Object object) throws KettleValueException; /** Convert the supplied data to a Number */ public Double getNumber(Object object) throws KettleValueException; /** Convert the supplied data to a BigNumber */ public BigDecimal getBigNumber(Object object) throws KettleValueException; /** Convert the supplied data to an Integer*/ public Long getInteger(Object object) throws KettleValueException; /** Convert the supplied data to a Date */ public Date getDate(Object object) throws KettleValueException; /** Convert the supplied data to a Boolean */ public Boolean getBoolean(Object object) throws KettleValueException; /** Convert the supplied data to binary data */ public byte[] getBinary(Object object) throws KettleValueException; /** * @return a copy of this value meta object */ public ValueMetaInterface clone(); /** * Checks wheter or not the value is a String. * @return true if the value is a String. */ public boolean isString(); /** * Checks whether or not this value is a Date * @return true if the value is a Date */ public boolean isDate(); /** * Checks whether or not the value is a Big Number * @return true is this value is a big number */ public boolean isBigNumber(); /** * Checks whether or not the value is a Number * @return true is this value is a number */ public boolean isNumber(); /** * Checks whether or not this value is a boolean * @return true if this value has type boolean. */ public boolean isBoolean(); /** * Checks whether or not this value is of type Serializable * @return true if this value has type Serializable */ public boolean isSerializableType(); /** * Checks whether or not this value is of type Binary * @return true if this value has type Binary */ public boolean isBinary(); /** * Checks whether or not this value is an Integer * @return true if this value is an integer */ public boolean isInteger(); /** * Checks whether or not this Value is Numeric * A Value is numeric if it is either of type Number or Integer * @return true if the value is either of type Number or Integer */ public boolean isNumeric(); /** * Return the type of a value in a textual form: "String", "Number", "Integer", "Boolean", "Date", ... * @return A String describing the type of value. */ public String getTypeDesc(); /** * a String text representation of this Value, optionally padded to the specified length * @return a String text representation of this Value, optionally padded to the specified length */ public String toStringMeta(); /** * Write the content of this class (metadata) to the specified output stream. * @param outputStream the outputstream to write to * @throws KettleFileException in case a I/O error occurs */ public void writeMeta(DataOutputStream outputStream) throws KettleFileException; /** * Serialize the content of the specified data object to the outputStream. No metadata is written. * @param outputStream the outputstream to write to * @param object the data object to serialize * @throws KettleFileException in case a I/O error occurs */ public void writeData(DataOutputStream outputStream, Object object) throws KettleFileException; /** * De-serialize data from an inputstream. No metadata is read or changed. * @param inputStream the input stream to read from * @return a new data object * @throws KettleFileException in case a I/O error occurs * @throws KettleEOFException When we have read all the data there is to read * @throws SocketTimeoutException In case there is a timeout (when set on a socket) during reading */ public Object readData(DataInputStream inputStream) throws KettleFileException, KettleEOFException, SocketTimeoutException; /** * Compare 2 values of the same data type * @param data1 the first value * @param data2 the second value * @return 0 if the values are equal, -1 if data1 is smaller than data2 and +1 if it's larger. * @throws KettleValueException In case we get conversion errors */ public int compare(Object data1, Object data2) throws KettleValueException; /** * Compare 2 values of the same data type * @param data1 the first value * @param meta2 the second value's metadata * @param data2 the second value * @return 0 if the values are equal, -1 if data1 is smaller than data2 and +1 if it's larger. * @throws KettleValueException In case we get conversion errors */ public int compare(Object data1, ValueMetaInterface meta2, Object data2) throws KettleValueException; /** * Convert the specified data to the data type specified in this object. * @param meta2 the metadata of the object to be converted * @param data2 the data of the object to be converted * @return the object in the data type of this value metadata object * @throws KettleValueException in case there is a data conversion error */ public Object convertData(ValueMetaInterface meta2, Object data2) throws KettleValueException; /** * Convert an object to the data type specified in the conversion metadata * @param data The data * @return The data converted to the conversion data type * @throws KettleValueException in case there is a conversion error. */ public Object convertDataUsingConversionMetaData(Object data) throws KettleValueException; /** * Convert the specified string to the data type specified in this object. * @param pol the string to be converted * @param convertMeta the metadata of the object (only string type) to be converted * @param nullif set the object to null if pos equals nullif (IgnoreCase) * @param ifNull set the object to ifNull when pol is empty or null * @param trim_type the trim type to be used (ValueMetaInterface.TRIM_TYPE_XXX) * @return the object in the data type of this value metadata object * @throws KettleValueException in case there is a data conversion error */ public Object convertDataFromString(String pol, ValueMetaInterface convertMeta, String nullif, String ifNull, int trim_type) throws KettleValueException; /** * Convert the given binary data to the actual data type.<br> * - byte[] --> Long (Integer)<br> * - byte[] --> Double (Number)<br> * - byte[] --> BigDecimal (BigNumber)<br> * - byte[] --> Date (Date)<br> * - byte[] --> Boolean (Boolean)<br> * - byte[] --> byte[] (Binary)<br> * <br> * @param binary the binary data read from file or database * @return the native data type after conversion * @throws KettleValueException in case there is a data conversion error */ public Object convertBinaryStringToNativeType(byte[] binary) throws KettleValueException; /** * Calculate the hashcode of the specified data object * @param object the data value to calculate a hashcode for * @return the calculated hashcode * @throws KettleValueException in case there is a data conversion error */ public int hashCode(Object object) throws KettleValueException; /** * Create an old-style value for backward compatibility reasons * @param data the data to store in the value * @return a newly created Value object * @throws KettleValueException in case there is a data conversion problem */ public Value createOriginalValue(Object data) throws KettleValueException; /** * Extracts the primitive data from an old style Value object * @param value the old style Value object * @return the value's data, NOT the meta data. * @throws KettleValueException case there is a data conversion problem */ public Object getValueData(Value value) throws KettleValueException; /** * @return the storage Meta data that is needed for internal conversion from BinaryString or String to the specified type. * This storage Meta data object survives cloning and should travel through the transformation unchanged as long as the data type remains the same. */ public ValueMetaInterface getStorageMetadata(); /** * @param storageMetadata the storage Meta data that is needed for internal conversion from BinaryString or String to the specified type. * This storage Meta data object survives cloning and should travel through the transformation unchanged as long as the data type remains the same. */ public void setStorageMetadata(ValueMetaInterface storageMetadata); /** * This conversion metadata can be attached to a String object to see where it came from and with which mask it was generated, the encoding, the local languages used, padding, etc. * @return The conversion metadata */ public ValueMetaInterface getConversionMetadata(); /** * Attach conversion metadata to a String object to see where it came from and with which mask it was generated, the encoding, the local languages used, padding, etc. * @param conversionMetadata the conversionMetadata to set */ public void setConversionMetadata(ValueMetaInterface conversionMetadata); /** * @return an XML representation of the row metadata * @throws IOException Thrown in case there is an (Base64/GZip) decoding problem */ public String getMetaXML() throws IOException; /** * @param value The data to serialize as XML * @return an xML representation of the row data * @throws IOException Thrown in case there is an (Base64/GZip) decoding problem */ public String getDataXML(Object value) throws IOException; /** * Convert a data XML node to an Object that corresponds to the metadata. * This is basically String to Object conversion that is being done. * @param node the node to retrieve the data value from * @return the converted data value * @throws IOException thrown in case there is a problem with the XML to object conversion */ public Object getValue(Node node) throws IOException; /** * @return the number of binary string to native data type conversions done with this object conversions */ public long getNumberOfBinaryStringConversions(); /** * @param numberOfBinaryStringConversions the number of binary string to native data type done with this object conversions to set */ public void setNumberOfBinaryStringConversions(long numberOfBinaryStringConversions); }
package org.supercsv.cellprocessor; import java.math.BigDecimal; import java.text.DecimalFormatSymbols; import org.supercsv.cellprocessor.ift.CellProcessor; import org.supercsv.cellprocessor.ift.StringCellProcessor; import org.supercsv.exception.NullInputException; import org.supercsv.exception.SuperCSVException; import org.supercsv.util.CSVContext; /** * Convert a string to a big decimal. It constructs BigDecimals from strings as recommended by the Javadoc (e.g. * <tt>new BigDecimal(0.1)</tt> yields unpredictable results, while <tt>new BidDecimal("0.1")</tt> yields * predictable results. * * @since 1.30 * @author Kasper B. Graversen */ public class ParseBigDecimal extends CellProcessorAdaptor implements StringCellProcessor { private DecimalFormatSymbols symbols; public ParseBigDecimal() { this((DecimalFormatSymbols)null); } public ParseBigDecimal(DecimalFormatSymbols symbols) { super(); this.symbols = symbols; } public ParseBigDecimal(final CellProcessor next) { this(null,next); } public ParseBigDecimal(DecimalFormatSymbols symbols, final CellProcessor next) { super(next); this.symbols = symbols; } /** * {@inheritDoc} */ @Override public Object execute(final Object value, final CSVContext context) throws SuperCSVException { if( value == null ) { throw new NullInputException("Input cannot be null on line " + context.lineNumber + " at column " + context.columnNumber, context, this); } final BigDecimal result; if( value instanceof String ) { try { if (symbols == null) { result = new BigDecimal((String) value); } else { if (symbols.getDecimalSeparator() != '.') { String s = (String) value; result = new BigDecimal(s.replace(symbols.getDecimalSeparator(), '.')); } else { result = new BigDecimal((String) value); } } } catch(final Exception e) { throw new SuperCSVException("Parser error", context, e); } } else { throw new SuperCSVException("Can't convert \"" + value + "\" to a BigDecimal. Input is not of type String, but of type " + value.getClass().getName(), context, this); } return next.execute(result, context); } }
package proy.gui.controladores; import java.util.List; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.control.Spinner; import javafx.scene.control.SpinnerValueFactory; import javafx.scene.control.TextArea; import javafx.scene.control.TextFormatter; import javafx.util.converter.IntegerStringConverter; import proy.datos.entidades.Herramienta; import proy.datos.entidades.Maquina; import proy.datos.entidades.Parte; import proy.datos.entidades.Pieza; import proy.datos.entidades.Proceso; import proy.datos.filtros.implementacion.FiltroDescripcionProceso; import proy.datos.filtros.implementacion.FiltroHerramienta; import proy.datos.filtros.implementacion.FiltroMaquina; import proy.datos.filtros.implementacion.FiltroParte; import proy.datos.filtros.implementacion.FiltroPieza; import proy.datos.filtros.implementacion.FiltroTipoProceso; import proy.excepciones.PersistenciaException; import proy.gui.ControladorRomano; import proy.logica.gestores.resultados.ResultadoCrearProceso; import proy.logica.gestores.resultados.ResultadoCrearProceso.ErrorCrearProceso; import proy.logica.gestores.resultados.ResultadoModificarProceso; import proy.logica.gestores.resultados.ResultadoModificarProceso.ErrorModificarProceso; public class NMProcesoController extends ControladorRomano { public static final String URL_VISTA = "/proy/gui/vistas/NMProceso.fxml"; @FXML private ComboBox<Maquina> cbMaquina; @FXML private ComboBox<Parte> cbParte; @FXML private ComboBox<String> cbDescripcion; @FXML private ComboBox<String> cbTipo; @FXML private Spinner<Integer> spHsTTPreparacion; @FXML private Spinner<Integer> spMsTTPreparacion; @FXML private Spinner<Integer> spSsTTPreparacion; @FXML private Spinner<Integer> spHsTTProceso; @FXML private Spinner<Integer> spMsTTProceso; @FXML private Spinner<Integer> spSsTTProceso; @FXML private Label lbTiempoPromedioProceso; @FXML private ComboBox<Pieza> cbPieza; @FXML private ListView<Pieza> listaPiezas; @FXML private ComboBox<Herramienta> cbHerramienta; @FXML private ListView<Herramienta> listaHerramientas; @FXML private TextArea observacionesProceso; private String titulo; private Proceso proceso; @FXML public void agregarPieza() { Pieza piezaAAgregar = cbPieza.getSelectionModel().getSelectedItem(); if(piezaAAgregar != null){ return; } cbPieza.getItems().remove(piezaAAgregar); cbPieza.getSelectionModel().select(null); listaPiezas.getItems().add(piezaAAgregar); } @FXML public void quitarPieza() { Pieza piezaAQuitar = listaPiezas.getSelectionModel().getSelectedItem(); if(piezaAQuitar != null){ return; } cbPieza.getItems().add(piezaAQuitar); listaPiezas.getItems().remove(piezaAQuitar); } @FXML public void agregarHerramienta() { Herramienta herramientaAAgregar = cbHerramienta.getSelectionModel().getSelectedItem(); if(herramientaAAgregar != null){ return; } cbHerramienta.getItems().remove(herramientaAAgregar); cbHerramienta.getSelectionModel().select(null); listaHerramientas.getItems().add(herramientaAAgregar); } @FXML public void quitarHerramienta() { Herramienta herramientaAQuitar = listaHerramientas.getSelectionModel().getSelectedItem(); if(herramientaAQuitar != null){ return; } cbHerramienta.getItems().add(herramientaAQuitar); listaHerramientas.getItems().remove(herramientaAQuitar); } @FXML public void guardar() { Boolean hayErrores = true; if(proceso == null){ hayErrores = crearProceso(); } else{ hayErrores = modificarProceso(); } if(!hayErrores){ salir(); } } private Boolean crearProceso() { ResultadoCrearProceso resultadoCrearProceso; StringBuffer erroresBfr = new StringBuffer(); Proceso proceso = new Proceso(); //Toma de datos de la vista proceso.setParte(cbParte.getValue()); proceso.setDescripcion(cbDescripcion.getValue().trim()); proceso.setTipo(cbTipo.getValue().trim()); long segsTTP = spSsTTPreparacion.getValue(); long minsTTP = spMsTTPreparacion.getValue(); long horasTTP = spHsTTPreparacion.getValue(); long milisTTP = horasTTP * 3600000 + minsTTP * 60000 + segsTTP * 1000; proceso.setTiempoTeoricoPreparacion(milisTTP); segsTTP = spSsTTProceso.getValue(); minsTTP = spMsTTProceso.getValue(); horasTTP = spHsTTProceso.getValue(); milisTTP = horasTTP * 3600000 + minsTTP * 60000 + segsTTP * 1000; proceso.setTiempoTeoricoProceso(milisTTP); proceso.getPiezas().clear(); proceso.getPiezas().addAll(listaPiezas.getItems()); proceso.getHerramientas().clear(); proceso.getHerramientas().addAll(listaHerramientas.getItems()); proceso.setObservaciones(observacionesProceso.getText().trim()); //Inicio transacciones al gestor try{ resultadoCrearProceso = coordinador.crearProceso(proceso); } catch(PersistenciaException e){ presentadorVentanas.presentarExcepcion(e, stage); return true; } catch(Exception e){ presentadorVentanas.presentarExcepcionInesperada(e, stage); return true; } //Tratamiento de errores if(resultadoCrearProceso.hayErrores()){ for(ErrorCrearProceso e: resultadoCrearProceso.getErrores()){ switch(e) { } } String errores = erroresBfr.toString(); if(!errores.isEmpty()){ presentadorVentanas.presentarError("Error al crear el proceso", errores, stage); } return true; } else{ presentadorVentanas.presentarInformacion("Operación exitosa", "Se ha creado el proceso con éxito", stage); return false; } } private Boolean modificarProceso() { ResultadoModificarProceso resultadoModificarProceso; StringBuffer erroresBfr = new StringBuffer(); //Toma de datos de la vista proceso.setParte(cbParte.getValue()); proceso.setDescripcion(cbDescripcion.getValue().trim()); proceso.setTipo(cbTipo.getValue().trim()); long segsTTP = spSsTTPreparacion.getValue(); long minsTTP = spMsTTPreparacion.getValue(); long horasTTP = spHsTTPreparacion.getValue(); long milisTTP = horasTTP * 3600000 + minsTTP * 60000 + segsTTP * 1000; proceso.setTiempoTeoricoPreparacion(milisTTP); segsTTP = spSsTTProceso.getValue(); minsTTP = spMsTTProceso.getValue(); horasTTP = spHsTTProceso.getValue(); milisTTP = horasTTP * 3600000 + minsTTP * 60000 + segsTTP * 1000; proceso.setTiempoTeoricoProceso(milisTTP); proceso.getPiezas().clear(); proceso.getPiezas().addAll(listaPiezas.getItems()); proceso.getHerramientas().clear(); proceso.getHerramientas().addAll(listaHerramientas.getItems()); proceso.setObservaciones(observacionesProceso.getText().trim()); //Inicio transacciones al gestor try{ resultadoModificarProceso = coordinador.modificarProceso(proceso); } catch(PersistenciaException e){ presentadorVentanas.presentarExcepcion(e, stage); return true; } catch(Exception e){ presentadorVentanas.presentarExcepcionInesperada(e, stage); return true; } //Tratamiento de errores if(resultadoModificarProceso.hayErrores()){ for(ErrorModificarProceso e: resultadoModificarProceso.getErrores()){ switch(e) { } } String errores = erroresBfr.toString(); if(!errores.isEmpty()){ presentadorVentanas.presentarError("Error al modificar el proceso", errores, stage); } return true; } else{ presentadorVentanas.presentarInformacion("Operación exitosa", "Se ha modificado el proceso con éxito", stage); return false; } } public void formatearNuevoProceso() { titulo = "Nuevo proceso"; } public void formatearModificarProceso(Proceso proceso) { titulo = "Modificar proceso"; this.proceso = proceso; cargarDatosProceso(proceso); } private void cargarDatosProceso(Proceso proceso) { Platform.runLater(() -> { cbMaquina.getSelectionModel().select(proceso.getParte().getMaquina()); cbParte.getSelectionModel().select(proceso.getParte()); cbDescripcion.getSelectionModel().select(proceso.getDescripcion()); cbTipo.getSelectionModel().select(proceso.getTipo()); long milisTTP = proceso.getTiempoTeoricoPreparacion(); long segsTTP = (milisTTP / 1000) % 60; long minsTTP = (milisTTP / 60000) % 60; long horasTTP = milisTTP / 3600000; spHsTTPreparacion.getValueFactory().setValue((int) horasTTP); spMsTTPreparacion.getValueFactory().setValue((int) minsTTP); spSsTTPreparacion.getValueFactory().setValue((int) segsTTP); milisTTP = proceso.getTiempoTeoricoProceso(); segsTTP = (milisTTP / 1000) % 60; minsTTP = (milisTTP / 60000) % 60; horasTTP = milisTTP / 3600000; spHsTTProceso.getValueFactory().setValue((int) horasTTP); spMsTTProceso.getValueFactory().setValue((int) minsTTP); spSsTTProceso.getValueFactory().setValue((int) segsTTP); milisTTP = proceso.getTiempoPromedioProceso(); segsTTP = (milisTTP / 1000) % 60; minsTTP = (milisTTP / 60000) % 60; horasTTP = milisTTP / 3600000; lbTiempoPromedioProceso.setText(horasTTP + "hs " + minsTTP + "ms " + segsTTP + "ss"); cbPieza.getItems().removeAll(proceso.getPiezas()); listaPiezas.getItems().addAll(proceso.getPiezas()); cbHerramienta.getItems().removeAll(proceso.getHerramientas()); listaHerramientas.getItems().addAll(proceso.getHerramientas()); observacionesProceso.setText(proceso.getObservaciones()); }); } @Override public void actualizar() { Platform.runLater(() -> { stage.setTitle(titulo); Maquina maquinaAnterior = cbMaquina.getValue(); cbMaquina.getItems().clear(); Parte parteAnterior = cbParte.getValue(); cbParte.getItems().clear(); String descripcionAnterior = cbDescripcion.getValue(); List<Pieza> piezasAnteriores = listaPiezas.getItems(); cbDescripcion.getItems().clear(); String tipoAnterior = cbTipo.getValue(); cbTipo.getItems().clear(); cbPieza.getItems().clear(); cbHerramienta.getItems().clear(); try{ cbMaquina.getItems().addAll(coordinador.listarMaquinas(new FiltroMaquina.Builder().build())); cbDescripcion.getItems().addAll(coordinador.listarDescripciones(new FiltroDescripcionProceso.Builder().build())); cbTipo.getItems().addAll(coordinador.listarTipos(new FiltroTipoProceso.Builder().build())); cbPieza.getItems().addAll(coordinador.listarPiezas(new FiltroPieza.Builder().build())); cbHerramienta.getItems().addAll(coordinador.listarHerramientas(new FiltroHerramienta.Builder().build())); } catch(PersistenciaException e){ presentadorVentanas.presentarExcepcion(e, stage); } cbMaquina.getSelectionModel().select(maquinaAnterior); //Selecciono la maquina anterior, lo que carga sus partes cbParte.getSelectionModel().select(parteAnterior); //Selecciono la parte anterior, lo que carga sus piezas piezasAnteriores.removeIf(p -> !cbParte.getItems().contains(p)); cbPieza.getItems().removeAll(piezasAnteriores); listaPiezas.getItems().addAll(piezasAnteriores); cbDescripcion.getSelectionModel().select(descripcionAnterior); if(cbDescripcion.getValue() == null && descripcionAnterior != null && !descripcionAnterior.isEmpty()){ cbDescripcion.setValue(descripcionAnterior); } cbTipo.getSelectionModel().select(tipoAnterior); if(cbTipo.getValue() == null && tipoAnterior != null && !tipoAnterior.isEmpty()){ cbTipo.setValue(tipoAnterior); } }); } @Override protected void inicializar() { spHsTTPreparacion.getEditor().setTextFormatter(getTextFormatter()); spHsTTPreparacion.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 10000, 0)); spMsTTPreparacion.getEditor().setTextFormatter(getTextFormatter()); spMsTTPreparacion.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 59, 0)); spSsTTPreparacion.getEditor().setTextFormatter(getTextFormatter()); spSsTTPreparacion.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 59, 0)); spHsTTProceso.getEditor().setTextFormatter(getTextFormatter()); spHsTTProceso.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 10000, 0)); spMsTTProceso.getEditor().setTextFormatter(getTextFormatter()); spMsTTProceso.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 59, 0)); spSsTTProceso.getEditor().setTextFormatter(getTextFormatter()); spSsTTProceso.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 59, 0)); cbMaquina.getSelectionModel().selectedItemProperty().addListener((obs, olvV, newV) -> { cbParte.getItems().clear(); if(newV != null){ try{ cbParte.getItems().addAll(coordinador.listarPartes(new FiltroParte.Builder().maquina(newV).build())); } catch(PersistenciaException e){ presentadorVentanas.presentarExcepcion(e, stage); } } }); cbParte.getSelectionModel().selectedItemProperty().addListener((obs, olvV, newV) -> { cbPieza.getItems().clear(); listaPiezas.getItems().clear(); if(newV != null){ try{ cbPieza.getItems().addAll(coordinador.listarPiezas(new FiltroPieza.Builder().parte(newV).build())); } catch(PersistenciaException e){ presentadorVentanas.presentarExcepcion(e, stage); } } }); actualizar(); } private TextFormatter<Integer> getTextFormatter() { return new TextFormatter<>( new IntegerStringConverter(), 0, c -> { if(c.isContentChange()){ Integer numeroIngresado = null; try{ numeroIngresado = new Integer(c.getControlNewText()); } catch(Exception e){ //No ingreso un entero; } if(numeroIngresado == null){ return null; } } return c; }); } }
package pt.webdetails.cda.dataaccess; import java.util.ArrayList; import java.util.Locale; import java.util.TimeZone; import javax.swing.table.TableModel; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.dom4j.Element; import org.pentaho.reporting.engine.classic.core.ClassicEngineBoot; import org.pentaho.reporting.engine.classic.core.DataFactory; import org.pentaho.reporting.engine.classic.core.DefaultReportEnvironment; import org.pentaho.reporting.engine.classic.core.ParameterDataRow; import org.pentaho.reporting.engine.classic.core.ReportDataFactoryException; import org.pentaho.reporting.engine.classic.core.ReportEnvironmentDataRow; import org.pentaho.reporting.engine.classic.core.parameters.CompoundDataRow; import org.pentaho.reporting.engine.classic.core.states.CachingDataFactory; import org.pentaho.reporting.engine.classic.core.util.CloseableTableModel; import org.pentaho.reporting.engine.classic.core.util.LibLoaderResourceBundleFactory; import org.pentaho.reporting.libraries.base.config.Configuration; import org.pentaho.reporting.libraries.resourceloader.ResourceKey; import org.pentaho.reporting.libraries.resourceloader.ResourceManager; import org.pentaho.reporting.platform.plugin.PentahoReportEnvironment; import pt.webdetails.cda.CdaEngine; import pt.webdetails.cda.connections.InvalidConnectionException; import pt.webdetails.cda.settings.UnknownConnectionException; public abstract class PREDataAccess extends SimpleDataAccess { private static final Log logger = LogFactory.getLog(PREDataAccess.class); private TableModel tableModel; private CachingDataFactory localDataFactory; public PREDataAccess() { } public PREDataAccess(final Element element) { super(element); } public abstract DataFactory getDataFactory() throws UnknownConnectionException, InvalidConnectionException; @Override protected TableModel performRawQuery(final ParameterDataRow parameterDataRow) throws QueryException { try { final CachingDataFactory dataFactory = new CachingDataFactory(getDataFactory()); final ResourceManager resourceManager = new ResourceManager(); resourceManager.registerDefaults(); final ResourceKey contextKey = getCdaSettings().getContextKey(); final Configuration configuration = ClassicEngineBoot.getInstance().getGlobalConfig(); dataFactory.initialize(configuration, resourceManager, contextKey, new LibLoaderResourceBundleFactory(resourceManager, contextKey, Locale.getDefault(), TimeZone.getDefault())); dataFactory.open(); // fire the query. you always get a tablemodel or an exception. final ReportEnvironmentDataRow environmentDataRow; if (CdaEngine.getInstance().isStandalone()) { environmentDataRow = new ReportEnvironmentDataRow(new DefaultReportEnvironment(configuration)); } else { environmentDataRow = new ReportEnvironmentDataRow(new PentahoReportEnvironment(configuration)); } final TableModel tm = dataFactory.queryData("query", new CompoundDataRow(environmentDataRow, parameterDataRow)); // Store this variable so that we can close it later setLocalDataFactory(dataFactory); setTableModel(tm); return tm; } catch (UnknownConnectionException e) { throw new QueryException("Unknown connection", e); } catch (InvalidConnectionException e) { throw new QueryException("Unknown connection", e); } catch (ReportDataFactoryException e) { throw new QueryException("ReportDataFactoryException : " + e.getMessage() + e.getParent()==null?"":("; Parent exception: " + e.getParent().getMessage()), e); } } public void closeDataSource() throws QueryException { if (localDataFactory == null) { return; } // and at the end, close your tablemodel if it holds on to resources like a resultset if (getTableModel() instanceof CloseableTableModel) { final CloseableTableModel ctm = (CloseableTableModel) getTableModel(); ctm.close(); } // and finally shut down the datafactory to free any connection that may be open. getLocalDataFactory().close(); localDataFactory = null; } public TableModel getTableModel() { return tableModel; } public void setTableModel(final TableModel tableModel) { this.tableModel = tableModel; } public CachingDataFactory getLocalDataFactory() { return localDataFactory; } public void setLocalDataFactory(final CachingDataFactory localDataFactory) { this.localDataFactory = localDataFactory; } /* public static ArrayList<DataAccessConnectionDescriptor> getDataAccessConnectionDescriptors() { ArrayList<DataAccessConnectionDescriptor> descriptor = new ArrayList<DataAccessConnectionDescriptor>(); DataAccessConnectionDescriptor proto = new DataAccessConnectionDescriptor(); proto.addDataAccessProperty(new PropertyDescriptor("Query",PropertyDescriptor.TYPE.STRING,PropertyDescriptor.SOURCE.DATAACCESS)); descriptor.add(proto); return descriptor; } */ @Override public ArrayList<PropertyDescriptor> getInterface() { ArrayList<PropertyDescriptor> properties = super.getInterface(); return properties; } }
package se.raddo.raddose3D.tests; import java.util.HashMap; import org.testng.Assert; import org.testng.annotations.*; import se.raddo.raddose3D.Crystal; import se.raddo.raddose3D.CrystalCuboid; import se.raddo.raddose3D.Wedge; /** * Tests for the Cuboid crystal class. */ public class CrystalCuboidTest { final static double dblRoundingTolerance = 1e-13; /** * Tests value against target. Includes testing for null and nice error * messages */ private void EqualsAssertion(Double value, Double target, String name) { Assert.assertNotNull(value, name + " is null"); Assert.assertTrue(Math.abs(value - target) < dblRoundingTolerance, name + " set incorrectly (" + value + ")"); } @Test(groups = { "advanced" }) /** Checks that a full 360 rotation in P or L makes the crystal invariant, * and that you get correct negatives under 180deg rotation. **/ public void testCuboidCrystalPandL() { final Double ang360 = 360d; final Double ang180 = 180d; HashMap<Object, Object> properties = new HashMap<Object, Object>(); properties.put(Crystal.CRYSTAL_DIM_X, 100d); properties.put(Crystal.CRYSTAL_DIM_Y, 100d); properties.put(Crystal.CRYSTAL_DIM_Z, 100d); properties.put(Crystal.CRYSTAL_RESOLUTION, 0.5d); properties.put(Crystal.CRYSTAL_ANGLE_P, 0d); properties.put(Crystal.CRYSTAL_ANGLE_L, 0d); Crystal c = new CrystalCuboid(properties); properties.put(Crystal.CRYSTAL_ANGLE_P, ang360); properties.put(Crystal.CRYSTAL_ANGLE_L, 0d); Crystal cEquivalentP360 = new CrystalCuboid(properties); // Should be the same as c properties.put(Crystal.CRYSTAL_ANGLE_P, 0d); properties.put(Crystal.CRYSTAL_ANGLE_L, ang360); Crystal cEquivalentL360 = new CrystalCuboid(properties); // Should be the same as c properties.put(Crystal.CRYSTAL_ANGLE_P, ang360); properties.put(Crystal.CRYSTAL_ANGLE_L, ang360); Crystal cEquivalentPL360 = new CrystalCuboid(properties); // Should be the same as c properties.put(Crystal.CRYSTAL_ANGLE_P, ang180); properties.put(Crystal.CRYSTAL_ANGLE_L, 0d); Crystal cP180 = new CrystalCuboid(properties); // (i,j,k) should = c(-i, -j, k) properties.put(Crystal.CRYSTAL_ANGLE_P, 0d); properties.put(Crystal.CRYSTAL_ANGLE_L, ang180); Crystal cL180 = new CrystalCuboid(properties); // (i,j,k) should = c(i , -j, -k) int x = c.getCrystSizeVoxels()[0]; int y = c.getCrystSizeVoxels()[1]; int z = c.getCrystSizeVoxels()[2]; for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { for (int k = 0; k < z; k++) { double id[] = c.getCrystCoord(i, j, k); EqualsAssertion(cEquivalentP360.getCrystCoord(i, j, k)[0], id[0], "P360-x"); EqualsAssertion(cEquivalentP360.getCrystCoord(i, j, k)[1], id[1], "P360-y"); EqualsAssertion(cEquivalentP360.getCrystCoord(i, j, k)[2], id[2], "P360-z"); EqualsAssertion(cEquivalentL360.getCrystCoord(i, j, k)[0], id[0], "L360-x"); EqualsAssertion(cEquivalentL360.getCrystCoord(i, j, k)[1], id[1], "L360-y"); EqualsAssertion(cEquivalentL360.getCrystCoord(i, j, k)[2], id[2], "L360-z"); EqualsAssertion(cEquivalentPL360.getCrystCoord(i, j, k)[0], id[0], "PL360-x"); EqualsAssertion(cEquivalentPL360.getCrystCoord(i, j, k)[1], id[1], "PL360-y"); EqualsAssertion(cEquivalentPL360.getCrystCoord(i, j, k)[2], id[2], "PL360-z"); EqualsAssertion(-1 * cP180.getCrystCoord(i, j, k)[0], id[0], "P180-x"); EqualsAssertion(-1 * cP180.getCrystCoord(i, j, k)[1], id[1], "P180-y"); EqualsAssertion(cP180.getCrystCoord(i, j, k)[2], id[2], "P180-z"); EqualsAssertion(cL180.getCrystCoord(i, j, k)[0], id[0], "L180-x"); EqualsAssertion(-1 * cL180.getCrystCoord(i, j, k)[1], id[1], "L180-y"); EqualsAssertion(-1 * cL180.getCrystCoord(i, j, k)[2], id[2], "L180-z"); } } } System.out.println("@Test - testCuboidCrystalPandL"); } //This should work now... Am going to tart up Wedge and have another go. @Test(groups = { "advanced" }) public static void testFindDepthSymmetry() { HashMap<Object, Object> properties = new HashMap<Object, Object>(); properties.put(Crystal.CRYSTAL_DIM_X, 100d); properties.put(Crystal.CRYSTAL_DIM_Y, 100d); properties.put(Crystal.CRYSTAL_DIM_Z, 100d); properties.put(Crystal.CRYSTAL_RESOLUTION, 1d); properties.put(Crystal.CRYSTAL_ANGLE_P, 0d); properties.put(Crystal.CRYSTAL_ANGLE_L, 0d); Crystal c = new CrystalCuboid(properties); Wedge w = new Wedge(2d, 0d, 90d, 100d, 0d, 0d, 0d, 0d, 0d, 0d, 0d); /* Some random test coordinates to work on */ double[] testCoords = { 0, 0, 0 };//{ 12.23, 21.56, -44.32}; double[] testInvCoords = { 0, 0, 0 };//{-12.23, 21.56, 44.32}; for (double angles = 0; angles < Math.toRadians(500); angles += Math .toRadians(18.8)) { // Loop over y as well, to make it more thorough //System.out.println(String.format("%n%n angle is %g", angles)); /* Rotating crystal into position */ double[] tempCoords = new double[3]; double[] tempInvCoords = new double[3]; //Debug System.out.println(i+j+k); tempCoords[0] = testCoords[0] * Math.cos(angles) - testCoords[2] * Math.sin(angles); //Rotate X tempCoords[1] = testCoords[1]; tempCoords[2] = testCoords[0] * Math.sin(angles) + testCoords[2] * Math.cos(angles); //Rotate Z /* Symmetry related pair of tempCoords */ tempInvCoords[0] = testInvCoords[0] * Math.cos(angles) - testInvCoords[2] * Math.sin(angles); //Rotate X tempInvCoords[1] = testInvCoords[1]; tempInvCoords[2] = testInvCoords[0] * Math.sin(angles) + testInvCoords[2] * Math.cos(angles); //Rotate Z Assert.assertTrue(Math.abs(tempCoords[1] - tempInvCoords[1]) <= 1e-10, "y does not match under inversion"); if (Math.abs(tempCoords[1] - tempInvCoords[1]) <= 1e-10) System.out.println("y coords match"); // System.out.println("tempcoords = " + tempCoords[0] + ", " + tempCoords[1] + ", " + tempCoords[2]); // System.out.println("tempInvCoords = " + tempInvCoords[0] + ", " + tempInvCoords[1] + ", " + tempInvCoords[2]); // System.out.println("depth tempCoords @ theta = 0: " + c.findDepth(tempCoords, angles, w)); // System.out.println("depth tempInvCoords @ theta = 0: " + c.findDepth(tempInvCoords, angles, w)); // System.out.println("depth tempCoords @ theta = 180: " + c.findDepth(tempCoords, angles + Math.PI, w)); // System.out.println("depth tempInvCoords @ theta = 180: "+ c.findDepth(tempInvCoords, angles + Math.PI, w)); /* um of depths should be constant under 180Deg rotation */ c.setupDepthFinding(angles, w); double sumdepths1 = c.findDepth(tempCoords, angles, w) + c.findDepth(tempInvCoords, angles, w); c.setupDepthFinding(angles + Math.PI, w); double sumdepths2 = c.findDepth(tempCoords, angles + Math.PI, w) + c.findDepth(tempInvCoords, angles + Math.PI, w); // System.out.println("sumdepths1 = " + sumdepths1); // System.out.println("sumdepths2 = " + sumdepths2); double depthDelta = sumdepths1 - sumdepths2; System.out.println("depthdelta = " + depthDelta); Assert.assertTrue(Math.abs(sumdepths1 - sumdepths2) <= 1e-10, "depths are not matched under symmetry"); } } @Test(groups = { "advanced" }) public static void testFindDepth() { int xdim = 90; int ydim = 74; int zdim = 40; Double resolution = 0.5d; // make a new map for a Cuboid Crystal, dimensions 90 x 74 x 40 um, // 0.5 voxels per um, no starting rotation. HashMap<Object, Object> properties = new HashMap<Object, Object>(); properties.put(Crystal.CRYSTAL_DIM_X, Double.valueOf(xdim)); properties.put(Crystal.CRYSTAL_DIM_Y, Double.valueOf(ydim)); properties.put(Crystal.CRYSTAL_DIM_Z, Double.valueOf(zdim)); properties.put(Crystal.CRYSTAL_RESOLUTION, resolution); properties.put(Crystal.CRYSTAL_ANGLE_P, 0d); properties.put(Crystal.CRYSTAL_ANGLE_L, 0d); Crystal c = new CrystalCuboid(properties); // create a new wedge with no rotation at 100 seconds' exposure // (doesn't matter) Wedge w = new Wedge(0d, 0d, 0d, 100d, 0d, 0d, 0d, 0d, 0d, 0d, 0d); // beam is along z axis. So when the crystal is not rotated, the // maximum depth along the z axis should be zdim um (length of crystal). double[] crystCoords; // this coordinate is in voxel coordinates. // this translates to bottom left corner of the crystal // in crystCoords (-45, -37, -20) // and should therefore be first to intercept the beam and have // a depth of 0. for (int x = 0; x < xdim * resolution; x++) { for (int y = 0; y < ydim * resolution; y++) { for (int z = 0; z < zdim * resolution; z++) { crystCoords = c.getCrystCoord(x, y, z); Assertion.equals(crystCoords[0], -(xdim / 2) + (x / resolution), "crystal coordinate x axis"); Assertion.equals(crystCoords[1], -(ydim / 2) + (y / resolution), "crystal coordinate y axis"); Assertion.equals(crystCoords[2], -(zdim / 2) + (z / resolution), "crystal coordinate z axis"); c.setupDepthFinding(0, w); double depth = c.findDepth(crystCoords, 0, w); // The depth finding overestimates by 10/resolution :( // depth -= (10 / resolution); // Because the crystal has not been rotated, // the depth should just be z / resolution Assertion.equals(depth, z / resolution, "depth at z=" + z); } } } } }
package com.abnormalentropy; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Comparator; public class LinqListTest { private static final Logger LOGGER = LoggerFactory.getLogger(LinqListTest.class); @Test public void constructionTest() { LOGGER.info("Running construction test"); LinqList<Integer> linqList = new LinqList<Integer>(); Assert.assertEquals(0, linqList.size()); linqList.add(2); linqList.add(3); linqList.add(4); Assert.assertEquals(3, linqList.size()); linqList.remove(0); Assert.assertEquals(2, linqList.size()); } @Test public void listConstructionTest() { LOGGER.info("Running list construction test"); ArrayList<Integer> arrayList = new ArrayList<Integer>(); arrayList.add(0); arrayList.add(1); arrayList.add(2); LinqList<Integer> linqList = new LinqList<Integer>(); linqList.addAll(arrayList); Assert.assertEquals(arrayList.size(), linqList.size()); } @Test public void whereGreaterThanTest() { LOGGER.info("Running where lambda (greater than) test"); LinqList<Integer> linqList = new LinqList<Integer>(); linqList.add(0); linqList.add(1); linqList.add(2); linqList.add(3); LinqList<Integer> newList = linqList.where(x -> x >= 2); LOGGER.debug(newList.toString()); Assert.assertEquals(2, newList.size()); Assert.assertEquals(2, newList.get(0).intValue()); Assert.assertEquals(3, newList.get(1).intValue()); } @Test public void whereLessThanTest() { LOGGER.info("Running where lambda (less than) test"); LinqList<Integer> linqList = new LinqList<Integer>(); linqList.add(0); linqList.add(1); linqList.add(2); linqList.add(3); LinqList<Integer> newList = linqList.where(x -> x < 2); LOGGER.debug(newList.toString()); Assert.assertEquals(2, newList.size()); Assert.assertEquals(0, newList.get(0).intValue()); Assert.assertEquals(1, newList.get(1).intValue()); } @Test public void whereBoundedTest() { LOGGER.info("Running where lambda (bounded) test"); LinqList<Integer> linqList = new LinqList<Integer>(); linqList.add(0); linqList.add(1); linqList.add(2); linqList.add(3); LinqList<Integer> newList = linqList.where(x -> x >= 1 && x <= 2); LOGGER.debug(newList.toString()); Assert.assertEquals(2, newList.size()); Assert.assertEquals(1, newList.get(0).intValue()); Assert.assertEquals(2, newList.get(1).intValue()); } @Test public void anyExistsTest() { LOGGER.info("Running any exists test"); LinqList<Integer> linqList = new LinqList<Integer>(); linqList.add(0); linqList.add(1); linqList.add(2); linqList.add(3); Assert.assertEquals(true, linqList.any(x -> x == 2)); Assert.assertEquals(false, linqList.any(x -> x == 5)); Assert.assertEquals(true, linqList.any(x -> x != 5)); } @Test public void allTest() { LOGGER.info("Running 'all' method test"); LinqList<Integer> linqList = new LinqList<Integer>(); linqList.add(0); linqList.add(1); linqList.add(2); linqList.add(3); Assert.assertEquals(true, linqList.all(x -> x > -1)); Assert.assertEquals(false, linqList.all(x -> x < 2)); } @Test public void comparatorContainsTest() { LOGGER.info("Running custom comparator contains test"); LinqList<Integer> linqList = new LinqList<Integer>(); linqList.add(0); linqList.add(1); linqList.add(2); linqList.add(3); Comparator<Integer> comparator = Comparator.comparing(Object::toString); Assert.assertEquals(true, linqList.contains(2, comparator)); Assert.assertEquals(false, linqList.contains(10, comparator)); } @Test public void unionTest() { LOGGER.info("Running union test"); LinqList<Integer> linqList = new LinqList<Integer>(); linqList.add(0); linqList.add(1); linqList.add(2); linqList.add(3); LinqList<Integer> linqList2 = new LinqList<Integer>(); linqList2.add(0); linqList2.add(1); linqList2.add(2); linqList2.add(3); LinqList<Integer> union = linqList.union(linqList2); LOGGER.debug(union.toString()); Assert.assertEquals(linqList.size(), union.size()); linqList2.add(5); union = linqList.union(linqList2); Assert.assertEquals(5, union.size()); LOGGER.debug(union.toString()); } }
import junit.framework.TestCase; import org.apache.log4j.Logger; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class GoldSitesTest extends TestCase { private static final Logger logger = Logger.getLogger(GoldSitesTest.class); public void testHuffingtonPost() { ContentExtractor contentExtractor = new ContentExtractor(); String url = "http: Article article = contentExtractor.extractContent(url); assertEquals("Federal Reserve's Low Rate Policy Is A 'Dangerous Gamble,' Says Top Central Bank Official", article.getTitle()); assertEquals("federal, reserve's, low, rate, policy, is, a, 'dangerous, gamble,', says, top, central, bank, official, business", article.getMetaKeywords()); assertEquals("A top regional Federal Reserve official sharply criticized Friday the Fed's ongoing policy of keeping interest rates near zero -- and at record lows -- as a \"dangerous gamble.\"", article.getMetaDescription()); assertTrue(article.getCleanedArticleText().startsWith("A top regional Federal Reserve official sharply")); } public void testTechCrunch() { ContentExtractor contentExtractor = new ContentExtractor(); String url = "http://techcrunch.com/2010/08/13/gantto-takes-on-microsoft-project-with-web-based-project-management-application/"; Article article = contentExtractor.extractContent(url); assertEquals("Gantto Takes On Microsoft Project With Web-Based Project Management Application", article.getTitle()); assertTrue(article.getCleanedArticleText().startsWith("Y Combinator-backed Gantto is launching")); assertTrue(article.getTopImage().getImageSrc().equals("http://tctechcrunch.files.wordpress.com/2010/08/tour.jpg")); } public void testCNN() { ContentExtractor contentExtractor = new ContentExtractor(); String url = "http: Article article = contentExtractor.extractContent(url); assertEquals("Democrats to use Social Security against GOP this fall", article.getTitle()); assertTrue(article.getCleanedArticleText().startsWith("Washington (CNN) -- Democrats pledged ")); assertTrue(article.getTopImage().getImageSrc().equals("http://i.cdn.turner.com/cnn/2010/POLITICS/08/13/democrats.social.security/story.kaine.gi.jpg")); } public void testBusinessWeek() { String url = "http: ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertEquals("Olivia Munn: Queen of the Uncool", article.getTitle()); assertTrue(article.getCleanedArticleText().startsWith("Six years ago, Olivia Munn arrived in Hollywood with fading ambitions of making it as a sports reporter and set about deploying")); assertTrue(article.getTopImage().getImageSrc().equals("http://images.businessweek.com/mz/10/34/370/1034_mz_66popmunnessa.jpg")); } public void testBusinessWeek2() { String url = "http: ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("There's discord on Wall Street: Strategists at major American investment banks see a")); assertTrue(article.getTopImage().getImageSrc().equals("http://images.businessweek.com/mz/covers/current_120x160.jpg")); } public void testFoxNews() { String url = "http: ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("Russia's announcement that it will help Iran get nuclear fuel is raising questions")); assertTrue(article.getTopImage().getImageSrc().equals("http://a57.foxnews.com/static/managed/img/Politics/397/224/startsign.jpg")); } public void testAOLNews() { String url = "http: ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("WASHINGTON (Aug. 13) -- Declaring &quot;the maritime soul of the Marine Corps")); assertTrue(article.getTopImage().getImageSrc().equals("http://o.aolcdn.com/photo-hub/news_gallery/6/8/680919/1281734929876.JPEG")); } public void testWallStreetJournal() { String url = "http://online.wsj.com/article/SB10001424052748704532204575397061414483040.html"; ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("The Obama administration has paid out less than a third of the nearly $230 billion")); assertTrue(article.getTopImage().getImageSrc().equals("http://si.wsj.net/public/resources/images/OB-JO747_stimul_G_20100814113803.jpg")); } public void testUSAToday() { String url = "http://content.usatoday.com/communities/thehuddle/post/2010/08/brett-favre-practices-set-to-speak-about-return-to-minnesota-vikings/1"; ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("Brett Favre couldn't get away from the")); assertTrue(article.getTopImage().getImageSrc().equals("http://i.usatoday.net/communitymanager/_photos/the-huddle/2010/08/18/favrespeaksx-inset-community.jpg")); } public void testUSAToday2() { String url = "http://content.usatoday.com/communities/driveon/post/2010/08/gm-finally-files-for-ipo/1"; ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("General Motors just filed with the Securities and Exchange ")); assertTrue(article.getTopImage().getImageSrc().equals("http://i.usatoday.net/communitymanager/_photos/drive-on/2010/08/18/cruzex-wide-community.jpg")); } public void testESPN() { String url = "http://sports.espn.go.com/espn/commentary/news/story?id=5461430"; ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("If you believe what college football coaches have said about sports")); assertTrue(article.getTopImage().getImageSrc().equals("http://a.espncdn.com/photo/2010/0813/ncf_i_mpouncey1_300.jpg")); } public void testESPN2() { String url = "http://sports.espn.go.com/golf/pgachampionship10/news/story?id=5463456"; ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("SHEBOYGAN, Wis. -- The only number that matters at the PGA Championship")); assertTrue(article.getTopImage().getImageSrc().equals("http://a.espncdn.com/media/motion/2010/0813/dm_100814_pga_rinaldi.jpg")); } public void testWashingtonPost() { String url = "http: ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("The Supreme Court sounded ")); assertTrue(article.getTopImage().getImageSrc().equals("http://media3.washingtonpost.com/wp-dyn/content/photo/2010/10/09/PH2010100904575.jpg")); } public void testGizmodo() { String url = "http://gizmodo.com/5616256/xbox-kinect-gets-its-fight-club"; ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("You love to punch your arms through the air")); assertTrue(article.getTopImage().getImageSrc().equals("http://cache.gawkerassets.com/assets/images/9/2010/08/500x_fighters_uncaged__screenshot_3b__jawbreaker.jpg")); } public void testEngadget() { String url = "http: ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("Streaming and downloading TV content to mobiles is nice")); assertTrue(article.getTopImage().getImageSrc().equals("http: } public void testBoingBoing() { String url = "http: ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("Dr. Laura Schlessinger is leaving radio to regain")); assertTrue(article.getTopImage().getImageSrc().equals("http: } public void testWired() { String url = "http: ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("On November 25, 1980, professional boxing")); assertTrue(article.getTopImage().getImageSrc().equals("http: assertTrue(article.getTitle().equals("Stress Hormones Could Predict Boxing Dominance")); } public void tetGigaOhm() { String url = "http://gigaom.com/apple/apples-next-macbook-an-800-mac-for-the-masses/"; ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("The MacBook Air is a bold move forward ")); assertTrue(article.getTopImage().getImageSrc().equals("http://gigapple.files.wordpress.com/2010/10/macbook-feature.png?w=300&h=200")); } public void testMashable() { String url = "http://mashable.com/2010/08/18/how-tonot-to-ask-someone-out-online/"; ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("Imagine, if you will, a crowded dance floor")); assertTrue(article.getTopImage().getImageSrc().equals("http://mashable.com/wp-content/uploads/2010/07/love.jpg")); } public void testReadWriteWeb() { String url = "http: ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("In the heart of downtown Chandler, Arizona")); assertTrue(article.getTopImage().getImageSrc().equals("http://rww.readwriteweb.netdna-cdn.com/start/images/pagelyscreen_aug10.jpg")); } public void testVentureBeat() { String url = "http://social.venturebeat.com/2010/08/18/facebook-reveals-the-details-behind-places/"; ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("Facebook just confirmed the rumors")); assertTrue(article.getTopImage().getImageSrc().equals("http://cdn.venturebeat.com/wp-content/uploads/2010/08/mark-zuckerberg-facebook-places.jpg")); } public void testTimeMagazine() { String url = "http: ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("This month, the federal government released")); assertTrue(article.getTopImage().getImageSrc().equals("http://img.timeinc.net/time/daily/2010/1008/bp_oil_spill_0817.jpg")); } public void testCnet() { String url = "http://news.cnet.com/8301-30686_3-20014053-266.html?tag=topStories1"; ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("NEW YORK--Verizon Communications is prepping a new")); assertTrue(article.getTopImage().getImageSrc().equals("http://i.i.com.com/cnwk.1d/i/tim//2010/08/18/Verizon_iPad_and_live_TV_610x458.JPG")); } public void testYahooNewsEvenThoughTheyFuckedUpDeliciousWeWillTestThemAnyway() { String url = "http://news.yahoo.com/s/ap/20101030/ap_on_el_se/us_nevada_senate"; ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("CARSON CITY, Nev. &ndash; Nevada's dead heat Senate race converged")); assertTrue(article.getTopImage().getImageSrc().equals("http://d.yimg.com/a/p/ap/20101030/capt.de99c9f6a76445fc885bb7bd00e45337-de99c9f6a76445fc885bb7bd00e45337-0.jpg?x=213&y=320&xc=1&yc=1&wc=272&hc=409&q=85&sig=P22sGCwd_PZ558JFQg79vQ--")); } public void testPolitico() { String url = "http: ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("If the newest Census Bureau estimates stay close to form")); assertTrue(article.getTopImage().getImageSrc().equals("http://images.politico.com/global/news/100927_obama22_ap_328.jpg")); } public void testNewsweek() { String url = "http: ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("At first glance, Kadyrov might seem")); assertTrue(article.getTopImage().getImageSrc().equals("http: } public void testLifeHacker() { String url = "http://lifehacker.com/5659837/build-a-rocket-stove-to-heat-your-home-with-wood-scraps"; ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("If you find yourself with lots of leftover wood")); assertTrue(article.getTopImage().getImageSrc().equals("http://cache.gawker.com/assets/images/lifehacker/2010/10/rocket-stove-finished.jpeg")); } public void testNinjaBlog() { String url = "http: ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("Many users around the world Google their queries")); } public void testNaturalHomeBlog() { String url = "http: ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("Guide trick or treaters and other friendly spirits to your front")); assertTrue(article.getTopImage().getImageSrc().equals("http: } public void testSFGate() { String url = "http: ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("Fewer homes in California and")); assertTrue(article.getTopImage().getImageSrc().equals("http://imgs.sfgate.com/c/pictures/2010/10/26/ba-foreclosures2_SFCG1288130091.jpg")); } public void testSportsIllustrated() { String url = "http://sportsillustrated.cnn.com/2010/football/ncaa/10/15/ohio-state-holmes.ap/index.html?xid=si_ncaaf"; ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("COLUMBUS, Ohio (AP) -- Ohio State has closed")); assertTrue(article.getTopImage().getImageSrc().equals("http://i.cdn.turner.com/si/.e1d/img/4.0/global/logos/si_100x100.jpg")); } // todo get this one working - I hate star magazine web designers, they put 2 html files into one // public void testStarMagazine() { // ContentExtractor contentExtractor = new ContentExtractor(); // Article article = contentExtractor.extractContent(url); // assertTrue(article.getCleanedArticleText().startsWith("The Real Reason Rihanna Skipped Katy's Wedding: No Cell Phone Reception!")); // assertTrue(article.getTopImage().getImageSrc().equals("Rihanna has admitted the real reason she was a no show")); public void testDailyBeast() { String url = "http: ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("Legendary Kennedy speechwriter Ted Sorensen passed")); assertTrue(article.getTopImage().getImageSrc().equals("http: } public void testBloomberg() { String url = "http: ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("The Chinese entrepreneur and the Peruvian shopkeeper")); assertTrue(article.getTopImage().getImageSrc().equals("http: } public void testScientificDaily() { String url = "http: ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("The common industrial chemical bisphenol A (BPA) ")); assertTrue(article.getTopImage().getImageSrc().equals("http: assertTrue(article.getTitle().equals("Everyday BPA Exposure Decreases Human Semen Quality")); } public void testSlamMagazine() { String url = "http: ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("When in doubt, rank players and add your findings")); assertTrue(article.getTopImage().getImageSrc().equals("http: assertTrue(article.getTitle().equals("NBA Schoolyard Rankings")); } public void testTheFrisky() { String url = "http: ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("Rachel Dratch had been keeping the identity of her baby daddy ")); assertTrue(article.getTopImage().getImageSrc().equals("http://cdn.thefrisky.com/images/uploads/rachel_dratch_102810_m.jpg")); assertTrue(article.getTitle().equals("Rachel Dratch Met Her Baby Daddy At A Bar")); } public void testUniverseToday() { String url = "http: ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("I had the chance to interview LCROSS")); assertTrue(article.getTopImage().getImageSrc().equals("http: assertTrue(article.getTitle().equals("More From Tony Colaprete on LCROSS")); } public void testValleyWag() { String url = "http://valleywag.gawker.com/5709823/apple-has-no-idea-where-steve-jobs-is"; ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("Does anyone know where Steve Jobs is? ")); assertTrue(article.getTopImage().getImageSrc().equals("http://cache.gawker.com/assets/images/gawker/2010/12/jobs.jpg")); assertTrue(article.getTitle().equals("Apple Has No Idea Where Steve Jobs Is")); } public void testCNBC() { String url = "http: ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("A prominent expert on Chinese works ")); assertTrue(article.getTopImage().getImageSrc().equals("http://media.cnbc.com/i/CNBC/Sections/News_And_Analysis/__Story_Inserts/graphics/__ART/chinese_vase_150.jpg")); assertTrue(article.getTitle().equals("Chinese Art Expert 'Skeptical' of Record-Setting Vase")); } public void testEspnWithFlashVideo() { String url = "http://sports.espn.go.com/nfl/news/story?id=5971053"; ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("PHILADELPHIA -- Michael Vick missed practice Thursday")); assertTrue(article.getTopImage().getImageSrc().equals("http://a.espncdn.com/media/motion/2010/1229/com_101229nfl_CDDAccu_DAL_PHI.jpg")); assertTrue(article.getTitle().equals("Michael Vick of Philadelphia Eagles misses practice, unlikely to play vs. Dallas Cowboys")); } public void testSportingNews() { String url = "http: ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("ALAMEDA, Calif. &mdash; The Oakland Raiders informed coach Tom Cable")); assertTrue(article.getTopImage().getImageSrc().equals("http://dy.snimg.com/story-image/0/69/174475/14072-650-366.jpg")); assertTrue(article.getTitle().equals("Raiders cut ties with Cable")); } public void testFoxSports() { String url = "http://msn.foxsports.com/nfl/story/Tom-Cable-fired-contract-option-Oakland-Raiders-coach-010411"; ContentExtractor contentExtractor = new ContentExtractor(); Article article = contentExtractor.extractContent(url); assertTrue(article.getCleanedArticleText().startsWith("The Oakland Raiders informed coach Tom Cable")); assertTrue(article.getTopImage().getImageSrc().equals("http://o.static.foxsports.com/content/fscom/img/2010/11/19/111910-NFL-Carolina-Panthers-John-Fox-PI_20101119122646_202_97.JPG")); assertTrue(article.getTitle().equals("Oakland Raiders won't bring Tom Cable back as coach - NFL News")); } }
package nl.homesensors; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import java.math.BigDecimal; import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Test; import nl.homesensors.smartmeter.Dsmr422Parser; import nl.homesensors.smartmeter.SmartMeterMessage; public class Dsmr422ParserTest { private Dsmr422Parser dsmr422Parser; @Before public void setup() { this.dsmr422Parser = new Dsmr422Parser(); } @Test public void shouldParseValidMessage1() throws Exception { final String message = IOUtils.toString(this.getClass().getResourceAsStream("message-4.2.2-1.txt"), StandardCharsets.UTF_8); final SmartMeterMessage smartMeterMessage = dsmr422Parser.parse(message); assertThat(smartMeterMessage).isNotNull(); assertThat(smartMeterMessage.getHeader()).isEqualTo("KFM5KAIFA-METER"); assertThat(smartMeterMessage.getVersionInformationForP1Output()).isEqualTo("42"); assertThat(smartMeterMessage.getTimestamp()).isEqualTo(LocalDateTime.of(2017, 2, 24, 19, 31,18)); assertThat(smartMeterMessage.getTimestampDstIndicator()).isEqualTo(SmartMeterMessage.DstIndicator.WINTER); assertThat(smartMeterMessage.getEquipmentIdentifierElectricity()).isEqualTo("4530303235303030303738363130313136"); assertThat(smartMeterMessage.getMeterReadingElectricityDeliveredToClientTariff1()).isEqualTo(new BigDecimal("1.628")); assertThat(smartMeterMessage.getMeterReadingElectricityDeliveredToClientTariff2()).isEqualTo(new BigDecimal("5.573")); assertThat(smartMeterMessage.getMeterReadingElectricityDeliveredByClientTariff1()).isEqualTo(new BigDecimal("1.301")); assertThat(smartMeterMessage.getMeterReadingElectricityDeliveredByClientTariff2()).isEqualTo(new BigDecimal("2.050")); assertThat(smartMeterMessage.getTariffIndicatorElectricity()).isEqualTo(2); assertThat(smartMeterMessage.getActualElectricityPowerDelivered()).isEqualTo(new BigDecimal("0.042")); assertThat(smartMeterMessage.getActualElectricityPowerRecieved()).isEqualTo(new BigDecimal("0.000")); assertThat(smartMeterMessage.getNumberOfPowerFailuresInAnyPhase()).isEqualTo(1); assertThat(smartMeterMessage.getNumberOfLongPowerFailuresInAnyPhase()).isEqualTo(1); assertThat(smartMeterMessage.getNumberOfVoltageSagsInPhaseL1()).isEqualTo(10); assertThat(smartMeterMessage.getNumberOfVoltageSagsInPhaseL2()).isEqualTo(2); assertThat(smartMeterMessage.getTextMessageCodes()).isEqualTo(null); assertThat(smartMeterMessage.getTextMessage()).isEqualTo(null); assertThat(smartMeterMessage.getInstantaneousCurrentL1()).isEqualTo(0); assertThat(smartMeterMessage.getInstantaneousActivePowerL1()).isEqualTo(new BigDecimal("0.042")); assertThat(smartMeterMessage.getInstantaneousActivePowerL2()).isEqualTo(new BigDecimal("0.000")); assertThat(smartMeterMessage.getEquipmentIdentifierGas()).isEqualTo("4730303235303033353032393639333137"); assertThat(smartMeterMessage.getLastHourlyValueOfTemperatureConvertedGasDeliveredToClient()).isEqualTo(new BigDecimal("13.027")); assertThat(smartMeterMessage.getLastHourlyValueOfTemperatureConvertedGasDeliveredToClientCaptureTimestamp()).isEqualTo(LocalDateTime.of(2017, 2, 24, 19, 0,0)); assertThat(smartMeterMessage.getLastHourlyValueOfTemperatureConvertedGasDeliveredToClientCaptureTimestampDstIndicator()).isEqualTo(SmartMeterMessage.DstIndicator.WINTER); assertThat(smartMeterMessage.getLongPowerFailureLog()).hasSize(1); assertThat(smartMeterMessage.getLongPowerFailureLog().get(0).getTimestampOfEndOfFailure()).isEqualTo(LocalDateTime.of(2016, 8, 15, 13, 51, 47)); assertThat(smartMeterMessage.getLongPowerFailureLog().get(0).getTimestampOfEndOfFailureDstIndicator()).isEqualTo(SmartMeterMessage.DstIndicator.SUMMER); assertThat(smartMeterMessage.getLongPowerFailureLog().get(0).getFailureDurationInSeconds()).isEqualTo(647L); } @Test public void shouldParseValidMessage2() throws Exception { final String message = IOUtils.toString(this.getClass().getResourceAsStream("message-4.2.2-2.txt"), StandardCharsets.UTF_8); final SmartMeterMessage smartMeterMessage = dsmr422Parser.parse(message); assertThat(smartMeterMessage.getLongPowerFailureLog()).hasSize(2); } @Test public void shouldParseValidMessage3() throws Exception { final String message = IOUtils.toString(this.getClass().getResourceAsStream("message-4.2.2-3.txt"), StandardCharsets.UTF_8); final SmartMeterMessage smartMeterMessage = dsmr422Parser.parse(message); assertThat(smartMeterMessage.getActualElectricityPowerDelivered()).isEqualTo(new BigDecimal("0.453")); } @Test public void shouldParseValidMessage4() throws Exception { final String message = IOUtils.toString(this.getClass().getResourceAsStream("message-4.2.2-4.txt"), StandardCharsets.UTF_8); final SmartMeterMessage smartMeterMessage = dsmr422Parser.parse(message); assertThat(smartMeterMessage.getActualElectricityPowerDelivered()).isEqualTo(new BigDecimal("0.454")); } @Test public void shouldFailParseValidMessageFoundOnInternetWithWrongVersion() throws Exception { final String message = IOUtils.toString(this.getClass().getResourceAsStream("message-4.0-from-internet.txt"), StandardCharsets.UTF_8); assertThatExceptionOfType(Dsmr422Parser.UnsupportedVersionException.class).isThrownBy(() -> dsmr422Parser.parse(message) ).withMessageStartingWith("Unsupported DSMR version"); } @Test public void shouldParseValidMessageFromSpecifiation() throws Exception { final String message = IOUtils.toString(this.getClass().getResourceAsStream("message-4.2.2-from-P1-specification.txt"), StandardCharsets.UTF_8); final SmartMeterMessage smartMeterMessage = dsmr422Parser.parse(message); assertThat(smartMeterMessage.getTextMessageCodes()).isEqualTo("01 61 81"); assertThat(smartMeterMessage.getTextMessage()).isEqualTo("0123456789:;<=>?0123456789:;<=>?0123456789:;<=>?0123456789:;<=>?0123456789:;<=>?"); } @Test public void invalidCrc() throws Exception { final String message = IOUtils.toString(this.getClass().getResourceAsStream("message-4.2.2-invalid-crc.txt"), StandardCharsets.UTF_8); assertThatExceptionOfType(Dsmr422Parser.InvalidSmartMeterMessageException.class).isThrownBy(() -> dsmr422Parser.parse(message) ).withMessageStartingWith("CRC checksum failed"); } }
package org.amc.game.chess; import static org.junit.Assert.assertTrue; import org.amc.game.chess.view.ChessBoardView; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class PawnPieceTest extends ChessPieceTest { private ChessBoard board; private String whiteStart = "F2"; private String blackStart = "F7"; private static final String[] invalidWhiteMovesFromF2 = { "F1", "E1", "E2", "G2", "G1", "E4", "G4", "F5", "D4", "H4", "H1" }; private static final String[] invalidBlackMovesFromF7 = { "F8", "E8", "E7", "G7", "G8", "E5", "G5", "F4", "D5", "H5", "H8" }; @Before public void setUp() { board = new ChessBoard(); setChessBoard(board); } @Test @Override public void testCanSlide() { assertTrue(PawnPiece.getPiece(Colour.BLACK).canSlide()); } @Test public void testIsMovingForwardOneSquareOnly() { PawnPiece pawn = PawnPiece.getPiece(Colour.WHITE); pawn.moved(); placeOnBoard(pawn, whiteStart); String endLocationOne = "F3"; assertTrue(pawn.isValidMove(board, newMove(whiteStart, endLocationOne))); } @Test public void testMoveBackOneSquare() { PawnPiece pawn = PawnPiece.getPiece(Colour.WHITE); pawn.moved(); placeOnBoard(pawn, whiteStart); String endLocationOne = "F1"; assertFalse(pawn.isValidMove(board, newMove(whiteStart, endLocationOne))); } @Test public void testMoveNoSquare() { PawnPiece pawn = PawnPiece.getPiece(Colour.WHITE); String startLocation = "F3"; placeOnBoard(pawn, startLocation); String endLocationOne = "F3"; assertFalse(pawn.isValidMove(board, newMove(startLocation, endLocationOne))); } @Override @Test public void testOnEmptyBoardIsValidMove() throws Exception { testOnEmptyBoardIsValidBlackMove(); testOnEmptyBoardIsValidWhiteMove(); } @Override @Test public void testOnEmptyBoardIsNotValidMove() throws Exception { testOnEmptyBoardIsNotValidBlackMove(); testOnEmptyBoardIsNotValidWhiteMove(); testOnEmptyBoardIsNotValidNonIntialWhiteMove(); testOnEmptyBoardIsNotValidNonIntialBlackMove(); } @Override @Test public void testOnBoardIsValidCapture() throws Exception { testOnBoardIsValidBlackCapture(); testOnBoardIsValidWhiteCapture(); } @Override @Test public void testOnBoardInvalidCapture() throws Exception { testOnBoardInvalidBlackCapture(); testOnBoardInvalidWhiteCapture(); } @Override @Test public void testOnBoardIsNotValidMove() throws Exception { testOnBoardIsNotValidWhiteMove(); testOnBoardIsNotValidBlackMove(); } @Test public void testOnBoardIsNotValidBlackMove2() { PawnPiece pawn = PawnPiece.getPiece(Colour.BLACK); PawnPiece enemyPawn = PawnPiece.getPiece(Colour.WHITE); placeOnBoard(pawn, blackStart); String endLocationOne = "F6"; String endLocationTwo = "F5"; placeOnBoard(enemyPawn, endLocationTwo); new ChessBoardView(board).displayTheBoard(); assertTrue(pawn.isValidMove(board, newMove(blackStart, endLocationOne))); assertFalse(pawn.isValidMove(board, newMove(blackStart, endLocationTwo))); } private void testOnEmptyBoardIsValidWhiteMove() { setUp(); PawnPiece pawn = PawnPiece.getPiece(Colour.WHITE); placeOnBoard(pawn, whiteStart); assertTrue(pawn.isValidMove(board, newMove(whiteStart, "F3"))); assertTrue(pawn.isValidMove(board, newMove(whiteStart, "F4"))); } private Move newMove(String start, String end) { return new Move(start + Move.LOCATION_SEPARATOR + end); } private void testOnEmptyBoardIsValidBlackMove() { setUp(); PawnPiece pawn = PawnPiece.getPiece(Colour.BLACK); placeOnBoard(pawn, (blackStart)); assertTrue(pawn.isValidMove(board, newMove(blackStart, "F6"))); assertTrue(pawn.isValidMove(board, newMove(blackStart, "F5"))); } private void testOnEmptyBoardIsNotValidWhiteMove() { setUp(); PawnPiece pawn = PawnPiece.getPiece(Colour.WHITE); placeOnBoard(pawn, whiteStart); for (String endLocation : invalidWhiteMovesFromF2) { assertFalse(pawn.isValidMove(board, newMove(whiteStart, endLocation))); } } private void testOnEmptyBoardIsNotValidBlackMove() { setUp(); PawnPiece pawn = PawnPiece.getPiece(Colour.BLACK); placeOnBoard(pawn, blackStart); for (String endLocation : invalidBlackMovesFromF7) { assertFalse(pawn.isValidMove(board, newMove(blackStart, endLocation))); } } private void testOnEmptyBoardIsNotValidNonIntialWhiteMove() { setUp(); PawnPiece pawn = PawnPiece.getPiece(Colour.WHITE); pawn = (PawnPiece)pawn.moved(); placeOnBoard(pawn, whiteStart); String endLocation = "F4"; assertFalse(pawn.isValidMove(board, newMove(whiteStart, endLocation))); } private void testOnEmptyBoardIsNotValidNonIntialBlackMove() { setUp(); PawnPiece pawn = PawnPiece.getPiece(Colour.BLACK); pawn.moved(); placeOnBoard(pawn, blackStart); String endLocation = "F4"; assertFalse(pawn.isValidMove(board, newMove(blackStart, endLocation))); } private void testOnBoardIsValidWhiteCapture() { setUp(); PawnPiece pawn = PawnPiece.getPiece(Colour.WHITE); PawnPiece enemyPawn = PawnPiece.getPiece(Colour.BLACK); String captureLocationOne = "E3"; String captureLocationTwo = "G3"; placeOnBoard(pawn, whiteStart); placeOnBoard(enemyPawn, captureLocationOne); placeOnBoard(enemyPawn, captureLocationTwo); assertTrue(pawn.isValidMove(board, newMove(whiteStart, captureLocationOne))); assertTrue(pawn.isValidMove(board, newMove(whiteStart, captureLocationTwo))); } private void testOnBoardIsValidBlackCapture() { setUp(); PawnPiece pawn = PawnPiece.getPiece(Colour.BLACK); PawnPiece enemyPawn = PawnPiece.getPiece(Colour.WHITE); String captureLocationOne = "E6"; String captureLocationTwo = "G6"; placeOnBoard(pawn, blackStart); placeOnBoard(enemyPawn, captureLocationOne); placeOnBoard(enemyPawn, captureLocationTwo); assertTrue(pawn.isValidMove(board, newMove(blackStart, captureLocationOne))); assertTrue(pawn.isValidMove(board, newMove(blackStart, captureLocationTwo))); } private void testOnBoardInvalidWhiteCapture() { setUp(); PawnPiece pawn = PawnPiece.getPiece(Colour.WHITE); String captureLocationOne = "E3"; String captureLocationTwo = "G3"; placeOnBoard(pawn, whiteStart); placeOnBoard(PawnPiece.getPiece(Colour.WHITE), captureLocationOne); assertFalse(pawn.isValidMove(board, newMove(whiteStart, captureLocationOne))); assertFalse(pawn.isValidMove(board, newMove(whiteStart, captureLocationTwo))); } private void testOnBoardInvalidBlackCapture() { setUp(); PawnPiece pawn = PawnPiece.getPiece(Colour.BLACK); String captureLocationOne = "E6"; String captureLocationTwo = "G6"; placeOnBoard(pawn, blackStart); placeOnBoard(PawnPiece.getPiece(Colour.BLACK), captureLocationOne); assertFalse(pawn.isValidMove(board, newMove(blackStart, captureLocationOne))); assertFalse(pawn.isValidMove(board, newMove(blackStart, captureLocationTwo))); } private void testOnBoardIsNotValidBlackMove() { setUp(); PawnPiece pawn = PawnPiece.getPiece(Colour.BLACK); PawnPiece enemyPawn = PawnPiece.getPiece(Colour.WHITE); placeOnBoard(pawn, blackStart); String endLocationOne = "F6"; String endLocationTwo = "F5"; placeOnBoard(enemyPawn, endLocationOne); assertFalse(pawn.isValidMove(board, newMove(blackStart, endLocationOne))); assertFalse(pawn.isValidMove(board, newMove(blackStart, endLocationTwo))); } private void testOnBoardIsNotValidWhiteMove() { setUp(); PawnPiece pawn = PawnPiece.getPiece(Colour.WHITE); PawnPiece enemyPawn = PawnPiece.getPiece(Colour.BLACK); placeOnBoard(pawn, whiteStart); String endLocationOne = "F3"; String endLocationTwo = "F4"; placeOnBoard(enemyPawn, endLocationOne); assertFalse(pawn.isValidMove(board, newMove(whiteStart, endLocationOne))); assertFalse(pawn.isValidMove(board, newMove(whiteStart, endLocationTwo))); } }
package org.jdesktop.swingx; import javax.swing.tree.TreePath; import junit.framework.TestCase; import org.jdesktop.swingx.util.ComponentTreeTableModel; public class JXTreeTableIssues extends TestCase { /** * sanity: toggling select/unselect via mouse the lead is * always painted, doing unselect via model (clear/remove path) * seems to clear the lead? * */ public void testBasicTreeLeadSelection() { JXTree tree = new JXTree(); TreePath path = tree.getPathForRow(0); tree.setSelectionPath(path); assertEquals(0, tree.getSelectionModel().getLeadSelectionRow()); assertEquals(path, tree.getLeadSelectionPath()); tree.removeSelectionPath(path); assertNotNull(tree.getLeadSelectionPath()); assertEquals(0, tree.getSelectionModel().getLeadSelectionRow()); } /** * Issue #341-swingx: missing synch of lead. * test lead after remove selection via tree. * */ public void testLeadAfterRemoveSelectionFromTree() { JXTreeTable treeTable = prepareTreeTable(true); treeTable.getTreeSelectionModel().removeSelectionPath( treeTable.getTreeSelectionModel().getLeadSelectionPath()); assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(), treeTable.getTreeSelectionModel().getLeadSelectionRow()); } /** * Issue #341-swingx: missing synch of lead. * test lead after clear selection via table. * */ public void testLeadAfterClearSelectionFromTable() { JXTreeTable treeTable = prepareTreeTable(true); treeTable.clearSelection(); assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(), treeTable.getTreeSelectionModel().getLeadSelectionRow()); } /** * Issue #341-swingx: missing synch of lead. * test lead after clear selection via table. * */ public void testLeadAfterClearSelectionFromTree() { JXTreeTable treeTable = prepareTreeTable(true); treeTable.getTreeSelectionModel().clearSelection(); assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(), treeTable.getTreeSelectionModel().getLeadSelectionRow()); } /** * Issue #341-swingx: missing synch of lead. * test lead after setting selection via table. * */ public void testLeadSelectionFromTable() { JXTreeTable treeTable = prepareTreeTable(false); assertEquals(-1, treeTable.getSelectionModel().getLeadSelectionIndex()); assertEquals(-1, treeTable.getTreeSelectionModel().getLeadSelectionRow()); treeTable.setRowSelectionInterval(0, 0); assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(), treeTable.getTreeSelectionModel().getLeadSelectionRow()); } /** * Issue #341-swingx: missing synch of lead. * test lead after setting selection via treeSelection. * */ public void testLeadSelectionFromTree() { JXTreeTable treeTable = prepareTreeTable(false); assertEquals(-1, treeTable.getSelectionModel().getLeadSelectionIndex()); assertEquals(-1, treeTable.getTreeSelectionModel().getLeadSelectionRow()); treeTable.getTreeSelectionModel().setSelectionPath(treeTable.getPathForRow(0)); assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(), treeTable.getTreeSelectionModel().getLeadSelectionRow()); assertEquals(0, treeTable.getTreeSelectionModel().getLeadSelectionRow()); } /** * creates and configures a treetable for usage in selection tests. * * @param selectFirstRow boolean to indicate if the first row should * be selected. * @return */ protected JXTreeTable prepareTreeTable(boolean selectFirstRow) { JXTreeTable treeTable = new JXTreeTable(new ComponentTreeTableModel(new JXFrame())); treeTable.setRootVisible(true); // sanity: assert that we have at least two rows to change selection assertTrue(treeTable.getRowCount() > 1); if (selectFirstRow) { treeTable.setRowSelectionInterval(0, 0); } return treeTable; } public void testDummy() { } }
package uk.org.ownage.dmdirc.ui.input; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JTextField; import uk.org.ownage.dmdirc.Config; /** * Handles events generated by a user typing into a textfield. Allows the user * to use shortcut keys for control characters (ctrl+b, etc), to tab complete * nicknames/channel names/etc, and to scroll through their previously issued * commands. * @author chris */ public class InputHandler implements KeyListener, ActionListener { /** * The current position in the buffer (where the user has scrolled back * to). */ private int bufferPosition; /** * The maximum size of the buffer */ private int bufferSize; /** * The maximum position we've got to in the buffer. This will be the * position that is inserted to next. Note that it will wrap around once * we hit the maximum size. */ private int bufferMaximum; /** * The lowest entry we've used in the buffer */ private int bufferMinimum; /** * The buffer itself */ private String[] buffer; /** * The textfield that we're handling input for */ private JTextField target; /** * The TabCompleter to use for tab completion */ private TabCompleter tabCompleter; /** * Creates a new instance of InputHandler. Adds listeners to the target * that we need to operate. * @param target The text field this input handler is dealing with. */ public InputHandler(JTextField target) { bufferSize = Integer.parseInt(Config.getOption("ui","inputbuffersize")); this.target = target; this.buffer = new String[bufferSize]; bufferPosition = 0; bufferMinimum = 0; bufferMaximum = 0; target.addKeyListener(this); target.addActionListener(this); target.setFocusTraversalKeysEnabled(false); } /** * Sets this input handler's tab completer * @param tabCompleter The new tab completer */ public void setTabCompleter(TabCompleter tabCompleter) { this.tabCompleter = tabCompleter; } /** * Called when the user types a normal character * @param keyEvent The event that was fired */ public void keyTyped(KeyEvent keyEvent) { } /** * Called when the user presses down any key. Handles the insertion of * control codes, tab completion, and scrolling the back buffer. * @param keyEvent The event that was fired */ public void keyPressed(KeyEvent keyEvent) { // Formatting codes if ((keyEvent.getModifiers() & KeyEvent.CTRL_MASK) != 0) { if (keyEvent.getKeyCode() == KeyEvent.VK_B) { append("" + (char)2); } if (keyEvent.getKeyCode() == KeyEvent.VK_U) { append("" + (char)31); } if (keyEvent.getKeyCode() == KeyEvent.VK_O) { append("" + (char)15); } if (keyEvent.getKeyCode() == KeyEvent.VK_K) { append("" + (char)3); } } // Back buffer scrolling if (keyEvent.getKeyCode() == KeyEvent.VK_UP) { if (bufferPosition != bufferMinimum) { bufferPosition = normalise(bufferPosition-1); retrieveBuffer(); } else { // TODO: Beep, or something. } } else if (keyEvent.getKeyCode() == KeyEvent.VK_DOWN) { if (bufferPosition != bufferMaximum) { bufferPosition = normalise(bufferPosition+1); retrieveBuffer(); } else { // TODO: Beep, or something } } // Tab completion if (keyEvent.getKeyCode() == KeyEvent.VK_TAB && tabCompleter != null) { String text = target.getText(); if (text.equals("")) { return; } int pos = target.getCaretPosition()-1; int start = (pos < 0) ? 0 : pos; int end = (pos < 0) ? 0 : pos; // Traverse backwards while (start > 0 && text.charAt(start) != ' ') { start } if (text.charAt(start) == ' ') { start++; } // And forwards while (end < text.length() && text.charAt(end) != ' ') { end++; } if (start > end) { return; } String word = text.substring(start, end); TabCompleterResult res = tabCompleter.complete(word); if (res.getResultCount() == 0) { // TODO: Beep, or something } else if (res.getResultCount() == 1) { // One result, just replace it String result = res.getResults().get(0); text = text.substring(0,start)+result+text.substring(end); target.setText(text); target.setCaretPosition(start+result.length()); } else { // Multiple results String sub = res.getBestSubstring(); if (sub == word) { // TODO: Beep, display possible answers, etc } else { text = text.substring(0,start)+sub+text.substring(end); target.setText(text); target.setCaretPosition(start+sub.length()); } } } } /** * Called when the user releases any key * @param keyEvent The event that was fired */ public void keyReleased(KeyEvent keyEvent) { } /** * Called when the user presses return in the text area. The line they * typed is added to the buffer for future use. * @param actionEvent The event that was fired */ public void actionPerformed(ActionEvent actionEvent) { buffer[bufferMaximum] = actionEvent.getActionCommand(); bufferMaximum = normalise(bufferMaximum + 1); bufferPosition = bufferMaximum; if (buffer[bufferSize-1] != null) { bufferMinimum = normalise(bufferMaximum + 1); buffer[bufferMaximum] = null; } } /** * Appends the specified string to the end of the textbox * @param string The string to be appeneded */ private void append(String string) { target.setText(target.getText()+string); } /** * Retrieves the buffered text stored at the position indicated by * bufferPos, and replaces the current textbox content with it */ private void retrieveBuffer() { target.setText(buffer[bufferPosition]); } /** * Normalises the input so that it is in the range 0 <= x < bufferSize. * @param input The number to normalise * @return The normalised number */ private int normalise(int input) { while (input < 0) { input = input + bufferSize; } return (input % bufferSize); } }
package com.esotericsoftware.kryo; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.nio.ByteBuffer; import java.util.Random; import com.esotericsoftware.kryo.io.ByteBufferInputStream; import com.esotericsoftware.kryo.io.ByteBufferOutput; import com.esotericsoftware.kryo.io.ByteBufferOutputStream; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; /** @author Nathan Sweet <misc@n4te.com> */ public class InputOutputTest extends KryoTestCase { public void testOutputStream () throws IOException { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); Output output = new Output(buffer, 2); output.writeBytes(new byte[] {11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26}); output.writeBytes(new byte[] {31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46}); output.writeBytes(new byte[] {51, 52, 53, 54, 55, 56, 57, 58}); output.writeBytes(new byte[] {61, 62, 63, 64, 65}); output.flush(); assertEquals(new byte[] { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 51, 52, 53, 54, 55, 56, 57, 58, 61, 62, 63, 64, 65}, buffer.toByteArray()); } public void testInputStream () throws IOException { byte[] bytes = new byte[] { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 51, 52, 53, 54, 55, 56, 57, 58, 61, 62, 63, 64, 65}; ByteArrayInputStream buffer = new ByteArrayInputStream(bytes); Input input = new Input(buffer, 2); byte[] temp = new byte[1024]; int count = input.read(temp, 512, bytes.length); assertEquals(bytes.length, count); byte[] temp2 = new byte[count]; System.arraycopy(temp, 512, temp2, 0, count); assertEquals(bytes, temp2); input = new Input(bytes); count = input.read(temp, 512, 512); assertEquals(bytes.length, count); temp2 = new byte[count]; System.arraycopy(temp, 512, temp2, 0, count); assertEquals(bytes, temp2); } public void testWriteBytes () throws IOException { Output buffer = new Output(512); buffer.writeBytes(new byte[] {11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26}); buffer.writeBytes(new byte[] {31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46}); buffer.writeByte(51); buffer.writeBytes(new byte[] {52, 53, 54, 55, 56, 57, 58}); buffer.writeByte(61); buffer.writeByte(62); buffer.writeByte(63); buffer.writeByte(64); buffer.writeByte(65); buffer.flush(); assertEquals(new byte[] { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 51, 52, 53, 54, 55, 56, 57, 58, 61, 62, 63, 64, 65}, buffer.toBytes()); } public void testStrings () throws IOException { runStringTest(new Output(4096)); runStringTest(new Output(897)); runStringTest(new Output(new ByteArrayOutputStream())); Output write = new Output(21); String value = "abcdef\u00E1\u00E9\u00ED\u00F3\u00FA\u1234"; write.writeString(value); Input read = new Input(write.toBytes()); assertEquals(value, read.readString()); write.clear(); write.writeString(null); read = new Input(write.toBytes()); assertEquals(null, read.readString()); for (int i = 0; i <= 258; i++) runStringTest(i); runStringTest(1); runStringTest(2); runStringTest(127); runStringTest(256); runStringTest(1024 * 1023); runStringTest(1024 * 1024); runStringTest(1024 * 1025); runStringTest(1024 * 1026); runStringTest(1024 * 1024 * 2); } public void runStringTest (int length) throws IOException { Output write = new Output(1024, -1); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < length; i++) buffer.append((char)i); String value = buffer.toString(); write.writeString(value); write.writeString(value); Input read = new Input(write.toBytes()); assertEquals(value, read.readString()); assertEquals(value, read.readStringBuilder().toString()); write.clear(); write.writeString(buffer); write.writeString(buffer); read = new Input(write.toBytes()); assertEquals(value, read.readStringBuilder().toString()); assertEquals(value, read.readString()); if (length <= 127) { write.clear(); write.writeAscii(value); write.writeAscii(value); read = new Input(write.toBytes()); assertEquals(value, read.readStringBuilder().toString()); assertEquals(value, read.readString()); } } public void runStringTest (Output write) throws IOException { String value1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ\rabcdefghijklmnopqrstuvwxyz\n1234567890\t\"!`?'.,;:()[]{}<>|/@\\^$-%+= String value2 = "abcdef\u00E1\u00E9\u00ED\u00F3\u00FA\u1234"; write.writeString(""); write.writeString("1"); write.writeString("22"); write.writeString("uno"); write.writeString("dos"); write.writeString("tres"); write.writeString(null); write.writeString(value1); write.writeString(value2); for (int i = 0; i < 127; i++) write.writeString(String.valueOf((char)i)); for (int i = 0; i < 127; i++) write.writeString(String.valueOf((char)i) + "abc"); Input read = new Input(write.toBytes()); assertEquals("", read.readString()); assertEquals("1", read.readString()); assertEquals("22", read.readString()); assertEquals("uno", read.readString()); assertEquals("dos", read.readString()); assertEquals("tres", read.readString()); assertEquals(null, read.readString()); assertEquals(value1, read.readString()); assertEquals(value2, read.readString()); for (int i = 0; i < 127; i++) assertEquals(String.valueOf((char)i), read.readString()); for (int i = 0; i < 127; i++) assertEquals(String.valueOf((char)i) + "abc", read.readString()); read.rewind(); assertEquals("", read.readStringBuilder().toString()); assertEquals("1", read.readStringBuilder().toString()); assertEquals("22", read.readStringBuilder().toString()); assertEquals("uno", read.readStringBuilder().toString()); assertEquals("dos", read.readStringBuilder().toString()); assertEquals("tres", read.readStringBuilder().toString()); assertEquals(null, read.readStringBuilder()); assertEquals(value1, read.readStringBuilder().toString()); assertEquals(value2, read.readStringBuilder().toString()); for (int i = 0; i < 127; i++) assertEquals(String.valueOf((char)i), read.readStringBuilder().toString()); for (int i = 0; i < 127; i++) assertEquals(String.valueOf((char)i) + "abc", read.readStringBuilder().toString()); } public void testCanReadInt () throws IOException { Output write = new Output(new ByteArrayOutputStream()); Input read = new Input(write.toBytes()); assertEquals(false, read.canReadInt()); write.writeInt(400, true); read = new Input(write.toBytes()); assertEquals(true, read.canReadInt()); read.setLimit(read.limit() - 1); assertEquals(false, read.canReadInt()); } public void testInts () throws IOException { runIntTest(new Output(4096)); runIntTest(new Output(new ByteArrayOutputStream())); } private void runIntTest (Output write) throws IOException { write.writeInt(0); write.writeInt(63); write.writeInt(64); write.writeInt(127); write.writeInt(128); write.writeInt(8192); write.writeInt(16384); write.writeInt(2097151); write.writeInt(1048575); write.writeInt(134217727); write.writeInt(268435455); write.writeInt(134217728); write.writeInt(268435456); write.writeInt(-2097151); write.writeInt(-1048575); write.writeInt(-134217727); write.writeInt(-268435455); write.writeInt(-134217728); write.writeInt(-268435456); assertEquals(1, write.writeInt(0, true)); assertEquals(1, write.writeInt(0, false)); assertEquals(1, write.writeInt(63, true)); assertEquals(1, write.writeInt(63, false)); assertEquals(1, write.writeInt(64, true)); assertEquals(2, write.writeInt(64, false)); assertEquals(1, write.writeInt(127, true)); assertEquals(2, write.writeInt(127, false)); assertEquals(2, write.writeInt(128, true)); assertEquals(2, write.writeInt(128, false)); assertEquals(2, write.writeInt(8191, true)); assertEquals(2, write.writeInt(8191, false)); assertEquals(2, write.writeInt(8192, true)); assertEquals(3, write.writeInt(8192, false)); assertEquals(2, write.writeInt(16383, true)); assertEquals(3, write.writeInt(16383, false)); assertEquals(3, write.writeInt(16384, true)); assertEquals(3, write.writeInt(16384, false)); assertEquals(3, write.writeInt(2097151, true)); assertEquals(4, write.writeInt(2097151, false)); assertEquals(3, write.writeInt(1048575, true)); assertEquals(3, write.writeInt(1048575, false)); assertEquals(4, write.writeInt(134217727, true)); assertEquals(4, write.writeInt(134217727, false)); assertEquals(4, write.writeInt(268435455, true)); assertEquals(5, write.writeInt(268435455, false)); assertEquals(4, write.writeInt(134217728, true)); assertEquals(5, write.writeInt(134217728, false)); assertEquals(5, write.writeInt(268435456, true)); assertEquals(5, write.writeInt(268435456, false)); assertEquals(1, write.writeInt(-64, false)); assertEquals(5, write.writeInt(-64, true)); assertEquals(2, write.writeInt(-65, false)); assertEquals(5, write.writeInt(-65, true)); assertEquals(2, write.writeInt(-8192, false)); assertEquals(5, write.writeInt(-8192, true)); assertEquals(3, write.writeInt(-1048576, false)); assertEquals(5, write.writeInt(-1048576, true)); assertEquals(4, write.writeInt(-134217728, false)); assertEquals(5, write.writeInt(-134217728, true)); assertEquals(5, write.writeInt(-134217729, false)); assertEquals(5, write.writeInt(-134217729, true)); assertEquals(5, write.writeInt(1000000000, false)); assertEquals(5, write.writeInt(1000000000, true)); assertEquals(5, write.writeInt(Integer.MAX_VALUE - 1, false)); assertEquals(5, write.writeInt(Integer.MAX_VALUE - 1, true)); assertEquals(5, write.writeInt(Integer.MAX_VALUE, false)); assertEquals(5, write.writeInt(Integer.MAX_VALUE, true)); Input read = new Input(write.toBytes()); assertEquals(0, read.readInt()); assertEquals(63, read.readInt()); assertEquals(64, read.readInt()); assertEquals(127, read.readInt()); assertEquals(128, read.readInt()); assertEquals(8192, read.readInt()); assertEquals(16384, read.readInt()); assertEquals(2097151, read.readInt()); assertEquals(1048575, read.readInt()); assertEquals(134217727, read.readInt()); assertEquals(268435455, read.readInt()); assertEquals(134217728, read.readInt()); assertEquals(268435456, read.readInt()); assertEquals(-2097151, read.readInt()); assertEquals(-1048575, read.readInt()); assertEquals(-134217727, read.readInt()); assertEquals(-268435455, read.readInt()); assertEquals(-134217728, read.readInt()); assertEquals(-268435456, read.readInt()); assertEquals(true, read.canReadInt()); assertEquals(true, read.canReadInt()); assertEquals(true, read.canReadInt()); assertEquals(0, read.readInt(true)); assertEquals(0, read.readInt(false)); assertEquals(63, read.readInt(true)); assertEquals(63, read.readInt(false)); assertEquals(64, read.readInt(true)); assertEquals(64, read.readInt(false)); assertEquals(127, read.readInt(true)); assertEquals(127, read.readInt(false)); assertEquals(128, read.readInt(true)); assertEquals(128, read.readInt(false)); assertEquals(8191, read.readInt(true)); assertEquals(8191, read.readInt(false)); assertEquals(8192, read.readInt(true)); assertEquals(8192, read.readInt(false)); assertEquals(16383, read.readInt(true)); assertEquals(16383, read.readInt(false)); assertEquals(16384, read.readInt(true)); assertEquals(16384, read.readInt(false)); assertEquals(2097151, read.readInt(true)); assertEquals(2097151, read.readInt(false)); assertEquals(1048575, read.readInt(true)); assertEquals(1048575, read.readInt(false)); assertEquals(134217727, read.readInt(true)); assertEquals(134217727, read.readInt(false)); assertEquals(268435455, read.readInt(true)); assertEquals(268435455, read.readInt(false)); assertEquals(134217728, read.readInt(true)); assertEquals(134217728, read.readInt(false)); assertEquals(268435456, read.readInt(true)); assertEquals(268435456, read.readInt(false)); assertEquals(-64, read.readInt(false)); assertEquals(-64, read.readInt(true)); assertEquals(-65, read.readInt(false)); assertEquals(-65, read.readInt(true)); assertEquals(-8192, read.readInt(false)); assertEquals(-8192, read.readInt(true)); assertEquals(-1048576, read.readInt(false)); assertEquals(-1048576, read.readInt(true)); assertEquals(-134217728, read.readInt(false)); assertEquals(-134217728, read.readInt(true)); assertEquals(-134217729, read.readInt(false)); assertEquals(-134217729, read.readInt(true)); assertEquals(1000000000, read.readInt(false)); assertEquals(1000000000, read.readInt(true)); assertEquals(Integer.MAX_VALUE - 1, read.readInt(false)); assertEquals(Integer.MAX_VALUE - 1, read.readInt(true)); assertEquals(Integer.MAX_VALUE, read.readInt(false)); assertEquals(Integer.MAX_VALUE, read.readInt(true)); assertEquals(false, read.canReadInt()); Random random = new Random(); for (int i = 0; i < 10000; i++) { int value = random.nextInt(); write.clear(); write.writeInt(value); write.writeInt(value, true); write.writeInt(value, false); read.setBuffer(write.toBytes()); assertEquals(value, read.readInt()); assertEquals(value, read.readInt(true)); assertEquals(value, read.readInt(false)); } } public void testLongs () throws IOException { runLongTest(new Output(4096)); runLongTest(new Output(new ByteArrayOutputStream())); } private void runLongTest (Output write) throws IOException { write.writeLong(0); write.writeLong(63); write.writeLong(64); write.writeLong(127); write.writeLong(128); write.writeLong(8192); write.writeLong(16384); write.writeLong(2097151); write.writeLong(1048575); write.writeLong(134217727); write.writeLong(268435455); write.writeLong(134217728); write.writeLong(268435456); write.writeLong(-2097151); write.writeLong(-1048575); write.writeLong(-134217727); write.writeLong(-268435455); write.writeLong(-134217728); write.writeLong(-268435456); assertEquals(1, write.writeLong(0, true)); assertEquals(1, write.writeLong(0, false)); assertEquals(1, write.writeLong(63, true)); assertEquals(1, write.writeLong(63, false)); assertEquals(1, write.writeLong(64, true)); assertEquals(2, write.writeLong(64, false)); assertEquals(1, write.writeLong(127, true)); assertEquals(2, write.writeLong(127, false)); assertEquals(2, write.writeLong(128, true)); assertEquals(2, write.writeLong(128, false)); assertEquals(2, write.writeLong(8191, true)); assertEquals(2, write.writeLong(8191, false)); assertEquals(2, write.writeLong(8192, true)); assertEquals(3, write.writeLong(8192, false)); assertEquals(2, write.writeLong(16383, true)); assertEquals(3, write.writeLong(16383, false)); assertEquals(3, write.writeLong(16384, true)); assertEquals(3, write.writeLong(16384, false)); assertEquals(3, write.writeLong(2097151, true)); assertEquals(4, write.writeLong(2097151, false)); assertEquals(3, write.writeLong(1048575, true)); assertEquals(3, write.writeLong(1048575, false)); assertEquals(4, write.writeLong(134217727, true)); assertEquals(4, write.writeLong(134217727, false)); assertEquals(4, write.writeLong(268435455l, true)); assertEquals(5, write.writeLong(268435455l, false)); assertEquals(4, write.writeLong(134217728l, true)); assertEquals(5, write.writeLong(134217728l, false)); assertEquals(5, write.writeLong(268435456l, true)); assertEquals(5, write.writeLong(268435456l, false)); assertEquals(1, write.writeLong(-64, false)); assertEquals(9, write.writeLong(-64, true)); assertEquals(2, write.writeLong(-65, false)); assertEquals(9, write.writeLong(-65, true)); assertEquals(2, write.writeLong(-8192, false)); assertEquals(9, write.writeLong(-8192, true)); assertEquals(3, write.writeLong(-1048576, false)); assertEquals(9, write.writeLong(-1048576, true)); assertEquals(4, write.writeLong(-134217728, false)); assertEquals(9, write.writeLong(-134217728, true)); assertEquals(5, write.writeLong(-134217729, false)); assertEquals(9, write.writeLong(-134217729, true)); Input read = new Input(write.toBytes()); assertEquals(0, read.readLong()); assertEquals(63, read.readLong()); assertEquals(64, read.readLong()); assertEquals(127, read.readLong()); assertEquals(128, read.readLong()); assertEquals(8192, read.readLong()); assertEquals(16384, read.readLong()); assertEquals(2097151, read.readLong()); assertEquals(1048575, read.readLong()); assertEquals(134217727, read.readLong()); assertEquals(268435455, read.readLong()); assertEquals(134217728, read.readLong()); assertEquals(268435456, read.readLong()); assertEquals(-2097151, read.readLong()); assertEquals(-1048575, read.readLong()); assertEquals(-134217727, read.readLong()); assertEquals(-268435455, read.readLong()); assertEquals(-134217728, read.readLong()); assertEquals(-268435456, read.readLong()); assertEquals(0, read.readLong(true)); assertEquals(0, read.readLong(false)); assertEquals(63, read.readLong(true)); assertEquals(63, read.readLong(false)); assertEquals(64, read.readLong(true)); assertEquals(64, read.readLong(false)); assertEquals(127, read.readLong(true)); assertEquals(127, read.readLong(false)); assertEquals(128, read.readLong(true)); assertEquals(128, read.readLong(false)); assertEquals(8191, read.readLong(true)); assertEquals(8191, read.readLong(false)); assertEquals(8192, read.readLong(true)); assertEquals(8192, read.readLong(false)); assertEquals(16383, read.readLong(true)); assertEquals(16383, read.readLong(false)); assertEquals(16384, read.readLong(true)); assertEquals(16384, read.readLong(false)); assertEquals(2097151, read.readLong(true)); assertEquals(2097151, read.readLong(false)); assertEquals(1048575, read.readLong(true)); assertEquals(1048575, read.readLong(false)); assertEquals(134217727, read.readLong(true)); assertEquals(134217727, read.readLong(false)); assertEquals(268435455, read.readLong(true)); assertEquals(268435455, read.readLong(false)); assertEquals(134217728, read.readLong(true)); assertEquals(134217728, read.readLong(false)); assertEquals(268435456, read.readLong(true)); assertEquals(268435456, read.readLong(false)); assertEquals(-64, read.readLong(false)); assertEquals(-64, read.readLong(true)); assertEquals(-65, read.readLong(false)); assertEquals(-65, read.readLong(true)); assertEquals(-8192, read.readLong(false)); assertEquals(-8192, read.readLong(true)); assertEquals(-1048576, read.readLong(false)); assertEquals(-1048576, read.readLong(true)); assertEquals(-134217728, read.readLong(false)); assertEquals(-134217728, read.readLong(true)); assertEquals(-134217729, read.readLong(false)); assertEquals(-134217729, read.readLong(true)); Random random = new Random(); for (int i = 0; i < 10000; i++) { long value = random.nextLong(); write.clear(); write.writeLong(value); write.writeLong(value, true); write.writeLong(value, false); read.setBuffer(write.toBytes()); assertEquals(value, read.readLong()); assertEquals(value, read.readLong(true)); assertEquals(value, read.readLong(false)); } } public void testShorts () throws IOException { runShortTest(new Output(4096)); runShortTest(new Output(new ByteArrayOutputStream())); } private void runShortTest (Output write) throws IOException { write.writeShort(0); write.writeShort(63); write.writeShort(64); write.writeShort(127); write.writeShort(128); write.writeShort(8192); write.writeShort(16384); write.writeShort(32767); write.writeShort(-63); write.writeShort(-64); write.writeShort(-127); write.writeShort(-128); write.writeShort(-8192); write.writeShort(-16384); write.writeShort(-32768); Input read = new Input(write.toBytes()); assertEquals(0, read.readShort()); assertEquals(63, read.readShort()); assertEquals(64, read.readShort()); assertEquals(127, read.readShort()); assertEquals(128, read.readShort()); assertEquals(8192, read.readShort()); assertEquals(16384, read.readShort()); assertEquals(32767, read.readShort()); assertEquals(-63, read.readShort()); assertEquals(-64, read.readShort()); assertEquals(-127, read.readShort()); assertEquals(-128, read.readShort()); assertEquals(-8192, read.readShort()); assertEquals(-16384, read.readShort()); assertEquals(-32768, read.readShort()); } public void testFloats () throws IOException { runFloatTest(new Output(4096)); runFloatTest(new Output(new ByteArrayOutputStream())); } private void runFloatTest (Output write) throws IOException { write.writeFloat(0); write.writeFloat(63); write.writeFloat(64); write.writeFloat(127); write.writeFloat(128); write.writeFloat(8192); write.writeFloat(16384); write.writeFloat(32767); write.writeFloat(-63); write.writeFloat(-64); write.writeFloat(-127); write.writeFloat(-128); write.writeFloat(-8192); write.writeFloat(-16384); write.writeFloat(-32768); assertEquals(1, write.writeFloat(0, 1000, true)); assertEquals(1, write.writeFloat(0, 1000, false)); assertEquals(3, write.writeFloat(63, 1000, true)); assertEquals(3, write.writeFloat(63, 1000, false)); assertEquals(3, write.writeFloat(64, 1000, true)); assertEquals(3, write.writeFloat(64, 1000, false)); assertEquals(3, write.writeFloat(127, 1000, true)); assertEquals(3, write.writeFloat(127, 1000, false)); assertEquals(3, write.writeFloat(128, 1000, true)); assertEquals(3, write.writeFloat(128, 1000, false)); assertEquals(4, write.writeFloat(8191, 1000, true)); assertEquals(4, write.writeFloat(8191, 1000, false)); assertEquals(4, write.writeFloat(8192, 1000, true)); assertEquals(4, write.writeFloat(8192, 1000, false)); assertEquals(4, write.writeFloat(16383, 1000, true)); assertEquals(4, write.writeFloat(16383, 1000, false)); assertEquals(4, write.writeFloat(16384, 1000, true)); assertEquals(4, write.writeFloat(16384, 1000, false)); assertEquals(4, write.writeFloat(32767, 1000, true)); assertEquals(4, write.writeFloat(32767, 1000, false)); assertEquals(3, write.writeFloat(-64, 1000, false)); assertEquals(5, write.writeFloat(-64, 1000, true)); assertEquals(3, write.writeFloat(-65, 1000, false)); assertEquals(5, write.writeFloat(-65, 1000, true)); assertEquals(4, write.writeFloat(-8192, 1000, false)); assertEquals(5, write.writeFloat(-8192, 1000, true)); Input read = new Input(write.toBytes()); assertEquals(read.readFloat(), 0f); assertEquals(read.readFloat(), 63f); assertEquals(read.readFloat(), 64f); assertEquals(read.readFloat(), 127f); assertEquals(read.readFloat(), 128f); assertEquals(read.readFloat(), 8192f); assertEquals(read.readFloat(), 16384f); assertEquals(read.readFloat(), 32767f); assertEquals(read.readFloat(), -63f); assertEquals(read.readFloat(), -64f); assertEquals(read.readFloat(), -127f); assertEquals(read.readFloat(), -128f); assertEquals(read.readFloat(), -8192f); assertEquals(read.readFloat(), -16384f); assertEquals(read.readFloat(), -32768f); assertEquals(read.readFloat(1000, true), 0f); assertEquals(read.readFloat(1000, false), 0f); assertEquals(read.readFloat(1000, true), 63f); assertEquals(read.readFloat(1000, false), 63f); assertEquals(read.readFloat(1000, true), 64f); assertEquals(read.readFloat(1000, false), 64f); assertEquals(read.readFloat(1000, true), 127f); assertEquals(read.readFloat(1000, false), 127f); assertEquals(read.readFloat(1000, true), 128f); assertEquals(read.readFloat(1000, false), 128f); assertEquals(read.readFloat(1000, true), 8191f); assertEquals(read.readFloat(1000, false), 8191f); assertEquals(read.readFloat(1000, true), 8192f); assertEquals(read.readFloat(1000, false), 8192f); assertEquals(read.readFloat(1000, true), 16383f); assertEquals(read.readFloat(1000, false), 16383f); assertEquals(read.readFloat(1000, true), 16384f); assertEquals(read.readFloat(1000, false), 16384f); assertEquals(read.readFloat(1000, true), 32767f); assertEquals(read.readFloat(1000, false), 32767f); assertEquals(read.readFloat(1000, false), -64f); assertEquals(read.readFloat(1000, true), -64f); assertEquals(read.readFloat(1000, false), -65f); assertEquals(read.readFloat(1000, true), -65f); assertEquals(read.readFloat(1000, false), -8192f); assertEquals(read.readFloat(1000, true), -8192f); } public void testDoubles () throws IOException { runDoubleTest(new Output(4096)); runDoubleTest(new Output(new ByteArrayOutputStream())); } private void runDoubleTest (Output write) throws IOException { write.writeDouble(0); write.writeDouble(63); write.writeDouble(64); write.writeDouble(127); write.writeDouble(128); write.writeDouble(8192); write.writeDouble(16384); write.writeDouble(32767); write.writeDouble(-63); write.writeDouble(-64); write.writeDouble(-127); write.writeDouble(-128); write.writeDouble(-8192); write.writeDouble(-16384); write.writeDouble(-32768); assertEquals(1, write.writeDouble(0, 1000, true)); assertEquals(1, write.writeDouble(0, 1000, false)); assertEquals(3, write.writeDouble(63, 1000, true)); assertEquals(3, write.writeDouble(63, 1000, false)); assertEquals(3, write.writeDouble(64, 1000, true)); assertEquals(3, write.writeDouble(64, 1000, false)); assertEquals(3, write.writeDouble(127, 1000, true)); assertEquals(3, write.writeDouble(127, 1000, false)); assertEquals(3, write.writeDouble(128, 1000, true)); assertEquals(3, write.writeDouble(128, 1000, false)); assertEquals(4, write.writeDouble(8191, 1000, true)); assertEquals(4, write.writeDouble(8191, 1000, false)); assertEquals(4, write.writeDouble(8192, 1000, true)); assertEquals(4, write.writeDouble(8192, 1000, false)); assertEquals(4, write.writeDouble(16383, 1000, true)); assertEquals(4, write.writeDouble(16383, 1000, false)); assertEquals(4, write.writeDouble(16384, 1000, true)); assertEquals(4, write.writeDouble(16384, 1000, false)); assertEquals(4, write.writeDouble(32767, 1000, true)); assertEquals(4, write.writeDouble(32767, 1000, false)); assertEquals(3, write.writeDouble(-64, 1000, false)); assertEquals(9, write.writeDouble(-64, 1000, true)); assertEquals(3, write.writeDouble(-65, 1000, false)); assertEquals(9, write.writeDouble(-65, 1000, true)); assertEquals(4, write.writeDouble(-8192, 1000, false)); assertEquals(9, write.writeDouble(-8192, 1000, true)); write.writeDouble(1.23456d); Input read = new Input(write.toBytes()); assertEquals(read.readDouble(), 0d); assertEquals(read.readDouble(), 63d); assertEquals(read.readDouble(), 64d); assertEquals(read.readDouble(), 127d); assertEquals(read.readDouble(), 128d); assertEquals(read.readDouble(), 8192d); assertEquals(read.readDouble(), 16384d); assertEquals(read.readDouble(), 32767d); assertEquals(read.readDouble(), -63d); assertEquals(read.readDouble(), -64d); assertEquals(read.readDouble(), -127d); assertEquals(read.readDouble(), -128d); assertEquals(read.readDouble(), -8192d); assertEquals(read.readDouble(), -16384d); assertEquals(read.readDouble(), -32768d); assertEquals(read.readDouble(1000, true), 0d); assertEquals(read.readDouble(1000, false), 0d); assertEquals(read.readDouble(1000, true), 63d); assertEquals(read.readDouble(1000, false), 63d); assertEquals(read.readDouble(1000, true), 64d); assertEquals(read.readDouble(1000, false), 64d); assertEquals(read.readDouble(1000, true), 127d); assertEquals(read.readDouble(1000, false), 127d); assertEquals(read.readDouble(1000, true), 128d); assertEquals(read.readDouble(1000, false), 128d); assertEquals(read.readDouble(1000, true), 8191d); assertEquals(read.readDouble(1000, false), 8191d); assertEquals(read.readDouble(1000, true), 8192d); assertEquals(read.readDouble(1000, false), 8192d); assertEquals(read.readDouble(1000, true), 16383d); assertEquals(read.readDouble(1000, false), 16383d); assertEquals(read.readDouble(1000, true), 16384d); assertEquals(read.readDouble(1000, false), 16384d); assertEquals(read.readDouble(1000, true), 32767d); assertEquals(read.readDouble(1000, false), 32767d); assertEquals(read.readDouble(1000, false), -64d); assertEquals(read.readDouble(1000, true), -64d); assertEquals(read.readDouble(1000, false), -65d); assertEquals(read.readDouble(1000, true), -65d); assertEquals(read.readDouble(1000, false), -8192d); assertEquals(read.readDouble(1000, true), -8192d); assertEquals(1.23456d, read.readDouble()); } public void testBooleans () throws IOException { runBooleanTest(new Output(4096)); runBooleanTest(new Output(new ByteArrayOutputStream())); } private void runBooleanTest (Output write) throws IOException { for (int i = 0; i < 100; i++) { write.writeBoolean(true); write.writeBoolean(false); } Input read = new Input(write.toBytes()); for (int i = 0; i < 100; i++) { assertEquals(true, read.readBoolean()); assertEquals(false, read.readBoolean()); } } public void testChars () throws IOException { runCharTest(new Output(4096)); runCharTest(new Output(new ByteArrayOutputStream())); } private void runCharTest (Output write) throws IOException { write.writeChar((char)0); write.writeChar((char)63); write.writeChar((char)64); write.writeChar((char)127); write.writeChar((char)128); write.writeChar((char)8192); write.writeChar((char)16384); write.writeChar((char)32767); write.writeChar((char)65535); Input read = new Input(write.toBytes()); assertEquals(0, read.readChar()); assertEquals(63, read.readChar()); assertEquals(64, read.readChar()); assertEquals(127, read.readChar()); assertEquals(128, read.readChar()); assertEquals(8192, read.readChar()); assertEquals(16384, read.readChar()); assertEquals(32767, read.readChar()); assertEquals(65535, read.readChar()); } public void testInputWithOffset () throws Exception { final byte[] buf = new byte[30]; final Input in = new Input(buf, 10, 10); assertEquals(10, in.available()); } public void testSmallBuffers () throws Exception { ByteBuffer buf = ByteBuffer.allocate(1024); ByteBufferOutputStream byteBufferOutputStream = new ByteBufferOutputStream(buf); Output testOutput = new Output(byteBufferOutputStream); testOutput.writeBytes(new byte[512]); testOutput.writeBytes(new byte[512]); testOutput.flush(); ByteBufferInputStream testInputs = new ByteBufferInputStream(); buf.flip(); testInputs.setByteBuffer(buf); Input input = new Input(testInputs, 512); byte[] toRead = new byte[512]; input.readBytes(toRead); input.readBytes(toRead); } public void testVerySmallBuffers() throws Exception { Output out1 = new Output(4, -1); Output out2 = new ByteBufferOutput(4, -1); for (int i = 0; i < 16; i++) { out1.writeVarInt(92, false); } for (int i = 0; i < 16; i++) { out2.writeVarInt(92, false); } assertEquals(out1.toBytes(), out2.toBytes()); } public void testZeroLengthOutputs() throws Exception { Output output = new Output(0, 10000); kryo.writeClassAndObject(output, "Test string"); Output byteBufferOutput = new ByteBufferOutput(0, 10000); kryo.writeClassAndObject(byteBufferOutput, "Test string"); } public void testFlushRoundTrip() throws Exception { Kryo kryo = new Kryo(); String s1 = "12345"; ByteArrayOutputStream os=new ByteArrayOutputStream(); ObjectOutputStream objOutput = new ObjectOutputStream(os); Output output = new Output(objOutput); kryo.writeClass(output, s1.getClass()); kryo.writeObject(output, s1); output.flush(); // objOutput.flush(); // this layer wasn't flushed prior to this bugfix, add it for a workaround byte [] b = os.toByteArray(); System.out.println("size: " + b.length); ByteArrayInputStream in = new ByteArrayInputStream(b); ObjectInputStream objIn = new ObjectInputStream(in); Input input = new Input(objIn); Registration r = kryo.readClass(input); String s2 = (String)kryo.readObject(input,r.getType()); assertEquals(s1, s2); } }
package net.bolbat.utils.lang; import java.util.Calendar; import org.junit.Assert; import org.junit.Test; /** * {@link TimeUtilsTest} test. * <p/> * Related to task BBUTILS-9 - TimeUtils refactoring. * * @author Alexandr Bolbat */ public class TimeUtilsTest { @Test public void generalTest() { // check TimeUnit values Assert.assertEquals("Should be equal.", Calendar.YEAR, TimeUtils.TimeUnit.YEAR.getMappedCalendarField()); Assert.assertEquals("Should be equal.", Calendar.MONTH, TimeUtils.TimeUnit.MONTH.getMappedCalendarField()); Assert.assertEquals("Should be equal.", Calendar.DAY_OF_MONTH, TimeUtils.TimeUnit.DAY.getMappedCalendarField()); Assert.assertEquals("Should be equal.", Calendar.HOUR_OF_DAY, TimeUtils.TimeUnit.HOUR.getMappedCalendarField()); Assert.assertEquals("Should be equal.", Calendar.MINUTE, TimeUtils.TimeUnit.MINUTE.getMappedCalendarField()); Assert.assertEquals("Should be equal.", Calendar.SECOND, TimeUtils.TimeUnit.SECOND.getMappedCalendarField()); // check rounding checkRound(TimeUtils.TimeUnit.SECOND, TimeUtils.Rounding.DOWN); checkRound(TimeUtils.TimeUnit.SECOND, TimeUtils.Rounding.UP); checkRound(TimeUtils.TimeUnit.MINUTE, TimeUtils.Rounding.DOWN); checkRound(TimeUtils.TimeUnit.MINUTE, TimeUtils.Rounding.UP); checkRound(TimeUtils.TimeUnit.HOUR, TimeUtils.Rounding.DOWN); checkRound(TimeUtils.TimeUnit.HOUR, TimeUtils.Rounding.UP); checkRound(TimeUtils.TimeUnit.DAY, TimeUtils.Rounding.DOWN); checkRound(TimeUtils.TimeUnit.DAY, TimeUtils.Rounding.UP); checkRound(TimeUtils.TimeUnit.MONTH, TimeUtils.Rounding.DOWN); checkRound(TimeUtils.TimeUnit.MONTH, TimeUtils.Rounding.UP); checkRound(TimeUtils.TimeUnit.YEAR, TimeUtils.Rounding.DOWN); checkRound(TimeUtils.TimeUnit.YEAR, TimeUtils.Rounding.UP); // check 'from now' checkFromNow(1, TimeUtils.TimeUnit.YEAR); checkFromNow(-1, TimeUtils.TimeUnit.YEAR); checkFromNow(1, TimeUtils.TimeUnit.MONTH); checkFromNow(-1, TimeUtils.TimeUnit.MONTH); checkFromNow(1, TimeUtils.TimeUnit.DAY); checkFromNow(-1, TimeUtils.TimeUnit.DAY); checkFromNow(1, TimeUtils.TimeUnit.HOUR); checkFromNow(-1, TimeUtils.TimeUnit.HOUR); checkFromNow(1, TimeUtils.TimeUnit.MINUTE); checkFromNow(-1, TimeUtils.TimeUnit.MINUTE); checkFromNow(1, TimeUtils.TimeUnit.SECOND); checkFromNow(-1, TimeUtils.TimeUnit.SECOND); // check 'from now' with no rounding param int fromNow = 1; TimeUtils.TimeUnit timeUnit = TimeUtils.TimeUnit.DAY; Calendar calendar = Calendar.getInstance(); calendar.add(timeUnit.getMappedCalendarField(), fromNow); // manual calculation roundCalendarManually(calendar, timeUnit, TimeUtils.Rounding.UP); long fromNowRoundUpByCalendar = calendar.getTimeInMillis(); // util calculation calendar.setTimeInMillis(TimeUtils.fromNow(fromNow, timeUnit)); roundCalendarManually(calendar, timeUnit, TimeUtils.Rounding.UP); Assert.assertEquals("Test time unit[" + timeUnit + "]. Values should be equal", fromNowRoundUpByCalendar, calendar.getTimeInMillis()); } @Test public void errorCaseTests() { try { TimeUtils.fromNow(0, null, TimeUtils.Rounding.DOWN); Assert.fail("Should fail cause param is wrong."); } catch (IllegalArgumentException e) { Assert.assertTrue(e instanceof IllegalArgumentException); } try { TimeUtils.fromNow(0, null); Assert.fail("Should fail cause param is wrong."); } catch (IllegalArgumentException e) { Assert.assertTrue(e instanceof IllegalArgumentException); } try { TimeUtils.round(null, TimeUtils.TimeUnit.SECOND, TimeUtils.Rounding.DOWN); Assert.fail("Should fail cause param is wrong."); } catch (IllegalArgumentException e) { Assert.assertTrue(e instanceof IllegalArgumentException); } try { TimeUtils.round(Calendar.getInstance(), null, TimeUtils.Rounding.DOWN); Assert.fail("Should fail cause param is wrong."); } catch (IllegalArgumentException e) { Assert.assertTrue(e instanceof IllegalArgumentException); } try { TimeUtils.round(Calendar.getInstance().getTimeInMillis(), null, TimeUtils.Rounding.DOWN); Assert.fail("Should fail cause param is wrong."); } catch (IllegalArgumentException e) { Assert.assertTrue(e instanceof IllegalArgumentException); } } /** * Check method 'round'. * * @param timeUnit * {@link TimeUtils.TimeUnit} * @param rounding * {@link TimeUtils.Rounding} */ private void checkRound(TimeUtils.TimeUnit timeUnit, TimeUtils.Rounding rounding) { Calendar calendar = Calendar.getInstance(); roundCalendarManually(calendar, timeUnit, rounding); Calendar utilCal = Calendar.getInstance(); TimeUtils.round(utilCal, timeUnit, rounding); Assert.assertEquals("Round value should be same", calendar.getTimeInMillis(), utilCal.getTimeInMillis()); } /** * Check method 'from now'. * * @param amount * amount of time units from now * @param timeUnit * {@link TimeUtils.TimeUnit} */ private void checkFromNow(int amount, TimeUtils.TimeUnit timeUnit) { Calendar calendar = Calendar.getInstance(); calendar.add(timeUnit.getMappedCalendarField(), amount); // manual calculation roundCalendarManually(calendar, timeUnit, TimeUtils.Rounding.UP); long fromNowRoundUpByCalendar = calendar.getTimeInMillis(); roundCalendarManually(calendar, timeUnit, TimeUtils.Rounding.DOWN); long fromNowRoundDownByCalendar = calendar.getTimeInMillis(); // util calculation long fromNowRoundUpByUtil = TimeUtils.fromNow(amount, timeUnit, TimeUtils.Rounding.UP); long fromNowRoundDownByUtil = TimeUtils.fromNow(amount, timeUnit, TimeUtils.Rounding.DOWN); Assert.assertEquals("Test time unit[" + timeUnit + "]. Values should be equal", fromNowRoundUpByCalendar, fromNowRoundUpByUtil); Assert.assertEquals("Test time unit[" + timeUnit + "]. Values should be equal", fromNowRoundDownByCalendar, fromNowRoundDownByUtil); } /** * Round calendar manually. * * @param cal * {@link Calendar} * @param timeUnit * {@link TimeUtils.TimeUnit} * @param rounding * {@link TimeUtils.Rounding} */ private void roundCalendarManually(Calendar cal, TimeUtils.TimeUnit timeUnit, TimeUtils.Rounding rounding) { if (rounding == null || TimeUtils.Rounding.NONE.equals(rounding)) return; boolean roundDown = TimeUtils.Rounding.DOWN.equals(rounding); switch (timeUnit) { case SECOND: cal.set(Calendar.MILLISECOND, roundDown ? cal.getActualMinimum(Calendar.MILLISECOND) : cal.getActualMaximum(Calendar.MILLISECOND)); break; case MINUTE: cal.set(Calendar.MILLISECOND, roundDown ? cal.getActualMinimum(Calendar.MILLISECOND) : cal.getActualMaximum(Calendar.MILLISECOND)); cal.set(Calendar.SECOND, roundDown ? cal.getActualMinimum(Calendar.SECOND) : cal.getActualMaximum(Calendar.SECOND)); break; case HOUR: cal.set(Calendar.MILLISECOND, roundDown ? cal.getActualMinimum(Calendar.MILLISECOND) : cal.getActualMaximum(Calendar.MILLISECOND)); cal.set(Calendar.SECOND, roundDown ? cal.getActualMinimum(Calendar.SECOND) : cal.getActualMaximum(Calendar.SECOND)); cal.set(Calendar.MINUTE, roundDown ? cal.getActualMinimum(Calendar.MINUTE) : cal.getActualMaximum(Calendar.MINUTE)); break; case DAY: cal.set(Calendar.MILLISECOND, roundDown ? cal.getActualMinimum(Calendar.MILLISECOND) : cal.getActualMaximum(Calendar.MILLISECOND)); cal.set(Calendar.SECOND, roundDown ? cal.getActualMinimum(Calendar.SECOND) : cal.getActualMaximum(Calendar.SECOND)); cal.set(Calendar.MINUTE, roundDown ? cal.getActualMinimum(Calendar.MINUTE) : cal.getActualMaximum(Calendar.MINUTE)); cal.set(Calendar.HOUR_OF_DAY, roundDown ? cal.getActualMinimum(Calendar.HOUR_OF_DAY) : cal.getActualMaximum(Calendar.HOUR_OF_DAY)); break; case MONTH: cal.set(Calendar.MILLISECOND, roundDown ? cal.getActualMinimum(Calendar.MILLISECOND) : cal.getActualMaximum(Calendar.MILLISECOND)); cal.set(Calendar.SECOND, roundDown ? cal.getActualMinimum(Calendar.SECOND) : cal.getActualMaximum(Calendar.SECOND)); cal.set(Calendar.MINUTE, roundDown ? cal.getActualMinimum(Calendar.MINUTE) : cal.getActualMaximum(Calendar.MINUTE)); cal.set(Calendar.HOUR_OF_DAY, roundDown ? cal.getActualMinimum(Calendar.HOUR_OF_DAY) : cal.getActualMaximum(Calendar.HOUR_OF_DAY)); cal.set(Calendar.DAY_OF_MONTH, roundDown ? cal.getActualMinimum(Calendar.DAY_OF_MONTH) : cal.getActualMaximum(Calendar.DAY_OF_MONTH)); break; case YEAR: cal.set(Calendar.MILLISECOND, roundDown ? cal.getActualMinimum(Calendar.MILLISECOND) : cal.getActualMaximum(Calendar.MILLISECOND)); cal.set(Calendar.SECOND, roundDown ? cal.getActualMinimum(Calendar.SECOND) : cal.getActualMaximum(Calendar.SECOND)); cal.set(Calendar.MINUTE, roundDown ? cal.getActualMinimum(Calendar.MINUTE) : cal.getActualMaximum(Calendar.MINUTE)); cal.set(Calendar.HOUR_OF_DAY, roundDown ? cal.getActualMinimum(Calendar.HOUR_OF_DAY) : cal.getActualMaximum(Calendar.HOUR_OF_DAY)); cal.set(Calendar.DAY_OF_MONTH, roundDown ? cal.getActualMinimum(Calendar.DAY_OF_MONTH) : cal.getActualMaximum(Calendar.DAY_OF_MONTH)); cal.set(Calendar.MONTH, roundDown ? cal.getActualMinimum(Calendar.MONTH) : cal.getActualMaximum(Calendar.MONTH)); break; } } }
package org.rascalmpl.value; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.rascalmpl.value.io.binary.IValueReader; import org.rascalmpl.value.io.binary.IValueWriter; import org.rascalmpl.value.type.Type; import org.rascalmpl.value.type.TypeFactory; import org.rascalmpl.value.type.TypeStore; import junit.framework.TestCase; /** * @author Anya Helene Bagge */ public abstract class BaseTestMap extends TestCase { protected final TypeStore ts = new TypeStore(); protected final TypeFactory tf = TypeFactory.getInstance(); private final Type fromToMapType = tf.mapType(tf.stringType(), "from", tf.stringType(), "to"); private final Type fromToValueMapType = tf.mapType(tf.valueType(), "from", tf.valueType(), "to"); private final Type keyValueMapType = tf.mapType(tf.stringType(), "key", tf.stringType(), "value"); private final Type unlabeledMapType = tf.mapType(tf.stringType(), tf.stringType()); enum Kind { BINARY }; protected IValueFactory vf; private Type a; private Type b; private TestValue[] testValues; private IMap[] testMaps; private StringPair[] keyValues; protected void setUp(IValueFactory factory) throws Exception { vf = factory; a = tf.abstractDataType(ts, "A"); b = tf.abstractDataType(ts, "B"); testValues = new TestValue[]{ new TestValue(this, "Bergen", "Amsterdam", "from", "to"), new TestValue(this, "New York", "London", null, null), new TestValue(this, "Banana", "Fruit", "key", "value"), }; testMaps = new IMap[] { vf.map(fromToMapType), vf.map(keyValueMapType), vf.map(unlabeledMapType), vf.map(fromToMapType).put(vf.string("Bergen"), vf.string("Amsterdam")), vf.map(fromToValueMapType).put(vf.string("Bergen"), vf.string("Amsterdam")).put(vf.string("Mango"), vf.string("Yummy")), vf.map(fromToMapType).put(vf.string("Bergen"), vf.string("Amsterdam")).put(vf.string("Amsterdam"), vf.string("Frankfurt")), vf.map(fromToMapType).put(vf.string("Bergen"), vf.string("Amsterdam")).put(vf.string("Amsterdam"), vf.string("Frankfurt")).put(vf.string("Frankfurt"), vf.string("Moscow")), vf.map(keyValueMapType).put(vf.string("Bergen"), vf.string("Rainy")).put(vf.string("Helsinki"), vf.string("Cold")), vf.map(unlabeledMapType).put(vf.string("Mango"), vf.string("Sweet")).put(vf.string("Banana"), vf.string("Yummy")), }; String[] strings = new String[] { "Bergen", "Amsterdam", "Frankfurt", "Helsinki", "Moscow", "Rainy", "Cold", "Mango", "Banana", "Sweet", "Yummy" }; List<String> list1 = Arrays.asList(strings); List<String> list2 = Arrays.asList(strings); Collections.shuffle(list1); Collections.shuffle(list2); keyValues = new StringPair[strings.length]; for(int i = 0; i < strings.length; i++) { keyValues[i] = new StringPair(vf.string(list1.get(i)), vf.string(list2.get(i))); } } public void testNoLabels() { // make a non-labeled map type, and the labels should be null Type type = tf.mapType(a, b); assertNull(type.getKeyLabel()); assertNull(type.getValueLabel()); } public void testLabels() { // make a labeled map type, and the labels should match Type type = tf.mapType(a, "apple", b, "banana"); assertEquals("apple", type.getKeyLabel()); assertEquals("banana", type.getValueLabel()); } public void testTwoLabels1() { // make two map types with same key/value types but different labels, // and the labels should be kept distinct Type type1 = tf.mapType(a, "apple", b, "banana"); Type type2 = tf.mapType(a, "orange", b, "mango"); Type type3 = tf.mapType(a, b); assertEquals("apple", type1.getKeyLabel()); assertEquals("banana", type1.getValueLabel()); assertEquals("orange", type2.getKeyLabel()); assertEquals("mango", type2.getValueLabel()); assertNull(type3.getKeyLabel()); assertNull(type3.getValueLabel()); } public void testTwoLabels2() { Type type1 = tf.mapType(a, "apple", b, "banana"); Type type2 = tf.mapType(a, "orange", b, "mango"); assertTrue("Two map types with different labels should be equivalent", type1.equivalent(type2)); assertTrue("Two map types with different labels should be equivalent", type2.equivalent(type1)); assertFalse("Two map types with different labels should not be equals", type1.equals(type2)); assertFalse("Two map types with different labels should not be equals", type2.equals(type1)); Type type3 = tf.mapType(a, b); assertTrue("Labeled and unlabeled maps should be equivalent", type1.equivalent(type3)); assertTrue("Labeled and unlabeled maps should be equivalent", type3.equivalent(type1)); assertTrue("Labeled and unlabeled maps should be equivalent", type2.equivalent(type3)); assertTrue("Labeled and unlabeled maps should be equivalent", type3.equivalent(type2)); assertFalse("Labeled and unlabeled maps should not be equals", type1.equals(type3)); assertFalse("Labeled and unlabeled maps should not be equals", type3.equals(type1)); assertFalse("Labeled and unlabeled maps should not be equals", type2.equals(type3)); assertFalse("Labeled and unlabeled maps should not be equals", type3.equals(type2)); } /** * Check basic properties of put() */ public void testPut() { for(IMap map : testMaps) { for(StringPair p : keyValues) { IMap newMap = map.put(p.a, p.b); assertTrue(newMap.containsKey(p.a)); assertEquals(p.b, newMap.get(p.a)); assertEquals(map.getType().getKeyLabel(), newMap.getType().getKeyLabel()); assertEquals(map.getType().getValueLabel(), newMap.getType().getValueLabel()); assertTrue(map.getType().isSubtypeOf(newMap.getType())); } } } /** * Check that putting doesn't modify original map, and doesn't modify other elements. */ public void testPutModification() { for(IMap map : testMaps) { for(StringPair p : keyValues) { // testing with an arbitrary element of map is sufficient if(map.containsKey(p.a)) { IValue val = map.get(p.a); for(StringPair q : keyValues) { IMap newMap = map.put(q.a, q.b); assertEquals(val, map.get(p.a)); // original is never modified if(!p.a.isEqual(q.a)) assertEquals(val, newMap.get(p.a)); // only element q.a is modified } } } } } public void testCommon() { for(IMap map1 : testMaps) { for(IMap map2 : testMaps) { IMap map3 = map1.common(map2); // all common values are present for(IValue key : map1) { if(map1.get(key).equals(map2.get(key))) { assertEquals(map1.get(key), map3.get(key)); } } // type is lub of map1 and map2 types if(!map3.isEmpty()) { assertTrue(map1.getType().toString() + " <: " + map3.getType(), map1.getType().isSubtypeOf(map3.getType())); assertTrue(map2.getType().toString() + " <: " + map3.getType(), map2.getType().isSubtypeOf(map3.getType())); } // check labels if(!map2.getType().hasFieldNames()) { assertEquals(map1.getType().getKeyLabel(), map3.getType().getKeyLabel()); assertEquals(map1.getType().getValueLabel(), map3.getType().getValueLabel()); } if(!map1.getType().hasFieldNames()) { assertEquals(map2.getType().getKeyLabel(), map3.getType().getKeyLabel()); assertEquals(map2.getType().getValueLabel(), map3.getType().getValueLabel()); } } } } public void testJoin() { for(IMap map1 : testMaps) { for(IMap map2 : testMaps) { IMap map3 = map1.join(map2); // should contain all values from map2... for(IValue key : map2) { assertEquals(map2.get(key), map3.get(key)); } // ...and all values from map1 unless the keys are in map2 for(IValue key : map1) { if(!map2.containsKey(key)) { assertEquals(map1.get(key), map3.get(key)); } } // type is lub of map1 and map2 types if(!map3.isEmpty()) { assertTrue(map1.getType().toString() + " <: " + map3.getType(), map1.getType().isSubtypeOf(map3.getType())); assertTrue(map2.getType().toString() + " <: " + map3.getType(), map2.getType().isSubtypeOf(map3.getType())); } // check labels if(!map2.getType().hasFieldNames()) { assertEquals(map1.getType().getKeyLabel(), map3.getType().getKeyLabel()); assertEquals(map1.getType().getValueLabel(), map3.getType().getValueLabel()); } if(!map1.getType().hasFieldNames()) { assertEquals(map2.getType().getKeyLabel(), map3.getType().getKeyLabel()); assertEquals(map2.getType().getValueLabel(), map3.getType().getValueLabel()); } } } } public void testCompose() { for(IMap map1 : testMaps) { for(IMap map2 : testMaps) { IMap map3 = map1.compose(map2); // should map keys in map1 to values in map2 for(IValue key : map1) { if(map2.containsKey(map1.get(key))) assertEquals(map2.get(map1.get(key)), map3.get(key)); else assertNull(map3.get(key)); } // type is key type of map1 and value type of map2 if(!map3.isEmpty()) { assertEquals(map1.getType().getKeyType(), map3.getType().getKeyType()); assertEquals(map2.getType().getValueType(), map3.getType().getValueType()); } // check labels if(map1.getType().hasFieldNames() && map2.getType().hasFieldNames()) { assertEquals(map1.getType().getKeyLabel(), map3.getType().getKeyLabel()); assertEquals(map2.getType().getValueLabel(), map3.getType().getValueLabel()); } else { assertFalse(map3.getType().hasFieldNames()); } } } } public void testRemove() { for(IMap map1 : testMaps) { for(IMap map2 : testMaps) { IMap map3 = map1.remove(map2); for(IValue key : map2) { assertFalse("Key " + key + " should not exist", map3.containsKey(key)); } // type is same as map1 if(!map3.isEmpty()) { assertEquals(map1.getType(), map3.getType()); } // labels are same as map1 if(map1.getType().hasFieldNames()) { assertEquals(map1.getType().getKeyLabel(), map3.getType().getKeyLabel()); assertEquals(map1.getType().getValueLabel(), map3.getType().getValueLabel()); } } } } public void testLabelsIO(){ try{ for(int i = 0; i < testValues.length; i++){ for(Kind k : Kind.values()) { TestValue testValue = testValues[i]; assertEquals(testValue.keyLabel, testValue.value.getType().getKeyLabel()); assertEquals(testValue.valueLabel, testValue.value.getType().getValueLabel()); System.out.println(testValue + " : " + testValue.value.getType()); // Temp IValue result = doIO(testValue.value, k); System.out.println(result + " : " + result.getType()); // Temp System.out.println(); // Temp if(!testValue.value.isEqual(result)){ String message = "Not equal: \n\t"+testValue+" : "+testValue.value.getType()+"\n\t"+result+" : "+result.getType(); System.err.println(message); fail(message); } Type resultType = result.getType(); assertEquals("Labels should be preserved by " + k.name() + " IO: ", testValue.keyLabel, resultType.getKeyLabel()); assertEquals("Labels should be preserved by " + k.name() + " IO: ", testValue.valueLabel, resultType.getValueLabel()); } } }catch(IOException ioex){ ioex.printStackTrace(); fail(ioex.getMessage()); } } private IValue doIO(IValue val, Kind kind) throws IOException { switch(kind) { case BINARY: { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (IValueWriter w = new IValueWriter(baos)) { w.write(val); } try (IValueReader r = new IValueReader(new ByteArrayInputStream(baos.toByteArray()), vf, ts)) { return r.read(); } } /*// Doesn't work, but should, perhaps? case XML: { ByteArrayOutputStream baos = new ByteArrayOutputStream(); XMLWriter writer = new XMLWriter(); writer.write(val, new OutputStreamWriter(baos), ts); byte[] data = baos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(data); XMLReader reader = new XMLReader(); printBytes(data); // Temp return reader.read(vf, new InputStreamReader(bais)); } */ /* TEXT IO shouldn't work, since the labels aren't present in the standard text representation */ /* // Doesn't work, but should, perhaps? case ATERM: { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ATermWriter writer = new ATermWriter(); writer.write(val, new OutputStreamWriter(baos), ts); byte[] data = baos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(data); ATermReader reader = new ATermReader(); printBytes(data); // Temp return reader.read(vf, bais); } */ default: throw new RuntimeException("Missing case: " + kind.name()); } } private final static String[] HEX = new String[]{"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"}; // May be handy when debugging. private static void printBytes(byte[] bytes){ for(int i = 0; i < bytes.length; i++){ byte b = bytes[i]; int higher = (b & 0xf0) >> 4; int lower = b & 0xf; System.out.print("0x"); System.out.print(HEX[higher]); System.out.print(HEX[lower]); System.out.print(" "); } System.out.println(); } static class TestValue { Type type; IValue value; String keyLabel; String valueLabel; TestValue(BaseTestMap baseTestMap, String key, String value, String keyLabel, String valueLabel) { TypeFactory tf = baseTestMap.tf; IValueFactory vf = baseTestMap.vf; this.keyLabel = keyLabel; this.valueLabel = valueLabel; if(keyLabel != null && valueLabel != null) type = tf.mapType(tf.stringType(), keyLabel, tf.stringType(), valueLabel); else type = tf.mapType(tf.stringType(), tf.stringType()); this.value = vf.map(type).put(vf.string(key), vf.string(value)); } public String toString() { return value.toString(); } } static class StringPair { IString a; IString b; StringPair(IString a, IString b) { this.a = a; this.b = b; } @Override public String toString() { return String.format("(%s,%s)", a, b); } } public void testPutReplaceGet() { final IMap m1 = vf.mapWriter().done() .put(vf.integer(1), vf.integer(1)) .put(vf.integer(1), vf.integer(2)); assertEquals(1, m1.size()); assertEquals(vf.integer(2), m1.get(vf.integer(1))); } public void testDynamicTypesAfterMapUpdatesGrow() { final IMap m1 = vf.mapWriter().done() .put(vf.integer(1), vf.integer(1)) .put(vf.integer(1), vf.real(1)); assertEquals(1, m1.size()); assertEquals(tf.integerType(), m1.getType().getKeyType()); assertEquals(tf.realType(), m1.getType().getValueType()); } public void testDynamicTypesAfterMapWriterUpdatesGrow() { final IMapWriter w1 = vf.mapWriter(); w1.put(vf.integer(1), vf.integer(1)); w1.put(vf.integer(1), vf.real(1)); final IMap m1 = w1.done(); assertEquals(1, m1.size()); assertEquals(tf.integerType(), m1.getType().getKeyType()); assertEquals(tf.realType(), m1.getType().getValueType()); } public void testDynamicTypesAfterMapUpdatesShrink() { final IMap m1 = vf.mapWriter().done() .put(vf.integer(1), vf.integer(1)) .put(vf.integer(1), vf.real(1)) .put(vf.integer(1), vf.integer(1)); assertEquals(1, m1.size()); assertEquals(tf.integerType(), m1.getType().getKeyType()); assertEquals(tf.integerType(), m1.getType().getValueType()); } public void testDynamicTypesAfterMapWriterUpdatesShrink() { final IMapWriter w1 = vf.mapWriter(); w1.put(vf.integer(1), vf.integer(1)); w1.put(vf.integer(1), vf.real(1)); w1.put(vf.integer(1), vf.integer(1)); final IMap m1 = w1.done(); assertEquals(1, m1.size()); assertEquals(tf.integerType(), m1.getType().getKeyType()); assertEquals(tf.integerType(), m1.getType().getValueType()); } public void testPutReplaceWithAnnotations_Map() { final Type E = tf.abstractDataType(ts, "E"); final Type N = tf.constructor(ts, E, "n", tf.integerType()); ts.declareAnnotation(E, "x", tf.integerType()); final IConstructor n = vf.constructor(N, vf.integer(1)); final IConstructor na = n.asAnnotatable().setAnnotation("x", vf.integer(1)); final IMap m1 = vf.mapWriter().done() .put(n, vf.integer(1)) .put(na, vf.integer(1)); assertEquals(1, m1.size()); assertEquals(vf.integer(1), m1.get(n)); assertEquals(vf.integer(1), m1.get(na)); } public void testPutReplaceWithAnnotationsValue_Map() { final Type E = tf.abstractDataType(ts, "E"); final Type N = tf.constructor(ts, E, "n", tf.integerType()); ts.declareAnnotation(E, "x", tf.integerType()); final IConstructor n = vf.constructor(N, vf.integer(1)); final IConstructor na = n.asAnnotatable().setAnnotation("x", vf.integer(1)); final IMap m1 = vf.mapWriter().done() .put(vf.integer(1), n) .put(vf.integer(1), na); assertEquals(1, m1.size()); assertEquals(na, m1.get(vf.integer(1))); } public void testPutReplaceWithAnnotations_MapWriter() { final Type E = tf.abstractDataType(ts, "E"); final Type N = tf.constructor(ts, E, "n", tf.integerType()); ts.declareAnnotation(E, "x", tf.integerType()); final IConstructor n = vf.constructor(N, vf.integer(1)); final IConstructor na = n.asAnnotatable().setAnnotation("x", vf.integer(1)); final IMapWriter w1 = vf.mapWriter(); w1.put(n, vf.integer(1)); w1.put(na, vf.integer(1)); final IMap m1 = w1.done(); assertEquals(1, m1.size()); assertEquals(vf.integer(1), m1.get(n)); assertEquals(vf.integer(1), m1.get(na)); } public void testPutReplaceWithAnnotationsValue_MapWriter() { final Type E = tf.abstractDataType(ts, "E"); final Type N = tf.constructor(ts, E, "n", tf.integerType()); ts.declareAnnotation(E, "x", tf.integerType()); final IConstructor n = vf.constructor(N, vf.integer(1)); final IConstructor na = n.asAnnotatable().setAnnotation("x", vf.integer(1)); final IMapWriter w1 = vf.mapWriter(); w1.put(vf.integer(1), n); w1.put(vf.integer(1), na); final IMap m1 = w1.done(); assertEquals(1, m1.size()); assertEquals(na, m1.get(vf.integer(1))); } }
/* * $Id: MockActivityRegulator.java,v 1.4 2003-06-25 21:25:07 eaalto Exp $ */ package org.lockss.test; import java.util.*; import org.lockss.daemon.*; import org.lockss.plugin.*; import org.lockss.util.*; import junit.framework.*; public class MockActivityRegulator extends ActivityRegulator { boolean shouldStartAuActivity = false; boolean shouldStartCusActivity = false; int finishedAuActivity = -1; ArchivalUnit finishedAu = null; int finishedCusActivity = -1; CachedUrlSet finishedCus = null; Map finishedCusActivities = new HashMap(); Set lockedCuses = new HashSet(); public MockActivityRegulator(ArchivalUnit au) { super(au); } public void startService() { throw new UnsupportedOperationException("Not implemented"); } public void stopService() { throw new UnsupportedOperationException("Not implemented"); } public void auActivityFinished(int activity) { finishedAuActivity = activity; // finishedAu = au; } public void assertNewContentCrawlFinished() { assertFinished(NEW_CONTENT_CRAWL); } public void assertRepairCrawlFinished(CachedUrlSet cus) { assertFinished(REPAIR_CRAWL, cus); } public void assertFinished(int activity, CachedUrlSet cus) { Integer finishedActivity = (Integer)finishedCusActivities.get(cus); if (finishedActivity == null) { Assert.fail("No finished activities for "+cus); } Assert.assertEquals(("Activity " +ActivityRegulator.activityCodeToString(activity) +" not finished on "+cus), activity, finishedActivity.intValue()); } public void assertFinished(int activity) { Assert.assertEquals(("Activity " +ActivityRegulator.activityCodeToString(activity) +" not finished"), activity, finishedAuActivity); // Assert.assertSame("Different aus", au, finishedAu); } public void cusActivityFinished(int activity, CachedUrlSet cus) { finishedCusActivities.put(cus, new Integer(activity)); // finishedCusActivity = activity; // finishedCus = cus; } public void setStartAuActivity(boolean shouldStartAuActivity) { this.shouldStartAuActivity = shouldStartAuActivity; } public Lock startAuActivity(int newActivity, long expireIn) { return shouldStartAuActivity ? new Lock(0, expireIn) : null; } public void setStartCusActivity(CachedUrlSet cus, boolean shouldStartCusActivity) { if (shouldStartCusActivity) { lockedCuses.remove(cus); } else { lockedCuses.add(cus); } // cusStates.put(cus, new Boolean(shouldStartCusActivity)); // this.shouldStartCusActivity = shouldStartCusActivity; } public Lock startCusActivity(int newActivity, CachedUrlSet cus, long expireIn) { return (lockedCuses.contains(cus) ? null : new Lock(0, expireIn)); // return shouldStartCusActivity ? new Lock(0, expireIn) : null; } }
package ttt; import java.rmi.*; import java.util.Scanner; public class TTTClient { // int winner = -1; // static int player = 0; static Scanner keyboardSc; public static void main(String[] args) throws Exception { int play; int cont = 0; int winner = -1; int player = 0; boolean acceptedPlay; boolean restart; try { System.out.println("Port search..."); TTTService game = (TTTService) Naming.lookup("//localhost:8080/TTT"); System.out.println("Port connection accepted"); do{ restart=false; do { player = ++player % 2; do { System.out.println(game.currentBoard()); //play = readPlay(); do { System.out.printf("\nPlayer %d, please enter the number of the square " + "where you want to place your %c (or 0 to refresh the board): \n", player, (player == 1) ? 'X' : 'O'); play = keyboardSc.nextInt(); } while (play > 10 || play < 0); if (play != 0) { if(play==10){ int last=game.lastPlay(player); if(last!=-1){ System.out.println("Last play was: " + last +" by player " + player); }else{ System.out.println("No plays made by player " + player); } acceptedPlay = false; continue; } acceptedPlay = game.play( --play / 3, play % 3, player); if (!acceptedPlay) System.out.println("Invalid play! Try again."); } else acceptedPlay = false; } while (!acceptedPlay); winner = game.checkWinner(); } while (winner == -1); if (winner == 2) System.out.printf("\nHow boring, it is a draw\n"); else System.out.printf( "\nCongratulations, player %d, YOU ARE THE WINNER!\n", winner); do{ System.out.println("Restart the game? (yes = 1/no = 2): "); cont = keyboardSc.nextInt(); }while(cont < 1 || cont> 2); if(cont == 1){ game.restart(); restart=true; play=0; player = 1; cont= 0; } }while(restart); }catch(RemoteException e){ System.out.println("TTT:"+ e.getMessage()); } } }
package com.uriio.beacons; import android.util.Log; import java.nio.ByteBuffer; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.UUID; public class Util { /** * Enables Log debug output. Unfortunately BuildConfig.DEBUG does not work for library projects. */ private static final boolean VERBOSE = false; /** * Hex characters used for binary to hex conversion */ private static final byte[] _hexAlphabet = "0123456789abcdef".getBytes(); public static void log(String tag, String message) { if (VERBOSE) { if (null == message) Log.e(tag, "message = <null>"); else Log.d(tag, message); } } public static void log(String message) { log("NoTag", message); } public static byte[] hexToBin(String hexStr) { byte[] raw = new byte[hexStr.length() / 2]; byte[] hexStrBytes = hexStr.getBytes(); for (int i = 0; i < raw.length; i++) { byte nibble1 = hexStrBytes[i * 2], nibble2 = hexStrBytes[i * 2 + 1]; nibble1 = (byte) (nibble1 >= 'a' ? nibble1 - 'a' + 10 : nibble1 - '0'); nibble2 = (byte) (nibble2 >= 'a' ? nibble2 - 'a' + 10 : nibble2 - '0'); raw[i] = (byte) ((nibble1 << 4) | nibble2); } return raw; } public static UUID binToUUID(byte[] raw) { ByteBuffer byteBuffer = ByteBuffer.wrap(raw); return new UUID(byteBuffer.getLong(), byteBuffer.getLong()); } public static String binToHex(byte[] raw) { return binToHex(raw, 0, raw.length); } public static String binToHex(byte[] raw, int offset, int len) { byte[] hex = new byte[len * 2]; for (int i = 0; i < len; i++) { hex[i * 2] = _hexAlphabet[(0xff & raw[offset + i]) >>> 4]; hex[i * 2 + 1] = _hexAlphabet[raw[offset + i] & 0x0f]; } return new String(hex); } public static String binToHex(byte[] raw, int offset, int len, char separator) { byte[] hex = new byte[len * 3]; for (int i = 0; i < len; i++) { hex[i * 3] = _hexAlphabet[(0xff & raw[offset + i]) >>> 4]; hex[i * 3 + 1] = _hexAlphabet[raw[offset + i] & 0x0f]; hex[i * 3 + 2] = (byte) separator; } return new String(hex); } public static byte[] computeSha1Digest(byte[] data) { return computeDigest(data, "SHA-1"); } public static byte[] computeSha256Digest(byte[] data) { return computeDigest(data, "SHA-256"); } private static byte[] computeDigest(byte[] data, String algorithm) { try { return MessageDigest.getInstance(algorithm).digest(data); } catch (NoSuchAlgorithmException e) { return null; } } }
package com.sun.star.wizards.table; import java.util.Hashtable; import com.sun.star.awt.TextEvent; import com.sun.star.awt.VclWindowPeerAttribute; import com.sun.star.awt.XTextListener; import com.sun.star.beans.PropertyValue; import com.sun.star.beans.XPropertySet; import com.sun.star.frame.XFrame; import com.sun.star.lang.XComponent; import com.sun.star.lang.XInitialization; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.sdb.CommandType; import com.sun.star.sdbc.SQLException; import com.sun.star.task.XJobExecutor; import com.sun.star.uno.UnoRuntime; import com.sun.star.wizards.common.*; import com.sun.star.wizards.db.TableDescriptor; import com.sun.star.wizards.ui.*; public class TableWizard extends WizardDialog implements XTextListener, XCompletion{ static String slblFields; static String slblSelFields; Finalizer curFinalizer; ScenarioSelector curScenarioSelector; FieldFormatter curFieldFormatter; PrimaryKeyHandler curPrimaryKeyHandler; String sMsgWizardName = ""; public Hashtable fielditems; int wizardmode; String tablename; String serrToManyFields; String serrTableNameexists; String scomposedtablename; TableDescriptor curTableDescriptor; public static final int SONULLPAGE = 0; public static final int SOMAINPAGE = 1; public static final int SOFIELDSFORMATPAGE = 2; public static final int SOPRIMARYKEYPAGE = 3; public static final int SOFINALPAGE = 4; private String sMsgColumnAlreadyExists = ""; XComponent[] components = null; XFrame CurFrame; String WizardHeaderText[] = new String[8]; public TableWizard(XMultiServiceFactory xMSF) { super(xMSF, 41200); super.addResourceHandler("TableWizard", "dbw"); String sTitle = m_oResource.getResText(UIConsts.RID_TABLE + 1); Helper.setUnoPropertyValues(xDialogModel, new String[] { "Height","Moveable","Name","PositionX","PositionY","Step","TabIndex","Title","Width"}, new Object[] { new Integer(218),Boolean.TRUE, "DialogTable", new Integer(102),new Integer(41),new Integer(1), new Short((short)0), sTitle, new Integer(330)} ); drawNaviBar(); fielditems = new Hashtable(); //TODO if reportResouces cannot be gotten dispose officedocument if (getTableResources() == true) setRightPaneHeaders(m_oResource, UIConsts.RID_TABLE + 8, 4); } protected void leaveStep(int nOldStep, int nNewStep){ switch (nOldStep){ case SOMAINPAGE: curScenarioSelector.addColumnsToDescriptor(); break; case SOFIELDSFORMATPAGE: curFieldFormatter.updateColumnofColumnDescriptor(); String[] sfieldnames = curFieldFormatter.getFieldNames(); super.setStepEnabled(SOFIELDSFORMATPAGE, sfieldnames.length > 0); curScenarioSelector.setSelectedFieldNames(sfieldnames); break; case SOPRIMARYKEYPAGE: break; case SOFINALPAGE: break; default: break; } } protected void enterStep(int nOldStep, int nNewStep) { switch (nNewStep){ case SOMAINPAGE: break; case SOFIELDSFORMATPAGE: curFieldFormatter.initialize(curTableDescriptor, this.curScenarioSelector.getSelectedFieldNames()); break; case SOPRIMARYKEYPAGE: curPrimaryKeyHandler.initialize(); break; case SOFINALPAGE: curFinalizer.initialize(curScenarioSelector.getFirstTableName()); break; default: break; } } /* (non-Javadoc) * @see com.sun.star.wizards.ui.XCompletion#iscompleted(int) */ public boolean iscompleted(int _ndialogpage) { switch (_ndialogpage){ case SOMAINPAGE: return curScenarioSelector.iscompleted(); case SOFIELDSFORMATPAGE: return this.curFieldFormatter.iscompleted(); case SOPRIMARYKEYPAGE: if (curPrimaryKeyHandler != null) return this.curPrimaryKeyHandler.iscompleted(); case SOFINALPAGE: return this.curFinalizer.iscompleted(); default: return false; } } /* (non-Javadoc) * @see com.sun.star.wizards.ui.XCompletion#setcompleted(int, boolean) */ public void setcompleted(int _ndialogpage, boolean _biscompleted) { boolean bScenarioiscompleted = _biscompleted; boolean bFieldFormatsiscompleted = _biscompleted; boolean bPrimaryKeysiscompleted = _biscompleted; boolean bFinalPageiscompleted = _biscompleted; if (_ndialogpage == SOMAINPAGE) curFinalizer.initialize(curScenarioSelector.getFirstTableName()); else bScenarioiscompleted = iscompleted(SOMAINPAGE); if (_ndialogpage != TableWizard.SOFIELDSFORMATPAGE){ bFieldFormatsiscompleted = iscompleted(SOFIELDSFORMATPAGE); if (!bFieldFormatsiscompleted) // it might be that the Fieldformatter has not yet been initialized bFieldFormatsiscompleted = bScenarioiscompleted; // in this case query the scenarioselector } if (_ndialogpage != TableWizard.SOPRIMARYKEYPAGE && (this.curPrimaryKeyHandler != null)) bPrimaryKeysiscompleted = iscompleted(SOPRIMARYKEYPAGE); if (_ndialogpage != TableWizard.SOFINALPAGE) bFinalPageiscompleted = iscompleted(SOFINALPAGE); // Basically the finalpage is always enabled if (bScenarioiscompleted){ super.setStepEnabled(SOFIELDSFORMATPAGE, true); super.setStepEnabled(SOPRIMARYKEYPAGE, true); if (bPrimaryKeysiscompleted){ super.enablefromStep(SOFINALPAGE, true); super.enableFinishButton(bFinalPageiscompleted); } else{ super.enablefromStep(SOFINALPAGE, false); enableNextButton(false); } } else if (_ndialogpage == SOFIELDSFORMATPAGE) super.enablefromStep(super.getCurrentStep()+1, iscompleted(SOFIELDSFORMATPAGE)); else super.enablefromStep(super.getCurrentStep()+1, false); } public static void main(String args[]) { String ConnectStr = "uno:socket,host=localhost,port=8100;urp,negotiate=0,forcesynchronous=1;StarOffice.NamingService"; PropertyValue[] curproperties = null; try { XMultiServiceFactory xLocMSF = com.sun.star.wizards.common.Desktop.connect(ConnectStr); TableWizard CurTableWizard = new TableWizard(xLocMSF); if(xLocMSF != null){ System.out.println("Connected to "+ ConnectStr); curproperties = new PropertyValue[1]; curproperties[0] = Properties.createProperty("DataSourceName", "Bibliography"); //curproperties[0] = Properties.createProperty("DatabaseLocation", "file:///path/to/database.odb"); CurTableWizard.startTableWizard(xLocMSF, curproperties); } } catch(Exception exception){ exception.printStackTrace(System.out); }} public void buildSteps(){ curScenarioSelector = new ScenarioSelector(this, this.curTableDescriptor, slblFields, slblSelFields); curFieldFormatter = new FieldFormatter(this, curTableDescriptor ); if (this.curTableDescriptor.supportsCoreSQLGrammar()) curPrimaryKeyHandler = new PrimaryKeyHandler(this, curTableDescriptor); curFinalizer = new Finalizer(this, curTableDescriptor); enableNavigationButtons(false, false, false); } public boolean createTable(){ boolean bIsSuccessfull = true; boolean bTableCreated = false; String schemaname = curFinalizer.getSchemaName(); String catalogname = curFinalizer.getCatalogName(); if (curTableDescriptor.supportsCoreSQLGrammar()){ String[] keyfieldnames = curPrimaryKeyHandler.getPrimaryKeyFields(curTableDescriptor); if (keyfieldnames != null){ if (keyfieldnames.length > 0){ boolean bIsAutoIncrement = curPrimaryKeyHandler.isAutoIncremented(); bIsSuccessfull = curTableDescriptor.createTable(catalogname, schemaname, tablename, keyfieldnames, bIsAutoIncrement, curScenarioSelector.getSelectedFieldNames()); bTableCreated = true; } } } if (!bTableCreated){ bIsSuccessfull = curTableDescriptor.createTable(catalogname, schemaname, tablename, curScenarioSelector.getSelectedFieldNames()); } if ((!bIsSuccessfull) && (curPrimaryKeyHandler.isAutomaticMode())){ curTableDescriptor.dropColumnbyName(curPrimaryKeyHandler.getAutomaticFieldName()); } return bIsSuccessfull; } public void finishWizard(){ super.switchToStep(super.getCurrentStep(), SOFINALPAGE); tablename = curFinalizer.getTableName(curScenarioSelector.getFirstTableName()); scomposedtablename = curFinalizer.getComposedTableName(tablename); if (this.curTableDescriptor.isSQL92CheckEnabled()) Desktop.removeSpecialCharacters(curTableDescriptor.xMSF, Configuration.getOfficeLocale(this.curTableDescriptor.xMSF), tablename); if (tablename != ""){ if (!curTableDescriptor.hasTableByName(scomposedtablename)){ wizardmode = curFinalizer.finish(); if (createTable()){ if (wizardmode == Finalizer.MODIFYTABLEMODE) components = curTableDescriptor.switchtoDesignmode(curTableDescriptor.getComposedTableName(), com.sun.star.sdb.CommandType.TABLE,CurFrame); else if (wizardmode == Finalizer.WORKWITHTABLEMODE) components = curTableDescriptor.switchtoDataViewmode(curTableDescriptor.getComposedTableName(), com.sun.star.sdb.CommandType.TABLE,CurFrame); super.xDialog.endExecute(); } } else{ String smessage = JavaTools.replaceSubString(serrTableNameexists, tablename, "%TABLENAME"); super.showMessageBox("WarningBox", com.sun.star.awt.VclWindowPeerAttribute.OK, smessage ); curFinalizer.setFocusToTableNameControl(); } } } private void callFormWizard(){ try { Object oFormWizard = this.xMSF.createInstance("com.sun.star.wizards.form.CallFormWizard"); PropertyValue[] aProperties = new PropertyValue[4]; aProperties[0] = Properties.createProperty("ActiveConnection", curTableDescriptor.DBConnection); aProperties[1] = Properties.createProperty("DataSource", curTableDescriptor.xDataSource); aProperties[2] = Properties.createProperty("CommandType", new Integer(CommandType.TABLE)); aProperties[3] = Properties.createProperty("Command", scomposedtablename); XInitialization xInitialization = (XInitialization) UnoRuntime.queryInterface(XInitialization.class, oFormWizard); xInitialization.initialize(aProperties); XJobExecutor xJobExecutor = (XJobExecutor) UnoRuntime.queryInterface(XJobExecutor.class, oFormWizard); xJobExecutor.trigger("start"); XPropertySet prop = (XPropertySet)UnoRuntime.queryInterface(XPropertySet.class,xJobExecutor); components[0] = (XComponent)prop.getPropertyValue("Document"); components[1] = (XComponent)prop.getPropertyValue("DocumentDefinition"); } catch (Exception e) { e.printStackTrace(System.out); }} public void cancelWizard() { xDialog.endExecute(); } public void insertFormRelatedSteps(){ addRoadmap(); int i = 0; i = insertRoadmapItem(0, true, m_oResource.getResText(UIConsts.RID_TABLE + 2), SOMAINPAGE); i = insertRoadmapItem(i, false, m_oResource.getResText(UIConsts.RID_TABLE + 3), SOFIELDSFORMATPAGE); if (this.curTableDescriptor.supportsCoreSQLGrammar()) i = insertRoadmapItem(i, false, m_oResource.getResText(UIConsts.RID_TABLE + 4), SOPRIMARYKEYPAGE); i = insertRoadmapItem(i, false, m_oResource.getResText(UIConsts.RID_TABLE + 5), SOFINALPAGE); // Orderby is always supported setRoadmapInteractive(true); setRoadmapComplete(true); setCurrentRoadmapItemID((short) 1); } public XComponent[] startTableWizard(XMultiServiceFactory _xMSF, PropertyValue[] CurPropertyValue){ try{ curTableDescriptor = new TableDescriptor(xMSF, super.xWindow, this.sMsgColumnAlreadyExists); if (curTableDescriptor.getConnection(CurPropertyValue)){ if (Properties.hasPropertyValue(CurPropertyValue, "ParentFrame")) CurFrame = (XFrame) UnoRuntime.queryInterface(XFrame.class,Properties.getPropertyValue(CurPropertyValue, "ParentFrame")); else CurFrame = Desktop.getActiveFrame(xMSF); buildSteps(); createWindowPeer(); curTableDescriptor.setWindowPeer(this.xControl.getPeer()); // setAutoMnemonic("lblDialogHeader", false); insertFormRelatedSteps(); short RetValue = executeDialog(); xComponent.dispose(); switch (RetValue){ case 0: // via Cancelbutton or via sourceCode with "endExecute" if (wizardmode == Finalizer.STARTFORMWIZARDMODE) callFormWizard(); break; case 1: break; } } } catch(java.lang.Exception jexception ){ jexception.printStackTrace(System.out); } return components; } public boolean getTableResources(){ sMsgWizardName = super.m_oResource.getResText(UIConsts.RID_TABLE+1); slblFields = m_oResource.getResText(UIConsts.RID_TABLE + 19); slblSelFields = m_oResource.getResText(UIConsts.RID_TABLE + 25); serrToManyFields = m_oResource.getResText(UIConsts.RID_TABLE + 47); serrTableNameexists = m_oResource.getResText(UIConsts.RID_TABLE + 48); sMsgColumnAlreadyExists = m_oResource.getResText(UIConsts.RID_TABLE + 51); return true; } public boolean verifyfieldcount( int _icount ){ try{ int maxfieldcount = curTableDescriptor.getMaxColumnsInTable(); if (_icount >= (maxfieldcount - 1)){ // keep one column as reserve for the automaticcally created key String smessage = serrToManyFields; smessage = JavaTools.replaceSubString(smessage, String.valueOf(maxfieldcount), "%COUNT"); showMessageBox("ErrorBox", VclWindowPeerAttribute.OK, smessage); return false; } } catch (SQLException e) { e.printStackTrace(System.out); } return true; } /* (non-Javadoc) * @see com.sun.star.awt.XTextListener#textChanged(com.sun.star.awt.TextEvent) */ public void textChanged(TextEvent aTextEvent) { if (this.curTableDescriptor.isSQL92CheckEnabled()){ Object otextcomponent = UnoDialog.getModel(aTextEvent.Source); String sName = (String) Helper.getUnoPropertyValue(otextcomponent, "Text"); sName = Desktop.removeSpecialCharacters(curTableDescriptor.xMSF, Configuration.getOfficeLocale(curTableDescriptor.xMSF), sName); Helper.setUnoPropertyValue(otextcomponent, "Text", sName); } } }
package ar.util; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; /**Federates multiple byte buffers into a single byte-buffer for mem-map access to a very large file**/ //TODO: Extend beyond read-only mode public class BigFileByteBuffer { private final ByteBuffer[] buffers; private final long limit; private long position; public BigFileByteBuffer(File source) throws IOException { FileInputStream inputStream = new FileInputStream(source); FileChannel channel = inputStream.getChannel(); limit = channel.size(); buffers = new ByteBuffer[(int) limit/Integer.MAX_VALUE]; for (int i=0; i<buffers.length; i++) { int low = Math.max(0, (i-1*Integer.MAX_VALUE)); int size = (int) Math.min(Integer.MAX_VALUE, limit-low); buffers[i]=channel.map(FileChannel.MapMode.READ_ONLY, low, size); } position=0; inputStream.close(); channel.close(); } public byte get() {return getAt(position, 1).get();} public short getShort() {return getAt(position, 2).getShort();} public int getInt() {return getAt(position, 4).getInt();} public long getLong() {return getAt(position, 8).getLong();} public char getChar() {return getAt(position, 2).getChar();} public double getFloat() {return getAt(position, 4).getFloat();} public double getDouble() {return getAt(position, 8).getDouble();} public long limit() {return limit;} public void position(long at) {this.position = at;} private ByteBuffer getAt(long p, int count) { int bufferID = (int) p/Integer.MAX_VALUE; long bottom = bufferID*Integer.MAX_VALUE; long start = p-bottom; long end = start+count; if (start < 0 || start > Integer.MAX_VALUE) {throw new IllegalArgumentException();} int s = (int) start; int e = (int) end; if (end < Integer.MAX_VALUE) { //Everything is in one buffer... buffers[bufferID].position(s); return buffers[bufferID]; } else { //Split between buffers, must make a temp buffer... e = (int) end-Integer.MAX_VALUE; byte[] bytes = new byte[count]; buffers[bufferID].get(bytes, s, (int) (buffers[bufferID].limit()-start)); buffers[bufferID+1].get(bytes, 0, e); return ByteBuffer.wrap(bytes); } } }
package example; //-*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: //@homepage@ import java.awt.*; import java.awt.event.*; import java.beans.*; import javax.swing.*; public final class MainPanel extends JPanel { private MainPanel() { super(new BorderLayout()); JComboBox combo = makeComboBox(); UIManager.put("ComboBox.font", combo.getFont()); JCheckBox check = new JCheckBox("<html>addAuxiliaryLookAndFeel<br>(Disable Right Click)"); LookAndFeel auxLookAndFeel = new AuxiliaryWindowsLookAndFeel(); UIManager.addPropertyChangeListener(e -> { if (e.getPropertyName().equals("lookAndFeel")) { String lnf = e.getNewValue().toString(); if (lnf.contains("Windows")) { if (check.isSelected()) { UIManager.addAuxiliaryLookAndFeel(auxLookAndFeel); } check.setEnabled(true); } else { UIManager.removeAuxiliaryLookAndFeel(auxLookAndFeel); check.setEnabled(false); } } }); check.addActionListener(e -> { String lnf = UIManager.getLookAndFeel().getName(); if (((JCheckBox) e.getSource()).isSelected() && lnf.contains("Windows")) { UIManager.addAuxiliaryLookAndFeel(auxLookAndFeel); } else { UIManager.removeAuxiliaryLookAndFeel(auxLookAndFeel); } SwingUtilities.updateComponentTreeUI(getRootPane()); }); combo.setEditable(true); Box box = Box.createVerticalBox(); box.add(check); box.add(Box.createVerticalStrut(5)); box.add(combo); box.add(Box.createVerticalStrut(5)); box.add(makeComboBox()); box.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15)); add(box, BorderLayout.NORTH); add(new JScrollPane(new JTree())); setPreferredSize(new Dimension(320, 240)); } private static JComboBox<String> makeComboBox() { DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>(); model.addElement("aaaa"); model.addElement("aaaabbb"); model.addElement("aaaabbbcc"); model.addElement("1354123451234513512"); model.addElement("bbb1"); model.addElement("bbb12"); return new JComboBox<>(model); } public static void main(String... args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowGUI(); } }); } public static void createAndShowGUI() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JMenuBar mb = new JMenuBar(); mb.add(LookAndFeelUtil.createLookAndFeelMenu()); JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.setJMenuBar(mb); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } final class LookAndFeelUtil { private static String lookAndFeel = UIManager.getLookAndFeel().getClass().getName(); private LookAndFeelUtil() { /* Singleton */ } public static JMenu createLookAndFeelMenu() { JMenu menu = new JMenu("LookAndFeel"); ButtonGroup lafRadioGroup = new ButtonGroup(); for (UIManager.LookAndFeelInfo lafInfo: UIManager.getInstalledLookAndFeels()) { menu.add(createLookAndFeelItem(lafInfo.getName(), lafInfo.getClassName(), lafRadioGroup)); } return menu; } private static JRadioButtonMenuItem createLookAndFeelItem(String lafName, String lafClassName, ButtonGroup lafRadioGroup) { JRadioButtonMenuItem lafItem = new JRadioButtonMenuItem(lafName, lafClassName.equals(lookAndFeel)); lafItem.setActionCommand(lafClassName); lafItem.setHideActionText(true); lafItem.addActionListener(e -> { ButtonModel m = lafRadioGroup.getSelection(); try { setLookAndFeel(m.getActionCommand()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } }); lafRadioGroup.add(lafItem); return lafItem; } private static void setLookAndFeel(String lookAndFeel) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException { String oldLookAndFeel = LookAndFeelUtil.lookAndFeel; if (!oldLookAndFeel.equals(lookAndFeel)) { UIManager.setLookAndFeel(lookAndFeel); LookAndFeelUtil.lookAndFeel = lookAndFeel; updateLookAndFeel(); // firePropertyChange("lookAndFeel", oldLookAndFeel, lookAndFeel); } } private static void updateLookAndFeel() { for (Window window: Frame.getWindows()) { SwingUtilities.updateComponentTreeUI(window); } } }
package org.wso2.security.tools.scanmanager.dao; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.wso2.security.tools.scanmanager.controller.ScanController; import org.wso2.security.tools.scanmanager.model.Scan; /** * The class {@code LogDAOImpl} is the DAO implementation class that implements the persistence methods of the * Scan logs. */ @Repository public class ScanDAOImpl implements ScanDAO { private static final Logger logger = LoggerFactory.getLogger(ScanDAOImpl.class); @Autowired private SessionFactory sessionFactory; @Override public boolean persist(Scan scan) { Boolean saveFlag = true; try { Session currentSession = sessionFactory.getCurrentSession(); //saving the data in the Database currentSession.saveOrUpdate(scan); logger.debug("scan is successfully persists"); } catch (Exception ex) { //handle exception logger.error("Error occurred while persisting scan from DAO", ex); saveFlag = false; } return saveFlag; } @Override public Scan getScan(Integer scanId) { Scan scan; try { Session currentSession = sessionFactory.getCurrentSession(); scan = (Scan) currentSession.get(Scan.class, scanId); logger.debug("scan is successfully retrieved"); } catch (Exception ex) { //return the empty scan object logger.error("Error occurred while retrieving scan from DAO null scan object was returned", ex); scan = new Scan(); } return scan; } }
package com.github.aint.jblog.web.controller; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.aint.jblog.model.dao.hibernate.ArticleHibernateDao; import com.github.aint.jblog.model.dao.hibernate.CommentHibernateDao; import com.github.aint.jblog.model.dao.hibernate.HubHibernateDao; import com.github.aint.jblog.model.dao.hibernate.UserHibernateDao; import com.github.aint.jblog.model.dao.hibernate.VoiceForArticleHibernateDao; import com.github.aint.jblog.model.dao.hibernate.VoiceForCommentHibernateDao; import com.github.aint.jblog.model.entity.Article; import com.github.aint.jblog.model.entity.Comment; import com.github.aint.jblog.model.entity.User; import com.github.aint.jblog.model.entity.VoiceValue; import com.github.aint.jblog.service.data.ArticleService; import com.github.aint.jblog.service.data.CommentService; import com.github.aint.jblog.service.data.HubService; import com.github.aint.jblog.service.data.UserService; import com.github.aint.jblog.service.data.impl.ArticleServiceImpl; import com.github.aint.jblog.service.data.impl.CommentServiceImpl; import com.github.aint.jblog.service.data.impl.HubServiceImpl; import com.github.aint.jblog.service.data.impl.UserServiceImpl; import com.github.aint.jblog.service.exception.data.EntityNotFoundException; import com.github.aint.jblog.service.exception.data.UserNotFoundException; import com.github.aint.jblog.service.exception.other.XmlUserRankConfigurationException; import com.github.aint.jblog.service.other.UserRankConfiguration; import com.github.aint.jblog.service.other.impl.XmlUserRankConfiguration; import com.github.aint.jblog.service.util.HibernateUtil; import com.github.aint.jblog.web.constant.ConstantHolder; import com.github.aint.jblog.web.constant.SessionConstant; /** * This servlet votes for an article or a comment. * * @author Olexandr Tyshkovets */ @WebServlet("/vote") public class Vote extends HttpServlet { private static final long serialVersionUID = -880762514442559473L; private static final Logger logger = LoggerFactory.getLogger(Vote.class); private static final String SHOWSTORY_SERVLET_URL_PATTERN = ConstantHolder.MAPPING .getProperty("mapping.servlet.displayArticle"); private static final String USER_RANK_XML_PATH = "/com/github/aint/jblog/service/other/userRank-config.xml"; private static final String USER_RANK_DTD_PATH = "/com/github/aint/jblog/service/other/userRank-config.dtd"; private ArticleService articleService; private CommentService commentService; private HubService hubService; private UserService userService; private UserRankConfiguration userRankConfig; private Long articleId; /** * {@inheritDoc} */ @Override public void init(ServletConfig config) throws ServletException { articleService = new ArticleServiceImpl(new ArticleHibernateDao(HibernateUtil.getSessionFactory())); commentService = new CommentServiceImpl(new CommentHibernateDao(HibernateUtil.getSessionFactory())); hubService = new HubServiceImpl(new HubHibernateDao(HibernateUtil.getSessionFactory())); userService = new UserServiceImpl(new UserHibernateDao(HibernateUtil.getSessionFactory())); try { userRankConfig = new XmlUserRankConfiguration(getClass().getResourceAsStream(USER_RANK_XML_PATH), getClass().getResourceAsStream(USER_RANK_DTD_PATH)); } catch (XmlUserRankConfigurationException e) { logger.error("Failed to configurate XmlUserRank", e); throw new ServletException(e); } } /** * {@inheritDoc} */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { User user = null; try { user = userService.getByUserName((String) request.getSession(true).getAttribute( SessionConstant.USER_NAME_SESSION_ATTRIBUTE)); } catch (UserNotFoundException e) { logger.error("The user not found", e); response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } VoiceValue voiceForArticle = VoiceValue.lookUp(request.getParameter("forArticle")); if (voiceForArticle != null) { Article article = null; try { this.articleId = Long.parseLong(request.getParameter("articleId")); article = articleService.get(this.articleId); articleService.voteForArticle(article, user, voiceForArticle, new VoiceForArticleHibernateDao(HibernateUtil.getSessionFactory())); } catch (NumberFormatException e) { logger.warn("The article's id parameter is uncorrect {} {}" + e.getClass() + " " + e.getMessage()); response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } catch (EntityNotFoundException e) { logger.info("The article not found", e); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } userService.updateRating(article.getAuthor(), voiceForArticle); userService.updateRank(article.getAuthor(), userRankConfig); hubService.updateRating(article.getHub(), voiceForArticle); } VoiceValue voiceForComment = VoiceValue.lookUp(request.getParameter("forComment")); if (voiceForComment != null) { Comment comment = null; try { comment = commentService.get(Long.parseLong(request.getParameter("commentId"))); commentService.voteForComment(comment, user, voiceForComment, new VoiceForCommentHibernateDao(HibernateUtil.getSessionFactory())); this.articleId = comment.getArticle().getId(); } catch (NumberFormatException e) { logger.error("The comment's id parameter is uncorrect {} {}" + e.getClass() + " " + e.getMessage()); response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } catch (EntityNotFoundException e) { logger.error("The comment not found", e); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } userService.updateRating(comment.getAuthor(), voiceForComment); userService.updateRank(comment.getAuthor(), userRankConfig); hubService.updateRating(comment.getArticle().getHub(), voiceForArticle); } response.sendRedirect(SHOWSTORY_SERVLET_URL_PATTERN + "/" + articleId); } /** * {@inheritDoc} */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }