repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
jfreyss/spirit
src/com/actelion/research/spiritapp/ui/result/edit/ResultDiscardDlg.java
3202
/* * Spirit, a study/biosample management tool for research. * Copyright (C) 2018 Idorsia Pharmaceuticals Ltd., Hegenheimermattweg 91, * CH-4123 Allschwil, Switzerland. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * * @author Joel Freyss */ package com.actelion.research.spiritapp.ui.result.edit; import java.awt.BorderLayout; import java.awt.Dimension; import java.util.List; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import com.actelion.research.spiritapp.Spirit; import com.actelion.research.spiritapp.ui.SpiritFrame; import com.actelion.research.spiritapp.ui.result.ResultTable; import com.actelion.research.spiritapp.ui.util.SpiritChangeListener; import com.actelion.research.spiritapp.ui.util.SpiritChangeType; import com.actelion.research.spiritcore.business.result.Result; import com.actelion.research.spiritcore.services.SpiritRights; import com.actelion.research.spiritcore.services.SpiritUser; import com.actelion.research.spiritcore.services.dao.DAOResult; import com.actelion.research.spiritcore.services.dao.JPAUtil; import com.actelion.research.util.ui.FastFont; import com.actelion.research.util.ui.JCustomLabel; import com.actelion.research.util.ui.UIUtils; public class ResultDiscardDlg { public static void createDialogForDelete(List<Result> results) throws Exception { //this.biosamples = biosamples; SpiritUser user = Spirit.askForAuthentication(); try { JPAUtil.pushEditableContext(SpiritFrame.getUser()); results = JPAUtil.reattach(results); for (Result result : results) { if(!SpiritRights.canDelete(result, user)) throw new Exception("You cannot delete "+result); } ResultTable table = new ResultTable(); table.setRows(results); JScrollPane sp = new JScrollPane(table); sp.setPreferredSize(new Dimension(700, 400)); JPanel msgPanel = new JPanel(new BorderLayout()); msgPanel.add(BorderLayout.NORTH, new JCustomLabel("Are you sure you want to 'DEFINITELY' delete " + (results.size()>1? "those " + results.size() + " results": " this result"), FastFont.BOLD)); msgPanel.add(BorderLayout.CENTER, sp); int res = JOptionPane.showOptionDialog(UIUtils.getMainFrame(), msgPanel, "DELETE Results", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, new String[] {"Delete", "Cancel"}, "Cancel"); if(res!=0) return; if(!Spirit.askReasonForChange()) return; DAOResult.deleteResults(results, user); } finally { JPAUtil.popEditableContext(); } SpiritChangeListener.fireModelChanged(SpiritChangeType.MODEL_DELETED, Result.class, results); } }
gpl-3.0
zqad/zmask
src/org/zkt/zmask/ZmaskFrame.java
30422
/* * ZmaskFrame.java * Copyright (C) 2010-2011 Jonas Eriksson * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.zkt.zmask; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.KeyEvent; import java.awt.event.InputEvent; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.File; import javax.imageio.ImageIO; import javax.swing.Timer; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JButton; import javax.swing.JToggleButton; import javax.swing.JMenu; import javax.swing.JPopupMenu; import javax.swing.JPanel; import javax.swing.JToolBar; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.ActionMap; import javax.swing.KeyStroke; import javax.swing.JPanel; import javax.swing.JDesktopPane; import javax.swing.JOptionPane; import javax.swing.JProgressBar; import java.util.List; import java.util.ResourceBundle; import java.beans.PropertyVetoException; import org.zkt.zmask.Image.StepException; import org.zkt.zmask.masks.RunMask; import org.zkt.zmask.utils.ComponentGroup; import org.zkt.zmask.utils.Resources; import org.zkt.zmask.utils.FileManager; import org.zkt.zmask.utils.PropertyManager; import org.zkt.zmask.tools.Select; import java.awt.Rectangle; import java.awt.Dimension; /** * The application's main frame. * * @author zqad */ public class ZmaskFrame extends JFrame { public static final long serialVersionUID = 1; private ActionMap actions; private Resources resources; private Resources actionResources; private ActionListener actionHandler; private ComponentGroup cgAll, cgUndoPossible, cgRedoPossible, cgChanged, cgImageActive, cgSelectionActive; private JToggleButton handToggleButton; private JToggleButton selectToggleButton; private JToggleButton zoomToggleButton; private JFileChooser openFileChooser; private JFileChooser saveAsFileChooser; private JProgressBar progressBar; private JDesktopPane mainDesktopPane; public ZmaskFrame() { super(); actions = new ActionMap(); resources = new Resources("org.zkt.zmask.resources.ZmaskFrame"); actionResources = new Resources("org.zkt.zmask.resources.ActionNames"); // NOI18N cgAll = new ComponentGroup(); cgUndoPossible = new ComponentGroup(); cgRedoPossible = new ComponentGroup(); cgChanged = new ComponentGroup(); cgImageActive = new ComponentGroup(); cgSelectionActive = new ComponentGroup(); actionHandler = new ActionHandler(); initComponents(); int messageTimeout = resources.getInt("StatusBar.messageTimeout"); messageTimer = new Timer(messageTimeout, new ActionListener() { public void actionPerformed(ActionEvent e) { } }); messageTimer.setRepeats(false); progressBar.setVisible(false); // connecting action tasks to status bar via TaskMonitor /*TaskMonitor taskMonitor = new TaskMonitor(); taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() { public void propertyChange(java.beans.PropertyChangeEvent evt) { String propertyName = evt.getPropertyName(); if ("started".equals(propertyName)) { progressBar.setVisible(true); progressBar.setIndeterminate(true); } else if ("done".equals(propertyName)) { progressBar.setVisible(false); progressBar.setValue(0); } else if ("message".equals(propertyName)) { String text = (String)(evt.getNewValue()); messageTimer.restart(); } else if ("progress".equals(propertyName)) { int value = (Integer)(evt.getNewValue()); progressBar.setVisible(true); progressBar.setIndeterminate(false); progressBar.setValue(value); } } });*/ // Init state State.setMainDesktopPane(mainDesktopPane); RunMask.init(); PropertyManager.loadProperties(); setSize(700, 500); /* Do initial button refresh */ refreshButtons(); } public void showAboutBox() { if (aboutBox == null) { aboutBox = new ZmaskAboutBox(this); aboutBox.setLocationRelativeTo(this); } aboutBox.setVisible(true); } private void initActions() { } private JButton createButton(String button, String action, ComponentGroup cg, boolean enabled) { JButton b = new JButton(); b.addActionListener(actionHandler); b.setActionCommand(action); b.setIcon(resources.getIcon(button + ".icon")); b.setToolTipText(actionResources.getString(action + ".short")); b.setFocusable(false); b.setEnabled(enabled); b.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); b.setName(button); b.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); cgAll.add(b); if (cg != null) cg.add(b); return b; } private JToggleButton createToggleButton(String button, String action, ComponentGroup cg, boolean enabled, boolean selected) { JToggleButton b = new JToggleButton(); b.addActionListener(actionHandler); b.setActionCommand(action); b.setIcon(resources.getIcon(button + ".icon")); b.setEnabled(enabled); b.setSelected(selected); b.setToolTipText(actionResources.getString(action + ".short")); b.setFocusable(false); b.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); b.setName(button); b.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); cgAll.add(b); if (cg != null) cg.add(b); return b; } private JMenuItem createMenuItem(String menuitem, String action, ComponentGroup cg) { return createMenuItem(menuitem, action, cg, null); } private JMenuItem createMenuItem(String menuItem, String action, ComponentGroup cg, KeyStroke ks) { JMenuItem i = new JMenuItem(); i.setActionCommand(action); if (ks != null) i.setAccelerator(ks); i.setText(resources.getString(menuItem + ".text")); i.setName(menuItem); // NOI18N i.addActionListener(actionHandler); cgAll.add(i); if (cg != null) cg.add(i); return i; } /* This method is called from within the constructor to * initialize the form. */ private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; mainDesktopPane = new JDesktopPane(); JPanel mainPanel = new JPanel(); progressBar = new javax.swing.JProgressBar(); status = new org.zkt.zmask.Statusbar(); mainPanel.setName("mainPanel"); // NOI18N mainPanel.setLayout(new java.awt.GridBagLayout()); /* *********** * * * Toolbar * * * *********** */ JToolBar mainToolBar = new JToolBar(); mainToolBar.setFloatable(false); mainToolBar.setRollover(true); mainToolBar.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); mainToolBar.setName("mainToolBar"); // NOI18N /* Open / save */ mainToolBar.add(createButton("openButton", "open", null, true)); mainToolBar.add(createButton("saveButton", "save", cgChanged, false)); mainToolBar.add(new javax.swing.JToolBar.Separator()); /* Undo / redo */ mainToolBar.add(createButton("undoButton", "undo", cgUndoPossible, false)); mainToolBar.add(createButton("redoButton", "redo", cgRedoPossible, false)); mainToolBar.add(new javax.swing.JToolBar.Separator()); /* Tools */ selectToggleButton = createToggleButton("selectToggleButton", "toolSelect", cgImageActive, false, true); mainToolBar.add(selectToggleButton); zoomToggleButton = createToggleButton("zoomToggleButton", "toolZoom", cgImageActive, false, false); mainToolBar.add(zoomToggleButton); handToggleButton = createToggleButton("handToggleButton", "toolHand", cgImageActive, false, false); mainToolBar.add(handToggleButton); mainToolBar.add(new javax.swing.JToolBar.Separator()); /* Selection shifts */ mainToolBar.add(createButton("shiftSelectionLeftButton", "shiftSelectionLeft", cgSelectionActive, false)); mainToolBar.add(createButton("shiftSelectionDownButton", "shiftSelectionDown", cgSelectionActive, false)); mainToolBar.add(createButton("shiftSelectionUpButton", "shiftSelectionUp", cgSelectionActive, false)); mainToolBar.add(createButton("shiftSelectionRightButton", "shiftSelectionRight", cgSelectionActive, false)); mainToolBar.add(new javax.swing.JToolBar.Separator()); /* Rotate */ mainToolBar.add(createButton("rotateCCWButton", "rotateCCW", cgImageActive, false)); mainToolBar.add(createButton("rotateCWButton", "rotateCW", cgImageActive, false)); mainToolBar.add(new javax.swing.JToolBar.Separator()); /* Selection content modifiers */ mainToolBar.add(createButton("rgbRotateButton", "rgbRotate", cgSelectionActive, false)); mainToolBar.add(createButton("xorButton", "xor", cgSelectionActive, false)); mainToolBar.add(createButton("invertButton", "invert", cgSelectionActive, false)); mainToolBar.add(createButton("flipVerticalButton", "flipVertical", cgSelectionActive, false)); mainToolBar.add(createButton("flipHorizontalButton", "flipHorizontal", cgSelectionActive, false)); mainToolBar.add(createButton("verticalGlassButton", "verticalGlass", cgSelectionActive, false)); mainToolBar.add(createButton("horizontalGlassButton", "horizontalGlass", cgSelectionActive, false)); mainToolBar.add(createButton("winButton", "win", cgSelectionActive, false)); mainToolBar.add(createButton("mekoPlusButton", "mekoPlus", cgSelectionActive, false)); mainToolBar.add(createButton("mekoMinusButton", "mekoMinus", cgSelectionActive, false)); mainToolBar.add(createButton("flButton", "fl", cgSelectionActive, false)); mainToolBar.add(createButton("q0Button", "q0", cgSelectionActive, false)); /* ********** * * * Layout * * * ********** */ gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; mainPanel.add(mainToolBar, gridBagConstraints); mainDesktopPane.setMinimumSize(new java.awt.Dimension(640, 480)); mainDesktopPane.setName("mainDesktopPane"); // NOI18N mainDesktopPane.setPreferredSize(null); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.ipady = 75; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; mainPanel.add(mainDesktopPane, gridBagConstraints); status.setMaximumSize(new java.awt.Dimension(758, 26)); status.setMinimumSize(new java.awt.Dimension(758, 26)); status.setName("status"); // NOI18N status.setPreferredSize(new java.awt.Dimension(758, 26)); progressBar.setMaximumSize(new java.awt.Dimension(148, 14)); progressBar.setMinimumSize(new java.awt.Dimension(148, 14)); progressBar.setName("progressBar"); // NOI18N javax.swing.GroupLayout statusLayout = new javax.swing.GroupLayout(status); status.setLayout(statusLayout); statusLayout.setHorizontalGroup( statusLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, statusLayout.createSequentialGroup() .addContainerGap(616, Short.MAX_VALUE) .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); statusLayout.setVerticalGroup( statusLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, statusLayout.createSequentialGroup() .addContainerGap() .addComponent(progressBar, javax.swing.GroupLayout.DEFAULT_SIZE, 14, Short.MAX_VALUE)) ); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTH; mainPanel.add(status, gridBagConstraints); /* *********** * * * Menubar * * * *********** */ JMenuBar menuBar = new JMenuBar(); menuBar.setName("menuBar"); /* File menu */ JMenu fileMenu = new JMenu(); fileMenu.setMnemonic('F'); fileMenu.setText(resources.getString("fileMenu.text")); fileMenu.setName("fileMenu"); fileMenu.add(createMenuItem("openMenuItem", "open", null, KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK))); fileMenu.add(createMenuItem("closeMenuItem", "close", cgImageActive, KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.CTRL_MASK))); fileMenu.add(createMenuItem("saveMenuItem", "save", cgChanged, KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK))); fileMenu.add(createMenuItem("saveAsMenuItem", "saveAs", cgImageActive, KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK | InputEvent.SHIFT_MASK))); fileMenu.add(new javax.swing.JPopupMenu.Separator()); fileMenu.add(createMenuItem("quitMenuItem", "quit", null, KeyStroke.getKeyStroke(KeyEvent.VK_Q, InputEvent.CTRL_MASK | InputEvent.SHIFT_MASK))); menuBar.add(fileMenu); /* Edit menu */ JMenu editMenu = new JMenu(); editMenu.setMnemonic('E'); editMenu.setText(resources.getString("editMenu.text")); // NOI18N editMenu.setName("editMenu"); // NOI18N editMenu.add(createMenuItem("undoMenuItem", "undo", cgUndoPossible, KeyStroke.getKeyStroke(KeyEvent.VK_Z, InputEvent.CTRL_MASK))); editMenu.add(createMenuItem("redoMenuItem", "redo", cgRedoPossible, KeyStroke.getKeyStroke(KeyEvent.VK_Y, InputEvent.CTRL_MASK))); editMenu.add(new javax.swing.JPopupMenu.Separator()); editMenu.add(createMenuItem("propertiesMenuItem", "properties", null, KeyStroke.getKeyStroke(KeyEvent.VK_P, InputEvent.CTRL_MASK))); menuBar.add(editMenu); /* View menu */ JMenu viewMenu = new JMenu(); viewMenu.setMnemonic('V'); viewMenu.setText(resources.getString("viewMenu.text")); // NOI18N viewMenu.setName("viewMenu"); // NOI18N viewMenu.add(createMenuItem("zoomInMenuItem", "zoomIn", cgImageActive, KeyStroke.getKeyStroke(KeyEvent.VK_PLUS, InputEvent.CTRL_MASK))); viewMenu.add(createMenuItem("zoomOutMenuItem", "zoomOut", cgImageActive, KeyStroke.getKeyStroke(KeyEvent.VK_MINUS, InputEvent.CTRL_MASK))); viewMenu.add(createMenuItem("zoom11MenuItem", "zoom11", cgImageActive, KeyStroke.getKeyStroke(KeyEvent.VK_1, InputEvent.CTRL_MASK))); viewMenu.add(createMenuItem("zoomFitMenuItem", "zoomFit", cgImageActive)); menuBar.add(viewMenu); /* Image menu */ JMenu imageMenu = new JMenu(); imageMenu.setMnemonic('I'); imageMenu.setText(resources.getString("imageMenu.text")); imageMenu.setName("imageMenu"); imageMenu.add(createMenuItem("selectAllMenuItem", "selectAll", cgImageActive, KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK))); imageMenu.add(createMenuItem("selectNoneMenuItem", "selectNone", cgSelectionActive)); imageMenu.add(new javax.swing.JPopupMenu.Separator()); imageMenu.add(createMenuItem("shiftSelectionLeftMenuItem", "shiftSelectionLeft", cgSelectionActive, KeyStroke.getKeyStroke(KeyEvent.VK_H, InputEvent.CTRL_MASK))); imageMenu.add(createMenuItem("shiftSelectionDownMenuItem", "shiftSelectionDown", cgSelectionActive, KeyStroke.getKeyStroke(KeyEvent.VK_J, InputEvent.CTRL_MASK))); imageMenu.add(createMenuItem("shiftSelectionUpMenuItem", "shiftSelectionUp", cgSelectionActive, KeyStroke.getKeyStroke(KeyEvent.VK_K, InputEvent.CTRL_MASK))); imageMenu.add(createMenuItem("shiftSelectionRightMenuItem", "shiftSelectionRight", cgSelectionActive, KeyStroke.getKeyStroke(KeyEvent.VK_L, InputEvent.CTRL_MASK))); imageMenu.add(new javax.swing.JPopupMenu.Separator()); imageMenu.add(createMenuItem("rotateCCWMenuItem", "rotateCCW", cgImageActive, KeyStroke.getKeyStroke(KeyEvent.VK_R, InputEvent.CTRL_MASK | InputEvent.SHIFT_MASK))); imageMenu.add(createMenuItem("rotateCWMenuItem", "rotateCW", cgImageActive, KeyStroke.getKeyStroke(KeyEvent.VK_R, InputEvent.CTRL_MASK))); menuBar.add(imageMenu); /* Mask menu */ JMenu maskMenu = new JMenu(); maskMenu.setMnemonic('M'); maskMenu.setText(resources.getString("maskMenu.text")); maskMenu.setName("maskMenu"); maskMenu.add(createMenuItem("rgbRotateMenuItem", "rgbRotate", cgSelectionActive)); maskMenu.add(createMenuItem("xorMenuItem", "xor", cgSelectionActive)); maskMenu.add(createMenuItem("invertMenuItem", "invert", cgSelectionActive)); maskMenu.add(createMenuItem("flipVerticalMenuItem", "flipVertical", cgSelectionActive)); maskMenu.add(createMenuItem("flipHorizontalMenuItem", "flipHorizontal", cgSelectionActive)); maskMenu.add(createMenuItem("verticalGlassMenuItem", "verticalGlass", cgSelectionActive)); maskMenu.add(createMenuItem("horizontalGlassMenuItem", "horizontalGlass", cgSelectionActive)); maskMenu.add(createMenuItem("winMenuItem", "win", cgSelectionActive)); maskMenu.add(createMenuItem("mekoPlusMenuItem", "mekoPlus", cgSelectionActive)); maskMenu.add(createMenuItem("mekoMinusMenuItem", "mekoMinus", cgSelectionActive)); maskMenu.add(createMenuItem("flMenuItem", "fl", cgSelectionActive)); maskMenu.add(createMenuItem("q0MenuItem", "q0", cgSelectionActive)); menuBar.add(maskMenu); /* Help Menu */ JMenu helpMenu = new JMenu(); helpMenu.setMnemonic('H'); helpMenu.setText(resources.getString("helpMenu.text")); helpMenu.setName("helpMenu"); helpMenu.add(createMenuItem("aboutMenuItem", "showAboutBox", null)); menuBar.add(helpMenu); /* Open file chooser */ openFileChooser = new javax.swing.JFileChooser(); openFileChooser.setName("openFileChooser"); List<FileNameExtensionFilter> openFileChooserFilters = FileManager.generateFileFilters(false); for (FileNameExtensionFilter filter : openFileChooserFilters) openFileChooser.addChoosableFileFilter(filter); openFileChooser.setFileFilter(openFileChooserFilters.get(0)); /* Save as file chooser */ saveAsFileChooser = new javax.swing.JFileChooser(); saveAsFileChooser.setDialogType(JFileChooser.SAVE_DIALOG); saveAsFileChooser.setName("saveAsFileChooser"); List<FileNameExtensionFilter> saveAsFileChooserFilters = FileManager.generateFileFilters(true); for (FileNameExtensionFilter filter : saveAsFileChooserFilters) saveAsFileChooser.addChoosableFileFilter(filter); saveAsFileChooser.setFileFilter(saveAsFileChooserFilters.get(0)); setJMenuBar(menuBar); /* ***************** * * * Settings pane * * * ***************** */ JOptionPane settingsPane = new JOptionPane(); settingsPane.setName("settingsPane"); add(mainPanel); } private class UndoRedoMouseAdapter extends MouseAdapter { private int steps; private boolean undo; public UndoRedoMouseAdapter(int steps, boolean undo) { super(); this.steps = steps; this.undo = undo; } public void mouseClicked(MouseEvent evt) { try { if (undo) State.getCurrentImage().undo(steps); else State.getCurrentImage().redo(steps); } catch(StepException se) { // Something is wrong.. State.refreshButtons(); se.printStackTrace(); } } } public Statusbar getStatusbar() { return status; } public void refreshButtons() { // Refresh buttons controlled by currentImage Image ci = State.getCurrentImage(); if (ci == null) { cgImageActive.setEnabled(false); cgChanged.setEnabled(false); cgUndoPossible.setEnabled(false); cgRedoPossible.setEnabled(false); cgSelectionActive.setEnabled(false); } else { cgImageActive.setEnabled(true); cgChanged.setEnabled(ci.isChanged()); cgUndoPossible.setEnabled(ci.isUndoPossible()); cgRedoPossible.setEnabled(ci.isRedoPossible()); cgSelectionActive.setEnabled(ci.getSelection() != null); } } /************************ * ACTIONS */ // Open/save public void openAction() { // TODO: openFileChooser.setCurrentDirectory(); int r = openFileChooser.showOpenDialog(this); if (r == JFileChooser.ERROR_OPTION) { JOptionPane.showMessageDialog(State.getMainDesktopPane(), resources.getString("fileLoadFaultySelection.title"), resources.getString("fileLoadFaultySelection.text"), JOptionPane.ERROR_MESSAGE); return; } if (r != JFileChooser.APPROVE_OPTION) return; BufferedImage image; File file = openFileChooser.getSelectedFile(); try { image = FileManager.loadFile(file); } catch (IOException e) { e.printStackTrace(); JOptionPane.showMessageDialog(State.getMainDesktopPane(), resources.getString("fileLoadIOError.title"), resources.getString("fileLoadIOError.text"), JOptionPane.ERROR_MESSAGE); return; } // Create window and add to destination desktop pane JDesktopPane destinationContainer = State.getMainDesktopPane(); String name = file.getName(); ImageWindow iw = new ImageWindow(name, image, destinationContainer); int lastDot = name.lastIndexOf('.'); // neither foo nor .foo is accepted if (lastDot > 0) { iw.getImagePanel().getImage().setFileAndFormat(file, name.substring(lastDot + 1)); } destinationContainer.add(iw); try { iw.setSelected(true); } catch (PropertyVetoException pve) { // Don't care } } private boolean saveImage(Image image, String format, File file) { image.setFileAndFormat(file, format); return saveImage(image); } private boolean saveImage(Image image) { try { if (!image.save()) { JOptionPane.showMessageDialog(State.getMainDesktopPane(), resources.getString("fileSaveFormatError.text") + " '" + image.getFormat() + "'", resources.getString("fileSaveFormatError.title"), JOptionPane.ERROR_MESSAGE); return false; } } catch (IOException e) { e.printStackTrace(); JOptionPane.showMessageDialog(State.getMainDesktopPane(), resources.getString("fileSaveIOError.title"), resources.getString("fileSaveIOError.text"), JOptionPane.ERROR_MESSAGE); return false; } return true; } public boolean saveAction(Image image) { File source = image.getFile(); if (source == null) { return __saveAsAction(image); } else { return saveImage(image, image.getFormat(), source); } } public boolean saveAction() { return saveAction(State.getCurrentImage()); } private boolean __saveAsAction(Image image) { int r = saveAsFileChooser.showOpenDialog(this); if (r == JFileChooser.ERROR_OPTION) { JOptionPane.showMessageDialog(State.getMainDesktopPane(), resources.getString("fileSaveFaultySelection.title"), resources.getString("fileSaveFaultySelection.text"), JOptionPane.ERROR_MESSAGE); return false; } if (r != JFileChooser.APPROVE_OPTION) return false; File selected = saveAsFileChooser.getSelectedFile(); String name = selected.getName(); String format = "jpeg"; int lastDot = name.lastIndexOf('.'); // neither foo nor .foo is accepted if (lastDot > 0) { format = name.substring(lastDot + 1); } return saveImage(image, format, selected); } public void saveAsAction() { Image image = State.getCurrentImage(); __saveAsAction(image); } public boolean closeAction(Image image) { image.getImagePanel().getParentImageWindow().close(); return true; } public void closeAction() { closeAction(State.getCurrentImage()); } // Undo, redo public void undoAction() { try { State.getCurrentImage().undo(); } catch (Image.StepException e) { State.refreshButtons(); } } public void redoAction() { try { State.getCurrentImage().redo(); } catch (Image.StepException e) { State.refreshButtons(); } } // Show properties dialog public void propertiesAction() { if (propertiesDialog == null) { propertiesDialog = new PropertiesDialog(this); propertiesDialog.setLocationRelativeTo(this); } propertiesDialog.setVisible(true); } // Tools public void toolSelectAction() { selectToggleButton.setSelected(true); zoomToggleButton.setSelected(false); handToggleButton.setSelected(false); State.setCurrentTool(State.Tools.SELECT_TOOL); } public void toolZoomAction() { selectToggleButton.setSelected(false); zoomToggleButton.setSelected(true); handToggleButton.setSelected(false); State.setCurrentTool(State.Tools.ZOOM_TOOL); } public void toolHandAction() { selectToggleButton.setSelected(false); zoomToggleButton.setSelected(false); handToggleButton.setSelected(true); State.setCurrentTool(State.Tools.HAND_TOOL); } // Shift selection public void shiftSelectionLeftAction() { State.getCurrentImage().shiftSelection(-1, 0); } public void shiftSelectionDownAction() { State.getCurrentImage().shiftSelection(0, 1); } public void shiftSelectionUpAction() { State.getCurrentImage().shiftSelection(0, -1); } public void shiftSelectionRightAction() { State.getCurrentImage().shiftSelection(1, 0); } // Rotate public void rotateCCWAction() { RunMask.run(State.getCurrentImage(), "RotateCCW"); } public void rotateCWAction() { RunMask.run(State.getCurrentImage(), "RotateCW"); } // Filters public void rgbRotateAction() { RunMask.run(State.getCurrentImage(), "RGBRotate"); } public void xorAction() { RunMask.run(State.getCurrentImage(), "XOR"); } public void invertAction() { RunMask.run(State.getCurrentImage(), "Invert"); } public void flipVerticalAction() { RunMask.run(State.getCurrentImage(), "FlipVertical"); } public void flipHorizontalAction() { RunMask.run(State.getCurrentImage(), "FlipHorizontal"); } public void verticalGlassAction() { RunMask.run(State.getCurrentImage(), "VerticalGlass"); } public void horizontalGlassAction() { RunMask.run(State.getCurrentImage(), "HorizontalGlass"); } public void winAction() { RunMask.run(State.getCurrentImage(), "Win"); } public void mekoPlusAction() { RunMask.run(State.getCurrentImage(), "MekoPlus"); } public void mekoMinusAction() { RunMask.run(State.getCurrentImage(), "MekoMinus"); } public void flAction() { RunMask.run(State.getCurrentImage(), "FL"); } public void q0Action() { RunMask.run(State.getCurrentImage(), "Q0"); } // Menu-only actions public void zoomInAction() { State.getCurrentImage().getImagePanel().zoomIn(); } public void zoomOutAction() { State.getCurrentImage().getImagePanel().zoomOut(); } public void zoom11Action() { State.getCurrentImage().getImagePanel().zoom11(); } public void zoomFitAction() { State.getCurrentImage().getImagePanel().zoomFit(); } public void selectAllAction() { Image image = State.getCurrentImage(); Dimension dim = GeneralProperties.getInstance().getBlockSize(); int width = image.getImageWidth() - 1; // Remove one to get end pixels int height = image.getImageHeight() - 1; Rectangle selection = new Rectangle(0, 0, width - width % dim.width, height - height % dim.height); Select select = new Select(image, selection); image.addTool(select, actionResources.getString("selectAll.short")); select.commit(0); } public void selectNoneAction() { Image image = State.getCurrentImage(); Select select = new Select(image, new Rectangle(0, 0, 0, 0)); image.addTool(select, actionResources.getString("selectNone.short")); select.commit(0); } public void quitAction() { for (Image image : State.getAllImages()) { if (!closeAction(image)) return; } System.exit(0); } private org.zkt.zmask.Statusbar status; private final Timer messageTimer; private JDialog aboutBox; private JDialog propertiesDialog; private class ActionHandler implements ActionListener { public void actionPerformed(ActionEvent ae) { String ac = ae.getActionCommand(); /* This is terrible */ if (ac.equals("close")) closeAction(); else if (ac.equals("fl")) flAction(); else if (ac.equals("flipHorizontal")) flipHorizontalAction(); else if (ac.equals("flipVertical")) flipVerticalAction(); else if (ac.equals("horizontalGlass")) horizontalGlassAction(); else if (ac.equals("invert")) invertAction(); else if (ac.equals("mekoMinus")) mekoMinusAction(); else if (ac.equals("mekoPlus")) mekoPlusAction(); else if (ac.equals("open")) openAction(); else if (ac.equals("properties")) propertiesAction(); else if (ac.equals("q0")) q0Action(); else if (ac.equals("quit")) quitAction(); else if (ac.equals("redo")) redoAction(); else if (ac.equals("rgbRotate")) rgbRotateAction(); else if (ac.equals("rotateCCW")) rotateCCWAction(); else if (ac.equals("rotateCW")) rotateCWAction(); else if (ac.equals("save")) saveAction(); else if (ac.equals("saveAs")) saveAsAction(); else if (ac.equals("selectAll")) selectAllAction(); else if (ac.equals("selectNone")) selectNoneAction(); else if (ac.equals("shiftSelectionDown")) shiftSelectionDownAction(); else if (ac.equals("shiftSelectionLeft")) shiftSelectionLeftAction(); else if (ac.equals("shiftSelectionRight")) shiftSelectionRightAction(); else if (ac.equals("shiftSelectionUp")) shiftSelectionUpAction(); else if (ac.equals("showAboutBox")) showAboutBox(); else if (ac.equals("toolHand")) toolHandAction(); else if (ac.equals("toolSelect")) toolSelectAction(); else if (ac.equals("toolZoom")) toolZoomAction(); else if (ac.equals("undo")) undoAction(); else if (ac.equals("verticalGlass")) verticalGlassAction(); else if (ac.equals("win")) winAction(); else if (ac.equals("xor")) xorAction(); else if (ac.equals("zoom11")) zoom11Action(); else if (ac.equals("zoomFit")) zoomFitAction(); else if (ac.equals("zoomIn")) zoomInAction(); else if (ac.equals("zoomOut")) zoomOutAction(); } } }
gpl-3.0
CCAFS/ccafs-ap
impactPathways/src/main/java/org/cgiar/ccafs/ap/data/dao/mysql/MySQLInstitutionDAO.java
24864
/***************************************************************** * This file is part of CCAFS Planning and Reporting Platform. * CCAFS P&R is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * at your option) any later version. * CCAFS P&R is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with CCAFS P&R. If not, see <http://www.gnu.org/licenses/>. * *************************************************************** */ package org.cgiar.ccafs.ap.data.dao.mysql; import org.cgiar.ccafs.ap.data.dao.InstitutionDAO; import org.cgiar.ccafs.utils.db.DAOManager; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.google.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Hector Fabio Tobón R. * @author Javier Andrés Gallego. * @author Carlos Alberto Martínez M. */ public class MySQLInstitutionDAO implements InstitutionDAO { public static Logger LOG = LoggerFactory.getLogger(MySQLInstitutionDAO.class); private DAOManager databaseManager; @Inject public MySQLInstitutionDAO(DAOManager databaseManager) { this.databaseManager = databaseManager; } @Override public boolean deleteProjectPartnerContributeInstitution(int projectPartnerID, int institutionID) { LOG.debug(">> deleteProjectPartnerContributeInstitution(projectPartnerID={}, institutionID={})", projectPartnerID, institutionID); String query = "DELETE FROM project_partner_contributions WHERE project_partner_id = ? AND contribution_institution_id = ?"; int rowsUpdated = databaseManager.delete(query, new Object[] {projectPartnerID, institutionID}); if (rowsUpdated >= 0) { LOG.debug("<< deleteProjectPartnerContributeInstitution():{}", true); return true; } LOG.debug("<< deleteProjectPartnerContributeInstitution:{}", false); return false; } @Override public List<Map<String, String>> getAllInstitutions() { LOG.debug(">> getAllInstitutions( )"); StringBuilder query = new StringBuilder(); query.append("SELECT i.id, i.name, i.acronym, i.is_ppa, i.website_link, i.institution_type_id,i.program_id, "); query.append("lc.id as loc_elements_id, lc.name as loc_elements_name,lc.code as loc_elements_code, "); query.append("it.name as institution_type_name, it.acronym as institution_type_acronym, "); query.append("ip.id as program_id, ip.name as program_name, ip.acronym as program_acronym "); query.append("FROM institutions i "); query.append("INNER JOIN institution_types it ON it.id=i.institution_type_id "); query.append("LEFT JOIN loc_elements lc ON lc.id=i.country_id "); query.append("LEFT JOIN ip_programs ip ON ip.id=i.program_id "); query.append("ORDER BY i.acronym, i.name, loc_elements_name ASC "); LOG.debug("-- getAllInstitutions() > Calling method executeQuery to get the results"); return this.getData(query.toString()); } @Override public List<Map<String, String>> getAllInstitutionTypes() { List<Map<String, String>> institutionsTypeDataList = new ArrayList<>(); StringBuilder query = new StringBuilder(); query.append("SELECT it.* "); query.append("FROM institution_types it "); query.append("ORDER BY it.name "); try (Connection con = databaseManager.getConnection()) { ResultSet rs = databaseManager.makeQuery(query.toString(), con); while (rs.next()) { Map<String, String> institutionTypeData = new HashMap<String, String>(); institutionTypeData.put("id", rs.getString("id")); institutionTypeData.put("name", rs.getString("name")); institutionTypeData.put("acronym", rs.getString("acronym")); institutionsTypeDataList.add(institutionTypeData); } con.close(); } catch (SQLException e) { LOG.error("Exception arised getting the institutions type for the user {}.", e); } return institutionsTypeDataList; } @Override public List<Map<String, String>> getAllPPAInstitutions() { LOG.debug(">> getAllPPAInstitutions( )"); StringBuilder query = new StringBuilder(); query.append("SELECT i.id, i.name, i.acronym, i.is_ppa, i.website_link, i.institution_type_id, i.program_id, "); query.append("lc.id as loc_elements_id, lc.name as loc_elements_name,lc.code as loc_elements_code, "); query.append("it.name as institution_type_name, it.acronym as institution_type_acronym, "); query.append("ip.id as program_id, ip.name as program_name, ip.acronym as program_acronym "); query.append("FROM institutions i "); query.append("INNER JOIN institution_types it ON it.id=i.institution_type_id "); query.append("LEFT JOIN loc_elements lc ON lc.id=i.country_id "); query.append("LEFT JOIN ip_programs ip ON ip.id=i.program_id "); query.append("WHERE i.is_ppa = 1 "); query.append("ORDER BY i.acronym, i.name, loc_elements_name ASC "); LOG.debug("-- getAllPPAInstitutions() > Calling method executeQuery to get the results"); return this.getData(query.toString()); } private List<Map<String, String>> getData(String query) { LOG.debug(">> executeQuery(query='{}')", query); List<Map<String, String>> institutionsList = new ArrayList<>(); try (Connection con = databaseManager.getConnection()) { ResultSet rs = databaseManager.makeQuery(query, con); while (rs.next()) { Map<String, String> institutionData = new HashMap<String, String>(); institutionData.put("id", rs.getString("id")); institutionData.put("name", rs.getString("name")); institutionData.put("acronym", rs.getString("acronym")); institutionData.put("is_ppa", Boolean.toString(rs.getBoolean("is_ppa"))); institutionData.put("website_link", rs.getString("website_link")); institutionData.put("loc_elements_id", rs.getString("loc_elements_id")); institutionData.put("loc_elements_name", rs.getString("loc_elements_name")); institutionData.put("loc_elements_code", rs.getString("loc_elements_code")); institutionData.put("institution_type_id", rs.getString("institution_type_id")); institutionData.put("institution_type_name", rs.getString("institution_type_name")); institutionData.put("institution_type_acronym", rs.getString("institution_type_acronym")); institutionData.put("program_id", rs.getString("program_id")); institutionData.put("program_name", rs.getString("program_name")); institutionData.put("program_acronym", rs.getString("program_acronym")); institutionsList.add(institutionData); } rs.close(); } catch (SQLException e) { String exceptionMessage = "-- executeQuery() > Exception raised trying "; exceptionMessage += "to execute the following query " + query; LOG.error(exceptionMessage, e); } LOG.debug("<< executeQuery():getAllInstitutions.size={}", institutionsList.size()); return institutionsList; } @Override public Map<String, String> getInstitution(int institutionID) { Map<String, String> institutionData = new HashMap<String, String>(); LOG.debug(">> getInstitution( institutionID = {} )", institutionID); StringBuilder query = new StringBuilder(); query.append("SELECT i.id, i.name, i.acronym, i.is_ppa, i.website_link, i.institution_type_id,i.program_id, "); query.append("lc.id as loc_elements_id, lc.name as loc_elements_name,lc.code as loc_elements_code, "); query.append("it.name as institution_type_name, it.acronym as institution_type_acronym, "); query.append("ip.id as program_id, ip.name as program_name, ip.acronym as program_acronym "); query.append("FROM institutions i "); query.append("INNER JOIN institution_types it ON it.id=i.institution_type_id "); query.append("LEFT JOIN loc_elements lc ON lc.id=i.country_id "); query.append("LEFT JOIN ip_programs ip ON ip.id=i.program_id "); query.append("WHERE i.id = "); query.append(institutionID); try (Connection con = databaseManager.getConnection()) { ResultSet rs = databaseManager.makeQuery(query.toString(), con); if (rs.next()) { institutionData.put("id", rs.getString("id")); institutionData.put("name", rs.getString("name")); institutionData.put("acronym", rs.getString("acronym")); institutionData.put("is_ppa", Boolean.toString(rs.getBoolean("is_ppa"))); institutionData.put("website_link", rs.getString("website_link")); institutionData.put("loc_elements_id", rs.getString("loc_elements_id")); institutionData.put("loc_elements_name", rs.getString("loc_elements_name")); institutionData.put("loc_elements_code", rs.getString("loc_elements_code")); institutionData.put("institution_type_id", rs.getString("institution_type_id")); institutionData.put("institution_type_name", rs.getString("institution_type_name")); institutionData.put("institution_type_acronym", rs.getString("institution_type_acronym")); institutionData.put("program_id", rs.getString("program_id")); institutionData.put("program_name", rs.getString("program_name")); institutionData.put("program_acronym", rs.getString("program_acronym")); } con.close(); } catch (SQLException e) { LOG.error("Exception arised getting the institutions for the user {}.", institutionID, e); } LOG.debug("-- getInstitution() > Calling method executeQuery to get the results"); return institutionData; } @Override public List<Map<String, String>> getInstitutionsByTypeAndCountry(int typeID, int countryID) { StringBuilder query = new StringBuilder(); query.append("SELECT i.id, i.name, i.acronym, i.is_ppa, i.website_link, i.institution_type_id,i.program_id, "); query.append("lc.id as loc_elements_id, lc.name as loc_elements_name,lc.code as loc_elements_code, "); query.append("it.name as institution_type_name, it.acronym as institution_type_acronym, "); query.append("ip.id as program_id, ip.name as program_name, ip.acronym as program_acronym "); query.append("FROM institutions i "); query.append("INNER JOIN institution_types it ON it.id=i.institution_type_id "); query.append("LEFT JOIN loc_elements lc ON lc.id=i.country_id "); query.append("LEFT JOIN ip_programs ip ON ip.id=i.program_id "); if (countryID != -1 || typeID != -1) { query.append("WHERE "); // Add the conditions if exists if (countryID != -1) { query.append("lc.id = '" + countryID + "' "); } else { query.append(" 1 "); } if (typeID != -1) { query.append(" AND it.id = '" + typeID + "' "); } } query.append(" ORDER BY i.acronym, i.name, loc_elements_name ASC "); LOG.debug("-- getAllInstitutions() > Calling method executeQuery to get the results"); return this.getData(query.toString()); } @Override public List<Map<String, String>> getInstitutionsByUser(int userID) { List<Map<String, String>> institutionsDataList = new ArrayList<>(); StringBuilder query = new StringBuilder(); query.append("SELECT e.id as 'employee_id', "); query.append("i.id as 'institution_id', "); query.append("i.name as 'institution_name', "); query.append("i.acronym as 'institution_acronym', "); query.append("i.is_ppa as 'institution_is_ppa', "); query.append("i.website_link as 'institution_website_link', "); query.append("p.id as 'program_id', "); query.append("p.name as 'program_name', "); query.append("p.acronym as 'program_acronym',"); query.append("it.id as 'institution_type_id', "); query.append("it.acronym as 'institution_type_acronym' "); query.append("FROM employees e "); query.append("INNER JOIN institutions i ON i.id = e.institution_id "); query.append("LEFT JOIN ip_programs p ON p.id = i.program_id "); query.append("LEFT JOIN institution_types it ON it.id = i.institution_type_id "); query.append("WHERE e.user_id = "); query.append(userID); try (Connection con = databaseManager.getConnection()) { ResultSet rs = databaseManager.makeQuery(query.toString(), con); while (rs.next()) { Map<String, String> institutionData = new HashMap<String, String>(); institutionData.put("id", rs.getString("institution_id")); institutionData.put("name", rs.getString("institution_name")); institutionData.put("acronym", rs.getString("institution_acronym")); institutionData.put("is_ppa", Boolean.toString(rs.getBoolean("institution_is_ppa"))); institutionData.put("website_link", rs.getString("institution_website_link")); institutionData.put("program_id", rs.getString("program_id")); institutionData.put("program_name", rs.getString("program_name")); institutionData.put("program_acronym", rs.getString("program_acronym")); institutionData.put("institution_type_id", rs.getString("institution_type_id")); institutionData.put("institution_type_acronym", rs.getString("institution_type_acronym")); institutionsDataList.add(institutionData); } con.close(); } catch (SQLException e) { LOG.error("Exception arised getting the institutions for the user {}.", userID, e); } return institutionsDataList; } @Override public Map<String, String> getInstitutionType(int institutionTypeID) { Map<String, String> institutionData = new HashMap<String, String>(); LOG.debug(">> getTypeInstitutionById( institutionID = {} )", institutionTypeID); StringBuilder query = new StringBuilder(); query.append("SELECT it.* "); query.append("FROM institution_types it "); query.append("WHERE it.id = "); query.append(institutionTypeID); try (Connection con = databaseManager.getConnection()) { ResultSet rs = databaseManager.makeQuery(query.toString(), con); if (rs.next()) { institutionData.put("id", rs.getString("id")); institutionData.put("name", rs.getString("name")); institutionData.put("acronym", rs.getString("acronym")); } con.close(); } catch (SQLException e) { LOG.error("Exception arised getting the institutions for the user {}.", institutionTypeID, e); } LOG.debug("-- getTypeInstitutionById() > Calling method executeQuery to get the results"); return institutionData; } @Override public List<Map<String, Object>> getProjectLeadingInstitutions() { List<Map<String, Object>> institutionsDataList = new ArrayList<>(); StringBuilder query = new StringBuilder(); query.append("SELECT i.id as 'institution_id', "); query.append("i.name as 'institution_name', "); query.append("i.acronym as 'institution_acronym', "); query.append("i.website_link as 'institution_website_link', "); query.append("pp.id as 'project_partner_id', "); query.append("ppp.contact_type as 'partner_person_type', "); query.append("pp.project_id as 'project_id', "); query.append("le.id as 'country_id', "); query.append("le.name as 'country_name', "); query.append("(SELECT "); query.append("(SELECT GROUP_CONCAT(DISTINCT 'P', p.id ORDER BY p.id asc SEPARATOR ', ') "); query.append("FROM projects p "); query.append("INNER JOIN project_partners pp ON p.id = pp.project_id "); query.append("INNER JOIN project_partner_persons ppp ON pp.id = ppp.project_partner_id "); query.append("WHERE pp.institution_id = ins.id AND ppp.contact_type = 'PL' AND p.is_active = 1 "); query.append(") FROM institutions ins WHERE ins.id = i.id "); query.append(") as 'projects' "); query.append("FROM institutions i "); query.append("INNER JOIN project_partners pp ON pp.institution_id = i.id "); query.append("INNER JOIN project_partner_persons ppp ON ppp.project_partner_id = pp.id "); query.append("INNER JOIN users u ON u.id = ppp.user_id "); query.append("LEFT JOIN loc_elements le ON le.id = i.country_id "); query.append("WHERE ppp.contact_type = 'PL' AND pp.is_active = 1 "); query.append("ORDER BY i.id"); try (Connection con = databaseManager.getConnection()) { ResultSet rs = databaseManager.makeQuery(query.toString(), con); while (rs.next()) { Map<String, Object> institutionData = new HashMap<String, Object>(); institutionData.put("id", rs.getString("institution_id")); institutionData.put("name", rs.getString("institution_name")); institutionData.put("acronym", rs.getString("institution_acronym")); institutionData.put("website_link", rs.getString("institution_website_link")); institutionData.put("project_partner_id", rs.getString("project_partner_id")); institutionData.put("partner_person_type", rs.getString("partner_person_type")); institutionData.put("project_id", rs.getString("project_id")); institutionData.put("country_id", rs.getString("country_id")); institutionData.put("country_name", rs.getString("country_name")); institutionData.put("projects", rs.getString("projects")); institutionsDataList.add(institutionData); } con.close(); } catch (SQLException e) { LOG.error("Exception arised getting the ProjectPartnersinstitutions.", e); } return institutionsDataList; } @Override public List<Map<String, Object>> getProjectPartnerInstitutions() { List<Map<String, Object>> institutionsDataList = new ArrayList<>(); StringBuilder query = new StringBuilder(); query.append("SELECT i.id as 'institution_id', "); query.append("i.name as 'institution_name', "); query.append("i.acronym as 'institution_acronym', "); query.append("i.website_link as 'institution_website_link', "); query.append("pp.id as 'project_partner_id', "); query.append("pp.project_id as 'project_id', "); query.append("le.id as 'country_id', "); query.append("le.name as 'country_name', "); query.append("it.id as institution_type_id, it.acronym as 'institution_type_acronym', "); query.append("it.name as 'institution_type_name', "); query.append("(SELECT "); query.append("(SELECT GROUP_CONCAT(DISTINCT 'P', p.id ORDER BY p.id asc SEPARATOR ', ') "); query.append("FROM projects p "); query.append("INNER JOIN project_partners pp ON p.id = pp.project_id "); query.append("INNER JOIN project_partner_persons ppp ON pp.id = ppp.project_partner_id "); query.append("WHERE pp.institution_id = ins.id AND p.is_active = 1 "); query.append(") FROM institutions ins WHERE ins.id = i.id "); query.append(") as 'projects' "); query.append("FROM institutions i "); query.append("INNER JOIN project_partners pp ON pp.institution_id = i.id "); query.append("LEFT JOIN loc_elements le ON le.id = i.country_id "); query.append("LEFT JOIN institution_types it ON i.institution_type_id = it.id "); query.append("ORDER BY i.id"); try (Connection con = databaseManager.getConnection()) { ResultSet rs = databaseManager.makeQuery(query.toString(), con); while (rs.next()) { Map<String, Object> institutionData = new HashMap<String, Object>(); institutionData.put("id", rs.getString("institution_id")); institutionData.put("name", rs.getString("institution_name")); institutionData.put("acronym", rs.getString("institution_acronym")); institutionData.put("website_link", rs.getString("institution_website_link")); institutionData.put("project_partner_id", rs.getString("project_partner_id")); institutionData.put("project_id", rs.getString("project_id")); institutionData.put("country_id", rs.getString("country_id")); institutionData.put("country_name", rs.getString("country_name")); institutionData.put("institution_type_id", rs.getString("institution_type_id")); institutionData.put("institution_type_acronym", rs.getString("institution_type_acronym")); institutionData.put("institution_type_name", rs.getString("institution_type_name")); institutionData.put("projects", rs.getString("projects")); institutionsDataList.add(institutionData); } con.close(); } catch (SQLException e) { LOG.error("Exception arised getting the ProjectPartnersinstitutions.", e); } return institutionsDataList; } @Override public Map<String, String> getUserMainInstitution(int userID) { Map<String, String> institutionData = new HashMap<>(); StringBuilder query = new StringBuilder(); query.append("SELECT i.id, i.name, i.acronym, i.is_ppa, i.website_link, "); query.append("p.id as program_id, p.name as program_name, p.acronym as 'program_acronym', "); query.append("it.id as institution_type_id, it.acronym as 'institution_type_acronym'"); query.append("FROM institutions i "); query.append("LEFT JOIN ip_programs p ON i.program_id = p.id "); query.append("LEFT JOIN institution_types it ON i.institution_type_id = it.id "); query.append("INNER JOIN employees e ON i.id = e.institution_id "); query.append("INNER JOIN users u ON e.user_id = u.id "); query.append("WHERE u.id = "); query.append(userID); query.append(" AND e.is_main = TRUE"); query.append(" GROUP BY i.id "); try (Connection con = databaseManager.getConnection()) { ResultSet rs = databaseManager.makeQuery(query.toString(), con); if (rs.next()) { institutionData.put("id", rs.getString("id")); institutionData.put("name", rs.getString("name")); institutionData.put("acronym", rs.getString("acronym")); institutionData.put("is_ppa", Boolean.toString(rs.getBoolean("is_ppa"))); institutionData.put("website_link", rs.getString("website_link")); institutionData.put("program_id", rs.getString("program_id")); institutionData.put("program_name", rs.getString("program_name")); institutionData.put("program_acronym", rs.getString("program_acronym")); institutionData.put("institution_type_id", rs.getString("institution_type_id")); institutionData.put("institution_type_acronym", rs.getString("institution_type_acronym")); } con.close(); } catch (SQLException e) { LOG.error("Exception arised getting the institutions for the user {}.", userID, e); } return institutionData; } @Override public int saveProjectPartnerContributeInstitution(Map<String, Object> contributionData) { LOG.debug(">> saveProjectPartnerContributeInstitution(contributionData)", contributionData); StringBuilder query = new StringBuilder(); Object[] values; // Inserting new record query.append("INSERT IGNORE INTO project_partner_contributions (project_partner_id, contribution_institution_id) "); query.append("VALUES (?, ?) "); values = new Object[2]; values[0] = contributionData.get("project_partner_id"); values[1] = contributionData.get("contribution_institution_id"); int result = databaseManager.saveData(query.toString(), values); LOG.debug("<< saveProjectPartnerContributeInstitution():{}", result); return result; } @Override public boolean validateLastOneInstitution(int projectPartnerID) { LOG.debug(">> validateLastOneInstitution( projectPartnerID = {} )", projectPartnerID); StringBuilder query = new StringBuilder(); query .append("SELECT COUNT(*) FROM project_partners pp WHERE pp.project_id = (SELECT pp2.project_id FROM project_partners pp2 WHERE pp2.id = "); query.append(projectPartnerID); query.append(") AND pp.partner_id = (SELECT pp3.partner_id FROM project_partners pp3 WHERE pp3.id = "); query.append(projectPartnerID); query.append(") AND pp.is_active = 1"); boolean isLastOne = false; try (Connection con = databaseManager.getConnection()) { ResultSet rs = databaseManager.makeQuery(query.toString(), con); if (rs.next()) { if (rs.getInt(1) <= 1) { isLastOne = true; } } con.close(); } catch (SQLException e) { LOG.error("Exception validating last one institution for project partner id = {}.", projectPartnerID, e); } LOG.debug("-- validateLastOneInstitution() > Calling method executeQuery to get the results"); return isLastOne; } }
gpl-3.0
idega/platform2
src/is/idega/idegaweb/campus/business/HabitantsComparator.java
3910
package is.idega.idegaweb.campus.business; import java.text.Collator; import java.util.Comparator; import java.util.Locale; /** * Title: * Description: * Copyright: Copyright (c) 2001 * Company: * @author * @version 1.0 */ public class HabitantsComparator implements Comparator { public static final int NAME = 1; public static final int APARTMENT = 2; public static final int FLOOR = 3; public static final int ADDRESS = 4; private Locale locale = Locale.ENGLISH; private Collator collator = null; private int sortBy; public HabitantsComparator(Locale locale) { sortBy = NAME; this.locale = locale; this.collator = Collator.getInstance(locale); } public HabitantsComparator(Locale locale,int toSortBy) { sortBy = toSortBy; this.locale = locale; this.collator = Collator.getInstance(locale); } public void sortBy(int toSortBy) { sortBy = toSortBy; } public int compare(Object o1, Object o2) { int result = 0; switch (sortBy) { case NAME : result = nameCompare(o1,o2); break; case APARTMENT : result = apartmentCompare(o1,o2); if (result == 0) result = nameCompare(o1,o2); break; case ADDRESS : result = addressCompare(o1,o2); if (result == 0) result = apartmentCompare(o1,o2); if (result == 0) result = nameCompare(o1,o2); break; case FLOOR : result = floorCompare(o1,o2); if (result == 0) result = addressCompare(o1,o2); if (result == 0) result = apartmentCompare(o1,o2); if (result == 0) result = nameCompare(o1,o2); break; } return(result); } public boolean equals(Object obj) { if (compare(this,obj) == 0) return(true); else return(false); } public int nameCompare(Object o1, Object o2) { HabitantsCollector r1 = (HabitantsCollector) o1; HabitantsCollector r2 = (HabitantsCollector) o2; int result = 0; String one = r1.getName()!=null?r1.getName():""; String two = r2.getName()!=null?r2.getName():""; result = collator.compare(one,two); /* String one = r1.getFirstName()!=null?r1.getFirstName():""; String two = r2.getFirstName()!=null?r2.getFirstName():""; result = IsCollator.getIsCollator().compare(one,two); if (result == 0){ one = r1.getLastName()!=null?r1.getLastName():""; two = r2.getLastName()!=null?r2.getLastName():""; result = IsCollator.getIsCollator().compare(one,two); } if (result == 0){ one = r1.getMiddleName()!=null?r1.getMiddleName():""; two = r2.getMiddleName()!=null?r2.getMiddleName():""; result = IsCollator.getIsCollator().compare(one,two); } */ return result; } public int apartmentCompare(Object o1, Object o2) { HabitantsCollector r1 = (HabitantsCollector) o1; HabitantsCollector r2 = (HabitantsCollector) o2; int result = 0; String one = r1.getApartment()!=null?r1.getApartment():""; String two = r2.getApartment()!=null?r2.getApartment():""; result = collator.compare(one,two); return result; } public int floorCompare(Object o1, Object o2) { HabitantsCollector r1 = (HabitantsCollector) o1; HabitantsCollector r2 = (HabitantsCollector) o2; int result = 0; String one = r1.getFloor()!=null?r1.getFloor():""; String two = r2.getFloor()!=null?r2.getFloor():""; result = collator.compare(one,two); return result; } public int addressCompare(Object o1, Object o2) { HabitantsCollector r1 = (HabitantsCollector) o1; HabitantsCollector r2 = (HabitantsCollector) o2; int result = 0; String one = r1.getAddress()!=null?r1.getAddress():""; String two = r2.getAddress()!=null?r2.getAddress():""; result = collator.compare(one,two); return result; } }
gpl-3.0
jkiddo/jolivia
jolivia.protocol/src/main/java/org/dyndns/jkiddo/dmp/chunks/ByteChunk.java
1328
/******************************************************************************* * Copyright (c) 2013 Jens Kristian Villadsen. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * * Contributors: * Jens Kristian Villadsen - Lead developer, owner and creator ******************************************************************************/ /* * Digital Audio Access Protocol (DAAP) Library * Copyright (C) 2004-2010 Roger Kapsi * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dyndns.jkiddo.dmp.chunks; public interface ByteChunk extends Chunk { public void setValue(int value); public int getValue(); }
gpl-3.0
abmindiarepomanager/ABMOpenMainet
Mainet1.0/MainetServiceParent/MainetServiceCommon/src/main/java/com/abm/mainet/common/ui/controller/AbstractController.java
25404
package com.abm.mainet.common.ui.controller; import java.io.UnsupportedEncodingException; import java.lang.reflect.ParameterizedType; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MaxUploadSizeExceededException; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.support.RequestContextUtils; import org.springframework.web.servlet.view.json.MappingJackson2JsonView; import com.abm.mainet.common.constant.ExceptionViewConstants; import com.abm.mainet.common.constant.MainetConstants; import com.abm.mainet.common.dto.JsonViewObject; import com.abm.mainet.common.integration.dms.fileUpload.FileUploadUtility; import com.abm.mainet.common.ui.model.AbstractModel; import com.abm.mainet.common.utility.ApplicationContextProvider; import com.abm.mainet.common.utility.ApplicationSession; import com.abm.mainet.common.utility.CommonMasterUtility; import com.abm.mainet.common.utility.HttpHelper; import com.abm.mainet.common.utility.LookUp; import com.abm.mainet.common.utility.UserSession; import com.abm.mainet.common.utility.Utility; @Component public abstract class AbstractController<TModel extends AbstractModel> implements HandlerExceptionResolver { private Class<TModel> modelClass; private String viewName; private final Logger logger = Logger.getLogger(this.getClass()); @InitBinder protected void initBinder(WebDataBinder binder) { AbstractModel.registerCustomEditors(binder); } @SuppressWarnings("unchecked") public AbstractController() { this.modelClass = (Class<TModel>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; String controllerType = this.getClass().getSimpleName(); this.viewName = controllerType.substring(0, controllerType.lastIndexOf("Controller")); } protected String getViewName() { return viewName; } protected ModelAndView getScrutinyView() { String sViewName = viewName+"View"; return new ModelAndView(sViewName,"command",this.getModel()); } /** * @return */ protected ApplicationSession getApplicationSession() { return (ApplicationSession) ApplicationContextProvider.getApplicationContext().getBean("applicationSession"); } /** * @return */ public TModel getModel() { return (TModel) ApplicationContextProvider.getApplicationContext().getBean(this.modelClass); } public BindingResult bindModel(HttpServletRequest request) { return getModel().bind(request); } /** * @return */ // @RequestMapping(method = RequestMethod.GET) public ModelAndView index() { return defaultResult(); } protected ModelAndView jsonResult(Object bean) { ModelAndView mv; if (bean == null) { mv = new ModelAndView(new MappingJackson2JsonView()); } else { mv = new ModelAndView(new MappingJackson2JsonView(), MainetConstants.FORM_NAME, bean); } return mv; } protected ModelAndView getResubmissionView() { String resubmissionName = viewName+"Resubmission"; return new ModelAndView(resubmissionName,"command",this.getModel()); } /** * @return */ protected ModelAndView defaultResult() { TModel model = getModel(); model.getAppSession().setLangId(UserSession.getCurrent().getLanguageId()); ModelAndView mv = new ModelAndView(viewName, MainetConstants.FORM_NAME, model); BindingResult bindingResult = model.getBindingResult(); if (bindingResult != null) { mv.addObject(BindingResult.MODEL_KEY_PREFIX + MainetConstants.FORM_NAME, model.getBindingResult()); } return mv; } protected ModelAndView customResult(String viewName) { TModel model = getModel(); model.getAppSession().setLangId(UserSession.getCurrent().getLanguageId()); ModelAndView mv = new ModelAndView(viewName, MainetConstants.FORM_NAME, model); BindingResult bindingResult = model.getBindingResult(); if (bindingResult != null) { mv.addObject(BindingResult.MODEL_KEY_PREFIX + MainetConstants.FORM_NAME, model.getBindingResult()); } return mv; } protected ModelAndView defaultMyResult() { TModel model = getModel(); model.getAppSession().setLangId(UserSession.getCurrent().getLanguageId()); ModelAndView mv = new ModelAndView(viewName + MainetConstants.VALIDN_SUFFIX , MainetConstants.FORM_NAME, model); BindingResult bindingResult = model.getBindingResult(); if (bindingResult != null) { mv.addObject(BindingResult.MODEL_KEY_PREFIX + MainetConstants.FORM_NAME, model.getBindingResult()); } return mv; } protected ModelAndView customDefaultMyResult(String viewName) { TModel model = getModel(); model.getAppSession().setLangId(UserSession.getCurrent().getLanguageId()); ModelAndView mv = new ModelAndView(viewName + MainetConstants.VALIDN_SUFFIX , MainetConstants.FORM_NAME, model); BindingResult bindingResult = model.getBindingResult(); if (bindingResult != null) { mv.addObject(BindingResult.MODEL_KEY_PREFIX + MainetConstants.FORM_NAME, model.getBindingResult()); } return mv; } protected ModelAndView defaultServerResult() { TModel model = getModel(); model.getAppSession().setLangId(UserSession.getCurrent().getLanguageId()); ModelAndView mv = new ModelAndView(MainetConstants.SERVER_ERROR_URL, MainetConstants.FORM_NAME, model); BindingResult bindingResult = model.getBindingResult(); if (bindingResult != null) { mv.addObject(BindingResult.MODEL_KEY_PREFIX + MainetConstants.FORM_NAME, model.getBindingResult()); } return mv; } protected final void sessionCleanup(HttpServletRequest request) { //HttpSession session = request.getSession(false); if(request.getSession(false) != null){ request.getSession().removeAttribute(getModel().getBeanName()); } /*HttpSession session = request.getSession(); session.removeAttribute(getModel().getBeanName());*/ } /** * This method get all the look up&acute;s sub information object&acute;s for * the given parent code and id. * @param typeCode {@link String} literal containing parent code. * @param typeId {@link String} literal containing parent id. * @return {@link List} of {@link LookUp} objects. */ @RequestMapping(params = "getSubInfo", produces = "application/json", method = RequestMethod.POST) public @ResponseBody final List<LookUp> getSubLookUpList(@RequestParam String typeCode, @RequestParam long typeId) { List<LookUp> lookup= getApplicationSession().getChildLookUpsFromParentId(typeId); if(lookup!=null && lookup.size()>0) { Collections.sort(lookup); } return lookup; } @RequestMapping(params = "getSubInfoByLevel", produces = "application/json", method = RequestMethod.POST) public @ResponseBody final List<LookUp> getSubLookUpListByLevel(@RequestParam String typeCode, @RequestParam long typeId,@RequestParam long level) { return getApplicationSession().getChildLookUpsFromParentIdForLevel(typeId,level); } @RequestMapping(params = "FileUpload", method = RequestMethod.POST) public @ResponseBody String uploadDocument(@RequestParam("files") List<MultipartFile> multipartFiles) { for (MultipartFile file : multipartFiles) { getModel().getMultipartFiles().add(file); } return getModel().getUploadedFiles(); } @RequestMapping(params = "Download", method = RequestMethod.POST) public ModelAndView download(@RequestParam("downloadLink") String downloadLink, HttpServletResponse httpServletResponse) { String outputPath = MainetConstants.DirectoryTree.DEFAULT_CACHE_FOLDER + MainetConstants.FILE_PATH_SEPARATOR + "SHOW_DOCS"; try { this.getModel().setFilePath(Utility.downloadedFileUrl(downloadLink, outputPath, this.getModel().getFileNetClient())); } catch (Exception ex) { return new ModelAndView("redirect:/404error.jsp.html"); } return new ModelAndView("viewHelp","command",this.getModel()); } /** * To get message text for given message template code. * @param msgTemplate the {@link String} literal containing message template * code. * @return {@link String} object which containing actual text message. */ public final String getMessageText(String msgTemplate) { TModel model = this.getModel(); return model.getAppSession().getMessage(msgTemplate); } //Madhura /* public boolean generateReportFromCollection(HttpServletRequest request, HttpServletResponse response, String jrxmlFileLocation, Map<String, Object> map, List<?> dataCollection) { String fileName = ReportUtility.generateReportFromCollectionUtility(request, response,jrxmlFileLocation,map,dataCollection); if(fileName.equals(MainetConstants.SERVER_ERROR)) return false; else { this.getModel().setFilePath(fileName); return true; } } public boolean generateReportUsingOracleFormsAndReport(String codeValue, String parameters, Object[] values, boolean isDevelopment, String formName) { String reportUrl = viewName + ReportConstant.CONTROLLER_EXT; return generateReportUsingOracleFormsAndReport(codeValue, parameters, values, isDevelopment, formName, reportUrl); } public boolean generateReportUsingOracleFormsAndReport(String codeValue, String parameters, Object[] values, boolean isDevelopment, String formName, String URL) { String fileName = ReportUtility.getCurrent().generateReportUsingOracleFormsAndReportService(parameters, codeValue, values, isDevelopment, getModel().getBindingResult(), URL, formName); if (fileName.equals(MainetConstants.SERVER_ERROR)) return false; else { this.getModel().setFilePath(fileName); return true; } } */ @RequestMapping(params = "locale", method = RequestMethod.GET) public String welcome(@RequestParam("lang") String requestLang,@RequestParam("url") String url, HttpServletRequest request, HttpServletResponse response) { LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request); localeResolver.setLocale(request, response, StringUtils.parseLocaleString(requestLang)); UserSession.getCurrent().setLanguageId(getLanguage(requestLang)); return "redirect:"+url; } private int getLanguage(String language) { if ("reg".equals(language)) { return 2; } else if ("en".equals(language)) { return 1; } else { return 1; } } @RequestMapping(params = "reset", method = RequestMethod.POST) protected @ResponseBody JsonViewObject resetForm(HttpServletRequest httpServletRequest) { try { this.sessionCleanup(httpServletRequest); FileUploadUtility.getCurrent().getFileMap().clear(); FileUploadUtility.getCurrent().getFileUploadSet().clear(); FileUploadUtility.getCurrent().setFolderCreated(false); return JsonViewObject.successResult(); } catch (Throwable ex) { return JsonViewObject.failureResult(ex); } } @RequestMapping(params = "ResubmissionApplication", method = RequestMethod.POST) public ModelAndView ResubmissionApplication(@RequestParam("menuparams") List<String> menuparams,@RequestParam("applId") long applId, @RequestParam("filterType") String filterType,HttpServletRequest httpServletRequest) { bindModel(httpServletRequest); getModel().setApmApplicationId(applId); getModel().setFilterType(filterType); getModel().viewResubmissionApplication(applId,menuparams); getModel().getDataForResubmission(applId,menuparams.get(0)); return this.getResubmissionView(); } /* * (non-Javadoc) * @see * org.springframework.web.servlet.HandlerExceptionResolver#resolveException * (javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse, java.lang.Object, * java.lang.Exception)*/ @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { // TODO replace with logger if (ex instanceof MaxUploadSizeExceededException) { return jsonResult(JsonViewObject.failureResult(getApplicationSession().getMessage("FileSizeExceed"))); } else { if (HttpHelper.isAjaxRequest(request)) { return jsonResult(JsonViewObject.failureResult("Unexpected error occurred ," + ex.getMessage())); } return new ModelAndView("redirect:/Home.html"); } } @RequestMapping(params = "getMessage", method = RequestMethod.POST) public @ResponseBody String getMessage(@RequestParam("key") String key,HttpServletRequest request, HttpServletResponse response) { return getApplicationSession().getMessage(key); } /*@RequestMapping(method = RequestMethod.GET, params = "ShowHelpDoc") public ModelAndView GlobalHelpDocs(HttpServletRequest httpServletRequest){ String outputPath = MainetConstants.DirectoryTree.DEFAULT_CACHE_FOLDER + MainetConstants.FILE_PATH_SEPARATOR + "HELP_DOCS"; CommonHelpDocs docs=this.getModel().getCommonHelpDoc(); if(docs!=null && docs.getModuleName()!=null && !docs.getModuleName().equalsIgnoreCase("")) { try { if(UserSession.getCurrent().getLanguageId()==1) { this.getModel().setFilePath(Utility.downloadedFileUrl(docs.getFilePath()+MainetConstants.FILE_PATH_SEPARATOR+docs.getFileNameEng(), outputPath, this.getModel().getFileNetClient())); } else if(UserSession.getCurrent().getLanguageId()==2 && docs.getFileNameReg()!=null && !docs.getFileNameReg().equalsIgnoreCase("")) { this.getModel().setFilePath(Utility.downloadedFileUrl(docs.getFilePathReg()+MainetConstants.FILE_PATH_SEPARATOR+docs.getFileNameReg(), outputPath, this.getModel().getFileNetClient())); } else{ this.getModel().setFilePath(Utility.downloadedFileUrl(docs.getFilePath()+MainetConstants.FILE_PATH_SEPARATOR+docs.getFileNameEng(), outputPath, this.getModel().getFileNetClient())); } } catch(Exception f) { return new ModelAndView("redirect:/404error.jsp.html"); } return new ModelAndView("viewHelp","command",this.getModel()); } else { if(this.getModel().getBeanName().equals(FileUploadConstant.ValidationMessageCode.FOR_CITI_REGISTRATION)){ return new ModelAndView("redirect:/notFoundFile.html"); }else{ return new ModelAndView("viewHelpNotFound","command",this.getModel()); } } } */ @RequestMapping(method = RequestMethod.GET, params = "ShowPolicy") public ModelAndView GlobalPolicy(HttpServletRequest httpServletRequest){ String outputPath = MainetConstants.DirectoryTree.DEFAULT_CACHE_FOLDER + MainetConstants.FILE_PATH_SEPARATOR + "POLICY"; this.getModel().setFilePath(Utility.downloadedFileUrl(UserSession.getCurrent().getOrganisation().getOrgid()+"\\POLICY"+MainetConstants.FILE_PATH_SEPARATOR+"Policy.pdf", outputPath, this.getModel().getFileNetClient())); return new ModelAndView("viewHelp","command",this.getModel()); } /** * Common handler method for Scrutiny Process * @param httpServletRequest * @return */ @RequestMapping(params = "viewApplicationAndDoScrutiny", method = RequestMethod.GET) public ModelAndView viewApplicationAndDoScrutiny(final HttpServletRequest request) { try { bindModel(request); final String applicationId = UserSession.getCurrent().getScrutinyCommonParamMap().get(MainetConstants.SCRUTINY_COMMON_PARAM.APM_APPLICATION_ID); getModel().populateApplicationData(Long.parseLong(applicationId)); } catch(Exception e) { logger.error("Problem occurred during fetching application related info from respective service:", e); return defaultExceptionFormView(); } return this.getScrutinyView(); } /* * Old scrutiny process which are No longer in use * * @RequestMapping(params = "viewApplication", method = RequestMethod.POST) public ModelAndView viewApplication(@RequestParam("menuparams") List<String> menuparams,@RequestParam("applId") long applId, HttpServletRequest httpServletRequest) { try { bindModel(httpServletRequest); UserSession.getCurrent().getScrutinyCommonParamMap().put(MainetConstants.SCRUTINY_COMMON_PARAM.SCRUTINY_APPL_ID, applId+""); getModel().viewScrutinyApplication(applId,menuparams); } catch(Exception e) { return defaultExceptionView(); } return this.getScrutinyView(); } */ @RequestMapping(params = "getFilePath", method = RequestMethod.POST) public @ResponseBody String getFilePath(HttpServletRequest httpServletRequest) { return this.getModel().getFilePath(); } protected ModelAndView defaultExceptionView() { return new ModelAndView("defaultExceptionView","command",this.getModel()); } protected ModelAndView defaultExceptionFormView() { return new ModelAndView("defaultExceptionFormView","command",this.getModel()); } @RequestMapping(params = "getToplevelTryList",method = RequestMethod.POST,produces = "application/json") @ResponseBody public LookUp getFirstAndSecondLevelList(@RequestParam(value="level") int level){ List<LookUp> list=new ArrayList<LookUp>(); List<LookUp> lookUpList=CommonMasterUtility.getSecondLevelData("TRY", level); for (LookUp lookUp : lookUpList) { if(lookUp.getDefaultVal().equalsIgnoreCase("Y")){ list.add(lookUp); } } if(list.size() > 0) return list.get(0); else return null; } @RequestMapping(params = "getTryList",method = RequestMethod.POST,produces = "application/json") public @ResponseBody List<LookUp> getDistrictList(@RequestParam(value = "term") String term,@RequestParam(value="parentId") String parentId) { List<LookUp> list=new ArrayList<LookUp>(); try { List<LookUp> lookupList =CommonMasterUtility.getChildLookUpsFromParentId(Long.parseLong(parentId)); for (LookUp lookUp : lookupList) { if(lookUp.getDescLangFirst().matches("(?i)^"+term+".*$")){ list.add(lookUp); } } } catch (NumberFormatException e) { return null; } return list; } @RequestMapping(method = RequestMethod.POST, params = "encrypted") public @ResponseBody String getEncrypted(@RequestParam("plainText") String plainText) throws IllegalBlockSizeException, InvalidKeyException, UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalStateException, BadPaddingException { String encryptedData=this.getModel().encryptData(plainText); return encryptedData; } @RequestMapping(method = RequestMethod.POST, params = "decrypted") public @ResponseBody Double getDecrypted(@RequestParam("plainText") String plainText) throws IllegalBlockSizeException, InvalidKeyException, UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalStateException, BadPaddingException { String decryptedData=this.getModel().decryptData(plainText); return Double.parseDouble(decryptedData); } @RequestMapping(method = RequestMethod.POST, params = "doFileUpload") public @ResponseBody JsonViewObject uploadDocument(HttpServletRequest httpServletRequest,HttpServletResponse response,String fileCode,@RequestParam String browserType) { UserSession.getCurrent().setBrowserType(browserType); MultipartHttpServletRequest request = (MultipartHttpServletRequest) httpServletRequest; JsonViewObject jsonViewObject = FileUploadUtility.getCurrent().doFileUpload(request,fileCode,browserType); return jsonViewObject; } @RequestMapping(method = RequestMethod.POST, params = "doFileUploadValidatn") public @ResponseBody List<JsonViewObject> doFileUploadValidatn(HttpServletRequest httpServletRequest,@RequestParam String browserType) { UserSession.getCurrent().setBrowserType(browserType); List<JsonViewObject> result = FileUploadUtility.getCurrent().getFileUploadList(); return result; } @RequestMapping(method = RequestMethod.POST, params = "doFileDeletion") public @ResponseBody JsonViewObject doFileDeletion(@RequestParam String fileId,HttpServletRequest httpServletRequest,@RequestParam String browserType,@RequestParam(name="uniqueId",required=false) Long uniqueId) { UserSession.getCurrent().setBrowserType(browserType); JsonViewObject jsonViewObject = JsonViewObject.successResult(); jsonViewObject = FileUploadUtility.getCurrent().deleteFile(fileId); return jsonViewObject; } /** * This method get all the look up&acute;s sub information object&acute;s for * the given parent code,id and isAlphaNumeric. * @param typeCode {@link String} literal containing parent code. * @param typeId {@link String} literal containing parent id. * @param isAlphaNumeric {@link String} literal containing alphanumericFlag. * @return {@link List} of {@link LookUp} objects. */ @RequestMapping(params = "getSubAlphanumericSortInfo", produces = "application/json", method = RequestMethod.POST) public @ResponseBody final List<LookUp> getSubAlphanumericSortInfo(@RequestParam String typeCode, @RequestParam long typeId , @RequestParam String isAlphaNumeric) { List<LookUp> lookup= getApplicationSession().getChildLookUpsFromParentId(typeId); if(lookup!=null && !lookup.isEmpty()) { if(isAlphaNumeric != null && isAlphaNumeric.equals("Y")){ Collections.sort(lookup,LookUp.alphanumericComparator); }else{ Collections.sort(lookup); } } return lookup; } @ExceptionHandler(Exception.class) public ModelAndView handleError(HttpServletRequest request, Exception exception) { logger.error("Exception found : ", exception); ModelAndView mav = new ModelAndView(); if (request.getMethod().equalsIgnoreCase(RequestMethod.GET.name())) { mav.setViewName(ExceptionViewConstants.DEFAULT_EXCEPTION_VIEW); } if (request.getMethod().equalsIgnoreCase(RequestMethod.POST.name())) { mav.setViewName(ExceptionViewConstants.DEFAULT_EXCEPTION_FORM_VIEW); } return mav; } @RequestMapping(params = "showErrorPage", method = RequestMethod.POST) public ModelAndView showErrorPage(HttpServletRequest httpServletRequest,Exception exception) { logger.error("Exception found : ", exception); ModelAndView modelAndView; modelAndView = new ModelAndView( ExceptionViewConstants.DEFAULT_EXCEPTION_FORM_VIEW, MainetConstants.FORM_NAME, getModel()); return modelAndView; } @RequestMapping(params = "generatWorkOrderAbstract", method = RequestMethod.GET) public String generatWorkOrder(final HttpServletRequest request) { try { bindModel(request); final String applicationId = UserSession.getCurrent().getScrutinyCommonParamMap().get(MainetConstants.SCRUTINY_COMMON_PARAM.APM_APPLICATION_ID); final String serviceId = UserSession.getCurrent().getScrutinyCommonParamMap().get(MainetConstants.SCRUTINY_COMMON_PARAM.SM_SERVICE_ID); String conncetionNo =getModel().getConnectioNo(Long.parseLong(applicationId),Long.parseLong(serviceId)) ; String[] temp; String delimiter = ","; temp = conncetionNo.split(delimiter); String conncetionNo1 = temp[0]; String PlumberID = temp[1]; request.getSession().setAttribute("conncetionNo", conncetionNo1); request.getSession().setAttribute("applicationId", applicationId); request.getSession().setAttribute("serviceId", serviceId); request.getSession().setAttribute("PlumberID", PlumberID); } catch(Exception e) { logger.error("Problem occurred generatWorkOrder service:", e); e.printStackTrace(); } return new String("redirect:/WorkOrder.html?generatWorkOrder"); } }
gpl-3.0
timcampbell/LetsModReboot
src/main/java/com/sopa89/letsmodreboot/client/handler/KeyEventHandler.java
715
package com.sopa89.letsmodreboot.client.handler; import com.sopa89.letsmodreboot.client.settings.KeyBindings; import com.sopa89.letsmodreboot.reference.Key; import com.sopa89.letsmodreboot.utility.LogHelper; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.InputEvent; public class KeyEventHandler { private static Key getPressedKeyBinding() { if(KeyBindings.charge.isPressed()) { return Key.CHARGE; } else if(KeyBindings.release.isPressed()) { return Key.RELEASE; } else { return Key.UNKNOWN; } } @SubscribeEvent public void handleKeyInputEvent(InputEvent.KeyInputEvent event) { LogHelper.info(getPressedKeyBinding()); } }
gpl-3.0
scrmtrey91/EARS
src/org/um/feri/ears/problems/unconstrained/Michalewicz2.java
950
package org.um.feri.ears.problems.unconstrained; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import org.apache.commons.lang3.ArrayUtils; import org.um.feri.ears.problems.Problem; public class Michalewicz2 extends Problem { public Michalewicz2() { super(2,0); lowerLimit = new ArrayList<Double>(Collections.nCopies(numberOfDimensions, 0.0)); upperLimit = new ArrayList<Double>(Collections.nCopies(numberOfDimensions, Math.PI)); name = "Michalewicz2"; optimum[0][0] = 2.20290552; optimum[0][1] = 1.57079633; } public double eval(double x[]) { double v = 0; int m = 10; for (int i = 0; i < numberOfDimensions; i++){ v = v + Math.sin(x[i])*Math.pow(Math.sin((i+1)*x[i]*x[i]/Math.PI), 2*m); } v = v * (-1); return v; } public double getOptimumEval() { return -1.80130341; } @Override public double eval(Double[] ds) { return eval(ArrayUtils.toPrimitive(ds)); } }
gpl-3.0
NICTA/SPINdle
src/spindle/engine/ReasoningEngineFactory.java
12335
/** * SPINdle (version 2.2.2) * Copyright (C) 2009-2012 NICTA Ltd. * * This file is part of SPINdle project. * * SPINdle is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SPINdle is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with SPINdle. If not, see <http://www.gnu.org/licenses/>. * * @author H.-P. Lam (oleklam@gmail.com), National ICT Australia - Queensland Research Laboratory */ package spindle.engine; import java.util.Map; import java.util.TreeMap; import com.app.utils.TextUtilities; import com.app.utils.Utilities; import spindle.core.dom.Theory; import spindle.core.dom.TheoryType; import spindle.engine.tdl.TdlConclusionUpdater; import spindle.sys.AppConst; import spindle.sys.Conf; import spindle.sys.message.ErrorMessage; import spindle.tools.evaluator.LiteralVariablesEvaluator; /** * Factory class for theory normalizer and reasoning engine * * @author H.-P. Lam (oleklam@gmail.com), National ICT Australia - Queensland Research Laboratory * @since version 1.0.0 * @version Last modified 2012.09.18 * @version 2012.07.21 */ public final class ReasoningEngineFactory { private static enum ENGINE_TYPE { AB, AP, AB_WF, AP_WF }; private static LiteralVariablesEvaluator literalVariableEvaluator = null; private static TdlConclusionUpdater conclusionUpdater = null; private static Map<TheoryType, Map<Integer, TheoryNormalizer>> theoryNormalizersStore = new TreeMap<TheoryType, Map<Integer, TheoryNormalizer>>(); private static Map<TheoryType, Map<ENGINE_TYPE, Map<Integer, ReasoningEngine>>> reasoningEnginesStore = new TreeMap<TheoryType, Map<ENGINE_TYPE, Map<Integer, ReasoningEngine>>>(); /** * Return a copy of literal variables evaluator. * * @return Literal variable evaluator. */ public static final LiteralVariablesEvaluator getLiteralVariablesEvaluator() { if (Conf.isMultiThreadMode()) return new LiteralVariablesEvaluator(); if (null == literalVariableEvaluator) literalVariableEvaluator = new LiteralVariablesEvaluator(); return literalVariableEvaluator; } /** * Return a copy of conclusion updater for TDL literals data store according to the configuration information. * * @return Conclusion updater. * @throws ReasoningEngineFactoryException */ public static final TdlConclusionUpdater getTdlConclusionUpdater() throws ReasoningEngineFactoryException { if (null == conclusionUpdater) { String clazzName = Conf.getTdlConclusionUpdaterClassName(); try { if (!AppConst.isDeploy) System.out.print("generating TDL conclusion updater class [" + clazzName + "]"); conclusionUpdater = Utilities.getInstance(clazzName, TdlConclusionUpdater.class); if (!AppConst.isDeploy) System.out.println("..success"); } catch (Exception e) { if (!AppConst.isDeploy) System.out.println("..failed"); throw new ReasoningEngineFactoryException("exception throw while generating TDL conclusion updater class [" + clazzName + "]", e); } } return conclusionUpdater; } /** * Create a new theory normalizer according to the theory type and reasoner version. * * @param theoryType theory type. * @param reasonerVersion reasoner version. * @return theory normalizer associated with the theory type * @throws ReasoningEngineFactoryException Indicates when there is no theory normalizer associated with the theory * type specified or the theory type does not exist. */ private static final TheoryNormalizer createTheoryNormalizer(TheoryType theoryType, int reasonerVersion) throws ReasoningEngineFactoryException { TheoryNormalizer theoryNormalizer = null; switch (theoryType) { case SDL: switch (reasonerVersion) { case 1: theoryNormalizer = new spindle.engine.sdl.SdlTheoryNormalizer(); break; default: theoryNormalizer = new spindle.engine.sdl.SdlTheoryNormalizer2(); } break; case MDL: switch (reasonerVersion) { case 1: theoryNormalizer = new spindle.engine.mdl.MdlTheoryNormalizer(); break; default: theoryNormalizer = new spindle.engine.mdl.MdlTheoryNormalizer2(); } break; case TDL: // only available when the package is not in deploy mode // - used for testing purpose if (AppConst.isDeploy) throw new ReasoningEngineFactoryException(ErrorMessage.THEORY_NORMALIZER_NOT_SUPPORTED, new Object[] { TheoryType.TDL }); try { theoryNormalizer = new spindle.engine.tdl.TdlTheoryNormalizer2(); } catch (TheoryNormalizerException e) { throw new ReasoningEngineFactoryException(e); } break; default: throw new ReasoningEngineFactoryException(ErrorMessage.THEORY_UNRECOGNIZED_THEORY_TYPE, new Object[] { theoryType }); } return theoryNormalizer; } /** * Return a theory normalizer as specified if the type of theory normalizer is in the theory normalizers store. * or create a new one otherwise. * * @param theoryType theory type. * @param reasonerVersion reasoner version. * @return theory normalizer associated with the theory type * @throws ReasoningEngineFactoryException Indicates when there is no theory normalizer associated with the theory * type specified or the theory type does not exist. */ private static final TheoryNormalizer getTheoryNormalizerFromStore(TheoryType theoryType, int reasonerVersion) throws ReasoningEngineFactoryException { Map<Integer, TheoryNormalizer> theoryNormalizers = theoryNormalizersStore.get(theoryType); if (null == theoryNormalizers) { theoryNormalizers = new TreeMap<Integer, TheoryNormalizer>(); theoryNormalizersStore.put(theoryType, theoryNormalizers); } TheoryNormalizer theoryNormalizer = theoryNormalizers.get(reasonerVersion); if (null == theoryNormalizer) { theoryNormalizer = createTheoryNormalizer(theoryType, reasonerVersion); theoryNormalizers.put(reasonerVersion, theoryNormalizer); } return theoryNormalizer; } /** * Return a theory normalizer according to the theory type. * * @param theoryType theory type * @return theory normalizer associated with the theory type * @throws ReasoningEngineFactoryException Indicates when there is no theory normalizer associated with the theory * type specified or the theory type does not exist. */ public static final TheoryNormalizer getTheoryNormalizer(TheoryType theoryType) throws ReasoningEngineFactoryException { if (theoryType == null) return null; if (Conf.isMultiThreadMode()) { return createTheoryNormalizer(theoryType, Conf.getReasonerVersion()); } else { return getTheoryNormalizerFromStore(theoryType, Conf.getReasonerVersion()); } } /** * Create a reasoning engine according to the theory type, engine type and reasoner version. * * @param theoryType theory type. * @param engineType engine type (ambiguity blocking, ambiguity propagation, well-founded semantics, or their * combination). * @param reasonerVersion reasoner version. * @return Reasoning engine with appropriate type as specified. * @throws ReasoningEngineFactoryException */ private static final ReasoningEngine createReasoningEngine(TheoryType theoryType, ENGINE_TYPE engineType, int reasonerVersion) throws ReasoningEngineFactoryException { ReasoningEngine engine = null; switch (theoryType) { case SDL: switch (reasonerVersion) { case 1: switch (engineType) { case AB: case AB_WF: engine = new spindle.engine.sdl.SdlReasoningEngine(); break; case AP: case AP_WF: engine = new spindle.engine.sdl.SdlReasoningEngineAP(); break; } break; default: switch (engineType) { case AB: case AB_WF: engine = new spindle.engine.sdl.SdlReasoningEngine2(); break; case AP: case AP_WF: engine = new spindle.engine.sdl.SdlReasoningEngineAP2(); break; } } break; case MDL: switch (reasonerVersion) { case 1: switch (engineType) { case AB: case AB_WF: engine = new spindle.engine.mdl.MdlReasoningEngine(); break; case AP: case AP_WF: engine = new spindle.engine.mdl.MdlReasoningEngineAP(); break; } break; default: switch (engineType) { case AB: case AB_WF: engine = new spindle.engine.mdl.MdlReasoningEngine2(); break; case AP: case AP_WF: engine = new spindle.engine.mdl.MdlReasoningEngineAP2(); break; } } break; case TDL: // TDL support only available in version 2 onward if (!AppConst.isDeploy) { try { engine = new spindle.engine.tdl.TdlReasoningEngine2(); } catch (ReasoningEngineException e) { throw new ReasoningEngineFactoryException(e); } } break; default: throw new ReasoningEngineFactoryException(ErrorMessage.THEORY_UNRECOGNIZED_THEORY_TYPE); } return engine; } /** * Return a reasoning engine as specified if the type of engine is in the reasoning engines store; * or create a new one otherwise. * * @param theoryType theory type. * @param engineType engine type (ambiguity blocking, ambiguity propagation, well-founded semantics, or their * combination). * @param reasonerVersion reasoner version. * @return Reasoning engine with appropriate type as specified. * @throws ReasoningEngineFactoryException */ private static final ReasoningEngine getReasoningEngineFromStore(TheoryType theoryType, ENGINE_TYPE engineType, int reasonerVersion) throws ReasoningEngineFactoryException { Map<ENGINE_TYPE, Map<Integer, ReasoningEngine>> enginesSetByTheoryType = reasoningEnginesStore.get(theoryType); if (null == enginesSetByTheoryType) { enginesSetByTheoryType = new TreeMap<ENGINE_TYPE, Map<Integer, ReasoningEngine>>(); reasoningEnginesStore.put(theoryType, enginesSetByTheoryType); } Map<Integer, ReasoningEngine> enginesSet = enginesSetByTheoryType.get(engineType); if (null == enginesSet) { enginesSet = new TreeMap<Integer, ReasoningEngine>(); enginesSetByTheoryType.put(engineType, enginesSet); } ReasoningEngine engine = enginesSet.get(reasonerVersion); if (null == engine) { engine = createReasoningEngine(theoryType, engineType, reasonerVersion); enginesSet.put(reasonerVersion, engine); } engine.clear(); return engine; } /** * Return a reasoning engine according to the theory type, reasoning mode and reasoner version required. * * @param theory defeasible theory * @return reasoning engine associated with the theory type and reasoning mode configured. * @throws ReasoningEngineFactoryException Indicates when there is no reasoning engine associated with the theory * type or reasoning mode specified. */ public static final ReasoningEngine getReasoningEngine(Theory theory) throws ReasoningEngineFactoryException { if (theory == null) return null; TheoryType theoryType = theory.getTheoryType(); if (Conf.isShowProgress() || !AppConst.isDeploy) { if (theory.getTheoryType() != TheoryType.SDL || Conf.isReasoningWithAmbiguityPropagation() || Conf.isReasoningWithWellFoundedSemantics()) { StringBuilder sb = new StringBuilder(); sb.append("Inferencing with ") // .append(theoryType).append(" reasoning engine (version ").append(Conf.getReasonerVersion()).append(")"); if (Conf.isReasoningWithAmbiguityPropagation()) sb.append("\n - Ambiguity Propagation"); if (Conf.isReasoningWithWellFoundedSemantics()) sb.append("\n - Well-Founded Semantics"); System.out.println(TextUtilities.generateHighLightedMessage(sb.toString())); } } ENGINE_TYPE engineType = Conf.isReasoningWithAmbiguityPropagation() ? ENGINE_TYPE.AP : ENGINE_TYPE.AB; if (Conf.isMultiThreadMode()) { return createReasoningEngine(theoryType, engineType, Conf.getReasonerVersion()); } else { return getReasoningEngineFromStore(theoryType, engineType, Conf.getReasonerVersion()); } } }
gpl-3.0
axkr/symja_android_library
symja_android_library/matheclipse-gpl/src/main/java/de/tilman_neumann/jml/factor/cfrac/tdiv/TDiv_CF63_02.java
7396
/* * java-math-library is a Java library focused on number theory, but not necessarily limited to it. It is based on the PSIQS 4.0 factoring project. * Copyright (C) 2018 Tilman Neumann (www.tilman-neumann.de) * * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program; * if not, see <http://www.gnu.org/licenses/>. */ package de.tilman_neumann.jml.factor.cfrac.tdiv; import java.math.BigInteger; import org.apache.log4j.Logger; import de.tilman_neumann.jml.factor.base.SortedIntegerArray; import de.tilman_neumann.jml.factor.base.SortedLongArray; import de.tilman_neumann.jml.factor.base.congruence.AQPair; import de.tilman_neumann.jml.factor.base.congruence.AQPairFactory; import de.tilman_neumann.jml.factor.base.congruence.Smooth_Perfect; import de.tilman_neumann.jml.factor.hart.Hart_TDiv_Race; import de.tilman_neumann.jml.factor.pollardRho.PollardRhoBrentMontgomery64; import de.tilman_neumann.jml.factor.pollardRho.PollardRhoBrentMontgomeryR64Mul63; import de.tilman_neumann.jml.factor.tdiv.TDiv31Inverse; import de.tilman_neumann.jml.primes.probable.PrPTest; /** * Auxiliary factor algorithm to find smooth decompositions of Q's. * * Version 02: * Uses trial division first, complete factorization if Q is considered sufficiently smooth. * * @author Tilman Neumann */ public class TDiv_CF63_02 implements TDiv_CF63 { private static final Logger LOG = Logger.getLogger(TDiv_CF63_02.class); private static final boolean DEBUG = false; private int primeBaseSize; private int[] primesArray; private int pMax; private long pMaxSquare; /** Q is sufficiently smooth if the unfactored Q_rest is smaller than this bound depending on N */ private double maxQRest; private TDiv31Inverse tDiv31 = new TDiv31Inverse(); private Hart_TDiv_Race hart = new Hart_TDiv_Race(); private PollardRhoBrentMontgomeryR64Mul63 pollardRhoR64Mul63 = new PollardRhoBrentMontgomeryR64Mul63(); private PollardRhoBrentMontgomery64 pollardRho64 = new PollardRhoBrentMontgomery64(); private PrPTest prpTest = new PrPTest(); // result: two arrays that are reused, their content is _copied_ to AQ-pairs private SortedIntegerArray smallFactors = new SortedIntegerArray(); private SortedLongArray bigFactors = new SortedLongArray(); private AQPairFactory aqPairFactory = new AQPairFactory(); @Override public String getName() { return "TDiv63-02"; } public void initialize(BigInteger N, double maxQRest) { this.maxQRest = maxQRest; } public void initialize(BigInteger kN, int primeBaseSize, int[] primesArray) { this.primeBaseSize = primeBaseSize; this.primesArray = primesArray; this.pMax = primesArray[primeBaseSize-1]; this.pMaxSquare = pMax * (long) pMax; } public AQPair test(BigInteger A, long Q) { smallFactors.reset(); bigFactors.reset(); // sign long Q_rest = Q; if (Q < 0) { smallFactors.add(-1); Q_rest = -Q; } // Remove multiples of 2 int lsb = Long.numberOfTrailingZeros(Q_rest); if (lsb > 0) { smallFactors.add(2, (short)lsb); Q_rest = Q_rest>>lsb; } // Trial division chain: // -> first do it in long, then in int. // -> (small or probabilistic) prime tests during trial division just slow it down. // -> running indices bottom-up is faster because small dividends are more likely to reduce the size of Q_rest. int trialDivIndex = 1; // p[0]=2 has already been tested int Q_rest_bits = 64 - Long.numberOfLeadingZeros(Q_rest); if (Q_rest_bits>31) { // do trial division in long while (trialDivIndex < primeBaseSize) { int p = primesArray[trialDivIndex]; if (Q_rest % p == 0) { // no remainder -> exact division -> small factor smallFactors.add(p); Q_rest /= p; // After division by a prime base element (typically < 20 bit), Q_rest is 12..61 bits. Q_rest_bits = 64 - Long.numberOfLeadingZeros(Q_rest); if (Q_rest_bits<32) break; // continue with int // trialDivIndex must remain as it is to find the same p more than once } else { trialDivIndex++; } } // end while (trialDivIndex < primeBaseSize) } // if (DEBUG) assertTrue(Q_rest>1); if (Q_rest_bits<32) { int Q_rest_int = (int) Q_rest; while (trialDivIndex < primeBaseSize) { // continue trial division in int int p = primesArray[trialDivIndex]; while (Q_rest_int % p == 0) { // in the last loop, a while pays out! // no remainder -> exact division -> small factor smallFactors.add(p); Q_rest_int /= p; } trialDivIndex++; } // end while (trialDivIndex < primeBaseSize) if (Q_rest_int==1) return new Smooth_Perfect(A, smallFactors); Q_rest = (long) Q_rest_int; // keep Q_rest up-to-date } // trial division was not sufficient to factor Q completely. // the remaining Q is either a prime > pMax, or a composite > pMax^2. if (Q_rest > maxQRest) return null; // Q is not sufficiently smooth // now we consider Q as sufficiently smooth. then we want to know all prime factors, as long as we do not find one that is too big to be useful. //LOG.debug("before factor_recurrent()"); boolean isSmooth = factor_recurrent(Q_rest); if (DEBUG) if (bigFactors.size()>2) LOG.debug("Found " + bigFactors.size() + " distinct big factors: " + bigFactors); return isSmooth ? aqPairFactory.create(A, smallFactors, bigFactors) : null; } private boolean factor_recurrent(long Q_rest) { if (Q_rest < pMaxSquare) { // we divided Q_rest by all primes <= pMax and the rest is < pMax^2 -> it must be prime // if (DEBUG) assertTrue(prpTest.isProbablePrime(Q_rest)); if (bitLength(Q_rest) > 31) return false; bigFactors.add((int)Q_rest); return true; } // here we can not do without isProbablePrime(), because calling findSingleFactor() may not return when called with a prime argument if (prpTest.isProbablePrime(Q_rest)) { // Q_rest is (probable) prime -> end of recurrence if (bitLength(Q_rest) > 31) return false; bigFactors.add((int)Q_rest); return true; } // else: Q_rest is surely not prime // Find a factor of Q_rest, where Q_rest is pMax < Q_rest <= maxQRest, composite and odd. long factor1; int Q_rest_bits = bitLength(Q_rest); if (Q_rest_bits < 25) { factor1 = tDiv31.findSingleFactor((int) Q_rest); } else if (Q_rest_bits < 50) { factor1 = hart.findSingleFactor(Q_rest); } else if (Q_rest_bits < 57) { factor1 = pollardRhoR64Mul63.findSingleFactor(Q_rest); } else { // max Q_rest_bits is 63, pollardRho64 works only until 62 bit, but that should be ok factor1 = pollardRho64.findSingleFactor(Q_rest); } // Recurrence: Is it possible to further decompose the parts? // Here we can not exclude factors > 31 bit because they may have 2 prime factors themselves. return factor_recurrent(factor1) && factor_recurrent(Q_rest / factor1); } private int bitLength(long n) { return 64 - Long.numberOfLeadingZeros(n); } }
gpl-3.0
lionelliang/zorka
zorka-core/src/test/java/com/jitlogic/zorka/core/test/support/TestUtil.java
4838
/** * Copyright 2012-2015 Rafal Lewczuk <rafal.lewczuk@jitlogic.com> * * ZORKA is free software. You can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * ZORKA is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * ZORKA. If not, see <http://www.gnu.org/licenses/>. */ package com.jitlogic.zorka.core.test.support; import com.jitlogic.zorka.core.spy.SpyClassTransformer; import static org.junit.Assert.fail; import javax.management.MBeanServerConnection; import javax.management.ObjectName; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class TestUtil extends ClassLoader { public static byte[] readResource(String name) throws Exception { InputStream is = TestUtil.class.getResourceAsStream("/" + name); byte[] buf = new byte[65536]; int len = is.read(buf); is.close(); byte[] ret = new byte[len]; System.arraycopy(buf, 0, ret, 0, len); return ret; } public static Object instantiate(SpyClassTransformer engine, String clazzName) throws Exception { String className = clazzName.replace(".", "/"); byte[] classBytes = readResource(className + ".class"); byte[] transformed = engine.transform(TestUtil.getSystemClassLoader(), className, null, null, classBytes); Class<?> clazz = new TestUtil().defineClass(clazzName, transformed, 0, transformed.length); return clazz.newInstance(); } private static Field lookupField(Class<?> clazz, String fieldName) { for (Field f : clazz.getFields()) { if (fieldName.equals(f.getName())) { return f; } } for (Field f : clazz.getDeclaredFields()) { if (fieldName.equals(f.getName())) { return f; } } if (clazz.getSuperclass() != Object.class) { Field f = lookupField(clazz.getSuperclass(), fieldName); if (f != null) { return f; } } fail("Cannot find field " + fieldName + " in class " + clazz.getName()); return null; } public static <T> T getField(Object obj, String fieldName) throws Exception { Field field = lookupField(obj.getClass(), fieldName); boolean accessible = field.isAccessible(); field.setAccessible(true); Object retVal = field.get(obj); field.setAccessible(accessible); return (T) retVal; } public static Object invoke(Object obj, String name, Object... args) throws Exception { Method method = null; Class<?> clazz = obj.getClass(); for (Method met : clazz.getMethods()) { if (name.equals(met.getName())) { method = met; break; } } if (method == null) { for (Method met : clazz.getDeclaredMethods()) { if (name.equals(met.getName())) { method = met; method.setAccessible(true); } } } try { if (method != null) { if (args.length == 0) { return method.invoke(obj); } else { return method.invoke(obj, args); } } } catch (InvocationTargetException e) { return e.getCause(); } catch (Exception e) { return e; } return null; } public static Object checkForError(Object obj) { if (obj instanceof Throwable) { System.err.println("Error: " + obj); ((Throwable) obj).printStackTrace(System.err); } return obj; } public static Object getAttr(MBeanServerConnection mbs, String mbeanName, String attr) throws Exception { return mbs.getAttribute(new ObjectName(mbeanName), attr); } public static void rmrf(String path) throws IOException { rmrf(new File(path)); } public static void rmrf(File f) throws IOException { if (f.exists()) { if (f.isDirectory()) { for (File c : f.listFiles()) { rmrf(c); } } f.delete(); } } }
gpl-3.0
unaguil/nu3a
src/nu3a/persistence/N3PersistentResourceContainer.java
1178
/* * Copyright (c) 2003 Jorge García, Unai Aguilera * * This file is part of Nu3A. * * Nu3A is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * Nu3A is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Nu3A. If not, see <http://www.gnu.org/licenses/>. * * * Authors: Jorge García <bardok@gmail.com>, Unai Aguilera <gkalgan@gmail.com> */ package nu3a.persistence; /** * Representa un contenedor de recursos persistentes. */ public interface N3PersistentResourceContainer { /** * A�ade los recursos persistentes que contiene a la lista de recursos. * * @param resources * Lista de recursos */ public void getPersistentResources(N3PersistentResourceList resources); }
gpl-3.0
srs-bsns/Realistic-Terrain-Generation
src/main/java/rtg/world/biome/realistic/vanilla/RealisticBiomeVanillaFlowerForest.java
12218
package rtg.world.biome.realistic.vanilla; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.BlockPlanks.EnumType; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Biomes; import net.minecraft.init.Blocks; import net.minecraft.world.biome.Biome; import net.minecraft.world.chunk.ChunkPrimer; import rtg.api.config.BiomeConfig; import rtg.api.util.BlockUtil; import rtg.api.util.WorldUtil.Terrain; import rtg.api.util.noise.SimplexNoise; import rtg.api.world.RTGWorld; import rtg.api.world.deco.DecoBaseBiomeDecorations; import rtg.api.world.deco.DecoFallenTree; import rtg.api.world.deco.DecoFlowersRTG; import rtg.api.world.deco.DecoGrass; import rtg.api.world.deco.DecoShrub; import rtg.api.world.deco.DecoTree; import rtg.api.world.deco.collection.DecoCollectionSmallPineTreesForest; import rtg.api.world.deco.helper.DecoHelper5050; import rtg.api.world.gen.feature.tree.rtg.TreeRTG; import rtg.api.world.gen.feature.tree.rtg.TreeRTGPinusPonderosa; import rtg.api.world.surface.SurfaceBase; import rtg.api.world.terrain.TerrainBase; import rtg.api.world.biome.RealisticBiomeBase; import static net.minecraft.block.BlockFlower.EnumFlowerType.ALLIUM; import static net.minecraft.block.BlockFlower.EnumFlowerType.BLUE_ORCHID; import static net.minecraft.block.BlockFlower.EnumFlowerType.DANDELION; import static net.minecraft.block.BlockFlower.EnumFlowerType.HOUSTONIA; import static net.minecraft.block.BlockFlower.EnumFlowerType.ORANGE_TULIP; import static net.minecraft.block.BlockFlower.EnumFlowerType.OXEYE_DAISY; import static net.minecraft.block.BlockFlower.EnumFlowerType.PINK_TULIP; import static net.minecraft.block.BlockFlower.EnumFlowerType.POPPY; import static net.minecraft.block.BlockFlower.EnumFlowerType.RED_TULIP; import static net.minecraft.block.BlockFlower.EnumFlowerType.WHITE_TULIP; import static rtg.api.world.deco.DecoFallenTree.LogCondition.RANDOM_CHANCE; public class RealisticBiomeVanillaFlowerForest extends RealisticBiomeBase { public static Biome biome = Biomes.MUTATED_FOREST; public static Biome river = Biomes.RIVER; public RealisticBiomeVanillaFlowerForest() { super(biome); } @Override public void initConfig() { this.getConfig().addProperty(this.getConfig().ALLOW_LOGS).set(true); this.getConfig().addProperty(this.getConfig().FALLEN_LOG_DENSITY_MULTIPLIER); this.getConfig().addProperty(this.getConfig().SURFACE_MIX_BLOCK).set(""); } @Override public TerrainBase initTerrain() { return new TerrainVanillaFlowerForest(); } @Override public SurfaceBase initSurface() { return new SurfaceVanillaFlowerForest(getConfig(), Blocks.GRASS.getDefaultState(), Blocks.DIRT.getDefaultState(), 0f, 1.5f, 60f, 65f, 1.5f, Blocks.GRASS.getDefaultState(), 0.05f); } @Override public void initDecos() { // First, let's get a few shrubs in to break things up a bit. DecoShrub decoShrub = new DecoShrub(); decoShrub.setMaxY(110); decoShrub.setStrengthFactor(4f); decoShrub.setChance(3); this.addDeco(decoShrub); // Flowers are the most aesthetically important feature of this biome, so let's add those next. DecoFlowersRTG decoFlowers1 = new DecoFlowersRTG() .addFlowers(POPPY, BLUE_ORCHID, ALLIUM, HOUSTONIA, RED_TULIP, ORANGE_TULIP, WHITE_TULIP, PINK_TULIP, OXEYE_DAISY, DANDELION) .setStrengthFactor(12f) .setHeightType(DecoFlowersRTG.HeightType.GET_HEIGHT_VALUE); // We're only bothered about surface flowers here. this.addDeco(decoFlowers1); // TODO: [1.12] Add double-plant flowers back into DecoFlowersRTG // DecoFlowersRTG decoFlowers2 = new DecoFlowersRTG(); // decoFlowers2.addFlowers(new int[]{10, 11, 14, 15}); //Only 2-block-tall flowers. // decoFlowers2.setStrengthFactor(2f); // Not as many of these. // decoFlowers2.setChance(3); // decoFlowers2.setHeightType(DecoFlowersRTG.HeightType.GET_HEIGHT_VALUE); // We're only bothered about surface flowers here. // this.addDeco(decoFlowers2); // Trees first. TreeRTG ponderosaOakTree = new TreeRTGPinusPonderosa(); ponderosaOakTree.setLogBlock(Blocks.LOG.getDefaultState()); ponderosaOakTree.setLeavesBlock(Blocks.LEAVES.getDefaultState()); ponderosaOakTree.setMinTrunkSize(11); ponderosaOakTree.setMaxTrunkSize(21); ponderosaOakTree.setMinCrownSize(15); ponderosaOakTree.setMaxCrownSize(29); this.addTree(ponderosaOakTree); DecoTree oakPines = new DecoTree(ponderosaOakTree); oakPines.setStrengthNoiseFactorForLoops(true); oakPines.setTreeType(DecoTree.TreeType.RTG_TREE); oakPines.getDistribution().setNoiseDivisor(80f); oakPines.getDistribution().setNoiseFactor(60f); oakPines.getDistribution().setNoiseAddend(-15f); oakPines.setTreeCondition(DecoTree.TreeCondition.ALWAYS_GENERATE); oakPines.setTreeConditionNoise(0f); oakPines.setTreeConditionChance(1); oakPines.setMaxY(140); TreeRTG ponderosaSpruceTree = new TreeRTGPinusPonderosa(); ponderosaSpruceTree.setLogBlock(BlockUtil.getStateLog(EnumType.SPRUCE)); ponderosaSpruceTree.setLeavesBlock(BlockUtil.getStateLeaf(EnumType.SPRUCE)); ponderosaSpruceTree.setMinTrunkSize(11); ponderosaSpruceTree.setMaxTrunkSize(21); ponderosaSpruceTree.setMinCrownSize(15); ponderosaSpruceTree.setMaxCrownSize(29); this.addTree(ponderosaSpruceTree); DecoTree sprucePines = new DecoTree(ponderosaSpruceTree); sprucePines.setStrengthNoiseFactorForLoops(true); sprucePines.setTreeType(DecoTree.TreeType.RTG_TREE); sprucePines.getDistribution().setNoiseDivisor(80f); sprucePines.getDistribution().setNoiseFactor(60f); sprucePines.getDistribution().setNoiseAddend(-15f); sprucePines.setTreeCondition(DecoTree.TreeCondition.ALWAYS_GENERATE); sprucePines.setTreeConditionNoise(0f); sprucePines.setTreeConditionChance(1); sprucePines.setMaxY(140); DecoHelper5050 decoPines = new DecoHelper5050(oakPines, sprucePines); this.addDeco(decoPines); // More trees. this.addDecoCollection(new DecoCollectionSmallPineTreesForest(this.getConfig())); // Not much free space left, so let's give some space to the base biome. DecoBaseBiomeDecorations decoBaseBiomeDecorations = new DecoBaseBiomeDecorations(); decoBaseBiomeDecorations.setNotEqualsZeroChance(4); this.addDeco(decoBaseBiomeDecorations); // Add some fallen trees of the oak and spruce variety (50/50 distribution). DecoFallenTree decoFallenOak = new DecoFallenTree(); decoFallenOak.setLogCondition(RANDOM_CHANCE); decoFallenOak.setLogConditionChance(8); decoFallenOak.setMaxY(100); decoFallenOak.setLogBlock(Blocks.LOG.getDefaultState()); decoFallenOak.setLeavesBlock(Blocks.LEAVES.getDefaultState()); decoFallenOak.setMinSize(3); decoFallenOak.setMaxSize(6); DecoFallenTree decoFallenSpruce = new DecoFallenTree(); decoFallenSpruce.setLogCondition(RANDOM_CHANCE); decoFallenSpruce.setLogConditionChance(8); decoFallenSpruce.setMaxY(100); decoFallenSpruce.setLogBlock(BlockUtil.getStateLog(EnumType.SPRUCE)); decoFallenSpruce.setLeavesBlock(BlockUtil.getStateLeaf(EnumType.SPRUCE)); decoFallenSpruce.setMinSize(3); decoFallenSpruce.setMaxSize(6); DecoHelper5050 decoFallenTree = new DecoHelper5050(decoFallenOak, decoFallenSpruce); this.addDeco(decoFallenTree, this.getConfig().ALLOW_LOGS.get()); // Grass filler. DecoGrass decoGrass = new DecoGrass(); decoGrass.setMaxY(128); decoGrass.setStrengthFactor(24f); this.addDeco(decoGrass); } public class TerrainVanillaFlowerForest extends TerrainBase { public TerrainVanillaFlowerForest() { } @Override public float generateNoise(RTGWorld rtgWorld, int x, int y, float border, float river) { return terrainPlains(x, y, rtgWorld, river, 160f, 10f, 60f, 80f, 65f); } } public class SurfaceVanillaFlowerForest extends SurfaceBase { private float min; private float sCliff = 1.5f; private float sHeight = 60f; private float sStrength = 65f; private float cCliff = 1.5f; private IBlockState mixBlock; private float mixHeight; public SurfaceVanillaFlowerForest(BiomeConfig config, IBlockState top, IBlockState fill, float minCliff, float stoneCliff, float stoneHeight, float stoneStrength, float clayCliff, IBlockState mix, float mixSize) { super(config, top, fill); min = minCliff; sCliff = stoneCliff; sHeight = stoneHeight; sStrength = stoneStrength; cCliff = clayCliff; mixBlock = this.getConfigBlock(config.SURFACE_MIX_BLOCK.get(), mix); mixHeight = mixSize; } @Override public void paintTerrain(ChunkPrimer primer, int i, int j, int x, int z, int depth, RTGWorld rtgWorld, float[] noise, float river, Biome[] base) { Random rand = rtgWorld.rand(); SimplexNoise simplex = rtgWorld.simplexInstance(0); float c = Terrain.calcCliff(x, z, noise); int cliff = 0; boolean m = false; Block b; for (int k = 255; k > -1; k--) { b = primer.getBlockState(x, k, z).getBlock(); if (b == Blocks.AIR) { depth = -1; } else if (b == Blocks.STONE) { depth++; if (depth == 0) { float p = simplex.noise3f(i / 8f, j / 8f, k / 8f) * 0.5f; if (c > min && c > sCliff - ((k - sHeight) / sStrength) + p) { cliff = 1; } if (c > cCliff) { cliff = 2; } if (cliff == 1) { if (rand.nextInt(3) == 0) { primer.setBlockState(x, k, z, hcCobble(rtgWorld, i, j, x, z, k)); } else { primer.setBlockState(x, k, z, hcStone(rtgWorld, i, j, x, z, k)); } } else if (cliff == 2) { primer.setBlockState(x, k, z, getShadowStoneBlock(rtgWorld, i, j, x, z, k)); } else if (k < 63) { if (k < 62) { primer.setBlockState(x, k, z, fillerBlock); } else { primer.setBlockState(x, k, z, topBlock); } } else if (simplex.noise2f(i / 12f, j / 12f) > mixHeight) { primer.setBlockState(x, k, z, mixBlock); m = true; } else { primer.setBlockState(x, k, z, topBlock); } } else if (depth < 6) { if (cliff == 1) { primer.setBlockState(x, k, z, hcStone(rtgWorld, i, j, x, z, k)); } else if (cliff == 2) { primer.setBlockState(x, k, z, getShadowStoneBlock(rtgWorld, i, j, x, z, k)); } else { primer.setBlockState(x, k, z, fillerBlock); } } } } } } }
gpl-3.0
redsoftbiz/executequery
src/org/executequery/io/ByteArrayFileWriter.java
1552
/* * ByteArrayFileWriter.java * * Copyright (C) 2002-2017 Takis Diakoumis * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 3 * of the License, or any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.executequery.io; import java.io.*; public class ByteArrayFileWriter { public void write(File file, byte[] data) throws IOException { OutputStream outputStream = null; BufferedOutputStream bufferedOutputStream = null; try { outputStream = new FileOutputStream(file); bufferedOutputStream = new BufferedOutputStream(outputStream); bufferedOutputStream.write(data); bufferedOutputStream.flush(); } finally { try { if (bufferedOutputStream != null) { bufferedOutputStream.close(); } if (outputStream != null) { outputStream.close(); } } catch (IOException e) { } } } }
gpl-3.0
utebock/spendenverwaltung
src/main/java/at/fraubock/spendenverwaltung/service/FilterServiceImplemented.java
11350
/******************************************************************************* * Copyright (c) 2013 Bockmas TU Vienna Team. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * * Contributors: * Bockmas TU Vienna Team: Cornelia Hasil, Chris Steele, Manuel Bichler, Philipp Muhoray, Roman Voglhuber, Thomas Niedermaier * * http://www.fraubock.at/ ******************************************************************************/ package at.fraubock.spendenverwaltung.service; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.log4j.Logger; import org.jfree.util.Log; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; import at.fraubock.spendenverwaltung.interfaces.dao.IFilterDAO; import at.fraubock.spendenverwaltung.interfaces.dao.IMountedFilterCriterionDAO; import at.fraubock.spendenverwaltung.interfaces.domain.filter.Filter; import at.fraubock.spendenverwaltung.interfaces.domain.filter.criterion.ConnectedCriterion; import at.fraubock.spendenverwaltung.interfaces.domain.filter.criterion.Criterion; import at.fraubock.spendenverwaltung.interfaces.domain.filter.to.FilterTO; import at.fraubock.spendenverwaltung.interfaces.exceptions.FilterInUseException; import at.fraubock.spendenverwaltung.interfaces.exceptions.PersistenceException; import at.fraubock.spendenverwaltung.interfaces.exceptions.ServiceException; import at.fraubock.spendenverwaltung.interfaces.service.IAddressService; import at.fraubock.spendenverwaltung.interfaces.service.IDonationService; import at.fraubock.spendenverwaltung.interfaces.service.IFilterService; import at.fraubock.spendenverwaltung.interfaces.service.IMailingService; import at.fraubock.spendenverwaltung.interfaces.service.IPersonService; import at.fraubock.spendenverwaltung.util.Pair; import at.fraubock.spendenverwaltung.util.filter.FilterType; import at.fraubock.spendenverwaltung.util.filter.LogicalOperator; import com.sun.xml.internal.txw2.IllegalSignatureException; /** * implementation of {@link IFilterService} * * @author philipp muhoray * */ @SuppressWarnings("restriction") public class FilterServiceImplemented implements IFilterService { private static final Logger log = Logger .getLogger(FilterServiceImplemented.class); private IFilterDAO filterDAO; private IMountedFilterCriterionDAO mountedCritDAO; private IAddressService addressService; private IPersonService personService; private IDonationService donationService; private IMailingService mailingService; /** * @return the addressService */ public IAddressService getAddressService() { return addressService; } /** * @param addressService * the addressService to set */ public void setAddressService(IAddressService addressService) { this.addressService = addressService; } /** * @return the personService */ public IPersonService getPersonService() { return personService; } /** * @param personService * the personService to set */ public void setPersonService(IPersonService personService) { this.personService = personService; } /** * @return the donationService */ public IDonationService getDonationService() { return donationService; } /** * @param donationService * the donationService to set */ public void setDonationService(IDonationService donationService) { this.donationService = donationService; } /** * @return the mailingService */ public IMailingService getMailingService() { return mailingService; } /** * @param mailingService * the mailingService to set */ public void setMailingService(IMailingService mailingService) { this.mailingService = mailingService; } public IFilterDAO getFilterDAO() { return filterDAO; } public void setFilterDAO(IFilterDAO filterDAO) { this.filterDAO = filterDAO; } @Override @Transactional(rollbackFor = Throwable.class, isolation = Isolation.READ_COMMITTED) public Filter create(FilterTO f) throws ServiceException { try { Filter filter = createFilterFromTransferObject(f); filterDAO.insert(filter); return filter; } catch (PersistenceException e) { throw new ServiceException(e); } } @Override @Transactional(rollbackFor = Throwable.class, isolation = Isolation.READ_COMMITTED) public Filter update(Filter f, FilterTO to) throws ServiceException { try { Filter filter = createFilterFromTransferObject(to); filter.setOwner(f.getOwner()); filter.setId(f.getId()); filterDAO.update(filter, f.getCriterion()); return filter; } catch (PersistenceException e) { throw new ServiceException(); } } @Override @Transactional(rollbackFor = Throwable.class, isolation = Isolation.READ_COMMITTED) public void delete(Filter f) throws ServiceException, FilterInUseException { if (f == null) { log.error("Filter was null in delete."); throw new ServiceException(); } if (f.getId() == null) { log.error("Filter had no ID in delete"); throw new ServiceException(); } try { for (Integer id : mountedCritDAO.getAllMountedFilterIds()) { if (f.getId().equals(id)) { throw new FilterInUseException(); } } filterDAO.delete(f); } catch (PersistenceException e) { throw new ServiceException(e); } } @Override @Transactional(readOnly = true, rollbackFor = Throwable.class, isolation = Isolation.READ_COMMITTED) public Pair<List<Filter>, String> getAll() throws ServiceException { List<Filter> list = null; String uName = null; try { list = filterDAO.getAll(); uName = filterDAO.getCurrentUserName(); } catch (PersistenceException e) { throw new ServiceException(e); } return new Pair<List<Filter>, String>(list, uName); } @Override @Transactional(readOnly = true, rollbackFor = Throwable.class, isolation = Isolation.READ_COMMITTED) public Pair<List<Filter>, String> getAllByFilterIgnoreAnonymous(FilterType type) throws ServiceException { if (type == null) { log.error("FilterType was null in getAllByFilter."); throw new ServiceException(); } List<Filter> list = new ArrayList<Filter>(); String uName; try { for (Filter filter : filterDAO.getAll()) { if (filter.getType() == type) { list.add(filter); } } uName = filterDAO.getCurrentUserName(); } catch (PersistenceException e) { throw new ServiceException(e); } return new Pair<List<Filter>, String>(list, uName); } @Override @Transactional(readOnly = true, rollbackFor = Throwable.class, isolation = Isolation.READ_COMMITTED) public Pair<List<Filter>, String> getAllByFilter(FilterType type) throws ServiceException { if (type == null) { log.error("FilterType was null in getAllByFilter."); throw new ServiceException(); } List<Filter> list = new ArrayList<Filter>(); String uName; try { for (Filter filter : filterDAO.getAll()) { if (filter.getType() == type && !filter.isAnonymous()) { list.add(filter); } } uName = filterDAO.getCurrentUserName(); } catch (PersistenceException e) { throw new ServiceException(e); } return new Pair<List<Filter>, String>(list, uName); } @Override @Transactional(readOnly = true, rollbackFor = Throwable.class, isolation = Isolation.READ_COMMITTED) public Pair<List<Filter>, String> getAllByAnonymous(boolean anonymous) throws ServiceException { Pair<List<Filter>, String> allPair = getAll(); Iterator<Filter> i = allPair.a.iterator(); while (i.hasNext()) { Filter f = i.next(); if (f.isAnonymous() != anonymous) { i.remove(); } } return allPair; } @Override @Transactional(readOnly = true, rollbackFor = Throwable.class, isolation = Isolation.READ_COMMITTED) public Filter getByID(int id) throws ServiceException { Filter filter = null; try { filter = filterDAO.getById(id); } catch (PersistenceException e) { throw new ServiceException(e); } return filter; } private Filter createFilterFromTransferObject(FilterTO filterTO) throws ServiceException { if (filterTO == null) { log.error("FilterTO was null in create"); throw new ServiceException(); } if (filterTO.getOperator() == null || filterTO.getPrivacyStatus() == null || filterTO.getType() == null) { log.error("FilterTO had invalid null values in create: " + filterTO.toString()); throw new ServiceException(); } Filter filter = new Filter(); filter.setType(filterTO.getType()); filter.setName(filterTO.getName()); filter.setAnonymous(filterTO.isAnonymous()); filter.setPrivacyStatus(filterTO.getPrivacyStatus()); LogicalOperator operator = filterTO.getOperator(); List<Criterion> crits = filterTO.getCriterions(); if (crits.isEmpty()) { return filter; } else if (crits.size() == 1) { filter.setCriterion(crits.get(0)); return filter; } ConnectedCriterion current = new ConnectedCriterion(); current.connect(crits.get(0), operator, crits.get(1)); for (int index = 2; index < crits.size(); index++) { ConnectedCriterion con = new ConnectedCriterion(); con.connect(current, operator, crits.get(index)); current = con; } filter.setCriterion(current); return filter; } public IMountedFilterCriterionDAO getMountedCritDAO() { return mountedCritDAO; } public void setMountedCritDAO(IMountedFilterCriterionDAO mountedCritDAO) { this.mountedCritDAO = mountedCritDAO; } @Override @Transactional(readOnly = true, rollbackFor = Throwable.class, isolation = Isolation.READ_COMMITTED) public String convertResultsToCSVById(int id) throws ServiceException { Filter f = getByID(id); if (f == null) return null; switch (f.getType()) { case ADDRESS: return addressService.convertToCSV(addressService.getByFilter(f)); case DONATION: return donationService.convertToCSV(donationService.getByFilter(f)); case MAILING: return mailingService.convertToCSV(mailingService.getByFilter(f)); case PERSON: return personService.convertToCSV(personService.getByFilter(f)); } // we should never get here String msg = "Programming error: This code should not be reached. The filter " + f + " is of an illegal type."; Log.error(msg); throw new IllegalSignatureException(msg); } @Override public boolean saveResultsAsCSVById(int id, File csvFile) throws ServiceException, IOException { Filter f = getByID(id); if (f == null) return false; switch (f.getType()) { case ADDRESS: addressService.saveAsCSV(addressService.getByFilter(f), csvFile); return true; case DONATION: donationService.saveAsCSV(donationService.getByFilter(f), csvFile); return true; case MAILING: mailingService.saveAsCSV(mailingService.getByFilter(f), csvFile); return true; case PERSON: personService.saveAsCSV(personService.getByFilter(f), csvFile); return true; } // we should never get here String msg = "Programming error: This code should not be reached. The filter " + f + " is of an illegal type."; Log.error(msg); throw new IllegalSignatureException(msg); } }
gpl-3.0
BlissRoms/platform_packages_apps_OmniSwitch
src/org/omnirom/omniswitch/RecentTasksLoader.java
22297
/* * Copyright (C) 2013-2016 The OmniROM Project * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.omnirom.omniswitch; import java.io.IOException; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import org.omnirom.omniswitch.ui.BitmapCache; import org.omnirom.omniswitch.ui.BitmapUtils; import org.omnirom.omniswitch.ui.IconPackHelper; import android.app.ActivityManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Handler; import android.os.ParcelFileDescriptor; import android.os.Process; import android.os.RemoteException; import android.os.SystemClock; import android.util.Log; public class RecentTasksLoader { private static final String TAG = "RecentTasksLoader"; private static final boolean DEBUG = false; private static final int TASK_INIT_LOAD = 8; private Context mContext; private AsyncTask<Void, List<TaskDescription>, Void> mTaskLoader; private AsyncTask<Void, Void, Void> mTaskInfoLoader; private AsyncTask<Void, TaskDescription, Void> mThumbnailLoader; private Handler mHandler; private List<TaskDescription> mLoadedTasks; private List<TaskDescription> mLoadedTasksOriginal; private boolean mPreloaded; private SwitchManager mSwitchManager; private ActivityManager mActivityManager; private Bitmap mDefaultThumbnail; private PreloadTaskRunnable mPreloadTasksRunnable; private boolean mHasThumbPermissions; private SwitchConfiguration mConfiguration; private PackageManager mPackageManager; private Drawable mDefaultAppIcon; private Set<String> mLockedAppsList; final static BitmapFactory.Options sBitmapOptions; static { sBitmapOptions = new BitmapFactory.Options(); sBitmapOptions.inMutable = true; sBitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565; } private enum State { LOADING, IDLE }; private State mState = State.IDLE; private static RecentTasksLoader sInstance; public static RecentTasksLoader getInstance(Context context) { if (sInstance == null) { sInstance = new RecentTasksLoader(context); } return sInstance; } public static void killInstance() { sInstance = null; } private RecentTasksLoader(Context context) { mContext = context; mHandler = new Handler(); mLoadedTasks = new CopyOnWriteArrayList<TaskDescription>(); mLoadedTasksOriginal = new CopyOnWriteArrayList<TaskDescription>(); mLockedAppsList = new HashSet<String>(); mActivityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE); mPackageManager = mContext.getPackageManager(); mDefaultThumbnail = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); mDefaultThumbnail.setHasAlpha(true); mDefaultThumbnail.eraseColor(0x00ffffff); mHasThumbPermissions = hasSystemPermission(context); mConfiguration = SwitchConfiguration.getInstance(mContext); mDefaultAppIcon = BitmapUtils.getDefaultActivityIcon(mContext); } private boolean isCurrentHomeActivity(ComponentName component, ActivityInfo homeInfo) { if (homeInfo == null) { homeInfo = new Intent(Intent.ACTION_MAIN).addCategory( Intent.CATEGORY_HOME).resolveActivityInfo(mPackageManager, 0); } return homeInfo != null && homeInfo.packageName.equals(component.getPackageName()) && homeInfo.name.equals(component.getClassName()); } // Create an TaskDescription, returning null if the title or icon is null TaskDescription createTaskDescription(int taskId, int persistentTaskId, int stackId, Intent baseIntent, ComponentName origActivity, boolean supportsSplitScreenMultiWindow) { // clear source bounds to find matching package intent baseIntent.setSourceBounds(null); Intent intent = new Intent(baseIntent); if (origActivity != null) { intent.setComponent(origActivity); } intent.setFlags((intent.getFlags() & ~Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) | Intent.FLAG_ACTIVITY_NEW_TASK); final ResolveInfo resolveInfo = mPackageManager.resolveActivity(intent, 0); if (resolveInfo != null) { if (DEBUG) Log.v(TAG, "creating activity desc for id=" + persistentTaskId); TaskDescription ad = new TaskDescription(taskId, persistentTaskId, resolveInfo, baseIntent, stackId, supportsSplitScreenMultiWindow); return ad; } return null; } private class PreloadTaskRunnable implements Runnable { @Override public void run() { if (DEBUG) { Log.d(TAG, "preload start " + System.currentTimeMillis()); } loadTasksInBackground(0, true, true); } } public void preloadTasks() { mPreloadTasksRunnable = new PreloadTaskRunnable(); mHandler.post(mPreloadTasksRunnable); } public void setSwitchManager(final SwitchManager manager) { mSwitchManager = manager; } public void cancelLoadingTasks() { if (DEBUG) { Log.d(TAG, "cancelLoadingTasks state = " + mState); } if (mTaskLoader != null) { mTaskLoader.cancel(true); mTaskLoader = null; } if (mTaskInfoLoader != null) { mTaskInfoLoader.cancel(true); mTaskInfoLoader = null; } if (mThumbnailLoader != null) { mThumbnailLoader.cancel(true); mThumbnailLoader = null; } if (mPreloadTasksRunnable != null) { mHandler.removeCallbacks(mPreloadTasksRunnable); mPreloadTasksRunnable = null; } mLoadedTasks.clear(); mLoadedTasksOriginal.clear(); mPreloaded = false; mState = State.IDLE; } public void loadTasksInBackground(int maxNumTasks, boolean withIcons, boolean withThumbs) { if (mPreloaded && mState != State.IDLE) { if (DEBUG) { Log.d(TAG, "recents preloaded: waiting for done"); } return; } if (mPreloaded && mSwitchManager != null) { if (DEBUG) { Log.d(TAG, "recents preloaded " + mLoadedTasks); } mSwitchManager.update(mLoadedTasks, mLoadedTasksOriginal); loadMissingTaskInfo(); return; } if (DEBUG) { Log.d(TAG, "recents load"); } mPreloaded = true; mState = State.LOADING; mLoadedTasks.clear(); mLoadedTasksOriginal.clear(); if (withThumbs) { BitmapCache.getInstance(mContext).clearThumbs(); } final long currentTime = System.currentTimeMillis(); final long bootTimeMillis = currentTime - SystemClock.elapsedRealtime(); mLockedAppsList.clear(); mLockedAppsList.addAll(mConfiguration.mLockedAppList); mTaskLoader = new AsyncTask<Void, List<TaskDescription>, Void>() { @Override protected void onProgressUpdate( List<TaskDescription>... values) { if (!isCancelled()) { if (mSwitchManager != null) { if (DEBUG) { Log.d(TAG, "recents loaded"); } mSwitchManager.update(mLoadedTasks, mLoadedTasksOriginal); loadMissingTaskInfo(); } else { if (DEBUG) { Log.d(TAG, "recents preloaded"); } } } } @Override protected Void doInBackground(Void... params) { long start = System.currentTimeMillis(); if (DEBUG) { Log.d(TAG, "loadTasksInBackground " + mSwitchManager + " start " + start); } final int origPri = Process.getThreadPriority(Process.myTid()); Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND); final List<ActivityManager.RecentTaskInfo> recentTasks = mActivityManager .getRecentTasks(maxNumTasks == 0 ? ActivityManager.getMaxRecentTasksStatic() : maxNumTasks, ActivityManager.RECENT_IGNORE_UNAVAILABLE | ActivityManager.RECENT_WITH_EXCLUDED); int numTasks = recentTasks.size(); final ActivityInfo homeInfo = new Intent(Intent.ACTION_MAIN) .addCategory(Intent.CATEGORY_HOME).resolveActivityInfo(mPackageManager, 0); boolean isFirstValidTask = true; int preloadTaskNum = 0; final boolean withIconPack = IconPackHelper.getInstance(mContext).isIconPackLoaded(); for (int i = 0; i < numTasks; ++i) { if (isCancelled()) { break; } final ActivityManager.RecentTaskInfo recentInfo = recentTasks .get(i); final ActivityManager.TaskDescription taskDescription = recentInfo.taskDescription; if (DEBUG) { Log.d(TAG, "" + i + " recent item = " + recentInfo.baseIntent + " " + recentInfo.taskDescription.getLabel()); } TaskDescription item = createTaskDescription(recentInfo.id, recentInfo.persistentId, recentInfo.stackId, recentInfo.baseIntent, recentInfo.origActivity, recentInfo.supportsSplitScreenMultiWindow); if (item == null) { continue; } if (mLockedAppsList.contains(item.getPackageName())) { item.setLocked(true); } Intent intent = new Intent(recentInfo.baseIntent); if (recentInfo.origActivity != null) { intent.setComponent(recentInfo.origActivity); } if (taskDescription != null) { item.setTaskPrimaryColor(taskDescription.getPrimaryColor()); item.setTaskBackgroundColor(taskDescription.getBackgroundColor()); } // Don't load the current home activity. if (isCurrentHomeActivity(intent.getComponent(), homeInfo)) { continue; } final String componentString = intent.getComponent().flattenToShortString(); if (componentString.contains(".recents.RecentsActivity") || componentString.contains("com.android.settings/.FallbackHome")) { continue; } boolean activeTask = true; // never time filter locked tasks if (mConfiguration.mFilterActive && !item.isLocked()) { long lastActiveTime = recentInfo.lastActiveTime; long firstActiveTime = recentInfo.firstActiveTime; if (DEBUG) { Log.d(TAG, intent.getComponent().getPackageName() + ": " + firstActiveTime + ":" + lastActiveTime + ":" + bootTimeMillis); } // only show active since boot if (mConfiguration.mFilterBoot && lastActiveTime < bootTimeMillis) { if (DEBUG) { Log.d(TAG, intent.getComponent().getPackageName() + ": filter app not active since boot"); } activeTask = false; } if (activeTask) { // filter older then time if (mConfiguration.mFilterTime != 0 && lastActiveTime < currentTime - mConfiguration.mFilterTime) { if (DEBUG) { Log.d(TAG, intent.getComponent().getPackageName() + ": filter app not active since " + mConfiguration.mFilterTime); } activeTask = false; } } if (activeTask) { if (mConfiguration.mFilterRunning && recentInfo.id < 0) { if (DEBUG) { Log.d(TAG, intent.getComponent().getPackageName() + ": filter app not running"); } activeTask = false; } } } if (!activeTask) { if (DEBUG) { Log.d(TAG, "skip inactive task =" + recentInfo.baseIntent); } continue; } // Check the first non-recents task, include this task even if it is marked as excluded boolean isExcluded = (recentInfo.baseIntent.getFlags() & Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS; if (isExcluded && !isFirstValidTask) { continue; } isFirstValidTask = false; mLoadedTasksOriginal.add(item); if (item.isLocked() && mConfiguration.mTopSortLockedApps) { mLoadedTasks.add(0, item); } else { mLoadedTasks.add(item); } if (preloadTaskNum < TASK_INIT_LOAD) { if (withIcons) { String label = item.resolveInfo.loadLabel(mPackageManager).toString(); loadTaskIcon(item, withIconPack, label); item.setLabel(label); } if (withThumbs) { Bitmap b = getThumbnail(item.persistentTaskId, true, preloadTaskNum == 0); if (b != null) { item.setThumb(b, false); } } preloadTaskNum++; } } if (!isCancelled()) { publishProgress(mLoadedTasks); } if (DEBUG) { Log.d(TAG, "loadTasksInBackground end " + (System.currentTimeMillis() - start)); } mState = State.IDLE; Process.setThreadPriority(origPri); return null; } }; mTaskLoader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } public Bitmap getThumbnail(int taskId, boolean reducedResolution, boolean firstThumb) { try { ActivityManager.TaskSnapshot snapshot = ActivityManager.getService().getTaskSnapshot(taskId, reducedResolution); if (snapshot != null) { if (DEBUG) { Log.d(TAG, "getThumbnail " + taskId); } return Bitmap.createHardwareBitmap(snapshot.getSnapshot()); } } catch (RemoteException e) { Log.w(TAG, "Failed to retrieve snapshot", e); } return null; } void loadTaskIcon(TaskDescription td, boolean withIconPack, String label) { Drawable icon = getFullResIcon(td.resolveInfo, withIconPack, label); if (icon == null) { icon = mDefaultAppIcon; } td.setIcon(icon); } private IconPackHelper getIconPackHelper() { return IconPackHelper.getInstance(mContext); } private Drawable getFullResIcon(ResolveInfo info, boolean withIconPack, String label) { Resources resources; try { resources = mPackageManager .getResourcesForApplication(info.activityInfo.applicationInfo); } catch (PackageManager.NameNotFoundException e) { resources = null; } if (resources != null) { int iconId = 0; if (withIconPack) { iconId = getIconPackHelper().getResourceIdForActivityIcon(info.activityInfo); if (iconId != 0) { return IconPackHelper.getInstance(mContext).getIconPackResources().getDrawable(iconId); } } iconId = info.activityInfo.getIconResource(); if (iconId != 0) { try { Drawable d = resources.getDrawable(iconId, null); if (withIconPack) { d = BitmapUtils.compose(resources, d, mContext, getIconPackHelper().getIconBackFor(label), getIconPackHelper().getIconMask(), getIconPackHelper().getIconUpon(), getIconPackHelper().getIconScale(), mConfiguration.mIconSize, mConfiguration.mDensity); } return d; } catch (Exception e) { } } } return null; } public void loadThumbnail(final TaskDescription td) { if (!mHasThumbPermissions) { return; } if (td.isThumbLoading()) { return; } mThumbnailLoader = new AsyncTask<Void, TaskDescription, Void>() { @Override protected void onProgressUpdate(TaskDescription... values) { } @Override protected Void doInBackground(Void... params) { final int origPri = Process.getThreadPriority(Process.myTid()); Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND); if (DEBUG) { Log.d(TAG, "late load thumb " + td + " " + td.persistentTaskId); } td.setThumbLoading(true); Bitmap b = getThumbnail(td.persistentTaskId, true, false); if (b != null) { td.setThumbLoading(false); td.setThumb(b, true); } Process.setThreadPriority(origPri); return null; } }; mThumbnailLoader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } public void loadTaskInfo(final TaskDescription td) { synchronized(td) { String label = td.resolveInfo.loadLabel(mPackageManager).toString(); final boolean withIconPack = IconPackHelper.getInstance(mContext).isIconPackLoaded(); Drawable icon = getFullResIcon(td.resolveInfo, withIconPack, label); if (icon == null) { icon = mDefaultAppIcon; } td.setIcon(icon); td.setLabel(label); } } private void loadMissingTaskInfo() { mTaskInfoLoader = new AsyncTask<Void, Void, Void>() { @Override protected void onProgressUpdate(Void... values) { } @Override protected Void doInBackground(Void... params) { long start = System.currentTimeMillis(); final int origPri = Process.getThreadPriority(Process.myTid()); Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); for (TaskDescription td : mLoadedTasks) { if (isCancelled()) { break; } synchronized(td) { if (DEBUG) { Log.d(TAG, "late load task info " + td + " " + td.persistentTaskId); } loadTaskInfo(td); } } if (DEBUG) { Log.d(TAG, "loadMissingTaskInfo end " + (System.currentTimeMillis() - start)); } Process.setThreadPriority(origPri); return null; } }; mTaskInfoLoader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } private boolean hasSystemPermission(Context context) { int result = context .checkCallingOrSelfPermission(android.Manifest.permission.READ_FRAME_BUFFER); return result == android.content.pm.PackageManager.PERMISSION_GRANTED; } public Bitmap getDefaultThumb() { return mDefaultThumbnail; } private String getSettingsActivity() { return mContext.getPackageName() + "/.SettingsActivity"; } }
gpl-3.0
Waikato/meka
src/test/java/meka/classifiers/multilabel/MLCBMaDTest.java
2055
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * Copyright (C) 2012 University of Waikato, Hamilton, New Zealand */ package meka.classifiers.multilabel; import junit.framework.Test; import junit.framework.TestSuite; import weka.classifiers.Classifier; import weka.core.Instances; /** * Tests MLCBMaD. Run from the command line with:<p/> * java meka.classifiers.multilabel.MLCBMaDTest * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision: 117 $ */ public class MLCBMaDTest extends AbstractMultiLabelClassifierTest { /** * Initializes the test. * * @param name the name of the test */ public MLCBMaDTest(String name) { super(name); } /** * Creates a default classifier. * * @return the classifier */ @Override public Classifier getClassifier() { MLCBMaD mlcbmad = new MLCBMaD(); mlcbmad.setSize(5); return mlcbmad; } public void testEvaluation() { System.out.println("Testing Evaluation"); Instances D = null; try { D = loadData("Music.arff"); } catch(Exception e) { System.err.println(" Failed to Load "); } //Assert.assertEquals("Result 1", D.classIndex(), 6); //Assert.assertEquals("Result 1", D.classIndex(), 3); } public static Test suite() { return new TestSuite(MLCBMaDTest.class); } public static void main(String[] args){ junit.textui.TestRunner.run(suite()); } }
gpl-3.0
eric-stanley/apg
OpenKeychain/src/main/java/org/sufficientlysecure/keychain/remote/RemoteService.java
10881
/* * Copyright (C) 2013-2014 Dominik Schürmann <dominik@dominikschuermann.de> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.thialfihar.android.apg.remote; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.Signature; import android.net.Uri; import android.os.Binder; import org.openintents.openpgp.OpenPgpError; import org.openintents.openpgp.util.OpenPgpApi; import org.thialfihar.android.apg.Constants; import org.thialfihar.android.apg.R; import org.thialfihar.android.apg.provider.ApgContract; import org.thialfihar.android.apg.provider.ProviderHelper; import org.thialfihar.android.apg.remote.ui.RemoteServiceActivity; import org.thialfihar.android.apg.util.Log; import java.util.ArrayList; import java.util.Arrays; /** * Abstract service class for remote APIs that handle app registration and user input. */ public abstract class RemoteService extends Service { public static class WrongPackageSignatureException extends Exception { private static final long serialVersionUID = -8294642703122196028L; public WrongPackageSignatureException(String message) { super(message); } } Context mContext; ProviderHelper mProviderHelper; public Context getContext() { return mContext; } /** * Checks if caller is allowed to access the API * * @param data * @return null if caller is allowed, or a Bundle with a PendingIntent */ protected Intent isAllowed(Intent data) { try { if (isCallerAllowed(false)) { return null; } else { String packageName = getCurrentCallingPackage(); Log.d(Constants.TAG, "isAllowed packageName: " + packageName); byte[] packageSignature; try { packageSignature = getPackageSignature(packageName); } catch (NameNotFoundException e) { Log.e(Constants.TAG, "Should not happen, returning!", e); // return error Intent result = new Intent(); result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR); result.putExtra(OpenPgpApi.RESULT_ERROR, new OpenPgpError(OpenPgpError.GENERIC_ERROR, e.getMessage())); return result; } Log.e(Constants.TAG, "Not allowed to use service! return PendingIntent for registration!"); Intent intent = new Intent(getBaseContext(), RemoteServiceActivity.class); intent.setAction(RemoteServiceActivity.ACTION_REGISTER); intent.putExtra(RemoteServiceActivity.EXTRA_PACKAGE_NAME, packageName); intent.putExtra(RemoteServiceActivity.EXTRA_PACKAGE_SIGNATURE, packageSignature); intent.putExtra(RemoteServiceActivity.EXTRA_DATA, data); PendingIntent pi = PendingIntent.getActivity(getBaseContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT); // return PendingIntent to be executed by client Intent result = new Intent(); result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED); result.putExtra(OpenPgpApi.RESULT_INTENT, pi); return result; } } catch (WrongPackageSignatureException e) { Log.e(Constants.TAG, "wrong signature!", e); Intent intent = new Intent(getBaseContext(), RemoteServiceActivity.class); intent.setAction(RemoteServiceActivity.ACTION_ERROR_MESSAGE); intent.putExtra(RemoteServiceActivity.EXTRA_ERROR_MESSAGE, getString(R.string.api_error_wrong_signature)); intent.putExtra(RemoteServiceActivity.EXTRA_DATA, data); PendingIntent pi = PendingIntent.getActivity(getBaseContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); // return PendingIntent to be executed by client Intent result = new Intent(); result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED); result.putExtra(OpenPgpApi.RESULT_INTENT, pi); return result; } } private byte[] getPackageSignature(String packageName) throws NameNotFoundException { PackageInfo pkgInfo = getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES); Signature[] signatures = pkgInfo.signatures; // TODO: Only first signature?! byte[] packageSignature = signatures[0].toByteArray(); return packageSignature; } /** * Returns package name associated with the UID, which is assigned to the process that sent you the * current transaction that is being processed :) * * @return package name */ protected String getCurrentCallingPackage() { // TODO: // callingPackages contains more than one entry when sharedUserId has been used... String[] callingPackages = getPackageManager().getPackagesForUid(Binder.getCallingUid()); String currentPkg = callingPackages[0]; Log.d(Constants.TAG, "currentPkg: " + currentPkg); return currentPkg; } /** * Retrieves AccountSettings from database for the application calling this remote service * * @return */ protected AccountSettings getAccSettings(String accountName) { String currentPkg = getCurrentCallingPackage(); Log.d(Constants.TAG, "accountName: " + accountName); Uri uri = ApgContract.ApiAccounts.buildByPackageAndAccountUri(currentPkg, accountName); AccountSettings settings = mProviderHelper.getApiAccountSettings(uri); return settings; // can be null! } protected Intent getCreateAccountIntent(Intent data, String accountName) { String packageName = getCurrentCallingPackage(); Log.d(Constants.TAG, "accountName: " + accountName); Intent intent = new Intent(getBaseContext(), RemoteServiceActivity.class); intent.setAction(RemoteServiceActivity.ACTION_CREATE_ACCOUNT); intent.putExtra(RemoteServiceActivity.EXTRA_PACKAGE_NAME, packageName); intent.putExtra(RemoteServiceActivity.EXTRA_ACC_NAME, accountName); intent.putExtra(RemoteServiceActivity.EXTRA_DATA, data); PendingIntent pi = PendingIntent.getActivity(getBaseContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); // return PendingIntent to be executed by client Intent result = new Intent(); result.putExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED); result.putExtra(OpenPgpApi.RESULT_INTENT, pi); return result; } /** * Checks if process that binds to this service (i.e. the package name corresponding to the * process) is in the list of allowed package names. * * @param allowOnlySelf allow only Keychain app itself * @return true if process is allowed to use this service * @throws WrongPackageSignatureException */ private boolean isCallerAllowed(boolean allowOnlySelf) throws WrongPackageSignatureException { return isUidAllowed(Binder.getCallingUid(), allowOnlySelf); } private boolean isUidAllowed(int uid, boolean allowOnlySelf) throws WrongPackageSignatureException { if (android.os.Process.myUid() == uid) { return true; } if (allowOnlySelf) { // barrier return false; } String[] callingPackages = getPackageManager().getPackagesForUid(uid); // is calling package allowed to use this service? for (int i = 0; i < callingPackages.length; i++) { String currentPkg = callingPackages[i]; if (isPackageAllowed(currentPkg)) { return true; } } Log.d(Constants.TAG, "Uid is NOT allowed!"); return false; } /** * Checks if packageName is a registered app for the API. Does not return true for own package! * * @param packageName * @return * @throws WrongPackageSignatureException */ private boolean isPackageAllowed(String packageName) throws WrongPackageSignatureException { Log.d(Constants.TAG, "isPackageAllowed packageName: " + packageName); ArrayList<String> allowedPkgs = mProviderHelper.getRegisteredApiApps(); Log.d(Constants.TAG, "allowed: " + allowedPkgs); // check if package is allowed to use our service if (allowedPkgs.contains(packageName)) { Log.d(Constants.TAG, "Package is allowed! packageName: " + packageName); // check package signature byte[] currentSig; try { currentSig = getPackageSignature(packageName); } catch (NameNotFoundException e) { throw new WrongPackageSignatureException(e.getMessage()); } byte[] storedSig = mProviderHelper.getApiAppSignature(packageName); if (Arrays.equals(currentSig, storedSig)) { Log.d(Constants.TAG, "Package signature is correct! (equals signature from database)"); return true; } else { throw new WrongPackageSignatureException( "PACKAGE NOT ALLOWED! Signature wrong! (Signature not " + "equals signature from database)"); } } Log.d(Constants.TAG, "Package is NOT allowed! packageName: " + packageName); return false; } @Override public void onCreate() { super.onCreate(); mContext = this; mProviderHelper = new ProviderHelper(this); } }
gpl-3.0
MythTV-Clients/MythtvPlayerForAndroid
mythtv-player/src/main/java/org/mythtv/android/data/entity/LiveStreamInfoEntity.java
4000
/* * MythTV Player An application for Android users to play MythTV Recordings and Videos * Copyright (c) 2015. Daniel Frey * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.mythtv.android.data.entity; import com.google.auto.value.AutoValue; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.annotations.SerializedName; import org.joda.time.DateTime; import javax.annotation.Nullable; /** * * * * @author dmfrey * * Created on 10/17/15. */ @AutoValue public abstract class LiveStreamInfoEntity { @SerializedName( "Id" ) public abstract int id(); @SerializedName( "Width" ) public abstract int width(); @SerializedName( "Height" ) public abstract int height(); @SerializedName( "Bitrate" ) public abstract int bitrate(); @SerializedName( "AudioBitrate" ) public abstract int audioBitrate(); @SerializedName( "SegmentSize" ) public abstract int segmentSize(); @SerializedName( "MaxSegments" ) public abstract int maxSegments(); @SerializedName( "StartSegment" ) public abstract int startSegment(); @SerializedName( "CurrentSegment" ) public abstract int currentSegment(); @SerializedName( "SegmentCount" ) public abstract int segmentCount(); @SerializedName( "PercentComplete" ) public abstract int percentComplete(); @Nullable @SerializedName( "Created" ) public abstract DateTime created(); @Nullable @SerializedName( "LastModified" ) public abstract DateTime lastModified(); @Nullable @SerializedName( "RelativeURL" ) public abstract String relativeUrl(); @Nullable @SerializedName( "FullURL" ) public abstract String fullUrl(); @Nullable @SerializedName( "StatusStr" ) public abstract String statusString(); @SerializedName( "StatusInt" ) public abstract int statusInt(); @Nullable @SerializedName( "StatusMessage" ) public abstract String statusMessage(); @Nullable @SerializedName( "SourceFile" ) public abstract String sourceFile(); @Nullable @SerializedName( "SourceHost" ) public abstract String sourceHost(); @SerializedName( "SourceWidth" ) public abstract int sourceWidth(); @SerializedName( "SourceHeight" ) public abstract int sourceHeight(); @SerializedName( "AudioOnlyBitrate" ) public abstract int audioOnlyBitrate(); public static LiveStreamInfoEntity create( int id, int width, int height, int bitrate, int audioBitrate, int segmentSize, int maxSegments, int startSegment, int currentSegment, int segmentCount, int percentComplete, DateTime created, DateTime lastModified, String relativeUrl, String fullUrl, String statusString, int statusInt, String statusMessage, String sourceFile, String sourceHost, int sourceWidth, int sourceHeight, int audioOnlyBitrate ) { return new AutoValue_LiveStreamInfoEntity( id, width, height, bitrate, audioBitrate, segmentSize, maxSegments, startSegment, currentSegment, segmentCount, percentComplete, created, lastModified, relativeUrl, fullUrl, statusString, statusInt, statusMessage, sourceFile, sourceHost, sourceWidth, sourceHeight, audioOnlyBitrate ); } public static TypeAdapter<LiveStreamInfoEntity> typeAdapter( Gson gson ) { return new AutoValue_LiveStreamInfoEntity.GsonTypeAdapter( gson ); } }
gpl-3.0
nsp/OpenSettlers
src/java/soc/util/CutoffExceededException.java
1346
/** * Open Settlers - an open implementation of the game Settlers of Catan * Copyright (C) 2003 Robert S. Thomas * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **/ package soc.util; /** * this exception means that the cutoff has been exceeded */ public class CutoffExceededException extends Exception { private static final long serialVersionUID = 8240071180658912137L; /** * Creates a new CutoffExceededException object. */ public CutoffExceededException() { super(); } /** * Creates a new CutoffExceededException object. * * @param s DOCUMENT ME! */ public CutoffExceededException(String s) { super(s); } }
gpl-3.0
dedeme/cgi
src/cgi/B41.java
5827
/* * Copyright 13-jun-2015 ºDeme * * This file is part of 'cgi'. * * 'cgi' is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License. * * 'cgi' is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with 'cgi'. If not, see <http://www.gnu.org/licenses/>. */ package cgi; import java.util.ArrayList; /** * * @version 1.0 * @since 13-jun-2015 * @author deme */ public class B41 { static String chars = "RSTUVWXYZa" + "bcdefghijk" + "lmnopqrstu" + "vwxyzABCDE" + "F"; /** * Returns the number of code B41 'b' * @param b * @return */ public static int b2n (char b) { return chars.indexOf(b); } /** * Returns the B41 code whose number is 'n' * @param n * @return */ public static char n2b (int n) { return chars.charAt(n); } /** * Encodes a string in B41 * @param s * @return */ public static String encode (String s) { StringBuilder r = new StringBuilder(); int i; for (i = 0; i < s.length(); i++) { int n = s.codePointAt(i); int n1 = n / 41; r.append(chars.charAt(n1 / 41)).append( chars.charAt(n1 % 41)).append( chars.charAt(n % 41)); } return r.toString(); } /** * Decodes a string codified with encode * @param c * @return */ public static String decode (String c) { StringBuilder r = new StringBuilder(); int i = 0; while (i < c.length()) { int n1 = chars.indexOf(c.charAt(i++)); int n2 = chars.indexOf(c.charAt(i++)); int n3 = chars.indexOf(c.charAt(i++)); r.append(new String(Character.toChars(1681 * n1 + 41 * n2 + n3))); } return r.toString(); } /** * Encodes an int[] in B41 * @param bs * @return */ public static String encodeBytes (int[] bs) { int lg = bs.length; boolean odd = false; if (lg % 2 != 0) { odd = true; --lg; } StringBuilder r = new StringBuilder(); int i = 0; while (i < lg) { int n = bs[i] * 256 + bs[i + 1]; int n1 = n / 41; r.append(chars.charAt(n1 / 41)).append( chars.charAt(n1 % 41)).append( chars.charAt(n % 41)); i += 2; } if (odd) { int n = bs[i]; r.append(chars.charAt(n / 41)).append(chars.charAt(n % 41)); } return r.toString(); } /** * Decodes an int[] codified with encodeBytes * @param c * @return */ public static int[] decodeInts (String c) { int lg = c.length(); boolean odd = false; if (lg % 3 != 0) { odd = true; lg -= 2; } ArrayList<Integer>r = new ArrayList<>(); int i = 0; while (i < lg) { int n1 = chars.indexOf(c.charAt(i++)); int n2 = chars.indexOf(c.charAt(i++)); int n3 = chars.indexOf(c.charAt(i++)); int n = 1681 * n1 + 41 * n2 + n3; r.add(n / 256); r.add(n % 256); } if (odd) { int n1 = chars.indexOf(c.charAt(i++)); int n2 = chars.indexOf(c.charAt(i++)); int n = 41 * n1 + n2; r.add(n); } return r.stream().mapToInt((Integer v) -> { return v; }).toArray(); } /** * Decodes a bytes[] codified with encodeBytes * @param c * @return */ public static byte[] decodeBytes (String c) { int lg = c.length(); boolean odd = false; if (lg % 3 != 0) { odd = true; lg -= 2; } ArrayList<Byte>r = new ArrayList<>(); int i = 0; while (i < lg) { int n1 = chars.indexOf(c.charAt(i++)); int n2 = chars.indexOf(c.charAt(i++)); int n3 = chars.indexOf(c.charAt(i++)); int n = 1681 * n1 + 41 * n2 + n3; r.add((byte)(n / 256)); r.add((byte)(n % 256)); } if (odd) { int n1 = chars.indexOf(c.charAt(i++)); int n2 = chars.indexOf(c.charAt(i++)); int n = 41 * n1 + n2; r.add((byte)n); } byte[] rb = new byte[r.size()]; for (i = 0; i < rb.length; i++){ rb[i] = r.get(i); } return rb; } /** * Compressing a B41 code. It is useful to codify strings. * @param s * @return */ public static String compress (String s) { String c = encode(s); int n = 0; int i = 0; String tmp = ""; StringBuilder r = new StringBuilder(); while (i < c.length()) { if (c.substring(i, i + 2).equals("RT")) { ++n; tmp = tmp + c.charAt(i + 2); if (n == 10) { r.append(String.valueOf(n - 1)).append(tmp); tmp = ""; n = 0; } } else { if (n > 0) { r.append(String.valueOf(n - 1)).append(tmp); tmp = ""; n = 0; } r.append(c.substring(i, i + 3)); } i += 3; } if (n > 0) { r.append(String.valueOf(n - 1)).append(tmp); } return r.toString(); } /** * Decompress a B41 code compressed with compress * @param c * @return */ public static String decompress (String c) { StringBuilder r = new StringBuilder(); int i = 0; while (i < c.length()) { char ch = c.charAt(i++); if (ch >= '0' && ch <= '9') { int n = Character.digit(ch, 10) + 1; for (int j = 0; j < n; j++) { ch = c.charAt(i++); r.append("RT").append(ch); } } else { r.append(ch); for (int j = 0; j < 2; j++) { ch = c.charAt(i++); r.append(ch); } } } return decode(r.toString()); } }
gpl-3.0
thshdw/lixia-javardp
src/com/lixia/rdp/RdesktopJFrame.java
7357
/* RdesktopJFrame.java * Component: LixiaJavaRDP * * Revision: $Revision: 1.0 $ * Author: $Author: pengzhou $ * Date: $Date: 2009/03/16 $ * * Copyright (c) 2010 pengzhou * * Purpose: Container of drawing panel. */ package com.lixia.rdp; import java.awt.Dialog; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.GridLayout; import java.awt.KeyboardFocusManager; import java.awt.Label; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.net.URL; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.WindowConstants; import org.apache.log4j.Logger; import com.lixia.rdp.Options; public class RdesktopJFrame extends javax.swing.JFrame { static Logger logger = Logger.getLogger(RdesktopJFrame.class); public RdesktopJPanel canvas = null; public RdpJPanel rdp = null; /** * */ private static final long serialVersionUID = 1L; public RdesktopJFrame() { super(); initGUI(); } private void initGUI() { try { Common.frame = this; canvas = new RdesktopJPanel_Localised(Options.width, Options.height); this.setContentPane(canvas); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); pack(); // setSize(Options.width+8, Options.height+12); // setSize(Options.width, Options.height); if (Constants.OS != Constants.WINDOWS) setResizable(false); addWindowListener(new RdesktopWindowAdapter()); canvas.addFocusListener(new RdesktopFocusListener()); // key board focus manger KeyboardFocusManager.setCurrentKeyboardFocusManager(null); if (Constants.OS == Constants.WINDOWS) { // redraws screen on window move addComponentListener(new RdesktopComponentAdapter()); } try{ URL url = RdesktopSwing.class.getResource("fron-ico.PNG"); if(url != null) this.setIconImage(Toolkit.getDefaultToolkit().getImage(url)); } catch(Exception e){ //nothing to do } this.setTitle(Options.windowTitle); setLocationRelativeTo(null); canvas.requestFocusInWindow(); } catch (Exception e) { e.printStackTrace(); } } class OKDialog extends JDialog implements ActionListener { public OKDialog(JFrame parent, String title, String[] message) { super(parent, title, true); JPanel msg = new JPanel(); msg.setLayout(new GridLayout(message.length, 1)); for (int i = 0; i < message.length; i++) msg.add(new JLabel(message[i], JLabel.CENTER)); this.add("Center", msg); JPanel p = new JPanel(); p.setLayout(new FlowLayout()); JButton ok = new JButton("OK"); ok.addActionListener(this); p.add(ok); this.add("South", p); this.pack(); if (getSize().width < 240) setSize(new Dimension(240, getSize().height)); // centreWindow(this); } public void actionPerformed(ActionEvent e) { this.setVisible(false); this.dispose(); } } public void showErrorDialog(String[] msg) { JDialog d = new OKDialog(this, "lixia-javardp: Error", msg); d.setVisible(true); } public void triggerReadyToSend() { // do not show out windows if seamless active. do it in ui_seamless_begin() if(!Options.no_loginProgress) this.setVisible(true); RdesktopJPanel pane = (RdesktopJPanel)this.getContentPane(); pane.triggerReadyToSend(); } public RdesktopJPanel getCanvas() { return this.canvas; } public void registerCommLayer(RdpJPanel rdp) { this.rdp = rdp; RdesktopJPanel pane = (RdesktopJPanel)this.getContentPane(); pane.registerCommLayer(rdp); } class YesNoDialog extends Dialog implements ActionListener { JButton yes, no; boolean retry = false; public YesNoDialog(Frame parent, String title, String[] message) { super(parent, title, true); // Box msg = Box.createVerticalBox(); // for(int i=0; i<message.length; i++) msg.add(new // Label(message[i],Label.CENTER)); // this.add("Center",msg); JPanel msg = new JPanel(); msg.setLayout(new GridLayout(message.length, 1)); for (int i = 0; i < message.length; i++) msg.add(new Label(message[i], Label.CENTER)); this.add("Center", msg); JPanel p = new JPanel(); p.setLayout(new FlowLayout()); yes = new JButton("Yes"); yes.addActionListener(this); p.add(yes); no = new JButton("No"); no.addActionListener(this); p.add(no); this.add("South", p); this.pack(); if (getSize().width < 240) setSize(new Dimension(240, getSize().height)); //centreWindow(this); } public void actionPerformed(ActionEvent e) { if (e.getSource() == yes) retry = true; else retry = false; this.setVisible(false); this.dispose(); } } public boolean showYesNoErrorDialog(String[] msg) { YesNoDialog d = new YesNoDialog(this, "lixia-javardp: Error", msg); d.setVisible(true); return d.retry; } private boolean menuVisible = false; /** * Hide the menu bar */ public void hideMenu(){ if(menuVisible && Options.enable_menu) this.setMenuBar(null); //canvas.setSize(this.WIDTH, this.HEIGHT); canvas.repaint(); menuVisible = false; } class RdesktopFocusListener implements FocusListener { public void focusGained(FocusEvent arg0) { if (Constants.OS == Constants.WINDOWS) { // canvas.repaint(); canvas.repaint(0, 0, Options.width, Options.height); } // gained focus..need to check state of locking keys canvas.gainedFocus(); } public void focusLost(FocusEvent arg0) { // lost focus - need clear keys that are down canvas.lostFocus(); } } class RdesktopWindowAdapter extends WindowAdapter { public void windowClosing(WindowEvent e) { setVisible(false); RdesktopSwing.exit(0, rdp, (RdesktopJFrame) e.getWindow(), true); } public void windowLostFocus(WindowEvent e) { logger.info("windowLostFocus"); // lost focus - need clear keys that are down canvas.lostFocus(); } public void windowDeiconified(WindowEvent e) { if (Constants.OS == Constants.WINDOWS) { // canvas.repaint(); canvas.repaint(0, 0, Options.width, Options.height); } canvas.gainedFocus(); } public void windowActivated(WindowEvent e) { if (Constants.OS == Constants.WINDOWS) { // canvas.repaint(); canvas.repaint(0, 0, Options.width, Options.height); } // gained focus..need to check state of locking keys canvas.gainedFocus(); } public void windowGainedFocus(WindowEvent e) { if (Constants.OS == Constants.WINDOWS) { // canvas.repaint(); canvas.repaint(0, 0, Options.width, Options.height); } // gained focus..need to check state of locking keys canvas.gainedFocus(); } } class RdesktopComponentAdapter extends ComponentAdapter { public void componentMoved(ComponentEvent e) { canvas.repaint(0, 0, Options.width, Options.height); } } }
gpl-3.0
trixromero/cafecomaromademulher
lulachances/src/main/java/br/com/entelgy/dtos/MessageDto.java
498
package br.com.entelgy.dtos; public class MessageDto { private String message; private MessageType type; public MessageDto() { super(); } public MessageDto(MessageType type, String msg) { super(); this.message = msg; this.type = type; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public MessageType getType() { return type; } public void setType(MessageType type) { this.type = type; } }
gpl-3.0
Effervex/DagYo
src/graph/core/DAGException.java
757
/******************************************************************************* * Copyright (C) 2013 University of Waikato, Hamilton, New Zealand. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * * Contributors: * Sam Sarjant - initial API and implementation ******************************************************************************/ package graph.core; public class DAGException extends Exception { private static final long serialVersionUID = 8297966398470776460L; public DAGException(String message) { super(message); } }
gpl-3.0
bluebottle/is.idega.idegaweb.block.pheidippides
src/java/is/idega/idegaweb/pheidippides/servlet/ValitorMoveSuccess.java
3203
package is.idega.idegaweb.pheidippides.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import com.idega.idegaweb.IWMainApplication; import com.idega.presentation.IWContext; import is.idega.idegaweb.pheidippides.business.PheidippidesService; import is.idega.idegaweb.pheidippides.business.RegistrationHeaderStatus; import is.idega.idegaweb.pheidippides.data.RegistrationHeader; public class ValitorMoveSuccess extends HttpServlet { private static final long serialVersionUID = -5479791076359839694L; private static final String VALITOR_SECURITY_NUMBER = "VALITOR_SECURITY_NUMBER"; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setStatus(200); resp.setContentType("text/plain"); IWContext iwc = new IWContext(req, resp, req.getSession().getServletContext()); WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(iwc.getServletContext()); PheidippidesService service = (PheidippidesService) springContext.getBean("pheidippidesService"); String uniqueID = iwc.getParameter("uniqueID"); RegistrationHeader header = service.getRegistrationHeader(uniqueID); if (header.getStatus().equals(RegistrationHeaderStatus.WaitingForPayment)) { String securityString = iwc.getParameter("RafraenUndirskriftSvar"); String referenceNumber = iwc.getParameter("Tilvisunarnumer"); String securityNumber = IWMainApplication .getDefaultIWApplicationContext().getApplicationSettings() .getProperty(VALITOR_SECURITY_NUMBER, "12345"); if (validateSecurityString(service, securityNumber, referenceNumber, securityString)) { String cardType = iwc.getParameter("Kortategund"); String cardNumber = iwc.getParameter("KortnumerSidustu"); String paymentDate = iwc.getParameter("Dagsetning"); String authorizationNumber = iwc.getParameter("Heimildarnumer"); String transactionNumber = iwc.getParameter("Faerslunumer"); String comment = iwc.getParameter("Athugasemd"); String saleID = iwc.getParameter("VefverslunSalaID"); service.markChangeDistanceAsPaid(header, securityString, cardType, cardNumber, paymentDate, authorizationNumber, transactionNumber, referenceNumber, comment, saleID); } } PrintWriter out = resp.getWriter(); out.println("The Valitor move success response has been processed..."); out.close(); } private boolean validateSecurityString(PheidippidesService service, String securityNumber, String referenceNumber, String securityString) { String created = service.createValitorSecurityString(securityNumber + referenceNumber); if (created != null && created.equals(securityString)) { return true; } return false; } }
gpl-3.0
lhebj/provence
src/com/provence/web/util/PageUtil.java
5906
package com.provence.web.util; import javax.servlet.http.HttpServletRequest; public class PageUtil { public static int SHOW_PAGE = 10; /** * current page */ private int curPage; /** * page size */ private int pageSize; /** * total result count */ private int totalCount; /** * total page count */ private int pageCount; /** * */ private int curFirstPage; /** * */ private int curLastPage; /** * */ private int start; /** * */ private int limit; /** * */ private int end; public PageUtil(int totalCount, int curPage) { this.curPage = curPage; this.pageSize = 25; this.totalCount = totalCount; this.pageCount = (int) Math.ceil((double) totalCount / pageSize); this.start = pageSize * (curPage - 1); this.limit = pageSize; if (totalCount - start > limit) { this.end = start + limit; } else { this.end = totalCount; } if (pageCount < SHOW_PAGE) { this.curFirstPage = 1; this.curLastPage = pageCount; } else if (pageCount - curPage < 5) { this.curFirstPage = pageCount - SHOW_PAGE + 1; this.curLastPage = pageCount; } else if ((curPage - SHOW_PAGE / 2) < 0) { this.curFirstPage = 1; this.curLastPage = SHOW_PAGE; } else { this.curFirstPage = curPage - SHOW_PAGE / 2 + 1; this.curLastPage = curPage + SHOW_PAGE / 2; } } public PageUtil(int totalCount, int curPage, int pageSize) { this.curPage = curPage; this.pageSize = pageSize; this.totalCount = totalCount; this.pageCount = (int) Math.ceil((double) totalCount / pageSize); this.start = pageSize * (curPage - 1); this.limit = pageSize; if (totalCount - start > limit) { this.end = start + limit; } else { this.end = totalCount; } if (pageCount < SHOW_PAGE) { this.curFirstPage = 1; this.curLastPage = pageCount; } else if (pageCount - curPage < 5) { this.curFirstPage = pageCount - SHOW_PAGE + 1; this.curLastPage = pageCount; } else if ((curPage - SHOW_PAGE / 2) < 0) { this.curFirstPage = 1; this.curLastPage = SHOW_PAGE; } else { this.curFirstPage = curPage - SHOW_PAGE / 2 + 1; this.curLastPage = curPage + SHOW_PAGE / 2; } } public PageUtil(int totalCount, int curPage, int pageSize, int showPage) { this.curPage = curPage; this.pageSize = pageSize; this.totalCount = totalCount; this.pageCount = (int) Math.ceil((double) totalCount / pageSize); this.start = pageSize * (curPage - 1); this.limit = pageSize; if (totalCount - start > limit) { this.end = start + limit; } else { this.end = totalCount; } if (pageCount < showPage) { this.curFirstPage = 1; this.curLastPage = pageCount; } else if (pageCount - curPage < 5) { this.curFirstPage = pageCount - showPage + 1; this.curLastPage = pageCount; } else if ((curPage - showPage / 2) < 0) { this.curFirstPage = 1; this.curLastPage = showPage; } else { this.curFirstPage = curPage - showPage / 2 + 1; this.curLastPage = curPage + showPage / 2; } } public int getCurPage() { return curPage; } public int getPageSize() { return pageSize; } public int getTotalCount() { return totalCount; } public int getPageCount() { return pageCount; } public int getCurFirstPage() { return curFirstPage; } public int getCurLastPage() { return curLastPage; } public int getStart() { return start; } public void setStart(int start) { this.start = start; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } public int getEnd() { return end; } public void setEnd(int end) { this.end = end; } public int first() { return 1; } public int last() { return pageCount; } public int previous() { return (curPage - 1 < 1) ? 1 : curPage - 1; } public int next() { return (curPage + 1 > pageCount) ? pageCount : curPage + 1; } public boolean isFirst() { return (curPage == 1) ? true : false; } public boolean isLast() { if (pageCount == 0) { return true; } return (curPage == pageCount) ? true : false; } public String getToolBar(String queryUrl, HttpServletRequest request) { String temp = ""; if (queryUrl.indexOf("?") == -1) { temp = "?"; } else { temp = "&"; } String str = "<p class=\"pageTurn\">"; if (isFirst()) str += "<span class=\"colorhuise\">"+LocalizationUtil.getClientString("FirstPage", request) + "</span> <span class=\"colorhuise\">" + LocalizationUtil.getClientString("PrevPage", request) + "</span>&nbsp;"; else { str += "<a href='" + queryUrl + temp + "curPage=1'>" + LocalizationUtil.getClientString("FirstPage", request) + "</a>&nbsp;"; str += "<a href='" + queryUrl + temp + "curPage=" + (curPage - 1) + "'>" + LocalizationUtil.getClientString("PrevPage", request) + "</a>&nbsp;"; } for (int i = curFirstPage; i <= curLastPage; i++) { if (i == curPage) { str += i + "&nbsp;"; } else { str += "<a href='" + queryUrl + temp + "curPage=" + i + "'>" + i + "</a>&nbsp;"; } } if (isLast()) str += "<span class=\"colorhuise\">" + LocalizationUtil.getClientString("NextPage", request) + "</span> <span class=\"colorhuise\">" + LocalizationUtil.getClientString("LastPage", request) + "</span>&nbsp;"; else { str += "<a href='" + queryUrl + temp + "curPage=" + (curPage + 1) + "'>" + LocalizationUtil.getClientString("NextPage", request) + "</a>&nbsp;"; str += "<a href='" + queryUrl + temp + "curPage=" + pageCount + "'>" + LocalizationUtil.getClientString("LastPage", request) + "</a>&nbsp;"; } str += "&nbsp;" + LocalizationUtil.getClientString("Total", request) + "&nbsp;<b>" + pageCount+"</b>&nbsp;" + LocalizationUtil.getClientString("Pages", request) + "&nbsp;" + LocalizationUtil.getClientString("Total", request) + "&nbsp;<b>" + totalCount + "</b>&nbsp;" + LocalizationUtil.getClientString("Records", request) + "&nbsp;</p>"; return str; } }
gpl-3.0
LamGC/TulingRobot-For-Minecraft
src/main/wzh/http/HttpRequest.java
3749
package wzh.http; import java.io.*; import java.net.URL; import java.net.URLConnection; /** * 本类代码来源 * http://www.cnblogs.com/zhuawang/archive/2012/12/08/2809380.html * 代码经过修改,详细请查看历史修改 */ public class HttpRequest { /** * 向指定URL发送GET方法的请求 * * @param url * 发送请求的URL * @param param * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return URL 所代表远程资源的响应结果 */ public static String sendGet(String url, String param) throws IOException { StringBuilder result = new StringBuilder(); BufferedReader in; String urlNameString = url + "?" + param; URL realUrl = new URL(urlNameString); // 打开和URL之间的连接 URLConnection connection = realUrl.openConnection(); // 设置通用的请求属性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 建立实际的连接 connection.connect(); // 获取所有响应头字段 //Map<String, List<String>> map = connection.getHeaderFields(); // 遍历所有的响应头字段 /*for (String key : map.keySet()) { System.out.println(key + "--->" + map.get(key)); }*/ // 定义 BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader( connection.getInputStream(),"UTF-8")); String line; while ((line = in.readLine()) != null) { result.append(line); } // 使用finally块来关闭输入流 return result.toString(); } /** * 向指定 URL 发送POST方法的请求 * * @param url * 发送请求的 URL * @param param * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return 所代表远程资源的响应结果 * @throws IOException 在请求失败,输出输入流错误时抛出 */ public static String sendPost(String url, String param,String ContentType) throws IOException { PrintWriter out; BufferedReader in; StringBuilder result = new StringBuilder(); URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection conn = realUrl.openConnection(); // 设置通用的请求属性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); if(!ContentType.equalsIgnoreCase("")){ conn.setRequestProperty("Content-Type", ContentType); } conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36"); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); // 获取URLConnection对象对应的输出流 out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8")); // 发送请求参数 out.print(param); // flush输出流的缓冲 out.flush(); // 定义BufferedReader输入流来读取URL的响应 in = new BufferedReader( new InputStreamReader(conn.getInputStream(),"UTF-8")); String line; while ((line = in.readLine()) != null) { result.append(line).append("\n"); } return result.toString(); } }
gpl-3.0
oRatioSolver/oRatio
src/it/cnr/istc/oratio/types/ReusableResource.java
12711
/* * Copyright (C) 2016 Riccardo De Benedictis <riccardo.debenedictis@istc.cnr.it> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package it.cnr.istc.oratio.types; import it.cnr.istc.ac.ArithExpr; import it.cnr.istc.ac.BoolExpr; import it.cnr.istc.ac.DomainListener; import it.cnr.istc.ac.LBool; import it.cnr.istc.ac.Var; import it.cnr.istc.core.Atom; import it.cnr.istc.core.AtomState; import it.cnr.istc.core.Constructor; import static it.cnr.istc.core.Core.REAL; import it.cnr.istc.core.Field; import it.cnr.istc.core.IArithItem; import it.cnr.istc.core.IBoolItem; import it.cnr.istc.core.IEnumItem; import it.cnr.istc.core.IItem; import static it.cnr.istc.core.IScope.SCOPE; import it.cnr.istc.core.Predicate; import it.cnr.istc.oratio.Flaw; import it.cnr.istc.oratio.Resolver; import it.cnr.istc.oratio.SmartType; import it.cnr.istc.oratio.Solver; import it.cnr.istc.utils.CombinationGenerator; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** * * @author Riccardo De Benedictis <riccardo.debenedictis@istc.cnr.it> */ public class ReusableResource extends SmartType { public static final String NAME = "ReusableResource"; public static final String CAPACITY = "capacity"; public static final String USE_PREDICATE_NAME = "Use"; public static final String AMOUNT = "amount"; private final Set<IItem> to_check = new HashSet<>(); public ReusableResource(Solver s) { super(s, s, NAME); fields.put(CAPACITY, new Field(s.getType(REAL), CAPACITY)); constructors.add(new Constructor(core, this) { @Override public boolean invoke(IItem item, IItem... expressions) { assert expressions.length == 0; IArithItem capacity = core.newRealItem(); set(item, scope.getField(CAPACITY), capacity); return core.add(core.geq(capacity, core.newRealItem(0))); } }); constructors.add(new Constructor(core, this, new Field(core.getType(REAL), CAPACITY)) { @Override public boolean invoke(IItem item, IItem... expressions) { assert expressions.length == 1; IArithItem capacity = (IArithItem) expressions[0]; set(item, scope.getField(CAPACITY), capacity); return core.add(core.geq(capacity, core.newRealItem(0))); } }); predicates.put(USE_PREDICATE_NAME, new Predicate(core, this, USE_PREDICATE_NAME, new Field(core.getType(REAL), AMOUNT)) { @Override public boolean apply(Atom atom) { throw new AssertionError("this rule should never be applied.."); } }); extendPredicate(predicates.get(USE_PREDICATE_NAME), core.getPredicate("IntervalPredicate")); } @Override protected void predicateDefined(Predicate predicate) { throw new AssertionError("reusable resource predicates are predefined.."); } @Override protected boolean factCreated(Atom atom) { if (super.factCreated(atom)) { return solver.add(core.not(core.eq(atom.state, AtomState.Unified))); } else { return false; } } @Override protected boolean factActivated(Atom atom) { if (super.factActivated(atom)) { core.addDomainListener(new AtomListener(atom)); to_check.addAll(((IEnumItem) atom.get(SCOPE)).getEnumVar().evaluate().getAllowedValues()); return core.getPredicate("IntervalPredicate").apply(atom); } else { return false; } } @Override protected boolean factUnified(Atom unifying, Atom with) { throw new AssertionError("facts cannot unify on reusable resources.."); } @Override protected boolean goalCreated(Atom atom) { throw new AssertionError("goals cannot be created on reusable resources.."); } @Override protected boolean goalActivated(Atom atom) { throw new AssertionError("goals cannot be activated on reusable resources.."); } @Override protected boolean goalUnified(Atom unifying, Atom with) { throw new AssertionError("goals cannot be unified on reusable resources.."); } @Override public Collection<Flaw> getInconsistencies() { if (to_check.isEmpty()) { // nothing has changed since last inconsistency check.. return Collections.emptyList(); } Map<IItem, Collection<Atom>> instances = new IdentityHashMap<>(to_check.size()); for (IItem i : to_check) { instances.put(i, new ArrayList<>()); } for (Atom atom : predicates.values().stream().flatMap(p -> p.getInstances().stream()).map(a -> (Atom) a).filter(a -> a.state.evaluate().isSingleton() && a.state.evaluate().contains(AtomState.Active)).collect(Collectors.toList())) { for (IItem i : ((IEnumItem) atom.get(SCOPE)).getEnumVar().evaluate().getAllowedValues()) { if (instances.containsKey(i)) { instances.get(i).add(atom); } } } Collection<Flaw> fs = new ArrayList<>(); for (IItem i : to_check) { Collection<Atom> atoms = instances.get(i); // For each pulse the atoms starting at that pulse Map<Double, Collection<Atom>> starting_atoms = new HashMap<>(atoms.size()); // For each pulse the atoms ending at that pulse Map<Double, Collection<Atom>> ending_atoms = new HashMap<>(atoms.size()); // The pulses of the timeline Set<Double> c_pulses = new HashSet<>(atoms.size() * 2); for (Atom atom : atoms) { double start = core.evaluate(((IArithItem) atom.get("start")).getArithVar()); double end = core.evaluate(((IArithItem) atom.get("end")).getArithVar()); if (!starting_atoms.containsKey(start)) { starting_atoms.put(start, new ArrayList<>()); } starting_atoms.get(start).add(atom); if (!ending_atoms.containsKey(end)) { ending_atoms.put(end, new ArrayList<>()); } ending_atoms.get(end).add(atom); c_pulses.add(start); c_pulses.add(end); } // we sort current pulses.. Double[] c_pulses_array = c_pulses.toArray(new Double[c_pulses.size()]); Arrays.sort(c_pulses_array); List<Atom> overlapping_atoms = new ArrayList<>(); for (Double p : c_pulses_array) { if (starting_atoms.containsKey(p)) { overlapping_atoms.addAll(starting_atoms.get(p)); } if (ending_atoms.containsKey(p)) { overlapping_atoms.removeAll(ending_atoms.get(p)); } if (overlapping_atoms.size() > 1 && core.evaluate(core.sum(overlapping_atoms.stream().map(atom -> ((IArithItem) atom.get(AMOUNT)).getArithVar()).toArray(ArithExpr[]::new))) > core.evaluate(((IArithItem) i.get(CAPACITY)).getArithVar())) { Collection<BoolExpr> or = new ArrayList<>(); for (Atom[] as : new CombinationGenerator<>(2, overlapping_atoms.toArray(new Atom[overlapping_atoms.size()]))) { ArithExpr a0_start = ((IArithItem) as[0].get("start")).getArithVar(); ArithExpr a0_end = ((IArithItem) as[0].get("end")).getArithVar(); ArithExpr a1_start = ((IArithItem) as[1].get("start")).getArithVar(); ArithExpr a1_end = ((IArithItem) as[1].get("end")).getArithVar(); BoolExpr a0_before_a1 = core.leq(a0_end, a1_start); if (a0_before_a1.root() != LBool.L_FALSE) { or.add(a0_before_a1); } BoolExpr a1_before_a0 = core.leq(a1_end, a0_start); if (a1_before_a0.root() != LBool.L_FALSE) { or.add(a1_before_a0); } IEnumItem a0_scope = (IEnumItem) as[0].get(SCOPE); Set<IItem> a0_scopes = a0_scope.getEnumVar().root().getAllowedValues(); if (a0_scopes.size() > 1) { for (IItem a0_s : a0_scopes) { or.add(core.not(a0_scope.allows(a0_s))); } } IEnumItem a1_scope = (IEnumItem) as[1].get(SCOPE); Set<IItem> a1_scopes = a1_scope.getEnumVar().root().getAllowedValues(); if (a1_scopes.size() > 1) { for (IItem a1_s : a1_scopes) { or.add(core.not(a1_scope.allows(a1_s))); } } } fs.add(new ReusableResourceFlaw(solver, or)); } } } to_check.clear(); return fs; } private class AtomListener implements DomainListener { private final Atom atom; AtomListener(Atom atom) { this.atom = atom; } @Override public Var<?>[] getVars() { return atom.getItems().values().stream().filter(i -> (i instanceof IBoolItem || i instanceof IArithItem || i instanceof IEnumItem)).map(i -> { if (i instanceof IBoolItem) { return ((IBoolItem) i).getBoolVar().to_var(core); } else if (i instanceof IArithItem) { return ((IArithItem) i).getArithVar().to_var(core); } else { return ((IEnumItem) i).getEnumVar().to_var(core); } }).toArray(Var<?>[]::new); } @Override public void domainChange(Var<?> var) { for (IItem i : ((IEnumItem) atom.get(SCOPE)).getEnumVar().evaluate().getAllowedValues()) { to_check.add(i); } } } private static class ReusableResourceFlaw extends Flaw { private final Collection<BoolExpr> or; ReusableResourceFlaw(Solver s, Collection<BoolExpr> or) { super(s, false); this.or = or; } @Override protected boolean computeResolvers(Collection<Resolver> rs) { for (BoolExpr expr : or) { rs.add(new ReusableResourceResolver(solver, solver.newReal(1.0 / or.size()), this, expr)); } return true; } @Override public String toSimpleString() { return "rr-flaw"; } @Override public String toString() { return or.stream().map(v -> v.toString()).collect(Collectors.joining(" | ")) + " " + in_plan.evaluate() + " " + solver.getCost(this); } } private static class ReusableResourceResolver extends Resolver { private final BoolExpr expr; ReusableResourceResolver(Solver s, ArithExpr c, Flaw e, BoolExpr expr) { super(s, c, e); this.expr = expr; } @Override protected boolean apply() { return solver.add(solver.imply(in_plan, expr)); } @Override public String toSimpleString() { return expr.id(); } } }
gpl-3.0
georgematos/ocaert
src/com/xcode/utils/Ratings.java
688
package com.xcode.utils; import com.xcode.interfaces.ExamObjective; public class Ratings { public static int getRating(ExamObjective... examObjective) { /** * Retorna a nota total de todos os tópicos. */ int rating = 0; for(ExamObjective objective : examObjective) { rating += objective.getReadiness(); } return rating; } public static int upMaxHate(int... rate) { /** * Verifica todos o valor de todos os subtópicos e caso o valor for 3 soma + 1, retornando o rating total do tópico. */ int rating = 0; for (int r : rate) { if(r == 3) { rating += r + 1; } else { rating += r; } } return rating; } }
gpl-3.0
incad/registrdigitalizace.harvest
src/main/java/cz/registrdigitalizace/harvest/db/ThumbnailDao.java
5827
/* * Copyright (C) 2011 Jan Pokorsky * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package cz.registrdigitalizace.harvest.db; import java.io.InputStream; import java.math.BigDecimal; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Iterator; import java.util.NoSuchElementException; /** * * @author Jan Pokorsky */ public final class ThumbnailDao { private HarvestTransaction source; public void setDataSource(HarvestTransaction source) { this.source = source; } public void insert(BigDecimal digiObjId, String mimeType, byte[] contents) throws DaoException { try { doInsert(digiObjId, mimeType, contents); } catch (SQLException ex) { throw new DaoException(ex); } } public void insert(BigDecimal digiObjId, String mimeType, InputStream contents, int length) throws DaoException { try { doInsert(digiObjId, mimeType, contents, length); } catch (SQLException ex) { throw new DaoException(ex); } } /** * Returns an iterator over DIGOBJEKTS whose THUMBNAILS should be downloaded. * The result contains <b>ALL</b> locations of DIGOBJEKT. */ public IterableResult<Thumbnail> findMissing() throws DaoException { try { return doFindMissing(); } catch (SQLException ex) { throw new DaoException(ex); } } /** * Deletes all THUMBNAILS whose DIGOBJEKTS were removed at the last harvest. */ public void deleteUnrelated() throws DaoException { try { doDeleteUnrelated(); } catch (SQLException ex) { throw new DaoException(ex); } } private void doDeleteUnrelated() throws SQLException { Connection conn = source.getConnection(); Statement stmt = conn.createStatement(); try { stmt.executeUpdate("delete from THUMBNAILS where DIGOBJEKTID not in (select ID from DIGOBJEKT)"); } finally { SQLQuery.tryClose(stmt); } } private IterableResult<Thumbnail> doFindMissing() throws SQLException { Connection conn = source.getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = null; try { rs = stmt.executeQuery(SQLQuery.getFindMissingThumbnails()); return new ThumbnailResult(rs, stmt); } finally { if (rs == null) { SQLQuery.tryClose(stmt); } } } private void doInsert(BigDecimal digiObjId, String mimeType, InputStream contents, int length) throws SQLException { Connection conn = source.getConnection(); PreparedStatement pstmt = conn.prepareStatement( "insert into THUMBNAILS (DIGOBJEKTID, MIME, CONTENTS) values (?, ?, ?)"); try { pstmt.setBigDecimal(1, digiObjId); pstmt.setString(2, mimeType); // pstmt.setBlob(3, contents, length); pstmt.setBinaryStream(3, contents, length); pstmt.executeUpdate(); } finally { SQLQuery.tryClose(pstmt); } } private void doInsert(BigDecimal digiObjId, String mimeType, byte[] contents) throws SQLException { Connection conn = source.getConnection(); PreparedStatement pstmt = conn.prepareStatement( "insert into THUMBNAILS (DIGOBJEKTID, MIME, CONTENTS) values (?, ?, ?)"); try { pstmt.setBigDecimal(1, digiObjId); pstmt.setString(2, mimeType); pstmt.setBytes(3, contents); pstmt.executeUpdate(); } finally { SQLQuery.tryClose(pstmt); } } public static final class Thumbnail { private BigDecimal digiObjId; private BigDecimal libraryId; private String uuid; public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public BigDecimal getDigiObjId() { return digiObjId; } public void setDigiObjId(BigDecimal digiObjId) { this.digiObjId = digiObjId; } public BigDecimal getLibraryId() { return libraryId; } public void setLibraryId(BigDecimal libraryId) { this.libraryId = libraryId; } } private static final class ThumbnailResult extends IterableResult<Thumbnail> { public ThumbnailResult(ResultSet rs, Statement stmt) { super(stmt, rs); } @Override protected Thumbnail fetchNext() throws DaoException { try { Thumbnail thumbnail = new Thumbnail(); thumbnail.setDigiObjId(rs.getBigDecimal("RDIGOBJEKTL")); thumbnail.setUuid(rs.getString("UUID")); thumbnail.setLibraryId(rs.getBigDecimal("LIBID")); return thumbnail; } catch (SQLException ex) { throw new DaoException(ex); } } } }
gpl-3.0
veithen/visualwas
connector/src/main/java/com/github/veithen/visualwas/x509/PromiscuousTrustManager.java
2528
/* * #%L * VisualWAS * %% * Copyright (C) 2013 - 2020 Andreas Veithen * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ package com.github.veithen.visualwas.x509; import java.net.Socket; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.SSLEngine; import javax.net.ssl.X509ExtendedTrustManager; /** Trust manager that accepts any certificate. */ public final class PromiscuousTrustManager extends X509ExtendedTrustManager { public static final PromiscuousTrustManager INSTANCE = new PromiscuousTrustManager(); private PromiscuousTrustManager() {} @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { throw new UnsupportedOperationException(); } @Override public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { throw new UnsupportedOperationException(); } @Override public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { throw new UnsupportedOperationException(); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { // Accept certificate } @Override public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { // Accept certificate } @Override public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { // Accept certificate } @Override public X509Certificate[] getAcceptedIssuers() { throw new UnsupportedOperationException(); } }
gpl-3.0
tomtomtom09/CampCraft
build/tmp/recompileMc/sources/net/minecraft/block/BlockRailBase.java
26936
package net.minecraft.block; import com.google.common.collect.Lists; import java.util.List; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumWorldBlockLayer; import net.minecraft.util.IStringSerializable; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public abstract class BlockRailBase extends Block { protected final boolean isPowered; public static boolean isRailBlock(World worldIn, BlockPos pos) { return isRailBlock(worldIn.getBlockState(pos)); } public static boolean isRailBlock(IBlockState state) { Block block = state.getBlock(); return block instanceof BlockRailBase; } protected BlockRailBase(boolean isPowered) { super(Material.circuits); this.isPowered = isPowered; this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.125F, 1.0F); this.setCreativeTab(CreativeTabs.tabTransport); } public AxisAlignedBB getCollisionBoundingBox(World worldIn, BlockPos pos, IBlockState state) { return null; } /** * Used to determine ambient occlusion and culling when rebuilding chunks for render */ public boolean isOpaqueCube() { return false; } /** * Ray traces through the blocks collision from start vector to end vector returning a ray trace hit. */ public MovingObjectPosition collisionRayTrace(World worldIn, BlockPos pos, Vec3 start, Vec3 end) { this.setBlockBoundsBasedOnState(worldIn, pos); return super.collisionRayTrace(worldIn, pos, start, end); } public void setBlockBoundsBasedOnState(IBlockAccess worldIn, BlockPos pos) { IBlockState iblockstate = worldIn.getBlockState(pos); BlockRailBase.EnumRailDirection blockrailbase$enumraildirection = iblockstate.getBlock() == this ? (BlockRailBase.EnumRailDirection)iblockstate.getValue(this.getShapeProperty()) : null; if (blockrailbase$enumraildirection != null && blockrailbase$enumraildirection.isAscending()) { this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.625F, 1.0F); } else { this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.125F, 1.0F); } } public boolean isFullCube() { return false; } public boolean canPlaceBlockAt(World worldIn, BlockPos pos) { return World.doesBlockHaveSolidTopSurface(worldIn, pos.down()); } public void onBlockAdded(World worldIn, BlockPos pos, IBlockState state) { if (!worldIn.isRemote) { state = this.func_176564_a(worldIn, pos, state, true); if (this.isPowered) { this.onNeighborBlockChange(worldIn, pos, state, this); } } } /** * Called when a neighboring block changes. */ public void onNeighborBlockChange(World worldIn, BlockPos pos, IBlockState state, Block neighborBlock) { if (!worldIn.isRemote) { BlockRailBase.EnumRailDirection blockrailbase$enumraildirection = (BlockRailBase.EnumRailDirection)state.getValue(this.getShapeProperty()); boolean flag = false; if (!World.doesBlockHaveSolidTopSurface(worldIn, pos.down())) { flag = true; } if (blockrailbase$enumraildirection == BlockRailBase.EnumRailDirection.ASCENDING_EAST && !World.doesBlockHaveSolidTopSurface(worldIn, pos.east())) { flag = true; } else if (blockrailbase$enumraildirection == BlockRailBase.EnumRailDirection.ASCENDING_WEST && !World.doesBlockHaveSolidTopSurface(worldIn, pos.west())) { flag = true; } else if (blockrailbase$enumraildirection == BlockRailBase.EnumRailDirection.ASCENDING_NORTH && !World.doesBlockHaveSolidTopSurface(worldIn, pos.north())) { flag = true; } else if (blockrailbase$enumraildirection == BlockRailBase.EnumRailDirection.ASCENDING_SOUTH && !World.doesBlockHaveSolidTopSurface(worldIn, pos.south())) { flag = true; } if (flag) { this.dropBlockAsItem(worldIn, pos, state, 0); worldIn.setBlockToAir(pos); } else { this.onNeighborChangedInternal(worldIn, pos, state, neighborBlock); } } } protected void onNeighborChangedInternal(World worldIn, BlockPos pos, IBlockState state, Block neighborBlock) { } protected IBlockState func_176564_a(World worldIn, BlockPos p_176564_2_, IBlockState p_176564_3_, boolean p_176564_4_) { return worldIn.isRemote ? p_176564_3_ : (new BlockRailBase.Rail(worldIn, p_176564_2_, p_176564_3_)).func_180364_a(worldIn.isBlockPowered(p_176564_2_), p_176564_4_).getBlockState(); } public int getMobilityFlag() { return 0; } @SideOnly(Side.CLIENT) public EnumWorldBlockLayer getBlockLayer() { return EnumWorldBlockLayer.CUTOUT; } public void breakBlock(World worldIn, BlockPos pos, IBlockState state) { super.breakBlock(worldIn, pos, state); if (((BlockRailBase.EnumRailDirection)state.getValue(this.getShapeProperty())).isAscending()) { worldIn.notifyNeighborsOfStateChange(pos.up(), this); } if (this.isPowered) { worldIn.notifyNeighborsOfStateChange(pos, this); worldIn.notifyNeighborsOfStateChange(pos.down(), this); } } public abstract IProperty<BlockRailBase.EnumRailDirection> getShapeProperty(); /* ======================================== FORGE START =====================================*/ /** * Return true if the rail can make corners. * Used by placement logic. * @param world The world. * @param pod Block's position in world * @return True if the rail can make corners. */ public boolean isFlexibleRail(IBlockAccess world, BlockPos pos) { return !this.isPowered; } /** * Returns true if the rail can make up and down slopes. * Used by placement logic. * @param world The world. * @param pod Block's position in world * @return True if the rail can make slopes. */ public boolean canMakeSlopes(IBlockAccess world, BlockPos pos) { return true; } /** * Returns the max speed of the rail at the specified position. * @param world The world. * @param cart The cart on the rail, may be null. * @param pod Block's position in world * @return The max speed of the current rail. */ public float getRailMaxSpeed(World world, net.minecraft.entity.item.EntityMinecart cart, BlockPos pos) { return 0.4f; } /** * This function is called by any minecart that passes over this rail. * It is called once per update tick that the minecart is on the rail. * @param world The world. * @param cart The cart on the rail. * @param pod Block's position in world */ public void onMinecartPass(World world, net.minecraft.entity.item.EntityMinecart cart, BlockPos pos) { } /** * Rotate the block. For vanilla blocks this rotates around the axis passed in (generally, it should be the "face" that was hit). * Note: for mod blocks, this is up to the block and modder to decide. It is not mandated that it be a rotation around the * face, but could be a rotation to orient *to* that face, or a visiting of possible rotations. * The method should return true if the rotation was successful though. * * @param world The world * @param pos Block position in world * @param axis The axis to rotate around * @return True if the rotation was successful, False if the rotation failed, or is not possible */ public boolean rotateBlock(World world, BlockPos pos, EnumFacing axis) { IBlockState state = world.getBlockState(pos); for (IProperty prop : (java.util.Set<IProperty>)state.getProperties().keySet()) { if (prop.getName().equals("shape")) { world.setBlockState(pos, state.cycleProperty(prop)); return true; } } return false; } /* ======================================== FORGE END =====================================*/ public static enum EnumRailDirection implements IStringSerializable { NORTH_SOUTH(0, "north_south"), EAST_WEST(1, "east_west"), ASCENDING_EAST(2, "ascending_east"), ASCENDING_WEST(3, "ascending_west"), ASCENDING_NORTH(4, "ascending_north"), ASCENDING_SOUTH(5, "ascending_south"), SOUTH_EAST(6, "south_east"), SOUTH_WEST(7, "south_west"), NORTH_WEST(8, "north_west"), NORTH_EAST(9, "north_east"); private static final BlockRailBase.EnumRailDirection[] META_LOOKUP = new BlockRailBase.EnumRailDirection[values().length]; private final int meta; private final String name; private EnumRailDirection(int meta, String name) { this.meta = meta; this.name = name; } public int getMetadata() { return this.meta; } public String toString() { return this.name; } public boolean isAscending() { return this == ASCENDING_NORTH || this == ASCENDING_EAST || this == ASCENDING_SOUTH || this == ASCENDING_WEST; } public static BlockRailBase.EnumRailDirection byMetadata(int meta) { if (meta < 0 || meta >= META_LOOKUP.length) { meta = 0; } return META_LOOKUP[meta]; } public String getName() { return this.name; } static { for (BlockRailBase.EnumRailDirection blockrailbase$enumraildirection : values()) { META_LOOKUP[blockrailbase$enumraildirection.getMetadata()] = blockrailbase$enumraildirection; } } } public class Rail { private final World world; private final BlockPos pos; private final BlockRailBase block; private IBlockState state; private final boolean isPowered; private final List<BlockPos> field_150657_g = Lists.<BlockPos>newArrayList(); private final boolean canMakeSlopes; public Rail(World worldIn, BlockPos pos, IBlockState state) { this.world = worldIn; this.pos = pos; this.state = state; this.block = (BlockRailBase)state.getBlock(); BlockRailBase.EnumRailDirection blockrailbase$enumraildirection = (BlockRailBase.EnumRailDirection)state.getValue(BlockRailBase.this.getShapeProperty()); this.isPowered = !this.block.isFlexibleRail(worldIn, pos); canMakeSlopes = this.block.canMakeSlopes(worldIn, pos); this.func_180360_a(blockrailbase$enumraildirection); } private void func_180360_a(BlockRailBase.EnumRailDirection p_180360_1_) { this.field_150657_g.clear(); switch (p_180360_1_) { case NORTH_SOUTH: this.field_150657_g.add(this.pos.north()); this.field_150657_g.add(this.pos.south()); break; case EAST_WEST: this.field_150657_g.add(this.pos.west()); this.field_150657_g.add(this.pos.east()); break; case ASCENDING_EAST: this.field_150657_g.add(this.pos.west()); this.field_150657_g.add(this.pos.east().up()); break; case ASCENDING_WEST: this.field_150657_g.add(this.pos.west().up()); this.field_150657_g.add(this.pos.east()); break; case ASCENDING_NORTH: this.field_150657_g.add(this.pos.north().up()); this.field_150657_g.add(this.pos.south()); break; case ASCENDING_SOUTH: this.field_150657_g.add(this.pos.north()); this.field_150657_g.add(this.pos.south().up()); break; case SOUTH_EAST: this.field_150657_g.add(this.pos.east()); this.field_150657_g.add(this.pos.south()); break; case SOUTH_WEST: this.field_150657_g.add(this.pos.west()); this.field_150657_g.add(this.pos.south()); break; case NORTH_WEST: this.field_150657_g.add(this.pos.west()); this.field_150657_g.add(this.pos.north()); break; case NORTH_EAST: this.field_150657_g.add(this.pos.east()); this.field_150657_g.add(this.pos.north()); } } private void func_150651_b() { for (int i = 0; i < this.field_150657_g.size(); ++i) { BlockRailBase.Rail blockrailbase$rail = this.findRailAt((BlockPos)this.field_150657_g.get(i)); if (blockrailbase$rail != null && blockrailbase$rail.func_150653_a(this)) { this.field_150657_g.set(i, blockrailbase$rail.pos); } else { this.field_150657_g.remove(i--); } } } private boolean hasRailAt(BlockPos pos) { return BlockRailBase.isRailBlock(this.world, pos) || BlockRailBase.isRailBlock(this.world, pos.up()) || BlockRailBase.isRailBlock(this.world, pos.down()); } private BlockRailBase.Rail findRailAt(BlockPos pos) { IBlockState iblockstate = this.world.getBlockState(pos); if (BlockRailBase.isRailBlock(iblockstate)) { return BlockRailBase.this.new Rail(this.world, pos, iblockstate); } else { BlockPos lvt_2_1_ = pos.up(); iblockstate = this.world.getBlockState(lvt_2_1_); if (BlockRailBase.isRailBlock(iblockstate)) { return BlockRailBase.this.new Rail(this.world, lvt_2_1_, iblockstate); } else { lvt_2_1_ = pos.down(); iblockstate = this.world.getBlockState(lvt_2_1_); return BlockRailBase.isRailBlock(iblockstate) ? BlockRailBase.this.new Rail(this.world, lvt_2_1_, iblockstate) : null; } } } private boolean func_150653_a(BlockRailBase.Rail p_150653_1_) { return this.func_180363_c(p_150653_1_.pos); } private boolean func_180363_c(BlockPos p_180363_1_) { for (int i = 0; i < this.field_150657_g.size(); ++i) { BlockPos blockpos = (BlockPos)this.field_150657_g.get(i); if (blockpos.getX() == p_180363_1_.getX() && blockpos.getZ() == p_180363_1_.getZ()) { return true; } } return false; } /** * Counts the number of rails adjacent to this rail. */ protected int countAdjacentRails() { int i = 0; for (EnumFacing enumfacing : EnumFacing.Plane.HORIZONTAL) { if (this.hasRailAt(this.pos.offset(enumfacing))) { ++i; } } return i; } private boolean func_150649_b(BlockRailBase.Rail rail) { return this.func_150653_a(rail) || this.field_150657_g.size() != 2; } private void func_150645_c(BlockRailBase.Rail p_150645_1_) { this.field_150657_g.add(p_150645_1_.pos); BlockPos blockpos = this.pos.north(); BlockPos blockpos1 = this.pos.south(); BlockPos blockpos2 = this.pos.west(); BlockPos blockpos3 = this.pos.east(); boolean flag = this.func_180363_c(blockpos); boolean flag1 = this.func_180363_c(blockpos1); boolean flag2 = this.func_180363_c(blockpos2); boolean flag3 = this.func_180363_c(blockpos3); BlockRailBase.EnumRailDirection blockrailbase$enumraildirection = null; if (flag || flag1) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.NORTH_SOUTH; } if (flag2 || flag3) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.EAST_WEST; } if (!this.isPowered) { if (flag1 && flag3 && !flag && !flag2) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.SOUTH_EAST; } if (flag1 && flag2 && !flag && !flag3) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.SOUTH_WEST; } if (flag && flag2 && !flag1 && !flag3) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.NORTH_WEST; } if (flag && flag3 && !flag1 && !flag2) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.NORTH_EAST; } } if (blockrailbase$enumraildirection == BlockRailBase.EnumRailDirection.NORTH_SOUTH && canMakeSlopes) { if (BlockRailBase.isRailBlock(this.world, blockpos.up())) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.ASCENDING_NORTH; } if (BlockRailBase.isRailBlock(this.world, blockpos1.up())) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.ASCENDING_SOUTH; } } if (blockrailbase$enumraildirection == BlockRailBase.EnumRailDirection.EAST_WEST && canMakeSlopes) { if (BlockRailBase.isRailBlock(this.world, blockpos3.up())) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.ASCENDING_EAST; } if (BlockRailBase.isRailBlock(this.world, blockpos2.up())) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.ASCENDING_WEST; } } if (blockrailbase$enumraildirection == null) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.NORTH_SOUTH; } this.state = this.state.withProperty(this.block.getShapeProperty(), blockrailbase$enumraildirection); this.world.setBlockState(this.pos, this.state, 3); } private boolean func_180361_d(BlockPos p_180361_1_) { BlockRailBase.Rail blockrailbase$rail = this.findRailAt(p_180361_1_); if (blockrailbase$rail == null) { return false; } else { blockrailbase$rail.func_150651_b(); return blockrailbase$rail.func_150649_b(this); } } public BlockRailBase.Rail func_180364_a(boolean p_180364_1_, boolean p_180364_2_) { BlockPos blockpos = this.pos.north(); BlockPos blockpos1 = this.pos.south(); BlockPos blockpos2 = this.pos.west(); BlockPos blockpos3 = this.pos.east(); boolean flag = this.func_180361_d(blockpos); boolean flag1 = this.func_180361_d(blockpos1); boolean flag2 = this.func_180361_d(blockpos2); boolean flag3 = this.func_180361_d(blockpos3); BlockRailBase.EnumRailDirection blockrailbase$enumraildirection = null; if ((flag || flag1) && !flag2 && !flag3) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.NORTH_SOUTH; } if ((flag2 || flag3) && !flag && !flag1) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.EAST_WEST; } if (!this.isPowered) { if (flag1 && flag3 && !flag && !flag2) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.SOUTH_EAST; } if (flag1 && flag2 && !flag && !flag3) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.SOUTH_WEST; } if (flag && flag2 && !flag1 && !flag3) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.NORTH_WEST; } if (flag && flag3 && !flag1 && !flag2) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.NORTH_EAST; } } if (blockrailbase$enumraildirection == null) { if (flag || flag1) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.NORTH_SOUTH; } if (flag2 || flag3) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.EAST_WEST; } if (!this.isPowered) { if (p_180364_1_) { if (flag1 && flag3) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.SOUTH_EAST; } if (flag2 && flag1) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.SOUTH_WEST; } if (flag3 && flag) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.NORTH_EAST; } if (flag && flag2) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.NORTH_WEST; } } else { if (flag && flag2) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.NORTH_WEST; } if (flag3 && flag) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.NORTH_EAST; } if (flag2 && flag1) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.SOUTH_WEST; } if (flag1 && flag3) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.SOUTH_EAST; } } } } if (blockrailbase$enumraildirection == BlockRailBase.EnumRailDirection.NORTH_SOUTH && canMakeSlopes) { if (BlockRailBase.isRailBlock(this.world, blockpos.up())) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.ASCENDING_NORTH; } if (BlockRailBase.isRailBlock(this.world, blockpos1.up())) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.ASCENDING_SOUTH; } } if (blockrailbase$enumraildirection == BlockRailBase.EnumRailDirection.EAST_WEST && canMakeSlopes) { if (BlockRailBase.isRailBlock(this.world, blockpos3.up())) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.ASCENDING_EAST; } if (BlockRailBase.isRailBlock(this.world, blockpos2.up())) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.ASCENDING_WEST; } } if (blockrailbase$enumraildirection == null) { blockrailbase$enumraildirection = BlockRailBase.EnumRailDirection.NORTH_SOUTH; } this.func_180360_a(blockrailbase$enumraildirection); this.state = this.state.withProperty(this.block.getShapeProperty(), blockrailbase$enumraildirection); if (p_180364_2_ || this.world.getBlockState(this.pos) != this.state) { this.world.setBlockState(this.pos, this.state, 3); for (int i = 0; i < this.field_150657_g.size(); ++i) { BlockRailBase.Rail blockrailbase$rail = this.findRailAt((BlockPos)this.field_150657_g.get(i)); if (blockrailbase$rail != null) { blockrailbase$rail.func_150651_b(); if (blockrailbase$rail.func_150649_b(this)) { blockrailbase$rail.func_150645_c(this); } } } } return this; } public IBlockState getBlockState() { return this.state; } } }
gpl-3.0
maplesond/spectre
core/src/main/java/uk/ac/uea/cmp/spectre/core/io/newick/NewickReader.java
2301
/* * Suite of PhylogEnetiC Tools for Reticulate Evolution (SPECTRE) * Copyright (C) 2017 UEA School of Computing Sciences * * This program is free software: you can redistribute it and/or modify it under the term of the GNU General Public * License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ package uk.ac.uea.cmp.spectre.core.io.newick; import uk.ac.uea.cmp.spectre.core.ds.tree.newick.NewickTree; import uk.ac.uea.cmp.spectre.core.io.AbstractSpectreReader; import uk.ac.uea.cmp.spectre.core.io.SpectreDataType; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Can read files that contain newick trees, one per line. */ public class NewickReader extends AbstractSpectreReader { @Override public List<NewickTree> readTrees(File input, double weight) throws IOException { List<NewickTree> trees = new ArrayList<>(); BufferedReader in = new BufferedReader(new FileReader(input)); String line = in.readLine(); while ((line = in.readLine()) != null) { // Trim the line of whitespace line = line.trim(); // If there is a blank line, go to next line (one tree per line) if (!line.isEmpty()) { trees.add(new NewickTree(line)); } } in.close(); return trees; } @Override public String[] commonFileExtensions() { return new String[]{"newick", "new", "tre"}; } @Override public String getIdentifier() { return "NEWICK"; } @Override public boolean acceptsDataType(SpectreDataType spectreDataType) { if (spectreDataType == SpectreDataType.TREE) return true; return false; } }
gpl-3.0
angecab10/travelport-uapi-tutorial
src/com/travelport/schema/common_v29_0/TypeCommissionType.java
1470
package com.travelport.schema.common_v29_0; import javax.annotation.Generated; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for typeCommissionType. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="typeCommissionType"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="Flat"/> * &lt;enumeration value="PercentBase"/> * &lt;enumeration value="PercentTotal"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "typeCommissionType") @XmlEnum @Generated(value = "com.sun.tools.xjc.Driver", date = "2014-09-19T03:10:02-06:00", comment = "JAXB RI v2.2.6") public enum TypeCommissionType { @XmlEnumValue("Flat") FLAT("Flat"), @XmlEnumValue("PercentBase") PERCENT_BASE("PercentBase"), @XmlEnumValue("PercentTotal") PERCENT_TOTAL("PercentTotal"); private final String value; TypeCommissionType(String v) { value = v; } public String value() { return value; } public static TypeCommissionType fromValue(String v) { for (TypeCommissionType c: TypeCommissionType.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
gpl-3.0
code-spartans-reply/qualification-round
src/main/java/com/reply/challenges/hashcode2017/codespartans/qualificationround/utils/OutputRenderer.java
2158
package com.reply.challenges.hashcode2017.codespartans.qualificationround.utils; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Path; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.google.common.io.Files; import com.reply.challenges.hashcode2017.codespartans.qualificationround.model.problem.Cache; import com.reply.challenges.hashcode2017.codespartans.qualificationround.model.problem.ProblemParameters; import com.reply.challenges.hashcode2017.codespartans.qualificationround.model.problem.Solution; import com.reply.challenges.hashcode2017.codespartans.qualificationround.model.problem.Video; import lombok.experimental.UtilityClass; import lombok.extern.slf4j.Slf4j; @UtilityClass @Slf4j public class OutputRenderer { public static void renderOutput(Solution result, ProblemParameters parameters, Path outputFile) throws IOException { log.info("Start writing solution to output file {}", outputFile); // Ensure target directory exists: Files.createParentDirs(outputFile.toFile()); try (final PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(outputFile.toFile())))) { List<Cache> cleanedCacheList = cleanEmptyCaches(result.getCaches()); writer.println(cleanedCacheList.size()); for(Cache cache : cleanedCacheList) { writer.print(cache.getId() + " "); List<Video> cachedVideos = cache.getCachedVideos(); for (Iterator<Video> iterator = cachedVideos.iterator(); iterator.hasNext();) { Video video = (Video) iterator.next(); writer.print(video.getId()); if (iterator.hasNext()) { writer.print(" "); } } writer.println(); } // TODO writer.print(result.data) writer.flush(); } } private static List<Cache> cleanEmptyCaches(Cache[] caches) { List<Cache> cleanedCacheList = new ArrayList<>(); if (caches != null) { for (int i = 0; i < caches.length; i++) { if (!caches[i].getCachedVideos().isEmpty()) { cleanedCacheList.add(caches[i]); } } } return cleanedCacheList; } }
gpl-3.0
boy0001/PlotSquared
PlotSquared/src/com/intellectualcrafters/plot/PlotMain.java
41054
/* * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * and/or monetize any of our intellectual property. IntellectualCrafters is not * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * * >> File = Main.java >> Generated by: Citymonstret at 2014-08-09 01:43 */ package com.intellectualcrafters.plot; import ca.mera.CameraAPI; import com.intellectualcrafters.plot.Logger.LogLevel; import com.intellectualcrafters.plot.Settings.Web; import com.intellectualcrafters.plot.commands.Camera; import com.intellectualcrafters.plot.commands.MainCommand; import com.intellectualcrafters.plot.database.DBFunc; import com.intellectualcrafters.plot.database.MySQL; import com.intellectualcrafters.plot.database.PlotMeConverter; import com.intellectualcrafters.plot.database.SQLite; import com.intellectualcrafters.plot.events.PlayerTeleportToPlotEvent; import com.intellectualcrafters.plot.events.PlotDeleteEvent; import com.intellectualcrafters.plot.generator.DefaultPlotManager; import com.intellectualcrafters.plot.generator.DefaultPlotWorld; import com.intellectualcrafters.plot.generator.WorldGenerator; import com.intellectualcrafters.plot.listeners.PlayerEvents; import com.intellectualcrafters.plot.listeners.WorldEditListener; import com.intellectualcrafters.plot.listeners.WorldGuardListener; import com.intellectualcrafters.plot.uuid.PlotUUIDSaver; import com.intellectualcrafters.plot.uuid.UUIDSaver; import com.sk89q.worldedit.bukkit.WorldEditPlugin; import com.sk89q.worldguard.bukkit.WorldGuardPlugin; import me.confuser.barapi.BarAPI; import net.milkbowl.vault.economy.Economy; import org.bukkit.*; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Tameable; import org.bukkit.generator.ChunkGenerator; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; /** * @awesome @author Citymonstret, Empire92 PlotMain class. */ public class PlotMain extends JavaPlugin { private static UUIDSaver uuidSaver; /** * settings.properties */ public static File configFile; public static YamlConfiguration config; private static int config_ver = 1; /** * storage.properties */ public static File storageFile; public static YamlConfiguration storage; public static int storage_ver = 1; /** * translations.properties */ public static File translationsFile; public static YamlConfiguration translations; public static int translations_ver = 1; /** * MySQL Object */ private static MySQL mySQL; /** * MySQL Connection */ public static Connection connection; /** * WorldEdit object */ public static WorldEditPlugin worldEdit = null; /** * BarAPI object */ public static BarAPI barAPI = null; /** * CameraAPI object */ public static CameraAPI cameraAPI; public static WorldGuardPlugin worldGuard = null; public static WorldGuardListener worldGuardListener = null; public static Economy economy; public static boolean useEconomy; /** * !!WorldGeneration!! */ @Override public ChunkGenerator getDefaultWorldGenerator(String worldname, String id) { return new WorldGenerator(worldname); } @SuppressWarnings("deprecation") public static void checkForExpiredPlots() { final JavaPlugin plugin = PlotMain.getMain(); Bukkit.getScheduler().scheduleAsyncRepeatingTask(plugin, new Runnable() { @Override public void run() { checkExpired(plugin, true); } }, 0l, 12 * 60 * 60 * 20l); } /** * Check a range of permissions e.g. 'plots.plot.<0-100>'<br> * Returns highest integer in range. * * @param player * @param stub * @param range * @return */ public static int hasPermissionRange(Player player, String stub, int range) { if (player==null || player.isOp()) { return range; } if (player.hasPermission(stub + ".*")) { return range; } for (int i = range; i > 0; i--) { if (player.hasPermission(stub + "." + i)) { return i; } } return 0; } /** * Check a player for a permission<br> * - Op has all permissions <br> * - checks for '*' nodes * * @param player * @param perms * @return */ public static boolean hasPermissions(Player player, String[] perms) { // Assumes null player is console. if (player==null || player.isOp()) { return true; } for (String perm : perms) { boolean hasperm = false; if (player.hasPermission(perm)) { hasperm = true; } else { String[] nodes = perm.split("\\."); StringBuilder n = new StringBuilder(); for (int i = 0; i < (nodes.length - 1); i++) { n.append(nodes[i] + "."); if (player.hasPermission(n + "*")) { hasperm = true; break; } } } if (!hasperm) { return false; } } return true; } public static void setUUIDSaver(UUIDSaver saver) { uuidSaver = saver; } public static UUIDSaver getUUIDSaver() { return uuidSaver; } /** * Check a player for a permission<br> * - Op has all permissions <br> * - checks for '*' nodes * * @param player * @param perm * @return */ public static boolean hasPermission(Player player, String perm) { if (player==null || player.isOp()) { return true; } if (player.hasPermission(perm)) { return true; } String[] nodes = perm.split("\\."); StringBuilder n = new StringBuilder(); for (int i = 0; i < (nodes.length - 1); i++) { n.append(nodes[i] + "."); if (player.hasPermission(n + "*")) { return true; } } return false; } /** * List of all plots * DO NOT USE EXCEPT FOR DATABASE PURPOSES */ private static HashMap<String, HashMap<PlotId, Plot>> plots; /** * All loaded plot worlds */ private static HashMap<String, PlotWorld> worlds = new HashMap<String, PlotWorld>(); private static HashMap<String, PlotManager> managers = new HashMap<String, PlotManager>(); /** * Get all plots * * @return HashMap containing the plot ID and the plot object. */ public static Set<Plot> getPlots() { ArrayList<Plot> myplots = new ArrayList<Plot>(); for (HashMap<PlotId, Plot> world : plots.values()) { myplots.addAll(world.values()); } return new HashSet<Plot>(myplots); } /** * @param player * @return */ public static Set<Plot> getPlots(Player player) { UUID uuid = player.getUniqueId(); ArrayList<Plot> myplots = new ArrayList<Plot>(); for (HashMap<PlotId, Plot> world : plots.values()) { for (Plot plot : world.values()) { if (plot.hasOwner()) { if (plot.getOwner().equals(uuid)) { myplots.add(plot); } } } } return new HashSet<Plot>(myplots); } /** * @param world * @param player * @return */ public static Set<Plot> getPlots(World world, Player player) { UUID uuid = player.getUniqueId(); ArrayList<Plot> myplots = new ArrayList<Plot>(); for (Plot plot : getPlots(world).values()) { if (plot.hasOwner()) { if (plot.getOwner().equals(uuid)) { myplots.add(plot); } } } return new HashSet<Plot>(myplots); } public static HashMap<PlotId, Plot> getPlots(String world) { if (plots.containsKey(world)) { return plots.get(world); } return new HashMap<PlotId, Plot>(); } /** * @param world * @return */ public static HashMap<PlotId, Plot> getPlots(World world) { if (plots.containsKey(world.getName())) { return plots.get(world.getName()); } return new HashMap<PlotId, Plot>(); } /** * get all plot worlds */ public static String[] getPlotWorlds() { return (worlds.keySet().toArray(new String[0])); } /** * @return */ public static String[] getPlotWorldsString() { return plots.keySet().toArray(new String[0]); } /** * @param world * @return */ public static boolean isPlotWorld(World world) { return (worlds.containsKey(world.getName())); } /** * @param world * @return */ public static boolean isPlotWorld(String world) { return (worlds.containsKey(world)); } /** * @param world * @return */ public static PlotManager getPlotManager(World world) { if (managers.containsKey(world.getName())) { return managers.get(world.getName()); } return null; } /** * @param world * @return */ public static PlotManager getPlotManager(String world) { if (managers.containsKey(world)) { return managers.get(world); } return null; } /** * @param world * @return */ public static PlotWorld getWorldSettings(World world) { if (worlds.containsKey(world.getName())) { return worlds.get(world.getName()); } return null; } /** * @param world * @return */ public static PlotWorld getWorldSettings(String world) { if (worlds.containsKey(world)) { return worlds.get(world); } return null; } /** * @param world * @return set containing the plots for a world */ public static Plot[] getWorldPlots(World world) { return (plots.get(world.getName()).values().toArray(new Plot[0])); } public static boolean removePlot(String world, PlotId id, boolean callEvent) { if (callEvent) { PlotDeleteEvent event = new PlotDeleteEvent(world, id); Bukkit.getServer().getPluginManager().callEvent(event); if (event.isCancelled()) { event.setCancelled(true); return false; } } plots.get(world).remove(id); return true; } /** * Replace the plot object with an updated version * * @param plot * plot object */ public static void updatePlot(Plot plot) { String world = plot.world; if (!plots.containsKey(world)) { plots.put(world, new HashMap<PlotId, Plot>()); } plot.hasChanged = true; plots.get(world).put(plot.id, plot); } /** * TODO: <b>Implement better system The whole point of this system is to * recycle old plots</b> <br> * So why not just allow users to claim old plots, and try to hide the fact * that the are owned. <br> * <br> * Reduce amount of expired plots: <br> * - On /plot <br> * auto<br> * - allow claiming of old plot, clear it so the user doesn't know<br> * - On /plot info,<br> * - show that the plot is expired and allowed to be claimed Have the task * run less often:<br> * - Run the task when there are very little, or no players online (great * for small servers)<br> * - Run the task at startup (also only useful for small servers)<br> * Also, in terms of faster code:<br> * - Have an array of plots, sorted by expiry time.<br> * - Add new plots to the end.<br> * - The task then only needs to go through the first few plots * * @param plugin * Plugin * @param async * Call async? */ private static void checkExpired(JavaPlugin plugin, boolean async) { if (async) { Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { @Override public void run() { for (String world : getPlotWorldsString()) { if (plots.containsKey(world)) { ArrayList<Plot> toDeletePlot = new ArrayList<Plot>(); for (Plot plot : plots.get(world).values()) { if (plot.owner == null) { continue; } long lastPlayed = getLastPlayed(plot.owner); if (lastPlayed == 0) { continue; } long compared = System.currentTimeMillis() - lastPlayed; if (TimeUnit.MILLISECONDS.toDays(compared) >= Settings.AUTO_CLEAR_DAYS) { PlotDeleteEvent event = new PlotDeleteEvent(world, plot.id); Bukkit.getServer().getPluginManager().callEvent(event); if (event.isCancelled()) { event.setCancelled(true); } else { toDeletePlot.add(plot); } } } for (Plot plot: toDeletePlot) { getPlotManager(world).clearPlot(null, plot); DBFunc.delete(world, plot); } } } } }); } else { for (String world : getPlotWorldsString()) { if (PlotMain.plots.containsKey(world)) { for (Plot plot : PlotMain.plots.get(world).values()) { if (PlayerFunctions.hasExpired(plot)) { PlotDeleteEvent event = new PlotDeleteEvent(world, plot.id); Bukkit.getServer().getPluginManager().callEvent(event); if (event.isCancelled()) { event.setCancelled(true); } else { DBFunc.delete(world, plot); } } } } } } } private void setupLogger() { File log = new File(getMain().getDataFolder() + File.separator + "logs" + File.separator + "plots.log"); if (!log.exists()) { try { if (!new File(getMain().getDataFolder() + File.separator + "logs").mkdirs()) { sendConsoleSenderMessage(C.PREFIX.s() + "&cFailed to create logs folder. Do it manually."); } if (log.createNewFile()) { FileWriter writer = new FileWriter(log); writer.write("Created at: " + new Date().toString() + "\n\n\n"); writer.close(); } } catch (IOException e) { e.printStackTrace(); } } Logger.setup(log); Logger.add(LogLevel.GENERAL, "Logger enabled"); } private static double getJavaVersion() { return Double.parseDouble(System.getProperty("java.specification.version")); } /** * On Load. */ @Override @SuppressWarnings("deprecation") public void onEnable() { // Init the logger setupLogger(); // Check for outdated java version. if (getJavaVersion() < 1.7) { sendConsoleSenderMessage(C.PREFIX.s() + "&cYour java version is outdated. Please update to at least 1.7."); // Didn't know of any other link :D sendConsoleSenderMessage(C.PREFIX.s() + "&cURL: &6https://java.com/en/download/index.jsp"); Bukkit.getPluginManager().disablePlugin(this); return; } // Setup configurations configs(); // Setup metrics if (Settings.METRICS) { try { Metrics metrics = new Metrics(this); metrics.start(); sendConsoleSenderMessage(C.PREFIX.s() + "&6Metrics enabled."); } catch (Exception e) { sendConsoleSenderMessage(C.PREFIX.s() + "&cFailed to load up metrics."); } } // Kill mobs on roads? if (Settings.KILL_ROAD_MOBS) { killAllEntities(); } // Enabled<3 if (C.ENABLED.s().length() > 0) { Broadcast(C.ENABLED); } // Use mysql? if (Settings.DB.USE_MYSQL) { try { mySQL = new MySQL(this, Settings.DB.HOST_NAME, Settings.DB.PORT, Settings.DB.DATABASE, Settings.DB.USER, Settings.DB.PASSWORD); connection = mySQL.openConnection(); { DatabaseMetaData meta = connection.getMetaData(); ResultSet res = meta.getTables(null, null, "plot", null); if (!res.next()) { DBFunc.createTables("mysql", true); } else { res = meta.getTables(null, null, "plot_trusted", null); if (!res.next()) { DBFunc.createTables("mysql", false); } else { res = meta.getTables(null, null, "plot_ratings", null); if (!res.next()) { DBFunc.createTables("mysql", false); } } } } } catch (ClassNotFoundException | SQLException e) { Logger.add(LogLevel.DANGER, "MySQL connection failed."); sendConsoleSenderMessage("&c[Plots] MySQL is not setup correctly. The plugin will disable itself."); if (config==null || config.getBoolean("debug")) { sendConsoleSenderMessage("&d==== Here is an ugly stacktrace if you are interested in those things ===="); e.printStackTrace(); sendConsoleSenderMessage("&d==== End of stacktrace ===="); sendConsoleSenderMessage("&6Please go to the PlotSquared 'storage.yml' and configure MySQL correctly."); } Bukkit.getPluginManager().disablePlugin(this); return; } plots = DBFunc.getPlots(); } // TODO: Implement mongo else if (Settings.DB.USE_MONGO) { sendConsoleSenderMessage(C.PREFIX.s() + "MongoDB is not yet implemented"); } // Use Sqlite :D<3 else if (Settings.DB.USE_SQLITE) { try { connection = new SQLite(this, Settings.DB.SQLITE_DB + ".db").openConnection(); { DatabaseMetaData meta = connection.getMetaData(); ResultSet res = meta.getTables(null, null, "plot", null); if (!res.next()) { DBFunc.createTables("sqlite", true); } else { res = meta.getTables(null, null, "plot_trusted", null); if (!res.next()) { DBFunc.createTables("sqlite", false); } else { res = meta.getTables(null, null, "plot_ratings", null); if (!res.next()) { DBFunc.createTables("sqlite", false); } } } } } catch (ClassNotFoundException | SQLException e) { Logger.add(LogLevel.DANGER, "SQLite connection failed"); sendConsoleSenderMessage(C.PREFIX.s() + "&cFailed to open SQLite connection. The plugin will disable itself."); sendConsoleSenderMessage("&9==== Here is an ugly stacktrace, if you are interested in those things ==="); e.printStackTrace(); Bukkit.getPluginManager().disablePlugin(this); return; } plots = DBFunc.getPlots(); } else { Logger.add(LogLevel.DANGER, "No storage type is set."); sendConsoleSenderMessage(C.PREFIX + "&cNo storage type is set!"); getServer().getPluginManager().disablePlugin(this); return; } if (getServer().getPluginManager().getPlugin("PlotMe") != null) { try { new PlotMeConverter(this).runAsync(); } catch (Exception e) { e.printStackTrace(); } } getCommand("plots").setExecutor(new MainCommand()); getCommand("plots").setAliases(new ArrayList<String>() { { add("p"); add("ps"); add("plotme"); add("plot"); } }); getServer().getPluginManager().registerEvents(new PlayerEvents(), this); defaultFlags(); if (getServer().getPluginManager().getPlugin("CameraAPI") != null) { cameraAPI = CameraAPI.getInstance(); Camera camera = new Camera(); MainCommand.subCommands.add(camera); getServer().getPluginManager().registerEvents(camera, this); } if (getServer().getPluginManager().getPlugin("BarAPI") != null) { barAPI = (BarAPI) getServer().getPluginManager().getPlugin("BarAPI"); } if (getServer().getPluginManager().getPlugin("WorldEdit") != null) { worldEdit = (WorldEditPlugin) getServer().getPluginManager().getPlugin("WorldEdit"); getServer().getPluginManager().registerEvents(new WorldEditListener(), this); } if (Settings.WORLDGUARD) { if (getServer().getPluginManager().getPlugin("WorldGuard") != null) { worldGuard = (WorldGuardPlugin) getServer().getPluginManager().getPlugin("WorldGuard"); worldGuardListener = new WorldGuardListener(this); getServer().getPluginManager().registerEvents(worldGuardListener, this); } } if (Settings.AUTO_CLEAR) { checkExpired(PlotMain.getMain(), true); checkForExpiredPlots(); } if (getServer().getPluginManager().getPlugin("Vault") != null) { RegisteredServiceProvider<Economy> economyProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); if (economyProvider != null) { economy = economyProvider.getProvider(); } useEconomy = (economy != null); } getServer().getScheduler().scheduleSyncRepeatingTask(this, new Lag(), 100L, 1L); if (Web.ENABLED) { sendConsoleSenderMessage(C.PREFIX.s() + "Web Is not implemented yet. Please bear with us."); } try { new SetBlockFast(); PlotHelper.canSetFast = true; } catch (Exception e) { PlotHelper.canSetFast = false; } //Setup version + downloads, will not be updated... maybe setup runnable? TODO Let jesse decide... com.intellectualcrafters.plot.commands.plugin.setup(this); setUUIDSaver(new PlotUUIDSaver()); getUUIDSaver().globalPopulate(); //UUIDHandler.startFetch(this); } /** * Get MySQL Connection * * @return connection MySQL Connection. */ @SuppressWarnings("unused") public static Connection getConnection() { return connection; } /** .. */ // Old Stuff /* * private static boolean checkForUpdate() throws IOException { URL call = * new URL(Settings.Update.VERSION_URL); InputStream stream = * call.openStream(); BufferedReader reader = new BufferedReader(new * InputStreamReader(stream)); String latest = reader.readLine(); * reader.close(); return * !getPlotMain().getDescription().getVersion().equalsIgnoreCase(latest); } * private static String getNextUpdateString() throws IOException { URL call * = new URL(Settings.Update.VERSION_URL); InputStream stream = * call.openStream(); BufferedReader reader = new BufferedReader(new * InputStreamReader(stream)); return reader.readLine(); } private static * void update() throws IOException { sendConsoleSenderMessage(C.PREFIX.s() * + "&c&lThere is an update! New Update: &6&l" + getNextUpdateString() + * "&c&l, Current Update: &6&l" + * getPlotMain().getDescription().getVersion()); } */ /** * Send a message to the console. * * @param string * message */ public static void sendConsoleSenderMessage(String string) { if (getMain().getServer().getConsoleSender() == null) { System.out.println(ChatColor.stripColor(ConsoleColors.fromString(string))); } else { getMain().getServer().getConsoleSender().sendMessage(ChatColor.translateAlternateColorCodes('&', string)); } } public static boolean teleportPlayer(Player player, Location from, Plot plot) { PlayerTeleportToPlotEvent event = new PlayerTeleportToPlotEvent(player, from, plot); Bukkit.getServer().getPluginManager().callEvent(event); if (!event.isCancelled()) { Location location = PlotHelper.getPlotHome(Bukkit.getWorld(plot.world), plot); if ((location.getBlockX() >= 29999999) || (location.getBlockX() <= -29999999) || (location.getBlockZ() >= 299999999) || (location.getBlockZ() <= -29999999)) { event.setCancelled(true); return false; } player.teleport(location); PlayerFunctions.sendMessage(player, C.TELEPORTED_TO_PLOT); } return event.isCancelled(); } /** * Send a message to the console * * @param c * message */ @SuppressWarnings("unused") public static void sendConsoleSenderMessage(C c) { sendConsoleSenderMessage(c.s()); } /** * Broadcast publicly * * @param c * message */ public static void Broadcast(C c) { Bukkit.broadcastMessage(ChatColor.translateAlternateColorCodes('&', C.PREFIX.s() + c.s())); } /** * Returns the main class. * * @return (this class) */ public static PlotMain getMain() { return JavaPlugin.getPlugin(PlotMain.class); } /** * Broadcast a message to all admins * * @param c * message */ public static void BroadcastWithPerms(C c) { for (Player player : Bukkit.getOnlinePlayers()) { if (player.hasPermission("plots.admin")) { PlayerFunctions.sendMessage(player, c); } } System.out.println(ChatColor.stripColor(ChatColor.translateAlternateColorCodes('&', C.PREFIX.s() + c.s()))); } public static void reloadTranslations() throws IOException { translations = YamlConfiguration.loadConfiguration(translationsFile); } public static long getLastPlayed(UUID uuid) { if (uuid == null) { return 0; } OfflinePlayer player; if (((player = Bukkit.getOfflinePlayer(uuid)) == null) || !player.hasPlayedBefore()) { return 0; } return player.getLastPlayed(); } /** * Load configuration files */ @SuppressWarnings("deprecation") public static void configs() { File folder = new File(getMain().getDataFolder() + File.separator + "config"); if (!folder.exists() && !folder.mkdirs()) { sendConsoleSenderMessage(C.PREFIX.s() + "&cFailed to create the /plugins/config folder. Please create it manually."); } try { configFile = new File(getMain().getDataFolder() + File.separator + "config" + File.separator + "settings.yml"); if (!configFile.exists()) { configFile.createNewFile(); } config = YamlConfiguration.loadConfiguration(configFile); setupConfig(); } catch (Exception err_trans) { Logger.add(LogLevel.DANGER, "Failed to save settings.yml"); System.out.println("Failed to save settings.yml"); } try { storageFile = new File(getMain().getDataFolder() + File.separator + "config" + File.separator + "storage.yml"); if (!storageFile.exists()) { storageFile.createNewFile(); } storage = YamlConfiguration.loadConfiguration(storageFile); setupStorage(); } catch (Exception err_trans) { Logger.add(LogLevel.DANGER, "Failed to save storage.yml"); System.out.println("Failed to save storage.yml"); } try { translationsFile = new File(getMain().getDataFolder() + File.separator + "config" + File.separator + "translations.yml"); if (!translationsFile.exists()) { translationsFile.createNewFile(); } translations = YamlConfiguration.loadConfiguration(translationsFile); setupTranslations(); } catch (Exception err_trans) { Logger.add(LogLevel.DANGER, "Failed to save translations.yml"); System.out.println("Failed to save translations.yml"); } try { config.save(configFile); storage.save(storageFile); translations.save(translationsFile); } catch (IOException e) { Logger.add(LogLevel.DANGER, "Configuration file saving failed"); e.printStackTrace(); } { Settings.DB.USE_MYSQL = storage.getBoolean("mysql.use"); Settings.DB.USER = storage.getString("mysql.user"); Settings.DB.PASSWORD = storage.getString("mysql.password"); Settings.DB.HOST_NAME = storage.getString("mysql.host"); Settings.DB.PORT = storage.getString("mysql.port"); Settings.DB.DATABASE = storage.getString("mysql.database"); Settings.DB.USE_SQLITE = storage.getBoolean("sqlite.use"); Settings.DB.SQLITE_DB = storage.getString("sqlite.db"); } { Settings.METRICS = config.getBoolean("metrics"); // Web // Web.ENABLED = config.getBoolean("web.enabled"); // Web.PORT = config.getInt("web.port"); Settings.AUTO_CLEAR = config.getBoolean("clear.auto.enabled"); Settings.AUTO_CLEAR_DAYS = config.getInt("clear.auto.days"); } if (Settings.DEBUG) { Map<String, String> settings = new HashMap<>(); settings.put("Kill Road Mobs", "" + Settings.KILL_ROAD_MOBS); settings.put("Use Metrics", "" + Settings.METRICS); settings.put("Mob Pathfinding", "" + Settings.MOB_PATHFINDING); settings.put("Web Enabled", "" + Web.ENABLED); settings.put("Web Port", "" + Web.PORT); settings.put("DB Mysql Enabled", "" + Settings.DB.USE_MYSQL); settings.put("DB SQLite Enabled", "" + Settings.DB.USE_SQLITE); settings.put("Auto Clear Enabled", "" + Settings.AUTO_CLEAR); settings.put("Auto Clear Days", "" + Settings.AUTO_CLEAR_DAYS); for (Entry<String, String> setting : settings.entrySet()) { sendConsoleSenderMessage(C.PREFIX.s() + String.format("&cKey: &6%s&c, Value: &6%s", setting.getKey(), setting.getValue())); } } } /** * Kill all entities on roads */ @SuppressWarnings("deprecation") public static void killAllEntities() { Bukkit.getScheduler().scheduleAsyncRepeatingTask(getMain(), new Runnable() { Location location; long ticked = 0l; long error = 0l; { sendConsoleSenderMessage(C.PREFIX.s() + "KillAllEntities started."); } @Override public void run() { if (this.ticked > 36000l) { this.ticked = 0l; sendConsoleSenderMessage(C.PREFIX.s() + "KillAllEntities has been running for 60 minutes. Errors: " + this.error); this.error = 0l; } for (String w : getPlotWorlds()) { getWorldSettings(w); World world = Bukkit.getServer().getWorld(w); try { if (world.getLoadedChunks().length < 1) { continue; } for (Chunk chunk : world.getLoadedChunks()) { Entity[] entities = chunk.getEntities(); for (int i = entities.length - 1; i >= 0; i--) { Entity entity = entities[i]; if ((entity instanceof Player) || PlayerEvents.isInPlot(entity.getLocation())) { continue; } boolean tamed = false; if (Settings.MOB_PATHFINDING) { if (entity instanceof Tameable) { Tameable tameable = (Tameable) entity; if (tameable.isTamed()) { tamed = true; } } else if (entity instanceof LivingEntity) { LivingEntity livingEntity = ((LivingEntity) entity); if (livingEntity.getCustomName() != null) { tamed = true; } } if (!tamed) { entity.remove(); continue; } boolean found = false; int radius = 1; int dir = 0; int x = this.location.getBlockX(); int y = this.location.getBlockY(); int z = this.location.getBlockZ(); while (!found && (radius < 4)) { Location pos; switch (dir) { case 0: pos = new Location(world, x + radius, y, z); dir++; break; case 1: pos = new Location(world, x, y, z + radius); dir++; break; case 2: pos = new Location(world, x - radius, y, z); dir++; break; case 3: pos = new Location(world, x, y, z - radius); dir = 0; radius++; break; default: pos = this.location; break; } if (PlayerEvents.isInPlot(pos)) { entity.teleport(pos.add(0.5, 0, 0.5)); found = true; break; } } entity.teleport(this.location.subtract(this.location.getDirection().normalize().multiply(2))); } } } } catch (Exception e) { ++this.error; } finally { ++this.ticked; } } } }, 0l, 2l); } /** * SETUP: settings.yml */ private static void setupConfig() { config.set("version", config_ver); Map<String, Object> options = new HashMap<String, Object>(); options.put("auto_update", false); options.put("worldguard.enabled", Settings.WORLDGUARD); options.put("kill_road_mobs", Settings.KILL_ROAD_MOBS_DEFAULT); options.put("mob_pathfinding", Settings.MOB_PATHFINDING_DEFAULT); options.put("web.enabled", Web.ENABLED); options.put("web.port", Web.PORT); options.put("metrics", true); options.put("debug", true); options.put("clear.auto.enabled", false); options.put("clear.auto.days", 365); options.put("max_plots", Settings.MAX_PLOTS); for (Entry<String, Object> node : options.entrySet()) { if (!config.contains(node.getKey())) { config.set(node.getKey(), node.getValue()); } } Settings.DEBUG = config.getBoolean("debug"); if (Settings.DEBUG) { sendConsoleSenderMessage(C.PREFIX.s() + "&6Debug Mode Enabled (Default). Edit the config to turn this off."); } Web.ENABLED = config.getBoolean("web.enabled"); Web.PORT = config.getInt("web.port"); Settings.KILL_ROAD_MOBS = config.getBoolean("kill_road_mobs"); Settings.WORLDGUARD = config.getBoolean("worldguard.enabled"); Settings.MOB_PATHFINDING = config.getBoolean("mob_pathfinding"); Settings.METRICS = config.getBoolean("metrics"); Settings.AUTO_CLEAR_DAYS = config.getInt("clear.auto.days"); Settings.AUTO_CLEAR = config.getBoolean("clear.auto.enabled"); Settings.MAX_PLOTS = config.getInt("max_plots"); } public static void createConfiguration(PlotWorld plotworld) { Map<String, Object> options = new HashMap<String, Object>(); for (ConfigurationNode setting : plotworld.getSettingNodes()) { setting.getConstant(); setting.getValue(); } for (Entry<String, Object> node : options.entrySet()) { if (!config.contains(node.getKey())) { config.set(node.getKey(), node.getValue()); } } try { config.save(PlotMain.configFile); } catch (IOException e) { PlotMain.sendConsoleSenderMessage("&c[Warning] PlotSquared failed to save the configuration&7 (settings.yml may differ from the one in memory)\n - To force a save from console use /plots save"); } } public static void loadWorld(String world, ChunkGenerator generator) { if (getWorldSettings(world) != null) { return; } Set<String> worlds; if (config.contains("worlds")) { worlds = config.getConfigurationSection("worlds").getKeys(false); } else { worlds = new HashSet<String>(); } if (generator != null && generator instanceof PlotGenerator) { sendConsoleSenderMessage(C.PREFIX.s() + "&aDetected world load for '" + world + "'."); PlotGenerator plotgen = (PlotGenerator) generator; PlotWorld plotworld = plotgen.getNewPlotWorld(world); PlotManager manager = plotgen.getPlotManager(); if (!config.contains("worlds." + world)) { config.createSection("worlds." + world); } plotworld.saveConfiguration(config.getConfigurationSection("worlds." + world)); plotworld.loadDefaultConfiguration(config.getConfigurationSection("worlds." + world)); try { config.save(configFile); } catch (IOException e) { e.printStackTrace(); } addPlotWorld(world, plotworld, manager); } else { if (worlds.contains(world)) { sendConsoleSenderMessage("&cWorld '" + world + "' in settings.yml is not using PlotSquared generator!"); PlotWorld plotworld = new DefaultPlotWorld(world); PlotManager manager = new DefaultPlotManager(); if (!config.contains("worlds." + world)) { config.createSection("worlds." + world); } plotworld.saveConfiguration(config.getConfigurationSection("worlds." + world)); plotworld.loadConfiguration(config.getConfigurationSection("worlds." + world)); try { config.save(configFile); } catch (IOException e) { e.printStackTrace(); } addPlotWorld(world, plotworld, manager); } } } /** * Adds an external world as a recognized PlotSquared world - The PlotWorld * class created is based off the configuration in the settings.yml - Do not * use this method unless the required world is preconfigured in the * settings.yml * * @param world */ public static void loadWorld(World world) { if (world == null) { return; } ChunkGenerator generator = world.getGenerator(); loadWorld(world.getName(), generator); } /** * SETUP: storage.properties */ private static void setupStorage() { storage.set("version", storage_ver); Map<String, Object> options = new HashMap<String, Object>(); options.put("mysql.use", true); options.put("sqlite.use", false); options.put("sqlite.db", "storage"); options.put("mysql.host", "localhost"); options.put("mysql.port", "3306"); options.put("mysql.user", "root"); options.put("mysql.password", "password"); options.put("mysql.database", "plot_db"); for (Entry<String, Object> node : options.entrySet()) { if (!storage.contains(node.getKey())) { storage.set(node.getKey(), node.getValue()); } } } /** * SETUP: translations.properties */ public static void setupTranslations() { translations.set("version", translations_ver); for (C c : C.values()) { if (!translations.contains(c.toString())) { translations.set(c.toString(), c.s()); } } } /** * On unload */ @Override public void onDisable() { Logger.add(LogLevel.GENERAL, "Logger disabled"); try { Logger.write(); } catch (IOException e1) { e1.printStackTrace(); } try { connection.close(); mySQL.closeConnection(); } catch (NullPointerException | SQLException e) { if (connection != null) { Logger.add(LogLevel.DANGER, "Could not close mysql connection"); } } /* * if(PlotWeb.PLOTWEB != null) { try { PlotWeb.PLOTWEB.stop(); } catch * (Exception e) { e.printStackTrace(); } } */ } // Material.STONE_BUTTON, Material.WOOD_BUTTON, // Material.LEVER, Material.STONE_PLATE, Material.WOOD_PLATE, // Material.CHEST, Material.TRAPPED_CHEST, Material.TRAP_DOOR, // Material.WOOD_DOOR, Material.WOODEN_DOOR, // Material.DISPENSER, Material.DROPPER public static HashMap<Material, String> booleanFlags = new HashMap<>(); static { booleanFlags.put(Material.WOODEN_DOOR, "wooden_door"); booleanFlags.put(Material.IRON_DOOR, "iron_door"); booleanFlags.put(Material.STONE_BUTTON, "stone_button"); booleanFlags.put(Material.WOOD_BUTTON, "wooden_button"); booleanFlags.put(Material.LEVER, "lever"); booleanFlags.put(Material.WOOD_PLATE, "wooden_plate"); booleanFlags.put(Material.STONE_PLATE, "stone_plate"); booleanFlags.put(Material.CHEST, "chest"); booleanFlags.put(Material.TRAPPED_CHEST, "trapped_chest"); booleanFlags.put(Material.TRAP_DOOR, "trap_door"); booleanFlags.put(Material.DISPENSER, "dispenser"); booleanFlags.put(Material.DROPPER, "dropper"); } private static void defaultFlags() { for(String str : booleanFlags.values()) { FlagManager.addFlag(new AbstractFlag(str) { @Override public String parseValue(String value) { switch (value) { case "true": case "1": case "yes": return "true"; case "false": case "off": case "0": return "false"; default: return null; } } @Override public String getValueDesc() { return "Flag value must be a boolean: true, false"; } }); } FlagManager.addFlag(new AbstractFlag("gamemode") { @Override public String parseValue(String value) { switch (value) { case "creative": case "c": case "1": return "creative"; case "survival": case "s": case "0": return "survival"; case "adventure": case "a": case "2": return "adventure"; default: return null; } } @Override public String getValueDesc() { return "Flag value must be a gamemode: 'creative' , 'survival' or 'adventure'"; } }); FlagManager.addFlag(new AbstractFlag("time") { @Override public String parseValue(String value) { try { return Long.parseLong(value)+""; } catch (Exception e) { return null; } } @Override public String getValueDesc() { return "Flag value must be a time in ticks: 0=sunrise 12000=noon 18000=sunset 24000=night"; } }); FlagManager.addFlag(new AbstractFlag("weather") { @Override public String parseValue(String value) { switch (value) { case "rain": case "storm": case "on": return "rain"; case "clear": case "off": case "sun": return "clear"; default: return null; } } @Override public String getValueDesc() { return "Flag value must be weather type: 'clear' or 'rain'"; } }); } public static void addPlotWorld(String world, PlotWorld plotworld, PlotManager manager) { worlds.put(world, plotworld); managers.put(world, manager); if (!plots.containsKey(world)) { plots.put(world, new HashMap<PlotId, Plot>()); } } public static void removePlotWorld(String world) { plots.remove(world); managers.remove(world); worlds.remove(world); } public static HashMap<String, HashMap<PlotId, Plot>> getAllPlotsRaw() { return plots; } public static void setAllPlotsRaw(HashMap<String, HashMap<PlotId, Plot>> plots) { PlotMain.plots = plots; } }
gpl-3.0
Plain-Simple/TextFile
TextFile.java
5959
import java.awt.*; import java.awt.datatransfer.*; import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; /** * A java utility class for handling simple textfiles. * Copyright (C) Plain Simple Apps * @author Stefan Kussmaul * * See <https://github.com/Plain-Simple/TextFile> for more information. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ public class TextFile extends File { /** * Creates a new TextFile instance using the file * specified by the given path. * * @throws NullPointerException if the given path is null */ public TextFile(String path) { super(path); } /** * Reads the file and returns its contents as a String. * * @return text contained in the file as a single- or multi- * line String, or null if the file cannot be read. */ public String readFile() { /* Try creating a BufferedReader using the file's path */ try (BufferedReader reader = Files.newBufferedReader(Paths.get(getPath()))) { String line, text = ""; int line_counter = 0; while ((line = reader.readLine()) != null) { if(line_counter == 0) text = line; else text += "\n" + line; line_counter++; } return text; } catch (IOException e) { return ""; } } /** * Prints file contents to console using System.print(). */ public void printFile() { System.out.print(readFile()); } /** * Writes the given String to the file. * * @param newText String to write to the file */ public boolean writeFile(String newText) { /* Try creating a BufferedWriter using the file's path */ try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(getPath()))) { writer.write(newText, 0, newText.length()); return true; } catch (IOException e) { return false; } } /* Writes the given String array to the file by * concatenating the array's elements into a single String * and writing it to the file. * * @param text String array to expand and write to file */ public void writeFile(String[] text) { String file_text = ""; for(int i = 0; i < text.length; i++) file_text += text[i]; writeFile(file_text); } /** * Appends the given String directly to the end of the file. * No new line will be created unless specified by the String. * * @param append String to add to the end of the file */ public void appendText(String append) { writeFile(readFile() + append); } /** * Clears the file of text. */ public void clear() { writeFile(""); } /** * Searches the file text for the specified * String and returns whether the String was * found. Will return false if the file cannot * be read. * * @return whether the file contains specified * String, or false if the file cannot be read. */ public boolean contains(String toFind) { try { return readFile().contains(toFind); } catch(NullPointerException e) { return false; } } /** * Reads the file line by line and returns a String arrayList * where each element is a separate line. * * @return a String arrayList containing individual lines * as elements, or null if file could not be read */ public ArrayList<String> readLines() { ArrayList<String> file_lines = new ArrayList<String> (); try { BufferedReader reader = new BufferedReader(new FileReader(this)); String line; while ((line = reader.readLine()) != null) { file_lines.add(line); } return file_lines; } catch(IOException e) { return null; } } /** * Pastes contents of system clipboard into file. * * @return whether clipboard contents were accessed and * written successfully to file */ public boolean pasteInto() { // Todo: fix bug where linebreaks are lost Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); /* get contents from clipboard (stored in a Transferable, which manages data transfer) */ Transferable contents = clipboard.getContents(null); /* if contents are transferable, the Transferable will not be null and will be the correct DataFlavor (String). DataFlavor refers to the type of object something is */ if (contents != null && contents.isDataFlavorSupported(DataFlavor.stringFlavor)) { try { return writeFile((String)contents.getTransferData(DataFlavor.stringFlavor)); } catch (UnsupportedFlavorException|IOException e) { return false; } } else { return false; } } /** * Copies contents of file to system clipboard. * If the file cannot be read system clipboard will * not be overwritten. * * @return whether file contents were successfully * copied */ public boolean copyFrom() { try { StringSelection selection = new StringSelection(readFile()); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(selection, selection); return true; } catch(IllegalStateException e) { return false; } } }
gpl-3.0
vpillac/vroom
VroomUtilities/src/vroom/common/utilities/StatCollector.java
11994
/** * */ package vroom.common.utilities; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.Format; import java.util.LinkedList; import java.util.List; import java.util.Locale; import vroom.common.utilities.logging.LoggerHelper; /** * <code>StatCollector</code> is a class that allows the collection of statistic information and their output in a CSV * text file. * <p> * Creation date: Jul 8, 2010 - 10:14:16 AM * * @author Victor Pillac, <a href="http://uniandes.edu.co">Universidad de Los Andes</a>-<a * href="http://copa.uniandes.edu.co">Copa</a> <a href="http://www.emn.fr">Ecole des Mines de Nantes</a>-<a * href="http://www.irccyn.ec-nantes.fr/irccyn/d/en/equipes/Slp">SLP</a> * @version 1.0 */ public class StatCollector { /** * Getter for this class logger * * @return the logger associated with this class */ public static LoggerHelper getLogger() { return LoggerHelper.getLogger(StatCollector.class); } private static String sNumberFormat = "###0.0000"; /** * Set the default format number to be used * * @param format * a string of the form <code>###0.0000</code> defining the formating of decimal numbers */ public static void setDefaultNumberFormat(String format) { sNumberFormat = format; } /** * Returns the default number format to be used * * @return the default number format to be used * @see #setDefaultNumberFormat(String) */ public static String getDefaultNumberFormat() { return sNumberFormat; } public static String sCVSSeparator = ";"; public static char sDecimalSeparator = '.'; public static char sGroupingSeparator = ','; public static String sCommentsPrefix = "#==================== COMMENTS ====================\n"; public static String sCommentsSuffix = "\n#==================================================\n\n"; private BufferedWriter mWriter; private boolean mAutoFlush; private final Label<?>[] mLabels; private final List<Object[]> mValues; private final DecimalFormat mFormat; private final String mComment; /** * Creates a new <code>StatCollector</code> with no file attached * * @param comment * an optional comment inserted at the beginning of the ouput file * @param labels * the labels for collected data * @see #setFile(File, boolean) */ public StatCollector(String comment, Label<?>... labels) { this(null, false, false, comment, labels); } /** * Creates a new <code>StatCollector</code> * * @param output * the file in which stats will be recorded * @param autoFlush * <code>true</code> if stats should be written immediatly in the file * @param append * <code>true</code> if statistics should be appended to the file, <code>false</code> to erase previous * content * @param comment * an optional comment inserted at the beginning of the ouput file * @param labels * the labels for collected data */ public StatCollector(File output, boolean autoFlush, boolean append, String comment, Label<?>... labels) { if (labels == null) { throw new IllegalArgumentException("Argument labels cannot be null"); } mLabels = labels; for (int i = 0; i < labels.length; i++) { mLabels[i].id = i; } mValues = new LinkedList<Object[]>(); DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.getDefault()); symbols.setDecimalSeparator(sDecimalSeparator); symbols.setGroupingSeparator(sGroupingSeparator); mFormat = new DecimalFormat(sNumberFormat, symbols); mValues.clear(); mComment = comment; setFile(output, autoFlush, append); } /** * Statistic collection. * <p> * The <code>stats</code> should be given in the same order as the labels were defined * </p> * * @param stats * the statistics to be collected */ public synchronized void collect(Object... stats) { if (stats.length != mLabels.length) { throw new IllegalArgumentException( "The array stats should have the same length as the labels"); } for (int i = 0; i < stats.length; i++) { if (stats[i] != null && !mLabels[i].mValueClass.isAssignableFrom(stats[i].getClass())) { throw new IllegalArgumentException(String.format( "Unexpected data type for label #%s - %s: expected %s but was %s", i, mLabels[i].mName, mLabels[i].mValueClass.getSimpleName(), stats[i] .getClass().getSimpleName())); } } mValues.add(stats); write(false, stats); } /** * Return the labels defined in this instance * * @return an array containing the defined labels */ public Label<?>[] getLabels() { return mLabels; } /** * Return the values collected for a given label * * @param <V> * the type of data * @param label * the label to lookup * @return an array containing the values collected so far */ @SuppressWarnings("unchecked") public <V> V[] getValues(Label<V> label) { V[] values = (V[]) new Object[mValues.size()]; int i = 0; for (Object[] val : mValues) { values[i++] = (V) val[label.id]; } return values; } public String getSatString(Object... stats) { if (stats.length != mLabels.length) { throw new IllegalArgumentException( "The array stats should have the same length as the labels"); } StringBuilder b = new StringBuilder(stats.length * 10); for (int i = 0; i < stats.length; i++) { b.append(mLabels[i].getName()); b.append("="); b.append(toString(mLabels[i], stats[i])); if (i < stats.length - 1) b.append(", "); } return b.toString(); } /** * Set the output file. * * @param output * the file in which stats will be recorded * @param autoflush * <code>true</code> if stats should be written immediatly in the file */ public synchronized void setFile(File output, boolean autoflush, boolean append) { boolean writeheader = (output != null) && (!output.exists() || !append); BufferedWriter writer = null; if (output != null) { try { writer = new BufferedWriter(new FileWriter(output, append)); } catch (IOException e) { getLogger().exception("StatCollector.setFile", e); writer = null; } } mWriter = writer; mAutoFlush = writer != null && autoflush; if (writeheader) { // Write comments write("%s%s%s", sCommentsPrefix, mComment, sCommentsSuffix); // Write column labels (headers) write(true, (Object[]) mLabels); } } /** * Write a formated string, used for comments * * @param format * @param args */ protected synchronized void write(String format, Object... args) { if (mWriter == null) { return; } try { mWriter.write(String.format(format, args)); mWriter.newLine(); if (mAutoFlush) { mWriter.flush(); } } catch (IOException e) { getLogger().exception("StatCollector.write", e); } } /** * Write an array of values separated by {@link #sCVSSeparator} * * @param header * {@code true} if the objects are headers of the columns * @param values * the values to be writen */ protected synchronized void write(boolean header, Object... values) { if (mWriter == null) { return; } StringBuilder b = new StringBuilder(); for (int v = 0; v < values.length; v++) { if (header) b.append(mLabels[v].getName()); else b.append(toString(mLabels[v], values[v])); if (v < values.length - 1) b.append(sCVSSeparator); } try { mWriter.write(b.toString()); mWriter.newLine(); if (mAutoFlush) { mWriter.flush(); } } catch (IOException e) { getLogger().exception("StatCollector.write", e); } } public String toString(Label<?> label, Object val) { if (val == null) return "null"; if ((val instanceof Double && Double.isNaN((double) val)) || (val instanceof Float && Float.isNaN((float) val))) return "-"; else if (label.mFormat != null) return label.mFormat.format(val); else if (val instanceof Double || val instanceof Float) return Constants.isZero(((Number) val).doubleValue()) ? mFormat.format(0) : mFormat .format(val); else return val.toString(); } /** * Write the collected stats to the file */ public synchronized void flush() { try { mWriter.flush(); } catch (IOException e) { getLogger().exception("StatCollector.write", e); } } /** * Close the underlying file writer */ public synchronized void close() { try { mWriter.close(); } catch (IOException e) { getLogger().exception("StatCollector.write", e); } } public static class Label<V extends Object> { private final String mName; private final Class<V> mValueClass; private int id; private final Format mFormat; /** * Getter for <code>name</code> * * @return the name */ public String getName() { return mName; } /** * Getter for <code>valueClass</code> * * @return the valueClass */ public Class<V> getValueClass() { return mValueClass; } /** * Creates a new <code>Label</code> using default formatting * * @param label * the name of the label * @param valueClass * the type of data that will be collected */ public Label(String label, Class<V> valueClass) { this(label, valueClass, null); } /** * Creates a new <code>Label</code> using a specific formatting * * @param label * the name of the label * @param valueClass * the type of data that will be collected * @param format * the format used to format the values (can be <code>null</code>) */ public Label(String label, Class<V> valueClass, Format format) { mName = label; mValueClass = valueClass; mFormat = format; id = -1; } /* * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return mName; } } }
gpl-3.0
benparvar/sousvide
android/app/src/main/java/com/benparvar/sousvide/infrastructure/Contants.java
3088
package com.benparvar.sousvide.infrastructure; /** * Created by alans on 19/05/17. */ public class Contants { // BLUETOOTH public interface Bluetooth { public final int REQUEST_ENABLE_BT = 0; public final String END_LINE = "\n"; public final String LINE_FEED = "\r"; } public interface Timer { public Long MIN_TARGET_TIMER_IN_SECONDS = 0L; public Long MAX_TARGET_TIMER_IN_SECONDS = 86400L; } public interface TimTemperatureer { public Double MIN_TARGET_TEMPERATURE = 30.00; public Double MAX_TARGET_TEMPERATURE = 60.00; } // ERROR CODE public interface ErrorCode { public final int NO_ERROR = -1; public final int UNKNOWN = 0; public final int NO_PAIRED_DEVICES = 1; public final int YES_PAIRED_DEVICES = 2; public final int NO_BLUETOOTH_ADAPTER = 3; public final int INVALID_TEMPERATURE = 4; public final int OFF = 5; public final int ON = 6; public final int READY = 7; } // STATUS public interface PanStatus { public final String STS_OFF = "0"; public final String STS_READY = "1"; public final String STS_COOK_IN_PROGRESS = "2"; public final String STS_COOK_FINISHED = "3"; } // COMMAND public interface PanCommand { public final String HEADER = "PAN"; public final String SEPARATOR = ":"; public final String VERB = "V"; public final String NOUN = "N"; public final String STATUS = "S"; } // VERB public interface PanVerb { public final String PAN_OFF = "000"; public final String PAN_ON = "001"; public final String PAN_TIMER = "002"; public final String PAN_TEMPERATURE = "003"; public final String PAN_TIMER_TARGET = "004"; public final String PAN_TEMPERATURE_TARGET = "005"; public final String PAN_CURRENT_TIMER = "006"; public final String PAN_CURRENT_TEMPERATURE = "007"; public final String PAN_READY = "008"; public final String PAN_COOK_IN_PROGRESS = "009"; public final String PAN_COOK_FINISHED = "010"; public final String PID_VALUE = "011"; public final String PAN_VERSION = "012"; } // ERROR CODE public interface PanErrorCode { public final String INVALID_HEADER = "900"; public final String INVALID_VERB = "901"; public final String INVALID_NOUN = "902"; public final String INVALID_TIMER_TARGET = "903"; public final String INVALID_TEMPERATURE_TARGET = "904"; public final String INVALID_ALREADY_OFF = "905"; public final String INVALID_ALREADY_COOKING = "906"; public final String INVALID_ALREADY_FINISHED_COOKING = "907"; public final String INVALID_NO_PROGRAMMED = "908"; } public interface SecurityKeys { String PREFERENCE_NAME = new String(new char[]{'b', 'e', 'n', 'p', 'a', 'r', 'v', 'a', 'r', 's', 'r', 'a', 'v', 'r', 'a', 'p', 'n', 'e', 'b' }); } }
gpl-3.0
aleatorio12/ProVentasConnector
jasperreports-6.2.1-project/jasperreports-6.2.1/src/net/sf/jasperreports/engine/convert/ConvertVisitor.java
8032
/* * JasperReports - Free Java Reporting Library. * Copyright (C) 2001 - 2014 TIBCO Software Inc. All rights reserved. * http://www.jaspersoft.com * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is part of JasperReports. * * JasperReports is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JasperReports is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with JasperReports. If not, see <http://www.gnu.org/licenses/>. */ /* * Contributors: * Eugene D - eugenedruy@users.sourceforge.net * Adrian Jackson - iapetus@users.sourceforge.net * David Taylor - exodussystems@users.sourceforge.net * Lars Kristensen - llk@users.sourceforge.net */ package net.sf.jasperreports.engine.convert; import java.util.List; import net.sf.jasperreports.crosstabs.JRCrosstab; import net.sf.jasperreports.engine.JRBoxContainer; import net.sf.jasperreports.engine.JRBreak; import net.sf.jasperreports.engine.JRChart; import net.sf.jasperreports.engine.JRChild; import net.sf.jasperreports.engine.JRComponentElement; import net.sf.jasperreports.engine.JRElementGroup; import net.sf.jasperreports.engine.JREllipse; import net.sf.jasperreports.engine.JRFrame; import net.sf.jasperreports.engine.JRGenericElement; import net.sf.jasperreports.engine.JRImage; import net.sf.jasperreports.engine.JRLine; import net.sf.jasperreports.engine.JRLineBox; import net.sf.jasperreports.engine.JRPrintElement; import net.sf.jasperreports.engine.JRPrintGraphicElement; import net.sf.jasperreports.engine.JRRectangle; import net.sf.jasperreports.engine.JRStaticText; import net.sf.jasperreports.engine.JRSubreport; import net.sf.jasperreports.engine.JRTextField; import net.sf.jasperreports.engine.JRVisitable; import net.sf.jasperreports.engine.JRVisitor; import net.sf.jasperreports.engine.base.JRBasePrintFrame; import net.sf.jasperreports.engine.base.JRBasePrintRectangle; import net.sf.jasperreports.engine.type.LineStyleEnum; import net.sf.jasperreports.engine.type.ModeEnum; /** * @author Teodor Danciu (teodord@users.sourceforge.net) */ public class ConvertVisitor implements JRVisitor { protected ReportConverter reportConverter; protected JRBasePrintFrame parentFrame; protected JRPrintElement printElement; /** * */ public ConvertVisitor(ReportConverter reportConverter) { this(reportConverter, null); } /** * */ public ConvertVisitor(ReportConverter reportConverter, JRBasePrintFrame parentFrame) { this.reportConverter = reportConverter; this.parentFrame = parentFrame; } /** * */ public JRPrintElement getVisitPrintElement(JRVisitable visitable) { if (visitable != null) { visitable.visit(this); return printElement; } return null; } /** * */ public void visitBreak(JRBreak breakElement) { //FIXMECONVERT } /** * */ public void visitChart(JRChart chart) { JRPrintElement printImage = ChartConverter.getInstance().convert(reportConverter, chart); addElement(parentFrame, printImage); addContour(reportConverter, parentFrame, printImage); } /** * */ public void visitCrosstab(JRCrosstab crosstab) { JRPrintElement printFrame = CrosstabConverter.getInstance().convert(reportConverter, crosstab); addElement(parentFrame, printFrame); addContour(reportConverter, parentFrame, printFrame); } /** * */ public void visitElementGroup(JRElementGroup elementGroup) { List<JRChild> children = elementGroup.getChildren(); if (children != null && children.size() > 0) { for(int i = 0; i < children.size(); i++) { children.get(i).visit(this); } } } /** * */ public void visitEllipse(JREllipse ellipse) { addElement(parentFrame, EllipseConverter.getInstance().convert(reportConverter, ellipse)); } /** * */ public void visitFrame(JRFrame frame) { JRPrintElement printFrame = FrameConverter.getInstance().convert(reportConverter, frame); addElement(parentFrame, printFrame); addContour(reportConverter, parentFrame, printFrame); } /** * */ public void visitImage(JRImage image) { JRPrintElement printImage = ImageConverter.getInstance().convert(reportConverter, image); addElement(parentFrame, printImage); addContour(reportConverter, parentFrame, printImage); } /** * */ public void visitLine(JRLine line) { addElement(parentFrame, LineConverter.getInstance().convert(reportConverter, line)); } /** * */ public void visitRectangle(JRRectangle rectangle) { addElement(parentFrame, RectangleConverter.getInstance().convert(reportConverter, rectangle)); } /** * */ public void visitStaticText(JRStaticText staticText) { JRPrintElement printText = StaticTextConverter.getInstance().convert(reportConverter, staticText); addElement(parentFrame, printText); addContour(reportConverter, parentFrame, printText); } /** * */ public void visitSubreport(JRSubreport subreport) { JRPrintElement printImage = SubreportConverter.getInstance().convert(reportConverter, subreport); addElement(parentFrame, printImage); addContour(reportConverter, parentFrame, printImage); } /** * */ public void visitTextField(JRTextField textField) { JRPrintElement printText = TextFieldConverter.getInstance().convert(reportConverter, textField); addElement(parentFrame, printText); addContour(reportConverter, parentFrame, printText); } /** * */ protected void addElement(JRBasePrintFrame frame, JRPrintElement element) { printElement = element; if (frame != null) { frame.addElement(element); } } /** * */ protected void addContour(ReportConverter reportConverter, JRBasePrintFrame frame, JRPrintElement element) { if (frame != null) { boolean hasContour = false; JRLineBox box = element instanceof JRBoxContainer ? ((JRBoxContainer)element).getLineBox() : null; if (box == null) { JRPrintGraphicElement graphicElement = element instanceof JRPrintGraphicElement ? (JRPrintGraphicElement)element : null; hasContour = (graphicElement == null) || graphicElement.getLinePen().getLineWidth().floatValue() <= 0f; } else { hasContour = box.getTopPen().getLineWidth().floatValue() <= 0f && box.getLeftPen().getLineWidth().floatValue() <= 0f && box.getRightPen().getLineWidth().floatValue() <= 0f && box.getBottomPen().getLineWidth().floatValue() <= 0f; } if (hasContour) { JRBasePrintRectangle rectangle = new JRBasePrintRectangle(reportConverter.getDefaultStyleProvider()); rectangle.setUUID(element.getUUID()); rectangle.setX(element.getX()); rectangle.setY(element.getY()); rectangle.setWidth(element.getWidth()); rectangle.setHeight(element.getHeight()); rectangle.getLinePen().setLineWidth(0.1f); rectangle.getLinePen().setLineStyle(LineStyleEnum.DASHED); rectangle.getLinePen().setLineColor(ReportConverter.GRID_LINE_COLOR); rectangle.setMode(ModeEnum.TRANSPARENT); frame.addElement(rectangle); } } } public void visitComponentElement(JRComponentElement componentElement) { JRPrintElement image = ComponentElementConverter.getInstance() .convert(reportConverter, componentElement); addElement(parentFrame, image); addContour(reportConverter, parentFrame, image); } public void visitGenericElement(JRGenericElement element) { JRPrintElement image = GenericElementConverter.getInstance() .convert(reportConverter, element); addElement(parentFrame, image); addContour(reportConverter, parentFrame, image); } }
gpl-3.0
taisbellini/pajeng
workspace/JavaCCPajeParser/src/br/ufrgs/inf/tlbellini/lib/PajeSetStateEvent.java
283
package br.ufrgs.inf.tlbellini.lib; public class PajeSetStateEvent extends PajeStateEvent { public PajeSetStateEvent(PajeTraceEvent event, PajeContainer container, PajeType type, double time, PajeValue value) { super(event, container, type, time); this.setValue(value); } }
gpl-3.0
craftercms/profile
security-provider/src/main/java/org/craftercms/security/authentication/impl/RestAuthenticationRequiredHandler.java
1732
/* * Copyright (C) 2007-2022 Crafter Software Corporation. All Rights Reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.craftercms.security.authentication.impl; import java.io.IOException; import javax.servlet.http.HttpServletResponse; import org.craftercms.commons.http.RequestContext; import org.craftercms.security.authentication.AuthenticationRequiredHandler; import org.craftercms.security.exception.AuthenticationException; import org.craftercms.security.exception.SecurityProviderException; import org.craftercms.security.utils.handlers.AbstractRestHandlerBase; /** * Implementation of {@link org.craftercms.security.authentication.AuthenticationRequiredHandler} for REST based * applications, which returns a 401 UNAUTHORIZED status with the authentication exception message. * * @author avasquez */ public class RestAuthenticationRequiredHandler extends AbstractRestHandlerBase implements AuthenticationRequiredHandler { @Override public void handle(RequestContext context, AuthenticationException e) throws SecurityProviderException, IOException { sendErrorMessage(HttpServletResponse.SC_UNAUTHORIZED, e, context); } }
gpl-3.0
hpiasg/asgcommon
src/main/java/de/uni_potsdam/hpi/asg/common/iohelper/StatisticsFile.java
2445
package de.uni_potsdam.hpi.asg.common.iohelper; /* * Copyright (C) 2017 - 2021 Norman Kluge * * This file is part of ASGcommon. * * ASGcommon is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ASGcommon is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ASGcommon. If not, see <http://www.gnu.org/licenses/>. */ import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBException; import jakarta.xml.bind.Marshaller; import jakarta.xml.bind.Unmarshaller; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class StatisticsFile { private static final Logger logger = LogManager.getLogger(); public static Statistics readIn(File file) { try { if(file.exists()) { JAXBContext jaxbContext = JAXBContext.newInstance(Statistics.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); return (Statistics)jaxbUnmarshaller.unmarshal(file); } else { logger.error("File " + file.getAbsolutePath() + " not found"); return null; } } catch(JAXBException e) { logger.error(e.getLocalizedMessage()); return null; } } public static boolean writeOut(Statistics stat, File file) { try { Writer fw = new FileWriter(file); JAXBContext context = JAXBContext.newInstance(Statistics.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); m.marshal(stat, fw); return true; } catch(JAXBException e) { logger.error(e.getLocalizedMessage()); return false; } catch(IOException e) { logger.error(e.getLocalizedMessage()); return false; } } }
gpl-3.0
timomer/HAPP
app/src/main/java/com/hypodiabetic/happ/services/FiveMinService.java
5310
package com.hypodiabetic.happ.services; import android.app.IntentService; import android.content.Intent; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import com.crashlytics.android.Crashlytics; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.hypodiabetic.happ.MainApp; import com.hypodiabetic.happ.Notifications; import com.hypodiabetic.happ.Objects.APSResult; import com.hypodiabetic.happ.Objects.Carb; import com.hypodiabetic.happ.Objects.Profile; import com.hypodiabetic.happ.Objects.Pump; import com.hypodiabetic.happ.Objects.RealmManager; import com.hypodiabetic.happ.Objects.Stat; import com.hypodiabetic.happ.Objects.Serializers.StatSerializer; import com.hypodiabetic.happ.Objects.TempBasal; import com.hypodiabetic.happ.integration.IntegrationsManager; import com.hypodiabetic.happ.Intents; import com.hypodiabetic.happ.integration.openaps.IOB; import org.json.JSONObject; import java.util.Date; /** * Created by Tim on 15/02/2016. */ public class FiveMinService extends IntentService { private static final String TAG = "FiveMinService"; private Profile profile; private Date date; private RealmManager realmManager; public FiveMinService() { super(FiveMinService.class.getName()); } @Override protected void onHandleIntent(Intent intent) { Log.d(TAG, "Service Started"); date = new Date(); profile = new Profile(date); realmManager = new RealmManager(); newStat(); //Save a new Stat Object checkTBRNotify(); //checks if a Cancel TBR Notification is active and TBR is not running anymore IntegrationsManager.checkOldInsulinIntegration(realmManager.getRealm()); //Check if there are any old Insulin Integration requests waiting to be synced IntegrationsManager.updatexDripWatchFace(realmManager.getRealm(), profile); //Updates xDrip Watch Face // TODO: 11/08/2016 Service appears to be killed after some hours by the system, we then lose CGM Receivers, etc. //Starts the service if its not running startService(new Intent(this, BackgroundService.class)); realmManager.closeRealm(); Log.d(TAG, "Service Finished"); } public void checkTBRNotify(){ if (profile.temp_basal_notification){ Pump pump = new Pump(profile, realmManager.getRealm()); APSResult apsResult = APSResult.last(realmManager.getRealm()); if (apsResult != null) { if (!pump.temp_basal_active && !apsResult.getAccepted() && apsResult.checkIsCancelRequest()) { Notifications.clear("newTemp"); realmManager.getRealm().beginTransaction(); apsResult.setAccepted(true); realmManager.getRealm().commitTransaction(); } } } } public void newStat(){ Stat stat = new Stat(); JSONObject iobJSONValue = IOB.iobTotal(profile, date, realmManager.getRealm()); JSONObject cobJSONValue = Carb.getCOB(profile, date, realmManager.getRealm()); TempBasal currentTempBasal = TempBasal.getCurrentActive(date, realmManager.getRealm()); Boolean error = false; try { stat.setIob (iobJSONValue.getDouble("iob")); stat.setBolus_iob (iobJSONValue.getDouble("bolusiob")); stat.setCob (cobJSONValue.getDouble("display")); stat.setBasal (profile.getCurrentBasal()); stat.setTemp_basal (currentTempBasal.getRate()); stat.setTemp_basal_type (currentTempBasal.getBasal_adjustemnt()); } catch (Exception e) { error = true; Crashlytics.logException(e); Log.d(TAG, "Service error " + e.getLocalizedMessage()); } finally { if (!error) { realmManager.getRealm().beginTransaction(); realmManager.getRealm().copyToRealm(stat); realmManager.getRealm().commitTransaction(); try { Gson gson = new GsonBuilder() .registerTypeAdapter(Class.forName("io.realm.StatRealmProxy"), new StatSerializer()) .create(); //sends result to update UI if loaded Intent intent = new Intent(Intents.UI_UPDATE); intent.putExtra("UPDATE", "NEW_STAT_UPDATE"); intent.putExtra("stat", gson.toJson(stat, Stat.class)); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); } catch (ClassNotFoundException e){ Log.e(TAG, "Error creating gson object: " + e.getLocalizedMessage()); } //send results to xDrip WF IntegrationsManager.updatexDripWatchFace(realmManager.getRealm(), profile); Log.d(TAG, "New Stat Saved"); } } } }
gpl-3.0
Reikion/sop
src/supervisor/package-info.java
85
/** * Contains Layer 5 - supervising process implementation. */ package supervisor;
gpl-3.0
NocBross/dec-net
utility/src/test/java/connection/IPAddressDataTest.java
2298
package test.java.connection; import org.junit.Assert; import org.junit.Test; import main.java.connection.IPAddressData; public class IPAddressDataTest { @Test public void test() { int activePort = 26000; int externalPort = 45978; int localPort = activePort; String activeAddress = "192.168.2.100"; String externalAddress = "45.156.211.1"; String localeAddress = activeAddress; IPAddressData data = new IPAddressData(); // test initial values Assert.assertEquals(-1, data.getActivePort()); Assert.assertEquals(-1, data.getExternalPort()); Assert.assertEquals(-1, data.getLocalPort()); Assert.assertNull(data.getActiveAddress()); Assert.assertNull(data.getExternalAddress()); Assert.assertNull(data.getLocalAddress()); // test active port methods data.setActivePort(1); Assert.assertEquals(1, data.getActivePort()); data.setActivePort(activePort); Assert.assertEquals(activePort, data.getActivePort()); // test external port data.setExternalPort(1); Assert.assertEquals(1, data.getExternalPort()); data.setExternalPort(externalPort); Assert.assertEquals(externalPort, data.getExternalPort()); // test external port data.setLocalPort(1); Assert.assertEquals(1, data.getLocalPort()); data.setLocalPort(localPort); Assert.assertEquals(localPort, data.getLocalPort()); // test active address methods data.setActiveAddress("test"); Assert.assertEquals("test", data.getActiveAddress()); data.setActiveAddress(activeAddress); Assert.assertEquals(activeAddress, data.getActiveAddress()); // test external address methods data.setExternalAddress("test"); Assert.assertEquals("test", data.getExternalAddress()); data.setExternalAddress(externalAddress); Assert.assertEquals(externalAddress, data.getExternalAddress()); // test local address methods data.setLocalAddress("test"); Assert.assertEquals("test", data.getLocalAddress()); data.setLocalAddress(localeAddress); Assert.assertEquals(localeAddress, data.getLocalAddress()); } }
gpl-3.0
neo4j-contrib/neo4j-graph-algorithms
core/src/main/java/org/neo4j/graphalgo/core/huge/loader/PagedPropertyMap.java
4162
/* * Copyright (c) 2017 "Neo4j, Inc." <http://neo4j.com> * * This file is part of Neo4j Graph Algorithms <http://github.com/neo4j-contrib/neo4j-graph-algorithms>. * * Neo4j Graph Algorithms is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.graphalgo.core.huge.loader; import com.carrotsearch.hppc.IntDoubleMap; import org.neo4j.graphalgo.core.utils.container.TrackingIntDoubleHashMap; import org.neo4j.graphalgo.core.utils.paged.AllocationTracker; import org.neo4j.graphalgo.core.utils.paged.HugeLongArray; import org.neo4j.graphalgo.core.utils.paged.PageUtil; import static org.neo4j.graphalgo.core.utils.paged.MemoryUsage.shallowSizeOfInstance; import static org.neo4j.graphalgo.core.utils.paged.MemoryUsage.sizeOfObjectArray; final class PagedPropertyMap { private static final int PAGE_SHIFT = 14; private static final int PAGE_SIZE = 1 << PAGE_SHIFT; private static final long PAGE_MASK = (long) (PAGE_SIZE - 1); static PagedPropertyMap of(long size, AllocationTracker tracker) { int numPages = PageUtil.numPagesFor(size, PAGE_SHIFT, PAGE_MASK); TrackingIntDoubleHashMap[] pages = new TrackingIntDoubleHashMap[numPages]; tracker.add(shallowSizeOfInstance(HugeLongArray.class)); tracker.add(sizeOfObjectArray(numPages)); return new PagedPropertyMap(size, pages, tracker); } private final long size; private final AllocationTracker tracker; private TrackingIntDoubleHashMap[] pages; private PagedPropertyMap( long size, TrackingIntDoubleHashMap[] pages, AllocationTracker tracker) { this.size = size; this.pages = pages; this.tracker = tracker; } public double getOrDefault(long index, double defaultValue) { assert index < size; int pageIndex = pageIndex(index); int indexInPage = indexInPage(index); IntDoubleMap page = pages[pageIndex]; return page == null ? defaultValue : page.getOrDefault(indexInPage, defaultValue); } public void put(long index, double value) { assert index < size; int pageIndex = pageIndex(index); int indexInPage = indexInPage(index); TrackingIntDoubleHashMap subMap = subMap(pageIndex); subMap.putSync(indexInPage, value); } private TrackingIntDoubleHashMap subMap(int pageIndex) { TrackingIntDoubleHashMap subMap = pages[pageIndex]; if (subMap != null) { return subMap; } return forceNewSubMap(pageIndex); } private synchronized TrackingIntDoubleHashMap forceNewSubMap(int pageIndex) { TrackingIntDoubleHashMap subMap = pages[pageIndex]; if (subMap == null) { subMap = new TrackingIntDoubleHashMap(tracker); pages[pageIndex] = subMap; } return subMap; } public long size() { return size; } public long release() { if (pages != null) { TrackingIntDoubleHashMap[] pages = this.pages; this.pages = null; long released = sizeOfObjectArray(pages.length); for (TrackingIntDoubleHashMap page : pages) { if (page != null) { released += page.instanceSize(); } } return released; } return 0L; } private static int pageIndex(long index) { return (int) (index >>> PAGE_SHIFT); } private static int indexInPage(long index) { return (int) (index & PAGE_MASK); } }
gpl-3.0
Hpcrusher/SecurityCraft
src/main/java/com/hpcrusher/securitycraft/client/gui/ModGuiConfig.java
759
package com.hpcrusher.securitycraft.client.gui; import com.hpcrusher.securitycraft.handler.ConfigurationHandler; import com.hpcrusher.securitycraft.reference.Reference; import net.minecraft.client.gui.GuiScreen; import net.minecraftforge.common.config.ConfigElement; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.client.config.GuiConfig; /** * @author Hpcrusher */ public class ModGuiConfig extends GuiConfig { public ModGuiConfig(GuiScreen guiScreen) { super(guiScreen, new ConfigElement(ConfigurationHandler.config.getCategory(Configuration.CATEGORY_GENERAL)).getChildElements(), Reference.MOD_ID, null, false, false, GuiConfig.getAbridgedConfigPath(ConfigurationHandler.config.toString())); } }
gpl-3.0
vpillac/vroom
VroomUtilities/src/vroom/common/utilities/optimization/IComponentHandler.java
3443
package vroom.common.utilities.optimization; import java.util.List; import vroom.common.utilities.IDisposable; /** * <code>IComponentHandler</code> is the interface for classes responsible for the handling of components in a generic * {@linkplain VariableComponentSearch variable component search}. * <p> * Creation date: 2 juil. 2010 - 20:11:22 * * @author Victor Pillac, <a href="http://uniandes.edu.co">Universidad de Los Andes</a>-<a * href="http://copa.uniandes.edu.co">Copa</a> <a href="http://www.emn.fr">Ecole des Mines de Nantes</a>-<a * href="http://www.irccyn.ec-nantes.fr/irccyn/d/en/equipes/Slp">SLP</a> * @version 1.0 * @param <S> */ public interface IComponentHandler<M> extends IDisposable { /** * <code>Outcome</code> is an enumeration of the possible outcomes resulting from the execution of a component. * <p> * Possible values are: {@link #NEW_BEST}, {@link #REJECTED}, {@link #ACCEPTED} * </p> * Creation date: 2 juil. 2010 - 20:11:22 * * @author Victor Pillac, <a href="http://uniandes.edu.co">Universidad de Los Andes</a>-<a * href="http://copa.uniandes.edu.co">Copa</a> <a href="http://www.emn.fr">Ecole des Mines de Nantes</a>-<a * href="http://www.irccyn.ec-nantes.fr/irccyn/d/en/equipes/Slp">SLP</a> * @version 1.0 */ public static enum Outcome { NEW_BEST, REJECTED, ACCEPTED } /** * Getter for the list of components * * @return the list containing the components */ public List<M> getComponents(); /** * Selects the next component and return it * * @return the next component to be used or <code>null</code> if all components have been used */ public M nextComponent(); /** * Return <code>true</code> if all components have been used * * @return <code>true</code> if all components have been used */ public boolean isCompletelyExplored(); /** * Update the handler state at the end of an iteration * * @param currentComponent * the last used component * @param improvement * the improvement in the objective function in the last iteration. Independently of optimization * direction positive values are considered as improvement. * @param time * the time spent on the last iteration (in ms) * @param iteration * the last iteration number * @param outcome * the result * @return <code>true</code> if the update changed the possible output of the next call to {@link #nextComponent()} */ public boolean updateStats(M currentComponent, double improvement, double time, int iteration, Outcome outcome); /** * Returns the weight associated with a given component. * <p> * The weight of a component should reflect the likelihood of being selected at the next call of * {@link #nextComponent()} * </p> * * @param component * the component to be evaluated * @return the weight of <code>component</code> */ public double getWeight(M component); /** * Initialize the handler * * @param instance * the instance that will be used */ public void initialize(IInstance instance); /** * Reset the handler */ public void reset(); }
gpl-3.0
sehrgut/sgcore
src/com/alphahelical/bukkit/sgcore/package-info.java
109
/** * SGCore Bukkit plugin */ /** * @author kbeckman * */ package com.alphahelical.bukkit.sgcore;
gpl-3.0
jogjayr/InTEL-Project
Statics/src/edu/gatech/newbeans/Encoder.java
12102
/* * Copyright 2000-2006 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package edu.gatech.newbeans; import java.util.*; /** * An <code>Encoder</code> is a class which can be used to create * files or streams that encode the state of a collection of * JavaBeans in terms of their public APIs. The <code>Encoder</code>, * in conjunction with its persistence delegates, is responsible for * breaking the object graph down into a series of <code>Statements</code>s * and <code>Expression</code>s which can be used to create it. * A subclass typically provides a syntax for these expressions * using some human readable form - like Java source code or XML. * * @since 1.4 * * @version 1.3 11/15/00 * @author Philip Milne */ public class Encoder { private Map bindings = new IdentityHashMap(); private ExceptionListener exceptionListener; boolean executeStatements = true; private Map attributes; /** * Write the specified object to the output stream. * The serialized form will denote a series of * expressions, the combined effect of which will create * an equivalent object when the input stream is read. * By default, the object is assumed to be a <em>JavaBean</em> * with a nullary constructor, whose state is defined by * the matching pairs of "setter" and "getter" methods * returned by the Introspector. * * @param o The object to be written to the stream. * * @see XMLDecoder#readObject */ protected void writeObject(Object o) { if (o == this) { return; } PersistenceDelegate info = getPersistenceDelegate(o == null ? null : o.getClass()); info.writeObject(o, this); } /** * Sets the exception handler for this stream to <code>exceptionListener</code>. * The exception handler is notified when this stream catches recoverable * exceptions. * * @param exceptionListener The exception handler for this stream; * if <code>null</code> the default exception listener will be used. * * @see #getExceptionListener */ public void setExceptionListener(ExceptionListener exceptionListener) { this.exceptionListener = exceptionListener; } /** * Gets the exception handler for this stream. * * @return The exception handler for this stream; * Will return the default exception listener if this has not explicitly been set. * * @see #setExceptionListener */ public ExceptionListener getExceptionListener() { return (exceptionListener != null) ? exceptionListener : Statement.defaultExceptionListener; } public Object getValue(Expression exp) { try { return (exp == null) ? null : exp.getValue(); } catch (Exception e) { getExceptionListener().exceptionThrown(e); throw new RuntimeException("failed to evaluate: " + exp.toString()); } } /** * Returns the persistence delegate for the given type. * The persistence delegate is calculated * by applying the following of rules in order: * <ul> * <li> * If the type is an array, an internal persistence * delegate is returned which will instantiate an * array of the appropriate type and length, initializing * each of its elements as if they are properties. * <li> * If the type is a proxy, an internal persistence * delegate is returned which will instantiate a * new proxy instance using the static * "newProxyInstance" method defined in the * Proxy class. * <li> * If the BeanInfo for this type has a <code>BeanDescriptor</code> * which defined a "persistenceDelegate" property, this * value is returned. * <li> * In all other cases the default persistence delegate * is returned. The default persistence delegate assumes * the type is a <em>JavaBean</em>, implying that it has a default constructor * and that its state may be characterized by the matching pairs * of "setter" and "getter" methods returned by the Introspector. * The default constructor is the constructor with the greatest number * of parameters that has the {@link ConstructorProperties} annotation. * If none of the constructors have the {@code ConstructorProperties} annotation, * then the nullary constructor (constructor with no parameters) will be used. * For example, in the following the nullary constructor * for {@code Foo} will be used, while the two parameter constructor * for {@code Bar} will be used. * <code> * public class Foo { * public Foo() { ... } * public Foo(int x) { ... } * } * public class Bar { * public Bar() { ... } * @ConstructorProperties({"x"}) * public Bar(int x) { ... } * @ConstructorProperties({"x", "y"}) * public Bar(int x, int y) { ... } * } * </code> * </ul> * * @param type The type of the object. * @return The persistence delegate for this type of object. * * @see #setPersistenceDelegate * @see java.beans.Introspector#getBeanInfo * @see java.beans.BeanInfo#getBeanDescriptor */ public PersistenceDelegate getPersistenceDelegate(Class<?> type) { return MetaData.getPersistenceDelegate(type); } /** * Sets the persistence delegate associated with this <code>type</code> to * <code>persistenceDelegate</code>. * * @param type The class of objects that <code>persistenceDelegate</code> applies to. * @param persistenceDelegate The persistence delegate for instances of <code>type</code>. * * @see #getPersistenceDelegate * @see java.beans.Introspector#getBeanInfo * @see java.beans.BeanInfo#getBeanDescriptor */ public void setPersistenceDelegate(Class<?> type, PersistenceDelegate persistenceDelegate) { MetaData.setPersistenceDelegate(type, persistenceDelegate); } /** * Removes the entry for this instance, returning the old entry. * * @param oldInstance The entry that should be removed. * @return The entry that was removed. * * @see #get */ public Object remove(Object oldInstance) { Expression exp = (Expression)bindings.remove(oldInstance); return getValue(exp); } /** * Returns a tentative value for <code>oldInstance</code> in * the environment created by this stream. A persistence * delegate can use its <code>mutatesTo</code> method to * determine whether this value may be initialized to * form the equivalent object at the output or whether * a new object must be instantiated afresh. If the * stream has not yet seen this value, null is returned. * * @param oldInstance The instance to be looked up. * @return The object, null if the object has not been seen before. */ public Object get(Object oldInstance) { if (oldInstance == null || oldInstance == this || oldInstance.getClass() == String.class) { return oldInstance; } Expression exp = (Expression)bindings.get(oldInstance); return getValue(exp); } private Object writeObject1(Object oldInstance) { Object o = get(oldInstance); if (o == null) { writeObject(oldInstance); o = get(oldInstance); } return o; } private Statement cloneStatement(Statement oldExp) { Object oldTarget = oldExp.getTarget(); Object newTarget = writeObject1(oldTarget); Object[] oldArgs = oldExp.getArguments(); Object[] newArgs = new Object[oldArgs.length]; for (int i = 0; i < oldArgs.length; i++) { newArgs[i] = writeObject1(oldArgs[i]); } if (oldExp.getClass() == Statement.class) { return new Statement(newTarget, oldExp.getMethodName(), newArgs); } else { return new Expression(newTarget, oldExp.getMethodName(), newArgs); } } /** * Writes statement <code>oldStm</code> to the stream. * The <code>oldStm</code> should be written entirely * in terms of the callers environment, i.e. the * target and all arguments should be part of the * object graph being written. These expressions * represent a series of "what happened" expressions * which tell the output stream how to produce an * object graph like the original. * <p> * The implementation of this method will produce * a second expression to represent the same expression in * an environment that will exist when the stream is read. * This is achieved simply by calling <code>writeObject</code> * on the target and all the arguments and building a new * expression with the results. * * @param oldStm The expression to be written to the stream. */ public void writeStatement(Statement oldStm) { // System.out.println("writeStatement: " + oldExp); Statement newStm = cloneStatement(oldStm); if (oldStm.getTarget() != this && executeStatements) { try { newStm.execute(); } catch (Exception e) { getExceptionListener().exceptionThrown(new Exception("Encoder: discarding statement " + newStm, e)); } } } /** * The implementation first checks to see if an * expression with this value has already been written. * If not, the expression is cloned, using * the same procedure as <code>writeStatement</code>, * and the value of this expression is reconciled * with the value of the cloned expression * by calling <code>writeObject</code>. * * @param oldExp The expression to be written to the stream. */ public void writeExpression(Expression oldExp) { // System.out.println("Encoder::writeExpression: " + oldExp); Object oldValue = getValue(oldExp); if (get(oldValue) != null) { return; } bindings.put(oldValue, (Expression)cloneStatement(oldExp)); writeObject(oldValue); } void clear() { bindings.clear(); } // Package private method for setting an attributes table for the encoder void setAttribute(Object key, Object value) { if (attributes == null) { attributes = new HashMap(); } attributes.put(key, value); } Object getAttribute(Object key) { if (attributes == null) { return null; } return attributes.get(key); } }
gpl-3.0
jbundle/jbundle
app/program/packages/src/main/java/org/jbundle/app/program/packages/db/Part.java
4158
/** * @(#)Part. * Copyright © 2013 jbundle.org. All rights reserved. * GPL3 Open Source Software License. */ package org.jbundle.app.program.packages.db; import java.util.*; import org.jbundle.base.db.*; import org.jbundle.thin.base.util.*; import org.jbundle.thin.base.db.*; import org.jbundle.base.db.event.*; import org.jbundle.base.db.filter.*; import org.jbundle.base.field.*; import org.jbundle.base.field.convert.*; import org.jbundle.base.field.event.*; import org.jbundle.base.model.*; import org.jbundle.base.util.*; import org.jbundle.model.*; import org.jbundle.model.db.*; import org.jbundle.model.screen.*; import org.jbundle.model.app.program.packages.db.*; /** * Part - Parts. */ public class Part extends VirtualRecord implements PartModel { private static final long serialVersionUID = 1L; /** * Default constructor. */ public Part() { super(); } /** * Constructor. */ public Part(RecordOwner screen) { this(); this.init(screen); } /** * Initialize class fields. */ public void init(RecordOwner screen) { super.init(screen); } /** * Get the table name. */ public String getTableNames(boolean bAddQuotes) { return (m_tableName == null) ? Record.formatTableNames(PART_FILE, bAddQuotes) : super.getTableNames(bAddQuotes); } /** * Get the Database Name. */ public String getDatabaseName() { return "program"; } /** * Is this a local (vs remote) file?. */ public int getDatabaseType() { return DBConstants.REMOTE | DBConstants.USER_DATA; } /** * Add this field in the Record's field sequence. */ public BaseField setupField(int iFieldSeq) { BaseField field = null; //if (iFieldSeq == 0) //{ // field = new CounterField(this, ID, Constants.DEFAULT_FIELD_LENGTH, null, null); // field.setHidden(true); //} //if (iFieldSeq == 1) //{ // field = new RecordChangedField(this, LAST_CHANGED, Constants.DEFAULT_FIELD_LENGTH, null, null); // field.setHidden(true); //} //if (iFieldSeq == 2) //{ // field = new BooleanField(this, DELETED, Constants.DEFAULT_FIELD_LENGTH, null, new Boolean(false)); // field.setHidden(true); //} if (iFieldSeq == 3) field = new StringField(this, DESCRIPTION, 60, null, null); if (iFieldSeq == 4) field = new IntegerField(this, SEQUENCE, Constants.DEFAULT_FIELD_LENGTH, null, null); if (iFieldSeq == 5) field = new StringField(this, KIND, 10, null, null); if (iFieldSeq == 6) field = new PartTypeField(this, PART_TYPE, Constants.DEFAULT_FIELD_LENGTH, null, null); if (iFieldSeq == 7) field = new JnlpFileField(this, JNLP_FILE_ID, Constants.DEFAULT_FIELD_LENGTH, null, null); if (iFieldSeq == 8) field = new StringField(this, PATH, 128, null, null); if (field == null) field = super.setupField(iFieldSeq); return field; } /** * Add this key area description to the Record. */ public KeyArea setupKey(int iKeyArea) { KeyArea keyArea = null; if (iKeyArea == 0) { keyArea = this.makeIndex(DBConstants.UNIQUE, ID_KEY); keyArea.addKeyField(ID, DBConstants.ASCENDING); } if (iKeyArea == 1) { keyArea = this.makeIndex(DBConstants.NOT_UNIQUE, DESCRIPTION_KEY); keyArea.addKeyField(DESCRIPTION, DBConstants.ASCENDING); } if (iKeyArea == 2) { keyArea = this.makeIndex(DBConstants.NOT_UNIQUE, JNLP_FILE_ID_KEY); keyArea.addKeyField(JNLP_FILE_ID, DBConstants.ASCENDING); keyArea.addKeyField(SEQUENCE, DBConstants.ASCENDING); keyArea.addKeyField(DESCRIPTION, DBConstants.ASCENDING); } if (keyArea == null) keyArea = super.setupKey(iKeyArea); return keyArea; } }
gpl-3.0
gitools/gitools
org.gitools.ui.core/src/main/java/org/gitools/ui/core/components/wizard/AnalysisWizard.java
1075
/* * #%L * org.gitools.ui.app * %% * Copyright (C) 2013 - 2014 Universitat Pompeu Fabra - Biomedical Genomics group * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ package org.gitools.ui.core.components.wizard; import org.gitools.api.analysis.IAnalysis; import org.gitools.ui.platform.wizard.AbstractWizard; public abstract class AnalysisWizard<A extends IAnalysis> extends AbstractWizard { public abstract A createAnalysis(); }
gpl-3.0
Link184/Respiration
respiration-firebase/src/test/java/com/link184/respiration/ConfigurationTest.java
1157
package com.link184.respiration; import com.link184.respiration.local.LocalConfiguration; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.io.File; /** * Created by eugeniu on 3/6/18. */ @RunWith(JUnit4.class) public class ConfigurationTest { @Test public void testLocalConfiguration() throws Exception { final String folderName = "folderName"; final String fileName = "fileName.json"; LocalConfiguration<Object> localConfiguration = new LocalConfiguration<>(Object.class); localConfiguration.setAssetDbFilePath(folderName + File.separator + fileName); assertEquals(fileName, localConfiguration.getDbName()); localConfiguration.setAssetDbFilePath(fileName); assertEquals(fileName, localConfiguration.getDbName()); localConfiguration.setAssetDbFilePath(File.separator + folderName + File.separator + fileName); assertEquals(fileName, localConfiguration.getDbName()); localConfiguration.setAssetDbFilePath(folderName + "/" + fileName); assertEquals(fileName, localConfiguration.getDbName()); } }
gpl-3.0
Egosife/DuldulEMR
DuldulEMR/src/com/duldul/emr/web/emr/service/TreatmentService.java
3467
package com.duldul.emr.web.emr.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.duldul.emr.web.emr.dao.ITreatmentDao; @Service public class TreatmentService implements ITreatmentService { @Autowired public ITreatmentDao iTreatmentDao; @Override public ArrayList<HashMap<String, String>> getPatient(HashMap<String, String> params) throws Throwable { return iTreatmentDao.getPatient(params); } @Override public HashMap<String, String> getPatient_info(HashMap<String, String> params) throws Throwable { return iTreatmentDao.getPatient_info(params); } @Override public String treat_commit(HashMap<String, String> params) throws Throwable { return iTreatmentDao.treat_commit(params); } @Override public String treat_commit_time(HashMap<String, String> params) throws Throwable { return iTreatmentDao.treat_commit_time(params); } @Override public HashMap<String, String> getTreatSEQ() throws Throwable { return iTreatmentDao.getTreatSEQ(); } @Override public ArrayList<HashMap<String, String>> getTreatType() throws Throwable { return iTreatmentDao.getTreatType(); } @Override public ArrayList<HashMap<String, String>> gettreatsort_type() throws Throwable { return iTreatmentDao.gettreatsort_type(); } @Override public ArrayList<HashMap<String, String>> getdoctor(HashMap<String, String> params) throws Throwable { return iTreatmentDao.getdoctor(params); } @Override public HashMap<String, String> getpatiinfo(HashMap<String, String> params) throws Throwable { return iTreatmentDao.getpatiinfo(params); } @Override public ArrayList<HashMap<String, String>> gettreatinfo(HashMap<String, String> params) throws Throwable { return iTreatmentDao.gettreatinfo(params); } @Override public ArrayList<HashMap<String, String>> getpillinfo(HashMap<String, String> params) throws Throwable { return iTreatmentDao.getpillinfo(params); } @Override public String inserttreathis(HashMap<String, String> params) throws Throwable { return iTreatmentDao.inserttreathis(params); } @Override public int updatetreat(HashMap<String, String> params) throws Throwable { return iTreatmentDao.updatetreat(params); } @Override public String inserttreatmore(HashMap<String, String> params) throws Throwable { return iTreatmentDao.inserttreatmore(params); } @Override public String inserttreatcare(List<String> patinum, List<String> treatnum, List<String> treatcare) throws Throwable { return iTreatmentDao.inserttreatcare(patinum,treatnum,treatcare); } @Override public String inserttreatpill(List<String> patinum, List<String> treatnum, List<String> treatpill) throws Throwable { return iTreatmentDao.inserttreatpill(patinum,treatnum,treatpill); } @Override public ArrayList<HashMap<String, String>> getcareinfo(HashMap<String, String> params) throws Throwable { return iTreatmentDao.getcareinfo(params); } @Override public ArrayList<HashMap<String, String>> getTodayTreat(HashMap<String, String> params) throws Throwable { return iTreatmentDao.getTodayTreat(params); } @Override public int updatetime(HashMap<String, String> params) throws Throwable { return iTreatmentDao.updatetime(params); } }
gpl-3.0
ArthurPons/FakeSteam
FakeSteam/src/dao/ConsoleDaoImpl.java
4292
package dao; import static dao.DaoTools.*; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import bean.Console; public class ConsoleDaoImpl implements ConsoleDao{ private static DaoFactory daoFactory; private static final String SQL_SELECT_BY_ID = "SELECT * FROM console WHERE id_console = ?"; private static final String SQL_INSERT = "INSERT INTO console (name_console) VALUES (?)"; private static final String SQL_SELECT_ALL = "SELECT * FROM console"; public ConsoleDaoImpl() { daoFactory= DaoFactory.getInstance(); } public ConsoleDaoImpl(DaoFactory dao) { daoFactory=dao; } @Override public void create( Console console ) throws DaoException { Connection connexion = null; PreparedStatement preparedStatement = null; ResultSet valeursAutoGenerees = null; try { /* Récupération d'une connexion depuis la Factory */ connexion = daoFactory.getConnection(); preparedStatement = initialisationRequetePreparee( connexion, SQL_INSERT, true, console.getNameConsole()); int statut = preparedStatement.executeUpdate(); /* Analyse du statut retourné par la requête d'insertion */ if ( statut == 0 ) { throw new DaoException( "Échec de la création de la console, aucune ligne ajoutée dans la table." ); } /* Récupération de l'id auto-généré par la requête d'insertion */ valeursAutoGenerees = preparedStatement.getGeneratedKeys(); if ( valeursAutoGenerees.next() ) { /* Puis initialisation de la propriété id du bean Console avec sa valeur */ console.setIdConsole((int) valeursAutoGenerees.getLong( 1 ) ); } else { throw new DaoException( "Échec de la création de la console, aucun ID auto-généré retourné." ); } } catch ( SQLException e ) { throw new DaoException( e ); } finally { fermeturesSilencieuses( valeursAutoGenerees, preparedStatement, connexion ); } } @Override public Console find( int id ) throws DaoException { Connection connexion = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; Console console = null; try { /* Récupération d'une connexion depuis la Factory */ connexion = daoFactory.getConnection(); preparedStatement = initialisationRequetePreparee( connexion, SQL_SELECT_BY_ID, false, id ); resultSet = preparedStatement.executeQuery(); /* Parcours de la ligne de données de l'éventuel ResulSet retourné */ if ( resultSet.next() ) { console = map( resultSet ); } } catch ( SQLException e ) { throw new DaoException( e ); } finally { fermeturesSilencieuses( resultSet, preparedStatement, connexion ); } return console; } public List<Console> findAll () throws DaoException { Connection connexion = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; Console console = null; List<Console> listOfConsole = new ArrayList<Console>(); try { /* Récupération d'une connexion depuis la Factory */ connexion = daoFactory.getConnection(); preparedStatement = initialisationRequetePreparee(connexion, SQL_SELECT_ALL, false); resultSet = preparedStatement.executeQuery(); /* Parcours de la ligne de données de l'éventuel ResulSet retourné */ while ( resultSet.next() ) { console = map( resultSet ); listOfConsole.add(console); } } catch ( SQLException e ) { throw new DaoException( e ); } finally { fermeturesSilencieuses( resultSet, preparedStatement, connexion ); } return listOfConsole; } private static Console map( ResultSet resultSet ) throws SQLException { Console console = new Console(); console.setIdConsole( resultSet.getInt( "id_console" ) ); console.setNameConsole( resultSet.getString("name_console") ); //recherche de l'objet game (id puis objet) int consoleId = resultSet.getInt("id_console"); System.out.print("console : "+consoleId+"\n"); return console; } }
gpl-3.0
opentechnologynet/triki
triki-image/src/main/groovy/net/opentechnology/triki/image/loader/ImageImporter.java
12481
/************************************************************************************ * * This file is part of triki * * Written by Donald McIntosh (dbm@opentechnology.net) * * triki is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * triki is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with triki. If not, see <http://www.gnu.org/licenses/>. * ************************************************************************************/ package net.opentechnology.triki.image.loader; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import javax.imageio.ImageIO; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.commons.io.FileUtils; import org.apache.jena.rdf.model.Literal; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.rdf.model.Resource; import org.apache.jena.sparql.vocabulary.FOAF; import org.apache.jena.vocabulary.DCTerms; import org.apache.log4j.Logger; import org.imgscalr.Scalr; import com.drew.imaging.ImageMetadataReader; import com.drew.imaging.ImageProcessingException; import com.drew.metadata.Directory; import com.drew.metadata.Metadata; import com.drew.metadata.MetadataException; import com.drew.metadata.Tag; import com.drew.metadata.exif.ExifSubIFDDirectory; import net.opentechnology.triki.core.model.ModelException; import net.opentechnology.triki.schema.Exif; import net.opentechnology.triki.schema.Time; import net.opentechnology.triki.schema.Triki; public class ImageImporter { String resourcePrefix = "/resource/"; String imagePrefix = "/image/"; Logger logger = Logger.getLogger(this.getClass()); Model model = ModelFactory.createDefaultModel(); private final String scanDir; private final String outDir; private final String baseUrl; private final String creator; private final String outFilename; private final String[] restricted; public ImageImporter(PropertiesConfiguration config){ scanDir = config.getString("photos_scanDir"); outDir = config.getString("photos_outDir"); baseUrl = config.getString("photos_baseUrl"); creator = config.getString("creator"); outFilename = config.getString("photos_outFilename"); restricted = config.getString("photos_restricted").split(" *, *"); } public ImageImporter(Model model, String outDir, String scanDir, String url, String creator, String outFilename, String[] restricted){ this.model = model; this.outDir = outDir; this.scanDir = scanDir; this.baseUrl = url; this.creator = creator; this.outFilename = outFilename; this.restricted = restricted; } public void importMetaData() { setPrefixes(); Iterator<File> images = FileUtils.iterateFiles(new File(scanDir), new String[] {"jpg", "JPG"}, true); try { while(images.hasNext()){ File imageFile = images.next(); String path = imageFile.getParent().replaceFirst(scanDir, outDir); File pathDir = new File(path); if(!pathDir.exists()){ pathDir.mkdirs(); } File outThumbnail = new File(path, getThumbName(imageFile.getName())); File outWeb = new File(path, getWebName(imageFile.getName())); if(!outThumbnail.exists() || !outWeb.exists()){ BufferedImage img = ImageIO.read(imageFile); if(!outThumbnail.exists()){ logger.info("Creating " + outThumbnail.getAbsolutePath()); BufferedImage thumbImg = createThumbnail(img); ImageIO.write(thumbImg, "jpg", outThumbnail); } if(!outWeb.exists()){ logger.info("Creating " + outWeb.getAbsolutePath()); BufferedImage webImg = createWeb(img); ImageIO.write(webImg, "jpg", outWeb); } } addImageResource(imageFile); } saveModel(); } catch (ModelException e) { logger.error("Problems with RDF model " , e); } catch (IOException e) { logger.error("IO problems " + e); } } private Resource addThumbnailResource(String fileName) { String thumbName = getThumbName(fileName); logger.info("Adding " + thumbName); String resname = resourcePrefix + thumbName; Resource image = model.createResource(baseUrl + resname, FOAF.Image); image.addProperty(Triki.content, imagePrefix + thumbName); return image; } private void addImageResource(File imageFile) { try { Metadata metadata = ImageMetadataReader.readMetadata(imageFile); Iterable<Directory> dirs = metadata.getDirectories(); boolean resourceAdded = false; for(Directory metadir: dirs){ //if(metadir.getName().equals("Exif SubIFD")){ resourceAdded = addResource(model, imageFile, metadir); //} //printAllTags(metadir.getName(), metadir); } if(!resourceAdded){ addSimpleResource(model, imageFile); } } catch (ImageProcessingException e) { logger.error("Problems processing file " + imageFile, e); } catch (IOException e) { logger.error("Problems accessing file " + imageFile, e); } } private void addSimpleResource(Model model, File jpg) { String webName = getWebName(jpg.getName()); String thumbName = getThumbName(jpg.getName()); logger.info("Adding " + webName); String resname = resourcePrefix + webName; Resource image = model.createResource(baseUrl + resname, FOAF.Image); image.addProperty(Triki.content, imagePrefix + webName); Resource thumbRes = addThumbnailResource(jpg.getName()); image.addProperty(Triki.thumbimg, thumbRes); //image.addProperty(Triki.restricted, Triki.publicUrl); } private String getThumbfileName(File imgFile){ String prefix = imgFile.getAbsolutePath().replaceFirst("\\..*", ""); String thumbFilename = prefix + "_thumb.JPG"; return thumbFilename; } private String getThumbName(String name){ String prefix = name.replaceFirst("\\..*", ""); String thumbFilename = prefix + "_thumb.JPG"; return thumbFilename; } private String getWebName(String name){ String prefix = name.replaceFirst("\\..*", ""); String thumbFilename = prefix + "_web.JPG"; return thumbFilename; } private String getWebfileName(File imgFile){ String prefix = imgFile.getAbsolutePath().replaceFirst("\\..*", ""); String thumbFilename = prefix + "_web.JPG"; return thumbFilename; } private void resizeImage(File imageFile) throws IOException { if(imageFile.getName().matches(".*_web.*") || imageFile.getName().matches(".*_thumb.*")){ logger.info("Skipping " + imageFile.getName()); return; } String thumbFilename = getThumbfileName(imageFile); String webFilename = getWebfileName(imageFile); File thumbFile = new File(thumbFilename); File webFile = new File(webFilename); if(!webFile.exists() || !thumbFile.exists()){ BufferedImage img = ImageIO.read(imageFile); if(!thumbFile.exists()){ logger.info("Creating " + thumbFilename); BufferedImage thumbImg = createThumbnail(img); ImageIO.write(thumbImg, "jpg", thumbFile); } if(!webFile.exists()){ logger.info("Creating " + webFilename); BufferedImage webImg = createWeb(img); ImageIO.write(webImg, "jpg", webFile); } } } private BufferedImage createWeb(BufferedImage img) { return Scalr.resize(img, Scalr.Method.SPEED, 2000, Scalr.OP_ANTIALIAS, Scalr.OP_BRIGHTER); } private BufferedImage createThumbnail(BufferedImage img) { return Scalr.resize(img, Scalr.Method.SPEED, 400, Scalr.OP_ANTIALIAS, Scalr.OP_BRIGHTER); } private void setPrefixes(){ model.setNsPrefix("resource", baseUrl + resourcePrefix); model.setNsPrefix("image", baseUrl + imagePrefix); model.setNsPrefix("exif", Exif.NS); model.setNsPrefix("dc", DCTerms.NS); model.setNsPrefix("triki", Triki.NS); model.setNsPrefix("time", Time.NS); model.setNsPrefix("foaf", FOAF.NS); model.setNsPrefix("xsd", "http://www.w3.org/2001/XMLSchema#"); } private void printAllTags(String name, Directory metadir){ for(Tag tag: metadir.getTags()){ logger.info(tag + " " + tag.getTagType() + " " + metadir.getDate(tag.getTagType())); } } private boolean addResource(Model model, File jpg, Directory metadir) { String webName = getWebName(jpg.getName()); String thumbName = getThumbName(jpg.getName()); //logger.info("Adding " + webName); try { String resname = resourcePrefix + webName; Resource image = model.createResource(baseUrl + resname, FOAF.Image); Date created = metadir.getDate(ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL); if(created != null){ Calendar timestampCal = Calendar.getInstance(); timestampCal.setTime(created); Literal timestampLiteral = model.createTypedLiteral(timestampCal); image.addProperty(DCTerms.created, timestampLiteral); } else { logger.warn("No timestamp for " + webName); } for(String restrict: restricted){ String prefix = restrict.replaceFirst(":.*$", ""); String suffix = restrict.replaceFirst("^.*:", ""); Resource restriction = model.createResource(model.getNsPrefixURI(prefix) + suffix); image.addProperty(Triki.restricted, restriction); } Resource creatorRes = model.createResource(creator, FOAF.Person); image.addProperty(DCTerms.creator, creatorRes); image.addProperty(DCTerms.title, jpg.getName()); image.addProperty(Triki.content, imagePrefix + webName); Resource thumbRes = addThumbnailResource(jpg.getName()); image.addProperty(Triki.thumbimg, thumbRes); if(metadir.getDate(ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL) != null){ image.addProperty(Exif.dateTimeOriginal, metadir.getDate(ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL).toString()); image.addProperty(Exif.width, Integer.toString(metadir.getInt(ExifSubIFDDirectory.TAG_EXIF_IMAGE_WIDTH))); image.addProperty(Exif.height, Integer.toString(metadir.getInt(ExifSubIFDDirectory.TAG_EXIF_IMAGE_HEIGHT))); } if(created != null){ indexDate(image, created); } } catch(MetadataException e){ logger.error("Problems reading meta data for " + jpg, e); } return true; } private void indexDate(Resource image, Date created) { SimpleDateFormat monFormat = new SimpleDateFormat("MMMMM"); String month = monFormat.format(created); SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy"); String year = yearFormat.format(created); String monthResName = resourcePrefix + year + month; Resource monthRes = model.createResource(baseUrl + monthResName, Time.Instant); monthRes.addLiteral(DCTerms.description, month + " " + year); monthRes.addLiteral(DCTerms.title, month + " " + year); monthRes.addProperty(Time.month, month); String yearResName = resourcePrefix + year; Resource yearRes = model.createResource(baseUrl + yearResName, Time.Instant); yearRes.addLiteral(DCTerms.description, year); yearRes.addLiteral(DCTerms.title, year); yearRes.addProperty(Time.year, year); for(String restrict: restricted){ String prefix = restrict.replaceFirst(":.*$", ""); String suffix = restrict.replaceFirst("^.*:", ""); Resource restriction = model.createResource(model.getNsPrefixURI(prefix) + suffix); monthRes.addProperty(Triki.restricted, restriction); yearRes.addProperty(Triki.restricted, restriction); } monthRes.addProperty(Time.year, yearRes); image.addProperty(Time.month, monthRes); } private void saveModel() throws ModelException { File outFile = new File(outFilename); try { FileOutputStream fos = new FileOutputStream(outFile); model.write(fos, "TURTLE"); } catch (FileNotFoundException e) { throw new ModelException("Could not save file due to " + e.getMessage()); } } public static void main(String[] args){ ImageImporter ii; String propsFile = System.getProperty("propsPath"); try { PropertiesConfiguration config = new PropertiesConfiguration(propsFile); ii = new ImageImporter(config); ii.importMetaData(); } catch (Exception e) { System.err.println(e); } } }
gpl-3.0
tvaughan77/trypaper-client
src/test/java/com/tbd/trypaper/client/responsehandlers/AbstractResponseHandlerTest.java
3234
package com.tbd.trypaper.client.responsehandlers; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.io.Resources; import com.tbd.trypaper.client.DefaultTryPaperClientBuilder; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.InputStream; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import static org.easymock.EasyMock.*; /** * <p>Common/reusable pieces across the tests for the different ResponseHandlers in this package</p> */ abstract class AbstractResponseHandlerTest { protected final ObjectMapper objectMapper = DefaultTryPaperClientBuilder.createDefaultObjectMapper(); /** * @param contentFixture A classpath resource containing whatever content the mock HttpEntity should stream back * from a call to its {@code getContent()} method. * @return A mock HttpEntity that will return an input stream with the contents of {@code contentFixture} * @throws Exception */ protected HttpEntity mockEntity(String contentFixture) throws Exception { InputStream inputStream = new BufferedInputStream(new FileInputStream(Resources.getResource(contentFixture).getFile())); HttpEntity entity = createStrictMock(HttpEntity.class); expect(entity.getContent()).andReturn(inputStream); replay(entity); return entity; } /** * @param statusLine * @param entity * @param headers An array of headers that is returned on <i>any</i> call to {@code HttpResponse.getHeaders( )} * @return A mock HttpResponse that will return the {@code statusLine}, {@code entity} and {@code headers} */ protected HttpResponse mockResponse(StatusLine statusLine, HttpEntity entity, Header[] headers) { HttpResponse response = createNiceMock(HttpResponse.class); expect(response.getStatusLine()).andReturn(statusLine).anyTimes(); expect(response.getEntity()).andReturn(entity).anyTimes(); expect(response.getHeaders(anyString())).andReturn(headers).anyTimes(); replay(response); return response; } /** * @param statusLine * @param entity * @return An HttpResponse returning status line {@code statusLine} and whatever content that's been set up in the * {@code entity} */ protected HttpResponse mockResponse(StatusLine statusLine, HttpEntity entity) { return mockResponse(statusLine, entity, null); } /** * @param statusLine * @return An HttpResponse returning just a status line but null entity content, null headers, null everything-else */ protected HttpResponse mockResponse(StatusLine statusLine) { return mockResponse(statusLine, null); } /** * @param responseCode * @return A mock StatusLine that returns {@code responseCode} when its {@code getStatusCode()} method is called */ protected StatusLine mockStatusLine(int responseCode) { StatusLine statusLine = createStrictMock(StatusLine.class); expect(statusLine.getStatusCode()).andReturn(responseCode); replay(statusLine); return statusLine; } }
gpl-3.0
CmdrStardust/Alite
src/de/phbouillon/android/games/alite/screens/opengl/objects/space/AIState.java
961
package de.phbouillon.android.games.alite.screens.opengl.objects.space; /* Alite - Discover the Universe on your Favorite Android Device * Copyright (C) 2015 Philipp Bouillon * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful and * fun, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see * http://http://www.gnu.org/licenses/gpl-3.0.txt. */ public enum AIState { IDLE, FLY_STRAIGHT, FLY_PATH, BANK, EVADE, TRACK, MISSILE_TRACK, ATTACK, FLEE, FOLLOW_CURVE }
gpl-3.0
wesklei/REC
REC_Lab7/src/main/java/com/br/rec_lab7/controller/Fibonacci.java
1474
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.br.rec_lab7.controller; /** * * @author Wesklei Migliorini <wesklei.m at gmail dt com> */ public class Fibonacci { private static int[] fibonacci; private int k = 1; private final int limite; /** * initialize to limite value of the serie * * @param limite */ public Fibonacci(int limite) { fibonacci = new int[limite + 1]; this.limite = limite; fibonacciSerie(limite); } /** * Recursive solution for fibonacci serie * * @param i * @return */ private long fibonacciSerie(int i) { if (i < 0) { return fibonacci[0]; } else { if (k < 3) { fibonacci[i] = k - 1; k++; } else { fibonacci[i] = fibonacci[i + 1] + fibonacci[i + 2]; } return fibonacciSerie(i - 1); } } /** * return the value at pos or null if has not been started at this pos * * @param pos * @return */ public synchronized Integer getPos(int pos) { if (pos < limite) { return fibonacci[limite - pos]; } else { return null; } } public int getLimite() { return limite; } }
gpl-3.0
silentbalanceyh/lyra
lyra-bus/util-comet/src/test/java/com/test/lyra/util/assist/CA2.java
90
package com.test.lyra.util.assist; public abstract class CA2 extends E{ // NOPMD }
gpl-3.0
brightmore/Chat
src/main/java/eu/siacs/conversations/parser/IqParser.java
4075
package eu.siacs.conversations.parser; import android.util.Log; import eu.siacs.conversations.Config; import eu.siacs.conversations.entities.Account; import eu.siacs.conversations.entities.Contact; import eu.siacs.conversations.services.XmppConnectionService; import eu.siacs.conversations.xml.Element; import eu.siacs.conversations.xmpp.OnIqPacketReceived; import eu.siacs.conversations.xmpp.jid.InvalidJidException; import eu.siacs.conversations.xmpp.jid.Jid; import eu.siacs.conversations.xmpp.stanzas.IqPacket; public class IqParser extends AbstractParser implements OnIqPacketReceived { public IqParser(XmppConnectionService service) { super(service); } public void rosterItems(Account account, Element query) { String version = query.getAttribute("ver"); if (version != null) { account.getRoster().setVersion(version); } for (Element item : query.getChildren()) { if (item.getName().equals("item")) { Jid jid; try { jid = Jid.fromString(item.getAttribute("jid")); } catch (final InvalidJidException e) { continue; } String name = item.getAttribute("name"); String subscription = item.getAttribute("subscription"); Contact contact = account.getRoster().getContact(jid); if (!contact.getOption(Contact.Options.DIRTY_PUSH)) { contact.setServerName(name); contact.parseGroupsFromElement(item); } if (subscription != null) { if (subscription.equals("remove")) { contact.resetOption(Contact.Options.IN_ROSTER); contact.resetOption(Contact.Options.DIRTY_DELETE); contact.resetOption(Contact.Options.PREEMPTIVE_GRANT); } else { contact.setOption(Contact.Options.IN_ROSTER); contact.resetOption(Contact.Options.DIRTY_PUSH); contact.parseSubscriptionFromElement(item); } } mXmppConnectionService.requestPresenceUpdatesIfMissing(contact); mXmppConnectionService.getAvatarService().clear(contact); } } mXmppConnectionService.updateConversationUi(); mXmppConnectionService.updateRosterUi(); } public String avatarData(IqPacket packet) { Element pubsub = packet.findChild("pubsub", "http://jabber.org/protocol/pubsub"); if (pubsub == null) { return null; } Element items = pubsub.findChild("items"); if (items == null) { return null; } return super.avatarData(items); } @Override public void onIqPacketReceived(Account account, IqPacket packet) { if (packet.hasChild("query", "jabber:iq:roster")) { final Jid from = packet.getFrom(); if ((from == null) || (from.equals(account.getJid().toBareJid()))) { Element query = packet.findChild("query"); this.rosterItems(account, query); } } else { if (packet.getFrom() == null) { Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": received iq with invalid from "+packet.toString()); return; } else if (packet.hasChild("open", "http://jabber.org/protocol/ibb") || packet.hasChild("data", "http://jabber.org/protocol/ibb")) { mXmppConnectionService.getJingleConnectionManager() .deliverIbbPacket(account, packet); } else if (packet.hasChild("query", "http://jabber.org/protocol/disco#info")) { IqPacket response = mXmppConnectionService.getIqGenerator() .discoResponse(packet); account.getXmppConnection().sendIqPacket(response, null); } else if (packet.hasChild("ping", "urn:xmpp:ping")) { IqPacket response = packet.generateRespone(IqPacket.TYPE_RESULT); mXmppConnectionService.sendIqPacket(account, response, null); } else { if ((packet.getType() == IqPacket.TYPE_GET) || (packet.getType() == IqPacket.TYPE_SET)) { IqPacket response = packet.generateRespone(IqPacket.TYPE_ERROR); Element error = response.addChild("error"); error.setAttribute("type", "cancel"); error.addChild("feature-not-implemented", "urn:ietf:params:xml:ns:xmpp-stanzas"); account.getXmppConnection().sendIqPacket(response, null); } } } } }
gpl-3.0
Chris81T/ct-chess-android
app/src/main/java/de/chrthms/chess/figures/RookView.java
1670
/* * ct-chess-android, a chess android ui app playing chess games. * Copyright (C) 2016-2017 Christian Thomas * * This program ct-chess-android is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.chrthms.chess.figures; import android.content.Context; import android.util.AttributeSet; import de.chrthms.chess.R; import de.chrthms.chess.engine.core.constants.ColorType; /** * Created by christian on 01.01.17. */ public class RookView extends AbstractFigureView { public RookView(Context context, int figureColor) { super(context, figureColor); } public RookView(Context context, AttributeSet attrs, int figureColor) { super(context, attrs, figureColor); } public RookView(Context context, AttributeSet attrs, int defStyleAttr, int figureColor) { super(context, attrs, defStyleAttr, figureColor); } @Override protected int getDrawableId(int figureColor) { return figureColor == ColorType.WHITE ? R.drawable.basic_rook_white: R.drawable.basic_rook_black; } }
gpl-3.0
yanellyjm/rabbitmq-client-java
src/test/java/com/rabbitmq/client/test/functional/ExceptionMessages.java
1297
package com.rabbitmq.client.test.functional; import com.rabbitmq.client.AlreadyClosedException; import com.rabbitmq.client.test.BrokerTestCase; import java.io.IOException; import java.util.UUID; public class ExceptionMessages extends BrokerTestCase { public void testAlreadyClosedExceptionMessageWithChannelError() throws IOException { String uuid = UUID.randomUUID().toString(); try { channel.queueDeclarePassive(uuid); fail("expected queueDeclarePassive to throw"); } catch (IOException e) { // ignored } try { channel.queueDeclarePassive(uuid); fail("expected queueDeclarePassive to throw"); } catch (AlreadyClosedException ace) { assertTrue(ace.getMessage().startsWith("channel is already closed due to channel error")); } } public void testAlreadyClosedExceptionMessageWithCleanClose() throws IOException { String uuid = UUID.randomUUID().toString(); try { channel.abort(); channel.queueDeclare(uuid, false, false, false, null); } catch (AlreadyClosedException ace) { assertTrue(ace.getMessage().startsWith("channel is already closed due to clean channel shutdown")); } } }
gpl-3.0
to2mbn/LoliXL
lolixl-modules/lolixl-ui/src/main/java/org/to2mbn/lolixl/ui/theme/Theme.java
687
package org.to2mbn.lolixl.ui.theme; import org.to2mbn.lolixl.ui.DisplayableItem; import javafx.beans.value.ObservableStringValue; import javafx.beans.value.ObservableValue; public interface Theme extends DisplayableItem { String PROPERTY_THEME_ID = "org.to2mbn.lolixl.ui.theme.id"; String PROPERTY_THEME_TYPE = "org.to2mbn.lolixl.ui.theme.type"; String TYPE_THEME_PACKAGE = "theme-package"; String TYPE_FONT = "font"; String TYPE_COLOR = "color"; String[] getStyleSheets(); default String getURI() { return null; } default ObservableValue<ObservableStringValue[]> getAuthors() { return null; } default ObservableStringValue getDescription() { return null; } }
gpl-3.0
harkwell/khallware
src/main/java/com/khallware/api/domain/FileItemTags.java
914
// Copyright Kevin D.Hall 2014-2018 package com.khallware.api.domain; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; @DatabaseTable(tableName = FileItemTags.TABLE) public class FileItemTags { public static final String TABLE = "fileitem_tags"; public static final String COL_FILEITEM = "fileitem"; public static final String COL_TAG = "tag"; @DatabaseField(generatedId = true) private int id; @DatabaseField(foreign = true, columnName = COL_TAG) private Tag tag; @DatabaseField(foreign = true, foreignAutoRefresh = true, columnName = COL_FILEITEM) private FileItem fileitem; // This default constructor is required by ORMlite public FileItemTags() {} public FileItemTags(FileItem fileitem, Tag tag) { this.fileitem = fileitem; this.tag = tag; } public FileItem getFileItem() { return(fileitem); } public Tag getTag() { return(tag); } }
gpl-3.0
FthrNature/unleashed-pixel-dungeon
src/main/java/com/shatteredpixel/pixeldungeonunleashed/windows/WndMessage.java
1608
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Shattered Pixel Dungeon * Copyright (C) 2014-2015 Evan Debenham * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.shatteredpixel.pixeldungeonunleashed.windows; import com.shatteredpixel.pixeldungeonunleashed.ShatteredPixelDungeon; import com.watabou.noosa.BitmapTextMultiline; import com.shatteredpixel.pixeldungeonunleashed.scenes.PixelScene; import com.shatteredpixel.pixeldungeonunleashed.ui.Window; public class WndMessage extends Window { private static final int WIDTH_P = 120; private static final int WIDTH_L = 144; private static final int MARGIN = 4; public WndMessage( String text ) { super(); BitmapTextMultiline info = PixelScene.createMultiline( text, 6 ); info.maxWidth = (ShatteredPixelDungeon.landscape() ? WIDTH_L : WIDTH_P) - MARGIN * 2; info.measure(); info.x = info.y = MARGIN; add( info ); resize( (int)info.width() + MARGIN * 2, (int)info.height() + MARGIN * 2 ); } }
gpl-3.0
fma0043/2017PCTR_M204
src/p01/Billiards.java
2225
package p01; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import java.awt.BorderLayout; import java.awt.Color; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @SuppressWarnings("serial") public class Billiards extends JFrame { public static int Width = 800; public static int Height = 600; private JButton b_start, b_stop; private Board board; private final int N_BALL = 7; private Ball[] balls = new Ball[N_BALL]; ArrayList<MoverBola> threadList = new ArrayList<MoverBola>(); public Billiards() { board = new Board(); board.setForeground(new Color(0, 128, 0)); board.setBackground(new Color(0, 128, 0)); initBalls(); b_start = new JButton("Empezar"); b_start.addActionListener(new StartListener()); b_stop = new JButton("Parar"); b_stop.addActionListener(new StopListener()); JPanel p_Botton = new JPanel(); p_Botton.setLayout(new FlowLayout()); p_Botton.add(b_start); p_Botton.add(b_stop); getContentPane().setLayout(new BorderLayout()); getContentPane().add(board, BorderLayout.CENTER); getContentPane().add(p_Botton, BorderLayout.PAGE_END); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(Width, Height); setLocationRelativeTo(null); setTitle("Práctica programación concurrente objetos móviles independientes"); setResizable(false); setVisible(true); } private void initBalls() { for (int i = 0; i < N_BALL; i++) { balls[i] = new Ball(); } } private class StartListener implements ActionListener { @Override public void actionPerformed(ActionEvent arg0) { MoverBola thread; board.setBalls(balls); for (int i = 0; i < N_BALL; i++) { thread = new MoverBola(balls[i],board); threadList.add(thread); threadList.get(i).start(); } } } private class StopListener implements ActionListener { @Override public void actionPerformed(ActionEvent arg0) { for(int i=0;i<N_BALL;i++){ threadList.get(i).interrupt(); } } } public static void main(String[] args) { new Billiards(); } }
gpl-3.0
tofuninja/Medusa
src/japa/parser/ast/expr/BooleanLiteralExpr.java
1839
/* * Copyright (C) 2007 Julio Vilmar Gesser. * * This file is part of Java 1.5 parser and Abstract Syntax Tree. * * Java 1.5 parser and Abstract Syntax Tree is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Java 1.5 parser and Abstract Syntax Tree is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Java 1.5 parser and Abstract Syntax Tree. If not, see <http://www.gnu.org/licenses/>. */ /* * Created on 02/03/2007 */ package japa.parser.ast.expr; import japa.parser.ast.visitor.GenericVisitor; import japa.parser.ast.visitor.VoidVisitor; /** * @author Julio Vilmar Gesser */ public final class BooleanLiteralExpr extends LiteralExpr { private boolean value; public BooleanLiteralExpr() { } public BooleanLiteralExpr(boolean value) { this.value = value; } public BooleanLiteralExpr(int beginLine, int beginColumn, int endLine, int endColumn, boolean value) { super(beginLine, beginColumn, endLine, endColumn); this.value = value; } @Override public <R, A> R accept(GenericVisitor<R, A> v, A arg) { return v.visit(this, arg); } @Override public <A> void accept(VoidVisitor<A> v, A arg) { v.visit(this, arg); } public boolean getValue() { return value; } public void setValue(boolean value) { this.value = value; } }
gpl-3.0
Captain-Chaos/WorldPainter
WorldPainter/WPUtils/src/main/java/org/pepsoft/util/BitField.java
4160
package org.pepsoft.util; import java.awt.*; import java.util.BitSet; import java.util.HashMap; import java.util.Map; /** * An unlimited (except by the range of the {@code int} type) * two-dimensional field of bits, initially {@code false}. * * <p>This class is <strong>not</strong> thread-safe. */ public class BitField { /** * Set a bit. * * @param x The X coordinate of the bit to set. * @param y The Y coordinate of the bit to set. */ public void set(int x, int y) { if ((x != cachedX) || (y != cachedY)) { cachedBits = booleans.computeIfAbsent(new Point(x >> 7, y >> 7), c -> new BitSet(16384)); cachedX = x; cachedY = y; } if (cachedBits == null) { // This might happen if reset() or get() was previously invoked for // these coordinates and there was no bitset created for them yet cachedBits = new BitSet(16384); booleans.put(new Point(x >> 7, y >> 7), cachedBits); } cachedBits.set(((x & 0x7f) << 7) | (y & 0x7f)); } /** * Reset a bit. * * @param x The X coordinate of the bit to reset. * @param y The Y coordinate of the bit to reset. */ public void reset(int x, int y) { if ((x != cachedX) || (y != cachedY)) { cachedBits = booleans.get(new Point(x >> 7, y >> 7)); cachedX = x; cachedY = y; } if (cachedBits != null) { cachedBits.clear(((x & 0x7f) << 7) | (y & 0x7f)); } } /** * Get a bit. * * @param x The X coordinate of the bit to get. * @param y The Y coordinate of the bit to get. * @return {@code true} if the bit is set, {@code false} * otherwise. */ public boolean get(int x, int y) { if ((x != cachedX) || (y != cachedY)) { cachedBits = booleans.get(new Point(x >> 7, y >> 7)); cachedX = x; cachedY = y; } if (cachedBits != null) { return cachedBits.get(((x & 0x7f) << 7) | (y & 0x7f)); } else { return false; } } /** * Get the bounding box of all the bits that are set. * * @return The bounding box of all the bits that are set, or * {@code null} if <em>no</em> bits are set. */ public Rectangle getBoundingBox() { // TODO throw new UnsupportedOperationException(); } /** * Perform a task for all bits that are set. * * @param visitor The task to perform. * @return {@code true} if the visitor returned {@code true} for * every bit and every bit was therefore visited. {@code false} if the * visitor returned {@code false} for some bit and not all bits may * have been visited. */ public boolean visitSetBits(BitVisitor visitor) { for (Map.Entry<Point, BitSet> entry: booleans.entrySet()) { int xOffset = entry.getKey().x << 7; int yOffset = entry.getKey().y << 7; BitSet bits = entry.getValue(); for (int i = bits.nextSetBit(0); i >= 0; i = bits.nextSetBit(i+1)) { int x = (i & 0x3f80) >> 7; int y = i & 0x7f; if (! visitor.visitBit(xOffset | x, yOffset | y, true)) { return false; } } } return true; } private int cachedX, cachedY; private BitSet cachedBits; private final Map<Point, BitSet> booleans = new HashMap<>(); /** * A visitor of bits on a 2D plane. */ @FunctionalInterface public interface BitVisitor { /** * Visit a specific bit. * * @param x The X coordinate of the bit on the 2D plane. * @param y The Y coordinate of the bit on the 2D plane. * @param bit Whether the bit is set. * @return Should return {@code true} to indicate that processing * should continue, or {@code false} to indicate that processing * may be aborted. */ boolean visitBit(int x, int y, boolean bit); } }
gpl-3.0
Antiquum/Crimson
src/com/subterranean_security/crimson/core/utility/Crypto.java
1165
package com.subterranean_security.crimson.core.utility; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public enum Crypto { ; private static byte[] hash(String type, byte[] target) throws NoSuchAlgorithmException { MessageDigest digest; digest = MessageDigest.getInstance(type); digest.update(target); return digest.digest(); } public static String hashPass(char[] pass, String salt) { byte[] hash = (new String(pass) + salt).getBytes(StandardCharsets.UTF_16); try { for (int i = 0; i < 999; i++) { hash = hash("SHA-256", hash); } } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } return new String(hash, StandardCharsets.UTF_16); } public static String hashPass(char[] pass) { byte[] hash = new String(pass).getBytes(StandardCharsets.UTF_16); try { for (int i = 0; i < 999; i++) { hash = hash("SHA-256", hash); } } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } return new String(hash, StandardCharsets.UTF_16); } }
gpl-3.0
Unfoolishly/Frozen-Mod
frozenmod_common/com/goldps/frozen/mob/entity/EntityElsa.java
241
package com.goldps.frozen.mob.entity; import net.minecraft.entity.monster.EntityMob; import net.minecraft.world.World; public class EntityElsa extends EntityMob { public EntityElsa(World par1World) { super(par1World); //this. } }
gpl-3.0
itachi1706/PneumaticCraft
src/pneumaticCraft/common/remote/WidgetLabelVariable.java
560
package pneumaticCraft.common.remote; import pneumaticCraft.client.gui.widget.WidgetLabel; public class WidgetLabelVariable extends WidgetLabel{ private final TextVariableParser parser; public WidgetLabelVariable(int x, int y, String text){ super(x, y, text); parser = new TextVariableParser(text); } @Override public void render(int mouseX, int mouseY, float partialTick){ String oldText = text; text = parser.parse(); super.render(mouseX, mouseY, partialTick); text = oldText; } }
gpl-3.0
Storyyeller/Krakatau
tests/roundtrip/source/RecordTest.java
1027
// Originally created as a test for Krakatau (https://github.com/Storyyeller/Krakatau) import java.net.*; import java.nio.file.*; import java.util.*; import java.util.zip.*; import java.lang.reflect.*; import java.lang.annotation.*; import java.util.function.*; import java.util.ArrayList; import java.util.List; import java.util.Map; @Target({ // ElementType.ANNOTATION_TYPE, // ElementType.CONSTRUCTOR, // ElementType.FIELD, // ElementType.LOCAL_VARIABLE, // ElementType.METHOD, // ElementType.PACKAGE, // ElementType.PARAMETER, // ElementType.TYPE, // ElementType.TYPE_PARAMETER, ElementType.TYPE_USE }) @interface A { double value() default 0.0/0.0; } @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE_USE }) @interface B {} record IPair (int a, @A(13) @B String b, IPair p) { static final int X = 7; } public class RecordTest { public static void main(String... args) throws Throwable { System.out.println(new IPair(3, "x", null)); } }
gpl-3.0
sarmbruster/gremlin-plugin
src/main/java/org/neo4j/server/webadmin/console/Neo4jGroovyImports.java
1333
/** * Copyright (c) 2002-2013 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.server.webadmin.console; import java.util.Arrays; import java.util.List; public class Neo4jGroovyImports { public static List<String> getImports() { String[] result = {"org.neo4j.graphdb.index.*", "org.neo4j.graphdb.event.*", "org.neo4j.graphdb.traversal.*", "org.neo4j.graphdb.helpers.*", "org.neo4j.graphdb.helpers.collection.*", "org.neo4j.graphdb.kernel.*", "org.neo4j.graphdb.*"}; return Arrays.asList( result ); } }
gpl-3.0
yangweijun213/Java
J2SE/src/com/jun/数组/stringbuild_56_57_58/Test02.java
464
package com.jun.数组.stringbuild_56_57_58; import java.util.ArrayList; /** * 测试StringBuilder的一些常用方法 * @author dell * */ public class Test02 { public static void main(String[] args) { StringBuilder sb = new StringBuilder("abcdefghijklmnopqrstuvwxyz"); sb.delete(3, 5).delete(3, 5); //结果:abchijklmnopqrstuvwxyz System.out.println(sb); sb.reverse(); System.out.println(sb); StringBuffer sb2 = new StringBuffer(); } }
gpl-3.0
rsby/learn
concepts/src/test/java/datastructures/HeapTest.java
9275
package datastructures; import org.junit.Test; import testutility.Distribution; import java.util.Arrays; import static datastructures.Heap.maxHeap; import static datastructures.Heap.minHeap; import static datastructures.Heap.sortAscending; import static datastructures.Heap.sortDescending; import static org.junit.Assert.assertEquals; /** * @author rees.byars */ public class HeapTest { // TODO this is bare bones, no edge cases covered @Test(expected = NullPointerException.class) public void test_nullInsert() { minHeap(1, 2).insert(null, null); } @Test(expected = NullPointerException.class) public void test_nullCreate() { minHeap(1, 2, null); } @Test public void testPeek() { Heap<Integer> heap = minHeap(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13); heap.insert(2, 3, 5, 4, 66, 87, 23, 3, 234, 85, 23554, 23, 456654, 2, 1, 4444, 9); assert heap.peek() == 1; heap = minHeap(); heap.insert(2, 3, 5, 4, 66, 87, 23, 3, 234, 85, 23554, 23, 456654, 2, 1, 4444, 9); assert heap.peek() == 1; assert maxHeap().peek() == null; } @Test public void testRemove() { Heap<Integer> heap = minHeap(7, 3, 2, 6, 9, 12, 14, 11, 3, 22, 19, 4); assert heap.peek() == 2; assert heap.remove() == 2; assert heap.remove() == 3; assert heap.remove() == 3; assert heap.remove() == 4; assert heap.remove() == 6; assert heap.remove() == 7; assert heap.remove() == 9; assert heap.remove() == 11; assert heap.remove() == 12; assert heap.remove() == 14; assert heap.remove() == 19; assert heap.remove() == 22; assert heap.remove() == null; assert heap.peek() == null; assert heap.toArray().length == 0; } @Test public void testRemoveElement() { Heap<Integer> heap = minHeap(7, 3, 2, 6, 9, 12, 14, 11, 3, 22, 19, 4); assert heap.peek() == 2; assert heap.remove(2) == 2; assert heap.remove(3) == 3; assert heap.remove(3) == 3; assert heap.remove(4) == 4; assert heap.remove(6) == 6; assert heap.remove(14) == 14; assert heap.remove() == 7; assert heap.remove() == 9; assert heap.remove() == 11; assert heap.remove() == 12; assert heap.remove() == 19; assert heap.remove() == 22; assert heap.remove() == null; assert heap.peek() == null; assert heap.toArray().length == 0; } @Test public void testInsert() { Heap<Integer> heap = minHeap(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13); heap.insert(2, 3, 5, 4, 66, 87, 23, 3, 234, 85, 23554, 23, 456654, 2, 1, 4444, 9); assert heap.peek() == 1; heap.insert(0); assert heap.peek() == 0; } @Test public void testPeek_max() { Heap<Integer> heap = maxHeap(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13); heap.insert(2, 3, 5, 4, 66, 87, 23, 3, 234, 85, 23554, 23, 456654, 2, 1, 4444, 9); assert heap.peek() == 456654; } @Test public void testRemove_max() { Heap<Integer> heap = maxHeap(7, 3, 2, 6, 9, 12, 14, 11, 3, 22, 19, 4); assert heap.remove() == 22; assert heap.remove() == 19; assert heap.remove() == 14; assert heap.remove() == 12; assert heap.remove() == 11; assert heap.remove() == 9; assert heap.remove() == 7; assert heap.remove() == 6; assert heap.remove() == 4; assert heap.remove() == 3; assert heap.remove() == 3; assert heap.remove() == 2; } @Test public void testInsert_max() { Heap<Integer> heap = maxHeap(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13); heap.insert(2, 3, 5, 4, 66, 87, 23, 3, 234, 85, 23554, 23, 456654, 2, 1, 4444, 9); assert heap.peek() == 456654; heap.insert(4566540); assert heap.peek() == 4566540; } @Test public void testToArray() { Heap<Integer> heap = minHeap(7, 3, 2, 6, 9, 12, 14, 11, 3, 22, 19, 4); Object[] first = heap.toArray(); assert first.length == 12; assert heap.toArray()[0].equals(2); assert heap.remove() == 2; assert heap.toArray().length + 1 == first.length; } @Test public void testSize() { Heap<Integer> heap = minHeap(7, 3, 2, 6, 9, 12, 14, 11, 3, 22, 19, 4); assert heap.size() == 12; } @Test public void testSortAscending() { Integer[] ints = {3, 5, 1, 88, 2, 5, 111, 7, 7, 7, 124333, -9, 324, -9, -3, 2222}; sortAscending(ints); assert ints[0] == -9; sortAscending(new Integer[0]); } @Test public void testSortDescending() { Integer[] ints = {3, 5, 1, 88, 2, 5, 111, 7, 7, 7, 124333, -9, 324, -9, -3, 2222}; sortDescending(ints); assert ints[0] == 124333; sortDescending(new Integer[0]); } @Test public void testOrder() { // NOTE: this test will FAIL if the offset is set to 0 (in which case the // passed in array is used for the heap queue, which in the case of this test // means the "values" array becomes the heap queue for (Distribution distribution : Distribution.values()) { Integer[] values = distribution.create(1000); Heap<Integer> heap = minHeap(values); Arrays.sort(values); for (Integer i : values) { assertEquals("Distribution [" + distribution + "]", i, heap.remove()); } } } @Test(expected = IllegalArgumentException.class) public void testSubsume_exception_comparator_mismatch() { Heap<Integer> heap = minHeap(7, 3, 2, 6, 9, 12, 14, 11, 3, 22, 19, 4); // min heap cannot consume max heap heap.subsume(maxHeap(5, 2, 54, 9, 0)); } @Test(expected = IllegalArgumentException.class) public void testSubsume_exception_heap_type_mismatch() { Heap<Integer> heap = minHeap(7, 3, 2, 6, 9, 12, 14, 11, 3, 22, 19, 4); // binary heap cannot consume delegating heap (so it says, really it could, but it doesn't know that) heap.subsume(new DelegatingHeap<>(minHeap(1))); } @Test public void testSubsume() { Heap<Integer> heap = minHeap(7, 3, 2, 6, 9, 12, 14, 11, 3, 22, 19, 4); assert heap.size() == 12; heap.subsume(minHeap(5, 2, 54, 9, 0)); assert heap.remove() == 0; assert heap.remove() == 2; assert heap.size() == 15; assert heap.remove() == 2; assert heap.remove() == 3; assert heap.remove() == 3; assert heap.remove() == 4; assert heap.remove() == 5; assert heap.remove() == 6; assert heap.remove() == 7; assert heap.remove() == 9; assert heap.remove() == 9; assert heap.remove() == 11; assert heap.remove() == 12; assert heap.remove() == 14; assert heap.remove() == 19; assert heap.remove() == 22; assert heap.remove() == 54; assert heap.remove() == null; heap = minHeap(7); heap.subsume(minHeap(5, 2, 54, 9, 0)); assert heap.remove() == 0; heap = minHeap(2); heap.subsume(minHeap()); assert heap.remove() == 2; assert heap.remove() == null; heap = minHeap(); heap.subsume(minHeap()); assert heap.remove() == null; heap = minHeap(2); heap.subsume(minHeap(-1)); assert heap.remove() == -1; assert heap.remove() == 2; assert heap.remove() == null; heap = minHeap(7, 2); heap.subsume(minHeap(5, 0)); assert heap.remove() == 0; assert heap.remove() == 2; assert heap.remove() == 5; assert heap.remove() == 7; assert heap.remove() == null; heap = minHeap(); heap.subsume(minHeap(5, 0)); assert heap.remove() == 0; assert heap.remove() == 5; assert heap.remove() == null; heap = minHeap(2, 1); heap.subsume(minHeap(0)); assert heap.remove() == 0; assert heap.remove() == 1; assert heap.remove() == 2; } static class DelegatingHeap<T> implements Heap<T> { final Heap<T> delegate; DelegatingHeap(Heap<T> delegate) { this.delegate = delegate; } @Override public T peek() { return delegate.peek(); } @Override public T remove() { return delegate.remove(); } @Override public T remove(T element) { return delegate.remove(element); } @Override public void insert(T element) { delegate.insert(element); } @Override public void subsume(Heap<? extends T> heap) { delegate.subsume(heap); } @Override public Object[] toArray() { return delegate.toArray(); } @Override public int size() { return delegate.size(); } } }
gpl-3.0
GenkunAbe/mobile-continuous-authentication
TouchAuth/app/src/main/java/org/genku/touchauth/Service/AuthService.java
2494
package org.genku.touchauth.Service; import android.app.Service; import android.content.Intent; import android.os.Environment; import android.os.IBinder; import android.widget.Toast; import org.genku.touchauth.Util.FileUtils; public class AuthService extends Service { public static final int INTERVAL = 4; private static final String authResultFilename = Environment.getExternalStorageDirectory().getAbsolutePath() + "Auth/AuthResult.txt"; public AuthService() { } @Override public int onStartCommand(Intent intent, int flags, int startId) { try { stopService(new Intent(this, TouchDataCollectingService.class)); stopService(new Intent(this, SensorDataCollectingService.class)); stopService(new Intent(this, TouchPredictingService.class)); stopService(new Intent(this, SensorPredictingService.class)); } catch (Exception e) { e.printStackTrace(); } startService(new Intent(this, TouchPredictingService.class)); startService(new Intent(this, SensorPredictingService.class)); new Thread(new Runnable() { @Override public void run() { predict(); } }).start(); return super.onStartCommand(intent, flags, startId); } private void predict() { Long start = System.currentTimeMillis(); try { while (true) { Long now = System.currentTimeMillis(); if (now - start < 4 * 1000) continue; double touchConfidence = TouchPredictingService.confidence; double sensorConfidence = SensorPredictingService.confidence; if (touchConfidence > 2 && sensorConfidence > 0) { Toast.makeText(getApplicationContext(), "True", Toast.LENGTH_SHORT).show(); FileUtils.writeFile(authResultFilename, "True\r\n", true); } else { Toast.makeText(getApplicationContext(), "False", Toast.LENGTH_SHORT).show(); FileUtils.writeFile(authResultFilename, "False\r\n", true); } } } catch (Exception e) { e.printStackTrace(); } } @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. return null; } }
gpl-3.0
Asterixyz/SRPG
src/main/java/com/asterixyz/SRPG/handler/ConfigurationHandler.java
1198
package com.asterixyz.SRPG.handler; import com.asterixyz.SRPG.reference.Reference; import cpw.mods.fml.client.event.ConfigChangedEvent; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.common.config.Configuration; import java.io.File; public class ConfigurationHandler { public static Configuration configuration; public static boolean testValue = false; public static void init(File configFile){ //Create the configuration object from the given configurationfile if (configuration == null) { configuration = new Configuration(configFile); loadConfiguration(); } } @SubscribeEvent public void onConfigurationChangedEvent(ConfigChangedEvent.OnConfigChangedEvent event){ if (event.modID.equalsIgnoreCase(Reference.MOD_ID)){ //Resync the configs loadConfiguration(); } } private static void loadConfiguration(){ testValue = configuration.getBoolean("configValue",configuration.CATEGORY_GENERAL, false, "This is an example config value"); if (configuration.hasChanged()){ configuration.save(); } } }
gpl-3.0
itachi1706/PneumaticCraft
src/pneumaticCraft/common/progwidgets/ProgWidgetConditionBase.java
2249
package pneumaticCraft.common.progwidgets; import java.util.ArrayList; import java.util.List; import pneumaticCraft.common.ai.IDroneBase; import pneumaticCraft.common.item.ItemPlasticPlants; public abstract class ProgWidgetConditionBase extends ProgWidget implements IJump{ @Override public boolean hasStepInput(){ return true; } @Override public Class<? extends IProgWidget> returnType(){ return null; } @Override public WidgetDifficulty getDifficulty(){ return WidgetDifficulty.MEDIUM; } @Override public void addErrors(List<String> curInfo, List<IProgWidget> widgets){ super.addErrors(curInfo, widgets); IProgWidget widget = getConnectedParameters()[getParameters().length - 1]; IProgWidget widget2 = getConnectedParameters()[getParameters().length * 2 - 1]; if(widget == null && widget2 == null) { curInfo.add("gui.progWidget.condition.error.noFlowControl"); } else if(widget != null && !(widget instanceof ProgWidgetString) || widget2 != null && !(widget2 instanceof ProgWidgetString)) { curInfo.add("gui.progWidget.condition.error.shouldConnectTextPieces"); } } @Override public List<String> getPossibleJumpLocations(){ IProgWidget widget = getConnectedParameters()[getParameters().length - 1]; IProgWidget widget2 = getConnectedParameters()[getParameters().length * 2 - 1]; ProgWidgetString textWidget = widget != null ? (ProgWidgetString)widget : null; ProgWidgetString textWidget2 = widget2 != null ? (ProgWidgetString)widget2 : null; List<String> locations = new ArrayList<String>(); if(textWidget != null) locations.add(textWidget.string); if(textWidget2 != null) locations.add(textWidget2.string); return locations; } @Override public IProgWidget getOutputWidget(IDroneBase drone, List<IProgWidget> allWidgets){ return ProgWidgetJump.jumpToLabel(allWidgets, this, evaluate(drone, this)); } public abstract boolean evaluate(IDroneBase drone, IProgWidget widget); @Override public int getCraftingColorIndex(){ return ItemPlasticPlants.LIGHTNING_PLANT_DAMAGE; } }
gpl-3.0
LostArchives/RP6_JAVA_CLIENT
src/model/RobotTrajectory.java
12320
package model; import java.util.ArrayList; import java.util.HashMap; import controller.RobotClient; import enums.RobotDirection; import enums.RobotOrientation; import enums.RobotState; import enums.TrajectoryMode; /** * Class which allows to store a trajectory which can be executed automatically by the robot * @author Valentin * */ public class RobotTrajectory { /** * Attribute which stores the client attached ot this trajectory */ private RobotClient _myClient; /** * Attribut which stores the drive commands contained inside this trajectory */ private ArrayList<DriveCommand> _driveCommands; /** * Attribute which stores the trajectory mode (1 time or infinite) */ private TrajectoryMode _trajMode; /** * Attribute which stores the orientation of the robot at every commands */ private HashMap<Integer, RobotOrientation> _orientationMap; /* Attribute to manage through outter classes */ private Thread drive_thread; private boolean _stop = true; private int _currentCommandIndex = -1; private RobotOrientation _currentOrientation; /** * Default constructor */ public RobotTrajectory() { _driveCommands = new ArrayList<DriveCommand>(); _trajMode = TrajectoryMode.NONE; _stop = true; _currentCommandIndex = -1; _currentOrientation = RobotOrientation.NONE; _orientationMap = new HashMap<Integer,RobotOrientation>(); } /** * Constructor with main parameters * @param p_client The client attached to this trajectory * @param p_driveCommands The drive commands inside this trajectory * @param p_mode The mode of this trajecory */ public RobotTrajectory(RobotClient p_client, ArrayList<DriveCommand> p_driveCommands, TrajectoryMode p_mode) { _myClient = p_client; _driveCommands = p_driveCommands; _trajMode = p_mode; } public RobotClient get_myClient() { return _myClient; } public void set_myClient(RobotClient _myClient) { this._myClient = _myClient; } public TrajectoryMode get_trajMode() { return _trajMode; } public void set_trajMode(TrajectoryMode _trajMode) { this._trajMode = _trajMode; } /** * Method to add a driveCommand to the list * @param toAdd DriveCommand to add */ public void addDriveCommand(DriveCommand toAdd) { _driveCommands.add(toAdd); _orientationMap.put(_driveCommands.size() - 1, estimOrientationAt(_driveCommands.size() - 1)); } /** * Method to replace a driveCommand at index by another * @param index Index of the actual command to replace * @param dc DriveCommand which will replace the previous one */ public void editDriveCommand(int index,DriveCommand dc) { _driveCommands.get(index).set_robotDirection(dc.get_robotDirection()); _driveCommands.get(index).set_robotSpeed(dc.get_robotSpeed()); _driveCommands.get(index).set_commandDuration(dc.get_commandDuration()); recompileHashMap(); } /** * Method to update the orientationHashMap after edit of the driveCommand list */ private void recompileHashMap() { _orientationMap.clear(); for (int i = 0 ; i < _driveCommands.size() ; i++) { RobotOrientation robotOrientation = estimOrientationAt(i); _orientationMap.put(i, robotOrientation); } } /** * Method to get the number of driveCommands into the list * @return The number of commands into the list */ public int getCommandsListSize() { return _driveCommands.size(); } /** * Method to get the driveCommand at the given index * @param index Index where the driveCommand is located * @return The driveCommand located at this index */ public DriveCommand getCommandAt(int index) { return _driveCommands.get(index); } public int get_currentCommandIndex() { return _currentCommandIndex; } public RobotOrientation get_currentOrientation() { return _currentOrientation; } /** * Method to get the orientation at the given index in the hashMap * @param index Index where the orientation is located * @return The orientation at the given index */ public RobotOrientation getOrientationAt(int index) { return _orientationMap.get(index); } /** * Method to know if the autopilot is running * @return The state of the autopilot (running or not) */ public boolean is_running() { return !_stop; } /** * Method to get the total duration of one loop of the robot trajectory * @return The total duration of one loop of this robot trajectory */ public int getTotalDuration() { int duration = 0; for (int i = 0 ; i< _driveCommands.size() ; i++) { duration += _driveCommands.get(i).get_commandDuration(); } return duration; } /** * Method to estimate the orientation of the robot after many commands * @param commandIndex The commandIndex where we want the orientation of the robot * @return The orientation of the robot at this commandIndex */ public RobotOrientation estimOrientationAt(int commandIndex) { RobotOrientation ro = RobotOrientation.FACE_FRONT; for (int i = 0 ; i < commandIndex ; i++) { RobotDirection rd = _driveCommands.get(i).get_robotDirection(); boolean found = false; if (ro == RobotOrientation.FACE_FRONT && !found) { switch(rd) { case FORWARD: ro = RobotOrientation.FACE_FRONT; found = true; break; case BACKWARD: ro = RobotOrientation.FACE_FRONT; found = true; break; case LEFT: ro = RobotOrientation.SIDE_LEFT; found = true; break; case RIGHT: ro = RobotOrientation.SIDE_RIGHT; found = true; break; case NONE: break; } } if (ro == RobotOrientation.FACE_REAR && !found) { switch(rd) { case FORWARD: ro = RobotOrientation.FACE_REAR; found = true; break; case BACKWARD: ro = RobotOrientation.FACE_REAR; found = true; break; case LEFT: ro = RobotOrientation.SIDE_RIGHT; found = true; break; case RIGHT: ro = RobotOrientation.SIDE_LEFT; found = true; break; case NONE: break; } } if (ro == RobotOrientation.SIDE_LEFT && !found) { switch(rd) { case FORWARD: ro = RobotOrientation.SIDE_LEFT; found = true; break; case BACKWARD: ro = RobotOrientation.SIDE_LEFT; found = true; break; case LEFT: ro = RobotOrientation.FACE_REAR; found = true; break; case RIGHT: ro = RobotOrientation.FACE_FRONT; found = true; break; case NONE: break; } } if (ro == RobotOrientation.SIDE_RIGHT && !found) { switch(rd) { case FORWARD: ro = RobotOrientation.SIDE_RIGHT; found = true; break; case BACKWARD: ro = RobotOrientation.SIDE_RIGHT; found = true; break; case LEFT: ro = RobotOrientation.FACE_FRONT; found = true; break; case RIGHT: ro = RobotOrientation.FACE_REAR; found = true; break; case NONE: break; } } } return ro; } /** * Method to get the 2D direction based on the orientation and the 3D direction( for the UI editor) * @param ro Actual robotOrientation * @param rd The direction wanted * @return The 2D direction based on the two parameters */ public RobotDirection getDirectionBaseOnOrientation(RobotOrientation ro,RobotDirection rd) { RobotDirection to_return = rd; if (ro == RobotOrientation.SIDE_LEFT) { switch(rd) { case FORWARD: to_return = RobotDirection.LEFT; break; case BACKWARD: to_return = RobotDirection.RIGHT; break; case LEFT: to_return = RobotDirection.BACKWARD; break; case RIGHT: to_return = RobotDirection.FORWARD; break; case NONE: break; } } if (ro == RobotOrientation.SIDE_RIGHT) { switch(rd) { case FORWARD: to_return = RobotDirection.RIGHT; break; case BACKWARD: to_return = RobotDirection.LEFT; break; case LEFT: to_return = RobotDirection.FORWARD; break; case RIGHT: to_return = RobotDirection.BACKWARD; break; case NONE: break; } } if (ro == RobotOrientation.FACE_REAR) { switch(rd) { case FORWARD: to_return = RobotDirection.BACKWARD; break; case BACKWARD: to_return = RobotDirection.FORWARD; break; case LEFT: to_return = RobotDirection.RIGHT; break; case RIGHT: to_return = RobotDirection.LEFT; break; case NONE: break; } } return to_return; } /** * Method to start the autopilot mode and execute the trajectory in the correct trajectory mode */ public void startAutoPilot() { drive_thread = new Thread() { @Override public void run() { switch (_trajMode) { case ONCE: _myClient.set_robotState(RobotState.READY_TO_START); executeCommands(); //_myClient.get_myUI().unSelectCurrentSegment(); break; case LOOP: _myClient.set_robotState(RobotState.READY_TO_START); executeCommands(); break; case NONE: System.out.println("Le mode de trajectoire n'est pas défini"); break; default: break; } } }; drive_thread.start(); } /** * Method to stop the autopilot */ public void stopAutoPilot() { _stop = true; } /** * Method to force the autopilot to stop by interrupting the thread */ public void forceStopAutoPilot() { if (!_stop) drive_thread.interrupt(); } /** * Method to turn the robot of 90 degrees on the left */ private void turnLeft() { _myClient.send("l"); _myClient.send("75"); try { Thread.sleep(2200); _myClient.send("stp"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Method to turn the robot of 90 degrees on the right */ private void tunrRight() { _myClient.send("r"); _myClient.send("75"); try { Thread.sleep(2200); _myClient.send("stp"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Method to execute the commands of the drive commands list */ private void executeCommands() { _currentCommandIndex = 0; _stop = false; while(!_stop) { String full_command = _driveCommands.get(_currentCommandIndex).toStringCommandForAutoPilot(); if (_driveCommands.get(_currentCommandIndex).get_robotDirection() == RobotDirection.LEFT) { turnLeft(); } if (_driveCommands.get(_currentCommandIndex).get_robotDirection() == RobotDirection.RIGHT) { tunrRight(); } _myClient.send(full_command); try{ Thread.sleep(_driveCommands.get(_currentCommandIndex).get_commandDuration() * 1000); }catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } nextCommand(); if (_currentCommandIndex == 0 && _trajMode == TrajectoryMode.ONCE) _stop = true; } _myClient.send("0"); _myClient.send("stp"); } /** * Method to go to next command and adjusting if needed */ private void nextCommand() { if (_currentCommandIndex + 1 >= _driveCommands.size()) _currentCommandIndex = 0; else _currentCommandIndex++; } /** * Method to get the state of the robot based on its direction * @param p_direction The direction of the robot to translate * @return The robot state based on this direction */ private RobotState getStateFromDirection(RobotDirection p_direction) { RobotState state = RobotState.NONE; switch (p_direction) { case FORWARD: state = RobotState.AUTO_MOVING_FORWARD; break; case BACKWARD: state = RobotState.AUTO_MOVING_BACKWARD; break; case LEFT: state = RobotState.AUTO_TURNING_LEFT; break; case RIGHT: state = RobotState.AUTO_TURNING_RIGHT; break; case NONE: state = RobotState.NONE; break; default: break; } return state; } }
gpl-3.0
isnuryusuf/ingress-indonesia-dev
apk/classes-ekstartk/com/nianticproject/ingress/common/x/f.java
280
package com.nianticproject.ingress.common.x; public abstract interface f { public abstract f a(p paramp); public abstract String n_(); } /* Location: classes_dex2jar.jar * Qualified Name: com.nianticproject.ingress.common.x.f * JD-Core Version: 0.6.2 */
gpl-3.0
kurtchen/Tiny-Tiny-RSS-for-Honeycomb
org.fox.ttrss/src/main/java/org/fox/ttrss/BaseFeedlistFragment.java
6832
package org.fox.ttrss; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.support.v4.app.Fragment; import android.support.v7.widget.SwitchCompat; import android.util.TypedValue; import android.view.InflateException; import android.view.LayoutInflater; import android.view.View; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import org.fox.ttrss.offline.OfflineActivity; import java.net.MalformedURLException; import java.net.URL; public abstract class BaseFeedlistFragment extends Fragment { abstract public void refresh(boolean background); public void initDrawerHeader(LayoutInflater inflater, View view, ListView list, final CommonActivity activity, final SharedPreferences prefs, boolean isRoot) { boolean isOffline = activity instanceof OfflineActivity; if (true /*m_activity.findViewById(R.id.headlines_drawer) != null*/) { try { if (activity.isSmallScreen()) { View layout = inflater.inflate(R.layout.drawer_header, list, false); list.addHeaderView(layout, null, false); TextView login = (TextView) view.findViewById(R.id.drawer_header_login); TextView server = (TextView) view.findViewById(R.id.drawer_header_server); login.setText(prefs.getString("login", "")); try { server.setText(new URL(prefs.getString("ttrss_url", "")).getHost()); } catch (MalformedURLException e) { server.setText(""); } View account = view.findViewById(R.id.drawer_header_account); account.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(prefs.getString("ttrss_url", ""))); startActivity(intent); } catch (Exception e) { } } }); } /* deal with ~material~ footers */ // divider View footer = inflater.inflate(R.layout.drawer_divider, list, false); footer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // } }); list.addFooterView(footer); // unread only checkbox footer = inflater.inflate(R.layout.feeds_row_toggle, list, false); list.addFooterView(footer); TextView text = (TextView) footer.findViewById(R.id.title); text.setText(R.string.unread_only); ImageView icon = (ImageView) footer.findViewById(R.id.icon); TypedValue tv = new TypedValue(); getActivity().getTheme().resolveAttribute(R.attr.ic_filter_variant, tv, true); icon.setImageResource(tv.resourceId); final SwitchCompat rowSwitch = (SwitchCompat) footer.findViewById(R.id.row_switch); rowSwitch.setChecked(activity.getUnreadOnly()); rowSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton button, boolean isChecked) { activity.setUnreadOnly(isChecked); refresh(true); } }); footer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { rowSwitch.setChecked(!rowSwitch.isChecked()); } }); if (isRoot) { // offline footer = inflater.inflate(R.layout.feeds_row, list, false); footer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (activity instanceof OnlineActivity) { ((OnlineActivity)activity).switchOffline(); } else if (activity instanceof OfflineActivity) { ((OfflineActivity)activity).switchOnline(); } } }); list.addFooterView(footer); text = (TextView) footer.findViewById(R.id.title); text.setText(isOffline ? R.string.go_online : R.string.go_offline); icon = (ImageView) footer.findViewById(R.id.icon); tv = new TypedValue(); getActivity().getTheme().resolveAttribute(isOffline ? R.attr.ic_cloud_upload : R.attr.ic_cloud_download, tv, true); icon.setImageResource(tv.resourceId); TextView counter = (TextView) footer.findViewById(R.id.unread_counter); counter.setText(R.string.blank); } // settings footer = inflater.inflate(R.layout.feeds_row, list, false); footer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(activity, PreferencesActivity.class); startActivityForResult(intent, 0); } }); list.addFooterView(footer); text = (TextView) footer.findViewById(R.id.title); text.setText(R.string.preferences); icon = (ImageView) footer.findViewById(R.id.icon); tv = new TypedValue(); getActivity().getTheme().resolveAttribute(R.attr.ic_settings, tv, true); icon.setImageResource(tv.resourceId); TextView counter = (TextView) footer.findViewById(R.id.unread_counter); counter.setText(R.string.blank); } catch (InflateException e) { // welp couldn't inflate header i guess e.printStackTrace(); } catch (java.lang.UnsupportedOperationException e) { e.printStackTrace(); } } } }
gpl-3.0
LasmGratel/FoodCraft-Reloaded
src/main/java/cc/lasmgratel/foodcraftreloaded/minecraft/client/util/masking/CustomModelMasking.java
1871
/* * FoodCraft Mod - Add more food to your Minecraft. * Copyright (C) 2017 Lasm Gratel * * This file is part of FoodCraft Mod. * * FoodCraft Mod is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * FoodCraft Mod is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with FoodCraft Mod. If not, see <http://www.gnu.org/licenses/>. */ package cc.lasmgratel.foodcraftreloaded.minecraft.client.util.masking; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.ItemMeshDefinition; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.client.renderer.color.IBlockColor; import net.minecraft.client.renderer.color.IItemColor; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Collections; import java.util.Map; public interface CustomModelMasking { @Nullable default ModelResourceLocation getModelLocation() { return null; } @Nonnull default Map<IBlockState, ModelResourceLocation> getStateModelLocations() { return Collections.emptyMap(); } default ItemMeshDefinition getItemMeshDefinition() { return null; } default int getTintIndex() { return -1; } @Nullable default IBlockColor getBlockColorMultiplier() { return null; } @Nullable default IItemColor getItemColorMultiplier() { return null; } }
gpl-3.0
mpawlucz/sfapi-selenium
src/main/java/net/sourceforge/seleniumflexapi/call/FlashComboHasSelectedValueCall.java
1722
/* * License * * This file is part of The SeleniumFlex-API. * * The SeleniumFlex-API is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of * the License, or any later version. * * The SeleniumFlex-API is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with The SeleniumFlex-API. * If not, see http://www.gnu.org/licenses/ * */ /* Contributed by Black Pepper Software Ltd. */ package net.sourceforge.seleniumflexapi.call; import net.sourceforge.seleniumflexapi.FlexSelenium; public class FlashComboHasSelectedValueCall implements FlashCall { private String objectId; private FlexSelenium flashApp; private String expectedValue; private String currentValue; public FlashComboHasSelectedValueCall(FlexSelenium flashApp, String objectId, String expectedValue) { super(); this.flashApp = flashApp; this.objectId = objectId; this.expectedValue = expectedValue; } @Override public boolean attemptCall() { currentValue = flashApp.getComboBoxSelectedItem(objectId); if (currentValue == null || !currentValue.equals(expectedValue)) { return false; } return true; } @Override public String getErrorMessage() { return "The selected item for " + objectId + " was not the value '" + expectedValue + "' but was '" + currentValue + "'" ; } }
gpl-3.0
mediathekview/MServer
src/main/java/mServer/crawler/sender/funk/json/FunkVideoDeserializer.java
3248
package mServer.crawler.sender.funk.json; import com.google.gson.JsonObject; import mServer.crawler.sender.base.JsonUtils; import mServer.crawler.sender.funk.FilmInfoDto; import mServer.crawler.sender.funk.FunkUrls; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.time.Duration; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.Optional; public class FunkVideoDeserializer extends AbstractFunkElementDeserializer<FilmInfoDto> { private static final Logger LOG = LogManager.getLogger(FunkVideoDeserializer.class); private static final String DATE_TIME_FORMAT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern(DATE_TIME_FORMAT_PATTERN); private static final String TAG_VIDEO_DTO_LIST = "videoDTOList"; private static final String TAG_TITLE = "title"; private static final String TAG_ENTITY_ID = "entityId"; private static final String TAG_DURATION = "duration"; private static final String TAG_DESCRIPTION = "description"; private static final String TAG_PUBLICATION_DATE = "publicationDate"; private static final String TAG_CHANNEL_ALIAS = "channelAlias"; private static final String TAG_ALIAS = "alias"; private static final String TAG_CHANNEL_ID = "channelId"; @Override protected FilmInfoDto mapToElement(final JsonObject jsonObject) { final FilmInfoDto filmInfo = new FilmInfoDto(createNexxCloudUrl(jsonObject.get(TAG_ENTITY_ID).getAsString())); // Required filmInfo.setTitle(jsonObject.get(TAG_TITLE).getAsString()); filmInfo.setTopic(jsonObject.get(TAG_CHANNEL_ID).getAsString()); filmInfo.setDuration(Duration.ofSeconds(jsonObject.get(TAG_DURATION).getAsInt())); final String timeText = jsonObject.get(TAG_PUBLICATION_DATE).getAsString(); try { filmInfo.setTime(LocalDateTime.parse(timeText, DATE_TIME_FORMATTER)); } catch (final DateTimeParseException dateTimeParseException) { LOG.error( String.format( "The text \"%s\" couldn't be parsed withe the pattern \"%s\".", timeText, DATE_TIME_FORMAT_PATTERN), dateTimeParseException); } // Optionals JsonUtils.getAttributeAsString(jsonObject, TAG_DESCRIPTION).ifPresent(filmInfo::setDescription); final Optional<String> channelAlias = JsonUtils.getAttributeAsString(jsonObject, TAG_CHANNEL_ALIAS); final Optional<String> alias = JsonUtils.getAttributeAsString(jsonObject, TAG_ALIAS); if (channelAlias.isPresent() && alias.isPresent()) { filmInfo.setWebsite( FunkUrls.WEBSITE.getAsString(channelAlias.get(), alias.get())); } return filmInfo; } private String createNexxCloudUrl(final String entityId) { return FunkUrls.NEXX_CLOUD_VIDEO.getAsString(entityId); } @Override protected String[] getRequiredTags() { return new String[]{ TAG_TITLE, TAG_ENTITY_ID, TAG_DURATION, TAG_PUBLICATION_DATE, TAG_CHANNEL_ID }; } @Override protected String getElementListTag() { return TAG_VIDEO_DTO_LIST; } }
gpl-3.0
sgdc3/AuthMeReloaded
src/main/java/fr/xephi/authme/util/Utils.java
11212
package fr.xephi.authme.util; import fr.xephi.authme.AuthMe; import fr.xephi.authme.ConsoleLogger; import fr.xephi.authme.cache.auth.PlayerCache; import fr.xephi.authme.cache.limbo.LimboCache; import fr.xephi.authme.cache.limbo.LimboPlayer; import fr.xephi.authme.events.AuthMeTeleportEvent; import fr.xephi.authme.permission.PermissionsManager; import fr.xephi.authme.permission.PlayerPermission; import fr.xephi.authme.settings.Settings; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collection; import java.util.Collections; /** * Utility class for various operations used in the codebase. */ public final class Utils { private static AuthMe plugin; private static Wrapper wrapper; private static boolean getOnlinePlayersIsCollection = false; private static Method getOnlinePlayers; static { wrapper = Wrapper.getInstance(); plugin = wrapper.getAuthMe(); initializeOnlinePlayersIsCollectionField(); } private Utils() { // Utility class } /** * Set the group of a player, by its AuthMe group type. * * @param player The player. * @param group The group type. * * @return True if succeeded, false otherwise. False is also returned if groups aren't supported * with the current permissions system. */ public static boolean setGroup(Player player, GroupType group) { // Check whether the permissions check is enabled if (!Settings.isPermissionCheckEnabled) { return false; } // Get the permissions manager, and make sure it's valid PermissionsManager permsMan = plugin.getPermissionsManager(); if (permsMan == null) { ConsoleLogger.showError("Failed to access permissions manager instance, shutting down."); return false; } // Make sure group support is available if (!permsMan.hasGroupSupport()) { ConsoleLogger.showError("The current permissions system doesn't have group support, unable to set group!"); return false; } switch (group) { case UNREGISTERED: // Remove the other group type groups, set the current group permsMan.removeGroups(player, Arrays.asList(Settings.getRegisteredGroup, Settings.getUnloggedinGroup)); return permsMan.addGroup(player, Settings.unRegisteredGroup); case REGISTERED: // Remove the other group type groups, set the current group permsMan.removeGroups(player, Arrays.asList(Settings.unRegisteredGroup, Settings.getUnloggedinGroup)); return permsMan.addGroup(player, Settings.getRegisteredGroup); case NOTLOGGEDIN: // Remove the other group type groups, set the current group permsMan.removeGroups(player, Arrays.asList(Settings.unRegisteredGroup, Settings.getRegisteredGroup)); return permsMan.addGroup(player, Settings.getUnloggedinGroup); case LOGGEDIN: // Get the limbo player data LimboPlayer limbo = LimboCache.getInstance().getLimboPlayer(player.getName().toLowerCase()); if (limbo == null) return false; // Get the players group String realGroup = limbo.getGroup(); // Remove the other group types groups, set the real group permsMan.removeGroups(player, Arrays.asList(Settings.unRegisteredGroup, Settings.getRegisteredGroup, Settings.getUnloggedinGroup)); return permsMan.addGroup(player, realGroup); default: return false; } } /** * TODO: This method requires better explanation. * <p> * Set the normal group of a player. * * @param player The player. * @param group The normal group. * * @return True on success, false on failure. */ public static boolean addNormal(Player player, String group) { if (!Settings.isPermissionCheckEnabled) { return false; } // Get the permissions manager, and make sure it's valid PermissionsManager permsMan = plugin.getPermissionsManager(); if (permsMan == null) { ConsoleLogger.showError("Failed to access permissions manager instance, aborting."); return false; } // Remove old groups permsMan.removeGroups(player, Arrays.asList(Settings.unRegisteredGroup, Settings.getRegisteredGroup, Settings.getUnloggedinGroup)); // Add the normal group, return the result return permsMan.addGroup(player, group); } // TODO: Move to a Manager public static boolean checkAuth(Player player) { if (player == null || Utils.isUnrestricted(player)) { return true; } if (PlayerCache.getInstance().isAuthenticated(player.getName())) { return true; } if (!Settings.isForcedRegistrationEnabled) { // TODO ljacqu 20151123: Use a getter to retrieve things from AuthMe if (!plugin.database.isAuthAvailable(player.getName())) { return true; } } return false; } public static boolean isUnrestricted(Player player) { return Settings.isAllowRestrictedIp && !Settings.getUnrestrictedName.isEmpty() && (Settings.getUnrestrictedName.contains(player.getName().toLowerCase())); } /** * Method packCoords. * * @param x double * @param y double * @param z double * @param w String * @param pl Player */ public static void packCoords(double x, double y, double z, String w, final Player pl) { World theWorld; if (w.equals("unavailableworld")) { theWorld = pl.getWorld(); } else { theWorld = Bukkit.getWorld(w); } if (theWorld == null) { theWorld = pl.getWorld(); } final World world = theWorld; final Location loc = new Location(world, x, y, z); Bukkit.getScheduler().scheduleSyncDelayedTask(wrapper.getAuthMe(), new Runnable() { @Override public void run() { AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(pl, loc); wrapper.getServer().getPluginManager().callEvent(tpEvent); if (!tpEvent.isCancelled()) { pl.teleport(tpEvent.getTo()); } } }); } /** * Force the game mode of a player. * * @param player the player to modify. */ public static void forceGM(Player player) { if (!plugin.getPermissionsManager().hasPermission(player, PlayerPermission.BYPASS_FORCE_SURVIVAL)) { player.setGameMode(GameMode.SURVIVAL); } } /** * Delete a given directory and all his content. * * @param directory File */ public static void purgeDirectory(File directory) { if (!directory.isDirectory()) { return; } File[] files = directory.listFiles(); if (files == null) { return; } for (File target : files) { if (target.isDirectory()) { purgeDirectory(target); } target.delete(); } } /** * Safe way to retrieve the list of online players from the server. Depending on the * implementation of the server, either an array of {@link Player} instances is being returned, * or a Collection. Always use this wrapper to retrieve online players instead of {@link * Bukkit#getOnlinePlayers()} directly. * * @return collection of online players * * @see <a href="https://www.spigotmc.org/threads/solved-cant-use-new-getonlineplayers.33061/">SpigotMC * forum</a> * @see <a href="http://stackoverflow.com/questions/32130851/player-changed-from-array-to-collection">StackOverflow</a> */ @SuppressWarnings("unchecked") public static Collection<? extends Player> getOnlinePlayers() { if (getOnlinePlayersIsCollection) { return Bukkit.getOnlinePlayers(); } try { // The lookup of a method via Reflections is rather expensive, so we keep a reference to it if (getOnlinePlayers == null) { getOnlinePlayers = Bukkit.class.getDeclaredMethod("getOnlinePlayers"); } Object obj = getOnlinePlayers.invoke(null); if (obj instanceof Collection<?>) { return (Collection<? extends Player>) obj; } else if (obj instanceof Player[]) { return Arrays.asList((Player[]) obj); } else { String type = (obj != null) ? obj.getClass().getName() : "null"; ConsoleLogger.showError("Unknown list of online players of type " + type); } } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { ConsoleLogger.showError("Could not retrieve list of online players: [" + e.getClass().getName() + "] " + e.getMessage()); } return Collections.emptyList(); } /** * Method run when the Utils class is loaded to verify whether or not the Bukkit implementation * returns the online players as a Collection. * * @see Utils#getOnlinePlayers() */ private static void initializeOnlinePlayersIsCollectionField() { try { Method method = Bukkit.class.getDeclaredMethod("getOnlinePlayers"); getOnlinePlayersIsCollection = method.getReturnType() == Collection.class; } catch (NoSuchMethodException e) { ConsoleLogger.showError("Error verifying if getOnlinePlayers is a collection! Method doesn't exist"); } } @SuppressWarnings("deprecation") public static Player getPlayer(String name) { name = name.toLowerCase(); return wrapper.getServer().getPlayer(name); } public static boolean isNPC(Player player) { return player.hasMetadata("NPC") || plugin.combatTagPlus != null && plugin.combatTagPlus.getNpcPlayerHelper().isNpc(player); } public static void teleportToSpawn(Player player) { if (Settings.isTeleportToSpawnEnabled && !Settings.noTeleport) { Location spawn = plugin.getSpawnLocation(player); AuthMeTeleportEvent tpEvent = new AuthMeTeleportEvent(player, spawn); wrapper.getServer().getPluginManager().callEvent(tpEvent); if (!tpEvent.isCancelled()) { player.teleport(tpEvent.getTo()); } } } /** */ public enum GroupType { UNREGISTERED, REGISTERED, NOTLOGGEDIN, LOGGEDIN } }
gpl-3.0
mstritt/orbit-image-analysis
src/test/java/com/actelion/research/orbit/imageAnalysis/test/TestShapeAnnotationList.java
7355
/* * Orbit, a versatile image analysis software for biological image-based quantification. * Copyright (C) 2009 - 2017 Idorsia Pharmaceuticals Ltd., Hegenheimermattweg 91, CH-4123 Allschwil, Switzerland. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.actelion.research.orbit.imageAnalysis.test; import com.actelion.research.orbit.beans.RawAnnotation; import com.actelion.research.orbit.imageAnalysis.models.ImageAnnotation; import com.actelion.research.orbit.imageAnalysis.models.PolygonExt; import com.actelion.research.orbit.imageAnalysis.models.RectangleExt; import com.actelion.research.orbit.imageAnalysis.models.ShapeAnnotationList; import com.actelion.research.orbit.imageAnalysis.utils.OrbitLogAppender; import com.actelion.research.orbit.imageAnalysis.utils.OrbitUtils; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.awt.*; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.*; public class TestShapeAnnotationList { static Logger logger = LoggerFactory.getLogger(TestShapeAnnotationList.class); @BeforeClass public static void setUp() { OrbitLogAppender.GUI_APPENDER = false; OrbitUtils.SLEEP_TASK=0; OrbitUtils.SLEEP_TILE=0; } @AfterClass public static void tearDown() { } @Test public void testOuterBounds() { Rectangle bounds = new Rectangle(100, 100, 200, 200); List<RawAnnotation> annos = new ArrayList<RawAnnotation>(); annos.add(new ImageAnnotation("incl1", new RectangleExt(50, 50, 10, 10), ImageAnnotation.SUBTYPE_INCLUSION, Color.yellow)); ShapeAnnotationList roi = new ShapeAnnotationList(annos, 0, bounds); logger.info("annosShape: " + roi); Rectangle re = roi.getBounds(); System.out.println("bounds: " + re); assertEquals(50, re.x); assertEquals(50, re.y); assertEquals(250, re.width); assertEquals(250, re.height); } @Test public void testROI() { List<RawAnnotation> annos = new ArrayList<RawAnnotation>(); annos.add(new ImageAnnotation("roi", new RectangleExt(100, 100, 200, 200), ImageAnnotation.SUBTYPE_ROI, Color.yellow)); annos.add(new ImageAnnotation("incl1", new RectangleExt(50, 50, 10, 10), ImageAnnotation.SUBTYPE_INCLUSION, Color.yellow)); ShapeAnnotationList roi = new ShapeAnnotationList(annos, 0, null); logger.info("annosShape: " + roi); Rectangle re = roi.getBounds(); System.out.println("bounds: " + re); assertEquals(50, re.x); assertEquals(50, re.y); assertEquals(250, re.width); assertEquals(250, re.height); assertTrue(roi.contains(110, 110)); assertTrue(roi.contains(299, 299)); assertTrue(roi.contains(51, 51)); assertFalse(roi.contains(70, 70)); assertFalse(roi.contains(310, 310)); assertFalse(roi.contains(40, 40)); } @Test public void testExcl() { List<RawAnnotation> annos = new ArrayList<RawAnnotation>(); annos.add(new ImageAnnotation("roi", new RectangleExt(100, 100, 200, 200), ImageAnnotation.SUBTYPE_ROI, Color.yellow)); annos.add(new ImageAnnotation("incl1", new RectangleExt(150, 150, 50, 50), ImageAnnotation.SUBTYPE_EXCLUSION, Color.yellow)); ShapeAnnotationList roi = new ShapeAnnotationList(annos, 0, null); logger.info("annosShape: " + roi); Rectangle re = roi.getBounds(); System.out.println("bounds: " + re); assertEquals(100, re.x); assertEquals(100, re.y); assertEquals(200, re.width); assertEquals(200, re.height); assertTrue(roi.contains(110, 110)); assertTrue(roi.contains(299, 299)); assertFalse(roi.contains(70, 70)); assertFalse(roi.contains(310, 310)); assertFalse(roi.contains(170, 170)); // excl } @Test public void testExclIncl() { List<RawAnnotation> annos = new ArrayList<RawAnnotation>(); annos.add(new ImageAnnotation("roi", new RectangleExt(100, 100, 200, 200), ImageAnnotation.SUBTYPE_ROI, Color.yellow)); annos.add(new ImageAnnotation("excl1", new RectangleExt(150, 150, 50, 50), ImageAnnotation.SUBTYPE_EXCLUSION, Color.yellow)); annos.add(new ImageAnnotation("incl1", new RectangleExt(170, 170, 20, 20), ImageAnnotation.SUBTYPE_INCLUSION, Color.yellow)); ShapeAnnotationList roi = new ShapeAnnotationList(annos, 0, null); logger.info("annosShape: " + roi); Rectangle re = roi.getBounds(); System.out.println("bounds: " + re); assertEquals(100, re.x); assertEquals(100, re.y); assertEquals(200, re.width); assertEquals(200, re.height); assertTrue(roi.contains(110, 110)); assertTrue(roi.contains(299, 299)); assertTrue(roi.contains(180, 180)); // incl assertFalse(roi.contains(70, 70)); assertFalse(roi.contains(310, 310)); assertFalse(roi.contains(160, 160)); // excl assertFalse(roi.contains(195, 195)); // excl } @Test public void testScale() { List<RawAnnotation> annos = new ArrayList<RawAnnotation>(); annos.add(new ImageAnnotation("excl1", new RectangleExt(25, 25, 50, 50), ImageAnnotation.SUBTYPE_EXCLUSION, Color.yellow)); annos.add(new ImageAnnotation("incl1", new RectangleExt(40, 40, 50, 50), ImageAnnotation.SUBTYPE_INCLUSION, Color.yellow)); PolygonExt p = new PolygonExt(); p.addPoint(0, 0); p.addPoint(100, 0); p.addPoint(100, 100); p.addPoint(0, 100); annos.add(new ImageAnnotation("incl1", p, ImageAnnotation.SUBTYPE_ROI, Color.yellow)); ShapeAnnotationList roi = new ShapeAnnotationList(annos, 0, null); System.out.println("scaled: " + roi); System.out.println("original bounds: " + roi.getBounds()); ShapeAnnotationList scaled = (ShapeAnnotationList) roi.getScaledInstance(50d, new Point(0, 0)); System.out.println("scaled: " + scaled); Rectangle re = scaled.getBounds(); System.out.println("scaled bounds: " + re); assertEquals(0, re.x); assertEquals(0, re.y); assertEquals(50, re.width); assertEquals(50, re.height); assertTrue(scaled.contains(0, 0)); assertTrue(scaled.contains(49, 49)); assertFalse(scaled.contains(15, 15)); // excl assertTrue(scaled.contains(24, 24)); // incl inside excl assertFalse(scaled.contains(50, 50)); assertFalse(scaled.contains(1000, 1000)); } }
gpl-3.0
wudiqishi123/test
src/test/java/thread/Product.java
563
package thread;/** * Created by zxl on 2018/5/25. */ /** * @description: * @author:zxl * @createTime:2018/5/25 16:43 */ public class Product { String id; String name; int age; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
gpl-3.0
xzzpig/PigUtils
WebSocket/src/main/java/com/github/xzzpig/pigutils/websocket/exceptions/InvalidHandshakeException.java
681
package com.github.xzzpig.pigutils.websocket.exceptions; import com.github.xzzpig.pigutils.websocket.framing.CloseFrame; public class InvalidHandshakeException extends InvalidDataException { /** * Serializable */ private static final long serialVersionUID = -1426533877490484964L; public InvalidHandshakeException() { super(CloseFrame.PROTOCOL_ERROR); } public InvalidHandshakeException(String arg0) { super(CloseFrame.PROTOCOL_ERROR, arg0); } public InvalidHandshakeException(String arg0, Throwable arg1) { super(CloseFrame.PROTOCOL_ERROR, arg0, arg1); } public InvalidHandshakeException(Throwable arg0) { super(CloseFrame.PROTOCOL_ERROR, arg0); } }
gpl-3.0
tonikelope/megabasterd
src/main/java/com/tonikelope/megabasterd/ChunkUploader.java
12121
package com.tonikelope.megabasterd; import static com.tonikelope.megabasterd.CryptTools.*; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.RandomAccessFile; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.SocketTimeoutException; import java.net.URL; import java.nio.channels.Channels; import java.util.logging.Level; import java.util.logging.Logger; import javax.crypto.CipherInputStream; /** * * @author tonikelope */ public class ChunkUploader implements Runnable, SecureSingleThreadNotifiable { public static final int MAX_CHUNK_ERROR = 50; private static final Logger LOG = Logger.getLogger(ChunkUploader.class.getName()); private final int _id; private final Upload _upload; private volatile boolean _exit; private final Object _secure_notify_lock; private volatile boolean _error_wait; private boolean _notified; private volatile boolean _chunk_exception; public ChunkUploader(int id, Upload upload) { _notified = false; _secure_notify_lock = new Object(); _id = id; _upload = upload; _chunk_exception = false; _exit = false; _error_wait = false; } public boolean isChunk_exception() { return _chunk_exception; } public void setExit(boolean exit) { _exit = exit; } public boolean isError_wait() { return _error_wait; } @Override public void secureNotify() { synchronized (_secure_notify_lock) { _notified = true; _secure_notify_lock.notify(); } } @Override public void secureWait() { synchronized (_secure_notify_lock) { while (!_notified) { try { _secure_notify_lock.wait(1000); } catch (InterruptedException ex) { _exit = true; LOG.log(Level.SEVERE, ex.getMessage()); } } _notified = false; } } public int getId() { return _id; } public boolean isExit() { return _exit; } public Upload getUpload() { return _upload; } public void setError_wait(boolean error_wait) { _error_wait = error_wait; } @Override public void run() { LOG.log(Level.INFO, "{0} ChunkUploader {1} hello! {2}", new Object[]{Thread.currentThread().getName(), getId(), _upload.getFile_name()}); long chunk_id = 0; byte[] buffer = new byte[MainPanel.DEFAULT_BYTE_BUFFER_SIZE]; boolean fatal_error = false; int conta_error = 0; try { while (!_upload.getMain_panel().isExit() && !_exit && !_upload.isStopped() && conta_error < MAX_CHUNK_ERROR && !fatal_error) { if (_upload.isPaused() && !_upload.isStopped()) { _upload.pause_worker(); secureWait(); } String worker_url = _upload.getUl_url(); int reads = 0, http_status; long tot_bytes_up; chunk_id = _upload.nextChunkId(); long chunk_offset = ChunkWriterManager.calculateChunkOffset(chunk_id, Upload.CHUNK_SIZE_MULTI); long chunk_size = ChunkWriterManager.calculateChunkSize(chunk_id, _upload.getFile_size(), chunk_offset, Upload.CHUNK_SIZE_MULTI); ChunkWriterManager.checkChunkID(chunk_id, _upload.getFile_size(), chunk_offset); String chunk_url = ChunkWriterManager.genChunkUrl(worker_url, _upload.getFile_size(), chunk_offset, chunk_size); URL url = new URL(chunk_url); HttpURLConnection con; if (MainPanel.isUse_proxy()) { con = (HttpURLConnection) url.openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(MainPanel.getProxy_host(), MainPanel.getProxy_port()))); if (MainPanel.getProxy_user() != null && !"".equals(MainPanel.getProxy_user())) { con.setRequestProperty("Proxy-Authorization", "Basic " + MiscTools.Bin2BASE64((MainPanel.getProxy_user() + ":" + MainPanel.getProxy_pass()).getBytes("UTF-8"))); } } else { con = (HttpURLConnection) url.openConnection(); } con.setConnectTimeout(Transference.HTTP_CONNECT_TIMEOUT); con.setReadTimeout(Transference.HTTP_READ_TIMEOUT); con.setRequestMethod("POST"); con.setDoOutput(true); con.setUseCaches(false); con.setFixedLengthStreamingMode(chunk_size); con.setRequestProperty("User-Agent", MainPanel.DEFAULT_USER_AGENT); tot_bytes_up = 0; boolean chunk_error = true; boolean timeout = false; try { if (!_exit) { RandomAccessFile f = new RandomAccessFile(_upload.getFile_name(), "r"); f.seek(chunk_offset); try (CipherInputStream cis = new CipherInputStream(new BufferedInputStream(Channels.newInputStream(f.getChannel())), genCrypter("AES", "AES/CTR/NoPadding", _upload.getByte_file_key(), forwardMEGALinkKeyIV(_upload.getByte_file_iv(), chunk_offset))); OutputStream out = new ThrottledOutputStream(con.getOutputStream(), _upload.getMain_panel().getStream_supervisor())) { LOG.log(Level.INFO, "{0} Uploading chunk {1} from worker {2} {3}...", new Object[]{Thread.currentThread().getName(), chunk_id, _id, _upload.getFile_name()}); while (!_exit && tot_bytes_up < chunk_size && (reads = cis.read(buffer)) != -1) { out.write(buffer, 0, reads); _upload.getPartialProgress().add((long) reads); _upload.getProgress_meter().secureNotify(); tot_bytes_up += reads; if (_upload.isPaused() && !_exit && !_upload.isStopped() && tot_bytes_up < chunk_size) { _upload.pause_worker(); secureWait(); } } } if (!_exit) { if ((http_status = con.getResponseCode()) != 200) { LOG.log(Level.INFO, "{0} Worker {1} Failed : HTTP error code : {2} {3}", new Object[]{Thread.currentThread().getName(), _id, http_status, _upload.getFile_name()}); } else if (tot_bytes_up == chunk_size || reads == -1) { if (_upload.getProgress() == _upload.getFile_size()) { _upload.getView().printStatusNormal("Waiting for completion handler ... ***DO NOT EXIT MEGABASTERD NOW***"); _upload.getView().getPause_button().setEnabled(false); } String httpresponse; try (InputStream is = con.getInputStream(); ByteArrayOutputStream byte_res = new ByteArrayOutputStream()) { while ((reads = is.read(buffer)) != -1) { byte_res.write(buffer, 0, reads); } httpresponse = new String(byte_res.toByteArray(), "UTF-8"); } if (httpresponse.length() > 0) { if (MegaAPI.checkMEGAError(httpresponse) != 0) { LOG.log(Level.WARNING, "{0} Worker {1} UPLOAD FAILED! (MEGA ERROR: {2}) {3}", new Object[]{Thread.currentThread().getName(), _id, MegaAPI.checkMEGAError(httpresponse), _upload.getFile_name()}); fatal_error = true; } else { LOG.log(Level.INFO, "{0} Worker {1} Completion handler -> {2} {3}", new Object[]{Thread.currentThread().getName(), _id, httpresponse, _upload.getFile_name()}); _upload.setCompletion_handler(httpresponse); chunk_error = false; } } else if (_upload.getProgress() != _upload.getFile_size() || _upload.getCompletion_handler() != null) { chunk_error = false; } } } if (_upload.getMain_panel().isExit()) { secureWait(); } } } catch (IOException ex) { if (ex instanceof SocketTimeoutException) { timeout = true; LOG.log(Level.SEVERE, "{0} Worker {1} {2} timeout reading chunk {3}", new Object[]{Thread.currentThread().getName(), _id, _upload.getFile_name(), chunk_id}); } else { LOG.log(Level.SEVERE, ex.getMessage()); } } finally { if (chunk_error) { LOG.log(Level.WARNING, "{0} Uploading chunk {1} from worker {2} FAILED! {3}...", new Object[]{Thread.currentThread().getName(), chunk_id, _id, _upload.getFile_name()}); _upload.rejectChunkId(chunk_id); if (tot_bytes_up > 0) { _upload.getPartialProgress().add(-1 * tot_bytes_up); _upload.getProgress_meter().secureNotify(); } if (fatal_error) { _upload.stopUploader("UPLOAD FAILED: FATAL ERROR"); LOG.log(Level.SEVERE, "UPLOAD FAILED: FATAL ERROR {0}", new Object[]{_upload.getFile_name()}); } else if (++conta_error == MAX_CHUNK_ERROR) { _upload.stopUploader("UPLOAD FAILED: too many errors"); LOG.log(Level.SEVERE, "UPLOAD FAILED: too many errors {0}", new Object[]{_upload.getFile_name()}); } else if (!_exit && !_upload.isStopped() && !timeout) { _error_wait = true; _upload.getView().updateSlotsStatus(); try { Thread.sleep(MiscTools.getWaitTimeExpBackOff(conta_error) * 1000); } catch (InterruptedException exc) { } _error_wait = false; _upload.getView().updateSlotsStatus(); } } else { LOG.log(Level.INFO, "{0} Worker {1} has uploaded chunk {2} {3}", new Object[]{Thread.currentThread().getName(), _id, chunk_id, _upload.getFile_name()}); conta_error = 0; } con.disconnect(); } } } catch (ChunkInvalidException ex) { _chunk_exception = true; } catch (OutOfMemoryError | Exception error) { _upload.stopUploader(error.getMessage()); LOG.log(Level.SEVERE, error.getMessage()); } _upload.stopThisSlot(this); _upload.getMac_generator().secureNotify(); LOG.log(Level.INFO, "{0} ChunkUploader [{1}] {2} bye bye...", new Object[]{Thread.currentThread().getName(), _id, _upload.getFile_name()}); } }
gpl-3.0
apatry/neo4j-lucene4-index
src/test/java/org/neo4j/index/impl/lucene/TestAutoIndexing.java
24993
/** * Copyright (c) 2002-2014 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.index.impl.lucene; import java.util.HashMap; import java.util.Map; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.neo4j.graphdb.DynamicRelationshipType; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.Transaction; import org.neo4j.graphdb.factory.GraphDatabaseSettings; import org.neo4j.graphdb.index.AutoIndexer; import org.neo4j.graphdb.index.Index; import org.neo4j.graphdb.index.ReadableIndex; import org.neo4j.graphdb.index.RelationshipIndex; import org.neo4j.test.ImpermanentGraphDatabase; import static org.junit.Assert.*; public class TestAutoIndexing { private ImpermanentGraphDatabase graphDb; private Transaction tx; private Map<String, String> config; private void newTransaction() { if ( tx != null ) { tx.success(); tx.finish(); } tx = graphDb.beginTx(); } private Map<String, String> getConfig() { if ( config == null ) { config = new HashMap<String, String>(); } return config; } @Before public void startDb() { graphDb = new ImpermanentGraphDatabase( getConfig() ); } @After public void stopDb() { if ( tx != null ) { tx.finish(); } if ( graphDb != null ) { graphDb.shutdown(); } tx = null; config = null; graphDb = null; } @Test public void testNodeAutoIndexFromAPISanity() { AutoIndexer<Node> autoIndexer = graphDb.index().getNodeAutoIndexer(); autoIndexer.startAutoIndexingProperty( "test_uuid" ); autoIndexer.setEnabled( true ); assertEquals( 1, autoIndexer.getAutoIndexedProperties().size() ); assertTrue( autoIndexer.getAutoIndexedProperties().contains( "test_uuid" ) ); newTransaction(); Node node1 = graphDb.createNode(); node1.setProperty( "test_uuid", "node1" ); Node node2 = graphDb.createNode(); node2.setProperty( "test_uuid", "node2" ); newTransaction(); assertEquals( node1, autoIndexer.getAutoIndex().get( "test_uuid", "node1" ).getSingle() ); assertEquals( node2, autoIndexer.getAutoIndex().get( "test_uuid", "node2" ).getSingle() ); } @Test public void testAutoIndexesReportReadOnly() { AutoIndexer<Node> autoIndexer = graphDb.index().getNodeAutoIndexer(); assertFalse( autoIndexer.getAutoIndex().isWriteable() ); autoIndexer.startAutoIndexingProperty( "test_uuid" ); autoIndexer.setEnabled( true ); assertFalse( autoIndexer.getAutoIndex().isWriteable() ); } @Test public void testChangesAreVisibleInTransaction() { AutoIndexer<Node> autoIndexer = graphDb.index().getNodeAutoIndexer(); autoIndexer.startAutoIndexingProperty( "nodeProp" ); autoIndexer.setEnabled( true ); newTransaction(); Node node1 = graphDb.createNode(); node1.setProperty( "nodeProp", "nodePropValue" ); node1.setProperty( "nodePropNonIndexable", "valueWhatever" ); ReadableIndex<Node> nodeIndex = autoIndexer.getAutoIndex(); assertEquals( node1, nodeIndex.get( "nodeProp", "nodePropValue" ).getSingle() ); newTransaction(); Node node2 = graphDb.createNode(); node2.setProperty( "nodeProp", "nodePropValue2" ); assertEquals( node2, nodeIndex.get( "nodeProp", "nodePropValue2" ).getSingle() ); node2.setProperty( "nodeProp", "nodePropValue3" ); assertEquals( node2, nodeIndex.get( "nodeProp", "nodePropValue3" ).getSingle() ); node2.removeProperty( "nodeProp" ); assertFalse( nodeIndex.get( "nodeProp", "nodePropValue2" ).hasNext() ); assertFalse( nodeIndex.get( "nodeProp", "nodePropValue3" ).hasNext() ); newTransaction(); assertEquals( node1, nodeIndex.get( "nodeProp", "nodePropValue" ).getSingle() ); assertFalse( nodeIndex.get( "nodeProp", "nodePropValue2" ).hasNext() ); assertFalse( nodeIndex.get( "nodeProp", "nodePropValue3" ).hasNext() ); } @Test public void testRelationshipAutoIndexFromAPISanity() { final String propNameToIndex = "test"; AutoIndexer<Relationship> autoIndexer = graphDb.index().getRelationshipAutoIndexer(); autoIndexer.startAutoIndexingProperty( propNameToIndex ); autoIndexer.setEnabled( true ); newTransaction(); Node node1 = graphDb.createNode(); Node node2 = graphDb.createNode(); Node node3 = graphDb.createNode(); Relationship rel12 = node1.createRelationshipTo( node2, DynamicRelationshipType.withName( "DYNAMIC" ) ); Relationship rel23 = node2.createRelationshipTo( node3, DynamicRelationshipType.withName( "DYNAMIC" ) ); rel12.setProperty( propNameToIndex, "rel12" ); rel23.setProperty( propNameToIndex, "rel23" ); newTransaction(); assertEquals( rel12, autoIndexer.getAutoIndex().get( propNameToIndex, "rel12" ).getSingle() ); assertEquals( rel23, autoIndexer.getAutoIndex().get( propNameToIndex, "rel23" ).getSingle() ); } @Test public void testConfigAndAPICompatibility() { stopDb(); config = new HashMap<String, String>(); config.put( GraphDatabaseSettings.node_keys_indexable.name(), "nodeProp1, nodeProp2" ); config.put( GraphDatabaseSettings.relationship_keys_indexable.name(), "relProp1, relProp2" ); config.put( GraphDatabaseSettings.node_auto_indexing.name(), "true" ); config.put( GraphDatabaseSettings.relationship_auto_indexing.name(), "true" ); startDb(); assertTrue( graphDb.index().getNodeAutoIndexer().isEnabled() ); assertTrue( graphDb.index().getRelationshipAutoIndexer().isEnabled() ); AutoIndexer<Node> autoNodeIndexer = graphDb.index().getNodeAutoIndexer(); // Start auto indexing a new and an already auto indexed autoNodeIndexer.startAutoIndexingProperty( "nodeProp1" ); autoNodeIndexer.startAutoIndexingProperty( "nodeProp3" ); assertEquals( 3, autoNodeIndexer.getAutoIndexedProperties().size() ); assertTrue( autoNodeIndexer.getAutoIndexedProperties().contains( "nodeProp1" ) ); assertTrue( autoNodeIndexer.getAutoIndexedProperties().contains( "nodeProp2" ) ); assertTrue( autoNodeIndexer.getAutoIndexedProperties().contains( "nodeProp3" ) ); } @Test public void testSmallGraphWithNonIndexableProps() throws Exception { stopDb(); config = new HashMap<String, String>(); config.put( GraphDatabaseSettings.node_keys_indexable.name(), "nodeProp1, nodeProp2" ); config.put( GraphDatabaseSettings.relationship_keys_indexable.name(), "relProp1, relProp2" ); config.put( GraphDatabaseSettings.node_auto_indexing.name(), "true" ); config.put( GraphDatabaseSettings.relationship_auto_indexing.name(), "true" ); startDb(); assertTrue( graphDb.index().getNodeAutoIndexer().isEnabled() ); assertTrue( graphDb.index().getRelationshipAutoIndexer().isEnabled() ); newTransaction(); // Build the graph, a 3-cycle Node node1 = graphDb.createNode(); Node node2 = graphDb.createNode(); Node node3 = graphDb.createNode(); Relationship rel12 = node1.createRelationshipTo( node2, DynamicRelationshipType.withName( "DYNAMIC" ) ); Relationship rel23 = node2.createRelationshipTo( node3, DynamicRelationshipType.withName( "DYNAMIC" ) ); Relationship rel31 = node3.createRelationshipTo( node1, DynamicRelationshipType.withName( "DYNAMIC" ) ); // Nodes node1.setProperty( "nodeProp1", "node1Value1" ); node1.setProperty( "nodePropNonIndexable1", "node1ValueNonIndexable" ); node2.setProperty( "nodeProp2", "node2Value1" ); node2.setProperty( "nodePropNonIndexable2", "node2ValueNonIndexable" ); node3.setProperty( "nodeProp1", "node3Value1" ); node3.setProperty( "nodeProp2", "node3Value2" ); node3.setProperty( "nodePropNonIndexable3", "node3ValueNonIndexable" ); // Relationships rel12.setProperty( "relProp1", "rel12Value1" ); rel12.setProperty( "relPropNonIndexable1", "rel12ValueNonIndexable" ); rel23.setProperty( "relProp2", "rel23Value1" ); rel23.setProperty( "relPropNonIndexable2", "rel23ValueNonIndexable" ); rel31.setProperty( "relProp1", "rel31Value1" ); rel31.setProperty( "relProp2", "rel31Value2" ); rel31.setProperty( "relPropNonIndexable3", "rel31ValueNonIndexable" ); newTransaction(); // Committed, time to check AutoIndexer<Node> autoNodeIndexer = graphDb.index().getNodeAutoIndexer(); assertEquals( node1, autoNodeIndexer.getAutoIndex().get( "nodeProp1", "node1Value1" ).getSingle() ); assertEquals( node2, autoNodeIndexer.getAutoIndex().get( "nodeProp2", "node2Value1" ).getSingle() ); assertEquals( node3, autoNodeIndexer.getAutoIndex().get( "nodeProp1", "node3Value1" ).getSingle() ); assertEquals( node3, autoNodeIndexer.getAutoIndex().get( "nodeProp2", "node3Value2" ).getSingle() ); assertFalse( autoNodeIndexer.getAutoIndex().get( "nodePropNonIndexable1", "node1ValueNonIndexable" ).hasNext() ); assertFalse( autoNodeIndexer.getAutoIndex().get( "nodePropNonIndexable2", "node2ValueNonIndexable" ).hasNext() ); assertFalse( autoNodeIndexer.getAutoIndex().get( "nodePropNonIndexable3", "node3ValueNonIndexable" ).hasNext() ); AutoIndexer<Relationship> autoRelIndexer = graphDb.index().getRelationshipAutoIndexer(); assertEquals( rel12, autoRelIndexer.getAutoIndex().get( "relProp1", "rel12Value1" ).getSingle() ); assertEquals( rel23, autoRelIndexer.getAutoIndex().get( "relProp2", "rel23Value1" ).getSingle() ); assertEquals( rel31, autoRelIndexer.getAutoIndex().get( "relProp1", "rel31Value1" ).getSingle() ); assertEquals( rel31, autoRelIndexer.getAutoIndex().get( "relProp2", "rel31Value2" ).getSingle() ); assertFalse( autoRelIndexer.getAutoIndex().get( "relPropNonIndexable1", "rel12ValueNonIndexable" ).hasNext() ); assertFalse( autoRelIndexer.getAutoIndex().get( "relPropNonIndexable2", "rel23ValueNonIndexable" ).hasNext() ); assertFalse( autoRelIndexer.getAutoIndex().get( "relPropNonIndexable3", "rel31ValueNonIndexable" ).hasNext() ); } @Test public void testDefaultIsOff() { newTransaction(); Node node1 = graphDb.createNode(); node1.setProperty( "testProp", "node1" ); newTransaction(); AutoIndexer<Node> autoIndexer = graphDb.index().getNodeAutoIndexer(); assertFalse( autoIndexer.getAutoIndex().get( "testProp", "node1" ).hasNext() ); } @Test public void testDefaulIfOffIsForEverything() { graphDb.index().getNodeAutoIndexer().setEnabled( true ); newTransaction(); Node node1 = graphDb.createNode(); node1.setProperty( "testProp", "node1" ); node1.setProperty( "testProp1", "node1" ); Node node2 = graphDb.createNode(); node2.setProperty( "testProp", "node2" ); node2.setProperty( "testProp1", "node2" ); newTransaction(); AutoIndexer<Node> autoIndexer = graphDb.index().getNodeAutoIndexer(); assertFalse( autoIndexer.getAutoIndex().get( "testProp", "node1" ).hasNext() ); assertFalse( autoIndexer.getAutoIndex().get( "testProp1", "node1" ).hasNext() ); assertFalse( autoIndexer.getAutoIndex().get( "testProp", "node2" ).hasNext() ); assertFalse( autoIndexer.getAutoIndex().get( "testProp1", "node2" ).hasNext() ); } @Test public void testDefaultIsOffIfExplicit() throws Exception { stopDb(); config = new HashMap<String, String>(); config.put( GraphDatabaseSettings.node_keys_indexable.name(), "nodeProp1, nodeProp2" ); config.put( GraphDatabaseSettings.relationship_keys_indexable.name(), "relProp1, relProp2" ); config.put( GraphDatabaseSettings.node_auto_indexing.name(), "false" ); config.put( GraphDatabaseSettings.relationship_auto_indexing.name(), "false" ); startDb(); AutoIndexer<Node> autoIndexer = graphDb.index().getNodeAutoIndexer(); autoIndexer.startAutoIndexingProperty( "testProp" ); newTransaction(); Node node1 = graphDb.createNode(); node1.setProperty( "nodeProp1", "node1" ); node1.setProperty( "nodeProp2", "node1" ); node1.setProperty( "testProp", "node1" ); newTransaction(); assertFalse( autoIndexer.getAutoIndex().get( "nodeProp1", "node1" ).hasNext() ); assertFalse( autoIndexer.getAutoIndex().get( "nodeProp2", "node1" ).hasNext() ); assertFalse( autoIndexer.getAutoIndex().get( "testProp", "node1" ).hasNext() ); } @Test public void testDefaultsAreSeparateForNodesAndRelationships() throws Exception { stopDb(); config = new HashMap<String, String>(); config.put( GraphDatabaseSettings.node_keys_indexable.name(), "propName" ); config.put( GraphDatabaseSettings.node_auto_indexing.name(), "true" ); // Now only node properties named propName should be indexed. startDb(); newTransaction(); Node node1 = graphDb.createNode(); Node node2 = graphDb.createNode(); node1.setProperty( "propName", "node1" ); node2.setProperty( "propName", "node2" ); node2.setProperty( "propName_", "node2" ); Relationship rel = node1.createRelationshipTo( node2, DynamicRelationshipType.withName( "DYNAMIC" ) ); rel.setProperty( "propName", "rel1" ); newTransaction(); ReadableIndex<Node> autoIndex = graphDb.index().getNodeAutoIndexer().getAutoIndex(); assertEquals( node1, autoIndex.get( "propName", "node1" ).getSingle() ); assertEquals( node2, autoIndex.get( "propName", "node2" ).getSingle() ); assertFalse( graphDb.index().getRelationshipAutoIndexer().getAutoIndex().get( "propName", "rel1" ).hasNext() ); } @Test public void testStartStopAutoIndexing() throws Exception { stopDb(); config = new HashMap<String, String>(); config.put( GraphDatabaseSettings.node_keys_indexable.name(), "propName" ); config.put( GraphDatabaseSettings.node_auto_indexing.name(), "true" ); // Now only node properties named propName should be indexed. startDb(); AutoIndexer<Node> autoIndexer = graphDb.index().getNodeAutoIndexer(); assertTrue( autoIndexer.isEnabled() ); autoIndexer.setEnabled( false ); assertFalse( autoIndexer.isEnabled() ); newTransaction(); Node node1 = graphDb.createNode(); Node node2 = graphDb.createNode(); node1.setProperty( "propName", "node" ); newTransaction(); assertFalse( autoIndexer.getAutoIndex().get( "nodeProp1", "node1" ).hasNext() ); autoIndexer.setEnabled( true ); node2.setProperty( "propName", "node" ); newTransaction(); assertEquals( node2, autoIndexer.getAutoIndex().get( "propName", "node" ).getSingle() ); } @Test public void testStopMonitoringProperty() { AutoIndexer<Node> autoIndexer = graphDb.index().getNodeAutoIndexer(); autoIndexer.setEnabled( true ); autoIndexer.startAutoIndexingProperty( "propName" ); newTransaction(); Node node1 = graphDb.createNode(); Node node2 = graphDb.createNode(); node1.setProperty( "propName", "node" ); newTransaction(); assertEquals( node1, autoIndexer.getAutoIndex().get( "propName", "node" ).getSingle() ); newTransaction(); // Setting just another property to autoindex autoIndexer.startAutoIndexingProperty( "propName2" ); autoIndexer.stopAutoIndexingProperty( "propName" ); node2.setProperty( "propName", "propValue" ); Node node3 = graphDb.createNode(); node3.setProperty( "propName2", "propValue" ); newTransaction(); // Now node2 must be not there, node3 must be there and node1 should not have been touched assertEquals( node1, autoIndexer.getAutoIndex().get( "propName", "node" ).getSingle() ); assertEquals( node3, autoIndexer.getAutoIndex().get( "propName2", "propValue" ).getSingle() ); // Now, since only propName2 is autoindexed, every other should be // removed when touched, such as node1's propName node1.setProperty( "propName", "newValue" ); newTransaction(); assertFalse( autoIndexer.getAutoIndex().get( "propName", "newValue" ).hasNext() ); } @Test public void testMutations() throws Exception { graphDb.index().getNodeAutoIndexer().startAutoIndexingProperty( "nodeProp1" ); graphDb.index().getNodeAutoIndexer().startAutoIndexingProperty( "nodeProp2" ); graphDb.index().getNodeAutoIndexer().setEnabled( true ); Transaction tx = graphDb.beginTx(); Node node1 = null, node2 = null, node3 = null, node4 = null; try { // Create the primitives node1 = graphDb.createNode(); node2 = graphDb.createNode(); node3 = graphDb.createNode(); node4 = graphDb.createNode(); // Add indexable and non-indexable properties node1.setProperty( "nodeProp1", "nodeProp1Value" ); node2.setProperty( "nodeProp2", "nodeProp2Value" ); node3.setProperty( "nodeProp1", "nodeProp3Value" ); node4.setProperty( "nodeProp2", "nodeProp4Value" ); // Make things persistent tx.success(); } catch ( Exception e ) { tx.failure(); } finally { tx.finish(); } /* * Here both nodes are indexed. To demonstrate removal, we stop * autoindexing nodeProp1. */ AutoIndexer<Node> nodeAutoIndexer = graphDb.index().getNodeAutoIndexer(); nodeAutoIndexer.stopAutoIndexingProperty( "nodeProp1" ); tx = graphDb.beginTx(); try { /* * nodeProp1 is no longer auto indexed. It will be * removed regardless. Note that node3 will remain. */ node1.setProperty( "nodeProp1", "nodeProp1Value2" ); /* * node2 will be auto updated */ node2.setProperty( "nodeProp2", "nodeProp2Value2" ); /* * remove node4 property nodeProp2 from index. */ node4.removeProperty( "nodeProp2" ); // Make things persistent tx.success(); } catch ( Exception e ) { tx.failure(); } finally { tx.finish(); } // Verify ReadableIndex<Node> nodeAutoIndex = nodeAutoIndexer.getAutoIndex(); // node1 is completely gone assertFalse( nodeAutoIndex.get( "nodeProp1", "nodeProp1Value" ).hasNext() ); assertFalse( nodeAutoIndex.get( "nodeProp1", "nodeProp1Value2" ).hasNext() ); // node2 is updated assertFalse( nodeAutoIndex.get( "nodeProp2", "nodeProp2Value" ).hasNext() ); assertEquals( node2, nodeAutoIndex.get( "nodeProp2", "nodeProp2Value2" ).getSingle() ); /* * node3 is still there, despite its nodeProp1 property not being monitored * any more because it was not touched, contrary to node1. */ assertEquals( node3, nodeAutoIndex.get( "nodeProp1", "nodeProp3Value" ).getSingle() ); // Finally, node4 is removed because the property was removed. assertFalse( nodeAutoIndex.get( "nodeProp2", "nodeProp4Value" ).hasNext() ); // END SNIPPET: Mutations } @Test public void testGettingAutoIndexByNameReturnsSomethingReadOnly() { // Create the node and relationship autoindexes graphDb.index().getNodeAutoIndexer().setEnabled( true ); graphDb.index().getNodeAutoIndexer().startAutoIndexingProperty( "nodeProp" ); graphDb.index().getRelationshipAutoIndexer().setEnabled( true ); graphDb.index().getRelationshipAutoIndexer().startAutoIndexingProperty( "relProp" ); newTransaction(); Node node1 = graphDb.createNode(); Node node2 = graphDb.createNode(); Relationship rel = node1.createRelationshipTo( node2, DynamicRelationshipType.withName( "FOO" ) ); node1.setProperty( "nodeProp", "nodePropValue" ); rel.setProperty( "relProp", "relPropValue" ); newTransaction(); assertEquals( 1, graphDb.index().nodeIndexNames().length ); assertEquals( 1, graphDb.index().relationshipIndexNames().length ); assertEquals( "node_auto_index", graphDb.index().nodeIndexNames()[0] ); assertEquals( "relationship_auto_index", graphDb.index().relationshipIndexNames()[0] ); Index<Node> nodeIndex = graphDb.index().forNodes( "node_auto_index" ); RelationshipIndex relIndex = graphDb.index().forRelationships( "relationship_auto_index" ); assertEquals( node1, nodeIndex.get( "nodeProp", "nodePropValue" ).getSingle() ); assertEquals( rel, relIndex.get( "relProp", "relPropValue" ).getSingle() ); try { nodeIndex.add( null, null, null ); fail("Auto indexes should not allow external manipulation"); } catch ( UnsupportedOperationException e ) { // good } try { relIndex.add( null, null, null ); fail( "Auto indexes should not allow external manipulation" ); } catch ( UnsupportedOperationException e ) { // good } } @Test public void testRemoveUnloadedHeavyProperty() { /* * Checks a bug where removing non-cached heavy properties * would cause NPE in auto indexer. */ graphDb.index().getNodeAutoIndexer().setEnabled( true ); graphDb.index().getNodeAutoIndexer().startAutoIndexingProperty( "nodeProp" ); newTransaction(); Node node1 = graphDb.createNode(); // Large array, needed for making sure this is a heavy property node1.setProperty( "nodeProp", new int[] { -1, 2, 3, 4, 5, 6, 1, 1, 1, 1 } ); newTransaction(); graphDb.getNodeManager().clearCache(); node1.removeProperty( "nodeProp" ); newTransaction(); assertFalse( node1.hasProperty( "nodeProp" ) ); } }
gpl-3.0
spyproof/NicknameManager
Core/src/main/java/be/spyproof/nickmanager/da/config/IConfigStorage.java
2060
package be.spyproof.nickmanager.da.config; import be.spyproof.nickmanager.da.player.IPlayerStorage; import java.util.List; import java.util.Map; /** * Created by Spyproof on 31/10/2016. */ public interface IConfigStorage { /** * Load the config from a file/data storage. * Should be able to be used to reload as well * <p> * If you obtain these values from a storage system that * updates its values in real time, this can be empty * * @throws Exception When the loading fails for any reason */ void load() throws Exception; /** * @return The language used for sending messages or other settings */ String getLanguage(); /** * @return If players need to accept the rules or not */ boolean mustAcceptRules(); /** * @return The amount of colours a player is allowed to have in their nickname * * @see be.spyproof.nickmanager.util.Colour */ int maxColours(); /** * @return The amount of styles a player is allowed to have in their nickname * * @see be.spyproof.nickmanager.util.Style */ int maxStyles(); /** * @return The maximum amount of character a player is allowed to have in their nickname with colour codes */ int maxNickLengthWithColour(); /** * @return The maximum amount of character a player is allowed to have in their nickname without colour codes */ int maxNickLengthWithoutColour(); /** * @return The player storage as specified in the config * * @throws Exception When the loading fails for any reason */ IPlayerStorage getPlayerStorage() throws Exception; /** * @return All cooldown categories on how long a player will have to wait before they can change their nickname again. * This must contain a key 'default' */ Map<String, Long> getCooldowns(); /** * @return A List of regex strings. A non formatted nickname can not match any of these values */ List<String> getBlacklist(); /** * @return If players nicknames will also be set in the tab list */ boolean setTabListName(); }
gpl-3.0
NJU-HouseWang/nju-eas-client
src/main/java/NJU/HouseWang/nju_eas_client/ui/MainUI/MsgBoxUI/SendMsgUI.java
8350
package NJU.HouseWang.nju_eas_client.ui.MainUI.MsgBoxUI; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.JTextField; import NJU.HouseWang.nju_eas_client.ui.CommonUI.Button.CommonBtn; import NJU.HouseWang.nju_eas_client.uiLogic.MsgBoxUILogic; import NJU.HouseWang.nju_eas_client.vo.Feedback; import NJU.HouseWang.nju_eas_client.vo.MessageVO; public class SendMsgUI { private MsgBoxUILogic logic = new MsgBoxUILogic(); private Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); private JFrame frame = new JFrame(); private JLabel receiveId = new JLabel("收件人ID:"); private JLabel receiveName = new JLabel("收件人:"); private JLabel topic = new JLabel("主题:"); private JLabel content = new JLabel("内容:"); private JTextField receiveIdtf = new JTextField(20); private JTextField receiveNametf = new JTextField(20); private JTextField topictf = new JTextField(60); private JTextArea contenttf = new JTextArea(); private JPanel panel = new JPanel(); private JPanel panel1 = new JPanel(null); private CommonBtn save_draftBtn = new CommonBtn("保存草稿"); private CommonBtn delBtn = new CommonBtn("删除草稿"); private CommonBtn sendBtn = new CommonBtn("发送"); private CommonBtn cancelBtn = new CommonBtn("取消"); private MessageVO msg = null; public SendMsgUI() { frame.setTitle("发送消息"); frame.setBounds((screen.width - 570) / 2, (screen.height - 480) / 2, 570, 480); frame.setLayout(null); receiveId.setFont(new Font("微软雅黑", Font.PLAIN, 14)); receiveName.setFont(new Font("微软雅黑", Font.PLAIN, 14)); topic.setFont(new Font("微软雅黑", Font.PLAIN, 14)); content.setFont(new Font("微软雅黑", Font.PLAIN, 14)); receiveIdtf.setFont(new Font("微软雅黑", Font.PLAIN, 14)); receiveNametf.setFont(new Font("微软雅黑", Font.PLAIN, 14)); receiveNametf.setEditable(false); topictf.setFont(new Font("微软雅黑", Font.PLAIN, 14)); contenttf.setFont(new Font("微软雅黑", Font.PLAIN, 14)); receiveId.setBounds(30, 20, 100, 30); receiveName.setBounds(310, 20, 100, 30); topic.setBounds(30, 50, 100, 30); content.setBounds(30, 80, 100, 30); receiveIdtf.setBounds(130, 23, 150, 24); receiveNametf.setBounds(380, 23, 150, 24); topictf.setBounds(130, 53, 400, 24); contenttf.setBounds(1, 1, 398, 298); contenttf.setColumns(50); contenttf.setLineWrap(true); contenttf.setAutoscrolls(true); panel1.setBackground(Color.gray); panel1.setBounds(130, 83, 400, 300); panel1.add(contenttf); panel.setBounds(10, 400, 530, 40); ((FlowLayout) panel.getLayout()).setHgap(80); panel.add(save_draftBtn); panel.add(sendBtn); panel.add(cancelBtn); frame.add(receiveId); frame.add(receiveName); frame.add(topic); frame.add(content); frame.add(receiveIdtf); frame.add(receiveNametf); frame.add(topictf); frame.add(panel1); frame.add(panel); frame.setResizable(false); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setVisible(true); setListener(); } public SendMsgUI(MessageVO msg) { this.msg = msg; frame.setTitle("发送消息"); frame.setBounds((screen.width - 570) / 2, (screen.height - 480) / 2, 570, 480); frame.setLayout(null); receiveId.setFont(new Font("微软雅黑", Font.PLAIN, 14)); receiveName.setFont(new Font("微软雅黑", Font.PLAIN, 14)); topic.setFont(new Font("微软雅黑", Font.PLAIN, 14)); content.setFont(new Font("微软雅黑", Font.PLAIN, 14)); receiveIdtf.setFont(new Font("微软雅黑", Font.PLAIN, 14)); receiveNametf.setFont(new Font("微软雅黑", Font.PLAIN, 14)); receiveNametf.setEditable(false); topictf.setFont(new Font("微软雅黑", Font.PLAIN, 14)); contenttf.setFont(new Font("微软雅黑", Font.PLAIN, 14)); receiveId.setBounds(30, 20, 100, 30); receiveName.setBounds(310, 20, 100, 30); topic.setBounds(30, 50, 100, 30); content.setBounds(30, 80, 100, 30); receiveIdtf.setBounds(130, 23, 150, 24); receiveNametf.setBounds(380, 23, 150, 24); topictf.setBounds(130, 53, 400, 24); contenttf.setBounds(1, 1, 398, 298); contenttf.setColumns(50); contenttf.setLineWrap(true); contenttf.setAutoscrolls(true); panel1.setBackground(Color.gray); panel1.setBounds(130, 83, 400, 300); panel1.add(contenttf); panel.setBounds(10, 400, 530, 40); ((FlowLayout) panel.getLayout()).setHgap(50); panel.add(save_draftBtn); panel.add(delBtn); panel.add(sendBtn); panel.add(cancelBtn); frame.add(receiveId); frame.add(receiveName); frame.add(topic); frame.add(content); frame.add(receiveIdtf); frame.add(receiveNametf); frame.add(topictf); frame.add(panel1); frame.add(panel); frame.setResizable(false); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setVisible(true); setListener(); receiveIdtf.setText(msg.recipientId); receiveNametf.setText(logic.showUserName(msg.senderId)); topictf.setText(msg.title); contenttf.append(msg.content); } private void setListener() { receiveIdtf.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent e) { if (receiveIdtf.getText().equals("")) { receiveNametf.setText(""); } else if (receiveIdtf.getText().equals("null")) { receiveNametf.setText(""); } else { receiveNametf.setText(logic.showUserName(receiveIdtf .getText())); } } }); save_draftBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { MessageVO newMsg = new MessageVO(); newMsg.senderId = "me"; newMsg.recipientId = receiveIdtf.getText().replaceAll(";", ";"); if (newMsg.recipientId.equals("")) { newMsg.recipientId = "null"; } newMsg.title = topictf.getText().replaceAll(";", ";"); if (newMsg.title.equals("")) { newMsg.title = "null"; } newMsg.content = contenttf.getText().replaceAll(";", ";"); if (newMsg.content.equals("")) { newMsg.content = "null"; } Feedback fb = logic.saveDraft(newMsg); JOptionPane.showMessageDialog(null, fb.getContent()); } }); sendBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { MessageVO newMsg = new MessageVO(); newMsg.senderId = "me"; newMsg.recipientId = receiveIdtf.getText().replaceAll(";", ";"); newMsg.title = topictf.getText().replaceAll(";", ";"); newMsg.content = contenttf.getText().replaceAll(";", ";"); if (newMsg.recipientId.equals("") || newMsg.recipientId.equals("") || newMsg.title.equals("") || newMsg.content.equals("")) { JOptionPane.showMessageDialog(null, "消息信息不完整"); return; } if (receiveNametf.getText().equals("")) { JOptionPane.showMessageDialog(null, "接收方不存在"); return; } Feedback fb = null; if (msg.id != null) { fb = logic.delMessage(2, msg.id); } if (fb == Feedback.OPERATION_SUCCEED) { fb = logic.sendMsg(newMsg); if (fb == Feedback.OPERATION_SUCCEED) { JOptionPane.showMessageDialog(null, "发送成功!"); frame.setVisible(false); frame.dispose(); } } else { JOptionPane.showMessageDialog(null, fb.getContent()); } } }); delBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { Feedback fb = logic.delMessage(2, msg.id); if (fb == Feedback.OPERATION_SUCCEED) { JOptionPane.showMessageDialog(null, "删除成功!"); frame.setVisible(false); frame.dispose(); } } }); cancelBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.setVisible(false); frame.dispose(); } }); } }
gpl-3.0
Ostrich-Emulators/semtool
gui/src/test/java/com/ostrichemulators/semtool/util/ExportUtilityTest.java
1435
package com.ostrichemulators.semtool.util; import static org.junit.Assert.*; import com.ostrichemulators.semtool.rdf.engine.api.IEngine; import com.ostrichemulators.semtool.ui.components.api.IPlaySheet; import java.awt.image.BufferedImage; import java.io.File; import java.util.List; import java.util.Map; import javax.swing.Action; import javax.swing.JFrame; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.eclipse.rdf4j.model.Model; import org.eclipse.rdf4j.model.Value; public class ExportUtilityTest { private BufferedImage image = null; private File testPDFFile = null; @Before public void setUp() throws Exception { image = GuiUtility.loadImage( "icons16/save_diskette1_16.png" ); } @After public void tearDown() throws Exception { image = null; if ( testPDFFile != null ) { testPDFFile.delete(); } } @Test public void testFileName() { File file = ExportUtility.getSuggestedFilename( "A Test File", ".pdf" ); assertTrue( "File name must contain the title of the component from which it is created", file.getName().contains( "A Test File" ) ); } @Test public void testExport() throws Exception { testPDFFile = File.createTempFile( "export-test-", ".pdf" ); ExportUtility.exportAsPdf( image, testPDFFile ); assertTrue( "File did not save properly.", testPDFFile.exists() ); assertNotEquals( "File is 0-length.", 0, testPDFFile.length() ); } }
gpl-3.0
nickapos/myBill
src/main/java/gr/oncrete/nick/mybill/BusinessLogic/FindRecurringPayments.java
2858
/* * Copyright (C) 2011 nickapos * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package gr.oncrete.nick.mybill.BusinessLogic; import gr.oncrete.nick.mybill.BusinessLogic.SelectInfo.SelectAverageExpensesPerCompanyInRange; import gr.oncrete.nick.mybill.BusinessLogic.SelectInfo.SelectAverageExpensesPerCompanyInRange.AnalyticsRecord; import java.time.LocalDateTime; import java.util.List; import java.util.stream.Collectors; /** * This class will compare the transactions of each month and find what are the * recurring payments through out the year * * @author nickapos */ public class FindRecurringPayments { SelectAverageExpensesPerCompanyInRange getMetrics; List<AnalyticsRecord> freqRecords; public FindRecurringPayments(int recordFrequency) { LocalDateTime now = LocalDateTime.now(); int currentMonth = now.getMonth().getValue(); int currentYear = now.getYear(); int remainingMonthsFromPrevYear = 12 - currentMonth; String periodStart = String.format("%s-%s-01", currentYear - 1, remainingMonthsFromPrevYear); String periodStop = String.format("%s-%s-31", currentYear, currentMonth); getMetrics = new SelectAverageExpensesPerCompanyInRange(periodStart, periodStop, "NumOfRecords"); freqRecords = selectRecordsOnFrequency(recordFrequency); } private List<AnalyticsRecord> selectRecordsOnFrequency(int freq) { List<AnalyticsRecord> a = getMetrics.getAnalyticsRecordList(); List<AnalyticsRecord> mostFrequent = a.stream().filter(record -> Integer.parseInt(record.getNumberOfRecords()) > freq).collect(Collectors.toList()); return mostFrequent; } public double returnMostFrequentTransactionsAverage() { return freqRecords.stream().mapToDouble(n -> n.getAvPriceDouble()).average().getAsDouble(); } public double returnMostFrequentTransactionsSum() { return freqRecords.stream().mapToDouble(n -> n.getAvPriceDouble()).sum(); } public int getNumberOfRecurringPayments() { return freqRecords.size(); } public String toString() { String results = freqRecords.stream().map(n -> n.toString()).collect(Collectors.joining("\n")); return results; } }
gpl-3.0
jmptrader/bgfinancas
src/badernageral/bgfinancas/modelo/Planejamento.java
5098
/* Copyright 2015 Jose Robson Mariano Alves This file is part of bgfinancas. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This package is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package badernageral.bgfinancas.modelo; import badernageral.bgfinancas.biblioteca.banco.Banco; import badernageral.bgfinancas.biblioteca.contrato.Modelo; import badernageral.bgfinancas.biblioteca.banco.Coluna; import badernageral.bgfinancas.biblioteca.sistema.Janela; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javafx.collections.FXCollections; import javafx.collections.ObservableList; public final class Planejamento extends Banco<Planejamento> implements Modelo { private static final String MODULO = RAIZ+"/modulo/planejamento"; public static final String FXML = MODULO+"/Planejamento.fxml"; public static final String FXML_FORMULARIO = MODULO+"/PlajenamentoFormulario.fxml"; public static final String TABELA = "planejamento"; private final Coluna idPlajenamento = new Coluna(TABELA, "id_planejamento"); private final Coluna mes = new Coluna(TABELA, "mes"); private final Coluna ano = new Coluna(TABELA, "ano"); private final Coluna valor = new Coluna(TABELA, "valor", "0.0"); public Planejamento(Integer mes, Integer ano){ this.mes.setValor(mes.toString()); this.ano.setValor(ano.toString()); } public Planejamento(String idPlajenamento, String mes, String ano, String valor){ this.idPlajenamento.setValor(idPlajenamento); this.mes.setValor(mes); this.ano.setValor(ano); this.valor.setValor(valor); } @Override protected Planejamento instanciar(ResultSet rs) throws SQLException{ return new Planejamento( rs.getString(idPlajenamento.getColuna()), rs.getString(mes.getColuna()), rs.getString(ano.getColuna()), rs.getString(valor.getColuna()) ); } @Override public boolean cadastrar(){ return this.insert(mes, ano, valor).commit(); } @Override public boolean alterar(){ return this.update(valor).where(idPlajenamento, "=").commit(); } @Override public boolean excluir(){ return this.delete(idPlajenamento, "=").commit(); } @Override public Planejamento consultar() { try{ this.select(idPlajenamento, mes, ano, valor); this.where(mes, "="); this.and(ano, "="); ResultSet rs = this.query(); if(rs != null && rs.next()){ return instanciar(rs); }else{ return null; } }catch(SQLException ex){ Janela.showException(ex); return null; } } @Override public ObservableList<Planejamento> listar(){ try{ this.select(idPlajenamento, mes, ano, valor); if(!mes.getValor().equals("") && !ano.getValor().equals("")){ this.where(mes, "="); this.and(ano, "="); } this.orderby(ano, mes); ResultSet rs = this.query(); if(rs != null){ List<Planejamento> Linhas = new ArrayList<>(); while(rs.next()){ Linhas.add(instanciar(rs)); } ObservableList<Planejamento> Resultado = FXCollections.observableList(Linhas); return Resultado; }else{ return null; } }catch(SQLException ex){ Janela.showException(ex); return null; } } public String getIdPlajenamento() { return idPlajenamento.getValor(); } public String getAno() { return ano.getValor(); } public String getMes() { return mes.getValor(); } public String getValor() { return valor.getValor(); } public void setValor(String valor){ this.valor.setValor(valor); } public Planejamento setAno(String ano){ this.ano.setValor(ano); return this; } public Planejamento setMes(String mes){ this.mes.setValor(mes); return this; } @Override protected Planejamento getThis() { return this; } }
gpl-3.0
ricecakesoftware/CommunityMedicalLink
ricecakesoftware.communitymedicallink.hl7/src/org/hl7/v3/COCTMT080000UVContent1.java
6226
package org.hl7.v3; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>COCT_MT080000UV.Content1 complex typeのJavaクラス。 * * <p>次のスキーマ・フラグメントは、このクラス内に含まれる予期されるコンテンツを指定します。 * * <pre> * &lt;complexType name="COCT_MT080000UV.Content1"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;group ref="{urn:hl7-org:v3}InfrastructureRootElements"/> * &lt;element name="container" type="{urn:hl7-org:v3}COCT_MT080000UV.Container"/> * &lt;/sequence> * &lt;attGroup ref="{urn:hl7-org:v3}InfrastructureRootAttributes"/> * &lt;attribute name="nullFlavor" type="{urn:hl7-org:v3}NullFlavor" /> * &lt;attribute name="classCode" use="required" type="{urn:hl7-org:v3}RoleClass" fixed="CONT" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "COCT_MT080000UV.Content1", propOrder = { "realmCode", "typeId", "templateId", "container" }) public class COCTMT080000UVContent1 { protected List<CS> realmCode; protected II typeId; protected List<II> templateId; @XmlElement(required = true) protected COCTMT080000UVContainer container; @XmlAttribute(name = "nullFlavor") protected List<String> nullFlavor; @XmlAttribute(name = "classCode", required = true) protected List<String> classCode; /** * Gets the value of the realmCode property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the realmCode property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRealmCode().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link CS } * * */ public List<CS> getRealmCode() { if (realmCode == null) { realmCode = new ArrayList<CS>(); } return this.realmCode; } /** * typeIdプロパティの値を取得します。 * * @return * possible object is * {@link II } * */ public II getTypeId() { return typeId; } /** * typeIdプロパティの値を設定します。 * * @param value * allowed object is * {@link II } * */ public void setTypeId(II value) { this.typeId = value; } /** * Gets the value of the templateId property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the templateId property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTemplateId().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link II } * * */ public List<II> getTemplateId() { if (templateId == null) { templateId = new ArrayList<II>(); } return this.templateId; } /** * containerプロパティの値を取得します。 * * @return * possible object is * {@link COCTMT080000UVContainer } * */ public COCTMT080000UVContainer getContainer() { return container; } /** * containerプロパティの値を設定します。 * * @param value * allowed object is * {@link COCTMT080000UVContainer } * */ public void setContainer(COCTMT080000UVContainer value) { this.container = value; } /** * Gets the value of the nullFlavor property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the nullFlavor property. * * <p> * For example, to add a new item, do as follows: * <pre> * getNullFlavor().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getNullFlavor() { if (nullFlavor == null) { nullFlavor = new ArrayList<String>(); } return this.nullFlavor; } /** * Gets the value of the classCode property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the classCode property. * * <p> * For example, to add a new item, do as follows: * <pre> * getClassCode().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getClassCode() { if (classCode == null) { classCode = new ArrayList<String>(); } return this.classCode; } }
gpl-3.0
greenaddress/GreenBits
app/src/main/java/com/greenaddress/greenapi/HDClientKey.java
1600
package com.greenaddress.greenapi; import android.util.SparseArray; import org.bitcoinj.crypto.ChildNumber; import org.bitcoinj.crypto.DeterministicKey; import org.bitcoinj.crypto.HDKeyDerivation; import java.util.ArrayList; import java.util.Map; public class HDClientKey { private static final SparseArray<DeterministicKey> mClientKeys = new SparseArray<>(); // // Temporary methods for use while converting from DeterministicKey private static DeterministicKey deriveChildKey(final DeterministicKey parent, final Integer childNum) { return HDKeyDerivation.deriveChildKey(parent, new ChildNumber(childNum)); } public static DeterministicKey getMyPublicKey(final int subAccount, final Integer pointer) { final DeterministicKey ret = deriveChildKey(mClientKeys.get(subAccount), HDKey.BRANCH_REGULAR); if (pointer == null) return ret; return deriveChildKey(ret, pointer); // Child } public static void resetCache(final ArrayList<Map<String, Object>> subAccounts, final ISigningWallet hdParent) { synchronized (mClientKeys) { mClientKeys.clear(); if (hdParent == null) return; mClientKeys.put(0, hdParent.getSubAccountPublicKey(0)); for (final Map<String, Object> subaccount : subAccounts) { final DeterministicKey key = hdParent.getSubAccountPublicKey((Integer) subaccount.get("pointer")); mClientKeys.put((Integer) subaccount.get("pointer"), key); } } } }
gpl-3.0
fduminy/swing-components
src/main/java/fr/duminy/components/swing/i18n/AbstractI18nAction.java
1845
/** * Swing-Components is a library of swing components. * * Copyright (C) 2013-2016 Fabien DUMINY (fabien [dot] duminy [at] webmails [dot] com) * * Swing-Components is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * Swing-Components is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. */ package fr.duminy.components.swing.i18n; import fr.duminy.components.swing.Bundle; import javax.swing.*; /** * Abstract implementation of {@link I18nAction}. * * @param <M> The class of message bundle. */ public abstract class AbstractI18nAction<M> extends AbstractAction implements I18nAction { private final Class<M> messagesClass; public AbstractI18nAction(Class<M> messagesClass) { this.messagesClass = messagesClass; } @Override public final void updateMessages() { putValue(Action.NAME, getName(getBundle())); putValue(Action.SHORT_DESCRIPTION, getShortDescription(getBundle())); } protected final M getBundle() { return getBundle(messagesClass); } M getBundle(Class<M> messagesClass) { return Bundle.getBundle(messagesClass); } abstract protected String getShortDescription(M bundle); protected String getName(M bundle) { return null; } }
gpl-3.0