answer
stringlengths
17
10.2M
package org.apache.commons.fileupload; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.io.OutputStream; /** * <p> The default implementation of the * {@link org.apache.commons.fileupload.FileItem FileItem} interface. * * <p> After retrieving an instance of this class from a {@link * org.apache.commons.fileupload.FileUpload FileUpload} instance (see * {@link org.apache.commons.fileupload.FileUpload * #parseRequest(javax.servlet.http.HttpServletRequest)}), you may * either request all contents of file at once using {@link #get()} or * request an {@link java.io.InputStream InputStream} with * {@link #getInputStream()} and process the file without attempting to load * it into memory, which may come handy with large files. * * @author <a href="mailto:Rafal.Krzewski@e-point.pl">Rafal Krzewski</a> * @author <a href="mailto:sean@informage.net">Sean Legassick</a> * @author <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a> * @author <a href="mailto:jmcnally@apache.org">John McNally</a> * @author <a href="mailto:martinc@apache.org">Martin Cooper</a> * @author Sean C. Sullivan * * @version $Id: DefaultFileItem.java,v 1.16 2003/03/07 23:29:26 sullis Exp $ */ public class DefaultFileItem implements FileItem { /** * Counter used in unique identifier generation. */ private static int counter = 0; /** * The original filename in the user's filesystem. */ private String fileName; /** * The content type passed by the browser, or <code>null</code> if * not defined. */ private String contentType; /** * Cached contents of the file. */ private byte[] content; /** * Temporary storage location on disk. */ private File storeLocation; /** * Temporary storage for in-memory files. */ private ByteArrayOutputStream byteStream; /** * The name of the form field as provided by the browser. */ private String fieldName; /** * Whether or not this item is a simple form field. */ private boolean isFormField; /** * Default constructor. * * @see #DefaultFileItem(String, String) * */ public DefaultFileItem() { } /** * Constructs a new <code>DefaultFileItem</code> instance. * * <p>Use {@link #newInstance(String,String,String,int,int)} to * instantiate <code>DefaultFileItem</code>s. * * @param fileName The original filename in the user's filesystem. * @param contentType The content type passed by the browser or * <code>null</code> if not defined. * * @see #DefaultFileItem() * */ protected DefaultFileItem(String fileName, String contentType) { this.fileName = fileName; this.contentType = contentType; } /** * Returns an {@link java.io.InputStream InputStream} that can be * used to retrieve the contents of the file. * * @return An {@link java.io.InputStream InputStream} that can be * used to retrieve the contents of the file. * * @exception IOException if an error occurs. */ public InputStream getInputStream() throws IOException { if (content == null) { if (storeLocation != null) { return new FileInputStream(storeLocation); } else { content = byteStream.toByteArray(); byteStream = null; } } return new ByteArrayInputStream(content); } /** * Returns the content type passed by the browser or <code>null</code> if * not defined. * * @return The content type passed by the browser or <code>null</code> if * not defined. */ public String getContentType() { return contentType; } /** * Returns the original filename in the client's filesystem. * * @return The original filename in the client's filesystem. */ public String getName() { return fileName; } /** * Provides a hint as to whether or not the file contents will be read * from memory. * * @return <code>true</code> if the file contents will be read * from memory. */ public boolean isInMemory() { return (content != null || byteStream != null); } /** * Returns the size of the file. * * @return The size of the file, in bytes. */ public long getSize() { if (storeLocation != null) { return storeLocation.length(); } else if (byteStream != null) { return byteStream.size(); } else { return content.length; } } /** * Returns the contents of the file as an array of bytes. If the * contents of the file were not yet cached in memory, they will be * loaded from the disk storage and cached. * * @return The contents of the file as an array of bytes. */ public byte[] get() { if (content == null) { if (storeLocation != null) { content = new byte[(int) getSize()]; FileInputStream fis = null; try { fis = new FileInputStream(storeLocation); fis.read(content); } catch (Exception e) { content = null; } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { // ignore } } } } else { content = byteStream.toByteArray(); byteStream = null; } } return content; } /** * Returns the contents of the file as a String, using the specified * encoding. This method uses {@link #get()} to retrieve the * contents of the file. * * @param encoding The character encoding to use. * * @return The contents of the file, as a string. * * @exception UnsupportedEncodingException if the requested character * encoding is not available. */ public String getString(String encoding) throws UnsupportedEncodingException { return new String(get(), encoding); } /** * Returns the contents of the file as a String, using the default * character encoding. This method uses {@link #get()} to retrieve the * contents of the file. * * @return The contents of the file, as a string. */ public String getString() { return new String(get()); } /** * Returns the {@link java.io.File} object for the <code>FileItem</code>'s * data's temporary location on the disk. Note that for * <code>FileItem</code>s that have their data stored in memory, * this method will return <code>null</code>. When handling large * files, you can use {@link java.io.File#renameTo(File)} to * move the file to new location without copying the data, if the * source and destination locations reside within the same logical * volume. * * @return The data file, or <code>null</code> if the data is stored in * memory. */ public File getStoreLocation() { return storeLocation; } /** * A convenience method to write an uploaded file to disk. The client code * is not concerned whether or not the file is stored in memory, or on disk * in a temporary location. They just want to write the uploaded file to * disk. * * @param file The full path to location where the uploaded file should * be stored. * * @exception Exception if an error occurs. */ public void write(String file) throws Exception { if (isInMemory()) { FileOutputStream fout = null; try { fout = new FileOutputStream(file); fout.write(get()); } finally { if (fout != null) { fout.close(); } } } else if (storeLocation != null) { /* * The uploaded file is being stored on disk * in a temporary location so move it to the * desired file. */ if (storeLocation.renameTo(new File(file)) == false) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream( new FileInputStream(storeLocation)); out = new BufferedOutputStream(new FileOutputStream(file)); byte[] bytes = new byte[2048]; int s = 0; while ((s = in.read(bytes)) != -1) { out.write(bytes, 0, s); } } finally { try { in.close(); } catch (Exception e) { // ignore } try { out.close(); } catch (Exception e) { // ignore } } } } else { /* * For whatever reason we cannot write the * file to disk. */ throw new FileUploadException( "Cannot write uploaded file to disk!"); } } /** * Deletes the underlying storage for a file item, including deleting any * associated temporary disk file. Although this storage will be deleted * automatically when the <code>FileItem</code> instance is garbage * collected, this method can be used to ensure that this is done at an * earlier time, thus preserving system resources. */ public void delete() { byteStream = null; content = null; if (storeLocation != null && storeLocation.exists()) { storeLocation.delete(); } } /** * Returns the name of the field in the multipart form corresponding to * this file item. * * @return The name of the form field. * * @see #setFieldName(String) * */ public String getFieldName() { return fieldName; } /** * Sets the field name used to reference this file item. * * @param fieldName The name of the form field. * * @see #getFieldName() * */ public void setFieldName(String fieldName) { this.fieldName = fieldName; } /** * Determines whether or not a <code>FileItem</code> instance represents * a simple form field. * * @return <code>true</code> if the instance represents a simple form * field; <code>false</code> if it represents an uploaded file. * * @see #setIsFormField(boolean) * */ public boolean isFormField() { return isFormField; } /** * Specifies whether or not a <code>FileItem</code> instance represents * a simple form field. * * @param state <code>true</code> if the instance represents a simple form * field; <code>false</code> if it represents an uploaded file. * * @see #isFormField() * */ public void setIsFormField(boolean state) { isFormField = state; } /** * Returns an {@link java.io.OutputStream OutputStream} that can * be used for storing the contents of the file. * * @return An {@link java.io.OutputStream OutputStream} that can be used * for storing the contensts of the file. * * @exception IOException if an error occurs. */ public OutputStream getOutputStream() throws IOException { if (storeLocation == null) { return byteStream; } else { return new FileOutputStream(storeLocation); } } /** * Removes the file contents from the temporary storage. */ protected void finalize() { if (storeLocation != null && storeLocation.exists()) { storeLocation.delete(); } } /** * Instantiates a DefaultFileItem. It uses <code>requestSize</code> to * decide what temporary storage approach the new item should take. * * @param path The path under which temporary files should be * created. * @param name The original filename in the client's filesystem. * @param contentType The content type passed by the browser, or * <code>null</code> if not defined. * @param requestSize The total size of the POST request this item * belongs to. * @param threshold The maximum size to store in memory. * * @return A <code>DefaultFileItem</code> instance. */ public static FileItem newInstance(String path, String name, String contentType, int requestSize, int threshold) { DefaultFileItem item = new DefaultFileItem(name, contentType); if (requestSize > threshold) { String fileName = getUniqueId(); fileName = "upload_" + fileName + ".tmp"; fileName = path + "/" + fileName; File f = new File(fileName); f.deleteOnExit(); item.storeLocation = f; } else { item.byteStream = new ByteArrayOutputStream(); } return item; } /** * Returns an identifier that is unique within the class loader used to * load this class, but does not have random-like apearance. * * @return A String with the non-random looking instance identifier. */ private static String getUniqueId() { int current; synchronized (DefaultFileItem.class) { current = counter++; } String id = Integer.toString(current); // If you manage to get more than 100 million of ids, you'll // start getting ids longer than 8 characters. if (current < 100000000) { id = ("00000000" + id).substring(id.length()); } return id; } }
package com.ezardlabs.dethsquare; import com.ezardlabs.dethsquare.util.IOUtils; import com.ezardlabs.dethsquare.util.RenderUtils; import java.io.BufferedReader; import java.io.IOException; import java.util.HashMap; public final class TextureAtlas { final String imagePath; final String mapPath; private final HashMap<String, Sprite> atlas = new HashMap<>(); public int textureName = -1; public int width; public int height; private TextureAtlas(String imagePath, String mapPath, int tileWidth, int tileHeight) { this.imagePath = imagePath; this.mapPath = mapPath; int[] data; if (Renderer.textures.containsKey(imagePath)) { data = Renderer.textures.get(imagePath); } else { data = RenderUtils.loadImage(imagePath); Renderer.textures.put(imagePath, data); } textureName = data[0]; width = data[1]; height = data[2]; if(mapPath != null) { try { String temp; BufferedReader reader = IOUtils.getReader(mapPath); while ((temp = reader.readLine()) != null) { String[] split = temp.split(" = "); String[] split2 = split[1].split(" "); atlas.put(split[0], new Sprite(Float.parseFloat(split2[0]) / width, Float.parseFloat(split2[1]) / height, Float.parseFloat(split2[2]) / width, Float.parseFloat(split2[3]) / height)); } } catch (IOException ignored) { } } else { int count = 0; for(int y = 0; y < height; y += tileHeight) { for(int x = 0; x < width; x += tileWidth) { atlas.put(String.valueOf(count++), new Sprite( (float) x / width, (float) y / height, (float) tileWidth / width, (float) tileHeight / height ) ); } } } } public TextureAtlas(String imagePath, String mapPath) { this(imagePath, mapPath, 0, 0); } public TextureAtlas(String imagePath, int tileWidth, int tileHeight) { this(imagePath, null, tileWidth, tileHeight); } public Sprite getSprite(String name) { if (!atlas.containsKey(name)) throw new Error("Sprite \"" + name + "\" not found in " + mapPath); Sprite sprite = atlas.get(name); return sprite; } public Sprite[] getSprites() { return atlas.values().toArray(new Sprite[atlas.size()]); } public static class Sprite { public float u; public float v; public float w; public float h; public Sprite(float u, float v, float w, float h) { this.u = u; this.v = v; this.w = w; this.h = h; } public String toString() { return "Sprite(u: " + u + ", v: " + v + ", w: " + w + ", h: " + h + ")"; } } }
package nl.mpi.arbil.ui.fieldeditors; import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyEvent; import java.util.List; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.ActionMap; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.InputMap; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JInternalFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.SwingConstants; import javax.swing.event.InternalFrameAdapter; import javax.swing.event.InternalFrameEvent; import nl.mpi.arbil.ArbilIcons; import nl.mpi.arbil.data.ArbilField; import nl.mpi.arbil.ui.ArbilTable; import nl.mpi.arbil.ui.ArbilWindowManager; import nl.mpi.arbil.data.ArbilDataNode; import nl.mpi.arbil.data.ArbilDataNodeContainer; public class ArbilLongFieldEditor extends JPanel implements ArbilDataNodeContainer { ArbilTable parentTable = null; ArbilDataNode parentArbilDataNode; ArbilField[] arbilFields; String fieldName = "unknown"; JTabbedPane tabPane; int selectedField = -1; // Object[] cellValue; JTextField keyEditorFields[] = null; JTextArea fieldEditors[] = null; JComboBox fieldLanguageBoxs[] = null; JInternalFrame editorFrame = null; private JPanel contentPanel; private List<ArbilField[]> parentFieldList; private JButton prevButton; private JButton nextButton; public ArbilLongFieldEditor() { this(null); } public ArbilLongFieldEditor(ArbilTable parentTableLocal) { parentTable = parentTableLocal; setInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, new lfeInputMap(getInputMap())); setActionMap(new lfeActionMap(getActionMap())); // Window has two panels: content panel and panel with previous/next buttons contentPanel = new JPanel(); setLayout(new BorderLayout()); contentPanel.setLayout(new BorderLayout()); this.add(contentPanel, BorderLayout.CENTER); this.add(createPreviousNextPanel(), BorderLayout.PAGE_END); } public void showEditor(ArbilField[] cellValueLocal, String currentEditorText, int selectedFieldLocal) { selectedField = selectedFieldLocal; arbilFields = cellValueLocal; parentArbilDataNode = arbilFields[0].parentDataNode; // todo: registerContainer should not be done on the parent node and the remove should scan all child nodes also, such that deleting a child like and actor would remove the correct nodes parentArbilDataNode.registerContainer(this); fieldName = arbilFields[0].getTranslateFieldName(); setParentFieldList(); contentPanel.removeAll(); JLabel parentLabel = new JLabel(parentArbilDataNode.toString(), ArbilIcons.getSingleInstance().getIconForNode(parentArbilDataNode), SwingConstants.LEADING); parentLabel.setBorder(BorderFactory.createEmptyBorder(5, 2, 0, 0)); contentPanel.add(parentLabel, BorderLayout.NORTH); tabPane = new JTabbedPane(); final JComponent focusedTabTextArea = populateTabbedPane(currentEditorText); contentPanel.add(tabPane, BorderLayout.CENTER); // todo: add all unused attributes as editable text editorFrame = ArbilWindowManager.getSingleInstance().createWindow(getWindowTitle(), this); editorFrame.addInternalFrameListener(new InternalFrameAdapter() { @Override public void internalFrameClosed(InternalFrameEvent e) { // deregister component from imditreenode parentArbilDataNode.removeContainer(ArbilLongFieldEditor.this); super.internalFrameClosed(e); if (parentTable != null) { parentTable.requestFocusInWindow(); } } }); if (selectedField != -1) { tabPane.setSelectedIndex(selectedField); } else { tabPane.setSelectedIndex(0); } setNavigationEnabled(); requestFocusFor(focusedTabTextArea); } private JPanel createKeyEditor(final int cellFieldIndex) { // if this is a key type field then show the editing options JPanel keyNamePanel = new JPanel(new BorderLayout()); keyEditorFields[cellFieldIndex] = new JTextField(arbilFields[cellFieldIndex].getKeyName()); keyEditorFields[cellFieldIndex].addFocusListener(editorFocusListener); keyEditorFields[cellFieldIndex].setEditable(parentArbilDataNode.getParentDomNode().isEditable()); keyNamePanel.add(new JLabel("Key Name:"), BorderLayout.LINE_START); keyNamePanel.add(keyEditorFields[cellFieldIndex], BorderLayout.CENTER); return keyNamePanel; } private JPanel createLanguageBox(final int cellFieldIndex) { fieldLanguageBoxs[cellFieldIndex] = new LanguageIdBox(arbilFields[cellFieldIndex], null); JPanel languagePanel = new JPanel(new BorderLayout()); languagePanel.add(new JLabel("Language:"), BorderLayout.LINE_START); if (parentArbilDataNode.getParentDomNode().isEditable()) { languagePanel.add(fieldLanguageBoxs[cellFieldIndex], BorderLayout.CENTER); } else { languagePanel.add(new JLabel(fieldLanguageBoxs[cellFieldIndex].getSelectedItem().toString()), BorderLayout.CENTER); } return languagePanel; } private JComponent populateTabbedPane(String currentEditorText) { //int titleCount = 1; JTextArea focusComponent = null; fieldEditors = new JTextArea[arbilFields.length]; keyEditorFields = new JTextField[arbilFields.length]; fieldLanguageBoxs = new JComboBox[arbilFields.length]; for (int cellFieldIndex = 0; cellFieldIndex < arbilFields.length; cellFieldIndex++) { fieldEditors[cellFieldIndex] = new JTextArea(); if (focusComponent == null || selectedField == cellFieldIndex) { // set the selected field as the first one or in the case of a single node being selected tab to its pane focusComponent = fieldEditors[cellFieldIndex]; } JPanel tabPanel = createTabPanel(cellFieldIndex, currentEditorText, createFieldDescription()); tabPane.add(fieldName + ((arbilFields.length <= 1) ? "" : " " + (cellFieldIndex + 1)), tabPanel); } // If field has language attribute but no language has been chosen yet, request focus on the language select drop down if (arbilFields[selectedField].getLanguageId() != null && arbilFields[selectedField].getLanguageId().isEmpty()) { return fieldLanguageBoxs[selectedField]; } else { return focusComponent; } } private JPanel createTabPanel(final int cellFieldIndex, String currentEditorText, JComponent fieldDescription) { JPanel tabPanel = new JPanel(); JPanel tabTitlePanel = new JPanel(); tabPanel.setLayout(new BorderLayout()); tabTitlePanel.setLayout(new BoxLayout(tabTitlePanel, BoxLayout.PAGE_AXIS)); tabTitlePanel.add(fieldDescription); initFieldEditor(cellFieldIndex, currentEditorText); //fieldLanguageBoxs[cellFieldIndex] = null; if (arbilFields[cellFieldIndex].getLanguageId() != null) { tabTitlePanel.add(createLanguageBox(cellFieldIndex)); } if (arbilFields[cellFieldIndex].getKeyName() != null) { tabTitlePanel.add(createKeyEditor(cellFieldIndex)); } tabPanel.add(tabTitlePanel, BorderLayout.PAGE_START); tabPanel.add(new JScrollPane(fieldEditors[cellFieldIndex]), BorderLayout.CENTER); return tabPanel; } private JTextArea createFieldDescription() { JTextArea fieldDescription = null; fieldDescription = new JTextArea(); fieldDescription.setLineWrap(true); fieldDescription.setEditable(false); fieldDescription.setOpaque(false); fieldDescription.setText(parentArbilDataNode.getNodeTemplate().getHelpStringForField(arbilFields[0].getFullXmlPath())); fieldDescription.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0)); return fieldDescription; } private void initFieldEditor(final int cellFieldIndex, String currentEditorText) { fieldEditors[cellFieldIndex].setEditable(parentArbilDataNode.getParentDomNode().isEditable()); fieldEditors[cellFieldIndex].addFocusListener(editorFocusListener); // insert the last key for only the selected field if (currentEditorText != null && (selectedField == cellFieldIndex || (selectedField == -1 && cellFieldIndex == 0))) { fieldEditors[cellFieldIndex].setText(currentEditorText); } else { fieldEditors[cellFieldIndex].setText(arbilFields[cellFieldIndex].getFieldValue()); } fieldEditors[cellFieldIndex].setLineWrap(true); fieldEditors[cellFieldIndex].setWrapStyleWord(true); fieldEditors[cellFieldIndex].setInputMap(JComponent.WHEN_FOCUSED, new lfeInputMap(fieldEditors[cellFieldIndex].getInputMap())); fieldEditors[cellFieldIndex].setActionMap(new lfeActionMap(fieldEditors[cellFieldIndex].getActionMap())); } private String getWindowTitle() { return fieldName + " in " + String.valueOf(parentArbilDataNode); } private JPanel createPreviousNextPanel() { prevButton = new JButton(previousAction); prevButton.setText("Previous"); prevButton.setMnemonic('p'); nextButton = new JButton(nextAction); nextButton.setText("Next"); nextButton.setMnemonic('n'); JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING)); buttonsPanel.add(prevButton); buttonsPanel.add(nextButton); return buttonsPanel; } private void setParentFieldList() { parentFieldList = parentArbilDataNode.getFieldsSorted(); } private void setNavigationEnabled() { int index = parentFieldList.indexOf(arbilFields); nextButton.setEnabled(index < parentFieldList.size() - 1); prevButton.setEnabled(index > 0); } private void requestFocusFor(final JComponent component) { EventQueue.invokeLater(new Runnable() { public void run() { component.requestFocusInWindow(); } }); } public void updateEditor() { arbilFields = parentArbilDataNode.getFields().get(fieldName); selectedField = Math.max(0, Math.min(tabPane.getTabCount(), tabPane.getSelectedIndex())); tabPane.removeAll(); if (arbilFields != null && arbilFields.length > 0) { editorFrame.setTitle(getWindowTitle()); JComponent focusedTabTextArea = populateTabbedPane(null); // fieldDescription.setText(parentArbilDataNode.getNodeTemplate().getHelpStringForField(arbilFields[0].getFullXmlPath())); requestFocusFor(focusedTabTextArea); if (selectedField < tabPane.getTabCount()) { tabPane.setSelectedIndex(selectedField); } } // todo: this could be done more softly by using the below code when the fields have not been reloaded, but be carefull that the ImdiFields in the language boxes are not out of sync. // // todo: the number of fields might have changed so we really should update the tabs or re create the form // // this will only be called when the long field editor is shown // // when an imdi node is edited or saved or reloaded this will be called to update the displayed values // fieldDescription.setText(parentImdiTreeObject.getNodeTemplate().getHelpStringForField(imdiFields[0].getFullXmlPath())); // for (int cellFieldCounter = 0; cellFieldCounter < imdiFields.length; cellFieldCounter++) { // fieldEditors[cellFieldCounter].setText(imdiFields[cellFieldCounter].getFieldValue()); // if (fieldLanguageBoxs[cellFieldCounter] != null) { // // set the language id selection in the dropdown // boolean selectedValueFound = false; // for (int itemCounter = 0; itemCounter < fieldLanguageBoxs[cellFieldCounter].getItemCount(); itemCounter++) { // Object currentObject = fieldLanguageBoxs[cellFieldCounter].getItemAt(itemCounter); // if (currentObject instanceof ImdiVocabularies.VocabularyItem) { // ImdiVocabularies.VocabularyItem currentItem = (ImdiVocabularies.VocabularyItem) currentObject; //// System.out.println(((ImdiField[]) cellValue)[cellFieldCounter].getLanguageId()); //// System.out.println(currentItem.languageCode); // if (currentItem.languageCode.equals(imdiFields[cellFieldCounter].getLanguageId())) { //// System.out.println("setting as current"); //// System.out.println(currentItem.languageCode); //// System.out.println(imdiFields[cellFieldCounter].getLanguageId()); // fieldLanguageBoxs[cellFieldCounter].setSelectedIndex(itemCounter); // selectedValueFound = true; // if (selectedValueFound == false) { // fieldLanguageBoxs[cellFieldCounter].addItem(LanguageIdBox.defaultLanguageDropDownValue); // fieldLanguageBoxs[cellFieldCounter].setSelectedItem(LanguageIdBox.defaultLanguageDropDownValue); //// System.out.println("field language: " + ((ImdiField[]) cellValue)[cellFieldCounter].getLanguageId()); // if (keyEditorFields[cellFieldCounter] != null) { // keyEditorFields[cellFieldCounter].setText(imdiFields[cellFieldCounter].getKeyName()); } public void closeWindow() { editorFrame.doDefaultCloseAction(); } public synchronized void storeChanges() { if (arbilFields != null) { for (int cellFieldCounter = 0; cellFieldCounter < arbilFields.length; cellFieldCounter++) { ArbilField cellField = (ArbilField) arbilFields[cellFieldCounter]; if (cellField.parentDataNode.getParentDomNode().isEditable()) { cellField.setFieldValue(fieldEditors[cellFieldCounter].getText(), true, false); if (keyEditorFields[cellFieldCounter] != null) { // Remember index of current field int index = parentFieldList.indexOf(arbilFields); // Let field apply new name if necessary if (cellField.setKeyName(keyEditorFields[cellFieldCounter].getText(), true, false)) { // Field name has changed, reload as required setParentFieldList(); moveTo(index); } } } } } } /** * Data node is to be removed * @param dataNode Data node that should be removed */ public void dataNodeRemoved(ArbilDataNode dataNode) { closeWindow(); } /** * Data node is clearing its icon * @param dataNode Data node that is clearing its icon */ public void dataNodeIconCleared(ArbilDataNode dataNode) { updateEditor(); setParentFieldList(); setNavigationEnabled(); } private synchronized void changeTab(int d) { final int index; if (d > 0) { index = Math.min(tabPane.getSelectedIndex() + 1, tabPane.getTabCount() - 1); } else { index = Math.max(tabPane.getSelectedIndex() - 1, 0); } tabPane.setSelectedIndex(index); requestFocusFor(fieldEditors[index]); } private synchronized void moveAdjacent(int d) { int index = parentFieldList.indexOf(arbilFields); index += d; if (index < parentFieldList.size() && index >= 0) { storeChanges(); moveTo(index); } } private synchronized void moveTo(int index) { fieldName = parentFieldList.get(index)[0].getTranslateFieldName(); updateEditor(); setNavigationEnabled(); } private Action nextAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { moveAdjacent(+1); } }; private Action previousAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { moveAdjacent(-1); } }; private class lfeActionMap extends ActionMap { public lfeActionMap(ActionMap parent) { super(); if (parent != null) { setParent(parent); } put("nextField", nextAction); put("previousField", previousAction); // Action that switches to the next tab (if there is one) put("nextTab", new AbstractAction() { public void actionPerformed(ActionEvent e) { changeTab(+1); } }); // Action that switches to the previous tab (if there is one) put("previousTab", new AbstractAction() { public void actionPerformed(ActionEvent e) { changeTab(-1); } }); } } private class lfeInputMap extends InputMap { public lfeInputMap(InputMap parent) { super(); if (parent != null) { setParent(parent); } // Next field keys put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, KeyEvent.META_DOWN_MASK), "nextField"); put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, KeyEvent.META_DOWN_MASK), "nextField"); put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, KeyEvent.CTRL_DOWN_MASK), "nextField"); put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, KeyEvent.CTRL_DOWN_MASK), "nextField"); // Previous field keys put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, KeyEvent.META_DOWN_MASK), "previousField"); put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, KeyEvent.META_DOWN_MASK), "previousField"); put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, KeyEvent.CTRL_DOWN_MASK), "previousField"); put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, KeyEvent.CTRL_DOWN_MASK), "previousField"); // Next tab keys put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, KeyEvent.META_DOWN_MASK), "nextTab"); put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, KeyEvent.CTRL_DOWN_MASK), "nextTab"); // Previous tab keys put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, KeyEvent.META_DOWN_MASK), "previousTab"); put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, KeyEvent.CTRL_DOWN_MASK), "previousTab"); } } private FocusListener editorFocusListener = new FocusListener() { public void focusGained(FocusEvent e) { } public void focusLost(FocusEvent e) { storeChanges(); } }; }
package org.knowm.xchange.ftx.service; import org.apache.commons.lang3.StringUtils; import org.knowm.xchange.ftx.FtxExchange; import org.knowm.xchange.ftx.dto.account.FtxBorrowingInfoDto; import org.knowm.xchange.ftx.dto.account.FtxBorrowingRatesDto; import org.knowm.xchange.ftx.dto.account.FtxBorrowingHistoryDto; import java.io.IOException; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; public class FtxBorrowingServiceRaw extends FtxBaseService { public FtxBorrowingServiceRaw(FtxExchange exchange) { super(exchange); } public List<FtxBorrowingHistoryDto> histories(String subaccount) { try { return ftx.getBorrowHistory( exchange.getExchangeSpecification().getApiKey(), exchange.getNonceFactory().createValue(), signatureCreator, subaccount ).getResult(); } catch (IOException e) { throw new FtxLendingServiceRaw.FtxLendingServiceException("Can't get lending infos subAccount: " + subaccount, e); } } public List<FtxBorrowingHistoryDto> histories(String subaccount, List<String> coins) { Objects.requireNonNull(coins); return histories(subaccount).stream() .filter(lendingHistory -> coins.contains(lendingHistory.getCoin())) .collect(Collectors.toList()); } public FtxBorrowingHistoryDto history(String subaccount, String coin) { Objects.requireNonNull(coin); if (StringUtils.isNotBlank(coin)) throw new FtxBorrowingServiceException("Coin are blank or empty"); return histories(subaccount).stream() .filter(lendingHistory -> lendingHistory.getCoin().equalsIgnoreCase(coin)) .findFirst() .orElse(null); } public List<FtxBorrowingInfoDto> infos(String subaccount) { try { return ftx.getBorrowingInfos( exchange.getExchangeSpecification().getApiKey(), exchange.getNonceFactory().createValue(), signatureCreator, subaccount ).getResult(); } catch (IOException e) { throw new FtxLendingServiceRaw.FtxLendingServiceException("Can't get lending infos", e); } } public List<FtxBorrowingInfoDto> infos(String subaccount, List<String> coins) { Objects.requireNonNull(coins); return infos(subaccount).stream() .filter(lendingInfo -> coins.contains(lendingInfo.getCoin())) .collect(Collectors.toList()); } public FtxBorrowingInfoDto info(String subaccount, String coin) { Objects.requireNonNull(coin); if (StringUtils.isNotBlank(coin)) throw new FtxBorrowingServiceException("Coin are blank or empty"); return infos(subaccount).stream() .filter(lendingInfo -> lendingInfo.getCoin().equalsIgnoreCase(coin)) .findFirst() .orElse(null); } public List<FtxBorrowingRatesDto> rates() { try { return ftx.getBorrowRates( exchange.getExchangeSpecification().getApiKey(), exchange.getNonceFactory().createValue(), signatureCreator ).getResult(); } catch (IOException e) { throw new FtxLendingServiceRaw.FtxLendingServiceException("Can't get lending rates", e); } } public List<FtxBorrowingRatesDto> rates(List<String> coins) { Objects.requireNonNull(coins); return rates().stream() .filter(lendingRates -> coins.contains(lendingRates.getCoin())) .collect(Collectors.toList()); } public FtxBorrowingRatesDto rate(String coin) { Objects.requireNonNull(coin); if (StringUtils.isNotBlank(coin)) throw new FtxBorrowingServiceException("Coin are blank or empty"); try { return ftx.getBorrowRates( exchange.getExchangeSpecification().getApiKey(), exchange.getNonceFactory().createValue(), signatureCreator ).getResult().stream() .filter(lendingRates -> lendingRates.getCoin().equalsIgnoreCase(coin)) .findFirst() .orElse(null); } catch (IOException e) { throw new FtxLendingServiceRaw.FtxLendingServiceException("Can't get lending rate coin: " + coin, e); } } public static class FtxBorrowingServiceException extends RuntimeException { public FtxBorrowingServiceException(String message, Throwable cause) { super(message, cause); } public FtxBorrowingServiceException(String message) { super(message); } } }
package nl.sense_os.testing.client.widgets; import java.util.ArrayList; import java.util.List; import nl.sense_os.testing.client.widgets.grid.PaginationGridPanel; import com.extjs.gxt.ui.client.data.ModelData; import com.extjs.gxt.ui.client.data.ModelType; import com.extjs.gxt.ui.client.fx.Draggable; import com.extjs.gxt.ui.client.store.ListStore; import com.extjs.gxt.ui.client.widget.Component; import com.extjs.gxt.ui.client.widget.LayoutContainer; import com.extjs.gxt.ui.client.widget.grid.ColumnConfig; import com.extjs.gxt.ui.client.widget.grid.ColumnData; import com.extjs.gxt.ui.client.widget.grid.ColumnModel; import com.extjs.gxt.ui.client.widget.grid.Grid; import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer; import com.extjs.gxt.ui.client.widget.table.CellRenderer; public class SensorDataGrid extends LayoutContainer { public SensorDataGrid(){ // Data store structure. ModelType model = new ModelType(); model.setTotalName("total"); model.setRoot("data"); model.addField("d"); model.addField("s"); model.addField("t"); model.addField("v"); // Column model. List<ColumnConfig> colConf = new ArrayList<ColumnConfig>(); ColumnConfig timeCol = new ColumnConfig(); timeCol.setId("t"); timeCol.setHeader("time"); timeCol.setDataIndex("t"); timeCol.setWidth(200); colConf.add(timeCol); ColumnConfig deviceCol = new ColumnConfig(); deviceCol.setId("d"); deviceCol.setHeader("device_id"); deviceCol.setDataIndex("d"); deviceCol.setWidth(200); colConf.add(deviceCol); ColumnConfig sensorCol = new ColumnConfig(); sensorCol.setId("s"); sensorCol.setHeader("sensor_id"); sensorCol.setDataIndex("s"); sensorCol.setWidth(200); colConf.add(sensorCol); ColumnConfig valueCol = new ColumnConfig(); valueCol.setId("v"); valueCol.setHeader("value"); valueCol.setDataIndex("v"); valueCol.setWidth(200); valueCol.setRenderer(getValueCellFormat()); colConf.add(valueCol); ColumnModel cm = new ColumnModel(colConf); // Grid. PaginationGridPanel gridPanel = new PaginationGridPanel( "http://dev2.almende.com/commonsense/get_sensor_data_paged.php" + "?email=steven@sense-os.nl&password=81dc9bdb52d04dc20036dbd8313ed055&d_id=78&s_id=2", model, cm, 5); // Grid config. /* HashMap<Integer, Object> gridConf = new HashMap<Integer, Object>(); gridConf.put(grid.WIDTH, 402); gridConf.put(grid.AUTO_HEIGHT, true); grid.loadConf(gridConf); */ gridPanel.setWidth(802); gridPanel.setAutoHeight(true); gridPanel.setTitle("sensor data"); gridPanel.setCollapsible(true); gridPanel.setBodyBorder(true); gridPanel.load(); new Draggable(gridPanel); add(gridPanel); } /** * * @return the value field html format */ private GridCellRenderer getValueCellFormat() { return new GridCellRenderer() { @Override public Object render( ModelData model, String property, ColumnData config, int rowIndex, int colIndex, ListStore store, Grid grid) { // @@ TODO: The sensor type should be identified to display the value // in a proper format. // example: accelerometer final int ACCELOMETER = 1; int sensorType = ACCELOMETER; switch (sensorType) { case ACCELOMETER: String value = (String) model.get("v"); String [] values = ((String) value).split(","); return "x-axis: " + values[0] + "<br />y-axis: " + values[1] + "<br />z-axis: " + values[2]; default: // Returns the value without format. return model.get("v"); } } }; } }
package com.github.sbouclier; import com.github.sbouclier.result.*; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; public class KrakenAPIClient { public static String BASE_URL = "https://api.kraken.com/0"; public enum Interval { ONE_MINUTE(1), FIVE_MINUTES(5), FIFTEEN_MINUTES(15), THIRTY_MINUTES(30), ONE_HOUR(60), FOUR_HOURS(240), ONE_DAY(1440), ONE_WEEK(10080), FIFTEEN_DAYS(21600); private int minutes; Interval(int minutes) { this.minutes = minutes; } @Override public String toString() { return "Interval{" + "minutes=" + minutes + '}'; } } /** * Get server time * * @return server time * @throws KrakenApiException */ public ServerTimeResult getServerTime() throws KrakenApiException { return new HttpApiClient<ServerTimeResult>() .callHttpClient(BASE_URL + "/public/Time", ServerTimeResult.class); } /** * Get asset information * * @return asset information * @throws KrakenApiException */ public AssetInformationResult getAssetInformation() throws KrakenApiException { return new HttpApiClient<AssetInformationResult>() .callHttpClient(BASE_URL + "/public/Assets", AssetInformationResult.class); } /** * Get tradable asset pairs * * @return asset pairs * @throws KrakenApiException */ public AssetPairsResult getAssetPairs() throws KrakenApiException { return new HttpApiClient<AssetPairsResult>() .callHttpClient(BASE_URL + "/public/AssetPairs", AssetPairsResult.class); } /** * Get ticker information of pairs * * @param pairs list of pair * @return ticker information * @throws KrakenApiException */ public TickerInformationResult getTickerInformation(List<String> pairs) throws KrakenApiException { Map<String, String> params = new HashMap<>(); params.put("pair", String.join(",", pairs)); return new HttpApiClient<TickerInformationResult>() .callHttpClient(BASE_URL + "/public/Ticker", TickerInformationResult.class, params); } /** * Get OHLC data * * @param pair currency pair * @param interval interval of time * @param since data since givene id * @return data (OHLC + last id) * @throws KrakenApiException */ public OHLCResult getOHLC(String pair, Interval interval, Integer since) throws KrakenApiException { Map<String, String> params = new HashMap<>(); params.put("pair", pair); params.put("interval", String.valueOf(interval.minutes)); params.put("since", String.valueOf(since)); return new HttpApiClient<OHLCResult>() .callHttpClient(BASE_URL + "/public/OHLC", OHLCResult.class, params); } /** * Get OHLC data * * @param pair currency pair * @param interval interval of time * @return data (OHLC + last id) * @throws KrakenApiException */ public OHLCResult getOHLC(String pair, Interval interval) throws KrakenApiException { Map<String, String> params = new HashMap<>(); params.put("pair", pair); params.put("interval", String.valueOf(interval.minutes)); return new HttpApiClient<OHLCResult>() .callHttpClient(BASE_URL + "/public/OHLC", OHLCResult.class, params); } public static void main(String[] args) { KrakenAPIClient client = new KrakenAPIClient(); //ServerTimeResult result = client.getServerTime(); //AssetInformationResult result = client.getAssetInformation(); //AssetPairsResult result = client.getAssetPairs(); //TickerInformationResult result = client.getTickerInformation(Arrays.asList("BTCEUR", "ETHEUR")); OHLCResult result = null; try { result = client.getOHLC("BTCEXXUR", Interval.ONE_MINUTE, Optional.empty()); // System.out.println(result.getResult().get("XXBTZEUR")); System.out.println(result.getOHLCData()); System.out.println(result.getLast()); //System.out.println(result.getResult().get("XETHZEUR").ask + " > " + result.getResult().get("XETHZEUR").ask.getClass()); } catch (KrakenApiException e) { e.printStackTrace(); System.out.println(e.getMessage()); } } }
package com.catpeds.model; import static org.junit.Assert.assertEquals; import java.time.LocalDate; import org.junit.Test; import com.catpeds.model.Pedigree.Gender; /** * Unit test class for {@link Pedigree} * * @author padriano * */ public class PedigreeTest { /** * Initialise */ @Test public void testToString() { // Given Pedigree pedigree = new Pedigree(); pedigree.setId(123); pedigree.setDamId(11); pedigree.setSireId(22); pedigree.setDob(LocalDate.of(2017, 1, 31)); pedigree.setEms("NFO w"); pedigree.setGender(Gender.M); pedigree.setInbreeding(12.3); pedigree.setLocationCountryCode("GB"); pedigree.setNationalityCountryCode("SE"); pedigree.setName("Padawan Amidala"); pedigree.setTitle("CH"); // When String result = pedigree.toString(); // Then String expectedResult = "Pedigree{id=123, name=Padawan Amidala, ems=NFO w, gender=M, dob=2017-01-31, " + "nationalityCountryCode=SE, locationCountryCode=GB, title=CH, inbreeding=12.3, sire=22, dam=11}"; assertEquals(expectedResult, result); } }
package com.github.andriell.db; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.Session; import org.hibernate.SessionFactory; import java.util.List; import java.util.Set; public class ProductDaoImpl implements ProductDao { private static final Log LOG = LogFactory.getLog(ProductDaoImpl.class); private static final String PRICE = "price"; private SessionFactory sessionFactory; public Product findByCode(String code, Session session) { List<Product> users = session.createQuery("from Product where code=:code") .setParameter("code", code) .list(); if (users.size() > 0) { return users.get(0); } else { return null; } } public int clearProperty(int productId, Session session) { return session.createQuery("delete from ProductProperty where name<>:name AND product_id = :product_id") .setParameter("name", PRICE) .setParameter("product_id", productId) .executeUpdate(); } public List<ProductProperty> getProperty(int productId, String propertyName) { return getSessionFactory() .getCurrentSession() .createQuery("from ProductProperty where product_id=:product_id AND name=:name") .setParameter("product_id", productId) .setParameter("name", propertyName) .list(); } public boolean save(Product product) { Session session = sessionFactory.openSession(); session.beginTransaction(); Product p = findByCode(product.getCode(), session); if (p != null) { product.setId(p.getId()); } session.save(product); clearProperty(product.getId(), session); Set<ProductProperty> properties = product.getProperty(); for (ProductProperty property: properties) { session.save(property); } session.getTransaction().commit(); return true; } public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } }
package com.intellij.util; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.ThrowableComputable; import com.intellij.openapi.util.registry.Registry; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.HashSet; import java.util.Set; public final class SlowOperations { private static final Logger LOG = Logger.getInstance(SlowOperations.class); private static final Set<String> ourReportedTraces = new HashSet<>(); private static final String[] misbehavingFrames = { "org.jetbrains.kotlin.idea.refactoring.introduce.introduceVariable.KotlinIntroduceVariableHandler", "org.jetbrains.kotlin.idea.actions.KotlinAddImportAction", "org.jetbrains.kotlin.idea.codeInsight.KotlinCopyPasteReferenceProcessor", "com.intellij.apiwatcher.plugin.presentation.bytecode.UsageHighlighter", }; private static boolean ourAllowedFlag = false; private SlowOperations() {} /** * If you get an exception from this method, then you need to move the computation to the background * while also trying to avoid blocking the UI thread as well. It's okay if the API changes in the process, * e.g. instead of wrapping implementation of some extension into {@link #allowSlowOperations}, * it's better to admit that the EP semantic as a whole requires index access, * and then move the iteration over all extensions to the background on the platform-side. * <p/> * In cases when it's impossible to do so, the computation should be wrapped into {@code allowSlowOperations} explicitly. * This way it's possible to find all such operations by searching usages of {@code allowSlowOperations}. * * @see com.intellij.openapi.application.NonBlockingReadAction * @see com.intellij.openapi.application.CoroutinesKt#readAction * @see com.intellij.openapi.actionSystem.ex.ActionUtil#underModalProgress */ public static void assertSlowOperationsAreAllowed() { if (Registry.is("ide.enable.slow.operations.in.edt")) { return; } Application application = ApplicationManager.getApplication(); if (application.isUnitTestMode() || !application.isDispatchThread() || application.isWriteAccessAllowed() || ourAllowedFlag) { return; } String stackTrace = ExceptionUtil.currentStackTrace(); if (ContainerUtil.or(misbehavingFrames, stackTrace::contains) || !ourReportedTraces.add(stackTrace)) { return; } LOG.error("Slow operations are prohibited in the EDT"); } public static <T, E extends Throwable> T allowSlowOperations(@NotNull ThrowableComputable<T, E> computable) throws E { if (!ApplicationManager.getApplication().isDispatchThread() || ourAllowedFlag) { return computable.compute(); } ourAllowedFlag = true; try { return computable.compute(); } finally { ourAllowedFlag = false; } } public static <E extends Throwable> void allowSlowOperations(@NotNull ThrowableRunnable<E> runnable) throws E { allowSlowOperations(() -> { runnable.run(); return null; }); } }
package com.github.onsdigital.errors; import java.io.IOException; import java.io.Reader; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import com.github.davidcarboni.ResourceUtils; import com.github.davidcarboni.restolino.api.RequestHandler; import com.github.davidcarboni.restolino.framework.Boom; public class Error500 implements Boom { @Override public Object handle(HttpServletRequest req, HttpServletResponse res, RequestHandler requestHandler, Throwable t) throws IOException { if (requestHandler != null) { System.out.println("Error in " + requestHandler.endpointClass.getName() + " (" + requestHandler.method.getName() + ")"); } System.out.println(ExceptionUtils.getStackTrace(t)); try (Reader input = ResourceUtils.getReader("/files/500.html")) { res.setCharacterEncoding("UTF8"); IOUtils.copy(input, res.getWriter()); } return null; } }
package com.gocardless.services; import com.gocardless.http.*; import com.gocardless.resources.Block; import com.google.common.collect.ImmutableMap; import com.google.gson.reflect.TypeToken; import java.util.List; import java.util.Map; /** * Service class for working with block resources. * * A block object is a simple rule, when matched, pushes a newly created mandate to a blocked state. * These details can be an exact match, like a bank account or an email, or a more generic match * such as an email domain. New block types may be added over time. Payments and subscriptions can't * be created against mandates in blocked state. * * <p class="notice"> * Client libraries have not yet been updated for this API but will be released soon. This API is * currently only available for approved integrators - please * <a href="mailto:help@gocardless.com">get in touch</a> if you would like to use this API. * </p> */ public class BlockService { private final HttpClient httpClient; /** * Constructor. Users of this library should have no need to call this - an instance of this * class can be obtained by calling {@link com.gocardless.GoCardlessClient#blocks() }. */ public BlockService(HttpClient httpClient) { this.httpClient = httpClient; } /** * Creates a new Block of a given type. By default it will be active. */ public BlockCreateRequest create() { return new BlockCreateRequest(httpClient); } /** * Retrieves the details of an existing block. */ public BlockGetRequest get(String identity) { return new BlockGetRequest(httpClient, identity); } /** * Returns a [cursor-paginated](#api-usage-cursor-pagination) list of your blocks. */ public BlockListRequest<ListResponse<Block>> list() { return new BlockListRequest<>(httpClient, ListRequest.<Block>pagingExecutor()); } public BlockListRequest<Iterable<Block>> all() { return new BlockListRequest<>(httpClient, ListRequest.<Block>iteratingExecutor()); } /** * Disables a block so that it no longer will prevent mandate creation. */ public BlockDisableRequest disable(String identity) { return new BlockDisableRequest(httpClient, identity); } /** * Enables a previously disabled block so that it will prevent mandate creation */ public BlockEnableRequest enable(String identity) { return new BlockEnableRequest(httpClient, identity); } /** * Request class for {@link BlockService#create }. * * Creates a new Block of a given type. By default it will be active. */ public static final class BlockCreateRequest extends IdempotentPostRequest<Block> { private Boolean active; private String blockType; private String reasonDescription; private String reasonType; private String resourceReference; /** * Shows if the block is active or disabled. Only active blocks will be used when deciding * if a mandate should be blocked. */ public BlockCreateRequest withActive(Boolean active) { this.active = active; return this; } /** * Type of entity we will seek to match against when blocking the mandate. This can * currently be one of 'email', 'email_domain', or 'bank_account'. */ public BlockCreateRequest withBlockType(String blockType) { this.blockType = blockType; return this; } /** * This field is required if the reason_type is other. It should be a description of the * reason for why you wish to block this payer and why it does not align with the given * reason_types. This is intended to help us improve our knowledge of types of fraud. */ public BlockCreateRequest withReasonDescription(String reasonDescription) { this.reasonDescription = reasonDescription; return this; } /** * The reason you wish to block this payer, can currently be one of 'identity_fraud', * 'no_intent_to_pay', 'unfair_chargeback'. If the reason isn't captured by one of the above * then 'other' can be selected but you must provide a reason description. */ public BlockCreateRequest withReasonType(String reasonType) { this.reasonType = reasonType; return this; } /** * This field is a reference to the value you wish to block. This may be the raw value (in * the case of emails or email domains) or the ID of the resource (in the case of bank * accounts). This means in order to block a specific bank account it must already have been * created as a resource. */ public BlockCreateRequest withResourceReference(String resourceReference) { this.resourceReference = resourceReference; return this; } public BlockCreateRequest withIdempotencyKey(String idempotencyKey) { super.setIdempotencyKey(idempotencyKey); return this; } @Override protected GetRequest<Block> handleConflict(HttpClient httpClient, String id) { BlockGetRequest request = new BlockGetRequest(httpClient, id); for (Map.Entry<String, String> header : this.getCustomHeaders().entrySet()) { request = request.withHeader(header.getKey(), header.getValue()); } return request; } private BlockCreateRequest(HttpClient httpClient) { super(httpClient); } public BlockCreateRequest withHeader(String headerName, String headerValue) { this.addHeader(headerName, headerValue); return this; } @Override protected String getPathTemplate() { return "blocks"; } @Override protected String getEnvelope() { return "blocks"; } @Override protected Class<Block> getResponseClass() { return Block.class; } @Override protected boolean hasBody() { return true; } } /** * Request class for {@link BlockService#get }. * * Retrieves the details of an existing block. */ public static final class BlockGetRequest extends GetRequest<Block> { @PathParam private final String identity; private BlockGetRequest(HttpClient httpClient, String identity) { super(httpClient); this.identity = identity; } public BlockGetRequest withHeader(String headerName, String headerValue) { this.addHeader(headerName, headerValue); return this; } @Override protected Map<String, String> getPathParams() { ImmutableMap.Builder<String, String> params = ImmutableMap.builder(); params.put("identity", identity); return params.build(); } @Override protected String getPathTemplate() { return "blocks/:identity"; } @Override protected String getEnvelope() { return "blocks"; } @Override protected Class<Block> getResponseClass() { return Block.class; } } /** * Request class for {@link BlockService#list }. * * Returns a [cursor-paginated](#api-usage-cursor-pagination) list of your blocks. */ public static final class BlockListRequest<S> extends ListRequest<S, Block> { private String block; private String blockType; private String createdAt; private String reasonType; private String updatedAt; /** * Cursor pointing to the start of the desired set. */ public BlockListRequest<S> withAfter(String after) { setAfter(after); return this; } /** * Cursor pointing to the end of the desired set. */ public BlockListRequest<S> withBefore(String before) { setBefore(before); return this; } /** * ID of a [Block](#core-endpoints-blocks). */ public BlockListRequest<S> withBlock(String block) { this.block = block; return this; } /** * Type of entity we will seek to match against when blocking the mandate. This can * currently be one of 'email', 'email_domain', or 'bank_account'. */ public BlockListRequest<S> withBlockType(String blockType) { this.blockType = blockType; return this; } /** * Fixed [timestamp](#api-usage-time-zones--dates), recording when this resource was * created. */ public BlockListRequest<S> withCreatedAt(String createdAt) { this.createdAt = createdAt; return this; } /** * Number of records to return. */ public BlockListRequest<S> withLimit(Integer limit) { setLimit(limit); return this; } /** * The reason you wish to block this payer, can currently be one of 'identity_fraud', * 'no_intent_to_pay', 'unfair_chargeback'. If the reason isn't captured by one of the above * then 'other' can be selected but you must provide a reason description. */ public BlockListRequest<S> withReasonType(String reasonType) { this.reasonType = reasonType; return this; } /** * Fixed [timestamp](#api-usage-time-zones--dates), recording when this resource was * updated. */ public BlockListRequest<S> withUpdatedAt(String updatedAt) { this.updatedAt = updatedAt; return this; } private BlockListRequest(HttpClient httpClient, ListRequestExecutor<S, Block> executor) { super(httpClient, executor); } public BlockListRequest<S> withHeader(String headerName, String headerValue) { this.addHeader(headerName, headerValue); return this; } @Override protected Map<String, Object> getQueryParams() { ImmutableMap.Builder<String, Object> params = ImmutableMap.builder(); params.putAll(super.getQueryParams()); if (block != null) { params.put("block", block); } if (blockType != null) { params.put("block_type", blockType); } if (createdAt != null) { params.put("created_at", createdAt); } if (reasonType != null) { params.put("reason_type", reasonType); } if (updatedAt != null) { params.put("updated_at", updatedAt); } return params.build(); } @Override protected String getPathTemplate() { return "blocks"; } @Override protected String getEnvelope() { return "blocks"; } @Override protected TypeToken<List<Block>> getTypeToken() { return new TypeToken<List<Block>>() {}; } } /** * Request class for {@link BlockService#disable }. * * Disables a block so that it no longer will prevent mandate creation. */ public static final class BlockDisableRequest extends PostRequest<Block> { @PathParam private final String identity; private BlockDisableRequest(HttpClient httpClient, String identity) { super(httpClient); this.identity = identity; } public BlockDisableRequest withHeader(String headerName, String headerValue) { this.addHeader(headerName, headerValue); return this; } @Override protected Map<String, String> getPathParams() { ImmutableMap.Builder<String, String> params = ImmutableMap.builder(); params.put("identity", identity); return params.build(); } @Override protected String getPathTemplate() { return "blocks/:identity/actions/disable"; } @Override protected String getEnvelope() { return "blocks"; } @Override protected Class<Block> getResponseClass() { return Block.class; } @Override protected boolean hasBody() { return false; } } /** * Request class for {@link BlockService#enable }. * * Enables a previously disabled block so that it will prevent mandate creation */ public static final class BlockEnableRequest extends PostRequest<Block> { @PathParam private final String identity; private BlockEnableRequest(HttpClient httpClient, String identity) { super(httpClient); this.identity = identity; } public BlockEnableRequest withHeader(String headerName, String headerValue) { this.addHeader(headerName, headerValue); return this; } @Override protected Map<String, String> getPathParams() { ImmutableMap.Builder<String, String> params = ImmutableMap.builder(); params.put("identity", identity); return params.build(); } @Override protected String getPathTemplate() { return "blocks/:identity/actions/enable"; } @Override protected String getEnvelope() { return "blocks"; } @Override protected Class<Block> getResponseClass() { return Block.class; } @Override protected boolean hasBody() { return false; } } }
package cn.jingzhuan.lib.chart.data; import java.util.List; import cn.jingzhuan.lib.chart.Viewport; import cn.jingzhuan.lib.chart.component.AxisY; public class MinuteLine extends LineDataSet { private float mLastClose = -1; public MinuteLine(List<PointValue> pointValues) { super(pointValues); } public MinuteLine(List<PointValue> pointValues, @AxisY.AxisDependency int axisDependency) { super(pointValues, axisDependency); } public float getLastClose() { return mLastClose; } public void setLastClose(float lastClose) { this.mLastClose = lastClose; } @Override public void calcMinMax(Viewport viewport) { super.calcMinMax(viewport); if (mLastClose > 0) { if (getValues() != null && getValues().size() > 0) { float maxDiff = Math.max(Math.abs(mViewportYMin - mLastClose), Math.abs(mViewportYMax - mLastClose)); maxDiff = Math.max(mLastClose * 0.01f, maxDiff); mViewportYMin = mLastClose - maxDiff; mViewportYMax = mLastClose + maxDiff; } else { mViewportYMin = mLastClose * 0.09f; mViewportYMax = mLastClose * 1.01f; } } } }
package com.intellij.diff.util; import com.intellij.codeInsight.daemon.OutsidersPsiFileSupport; import com.intellij.codeStyle.CodeStyleFacade; import com.intellij.diff.*; import com.intellij.diff.comparison.ByWord; import com.intellij.diff.comparison.ComparisonMergeUtil; import com.intellij.diff.comparison.ComparisonPolicy; import com.intellij.diff.comparison.ComparisonUtil; import com.intellij.diff.contents.DiffContent; import com.intellij.diff.contents.DocumentContent; import com.intellij.diff.contents.EmptyContent; import com.intellij.diff.fragments.DiffFragment; import com.intellij.diff.fragments.LineFragment; import com.intellij.diff.fragments.MergeLineFragment; import com.intellij.diff.fragments.MergeWordFragment; import com.intellij.diff.impl.DiffSettingsHolder.DiffSettings; import com.intellij.diff.impl.DiffToolSubstitutor; import com.intellij.diff.requests.ContentDiffRequest; import com.intellij.diff.requests.DiffRequest; import com.intellij.diff.tools.util.DiffNotifications; import com.intellij.diff.tools.util.FoldingModelSupport; import com.intellij.diff.tools.util.base.TextDiffSettingsHolder.TextDiffSettings; import com.intellij.diff.tools.util.base.TextDiffViewerUtil; import com.intellij.diff.tools.util.text.*; import com.intellij.icons.AllIcons; import com.intellij.lang.Language; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.impl.LaterInvocator; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.command.UndoConfirmationPolicy; import com.intellij.openapi.command.undo.DocumentReference; import com.intellij.openapi.command.undo.DocumentReferenceManager; import com.intellij.openapi.command.undo.UndoManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.diff.impl.GenericDataProvider; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.colors.EditorColors; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.editor.ex.EditorMarkupModel; import com.intellij.openapi.editor.ex.util.EditorUtil; import com.intellij.openapi.editor.ex.util.EmptyEditorHighlighter; import com.intellij.openapi.editor.highlighter.EditorHighlighter; import com.intellij.openapi.editor.highlighter.EditorHighlighterFactory; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.PlainTextFileType; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.ui.DialogWrapperDialog; import com.intellij.openapi.ui.MessageType; import com.intellij.openapi.ui.WindowWrapper; import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.util.*; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.ReadonlyStatusHandler; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.newvfs.RefreshQueue; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.openapi.wm.IdeFrame; import com.intellij.openapi.wm.WindowManager; import com.intellij.openapi.wm.ex.IdeFrameEx; import com.intellij.openapi.wm.impl.IdeFrameImpl; import com.intellij.testFramework.LightVirtualFile; import com.intellij.ui.ColorUtil; import com.intellij.ui.HyperlinkAdapter; import com.intellij.ui.JBColor; import com.intellij.ui.ScreenUtil; import com.intellij.ui.awt.RelativePoint; import com.intellij.ui.components.JBLabel; import com.intellij.util.ArrayUtil; import com.intellij.util.DocumentUtil; import com.intellij.util.ImageLoader; import com.intellij.util.LineSeparator; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.Convertor; import com.intellij.util.ui.JBInsets; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import gnu.trove.Equality; import gnu.trove.TIntFunction; import org.jetbrains.annotations.*; import javax.swing.*; import javax.swing.border.Border; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import java.awt.*; import java.nio.charset.Charset; import java.util.List; import java.util.*; public class DiffUtil { private static final Logger LOG = Logger.getInstance(DiffUtil.class); public static final Key<Boolean> TEMP_FILE_KEY = Key.create("Diff.TempFile"); @NotNull public static final String DIFF_CONFIG = "diff.xml"; public static final int TITLE_GAP = JBUI.scale(2); public static final List<Image> DIFF_FRAME_ICONS = loadDiffFrameImages(); @NotNull private static List<Image> loadDiffFrameImages() { return ContainerUtil.list( ImageLoader.loadFromResource("/diff_frame32.png"), ImageLoader.loadFromResource("/diff_frame64.png"), ImageLoader.loadFromResource("/diff_frame128.png") ); } // Editor public static boolean isDiffEditor(@NotNull Editor editor) { return editor.getEditorKind() == EditorKind.DIFF; } @Nullable public static EditorHighlighter initEditorHighlighter(@Nullable Project project, @NotNull DocumentContent content, @NotNull CharSequence text) { EditorHighlighter highlighter = createEditorHighlighter(project, content); if (highlighter == null) return null; highlighter.setText(text); return highlighter; } @NotNull public static EditorHighlighter initEmptyEditorHighlighter(@NotNull CharSequence text) { EditorHighlighter highlighter = createEmptyEditorHighlighter(); highlighter.setText(text); return highlighter; } @Nullable private static EditorHighlighter createEditorHighlighter(@Nullable Project project, @NotNull DocumentContent content) { FileType type = content.getContentType(); VirtualFile file = content.getHighlightFile(); Language language = content.getUserData(DiffUserDataKeys.LANGUAGE); EditorHighlighterFactory highlighterFactory = EditorHighlighterFactory.getInstance(); if (language != null) { SyntaxHighlighter syntaxHighlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(language, project, file); return highlighterFactory.createEditorHighlighter(syntaxHighlighter, EditorColorsManager.getInstance().getGlobalScheme()); } if (file != null && file.isValid()) { if ((type == null || type == PlainTextFileType.INSTANCE) || file.getFileType() == type || file instanceof LightVirtualFile) { return highlighterFactory.createEditorHighlighter(project, file); } } if (type != null) { return highlighterFactory.createEditorHighlighter(project, type); } return null; } @NotNull private static EditorHighlighter createEmptyEditorHighlighter() { return new EmptyEditorHighlighter(EditorColorsManager.getInstance().getGlobalScheme().getAttributes(HighlighterColors.TEXT)); } public static void setEditorHighlighter(@Nullable Project project, @NotNull EditorEx editor, @NotNull DocumentContent content) { EditorHighlighter highlighter = createEditorHighlighter(project, content); if (highlighter != null) editor.setHighlighter(highlighter); } public static void setEditorCodeStyle(@Nullable Project project, @NotNull EditorEx editor, @Nullable FileType fileType) { if (project != null && fileType != null && editor.getVirtualFile() == null) { CodeStyleFacade codeStyleFacade = CodeStyleFacade.getInstance(project); editor.getSettings().setTabSize(codeStyleFacade.getTabSize(fileType)); editor.getSettings().setUseTabCharacter(codeStyleFacade.useTabCharacter(fileType)); } editor.getSettings().setCaretRowShown(false); editor.reinitSettings(); } public static void setFoldingModelSupport(@NotNull EditorEx editor) { editor.getSettings().setFoldingOutlineShown(true); editor.getSettings().setAutoCodeFoldingEnabled(false); editor.getColorsScheme().setAttributes(EditorColors.FOLDED_TEXT_ATTRIBUTES, null); } @NotNull public static EditorEx createEditor(@NotNull Document document, @Nullable Project project, boolean isViewer) { return createEditor(document, project, isViewer, false); } @NotNull public static EditorEx createEditor(@NotNull Document document, @Nullable Project project, boolean isViewer, boolean enableFolding) { EditorFactory factory = EditorFactory.getInstance(); EditorKind kind = EditorKind.DIFF; EditorEx editor = (EditorEx)(isViewer ? factory.createViewer(document, project, kind) : factory.createEditor(document, project, kind)); editor.getSettings().setShowIntentionBulb(false); ((EditorMarkupModel)editor.getMarkupModel()).setErrorStripeVisible(true); editor.getGutterComponentEx().setShowDefaultGutterPopup(false); if (enableFolding) { setFoldingModelSupport(editor); } else { editor.getSettings().setFoldingOutlineShown(false); editor.getFoldingModel().setFoldingEnabled(false); } UIUtil.removeScrollBorder(editor.getComponent()); return editor; } public static void configureEditor(@NotNull EditorEx editor, @NotNull DocumentContent content, @Nullable Project project) { VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(content.getDocument()); if (virtualFile != null && Registry.is("diff.enable.psi.highlighting")) { editor.setFile(virtualFile); } setEditorHighlighter(project, editor, content); setEditorCodeStyle(project, editor, content.getContentType()); } public static boolean isMirrored(@NotNull Editor editor) { if (editor instanceof EditorEx) { return ((EditorEx)editor).getVerticalScrollbarOrientation() == EditorEx.VERTICAL_SCROLLBAR_LEFT; } return false; } @Contract("null, _ -> false; _, null -> false") public static boolean canNavigateToFile(@Nullable Project project, @Nullable VirtualFile file) { if (project == null || project.isDefault()) return false; if (file == null || !file.isValid()) return false; if (OutsidersPsiFileSupport.isOutsiderFile(file)) return false; if (file.getUserData(TEMP_FILE_KEY) == Boolean.TRUE) return false; return true; } public static void installLineConvertor(@NotNull EditorEx editor, @NotNull FoldingModelSupport foldingSupport) { assert foldingSupport.getCount() == 1; TIntFunction foldingLineConvertor = foldingSupport.getLineConvertor(0); editor.getGutterComponentEx().setLineNumberConvertor(foldingLineConvertor); } public static void installLineConvertor(@NotNull EditorEx editor, @NotNull DocumentContent content) { TIntFunction contentLineConvertor = getContentLineConvertor(content); editor.getGutterComponentEx().setLineNumberConvertor(contentLineConvertor); } public static void installLineConvertor(@NotNull EditorEx editor, @NotNull DocumentContent content, @NotNull FoldingModelSupport foldingSupport, int editorIndex) { TIntFunction contentLineConvertor = getContentLineConvertor(content); TIntFunction foldingLineConvertor = foldingSupport.getLineConvertor(editorIndex); editor.getGutterComponentEx().setLineNumberConvertor(mergeLineConverters(contentLineConvertor, foldingLineConvertor)); } @Nullable public static TIntFunction getContentLineConvertor(@NotNull DocumentContent content) { return content.getUserData(DiffUserDataKeysEx.LINE_NUMBER_CONVERTOR); } @Nullable public static TIntFunction mergeLineConverters(@Nullable TIntFunction convertor1, @Nullable TIntFunction convertor2) { if (convertor1 == null && convertor2 == null) return null; if (convertor1 == null) return convertor2; if (convertor2 == null) return convertor1; return value -> { int value2 = convertor2.execute(value); return value2 >= 0 ? convertor1.execute(value2) : value2; }; } // Scrolling public static void disableBlitting(@NotNull EditorEx editor) { if (Registry.is("diff.divider.repainting.disable.blitting")) { editor.getScrollPane().getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE); } } public static void moveCaret(@Nullable final Editor editor, int line) { if (editor == null) return; editor.getCaretModel().removeSecondaryCarets(); editor.getCaretModel().moveToLogicalPosition(new LogicalPosition(line, 0)); } public static void scrollEditor(@Nullable final Editor editor, int line, boolean animated) { scrollEditor(editor, line, 0, animated); } public static void scrollEditor(@Nullable final Editor editor, int line, int column, boolean animated) { if (editor == null) return; editor.getCaretModel().removeSecondaryCarets(); editor.getCaretModel().moveToLogicalPosition(new LogicalPosition(line, column)); scrollToCaret(editor, animated); } public static void scrollToPoint(@Nullable Editor editor, @NotNull Point point, boolean animated) { if (editor == null) return; if (!animated) editor.getScrollingModel().disableAnimation(); editor.getScrollingModel().scrollHorizontally(point.x); editor.getScrollingModel().scrollVertically(point.y); if (!animated) editor.getScrollingModel().enableAnimation(); } public static void scrollToCaret(@Nullable Editor editor, boolean animated) { if (editor == null) return; if (!animated) editor.getScrollingModel().disableAnimation(); editor.getScrollingModel().scrollToCaret(ScrollType.CENTER); if (!animated) editor.getScrollingModel().enableAnimation(); } @NotNull public static Point getScrollingPosition(@Nullable Editor editor) { if (editor == null) return new Point(0, 0); ScrollingModel model = editor.getScrollingModel(); return new Point(model.getHorizontalScrollOffset(), model.getVerticalScrollOffset()); } @NotNull public static LogicalPosition getCaretPosition(@Nullable Editor editor) { return editor != null ? editor.getCaretModel().getLogicalPosition() : new LogicalPosition(0, 0); } public static void moveCaretToLineRangeIfNeeded(@NotNull Editor editor, int startLine, int endLine) { int caretLine = editor.getCaretModel().getLogicalPosition().line; if (!isSelectedByLine(caretLine, startLine, endLine)) { editor.getCaretModel().moveToLogicalPosition(new LogicalPosition(startLine, 0)); } } // Icons @NotNull public static Icon getArrowIcon(@NotNull Side sourceSide) { return sourceSide.select(AllIcons.Diff.ArrowRight, AllIcons.Diff.Arrow); } @NotNull public static Icon getArrowDownIcon(@NotNull Side sourceSide) { return sourceSide.select(AllIcons.Diff.ArrowRightDown, AllIcons.Diff.ArrowLeftDown); } public static void registerAction(@NotNull AnAction action, @NotNull JComponent component) { action.registerCustomShortcutSet(action.getShortcutSet(), component); } @NotNull public static JPanel createMessagePanel(@NotNull String message) { String text = StringUtil.replace(message, "\n", "<br>"); JLabel label = new JBLabel(text) { @Override public Dimension getMinimumSize() { Dimension size = super.getMinimumSize(); size.width = Math.min(size.width, 200); size.height = Math.min(size.height, 100); return size; } }.setCopyable(true); label.setForeground(UIUtil.getInactiveTextColor()); return new CenteredPanel(label, JBUI.Borders.empty(5)); } public static void addActionBlock(@NotNull DefaultActionGroup group, AnAction... actions) { addActionBlock(group, Arrays.asList(actions)); } public static void addActionBlock(@NotNull DefaultActionGroup group, @Nullable List<? extends AnAction> actions) { if (actions == null || actions.isEmpty()) return; group.addSeparator(); AnAction[] children = group.getChildren(null); for (AnAction action : actions) { if (action instanceof Separator || !ArrayUtil.contains(action, children)) { group.add(action); } } } @NotNull public static String getSettingsConfigurablePath() { return "Settings | Tools | Diff"; } @NotNull public static String createTooltipText(@NotNull String text, @Nullable String appendix) { StringBuilder result = new StringBuilder(); result.append("<html><body>"); result.append(text); if (appendix != null) { result.append("<br><div style='margin-top: 5px'><font size='2'>"); result.append(appendix); result.append("</font></div>"); } result.append("</body></html>"); return result.toString(); } @NotNull public static String createNotificationText(@NotNull String text, @Nullable String appendix) { StringBuilder result = new StringBuilder(); result.append("<html><body>"); result.append(text); if (appendix != null) { result.append("<br><span style='color:#").append(ColorUtil.toHex(JBColor.gray)).append("'><small>"); result.append(appendix); result.append("</small></span>"); } result.append("</body></html>"); return result.toString(); } public static void showSuccessPopup(@NotNull String message, @NotNull RelativePoint point, @NotNull Disposable disposable, @Nullable Runnable hyperlinkHandler) { HyperlinkListener listener = null; if (hyperlinkHandler != null) { listener = new HyperlinkAdapter() { @Override protected void hyperlinkActivated(HyperlinkEvent e) { hyperlinkHandler.run(); } }; } Color bgColor = MessageType.INFO.getPopupBackground(); Balloon balloon = JBPopupFactory.getInstance() .createHtmlTextBalloonBuilder(message, null, bgColor, listener) .setAnimationCycle(200) .createBalloon(); balloon.show(point, Balloon.Position.below); Disposer.register(disposable, balloon); } // Titles @NotNull public static List<JComponent> createSimpleTitles(@NotNull ContentDiffRequest request) { List<DiffContent> contents = request.getContents(); List<String> titles = request.getContentTitles(); if (!ContainerUtil.exists(titles, Condition.NOT_NULL)) { return Collections.nCopies(titles.size(), null); } List<JComponent> components = new ArrayList<>(titles.size()); for (int i = 0; i < contents.size(); i++) { JComponent title = createTitle(StringUtil.notNullize(titles.get(i))); title = createTitleWithNotifications(title, contents.get(i)); components.add(title); } return components; } @NotNull public static List<JComponent> createTextTitles(@NotNull ContentDiffRequest request, @NotNull List<? extends Editor> editors) { List<DiffContent> contents = request.getContents(); List<String> titles = request.getContentTitles(); boolean equalCharsets = TextDiffViewerUtil.areEqualCharsets(contents); boolean equalSeparators = TextDiffViewerUtil.areEqualLineSeparators(contents); List<JComponent> result = new ArrayList<>(contents.size()); if (equalCharsets && equalSeparators && !ContainerUtil.exists(titles, Condition.NOT_NULL)) { return Collections.nCopies(titles.size(), null); } for (int i = 0; i < contents.size(); i++) { JComponent title = createTitle(StringUtil.notNullize(titles.get(i)), contents.get(i), equalCharsets, equalSeparators, editors.get(i)); title = createTitleWithNotifications(title, contents.get(i)); result.add(title); } return result; } @Nullable private static JComponent createTitleWithNotifications(@Nullable JComponent title, @NotNull DiffContent content) { List<JComponent> notifications = new ArrayList<>(getCustomNotifications(content)); if (content instanceof DocumentContent) { Document document = ((DocumentContent)content).getDocument(); if (FileDocumentManager.getInstance().isPartialPreviewOfALargeFile(document)) { notifications.add(DiffNotifications.createNotification("File is too large. Only preview is loaded.")); } } if (notifications.isEmpty()) return title; JPanel panel = new JPanel(new BorderLayout(0, TITLE_GAP)); if (title != null) panel.add(title, BorderLayout.NORTH); panel.add(createStackedComponents(notifications, TITLE_GAP), BorderLayout.SOUTH); return panel; } @Nullable private static JComponent createTitle(@NotNull String title, @NotNull DiffContent content, boolean equalCharsets, boolean equalSeparators, @Nullable Editor editor) { if (content instanceof EmptyContent) return null; DocumentContent documentContent = (DocumentContent)content; Charset charset = equalCharsets ? null : documentContent.getCharset(); Boolean bom = equalCharsets ? null : documentContent.hasBom(); LineSeparator separator = equalSeparators ? null : documentContent.getLineSeparator(); boolean isReadOnly = editor == null || editor.isViewer() || !canMakeWritable(editor.getDocument()); return createTitle(title, separator, charset, bom, isReadOnly); } @NotNull public static JComponent createTitle(@NotNull String title) { return createTitle(title, null, null, null, false); } @NotNull public static JComponent createTitle(@NotNull String title, @Nullable LineSeparator separator, @Nullable Charset charset, @Nullable Boolean bom, boolean readOnly) { JPanel panel = new JPanel(new BorderLayout()); panel.setBorder(JBUI.Borders.empty(0, 4)); JBLabel titleLabel = new JBLabel(title).setCopyable(true); if (readOnly) titleLabel.setIcon(AllIcons.Ide.Readonly); panel.add(titleLabel, BorderLayout.CENTER); if (charset != null && separator != null) { JPanel panel2 = new JPanel(); panel2.setLayout(new BoxLayout(panel2, BoxLayout.X_AXIS)); panel2.add(createCharsetPanel(charset, bom)); panel2.add(Box.createRigidArea(JBUI.size(4, 0))); panel2.add(createSeparatorPanel(separator)); panel.add(panel2, BorderLayout.EAST); } else if (charset != null) { panel.add(createCharsetPanel(charset, bom), BorderLayout.EAST); } else if (separator != null) { panel.add(createSeparatorPanel(separator), BorderLayout.EAST); } return panel; } @NotNull private static JComponent createCharsetPanel(@NotNull Charset charset, @Nullable Boolean bom) { String text = charset.displayName(); if (bom != null && bom) { text += " BOM"; } JLabel label = new JLabel(text); // TODO: specific colors for other charsets if (charset.equals(Charset.forName("UTF-8"))) { label.setForeground(JBColor.BLUE); } else if (charset.equals(Charset.forName("ISO-8859-1"))) { label.setForeground(JBColor.RED); } else { label.setForeground(JBColor.BLACK); } return label; } @NotNull private static JComponent createSeparatorPanel(@NotNull LineSeparator separator) { JLabel label = new JLabel(separator.name()); Color color; if (separator == LineSeparator.CRLF) { color = JBColor.RED; } else if (separator == LineSeparator.LF) { color = JBColor.BLUE; } else if (separator == LineSeparator.CR) { color = JBColor.MAGENTA; } else { color = JBColor.BLACK; } label.setForeground(color); return label; } @NotNull public static List<JComponent> createSyncHeightComponents(@NotNull final List<JComponent> components) { if (!ContainerUtil.exists(components, Condition.NOT_NULL)) return components; List<JComponent> result = new ArrayList<>(); for (int i = 0; i < components.size(); i++) { result.add(new SyncHeightComponent(components, i)); } return result; } @NotNull public static JComponent createStackedComponents(@NotNull List<? extends JComponent> components, int gap) { JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); for (int i = 0; i < components.size(); i++) { if (i != 0) panel.add(Box.createVerticalStrut(JBUI.scale(gap))); panel.add(components.get(i)); } return panel; } // Focus public static boolean isFocusedComponent(@Nullable Component component) { return isFocusedComponent(null, component); } public static boolean isFocusedComponent(@Nullable Project project, @Nullable Component component) { if (component == null) return false; Component ideFocusOwner = IdeFocusManager.getInstance(project).getFocusOwner(); if (ideFocusOwner != null && SwingUtilities.isDescendingFrom(ideFocusOwner, component)) return true; Component jdkFocusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); if (jdkFocusOwner != null && SwingUtilities.isDescendingFrom(jdkFocusOwner, component)) return true; return false; } public static void requestFocus(@Nullable Project project, @Nullable Component component) { if (component == null) return; IdeFocusManager.getInstance(project).requestFocus(component, true); } public static boolean isFocusedComponentInWindow(@Nullable Component component) { if (component == null) return false; Window window = UIUtil.getWindow(component); if (window == null) return false; Component windowFocusOwner = window.getMostRecentFocusOwner(); return windowFocusOwner != null && SwingUtilities.isDescendingFrom(windowFocusOwner, component); } public static void requestFocusInWindow(@Nullable Component component) { if (component != null) component.requestFocusInWindow(); } public static void runPreservingFocus(@NotNull FocusableContext context, @NotNull Runnable task) { boolean hadFocus = context.isFocusedInWindow(); // if (hadFocus) KeyboardFocusManager.getCurrentKeyboardFocusManager().clearFocusOwner(); task.run(); if (hadFocus) context.requestFocusInWindow(); } // Compare @NotNull public static TwosideTextDiffProvider createTextDiffProvider(@Nullable Project project, @NotNull ContentDiffRequest request, @NotNull TextDiffSettings settings, @NotNull Runnable rediff, @NotNull Disposable disposable) { DiffUserDataKeysEx.DiffComputer diffComputer = request.getUserData(DiffUserDataKeysEx.CUSTOM_DIFF_COMPUTER); if (diffComputer != null) return new SimpleTextDiffProvider(settings, rediff, disposable, diffComputer); TwosideTextDiffProvider smartProvider = SmartTextDiffProvider.create(project, request, settings, rediff, disposable); if (smartProvider != null) return smartProvider; return new SimpleTextDiffProvider(settings, rediff, disposable); } @NotNull public static TwosideTextDiffProvider.NoIgnore createNoIgnoreTextDiffProvider(@Nullable Project project, @NotNull ContentDiffRequest request, @NotNull TextDiffSettings settings, @NotNull Runnable rediff, @NotNull Disposable disposable) { DiffUserDataKeysEx.DiffComputer diffComputer = request.getUserData(DiffUserDataKeysEx.CUSTOM_DIFF_COMPUTER); if (diffComputer != null) return new SimpleTextDiffProvider.NoIgnore(settings, rediff, disposable, diffComputer); TwosideTextDiffProvider.NoIgnore smartProvider = SmartTextDiffProvider.createNoIgnore(project, request, settings, rediff, disposable); if (smartProvider != null) return smartProvider; return new SimpleTextDiffProvider.NoIgnore(settings, rediff, disposable); } @Nullable public static MergeInnerDifferences compareThreesideInner(@NotNull List<? extends CharSequence> chunks, @NotNull ComparisonPolicy comparisonPolicy, @NotNull ProgressIndicator indicator) { if (chunks.get(0) == null && chunks.get(1) == null && chunks.get(2) == null) return null; if (comparisonPolicy == ComparisonPolicy.IGNORE_WHITESPACES) { if (isChunksEquals(chunks.get(0), chunks.get(1), comparisonPolicy) && isChunksEquals(chunks.get(0), chunks.get(2), comparisonPolicy)) { // whitespace-only changes, ex: empty lines added/removed return new MergeInnerDifferences(Collections.emptyList(), Collections.emptyList(), Collections.emptyList()); } } if (chunks.get(0) == null && chunks.get(1) == null || chunks.get(0) == null && chunks.get(2) == null || chunks.get(1) == null && chunks.get(2) == null) { return null; } if (chunks.get(0) != null && chunks.get(1) != null && chunks.get(2) != null) { List<DiffFragment> fragments1 = ByWord.compare(chunks.get(1), chunks.get(0), comparisonPolicy, indicator); List<DiffFragment> fragments2 = ByWord.compare(chunks.get(1), chunks.get(2), comparisonPolicy, indicator); List<TextRange> left = new ArrayList<>(); List<TextRange> base = new ArrayList<>(); List<TextRange> right = new ArrayList<>(); for (DiffFragment wordFragment : fragments1) { base.add(new TextRange(wordFragment.getStartOffset1(), wordFragment.getEndOffset1())); left.add(new TextRange(wordFragment.getStartOffset2(), wordFragment.getEndOffset2())); } for (DiffFragment wordFragment : fragments2) { base.add(new TextRange(wordFragment.getStartOffset1(), wordFragment.getEndOffset1())); right.add(new TextRange(wordFragment.getStartOffset2(), wordFragment.getEndOffset2())); } return new MergeInnerDifferences(left, base, right); } final ThreeSide side1 = chunks.get(0) != null ? ThreeSide.LEFT : ThreeSide.BASE; final ThreeSide side2 = chunks.get(2) != null ? ThreeSide.RIGHT : ThreeSide.BASE; CharSequence chunk1 = side1.select(chunks); CharSequence chunk2 = side2.select(chunks); List<DiffFragment> wordConflicts = ByWord.compare(chunk1, chunk2, comparisonPolicy, indicator); List<List<TextRange>> textRanges = ThreeSide.map(side -> { if (side == side1) { return ContainerUtil.map(wordConflicts, fragment -> new TextRange(fragment.getStartOffset1(), fragment.getEndOffset1())); } if (side == side2) { return ContainerUtil.map(wordConflicts, fragment -> new TextRange(fragment.getStartOffset2(), fragment.getEndOffset2())); } return null; }); return new MergeInnerDifferences(textRanges.get(0), textRanges.get(1), textRanges.get(2)); } private static boolean isChunksEquals(@Nullable CharSequence chunk1, @Nullable CharSequence chunk2, @NotNull ComparisonPolicy comparisonPolicy) { if (chunk1 == null) chunk1 = ""; if (chunk2 == null) chunk2 = ""; return ComparisonUtil.isEquals(chunk1, chunk2, comparisonPolicy); } @NotNull public static <T> int[] getSortedIndexes(@NotNull List<? extends T> values, @NotNull Comparator<? super T> comparator) { final List<Integer> indexes = new ArrayList<>(values.size()); for (int i = 0; i < values.size(); i++) { indexes.add(i); } ContainerUtil.sort(indexes, (i1, i2) -> { T val1 = values.get(i1); T val2 = values.get(i2); return comparator.compare(val1, val2); }); return ArrayUtil.toIntArray(indexes); } @NotNull public static int[] invertIndexes(@NotNull int[] indexes) { int[] inverted = new int[indexes.length]; for (int i = 0; i < indexes.length; i++) { inverted[indexes[i]] = i; } return inverted; } // Document modification public static boolean isSomeRangeSelected(@NotNull Editor editor, @NotNull Condition<? super BitSet> condition) { List<Caret> carets = editor.getCaretModel().getAllCarets(); if (carets.size() != 1) return true; Caret caret = carets.get(0); if (caret.hasSelection()) return true; return condition.value(getSelectedLines(editor)); } @NotNull public static BitSet getSelectedLines(@NotNull Editor editor) { Document document = editor.getDocument(); int totalLines = getLineCount(document); BitSet lines = new BitSet(totalLines + 1); if (editor instanceof EditorEx) { int expectedCaretOffset = ((EditorEx)editor).getExpectedCaretOffset(); if (editor.getCaretModel().getOffset() != expectedCaretOffset) { Caret caret = editor.getCaretModel().getPrimaryCaret(); appendSelectedLines(editor, lines, caret, expectedCaretOffset); return lines; } } for (Caret caret : editor.getCaretModel().getAllCarets()) { appendSelectedLines(editor, lines, caret, -1); } return lines; } private static void appendSelectedLines(@NotNull Editor editor, @NotNull BitSet lines, @NotNull Caret caret, int expectedCaretOffset) { Document document = editor.getDocument(); int totalLines = getLineCount(document); if (caret.hasSelection()) { int line1 = editor.offsetToLogicalPosition(caret.getSelectionStart()).line; int line2 = editor.offsetToLogicalPosition(caret.getSelectionEnd()).line; lines.set(line1, line2 + 1); if (caret.getSelectionEnd() == document.getTextLength()) lines.set(totalLines); } else { int offset; VisualPosition visualPosition; if (expectedCaretOffset == -1) { offset = caret.getOffset(); visualPosition = caret.getVisualPosition(); } else { offset = expectedCaretOffset; visualPosition = editor.offsetToVisualPosition(expectedCaretOffset); } Pair<LogicalPosition, LogicalPosition> pair = EditorUtil.calcSurroundingRange(editor, visualPosition, visualPosition); lines.set(pair.first.line, Math.max(pair.second.line, pair.first.line + 1)); if (offset == document.getTextLength()) lines.set(totalLines); } } public static boolean isSelectedByLine(int line, int line1, int line2) { if (line1 == line2 && line == line1) { return true; } if (line >= line1 && line < line2) { return true; } return false; } public static boolean isSelectedByLine(@NotNull BitSet selected, int line1, int line2) { if (line1 == line2) { return selected.get(line1); } else { int next = selected.nextSetBit(line1); return next != -1 && next < line2; } } private static void deleteLines(@NotNull Document document, int line1, int line2) { TextRange range = getLinesRange(document, line1, line2); int offset1 = range.getStartOffset(); int offset2 = range.getEndOffset(); if (offset1 > 0) { offset1 } else if (offset2 < document.getTextLength()) { offset2++; } document.deleteString(offset1, offset2); } private static void insertLines(@NotNull Document document, int line, @NotNull CharSequence text) { if (line == getLineCount(document)) { document.insertString(document.getTextLength(), "\n" + text); } else { document.insertString(document.getLineStartOffset(line), text + "\n"); } } private static void replaceLines(@NotNull Document document, int line1, int line2, @NotNull CharSequence text) { TextRange currentTextRange = getLinesRange(document, line1, line2); int offset1 = currentTextRange.getStartOffset(); int offset2 = currentTextRange.getEndOffset(); document.replaceString(offset1, offset2, text); } public static void applyModification(@NotNull Document document, int line1, int line2, @NotNull List<? extends CharSequence> newLines) { if (line1 == line2 && newLines.isEmpty()) return; if (line1 == line2) { insertLines(document, line1, StringUtil.join(newLines, "\n")); } else if (newLines.isEmpty()) { deleteLines(document, line1, line2); } else { replaceLines(document, line1, line2, StringUtil.join(newLines, "\n")); } } public static void applyModification(@NotNull Document document1, int line1, int line2, @NotNull Document document2, int oLine1, int oLine2) { if (line1 == line2 && oLine1 == oLine2) return; if (line1 == line2) { insertLines(document1, line1, getLinesContent(document2, oLine1, oLine2)); } else if (oLine1 == oLine2) { deleteLines(document1, line1, line2); } else { replaceLines(document1, line1, line2, getLinesContent(document2, oLine1, oLine2)); } } public static String applyModification(@NotNull CharSequence text, @NotNull LineOffsets lineOffsets, @NotNull CharSequence otherText, @NotNull LineOffsets otherLineOffsets, @NotNull List<? extends Range> ranges) { return new Object() { private final StringBuilder stringBuilder = new StringBuilder(); private boolean isEmpty = true; @NotNull public String execute() { int lastLine = 0; for (Range range : ranges) { CharSequence newChunkContent = getLinesContent(otherText, otherLineOffsets, range.start2, range.end2); appendOriginal(lastLine, range.start1); append(newChunkContent, range.end2 - range.start2); lastLine = range.end1; } appendOriginal(lastLine, lineOffsets.getLineCount()); return stringBuilder.toString(); } private void appendOriginal(int start, int end) { append(getLinesContent(text, lineOffsets, start, end), end - start); } private void append(CharSequence content, int lineCount) { if (lineCount > 0 && !isEmpty) { stringBuilder.append('\n'); } stringBuilder.append(content); isEmpty &= lineCount == 0; } }.execute(); } @NotNull public static CharSequence getLinesContent(@NotNull Document document, int line1, int line2) { return getLinesRange(document, line1, line2).subSequence(document.getImmutableCharSequence()); } @NotNull public static CharSequence getLinesContent(@NotNull Document document, int line1, int line2, boolean includeNewLine) { return getLinesRange(document, line1, line2, includeNewLine).subSequence(document.getImmutableCharSequence()); } @NotNull public static CharSequence getLinesContent(@NotNull CharSequence sequence, @NotNull LineOffsets lineOffsets, int line1, int line2) { return getLinesContent(sequence, lineOffsets, line1, line2, false); } @NotNull public static CharSequence getLinesContent(@NotNull CharSequence sequence, @NotNull LineOffsets lineOffsets, int line1, int line2, boolean includeNewline) { assert sequence.length() == lineOffsets.getTextLength(); return getLinesRange(lineOffsets, line1, line2, includeNewline).subSequence(sequence); } /** * Return affected range, without non-internal newlines * <p/> * we consider '\n' not as a part of line, but a separator between lines * ex: if last line is not empty, the last symbol will not be '\n' */ public static TextRange getLinesRange(@NotNull Document document, int line1, int line2) { return getLinesRange(document, line1, line2, false); } @NotNull public static TextRange getLinesRange(@NotNull Document document, int line1, int line2, boolean includeNewline) { return getLinesRange(LineOffsetsUtil.create(document), line1, line2, includeNewline); } @NotNull public static TextRange getLinesRange(@NotNull LineOffsets lineOffsets, int line1, int line2, boolean includeNewline) { if (line1 == line2) { int lineStartOffset = line1 < lineOffsets.getLineCount() ? lineOffsets.getLineStart(line1) : lineOffsets.getTextLength(); return new TextRange(lineStartOffset, lineStartOffset); } else { int startOffset = lineOffsets.getLineStart(line1); int endOffset = lineOffsets.getLineEnd(line2 - 1); if (includeNewline && endOffset < lineOffsets.getTextLength()) endOffset++; return new TextRange(startOffset, endOffset); } } public static int getOffset(@NotNull Document document, int line, int column) { if (line < 0) return 0; if (line >= getLineCount(document)) return document.getTextLength(); int start = document.getLineStartOffset(line); int end = document.getLineEndOffset(line); return Math.min(start + column, end); } /** * Document.getLineCount() returns 0 for empty text. * <p> * This breaks an assumption "getLineCount() == StringUtil.countNewLines(text) + 1" * and adds unnecessary corner case into line ranges logic. */ public static int getLineCount(@NotNull Document document) { return Math.max(document.getLineCount(), 1); } @NotNull public static List<String> getLines(@NotNull Document document) { return getLines(document, 0, getLineCount(document)); } @NotNull public static List<String> getLines(@NotNull CharSequence text, @NonNls LineOffsets lineOffsets) { return getLines(text, lineOffsets, 0, lineOffsets.getLineCount()); } @NotNull public static List<String> getLines(@NotNull Document document, int startLine, int endLine) { return getLines(document.getCharsSequence(), LineOffsetsUtil.create(document), startLine, endLine); } @NotNull public static List<String> getLines(@NotNull CharSequence text, @NonNls LineOffsets lineOffsets, int startLine, int endLine) { if (startLine < 0 || startLine > endLine || endLine > lineOffsets.getLineCount()) { throw new IndexOutOfBoundsException(String.format("Wrong line range: [%d, %d); lineCount: '%d'", startLine, endLine, lineOffsets.getLineCount())); } List<String> result = new ArrayList<>(); for (int i = startLine; i < endLine; i++) { int start = lineOffsets.getLineStart(i); int end = lineOffsets.getLineEnd(i); result.add(text.subSequence(start, end).toString()); } return result; } public static int bound(int value, int lowerBound, int upperBound) { assert lowerBound <= upperBound : String.format("%s - [%s, %s]", value, lowerBound, upperBound); return Math.max(Math.min(value, upperBound), lowerBound); } // Updating ranges on change @NotNull public static LineRange getAffectedLineRange(@NotNull DocumentEvent e) { int line1 = e.getDocument().getLineNumber(e.getOffset()); int line2 = e.getDocument().getLineNumber(e.getOffset() + e.getOldLength()) + 1; return new LineRange(line1, line2); } public static int countLinesShift(@NotNull DocumentEvent e) { return StringUtil.countNewLines(e.getNewFragment()) - StringUtil.countNewLines(e.getOldFragment()); } @NotNull public static UpdatedLineRange updateRangeOnModification(int start, int end, int changeStart, int changeEnd, int shift) { return updateRangeOnModification(start, end, changeStart, changeEnd, shift, false); } @NotNull public static UpdatedLineRange updateRangeOnModification(int start, int end, int changeStart, int changeEnd, int shift, boolean greedy) { if (end <= changeStart) { // change before return new UpdatedLineRange(start, end, false); } if (start >= changeEnd) { // change after return new UpdatedLineRange(start + shift, end + shift, false); } if (start <= changeStart && end >= changeEnd) { // change inside return new UpdatedLineRange(start, end + shift, false); } // range is damaged. We don't know new boundaries. // But we can try to return approximate new position int newChangeEnd = changeEnd + shift; if (start >= changeStart && end <= changeEnd) { // fully inside change return greedy ? new UpdatedLineRange(changeStart, newChangeEnd, true) : new UpdatedLineRange(newChangeEnd, newChangeEnd, true); } if (start < changeStart) { // bottom boundary damaged return greedy ? new UpdatedLineRange(start, newChangeEnd, true) : new UpdatedLineRange(start, changeStart, true); } else { // top boundary damaged return greedy ? new UpdatedLineRange(changeStart, end + shift, true) : new UpdatedLineRange(newChangeEnd, end + shift, true); } } public static class UpdatedLineRange { public final int startLine; public final int endLine; public final boolean damaged; public UpdatedLineRange(int startLine, int endLine, boolean damaged) { this.startLine = startLine; this.endLine = endLine; this.damaged = damaged; } } // Types @NotNull public static TextDiffType getLineDiffType(@NotNull LineFragment fragment) { boolean left = fragment.getStartLine1() != fragment.getEndLine1(); boolean right = fragment.getStartLine2() != fragment.getEndLine2(); return getDiffType(left, right); } @NotNull public static TextDiffType getDiffType(@NotNull DiffFragment fragment) { boolean left = fragment.getEndOffset1() != fragment.getStartOffset1(); boolean right = fragment.getEndOffset2() != fragment.getStartOffset2(); return getDiffType(left, right); } @NotNull public static TextDiffType getDiffType(boolean hasDeleted, boolean hasInserted) { if (hasDeleted && hasInserted) { return TextDiffType.MODIFIED; } else if (hasDeleted) { return TextDiffType.DELETED; } else if (hasInserted) { return TextDiffType.INSERTED; } else { LOG.error("Diff fragment should not be empty"); return TextDiffType.MODIFIED; } } @NotNull public static MergeConflictType getMergeType(@NotNull Condition<? super ThreeSide> emptiness, @NotNull Equality<? super ThreeSide> equality, @Nullable Equality<? super ThreeSide> trueEquality, @NotNull BooleanGetter conflictResolver) { boolean isLeftEmpty = emptiness.value(ThreeSide.LEFT); boolean isBaseEmpty = emptiness.value(ThreeSide.BASE); boolean isRightEmpty = emptiness.value(ThreeSide.RIGHT); assert !isLeftEmpty || !isBaseEmpty || !isRightEmpty; if (isBaseEmpty) { if (isLeftEmpty) { return new MergeConflictType(TextDiffType.INSERTED, false, true); } else if (isRightEmpty) { return new MergeConflictType(TextDiffType.INSERTED, true, false); } else { boolean equalModifications = equality.equals(ThreeSide.LEFT, ThreeSide.RIGHT); if (equalModifications) { return new MergeConflictType(TextDiffType.INSERTED, true, true); } else { return new MergeConflictType(TextDiffType.CONFLICT, true, true, false); } } } else { if (isLeftEmpty && isRightEmpty) { return new MergeConflictType(TextDiffType.DELETED, true, true); } else { boolean unchangedLeft = equality.equals(ThreeSide.BASE, ThreeSide.LEFT); boolean unchangedRight = equality.equals(ThreeSide.BASE, ThreeSide.RIGHT); if (unchangedLeft && unchangedRight) { assert trueEquality != null; boolean trueUnchangedLeft = trueEquality.equals(ThreeSide.BASE, ThreeSide.LEFT); boolean trueUnchangedRight = trueEquality.equals(ThreeSide.BASE, ThreeSide.RIGHT); assert !trueUnchangedLeft || !trueUnchangedRight; return new MergeConflictType(TextDiffType.MODIFIED, !trueUnchangedLeft, !trueUnchangedRight); } if (unchangedLeft) return new MergeConflictType(isRightEmpty ? TextDiffType.DELETED : TextDiffType.MODIFIED, false, true); if (unchangedRight) return new MergeConflictType(isLeftEmpty ? TextDiffType.DELETED : TextDiffType.MODIFIED, true, false); boolean equalModifications = equality.equals(ThreeSide.LEFT, ThreeSide.RIGHT); if (equalModifications) { return new MergeConflictType(TextDiffType.MODIFIED, true, true); } else { boolean canBeResolved = !isLeftEmpty && !isRightEmpty && conflictResolver.get(); return new MergeConflictType(TextDiffType.CONFLICT, true, true, canBeResolved); } } } } @NotNull public static MergeConflictType getLineThreeWayDiffType(@NotNull MergeLineFragment fragment, @NotNull List<? extends CharSequence> sequences, @NotNull List<? extends LineOffsets> lineOffsets, @NotNull ComparisonPolicy policy) { return getMergeType((side) -> isLineMergeIntervalEmpty(fragment, side), (side1, side2) -> compareLineMergeContents(fragment, sequences, lineOffsets, policy, side1, side2), null, () -> canResolveLineConflict(fragment, sequences, lineOffsets)); } @NotNull public static MergeConflictType getLineMergeType(@NotNull MergeLineFragment fragment, @NotNull List<? extends CharSequence> sequences, @NotNull List<? extends LineOffsets> lineOffsets, @NotNull ComparisonPolicy policy) { return getMergeType((side) -> isLineMergeIntervalEmpty(fragment, side), (side1, side2) -> compareLineMergeContents(fragment, sequences, lineOffsets, policy, side1, side2), (side1, side2) -> compareLineMergeContents(fragment, sequences, lineOffsets, ComparisonPolicy.DEFAULT, side1, side2), () -> canResolveLineConflict(fragment, sequences, lineOffsets)); } private static boolean canResolveLineConflict(@NotNull MergeLineFragment fragment, @NotNull List<? extends CharSequence> sequences, @NotNull List<? extends LineOffsets> lineOffsets) { List<? extends CharSequence> contents = ThreeSide.map(side -> { return getLinesContent(side.select(sequences), side.select(lineOffsets), fragment.getStartLine(side), fragment.getEndLine(side)); }); return ComparisonMergeUtil.tryResolveConflict(contents.get(0), contents.get(1), contents.get(2)) != null; } private static boolean compareLineMergeContents(@NotNull MergeLineFragment fragment, @NotNull List<? extends CharSequence> sequences, @NotNull List<? extends LineOffsets> lineOffsets, @NotNull ComparisonPolicy policy, @NotNull ThreeSide side1, @NotNull ThreeSide side2) { int start1 = fragment.getStartLine(side1); int end1 = fragment.getEndLine(side1); int start2 = fragment.getStartLine(side2); int end2 = fragment.getEndLine(side2); if (end2 - start2 != end1 - start1) return false; CharSequence sequence1 = side1.select(sequences); CharSequence sequence2 = side2.select(sequences); LineOffsets offsets1 = side1.select(lineOffsets); LineOffsets offsets2 = side2.select(lineOffsets); for (int i = 0; i < end1 - start1; i++) { int line1 = start1 + i; int line2 = start2 + i; CharSequence content1 = getLinesContent(sequence1, offsets1, line1, line1 + 1); CharSequence content2 = getLinesContent(sequence2, offsets2, line2, line2 + 1); if (!ComparisonUtil.isEquals(content1, content2, policy)) return false; } return true; } private static boolean isLineMergeIntervalEmpty(@NotNull MergeLineFragment fragment, @NotNull ThreeSide side) { return fragment.getStartLine(side) == fragment.getEndLine(side); } @NotNull public static MergeConflictType getWordMergeType(@NotNull MergeWordFragment fragment, @NotNull List<? extends CharSequence> texts, @NotNull ComparisonPolicy policy) { return getMergeType((side) -> isWordMergeIntervalEmpty(fragment, side), (side1, side2) -> compareWordMergeContents(fragment, texts, policy, side1, side2), null, BooleanGetter.FALSE); } public static boolean compareWordMergeContents(@NotNull MergeWordFragment fragment, @NotNull List<? extends CharSequence> texts, @NotNull ComparisonPolicy policy, @NotNull ThreeSide side1, @NotNull ThreeSide side2) { int start1 = fragment.getStartOffset(side1); int end1 = fragment.getEndOffset(side1); int start2 = fragment.getStartOffset(side2); int end2 = fragment.getEndOffset(side2); CharSequence document1 = side1.select(texts); CharSequence document2 = side2.select(texts); CharSequence content1 = document1.subSequence(start1, end1); CharSequence content2 = document2.subSequence(start2, end2); return ComparisonUtil.isEquals(content1, content2, policy); } private static boolean isWordMergeIntervalEmpty(@NotNull MergeWordFragment fragment, @NotNull ThreeSide side) { return fragment.getStartOffset(side) == fragment.getEndOffset(side); } // Writable @CalledInAwt public static boolean executeWriteCommand(@Nullable Project project, @NotNull Document document, @Nullable String commandName, @Nullable String commandGroupId, @NotNull UndoConfirmationPolicy confirmationPolicy, boolean underBulkUpdate, @NotNull Runnable task) { if (!makeWritable(project, document)) { VirtualFile file = FileDocumentManager.getInstance().getFile(document); LOG.warn("Document is read-only" + (file != null ? ": " + file.getPresentableName() : "")); return false; } ApplicationManager.getApplication().runWriteAction(() -> { CommandProcessor.getInstance().executeCommand(project, () -> { if (underBulkUpdate) { DocumentUtil.executeInBulk(document, true, task); } else { task.run(); } }, commandName, commandGroupId, confirmationPolicy, document); }); return true; } @CalledInAwt public static boolean executeWriteCommand(@NotNull final Document document, @Nullable final Project project, @Nullable final String commandName, @NotNull final Runnable task) { return executeWriteCommand(project, document, commandName, null, UndoConfirmationPolicy.DEFAULT, false, task); } public static boolean isEditable(@NotNull Editor editor) { return !editor.isViewer() && canMakeWritable(editor.getDocument()); } public static boolean canMakeWritable(@NotNull Document document) { if (document.isWritable()) { return true; } VirtualFile file = FileDocumentManager.getInstance().getFile(document); if (file != null && file.isValid() && file.isInLocalFileSystem()) { if (file.getUserData(TEMP_FILE_KEY) == Boolean.TRUE) return false; // decompiled file can be writable, but Document with decompiled content is still read-only return !file.isWritable(); } return false; } @CalledInAwt public static boolean makeWritable(@Nullable Project project, @NotNull Document document) { VirtualFile file = FileDocumentManager.getInstance().getFile(document); if (file == null) return document.isWritable(); if (!file.isValid()) return false; return makeWritable(project, file) && document.isWritable(); } @CalledInAwt public static boolean makeWritable(@Nullable Project project, @NotNull VirtualFile file) { if (project == null) project = ProjectManager.getInstance().getDefaultProject(); return !ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(file).hasReadonlyFiles(); } public static void putNonundoableOperation(@Nullable Project project, @NotNull Document document) { UndoManager undoManager = project != null ? UndoManager.getInstance(project) : UndoManager.getGlobalInstance(); if (undoManager != null) { DocumentReference ref = DocumentReferenceManager.getInstance().create(document); undoManager.nonundoableActionPerformed(ref, false); } } /** * Difference with {@link VfsUtil#markDirtyAndRefresh} is that refresh from VfsUtil will be performed with ModalityState.NON_MODAL. */ public static void markDirtyAndRefresh(boolean async, boolean recursive, boolean reloadChildren, @NotNull VirtualFile... files) { ModalityState modalityState = ApplicationManager.getApplication().getDefaultModalityState(); VfsUtil.markDirty(recursive, reloadChildren, files); RefreshQueue.getInstance().refresh(async, recursive, null, modalityState, files); } // Windows @NotNull public static Dimension getDefaultDiffPanelSize() { return new Dimension(400, 200); } @NotNull public static Dimension getDefaultDiffWindowSize() { Rectangle screenBounds = ScreenUtil.getMainScreenBounds(); int width = (int)(screenBounds.width * 0.8); int height = (int)(screenBounds.height * 0.8); return new Dimension(width, height); } @NotNull public static WindowWrapper.Mode getWindowMode(@NotNull DiffDialogHints hints) { WindowWrapper.Mode mode = hints.getMode(); if (mode == null) { boolean isUnderDialog = LaterInvocator.isInModalContext(); mode = isUnderDialog ? WindowWrapper.Mode.MODAL : WindowWrapper.Mode.FRAME; } return mode; } public static void closeWindow(@Nullable Window window, boolean modalOnly, boolean recursive) { if (window == null) return; Component component = window; while (component != null) { if (component instanceof Window) { boolean isClosed = closeWindow((Window)component, modalOnly); if (!isClosed) break; } component = recursive ? component.getParent() : null; } } /** * @return whether window was closed */ private static boolean closeWindow(@NotNull Window window, boolean modalOnly) { if (window instanceof IdeFrameImpl) return false; if (modalOnly && canBeHiddenBehind(window)) return false; if (window instanceof DialogWrapperDialog) { ((DialogWrapperDialog)window).getDialogWrapper().doCancelAction(); return !window.isVisible(); } window.setVisible(false); window.dispose(); return true; } private static boolean canBeHiddenBehind(@NotNull Window window) { if (!(window instanceof Frame)) return false; if (SystemInfo.isMac) { if (window instanceof IdeFrame) { // we can't move focus to full-screen main frame, as it will be hidden behind other frame windows Project project = ((IdeFrame)window).getProject(); IdeFrame projectFrame = WindowManager.getInstance().getIdeFrame(project); if (projectFrame instanceof IdeFrameEx) { return !((IdeFrameEx)projectFrame).isInFullScreen(); } } } return true; } // UserData public static <T> UserDataHolderBase createUserDataHolder(@NotNull Key<T> key, @Nullable T value) { UserDataHolderBase holder = new UserDataHolderBase(); holder.putUserData(key, value); return holder; } public static boolean isUserDataFlagSet(@NotNull Key<Boolean> key, UserDataHolder... holders) { for (UserDataHolder holder : holders) { if (holder == null) continue; Boolean data = holder.getUserData(key); if (data != null) return data; } return false; } public static <T> T getUserData(@Nullable UserDataHolder first, @Nullable UserDataHolder second, @NotNull Key<T> key) { if (first != null) { T data = first.getUserData(key); if (data != null) return data; } if (second != null) { T data = second.getUserData(key); if (data != null) return data; } return null; } public static void addNotification(@Nullable JComponent component, @NotNull UserDataHolder holder) { if (component == null) return; List<JComponent> oldComponents = ContainerUtil.notNullize(holder.getUserData(DiffUserDataKeys.NOTIFICATIONS)); holder.putUserData(DiffUserDataKeys.NOTIFICATIONS, ContainerUtil.append(oldComponents, component)); } @NotNull public static List<JComponent> getCustomNotifications(@NotNull UserDataHolder context, @NotNull UserDataHolder request) { List<JComponent> requestComponents = request.getUserData(DiffUserDataKeys.NOTIFICATIONS); List<JComponent> contextComponents = context.getUserData(DiffUserDataKeys.NOTIFICATIONS); return ContainerUtil.concat(ContainerUtil.notNullize(contextComponents), ContainerUtil.notNullize(requestComponents)); } @NotNull public static List<JComponent> getCustomNotifications(@NotNull DiffContent content) { return ContainerUtil.notNullize(content.getUserData(DiffUserDataKeys.NOTIFICATIONS)); } // DataProvider @Nullable public static Object getData(@Nullable DataProvider provider, @Nullable DataProvider fallbackProvider, @NotNull @NonNls String dataId) { if (provider != null) { Object data = provider.getData(dataId); if (data != null) return data; } if (fallbackProvider != null) { Object data = fallbackProvider.getData(dataId); if (data != null) return data; } return null; } public static <T> void putDataKey(@NotNull UserDataHolder holder, @NotNull DataKey<T> key, @Nullable T value) { DataProvider dataProvider = holder.getUserData(DiffUserDataKeys.DATA_PROVIDER); if (!(dataProvider instanceof GenericDataProvider)) { dataProvider = new GenericDataProvider(dataProvider); holder.putUserData(DiffUserDataKeys.DATA_PROVIDER, dataProvider); } ((GenericDataProvider)dataProvider).putData(key, value); } @NotNull public static DiffSettings getDiffSettings(@NotNull DiffContext context) { DiffSettings settings = context.getUserData(DiffSettings.KEY); if (settings == null) { settings = DiffSettings.getSettings(context.getUserData(DiffUserDataKeys.PLACE)); context.putUserData(DiffSettings.KEY, settings); } return settings; } @NotNull public static <K, V> TreeMap<K, V> trimDefaultValues(@NotNull TreeMap<K, V> map, @NotNull Convertor<? super K, V> defaultValue) { TreeMap<K, V> result = new TreeMap<>(); for (Map.Entry<K, V> it : map.entrySet()) { K key = it.getKey(); V value = it.getValue(); if (!value.equals(defaultValue.convert(key))) result.put(key, value); } return result; } // Tools @NotNull public static <T extends DiffTool> List<T> filterSuppressedTools(@NotNull List<T> tools) { if (tools.size() < 2) return tools; final List<Class<? extends DiffTool>> suppressedTools = new ArrayList<>(); for (T tool : tools) { try { if (tool instanceof SuppressiveDiffTool) suppressedTools.addAll(((SuppressiveDiffTool)tool).getSuppressedTools()); } catch (Throwable e) { LOG.error(e); } } if (suppressedTools.isEmpty()) return tools; List<T> filteredTools = ContainerUtil.filter(tools, tool -> !suppressedTools.contains(tool.getClass())); return filteredTools.isEmpty() ? tools : filteredTools; } @Nullable public static DiffTool findToolSubstitutor(@NotNull DiffTool tool, @NotNull DiffContext context, @NotNull DiffRequest request) { for (DiffToolSubstitutor substitutor : DiffToolSubstitutor.EP_NAME.getExtensions()) { DiffTool replacement = substitutor.getReplacement(tool, context, request); if (replacement == null) continue; boolean canShow = replacement.canShow(context, request); if (!canShow) { LOG.error("DiffTool substitutor returns invalid tool"); continue; } return replacement; } return null; } // Helpers private static class SyncHeightComponent extends JPanel { @NotNull private final List<JComponent> myComponents; SyncHeightComponent(@NotNull List<JComponent> components, int index) { super(new BorderLayout()); myComponents = components; JComponent delegate = components.get(index); if (delegate != null) add(delegate, BorderLayout.CENTER); } @Override public Dimension getPreferredSize() { Dimension size = super.getPreferredSize(); size.height = getPreferredHeight(); return size; } private int getPreferredHeight() { int height = 0; for (JComponent component : myComponents) { if (component == null) continue; height = Math.max(height, component.getPreferredSize().height); } return height; } } public static class CenteredPanel extends JPanel { private final JComponent myComponent; public CenteredPanel(@NotNull JComponent component) { myComponent = component; add(component); } public CenteredPanel(@NotNull JComponent component, @NotNull Border border) { this(component); setBorder(border); } @Override public void doLayout() { final Dimension size = getSize(); final Dimension preferredSize = myComponent.getPreferredSize(); Insets insets = getInsets(); JBInsets.removeFrom(size, insets); int width = Math.min(size.width, preferredSize.width); int height = Math.min(size.height, preferredSize.height); int x = Math.max(0, (size.width - preferredSize.width) / 2); int y = Math.max(0, (size.height - preferredSize.height) / 2); myComponent.setBounds(insets.left + x, insets.top + y, width, height); } @Override public Dimension getPreferredSize() { return addInsets(myComponent.getPreferredSize()); } @Override public Dimension getMinimumSize() { return addInsets(myComponent.getMinimumSize()); } @Override public Dimension getMaximumSize() { return addInsets(myComponent.getMaximumSize()); } private Dimension addInsets(Dimension dimension) { JBInsets.addTo(dimension, getInsets()); return dimension; } } }
package com.gocardless.services; import java.util.HashMap; import java.util.List; import java.util.Map; import com.gocardless.http.*; import com.gocardless.resources.Refund; import com.google.common.collect.ImmutableMap; import com.google.gson.reflect.TypeToken; /** * Service class for working with refund resources. * * Refund objects represent (partial) refunds of a [payment](#core-endpoints-payment) back to the * [customer](#core-endpoints-customers). * * GoCardless will notify you via a [webhook](#webhooks) * whenever a refund is created, and will update the `amount_refunded` property of the payment. * * * _Note:_ A payment that has been (partially) refunded can still receive a late failure or * chargeback from the banks. */ public class RefundService { private HttpClient httpClient; /** * Constructor. Users of this library should have no need to call this - an instance * of this class can be obtained by calling {@link com.gocardless.GoCardlessClient#refunds() }. */ public RefundService(HttpClient httpClient) { this.httpClient = httpClient; } /** * Creates a new refund object. * * This fails with:<a name="refund_payment_invalid_state"></a><a * name="total_amount_confirmation_invalid"></a><a name="number_of_refunds_exceeded"></a> * * - * `refund_payment_invalid_state` error if the linked [payment](#core-endpoints-payments) isn't * either `confirmed` or `paid_out`. * * - `total_amount_confirmation_invalid` if the confirmation * amount doesn't match the total amount refunded for the payment. This safeguard is there to prevent * two processes from creating refunds without awareness of each other. * * - * `number_of_refunds_exceeded` if five or more refunds have already been created against the * payment. * */ public RefundCreateRequest create() { return new RefundCreateRequest(httpClient); } /** * Returns a [cursor-paginated](#overview-cursor-pagination) list of your refunds. */ public RefundListRequest<ListResponse<Refund>> list() { return new RefundListRequest<>(httpClient, ListRequest.<Refund>pagingExecutor()); } public RefundListRequest<Iterable<Refund>> all() { return new RefundListRequest<>(httpClient, ListRequest.<Refund>iteratingExecutor()); } /** * Retrieves all details for a single refund */ public RefundGetRequest get(String identity) { return new RefundGetRequest(httpClient, identity); } /** * Updates a refund object. */ public RefundUpdateRequest update(String identity) { return new RefundUpdateRequest(httpClient, identity); } /** * Request class for {@link RefundService#create }. * * Creates a new refund object. * * This fails with:<a name="refund_payment_invalid_state"></a><a * name="total_amount_confirmation_invalid"></a><a name="number_of_refunds_exceeded"></a> * * - * `refund_payment_invalid_state` error if the linked [payment](#core-endpoints-payments) isn't * either `confirmed` or `paid_out`. * * - `total_amount_confirmation_invalid` if the confirmation * amount doesn't match the total amount refunded for the payment. This safeguard is there to prevent * two processes from creating refunds without awareness of each other. * * - * `number_of_refunds_exceeded` if five or more refunds have already been created against the * payment. * */ public static final class RefundCreateRequest extends PostRequest<Refund> { private Integer amount; private Links links; private Map<String, String> metadata; private Integer totalAmountConfirmation; /** * Amount in pence or cents. */ public RefundCreateRequest withAmount(Integer amount) { this.amount = amount; return this; } public RefundCreateRequest withLinks(Links links) { this.links = links; return this; } /** * ID of the [payment](#core-endpoints-payments) against which the refund is being made. */ public RefundCreateRequest withLinksPayment(String payment) { if (links == null) { links = new Links(); } links.withPayment(payment); return this; } /** * Key-value store of custom data. Up to 3 keys are permitted, with key names up to 50 characters and * values up to 200 characters. */ public RefundCreateRequest withMetadata(Map<String, String> metadata) { this.metadata = metadata; return this; } /** * Key-value store of custom data. Up to 3 keys are permitted, with key names up to 50 characters and * values up to 200 characters. */ public RefundCreateRequest withMetadata(String key, String value) { if (metadata == null) { metadata = new HashMap<>(); } metadata.put(key, value); return this; } /** * Total expected refunded amount in pence or cents. If there are other partial refunds against this * payment, this value should be the sum of the existing refunds plus the amount of the refund being * created. */ public RefundCreateRequest withTotalAmountConfirmation(Integer totalAmountConfirmation) { this.totalAmountConfirmation = totalAmountConfirmation; return this; } private RefundCreateRequest(HttpClient httpClient) { super(httpClient); } @Override protected String getPathTemplate() { return "/refunds"; } @Override protected String getEnvelope() { return "refunds"; } @Override protected Class<Refund> getResponseClass() { return Refund.class; } @Override protected boolean hasBody() { return true; } public static class Links { private String payment; /** * ID of the [payment](#core-endpoints-payments) against which the refund is being made. */ public Links withPayment(String payment) { this.payment = payment; return this; } } } /** * Request class for {@link RefundService#list }. * * Returns a [cursor-paginated](#overview-cursor-pagination) list of your refunds. */ public static final class RefundListRequest<S> extends ListRequest<S, Refund> { private String payment; /** * Cursor pointing to the start of the desired set. */ public RefundListRequest<S> withAfter(String after) { setAfter(after); return this; } /** * Cursor pointing to the end of the desired set. */ public RefundListRequest<S> withBefore(String before) { setBefore(before); return this; } /** * Number of records to return. */ public RefundListRequest<S> withLimit(Integer limit) { setLimit(limit); return this; } /** * Unique identifier, beginning with "PM". */ public RefundListRequest<S> withPayment(String payment) { this.payment = payment; return this; } private RefundListRequest(HttpClient httpClient, ListRequestExecutor<S, Refund> executor) { super(httpClient, executor); } @Override protected Map<String, Object> getQueryParams() { ImmutableMap.Builder<String, Object> params = ImmutableMap.builder(); params.putAll(super.getQueryParams()); if (payment != null) { params.put("payment", payment); } return params.build(); } @Override protected String getPathTemplate() { return "/refunds"; } @Override protected String getEnvelope() { return "refunds"; } @Override protected TypeToken<List<Refund>> getTypeToken() { return new TypeToken<List<Refund>>() {}; } } /** * Request class for {@link RefundService#get }. * * Retrieves all details for a single refund */ public static final class RefundGetRequest extends GetRequest<Refund> { @PathParam private final String identity; private RefundGetRequest(HttpClient httpClient, String identity) { super(httpClient); this.identity = identity; } @Override protected Map<String, String> getPathParams() { ImmutableMap.Builder<String, String> params = ImmutableMap.builder(); params.put("identity", identity); return params.build(); } @Override protected String getPathTemplate() { return "/refunds/:identity"; } @Override protected String getEnvelope() { return "refunds"; } @Override protected Class<Refund> getResponseClass() { return Refund.class; } } /** * Request class for {@link RefundService#update }. * * Updates a refund object. */ public static final class RefundUpdateRequest extends PutRequest<Refund> { @PathParam private final String identity; private Map<String, String> metadata; /** * Key-value store of custom data. Up to 3 keys are permitted, with key names up to 50 characters and * values up to 200 characters. */ public RefundUpdateRequest withMetadata(Map<String, String> metadata) { this.metadata = metadata; return this; } /** * Key-value store of custom data. Up to 3 keys are permitted, with key names up to 50 characters and * values up to 200 characters. */ public RefundUpdateRequest withMetadata(String key, String value) { if (metadata == null) { metadata = new HashMap<>(); } metadata.put(key, value); return this; } private RefundUpdateRequest(HttpClient httpClient, String identity) { super(httpClient); this.identity = identity; } @Override protected Map<String, String> getPathParams() { ImmutableMap.Builder<String, String> params = ImmutableMap.builder(); params.put("identity", identity); return params.build(); } @Override protected String getPathTemplate() { return "/refunds/:identity"; } @Override protected String getEnvelope() { return "refunds"; } @Override protected Class<Refund> getResponseClass() { return Refund.class; } @Override protected boolean hasBody() { return true; } } }
package com.greplin.interval; import com.google.common.base.Objects; import com.google.common.collect.ImmutableList; /** * Base class for numeric intervals. Most functionality is implemented in * subclasses to avoid autoboxing and improve performance. * @param <T> value type */ public abstract class NumericInterval<T extends Number> { /** * @return the start of the interval, boxed. */ public abstract T getBoxedStart(); /** * @return the end of the interval, boxed. */ public abstract T getBoxedEnd(); @Override @SuppressWarnings("unchecked") // Safe because this class is abstract. public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NumericInterval<T> interval = (NumericInterval<T>) o; return this.getBoxedEnd().equals(interval.getBoxedEnd()) && this.getBoxedStart().equals(interval.getBoxedStart()); } @Override public int hashCode() { return Objects.hashCode(this.getBoxedStart(), this.getBoxedEnd()); } @Override public String toString() { return this.getClass().getSimpleName() + "{" + this.getBoxedStart() + '-' + this.getBoxedEnd() + '}'; } /** * @return this interval formatted as a string. */ public String asString() { return this.getBoxedStart() + "-" + this.getBoxedEnd(); } /** * @return this interval formatted as a 2 element list. */ public ImmutableList<T> asList() { return ImmutableList.of(this.getBoxedStart(), this.getBoxedEnd()); } /** * @return this interval formatted as a 2 element list of strings. */ public ImmutableList<String> asStringList() { return ImmutableList.of( this.getBoxedStart().toString(), this.getBoxedEnd().toString()); } }
package com.google.sps.servlets; import com.google.cloud.tasks.v2.AppEngineHttpRequest; import com.google.cloud.tasks.v2.CloudTasksClient; import com.google.cloud.tasks.v2.HttpMethod; import com.google.cloud.tasks.v2.QueueName; import com.google.cloud.tasks.v2.Task; import com.google.common.annotations.VisibleForTesting; import com.google.protobuf.ByteString; import com.google.sps.workspace.Workspace; import com.google.sps.workspace.WorkspaceFactory; import java.io.IOException; import java.nio.charset.Charset; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/workspace/queueDownload") public class QueueDownload extends HttpServlet { WorkspaceFactory workspaceFactory = WorkspaceFactory.getInstance(); public QueueDownload() {} protected QueueDownload(WorkspaceFactory workspaceFactory) { this.workspaceFactory = workspaceFactory; } @VisibleForTesting protected CloudTasksClient getClient() throws IOException { return CloudTasksClient.create(); } @VisibleForTesting protected String getProjectID() { return System.getenv("GOOGLE_CLOUD_PROJECT"); } @VisibleForTesting protected String getQueueName() { return System.getenv("DOWNLOAD_QUEUE_ID"); } @VisibleForTesting protected String getLocation() { return System.getenv("LOCATION_ID"); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Workspace w = workspaceFactory.fromWorkspaceID(req.getParameter("workspaceID")); String downloadID = w.newDownloadID(); try (CloudTasksClient client = getClient()) { String queuePath = QueueName.of(getProjectID(), getLocation(), getQueueName()).toString(); Task.Builder taskBuilder = Task.newBuilder() .setAppEngineHttpRequest( AppEngineHttpRequest.newBuilder() .setBody( ByteString.copyFrom( String.join(",", w.getWorkspaceID(), downloadID), Charset.defaultCharset())) .setRelativeUri("/tasks/prepareDownload") .setHttpMethod(HttpMethod.POST) .build()); client.createTask(queuePath, taskBuilder.build()); resp.getWriter().print(downloadID); } } }
package org.jivesoftware.wildfire; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.jivesoftware.database.DbConnectionManager; import org.jivesoftware.database.SequenceManager; import org.jivesoftware.util.*; import org.jivesoftware.wildfire.container.BasicModule; import org.jivesoftware.wildfire.event.UserEventDispatcher; import org.jivesoftware.wildfire.event.UserEventListener; import org.jivesoftware.wildfire.user.User; import org.xmpp.packet.Message; import java.io.StringReader; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.*; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; /** * Represents the user's offline message storage. A message store holds messages that were * sent to the user while they were unavailable. The user can retrieve their messages by * setting their presence to "available". The messages will then be delivered normally. * Offline message storage is optional, in which case a null implementation is returned that * always throws UnauthorizedException when adding messages to the store. * * @author Iain Shigeoka */ public class OfflineMessageStore extends BasicModule implements UserEventListener { private static final String INSERT_OFFLINE = "INSERT INTO jiveOffline (username, messageID, creationDate, messageSize, message) " + "VALUES (?, ?, ?, ?, ?)"; private static final String LOAD_OFFLINE = "SELECT message, creationDate FROM jiveOffline WHERE username=?"; private static final String LOAD_OFFLINE_MESSAGE = "SELECT message FROM jiveOffline WHERE username=? AND creationDate=?"; private static final String SELECT_SIZE_OFFLINE = "SELECT SUM(messageSize) FROM jiveOffline WHERE username=?"; private static final String SELECT_SIZE_ALL_OFFLINE = "SELECT SUM(messageSize) FROM jiveOffline"; private static final String DELETE_OFFLINE = "DELETE FROM jiveOffline WHERE username=?"; private static final String DELETE_OFFLINE_MESSAGE = "DELETE FROM jiveOffline WHERE username=? AND creationDate=?"; private Cache sizeCache; private FastDateFormat dateFormat; /** * Returns the instance of <tt>OfflineMessageStore</tt> being used by the XMPPServer. * * @return the instance of <tt>OfflineMessageStore</tt> being used by the XMPPServer. */ public static OfflineMessageStore getInstance() { return XMPPServer.getInstance().getOfflineMessageStore(); } /** * Pool of SAX Readers. SAXReader is not thread safe so we need to have a pool of readers. */ private BlockingQueue<SAXReader> xmlReaders = new LinkedBlockingQueue<SAXReader>(); /** * Constructs a new offline message store. */ public OfflineMessageStore() { super("Offline Message Store"); dateFormat = FastDateFormat.getInstance("yyyyMMdd'T'HH:mm:ss", TimeZone.getTimeZone("UTC")); sizeCache = new Cache("Offline Message Size Cache", 1024*100, JiveConstants.HOUR*12); } /** * Adds a message to this message store. Messages will be stored and made * available for later delivery. * * @param message the message to store. */ public void addMessage(Message message) { if (message == null) { return; } String username = message.getTo().getNode(); // If the username is null (such as when an anonymous user), don't store. if (username == null) { return; } else if (!XMPPServer.getInstance().getServerInfo().getName().equals(message.getTo() .getDomain())) { // Do not store messages sent to users of remote servers return; } long messageID = SequenceManager.nextID(JiveConstants.OFFLINE); // Get the message in XML format. String msgXML = message.getElement().asXML(); Connection con = null; PreparedStatement pstmt = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement(INSERT_OFFLINE); pstmt.setString(1, username); pstmt.setLong(2, messageID); pstmt.setString(3, StringUtils.dateToMillis(new java.util.Date())); pstmt.setInt(4, msgXML.length()); pstmt.setString(5, msgXML); pstmt.executeUpdate(); } catch (Exception e) { Log.error(LocaleUtils.getLocalizedString("admin.error"), e); } finally { try { if (pstmt != null) { pstmt.close(); } } catch (Exception e) { Log.error(e); } try { if (con != null) { con.close(); } } catch (Exception e) { Log.error(e); } } // Update the cached size if it exists. if (sizeCache.containsKey(username)) { int size = (Integer)sizeCache.get(username); size += msgXML.length(); sizeCache.put(username, size); } } /** * Returns a Collection of all messages in the store for a user. * Messages may be deleted after being selected from the database depending on * the delete param. * * @param username the username of the user who's messages you'd like to receive. * @param delete true if the offline messages should be deleted. * @return An iterator of packets containing all offline messages. */ public Collection<OfflineMessage> getMessages(String username, boolean delete) { List<OfflineMessage> messages = new ArrayList<OfflineMessage>(); Connection con = null; PreparedStatement pstmt = null; SAXReader xmlReader = null; try { // Get a sax reader from the pool xmlReader = xmlReaders.take(); con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement(LOAD_OFFLINE); pstmt.setString(1, username); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { String msgXML = rs.getString(1); Date creationDate = new Date(Long.parseLong(rs.getString(2).trim())); OfflineMessage message = new OfflineMessage(creationDate, xmlReader.read(new StringReader(msgXML)).getRootElement()); // Add a delayed delivery (JEP-0091) element to the message. Element delay = message.addChildElement("x", "jabber:x:delay"); delay.addAttribute("from", XMPPServer.getInstance().getServerInfo().getName()); delay.addAttribute("stamp", dateFormat.format(creationDate)); messages.add(message); } rs.close(); // Check if the offline messages loaded should be deleted if (delete) { pstmt.close(); pstmt = con.prepareStatement(DELETE_OFFLINE); pstmt.setString(1, username); pstmt.executeUpdate(); removeUsernameFromSizeCache(username); } } catch (Exception e) { Log.error(LocaleUtils.getLocalizedString("admin.error"), e); } finally { // Return the sax reader to the pool if (xmlReader != null) xmlReaders.add(xmlReader); try { if (pstmt != null) { pstmt.close(); } } catch (Exception e) { Log.error(e); } try { if (con != null) { con.close(); } } catch (Exception e) { Log.error(e); } } return messages; } /** * Returns the offline message of the specified user with the given creation date. The * returned message will NOT be deleted from the database. * * @param username the username of the user who's message you'd like to receive. * @param creationDate the date when the offline message was stored in the database. * @return the offline message of the specified user with the given creation stamp. */ public OfflineMessage getMessage(String username, Date creationDate) { OfflineMessage message = null; Connection con = null; PreparedStatement pstmt = null; SAXReader xmlReader = null; try { // Get a sax reader from the pool xmlReader = xmlReaders.take(); con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement(LOAD_OFFLINE_MESSAGE); pstmt.setString(1, username); pstmt.setString(2, StringUtils.dateToMillis(creationDate)); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { String msgXML = rs.getString(1); message = new OfflineMessage(creationDate, xmlReader.read(new StringReader(msgXML)).getRootElement()); // Add a delayed delivery (JEP-0091) element to the message. Element delay = message.addChildElement("x", "jabber:x:delay"); delay.addAttribute("from", XMPPServer.getInstance().getServerInfo().getName()); delay.addAttribute("stamp", dateFormat.format(creationDate)); } rs.close(); } catch (Exception e) { Log.error(LocaleUtils.getLocalizedString("admin.error"), e); } finally { // Return the sax reader to the pool if (xmlReader != null) xmlReaders.add(xmlReader); try { if (pstmt != null) { pstmt.close(); } } catch (Exception e) { Log.error(e); } try { if (con != null) { con.close(); } } catch (Exception e) { Log.error(e); } } return message; } /** * Deletes all offline messages in the store for a user. * * @param username the username of the user who's messages are going to be deleted. */ public void deleteMessages(String username) { Connection con = null; PreparedStatement pstmt = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement(DELETE_OFFLINE); pstmt.setString(1, username); pstmt.executeUpdate(); removeUsernameFromSizeCache(username); } catch (Exception e) { Log.error(LocaleUtils.getLocalizedString("admin.error"), e); } finally { try { if (pstmt != null) { pstmt.close(); } } catch (Exception e) { Log.error(e); } try { if (con != null) { con.close(); } } catch (Exception e) { Log.error(e); } } } private void removeUsernameFromSizeCache(String username) { // Update the cached size if it exists. if (sizeCache.containsKey(username)) { sizeCache.remove(username); } } /** * Deletes the specified offline message in the store for a user. The way to identify the * message to delete is based on the creationDate and username. * * @param username the username of the user who's message is going to be deleted. * @param creationDate the date when the offline message was stored in the database. */ public void deleteMessage(String username, Date creationDate) { Connection con = null; PreparedStatement pstmt = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement(DELETE_OFFLINE_MESSAGE); pstmt.setString(1, username); pstmt.setString(2, StringUtils.dateToMillis(creationDate)); pstmt.executeUpdate(); //force a refresh for next call to getSize(username) //its easier than loading the msg to be deleted just //to update the cache. removeUsernameFromSizeCache(username); } catch (Exception e) { Log.error(LocaleUtils.getLocalizedString("admin.error"), e); } finally { try { if (pstmt != null) { pstmt.close(); } } catch (Exception e) { Log.error(e); } try { if (con != null) { con.close(); } } catch (Exception e) { Log.error(e); } } } /** * Returns the approximate size (in bytes) of the XML messages stored for * a particular user. * * @param username the username of the user. * @return the approximate size of stored messages (in bytes). */ public int getSize(String username) { // See if the size is cached. if (sizeCache.containsKey(username)) { return (Integer)sizeCache.get(username); } int size = 0; Connection con = null; PreparedStatement pstmt = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement(SELECT_SIZE_OFFLINE); pstmt.setString(1, username); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { size = rs.getInt(1); } rs.close(); // Add the value to cache. sizeCache.put(username, size); } catch (Exception e) { Log.error(LocaleUtils.getLocalizedString("admin.error"), e); } finally { try { if (pstmt != null) { pstmt.close(); } } catch (Exception e) { Log.error(e); } try { if (con != null) { con.close(); } } catch (Exception e) { Log.error(e); } } return size; } /** * Returns the approximate size (in bytes) of the XML messages stored for all * users. * * @return the approximate size of all stored messages (in bytes). */ public int getSize() { int size = 0; Connection con = null; PreparedStatement pstmt = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement(SELECT_SIZE_ALL_OFFLINE); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { size = rs.getInt(1); } rs.close(); } catch (Exception e) { Log.error(LocaleUtils.getLocalizedString("admin.error"), e); } finally { try { if (pstmt != null) { pstmt.close(); } } catch (Exception e) { Log.error(e); } try { if (con != null) { con.close(); } } catch (Exception e) { Log.error(e); } } return size; } public void userCreated(User user, Map params) { //Do nothing } public void userDeleting(User user, Map params) { // Delete all offline messages of the user deleteMessages(user.getUsername()); } public void userModified(User user, Map params) { //Do nothing } public void start() throws IllegalStateException { super.start(); // Initialize the pool of sax readers for (int i=0; i<10; i++) { xmlReaders.add(new SAXReader()); } // Add this module as a user event listener so we can delete // all offline messages when a user is deleted UserEventDispatcher.addListener(this); } public void stop() { super.stop(); // Clean up the pool of sax readers xmlReaders.clear(); // Remove this module as a user event listener UserEventDispatcher.removeListener(this); } }
/** * blinkerChannel is a CommandChannel created to transport data. * Data is published to the channel, and it can also be accessed * by playload.writeInt() to read from the channel * <p> * The blinky light is achieved by alternate the value publish to * the channel. The method shown below enable to turn on/off the * LED as well as block the command channel for the duration of a * blink * digitalSetValueAndBlock(int connector, int value, long msDuration) * @param connector the LED connect to the digital connector D5 * @param value 1 is turn on the LED while 0 turn off the LED * @param msDuration how long the channel is blocked till it is available for next command * @return return true when the method operated successfully */ package com.ociweb.iot.project.lightblink; import com.ociweb.gl.api.MessageReader; import com.ociweb.gl.api.PubSubListener; import com.ociweb.gl.api.StartupListener; import com.ociweb.iot.maker.FogCommandChannel; import com.ociweb.iot.maker.FogRuntime; import com.ociweb.iot.maker.FogApp; public class BlinkerBehavior implements StartupListener, PubSubListener { private static final String TOPIC = "light"; private static final int PAUSE = 500; private FogCommandChannel blinkerChannel; public BlinkerBehavior(FogRuntime runtime) { blinkerChannel = runtime.newCommandChannel( FogRuntime.PIN_WRITER | FogApp.DYNAMIC_MESSAGING); } @Override public boolean message(CharSequence topic, BlobReader payload) { int value = payload.readInt(); blinkerChannel.setValueAndBlock(IoTApp.LED_PORT, value==1, PAUSE); return blinkerChannel.publishTopic(TOPIC, w->{ w.writeInt( 1==value ? 0 : 1 ); }); } @Override public void startup() { blinkerChannel.subscribe(TOPIC, this); blinkerChannel.publishTopic(TOPIC,w->{ w.writeInt( 1 ); }); } }
package com.intellij.ui; import com.intellij.application.Topics; import com.intellij.codeInsight.hint.HintManagerImpl; import com.intellij.icons.AllIcons; import com.intellij.ide.FrameStateListener; import com.intellij.ide.IdeEventQueue; import com.intellij.ide.IdeTooltip; import com.intellij.ide.RemoteDesktopService; import com.intellij.ide.ui.PopupLocationTracker; import com.intellij.ide.ui.ScreenAreaConsumer; import com.intellij.openapi.MnemonicHelper; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.ex.AnActionListener; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.ui.GraphicsConfig; import com.intellij.openapi.ui.impl.ShadowBorderPainter; import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.ui.popup.JBPopupListener; import com.intellij.openapi.ui.popup.LightweightWindowEvent; import com.intellij.openapi.util.*; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.openapi.wm.IdeGlassPane; import com.intellij.openapi.wm.WeakFocusStackManager; import com.intellij.ui.awt.RelativePoint; import com.intellij.ui.components.panels.Wrapper; import com.intellij.ui.jcef.HwFacadeJPanel; import com.intellij.ui.jcef.HwFacadeNonOpaquePanel; import com.intellij.ui.scale.JBUIScale; import com.intellij.util.Alarm; import com.intellij.util.Consumer; import com.intellij.util.ui.*; import com.intellij.util.ui.accessibility.AccessibleContextUtil; import com.intellij.util.ui.accessibility.ScreenReader; import org.intellij.lang.annotations.JdkConstants; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.border.EmptyBorder; import javax.swing.event.HyperlinkEvent; import java.awt.*; import java.awt.event.*; import java.awt.geom.Area; import java.awt.geom.GeneralPath; import java.awt.geom.Rectangle2D; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.awt.image.ImageFilter; import java.awt.image.RGBImageFilter; import java.util.List; import java.util.*; import java.util.concurrent.CopyOnWriteArraySet; import static com.intellij.util.ui.UIUtil.useSafely; public final class BalloonImpl implements Balloon, IdeTooltip.Ui, ScreenAreaConsumer { private static final Logger LOG = Logger.getInstance(BalloonImpl.class); /** * This key is supposed to be used as client property of content component (with value Boolean.TRUE) to suppress shadow painting * when builder is being created indirectly and client cannot call its methods */ public static final Key<Boolean> FORCED_NO_SHADOW = Key.create("BALLOON_FORCED_NO_SHADOW"); private static final JBValue DIALOG_ARC = new JBValue.Float(6); public static final JBValue ARC = new JBValue.Float(3); private static final JBValue DIALOG_TOPBOTTOM_POINTER_WIDTH = new JBValue.Float(24); public static final JBValue DIALOG_POINTER_WIDTH = new JBValue.Float(17); private static final JBValue TOPBOTTOM_POINTER_WIDTH = new JBValue.Float(14); private static final JBValue POINTER_WIDTH = new JBValue.Float(11); private static final JBValue DIALOG_TOPBOTTOM_POINTER_LENGTH = new JBValue.Float(16); private static final JBValue DIALOG_POINTER_LENGTH = new JBValue.Float(14); private static final JBValue TOPBOTTOM_POINTER_LENGTH = new JBValue.Float(10); public static final JBValue POINTER_LENGTH = new JBValue.Float(8); private static final JBValue BORDER_STROKE_WIDTH = new JBValue.Float(1); private final Alarm myFadeoutAlarm = new Alarm(this); private long myFadeoutRequestMillis; private int myFadeoutRequestDelay; private boolean mySmartFadeout; private boolean mySmartFadeoutPaused; private int mySmartFadeoutDelay; private MyComponent myComp; private JLayeredPane myLayeredPane; private AbstractPosition myPosition; private Point myTargetPoint; private final boolean myHideOnFrameResize; private final boolean myHideOnLinkClick; private final Color myBorderColor; private final Insets myBorderInsets; private Color myFillColor; private Color myPointerColor; private final Insets myContainerInsets; private boolean myLastMoveWasInsideBalloon; private Rectangle myForcedBounds; private ActionProvider myActionProvider; private List<ActionButton> myActionButtons; private final AWTEventListener myAwtActivityListener = new AWTEventListener() { @Override public void eventDispatched(final AWTEvent e) { if (mySmartFadeoutDelay > 0) { startFadeoutTimer(mySmartFadeoutDelay); mySmartFadeoutDelay = 0; } final int id = e.getID(); if (e instanceof MouseEvent) { final MouseEvent me = (MouseEvent)e; final boolean insideBalloon = isInsideBalloon(me); boolean forcedExit = id == MouseEvent.MOUSE_EXITED && me.getButton() != MouseEvent.NOBUTTON && !myBlockClicks; if (myHideOnMouse && (id == MouseEvent.MOUSE_PRESSED || forcedExit)) { if ((!insideBalloon || forcedExit) && !isWithinChildWindow(me)) { if (myHideListener == null) { hide(); if (forcedExit) { int[] ids = {MouseEvent.MOUSE_ENTERED, MouseEvent.MOUSE_PRESSED, MouseEvent.MOUSE_RELEASED, MouseEvent.MOUSE_CLICKED}; for (int id_ : ids) { IdeEventQueue.getInstance() .dispatchEvent(new MouseEvent(me.getComponent(), id_, me.getWhen(), me.getModifiers(), me.getX(), me .getY(), me.getClickCount(), me.isPopupTrigger(), me.getButton())); } } } else { myHideListener.run(); } } return; } if (myClickHandler != null && id == MouseEvent.MOUSE_CLICKED) { if (!(me.getComponent() instanceof CloseButton) && insideBalloon) { myClickHandler.actionPerformed(new ActionEvent(me, ActionEvent.ACTION_PERFORMED, "click", me.getModifiersEx())); if (myCloseOnClick) { hide(); return; } } } if (myEnableButtons && id == MouseEvent.MOUSE_MOVED) { final boolean moveChanged = insideBalloon != myLastMoveWasInsideBalloon; myLastMoveWasInsideBalloon = insideBalloon; if (moveChanged) { if (insideBalloon && !myFadeoutAlarm.isEmpty()) { //Pause hiding timer when mouse is hover myFadeoutAlarm.cancelAllRequests(); myFadeoutRequestDelay -= System.currentTimeMillis() - myFadeoutRequestMillis; } if (!insideBalloon && myFadeoutRequestDelay > 0) { startFadeoutTimer(myFadeoutRequestDelay); } myComp.repaintButton(); } } if (myHideOnCloseClick && UIUtil.isCloseClick(me)) { if (isInsideBalloon(me)) { hide(); me.consume(); } return; } } if ((myHideOnKey || myHideListener != null) && e instanceof KeyEvent && id == KeyEvent.KEY_PRESSED) { final KeyEvent ke = (KeyEvent)e; if (myHideListener != null) { if (ke.getKeyCode() == KeyEvent.VK_ESCAPE) { myHideListener.run(); } return; } if (ke.getKeyCode() != KeyEvent.VK_SHIFT && ke.getKeyCode() != KeyEvent.VK_CONTROL && ke.getKeyCode() != KeyEvent.VK_ALT && ke.getKeyCode() != KeyEvent.VK_META) { boolean doHide = false; // Close the balloon is ESC is pressed inside the balloon if (ke.getKeyCode() == KeyEvent.VK_ESCAPE && SwingUtilities.isDescendingFrom(ke.getComponent(), myComp)) { doHide = true; } // Close the balloon if any key is pressed outside the balloon //noinspection ConstantConditions if (myHideOnKey && !SwingUtilities.isDescendingFrom(ke.getComponent(), myComp)) { doHide = true; } if (doHide) hide(); } } } }; private boolean isWithinChildWindow(@NotNull MouseEvent event) { Component owner = ComponentUtil.getWindow(myContent); if (owner != null) { Component child = ComponentUtil.getWindow(event.getComponent()); if (child != owner) { for (; child != null; child = child.getParent()) { if (child == owner) { return true; } } } } return false; } public void setFillColor(Color fillColor) { myFillColor = fillColor; } public Color getPointerColor() { return myPointerColor; } public void setPointerColor(Color pointerColor) { myPointerColor = pointerColor; } private final long myFadeoutTime; private Dimension myDefaultPrefSize; private final ActionListener myClickHandler; private final boolean myCloseOnClick; private final int myShadowSize; private ShadowBorderProvider myShadowBorderProvider; private final Collection<JBPopupListener> myListeners = new CopyOnWriteArraySet<>(); private boolean myVisible; private PositionTracker<Balloon> myTracker; private final int myAnimationCycle; private boolean myFadedIn; private boolean myFadedOut; private final int myCalloutShift; private final int myPositionChangeXShift; private final int myPositionChangeYShift; private boolean myDialogMode; private IdeFocusManager myFocusManager; private final String myTitle; private JLabel myTitleLabel; private boolean myAnimationEnabled = true; private final boolean myShadow; private final Layer myLayer; private final boolean myBlockClicks; private RelativePoint myPrevMousePoint; private boolean isInsideBalloon(@NotNull MouseEvent me) { return isInside(new RelativePoint(me)); } @Override public boolean isInside(@NotNull RelativePoint target) { if (myComp == null) return false; Component cmp = target.getOriginalComponent(); if (!cmp.isShowing()) return true; if (cmp instanceof MenuElement) return false; if (myActionButtons != null) { for (ActionButton button : myActionButtons) { if (cmp == button) return true; } } if (UIUtil.isDescendingFrom(cmp, myComp)) return true; if (myComp == null || !myComp.isShowing()) return false; Point point = target.getScreenPoint(); SwingUtilities.convertPointFromScreen(point, myComp); return myComp.contains(point); } public boolean isMovingForward(@NotNull RelativePoint target) { try { if (myComp == null || !myComp.isShowing()) return false; if (myPrevMousePoint == null) return true; if (myPrevMousePoint.getComponent() != target.getComponent()) return false; Rectangle rectangleOnScreen = new Rectangle(myComp.getLocationOnScreen(), myComp.getSize()); return ScreenUtil.isMovementTowards(myPrevMousePoint.getScreenPoint(), target.getScreenPoint(), rectangleOnScreen); } finally { myPrevMousePoint = target; } } private final ComponentAdapter myComponentListener = new ComponentAdapter() { @Override public void componentResized(final ComponentEvent e) { if (myHideOnFrameResize) { hide(); } } }; private Animator myAnimator; private boolean myShowPointer; private boolean myDisposed; private final JComponent myContent; private boolean myHideOnMouse; private Runnable myHideListener; private final boolean myHideOnKey; private final boolean myHideOnAction; private final boolean myHideOnCloseClick; private final boolean myRequestFocus; private Component myOriginalFocusOwner; private final boolean myEnableButtons; private final Dimension myPointerSize; private final int myCornerToPointerDistance; public BalloonImpl(@NotNull JComponent content, @NotNull Color borderColor, Insets borderInsets, @NotNull Color fillColor, boolean hideOnMouse, boolean hideOnKey, boolean hideOnAction, boolean hideOnCloseClick, boolean showPointer, boolean enableButtons, long fadeoutTime, boolean hideOnFrameResize, boolean hideOnLinkClick, ActionListener clickHandler, boolean closeOnClick, int animationCycle, int calloutShift, int positionChangeXShift, int positionChangeYShift, boolean dialogMode, String title, Insets contentInsets, boolean shadow, boolean smallVariant, boolean blockClicks, Layer layer, boolean requestFocus, Dimension pointerSize, int cornerToPointerDistance) { myBorderColor = borderColor; myBorderInsets = borderInsets != null ? borderInsets : JBInsets.create(5, 8); myFillColor = fillColor; myContent = content; myHideOnMouse = hideOnMouse; myHideOnKey = hideOnKey; myHideOnAction = hideOnAction; myHideOnCloseClick = hideOnCloseClick; myShowPointer = showPointer; myEnableButtons = enableButtons; myHideOnFrameResize = hideOnFrameResize; myHideOnLinkClick = hideOnLinkClick; myClickHandler = clickHandler; myCloseOnClick = closeOnClick; myCalloutShift = calloutShift; myPositionChangeXShift = positionChangeXShift; myPositionChangeYShift = positionChangeYShift; myDialogMode = dialogMode; myTitle = title; myLayer = layer != null ? layer : Layer.normal; myBlockClicks = blockClicks; myRequestFocus = requestFocus; MnemonicHelper.init(content); if (!myDialogMode) { for (Component component : UIUtil.uiTraverser(myContent)) { if (component instanceof JLabel) { JLabel label = (JLabel)component; if (label.getDisplayedMnemonic() != '\0' || label.getDisplayedMnemonicIndex() >= 0) { myDialogMode = true; break; } } else if (component instanceof JCheckBox) { JCheckBox checkBox = (JCheckBox)component; if (checkBox.getMnemonic() >= 0 || checkBox.getDisplayedMnemonicIndex() >= 0) { myDialogMode = true; break; } } } } myShadow = shadow; myShadowSize = Registry.intValue("ide.balloon.shadow.size"); myContainerInsets = contentInsets; myFadeoutTime = fadeoutTime; myAnimationCycle = animationCycle; myPointerSize = pointerSize; myCornerToPointerDistance = cornerToPointerDistance; if (smallVariant) { for (Component component : UIUtil.uiTraverser(myContent)) { UIUtil.applyStyle(UIUtil.ComponentStyle.SMALL, component); } } } @Override public void show(final RelativePoint target, final Balloon.Position position) { show(target, getAbstractPositionFor(position)); } public int getLayer() { Integer result = JLayeredPane.DEFAULT_LAYER; switch (myLayer) { case normal: result = JLayeredPane.POPUP_LAYER; break; case top: result = JLayeredPane.DRAG_LAYER; break; } return result; } private static AbstractPosition getAbstractPositionFor(@NotNull Position position) { switch (position) { case atLeft: return AT_LEFT; case atRight: return AT_RIGHT; case above: return ABOVE; case below: default: return BELOW; } } @Override public void show(PositionTracker<Balloon> tracker, Balloon.Position position) { show(tracker, getAbstractPositionFor(position)); } private Insets getInsetsCopy() { return JBUI.insets(myBorderInsets); } private void show(RelativePoint target, AbstractPosition position) { show(new PositionTracker.Static<>(target), position); } private void show(PositionTracker<Balloon> tracker, AbstractPosition position) { assert !myDisposed : "Balloon is already disposed"; if (isVisible()) return; final Component comp = tracker.getComponent(); if (!comp.isShowing()) return; myTracker = tracker; myTracker.init(this); JRootPane root = Objects.requireNonNull(UIUtil.getRootPane(comp)); myVisible = true; myLayeredPane = root.getLayeredPane(); myPosition = position; UIUtil.setFutureRootPane(myContent, root); myFocusManager = IdeFocusManager.findInstanceByComponent(myLayeredPane); final Ref<Component> originalFocusOwner = new Ref<>(); final Ref<ActionCallback> proxyFocusRequest = new Ref<>(ActionCallback.DONE); boolean mnemonicsFix = myDialogMode && SystemInfo.isMac && Registry.is("ide.mac.inplaceDialogMnemonicsFix"); if (mnemonicsFix) { proxyFocusRequest.set(new ActionCallback()); myFocusManager.doWhenFocusSettlesDown(new ExpirableRunnable() { @Override public boolean isExpired() { return isDisposed(); } @Override public void run() { IdeEventQueue.getInstance().disableInputMethods(BalloonImpl.this); originalFocusOwner.set(myFocusManager.getFocusOwner()); } }); } myLayeredPane.addComponentListener(myComponentListener); myTargetPoint = myPosition.getShiftedPoint(myTracker.recalculateLocation(this).getPoint(myLayeredPane), myCalloutShift); if (myDisposed) return; //tracker may dispose the balloon int positionChangeFix = 0; if (myShowPointer) { Rectangle rec = getRecForPosition(myPosition, true); if (!myPosition.isOkToHavePointer(myTargetPoint, rec, getPointerLength(myPosition), getPointerWidth(myPosition), getArc())) { rec = getRecForPosition(myPosition, false); Rectangle lp = new Rectangle(new Point(myContainerInsets.left, myContainerInsets.top), myLayeredPane.getSize()); lp.width -= myContainerInsets.right; lp.height -= myContainerInsets.bottom; if (!lp.contains(rec) || !PopupLocationTracker.canRectangleBeUsed(myLayeredPane, rec, this)) { Rectangle2D currentSquare = lp.createIntersection(rec); double maxSquare = currentSquare.getWidth() * currentSquare.getHeight(); AbstractPosition targetPosition = myPosition; for (AbstractPosition eachPosition : myPosition.getOtherPositions()) { Rectangle2D eachIntersection = lp.createIntersection(getRecForPosition(eachPosition, false)); double eachSquare = eachIntersection.getWidth() * eachIntersection.getHeight(); if (maxSquare < eachSquare) { maxSquare = eachSquare; targetPosition = eachPosition; } } myPosition = targetPosition; positionChangeFix = myPosition.getChangeShift(position, myPositionChangeXShift, myPositionChangeYShift); } } } if (myPosition != position) { myTargetPoint = myPosition.getShiftedPoint(myTracker.recalculateLocation(this).getPoint(myLayeredPane), myCalloutShift > 0 ? myCalloutShift + positionChangeFix : positionChangeFix); position = myPosition; } createComponent(); Rectangle r = getRecForPosition(myPosition, false); Point location = r.getLocation(); SwingUtilities.convertPointToScreen(location, myLayeredPane); r.setLocation(location); if (!PopupLocationTracker.canRectangleBeUsed(myLayeredPane, r, this)) { for (AbstractPosition eachPosition : myPosition.getOtherPositions()) { r = getRecForPosition(eachPosition, false); location = r.getLocation(); SwingUtilities.convertPointToScreen(location, myLayeredPane); r.setLocation(location); if (PopupLocationTracker.canRectangleBeUsed(myLayeredPane, r, this)) { myPosition = eachPosition; positionChangeFix = myPosition.getChangeShift(position, myPositionChangeXShift, myPositionChangeYShift); myTargetPoint = myPosition.getShiftedPoint(myTracker.recalculateLocation(this).getPoint(myLayeredPane), myCalloutShift > 0 ? myCalloutShift + positionChangeFix : positionChangeFix); myPosition.updateBounds(this); break; } } } myComp.validate(); Rectangle rec = myComp.getContentBounds(); if (myShowPointer && !myPosition.isOkToHavePointer(myTargetPoint, rec, getPointerLength(myPosition), getPointerWidth(myPosition), getArc())) { myShowPointer = false; myComp.removeAll(); myLayeredPane.remove(myComp); createComponent(); Dimension availSpace = myLayeredPane.getSize(); Dimension reqSpace = myComp.getSize(); if (!new Rectangle(availSpace).contains(new Rectangle(reqSpace))) { // Balloon is bigger than window, don't show it at all. LOG.warn("Not enough space to show: " + "required [" + reqSpace.width + " x " + reqSpace.height + "], " + "available [" + availSpace.width + " x " + availSpace.height + "]"); myComp.removeAll(); myLayeredPane.remove(myComp); myLayeredPane = null; hide(); return; } } for (JBPopupListener each : myListeners) { each.beforeShown(new LightweightWindowEvent(this)); } if (isAnimationEnabled()) { runAnimation(true, myLayeredPane, null); } myLayeredPane.revalidate(); myLayeredPane.repaint(); if (myRequestFocus) { myFocusManager.doWhenFocusSettlesDown(new ExpirableRunnable() { @Override public boolean isExpired() { return isDisposed(); } @Override public void run() { myOriginalFocusOwner = myFocusManager.getFocusOwner(); // Set the accessible parent so that screen readers don't announce // a window context change -- the tooltip is "logically" hosted // inside the component (e.g. editor) it appears on top of. AccessibleContextUtil.setParent((Component)myContent, myOriginalFocusOwner); // Set the focus to "myContent" myFocusManager.requestFocus(getContentToFocus(), true); } }); } if (mnemonicsFix) { proxyFocusRequest.get().doWhenDone(() -> myFocusManager.requestFocus(originalFocusOwner.get(), true)); } Toolkit.getDefaultToolkit().addAWTEventListener( myAwtActivityListener, AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK | AWTEvent.KEY_EVENT_MASK); if (ApplicationManager.getApplication() != null) { ApplicationManager.getApplication().getMessageBus().connect(this).subscribe(AnActionListener.TOPIC, new AnActionListener() { @Override public void beforeActionPerformed(@NotNull AnAction action, @NotNull DataContext dataContext, @NotNull AnActionEvent event) { if (myHideOnAction && !(action instanceof HintManagerImpl.ActionToIgnore)) { hide(); } } }); } if (myHideOnLinkClick) { JEditorPane editorPane = UIUtil.uiTraverser(myContent).traverse().filter(JEditorPane.class).first(); if (editorPane != null) { editorPane.addHyperlinkListener(new HyperlinkAdapter() { @Override protected void hyperlinkActivated(HyperlinkEvent e) { hide(); } }); } } } /** * Figure out the component to focus inside the {@link #myContent} field. */ @NotNull private Component getContentToFocus() { Component focusComponent = myContent; FocusTraversalPolicy policy = myContent.getFocusTraversalPolicy(); if (policy instanceof SortingFocusTraversalPolicy && ((SortingFocusTraversalPolicy)policy).getImplicitDownCycleTraversal()) { focusComponent = policy.getDefaultComponent(myContent); } while (true) { // Setting focus to a JScrollPane is not very useful. Better setting focus to the // contained view. This is useful for Tooltip popups, for example. if (focusComponent instanceof JScrollPane) { JViewport viewport = ((JScrollPane)focusComponent).getViewport(); if (viewport == null) { break; } Component child = viewport.getView(); if (child == null) { break; } focusComponent = child; continue; } // Done if we can't find anything to dive into break; } return focusComponent; } private Rectangle getRecForPosition(AbstractPosition position, boolean adjust) { Dimension size = getContentSizeFor(position); Rectangle rec = new Rectangle(new Point(0, 0), size); position.setRecToRelativePosition(rec, myTargetPoint); if (adjust) { rec = myPosition.getUpdatedBounds(this, rec.getSize()); } return rec; } private Dimension getContentSizeFor(AbstractPosition position) { Dimension size = myContent.getPreferredSize(); if (myShadowBorderProvider == null) { JBInsets.addTo(size, position.createBorder(this).getBorderInsets()); JBInsets.addTo(size, getShadowBorderInsets()); } return size; } private void disposeButton(ActionButton button) { if (button != null && button.getParent() != null) { Container parent = button.getParent(); parent.remove(button); //noinspection RedundantCast ((JComponent)parent).revalidate(); parent.repaint(); } } public JComponent getContent() { return myContent; } public JComponent getComponent() { return myComp; } private void createComponent() { myComp = new MyComponent(myContent, this, myShadowBorderProvider != null ? null : myShowPointer ? myPosition.createBorder(this) : getPointlessBorder()); if (myActionProvider == null) { final Consumer<MouseEvent> listener = event -> { //noinspection SSBasedInspection SwingUtilities.invokeLater(() -> hide()); }; myActionProvider = new ActionProvider() { private ActionButton myCloseButton; @NotNull @Override public List<ActionButton> createActions() { myCloseButton = new CloseButton(listener); return Collections.singletonList(myCloseButton); } @Override public void layout(@NotNull Rectangle lpBounds) { if (myCloseButton == null || !myCloseButton.isVisible()) { return; } Icon icon = getCloseButton(); int iconWidth = icon.getIconWidth(); int iconHeight = icon.getIconHeight(); Insets borderInsets = getShadowBorderInsets(); myCloseButton.setBounds(lpBounds.x + lpBounds.width - iconWidth - borderInsets.right - JBUIScale.scale(8), lpBounds.y + borderInsets.top + JBUIScale.scale(6), iconWidth, iconHeight); } }; } myComp.clear(); myComp.myAlpha = isAnimationEnabled() ? 0f : -1; myComp.setBorder(new EmptyBorder(getShadowBorderInsets())); myLayeredPane.add(myComp); myLayeredPane.setLayer(myComp, getLayer(), 0); // the second balloon must be over the first one myPosition.updateBounds(this); PopupLocationTracker.register(this); if (myBlockClicks) { myComp.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { e.consume(); } @Override public void mousePressed(MouseEvent e) { e.consume(); } @Override public void mouseReleased(MouseEvent e) { e.consume(); } }); } } @NotNull @Override public Rectangle getConsumedScreenBounds() { Rectangle bounds = myComp.getBounds(); Point location = bounds.getLocation(); SwingUtilities.convertPointToScreen(location, myLayeredPane); bounds.setLocation(location); return bounds; } @Override public Window getUnderlyingWindow() { return ComponentUtil.getWindow(myLayeredPane); } @NotNull private EmptyBorder getPointlessBorder() { return new EmptyBorder(myBorderInsets); } @Override public void revalidate() { revalidate(myTracker); } @Override public void revalidate(@NotNull PositionTracker<Balloon> tracker) { if (ApplicationManager.getApplication().isDisposed()) { return; } RelativePoint newPosition = tracker.recalculateLocation(this); if (newPosition != null) { myTargetPoint = myPosition.getShiftedPoint(newPosition.getPoint(myLayeredPane), myCalloutShift); myPosition.updateBounds(this); } } public void setShadowBorderProvider(@NotNull ShadowBorderProvider provider) { myShadowBorderProvider = provider; } private int getShadowBorderSize() { return hasShadow() ? myShadowSize : 0; } @NotNull public Insets getShadowBorderInsets() { if (myShadowBorderProvider != null) { return myShadowBorderProvider.getInsets(); } return JBUI.insets(getShadowBorderSize()); } public boolean hasShadow() { return myShadowBorderProvider != null || myShadow && Registry.is("ide.balloon.shadowEnabled"); } public interface ShadowBorderProvider { @NotNull Insets getInsets(); void paintShadow(@NotNull JComponent component, @NotNull Graphics g); void paintBorder(@NotNull Rectangle bounds, @NotNull Graphics2D g); void paintPointingShape(@NotNull Rectangle bounds, @NotNull Point pointTarget, @NotNull Position position, @NotNull Graphics2D g); } @Override public void show(JLayeredPane pane) { show(pane, null); } @Override public void showInCenterOf(JComponent component) { final Dimension size = component.getSize(); show(new RelativePoint(component, new Point(size.width / 2, size.height / 2)), Balloon.Position.above); } public void show(JLayeredPane pane, @Nullable Rectangle bounds) { if (bounds != null) { myForcedBounds = bounds; } show(new RelativePoint(pane, new Point(0, 0)), Balloon.Position.above); } private void runAnimation(boolean forward, final JLayeredPane layeredPane, @Nullable final Runnable onDone) { if (myAnimator != null) { Disposer.dispose(myAnimator); } myAnimator = new Animator("Balloon", 8, isAnimationEnabled() ? myAnimationCycle : 0, false, forward) { @Override public void paintNow(final int frame, final int totalFrames, final int cycle) { if (myComp == null || myComp.getParent() == null || !isAnimationEnabled()) return; myComp.setAlpha((float)frame / totalFrames); } @Override protected void paintCycleEnd() { if (myComp == null || myComp.getParent() == null) return; if (isForward()) { myComp.clear(); myComp.repaint(); myFadedIn = true; if (!myFadeoutAlarm.isDisposed()) { startFadeoutTimer((int)myFadeoutTime); } } else { layeredPane.remove(myComp); layeredPane.revalidate(); layeredPane.repaint(); } Disposer.dispose(this); } @Override public void dispose() { super.dispose(); myAnimator = null; if (onDone != null) { onDone.run(); } } }; myAnimator.resume(); } void runWithSmartFadeoutPause(@NotNull Runnable handler) { if (mySmartFadeout) { mySmartFadeoutPaused = true; handler.run(); if (mySmartFadeoutPaused) { mySmartFadeoutPaused = false; } else { setAnimationEnabled(true); hide(); } } else { handler.run(); } } public void startSmartFadeoutTimer(int delay) { mySmartFadeout = true; mySmartFadeoutDelay = delay; Topics.subscribe(FrameStateListener.TOPIC, this, new FrameStateListener() { @Override public void onFrameDeactivated() { if (!myFadeoutAlarm.isEmpty()) { myFadeoutAlarm.cancelAllRequests(); mySmartFadeoutDelay = myFadeoutRequestDelay - (int)(System.currentTimeMillis() - myFadeoutRequestMillis); if (mySmartFadeoutDelay <= 0) { mySmartFadeoutDelay = 1; } } } }); } public void startFadeoutTimer(final int fadeoutDelay) { if (fadeoutDelay > 0) { myFadeoutAlarm.cancelAllRequests(); myFadeoutRequestMillis = System.currentTimeMillis(); myFadeoutRequestDelay = fadeoutDelay; myFadeoutAlarm.addRequest(() -> { if (mySmartFadeout) { setAnimationEnabled(true); } hide(); }, fadeoutDelay, null); } } private int getArc() { return myDialogMode ? DIALOG_ARC.get() : ARC.get(); } private int getPointerWidth(AbstractPosition position) { if (myPointerSize == null || myPointerSize.width <= 0) { if (myDialogMode) { return position.isTopBottomPointer() ? DIALOG_TOPBOTTOM_POINTER_WIDTH.get() : DIALOG_POINTER_WIDTH.get(); } else { return position.isTopBottomPointer() ? TOPBOTTOM_POINTER_WIDTH.get() : POINTER_WIDTH.get(); } } else { return myPointerSize.width; } } public static int getNormalInset() { return 3; } private int getPointerLength(AbstractPosition position) { return myPointerSize == null || myPointerSize.height <= 0 ? getPointerLength(position, myDialogMode) : myPointerSize.height; } private static int getPointerLength(AbstractPosition position, boolean dialogMode) { if (dialogMode) { return position.isTopBottomPointer() ? DIALOG_TOPBOTTOM_POINTER_LENGTH.get() : DIALOG_POINTER_LENGTH.get(); } else { return position.isTopBottomPointer() ? TOPBOTTOM_POINTER_LENGTH.get() : POINTER_LENGTH.get(); } } public static int getPointerLength(@NotNull Position position, boolean dialogMode) { return getPointerLength(getAbstractPositionFor(position), dialogMode); } @Override public void hide() { hide(false); } @Override public void hide(boolean ok) { hideAndDispose(ok); } @Override public void dispose() { hideAndDispose(false); } private void hideAndDispose(final boolean ok) { if (myDisposed) return; if (mySmartFadeoutPaused) { mySmartFadeoutPaused = false; return; } myDisposed = true; hideComboBoxPopups(); final Runnable disposeRunnable = () -> { myFadedOut = true; if (myRequestFocus) { if (myOriginalFocusOwner != null) { myFocusManager.requestFocus(myOriginalFocusOwner, false); } } for (JBPopupListener each : myListeners) { each.onClosed(new LightweightWindowEvent(this, ok)); } Disposer.dispose(this); onDisposed(); }; Toolkit.getDefaultToolkit().removeAWTEventListener(myAwtActivityListener); if (myLayeredPane != null) { myLayeredPane.removeComponentListener(myComponentListener); if (isAnimationEnabled()) { runAnimation(false, myLayeredPane, disposeRunnable); } else { if (myAnimator != null) { Disposer.dispose(myAnimator); } if (myComp != null) { myLayeredPane.remove(myComp); myLayeredPane.revalidate(); myLayeredPane.repaint(); } disposeRunnable.run(); } } else { disposeRunnable.run(); } myVisible = false; myTracker = null; } private void hideComboBoxPopups() { List<JComboBox> comboBoxes = UIUtil.findComponentsOfType(myComp, JComboBox.class); for (JComboBox box : comboBoxes) { box.hidePopup(); } } private void onDisposed() { } @Override public void addListener(@NotNull JBPopupListener listener) { myListeners.add(listener); } public boolean isVisible() { return myVisible; } public void setHideOnClickOutside(boolean hideOnMouse) { myHideOnMouse = hideOnMouse; } public void setHideListener(@NotNull Runnable listener) { myHideListener = listener; myHideOnMouse = true; } public void setShowPointer(final boolean show) { myShowPointer = show; } public Icon getCloseButton() { return AllIcons.Ide.Notification.Close; } @Override public void setBounds(Rectangle bounds) { myForcedBounds = bounds; if (myPosition != null) { myPosition.updateBounds(this); } } @Override public Dimension getPreferredSize() { if (myComp != null) { return myComp.getPreferredSize(); } if (myDefaultPrefSize == null) { final EmptyBorder border = myShadowBorderProvider == null ? getPointlessBorder() : null; final MyComponent c = new MyComponent(myContent, this, border); c.setBorder(new EmptyBorder(getShadowBorderInsets())); myDefaultPrefSize = c.getPreferredSize(); } return myDefaultPrefSize; } private abstract static class AbstractPosition { abstract EmptyBorder createBorder(final BalloonImpl balloon); abstract void setRecToRelativePosition(Rectangle rec, Point targetPoint); abstract int getChangeShift(AbstractPosition original, int xShift, int yShift); public void updateBounds(@NotNull final BalloonImpl balloon) { if (balloon.myLayeredPane == null || balloon.myComp == null) return; Rectangle bounds = getUpdatedBounds(balloon, balloon.myComp.getPreferredSize()); if (balloon.myShadowBorderProvider == null) { bounds = new Rectangle(getShiftedPoint(bounds.getLocation(), balloon.getShadowBorderInsets()), bounds.getSize()); } balloon.myComp._setBounds(bounds); } @NotNull Rectangle getUpdatedBounds(BalloonImpl balloon, Dimension preferredSize) { Dimension layeredPaneSize = balloon.myLayeredPane.getSize(); Point point = balloon.myTargetPoint; Rectangle bounds = balloon.myForcedBounds; if (bounds == null) { int distance = getDistance(balloon, preferredSize); Point location = balloon.myShowPointer ? getLocation(layeredPaneSize, point, preferredSize, distance) // Now distance is used for pointer enabled balloons only : new Point(point.x - preferredSize.width / 2, point.y - preferredSize.height / 2); bounds = new Rectangle(location.x, location.y, preferredSize.width, preferredSize.height); ScreenUtil.moveToFit(bounds, new Rectangle(0, 0, layeredPaneSize.width, layeredPaneSize.height), balloon.myContainerInsets); } return bounds; } private int getDistance(@NotNull BalloonImpl balloon, @NotNull Dimension size) { if (balloon.myCornerToPointerDistance < 0) return -1; int indent = balloon.getArc() + balloon.getPointerWidth(this)/2; if (balloon.myCornerToPointerDistance < indent) return indent; int limit = this == ABOVE || this == BELOW ? size.width - indent : size.height - indent; return Math.min(balloon.myCornerToPointerDistance, limit); } abstract Point getLocation(final Dimension containerSize, final Point targetPoint, final Dimension balloonSize, int distance); void paintComponent(BalloonImpl balloon, final Rectangle bounds, final Graphics2D g, Point pointTarget) { final GraphicsConfig cfg = new GraphicsConfig(g); cfg.setAntialiasing(true); if (balloon.myShadowBorderProvider != null) { balloon.myShadowBorderProvider.paintBorder(bounds, g); if (balloon.myShowPointer) { Position position; if (this == ABOVE) { position = Position.above; } else if (this == BELOW) { position = Position.below; } else if (this == AT_LEFT) { position = Position.atLeft; } else { position = Position.atRight; } balloon.myShadowBorderProvider.paintPointingShape(bounds, pointTarget, position, g); } cfg.restore(); return; } Shape shape; if (balloon.myShowPointer) { shape = getPointingShape(bounds, pointTarget, balloon); } else { shape = getPointlessShape(balloon, bounds); } g.setPaint(balloon.myFillColor); g.fill(shape); if (balloon.myShowPointer && balloon.myPointerColor != null) { Shape balloonShape = getPointlessContentRec(bounds, getPointerLength(this, balloon.myDialogMode) + 1); Area area = new Area(shape); area.subtract(new Area(balloonShape)); g.setColor(balloon.myPointerColor); g.fill(area); } g.setColor(balloon.myBorderColor); if (balloon.myTitleLabel != null) { Rectangle titleBounds = balloon.myTitleLabel.getBounds(); Insets inset = getTitleInsets(getNormalInset() - 1, balloon.getPointerLength(this) + 50); Insets borderInsets = balloon.getShadowBorderInsets(); inset.top += borderInsets.top; inset.bottom += borderInsets.bottom; inset.left += borderInsets.left; inset.right += borderInsets.right; titleBounds.x -= inset.left + JBUIScale.scale(1); titleBounds.width += inset.left + inset.right + JBUIScale.scale(50); titleBounds.y -= inset.top + JBUIScale.scale(1); titleBounds.height += inset.top + inset.bottom + JBUIScale.scale(1); Area area = new Area(shape); area.intersect(new Area(titleBounds)); Color fgColor = UIManager.getColor("Label.foreground"); fgColor = ColorUtil.toAlpha(fgColor, 140); g.setColor(fgColor); g.fill(area); g.setColor(balloon.myBorderColor); g.draw(area); } g.setStroke(new BasicStroke(BORDER_STROKE_WIDTH.get())); g.draw(shape); cfg.restore(); } protected abstract Insets getTitleInsets(int normalInset, int pointerLength); protected abstract Shape getPointingShape(final Rectangle bounds, final Point pointTarget, final BalloonImpl balloon); boolean isOkToHavePointer(@NotNull Point targetPoint, @NotNull Rectangle bounds, int pointerLength, int pointerWidth, int arc) { if (bounds.x < targetPoint.x && bounds.x + bounds.width > targetPoint.x && bounds.y < targetPoint.y && bounds.y + bounds.height > targetPoint.y) { return false; } Rectangle pointless = getPointlessContentRec(bounds, pointerLength); int distance = getDistanceToTarget(pointless, targetPoint); if (distance < pointerLength - 1 || distance > 2 * pointerLength) return false; UnfairTextRange balloonRange; UnfairTextRange pointerRange; if (isTopBottomPointer()) { balloonRange = new UnfairTextRange(bounds.x + arc - 1, bounds.x + bounds.width - arc * 2 + 1); pointerRange = new UnfairTextRange(targetPoint.x - pointerWidth / 2, targetPoint.x + pointerWidth / 2); } else { balloonRange = new UnfairTextRange(bounds.y + arc - 1, bounds.y + bounds.height - arc * 2 + 1); pointerRange = new UnfairTextRange(targetPoint.y - pointerWidth / 2, targetPoint.y + pointerWidth / 2); } return balloonRange.contains(pointerRange); } protected abstract int getDistanceToTarget(Rectangle rectangle, Point targetPoint); boolean isTopBottomPointer() { return this instanceof Below || this instanceof Above; } protected abstract Rectangle getPointlessContentRec(Rectangle bounds, int pointerLength); @NotNull Set<AbstractPosition> getOtherPositions() { LinkedHashSet<AbstractPosition> all = new LinkedHashSet<>(); all.add(BELOW); all.add(ABOVE); all.add(AT_RIGHT); all.add(AT_LEFT); all.remove(this); return all; } @NotNull public abstract Point getShiftedPoint(@NotNull Point targetPoint, int shift); @NotNull public abstract Point getShiftedPoint(@NotNull Point targetPoint, @NotNull Insets shift); @Override public String toString() { return getClass().getSimpleName(); } } @NotNull private static RoundRectangle2D.Double getPointlessShape(BalloonImpl balloon, Rectangle bounds) { return new RoundRectangle2D.Double(bounds.x, bounds.y, bounds.width - JBUIScale.scale(1), bounds.height - JBUIScale.scale(1), balloon.getArc(), balloon.getArc()); } public static final AbstractPosition BELOW = new Below(); public static final AbstractPosition ABOVE = new Above(); public static final AbstractPosition AT_RIGHT = new AtRight(); public static final AbstractPosition AT_LEFT = new AtLeft(); private static class Below extends AbstractPosition { @NotNull @Override public Point getShiftedPoint(@NotNull Point targetPoint, int shift) { return new Point(targetPoint.x, targetPoint.y + shift); } @NotNull @Override public Point getShiftedPoint(@NotNull Point targetPoint, @NotNull Insets shift) { return getShiftedPoint(targetPoint, -shift.top); } @Override int getChangeShift(AbstractPosition original, int xShift, int yShift) { return original == ABOVE ? yShift : 0; } @Override protected int getDistanceToTarget(Rectangle rectangle, Point targetPoint) { return rectangle.y - targetPoint.y; } @Override protected Rectangle getPointlessContentRec(Rectangle bounds, int pointerLength) { return new Rectangle(bounds.x, bounds.y + pointerLength, bounds.width, bounds.height - pointerLength); } @Override EmptyBorder createBorder(final BalloonImpl balloon) { Insets insets = balloon.getInsetsCopy(); insets.top += balloon.getPointerLength(this); return new EmptyBorder(insets); } @Override void setRecToRelativePosition(Rectangle rec, Point targetPoint) { rec.setLocation(new Point(targetPoint.x - rec.width / 2, targetPoint.y)); } @Override Point getLocation(final Dimension containerSize, final Point targetPoint, final Dimension balloonSize, int distance) { if (distance > 0) { return new Point(targetPoint.x - distance, targetPoint.y); } else { final Point center = StartupUiUtil.getCenterPoint(new Rectangle(targetPoint, JBUI.emptySize()), balloonSize); return new Point(center.x, targetPoint.y); } } @Override protected Insets getTitleInsets(int normalInset, int pointerLength) { //noinspection UseDPIAwareInsets return new Insets(pointerLength, JBUIScale.scale(normalInset), JBUIScale.scale(normalInset), JBUIScale.scale(normalInset)); } @Override protected Shape getPointingShape(final Rectangle bounds, Point pointTarget, final BalloonImpl balloon) { pointTarget = new Point(pointTarget.x, Math.min(bounds.y, pointTarget.y)); final Shaper shaper = new Shaper(balloon, bounds, pointTarget, SwingConstants.TOP); shaper.line(balloon.getPointerWidth(this) / 2, balloon.getPointerLength(this)).toRightCurve().roundRightDown().toBottomCurve() .roundLeftDown() .toLeftCurve().roundLeftUp().toTopCurve().roundUpRight() .lineTo(pointTarget.x - balloon.getPointerWidth(this) / 2, shaper.getCurrent().y).lineTo(pointTarget.x, pointTarget.y); shaper.close(); return shaper.getShape(); } } private static class Above extends AbstractPosition { @NotNull @Override public Point getShiftedPoint(@NotNull Point targetPoint, int shift) { return new Point(targetPoint.x, targetPoint.y - shift); } @NotNull @Override public Point getShiftedPoint(@NotNull Point targetPoint, @NotNull Insets shift) { return getShiftedPoint(targetPoint, -shift.top); } @Override int getChangeShift(AbstractPosition original, int xShift, int yShift) { return original == BELOW ? -yShift : 0; } @Override protected int getDistanceToTarget(Rectangle rectangle, Point targetPoint) { return targetPoint.y - (int)rectangle.getMaxY(); } @Override protected Rectangle getPointlessContentRec(Rectangle bounds, int pointerLength) { return new Rectangle(bounds.x, bounds.y, bounds.width, bounds.height - pointerLength); } @Override EmptyBorder createBorder(final BalloonImpl balloon) { Insets insets = balloon.getInsetsCopy(); insets.bottom += balloon.getPointerLength(this); return new EmptyBorder(insets); } @Override void setRecToRelativePosition(Rectangle rec, Point targetPoint) { rec.setLocation(targetPoint.x - rec.width / 2, targetPoint.y - rec.height); } @Override Point getLocation(final Dimension containerSize, final Point targetPoint, final Dimension balloonSize, int distance) { if (distance > 0) { return new Point(targetPoint.x - distance, targetPoint.y - balloonSize.height); } else { final Point center = StartupUiUtil.getCenterPoint(new Rectangle(targetPoint, JBUI.emptySize()), balloonSize); return new Point(center.x, targetPoint.y - balloonSize.height); } } @Override protected Insets getTitleInsets(int normalInset, int pointerLength) { return JBUI.insets(normalInset, normalInset, normalInset, normalInset); } @Override protected Shape getPointingShape(final Rectangle bounds, Point pointTarget, final BalloonImpl balloon) { pointTarget = new Point(pointTarget.x, Math.max((int) bounds.getMaxY(), pointTarget.y)); final Shaper shaper = new Shaper(balloon, bounds, pointTarget, SwingConstants.BOTTOM); shaper.line(-balloon.getPointerWidth(this) / 2, -balloon.getPointerLength(this) + JBUIScale.scale(1)); shaper.toLeftCurve().roundLeftUp().toTopCurve().roundUpRight().toRightCurve().roundRightDown().toBottomCurve().line(0, 2) .roundLeftDown().lineTo(pointTarget.x + balloon.getPointerWidth(this) / 2, shaper.getCurrent().y) .lineTo(pointTarget.x, pointTarget.y) .close(); return shaper.getShape(); } } private static class AtRight extends AbstractPosition { @NotNull @Override public Point getShiftedPoint(@NotNull Point targetPoint, int shift) { return new Point(targetPoint.x + shift, targetPoint.y); } @NotNull @Override public Point getShiftedPoint(@NotNull Point targetPoint, @NotNull Insets shift) { return getShiftedPoint(targetPoint, -shift.left); } @Override int getChangeShift(AbstractPosition original, int xShift, int yShift) { return original == AT_LEFT ? xShift : 0; } @Override protected int getDistanceToTarget(Rectangle rectangle, Point targetPoint) { return rectangle.x - targetPoint.x; } @Override protected Rectangle getPointlessContentRec(Rectangle bounds, int pointerLength) { return new Rectangle(bounds.x + pointerLength, bounds.y, bounds.width - pointerLength, bounds.height); } @Override EmptyBorder createBorder(final BalloonImpl balloon) { Insets insets = balloon.getInsetsCopy(); insets.left += balloon.getPointerLength(this); return new EmptyBorder(insets); } @Override void setRecToRelativePosition(Rectangle rec, Point targetPoint) { rec.setLocation(targetPoint.x, targetPoint.y - rec.height / 2); } @Override Point getLocation(final Dimension containerSize, final Point targetPoint, final Dimension balloonSize, int distance) { if (distance > 0) { return new Point(targetPoint.x, targetPoint.y - distance); } else { final Point center = StartupUiUtil.getCenterPoint(new Rectangle(targetPoint, JBUI.emptySize()), balloonSize); return new Point(targetPoint.x, center.y); } } @Override protected Insets getTitleInsets(int normalInset, int pointerLength) { //noinspection UseDPIAwareInsets return new Insets(JBUIScale.scale(normalInset), pointerLength, JBUIScale.scale(normalInset), JBUIScale.scale(normalInset)); } @Override protected Shape getPointingShape(final Rectangle bounds, Point pointTarget, final BalloonImpl balloon) { pointTarget = new Point(Math.min(bounds.x, pointTarget.y), pointTarget.y); final Shaper shaper = new Shaper(balloon, bounds, pointTarget, SwingConstants.LEFT); shaper.line(balloon.getPointerLength(this), -balloon.getPointerWidth(this) / 2).toTopCurve().roundUpRight().toRightCurve() .roundRightDown() .toBottomCurve().roundLeftDown().toLeftCurve().roundLeftUp() .lineTo(shaper.getCurrent().x, pointTarget.y + balloon.getPointerWidth(this) / 2).lineTo(pointTarget.x, pointTarget.y).close(); return shaper.getShape(); } } private static class AtLeft extends AbstractPosition { @NotNull @Override public Point getShiftedPoint(@NotNull Point targetPoint, int shift) { return new Point(targetPoint.x - shift, targetPoint.y); } @NotNull @Override public Point getShiftedPoint(@NotNull Point targetPoint, @NotNull Insets shift) { return getShiftedPoint(targetPoint, -shift.left); } @Override int getChangeShift(AbstractPosition original, int xShift, int yShift) { return original == AT_RIGHT ? -xShift : 0; } @Override protected int getDistanceToTarget(Rectangle rectangle, Point targetPoint) { return targetPoint.x - (int)rectangle.getMaxX(); } @Override protected Rectangle getPointlessContentRec(Rectangle bounds, int pointerLength) { return new Rectangle(bounds.x, bounds.y, bounds.width - pointerLength, bounds.height); } @Override EmptyBorder createBorder(final BalloonImpl balloon) { Insets insets = balloon.getInsetsCopy(); insets.right += balloon.getPointerLength(this); return new EmptyBorder(insets); } @Override void setRecToRelativePosition(Rectangle rec, Point targetPoint) { rec.setLocation(targetPoint.x - rec.width, targetPoint.y - rec.height / 2); } @Override Point getLocation(final Dimension containerSize, final Point targetPoint, final Dimension balloonSize, int distance) { if (distance > 0) { return new Point(targetPoint.x - balloonSize.width, targetPoint.y - distance); } else { final Point center = StartupUiUtil.getCenterPoint(new Rectangle(targetPoint, JBUI.emptySize()), balloonSize); return new Point(targetPoint.x - balloonSize.width, center.y); } } @Override protected Insets getTitleInsets(int normalInset, int pointerLength) { //noinspection UseDPIAwareInsets return new Insets(JBUIScale.scale(normalInset), pointerLength, JBUIScale.scale(normalInset), JBUIScale.scale(normalInset)); } @Override protected Shape getPointingShape(final Rectangle bounds, Point pointTarget, final BalloonImpl balloon) { pointTarget = new Point(Math.max((int) bounds.getMaxX(), pointTarget.x), pointTarget.y); final Shaper shaper = new Shaper(balloon, bounds, pointTarget, SwingConstants.RIGHT); shaper .lineTo((int)bounds.getMaxX() - shaper.getTargetDelta(SwingConstants.RIGHT) - JBUIScale.scale(1), pointTarget.y + balloon.getPointerWidth(this) / 2); shaper.toBottomCurve().roundLeftDown().toLeftCurve().roundLeftUp().toTopCurve().roundUpRight().toRightCurve().roundRightDown() .lineTo(shaper.getCurrent().x, pointTarget.y - balloon.getPointerWidth(this) / 2).lineTo(pointTarget.x, pointTarget.y).close(); return shaper.getShape(); } } public interface ActionProvider { @NotNull List<ActionButton> createActions(); void layout(@NotNull Rectangle bounds); } public class ActionButton extends HwFacadeNonOpaquePanel implements IdeGlassPane.TopComponent { private final Icon myIcon; private final Icon myHoverIcon; private final Consumer<? super MouseEvent> myListener; protected final BaseButtonBehavior myButton; public ActionButton(@NotNull Icon icon, @Nullable Icon hoverIcon, @Nullable String hint, @NotNull Consumer<? super MouseEvent> listener) { myIcon = icon; myHoverIcon = hoverIcon; myListener = listener; setToolTipText(hint); myButton = new BaseButtonBehavior(this, TimedDeadzone.NULL) { @Override protected void execute(MouseEvent e) { myListener.consume(e); } }; } @Override public Dimension getPreferredSize() { return new Dimension(myIcon.getIconWidth(), myIcon.getIconHeight()); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); if (hasPaint()) { paintIcon(g, myHoverIcon != null && myButton.isHovered() ? myHoverIcon : myIcon); } } boolean hasPaint() { return getWidth() > 0 && myLastMoveWasInsideBalloon; } protected void paintIcon(@NotNull Graphics g, @NotNull Icon icon) { icon.paintIcon(this, g, 0, 0); } @Override public boolean canBePreprocessed(@NotNull MouseEvent e) { return false; } } private class CloseButton extends ActionButton { private CloseButton(@NotNull Consumer<? super MouseEvent> listener) { super(getCloseButton(), null, null, listener); setVisible(myEnableButtons); } @Override protected void paintIcon(@NotNull Graphics g, @NotNull Icon icon) { if (myEnableButtons) { final boolean pressed = myButton.isPressedByMouse(); icon.paintIcon(this, g, pressed ? JBUIScale.scale(1) : 0, pressed ? JBUIScale.scale(1) : 0); } } } private class MyComponent extends HwFacadeJPanel implements ComponentWithMnemonics { private BufferedImage myImage; private float myAlpha; private final BalloonImpl myBalloon; private final JComponent myContent; private ShadowBorderPainter.Shadow myShadow; private MyComponent(JComponent content, BalloonImpl balloon, EmptyBorder shapeBorder) { setOpaque(false); setLayout(null); putClientProperty(UIUtil.TEXT_COPY_ROOT, Boolean.TRUE); myBalloon = balloon; // When a screen reader is active, TAB/Shift-TAB should allow moving the focus // outside the balloon in the event the balloon acquired the focus. if (!ScreenReader.isActive()) { setFocusCycleRoot(true); } putClientProperty(Balloon.KEY, BalloonImpl.this); myContent = new JPanel(new BorderLayout(2, 2)); Wrapper contentWrapper = new Wrapper(content); if (myTitle != null) { myTitleLabel = new JLabel(myTitle, SwingConstants.CENTER); myTitleLabel.setForeground(UIUtil.getListBackground()); myTitleLabel.setBorder(JBUI.Borders.empty(0, 4)); myContent.add(myTitleLabel, BorderLayout.NORTH); contentWrapper.setBorder(JBUI.Borders.empty(1)); } myContent.add(contentWrapper, BorderLayout.CENTER); myContent.setBorder(shapeBorder); myContent.setOpaque(false); add(myContent); setFocusTraversalPolicyProvider(true); setFocusTraversalPolicy(new FocusTraversalPolicy() { @Override public Component getComponentAfter(Container aContainer, Component aComponent) { return WeakFocusStackManager.getInstance().getLastFocusedOutside(MyComponent.this); } @Override public Component getComponentBefore(Container aContainer, Component aComponent) { return WeakFocusStackManager.getInstance().getLastFocusedOutside(MyComponent.this); } @Override public Component getFirstComponent(Container aContainer) { return WeakFocusStackManager.getInstance().getLastFocusedOutside(MyComponent.this); } @Override public Component getLastComponent(Container aContainer) { return WeakFocusStackManager.getInstance().getLastFocusedOutside(MyComponent.this); } @Override public Component getDefaultComponent(Container aContainer) { return WeakFocusStackManager.getInstance().getLastFocusedOutside(MyComponent.this); } }); } @NotNull Rectangle getContentBounds() { Rectangle bounds = getBounds(); JBInsets.removeFrom(bounds, getInsets()); return bounds; } public void clear() { myImage = null; myAlpha = -1; } @Override public void doLayout() { Rectangle bounds = new Rectangle(getWidth(), getHeight()); JBInsets.removeFrom(bounds, getInsets()); myContent.setBounds(bounds); } @Override public Dimension getPreferredSize() { return addInsets(myContent.getPreferredSize()); } @Override public Dimension getMinimumSize() { return addInsets(myContent.getMinimumSize()); } private Dimension addInsets(Dimension size) { JBInsets.addTo(size, getInsets()); return size; } @Override protected void paintChildren(Graphics g) { if (myImage == null || myAlpha == -1) { super.paintChildren(g); } } private void paintChildrenImpl(Graphics g) { // Paint to an image without alpha to preserve fonts subpixel antialiasing BufferedImage image = ImageUtil.createImage(g, getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);//new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB); useSafely(image.createGraphics(), imageGraphics -> { //noinspection UseJBColor imageGraphics.setPaint(new Color(myFillColor.getRGB())); // create a copy to remove alpha imageGraphics.fillRect(0, 0, getWidth(), getHeight()); super.paintChildren(imageGraphics); }); Graphics2D g2d = (Graphics2D)g.create(); try { if (JreHiDpiUtil.isJreHiDPI(g2d)) { float s = 1 / JBUIScale.sysScale(g2d); g2d.scale(s, s); } StartupUiUtil.drawImage(g2d, makeColorTransparent(image, myFillColor), 0, 0, null); } finally { g2d.dispose(); } } private Image makeColorTransparent(Image image, Color color) { final int markerRGB = color.getRGB() | 0xFF000000; ImageFilter filter = new RGBImageFilter() { @Override public int filterRGB(int x, int y, int rgb) { if ((rgb | 0xFF000000) == markerRGB) { return 0x00FFFFFF & rgb; // set alpha to 0 } return rgb; } }; return ImageUtil.filter(image, filter); } @Override protected void paintComponent(final Graphics g) { super.paintComponent(g); final Graphics2D g2d = (Graphics2D)g; Point pointTarget = SwingUtilities.convertPoint(myLayeredPane, myBalloon.myTargetPoint, this); Rectangle shapeBounds = myContent.getBounds(); int shadowSize = myBalloon.getShadowBorderSize(); if (shadowSize > 0 && myShadow == null && myShadowBorderProvider == null) { initComponentImage(pointTarget, shapeBounds); myShadow = ShadowBorderPainter.createShadow(myImage, 0, 0, false, shadowSize / 2); } if (myImage == null && myAlpha != -1) { initComponentImage(pointTarget, shapeBounds); } if (myImage != null && myAlpha != -1) { g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, myAlpha)); } if (myShadowBorderProvider != null) { myShadowBorderProvider.paintShadow(this, g); } if (myImage != null && myAlpha != -1) { paintShadow(g); StartupUiUtil.drawImage(g2d, myImage, 0, 0, null); } else { paintShadow(g); myBalloon.myPosition.paintComponent(myBalloon, shapeBounds, (Graphics2D)g, pointTarget); } } private void paintShadow(Graphics graphics) { if (myShadow != null) { Graphics2D g2d = (Graphics2D)graphics; try { if (JreHiDpiUtil.isJreHiDPI(g2d)) { g2d = (Graphics2D)graphics.create(); float s = 1 / JBUIScale.sysScale(this); g2d.scale(s, s); } StartupUiUtil.drawImage(g2d, myShadow.getImage(), myShadow.getX(), myShadow.getY(), null); } finally { if (g2d != graphics) g2d.dispose(); } } } @Override public boolean contains(int x, int y) { Point pointTarget = SwingUtilities.convertPoint(myLayeredPane, myBalloon.myTargetPoint, this); Rectangle bounds = myContent.getBounds(); Shape shape; if (myShowPointer) { shape = myBalloon.myPosition.getPointingShape(bounds, pointTarget, myBalloon); } else { shape = getPointlessShape(myBalloon, bounds); } return shape.contains(x, y); } private void initComponentImage(Point pointTarget, Rectangle shapeBounds) { if (myImage != null) return; myImage = UIUtil.createImage(myComp, getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB); useSafely(myImage.getGraphics(), imageGraphics -> { myBalloon.myPosition.paintComponent(myBalloon, shapeBounds, imageGraphics, pointTarget); paintChildrenImpl(imageGraphics); }); } @Override public void removeNotify() { super.removeNotify(); if (!ScreenUtil.isStandardAddRemoveNotify(this)) { return; } final List<ActionButton> buttons = myActionButtons; myActionButtons = null; if (buttons != null) { //noinspection SSBasedInspection SwingUtilities.invokeLater(() -> { for (ActionButton button : buttons) { disposeButton(button); } }); } } public void setAlpha(float alpha) { myAlpha = alpha; paintImmediately(0, 0, getWidth(), getHeight()); } void _setBounds(@NotNull Rectangle bounds) { Rectangle currentBounds = getBounds(); if (!currentBounds.equals(bounds)) { invalidateShadowImage(); } setBounds(bounds); if (getParent() != null) { if (myActionButtons == null) { myActionButtons = myActionProvider.createActions(); } for (ActionButton button : myActionButtons) { if (button.getParent() == null) { myLayeredPane.add(button); myLayeredPane.setLayer(button, JLayeredPane.DRAG_LAYER); } } } if (isVisible()) { Rectangle lpBounds = SwingUtilities.convertRectangle(getParent(), bounds, myLayeredPane); lpBounds = myPosition .getPointlessContentRec(lpBounds, myBalloon.myShadowBorderProvider == null ? myBalloon.getPointerLength(myPosition) : 0); myActionProvider.layout(lpBounds); } if (isVisible()) { revalidate(); repaint(); } } private void invalidateShadowImage() { myImage = null; myShadow = null; } void repaintButton() { if (myActionButtons != null) { for (ActionButton button : myActionButtons) { button.repaint(); } } } } private static class Shaper { private final GeneralPath myPath = new GeneralPath(); Rectangle myBounds; @JdkConstants.TabPlacement private final int myTargetSide; private final BalloonImpl myBalloon; Shaper(BalloonImpl balloon, Rectangle bounds, Point targetPoint, @JdkConstants.TabPlacement int targetSide) { myBalloon = balloon; myBounds = bounds; myTargetSide = targetSide; start(targetPoint); } private void start(Point start) { myPath.moveTo(start.x, start.y); } @NotNull Shaper roundUpRight() { myPath.quadTo(getCurrent().x, getCurrent().y - myBalloon.getArc(), getCurrent().x + myBalloon.getArc(), getCurrent().y - myBalloon.getArc()); return this; } @NotNull Shaper roundRightDown() { myPath.quadTo(getCurrent().x + myBalloon.getArc(), getCurrent().y, getCurrent().x + myBalloon.getArc(), getCurrent().y + myBalloon.getArc()); return this; } @NotNull Shaper roundLeftUp() { myPath.quadTo(getCurrent().x - myBalloon.getArc(), getCurrent().y, getCurrent().x - myBalloon.getArc(), getCurrent().y - myBalloon.getArc()); return this; } @NotNull Shaper roundLeftDown() { myPath.quadTo(getCurrent().x, getCurrent().y + myBalloon.getArc(), getCurrent().x - myBalloon.getArc(), getCurrent().y + myBalloon.getArc()); return this; } public Point getCurrent() { return new Point((int)myPath.getCurrentPoint().getX(), (int)myPath.getCurrentPoint().getY()); } public Shaper line(final int deltaX, final int deltaY) { myPath.lineTo(getCurrent().x + deltaX, getCurrent().y + deltaY); return this; } public Shaper lineTo(final int x, final int y) { myPath.lineTo(x, y); return this; } private int getTargetDelta(@JdkConstants.TabPlacement int effectiveSide) { return effectiveSide == myTargetSide ? myBalloon.getPointerLength(myBalloon.myPosition) : 0; } @NotNull Shaper toRightCurve() { myPath.lineTo((int)myBounds.getMaxX() - myBalloon.getArc() - getTargetDelta(SwingConstants.RIGHT) - JBUIScale.scale(1), getCurrent().y); return this; } @NotNull Shaper toBottomCurve() { myPath.lineTo(getCurrent().x, (int)myBounds.getMaxY() - myBalloon.getArc() - getTargetDelta(SwingConstants.BOTTOM) - JBUIScale.scale(1)); return this; } @NotNull Shaper toLeftCurve() { myPath.lineTo((int)myBounds.getX() + myBalloon.getArc() + getTargetDelta(SwingConstants.LEFT), getCurrent().y); return this; } @NotNull Shaper toTopCurve() { myPath.lineTo(getCurrent().x, (int)myBounds.getY() + myBalloon.getArc() + getTargetDelta(SwingConstants.TOP)); return this; } public void close() { myPath.closePath(); } public Shape getShape() { return myPath; } } @Override public boolean wasFadedIn() { return myFadedIn; } @Override public boolean wasFadedOut() { return myFadedOut; } @Override public boolean isDisposed() { return myDisposed; } @Override public void setTitle(String title) { myTitleLabel.setText(title); } public void setActionProvider(@NotNull ActionProvider actionProvider) { myActionProvider = actionProvider; } @Override public RelativePoint getShowingPoint() { Point p = myPosition.getShiftedPoint(myTargetPoint, myCalloutShift * -1); return new RelativePoint(myLayeredPane, p); } @Override public void setAnimationEnabled(boolean enabled) { myAnimationEnabled = enabled; } public boolean isAnimationEnabled() { return myAnimationEnabled && myAnimationCycle > 0 && !RemoteDesktopService.isRemoteSession(); } public boolean isBlockClicks() { return myBlockClicks; } // Returns true if balloon is 'prepared' to process clicks by itself. // For example balloon would ignore clicks and won't hide explicitly or would trigger some actions/navigation public boolean isClickProcessor() { return myClickHandler != null || !myCloseOnClick || isBlockClicks(); } }
package com.googlecode.jsu.util; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.List; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.ofbiz.core.entity.GenericEntityException; import org.ofbiz.core.entity.GenericValue; import com.atlassian.core.user.GroupUtils; import com.atlassian.core.user.UserUtils; import com.atlassian.jira.ComponentManager; import com.atlassian.jira.ManagerFactory; import com.atlassian.jira.bc.project.component.ProjectComponent; import com.atlassian.jira.bc.project.component.ProjectComponentManager; import com.atlassian.jira.config.properties.APKeys; import com.atlassian.jira.config.properties.ApplicationProperties; import com.atlassian.jira.issue.Issue; import com.atlassian.jira.issue.IssueConstant; import com.atlassian.jira.issue.IssueFieldConstants; import com.atlassian.jira.issue.IssueRelationConstants; import com.atlassian.jira.issue.ModifiedValue; import com.atlassian.jira.issue.MutableIssue; import com.atlassian.jira.issue.customfields.CustomFieldType; import com.atlassian.jira.issue.customfields.view.CustomFieldParams; import com.atlassian.jira.issue.customfields.view.CustomFieldParamsImpl; import com.atlassian.jira.issue.fields.CustomField; import com.atlassian.jira.issue.fields.Field; import com.atlassian.jira.issue.fields.FieldManager; import com.atlassian.jira.issue.fields.layout.field.FieldLayoutItem; import com.atlassian.jira.issue.fields.layout.field.FieldLayoutStorageException; import com.atlassian.jira.issue.fields.screen.FieldScreen; import com.atlassian.jira.issue.resolution.Resolution; import com.atlassian.jira.issue.status.Status; import com.atlassian.jira.issue.util.IssueChangeHolder; import com.atlassian.jira.issue.worklog.WorkRatio; import com.atlassian.jira.project.version.Version; import com.atlassian.jira.project.version.VersionManager; import com.atlassian.jira.workflow.WorkflowActionsBean; import com.opensymphony.user.Entity; import com.opensymphony.user.EntityNotFoundException; import com.opensymphony.user.Group; import com.opensymphony.user.User; import com.opensymphony.workflow.loader.ActionDescriptor; /** * @author Gustavo Martin. * * This utils class exposes common methods to custom workflow objects. * */ public class WorkflowUtils { public static final String SPLITTER = "@@"; private static final WorkflowActionsBean workflowActionsBean = new WorkflowActionsBean(); public static final String CASCADING_SELECT_TYPE = "com.atlassian.jira.plugin.system.customfieldtypes:cascadingselect"; private static final Logger log = Logger.getLogger(WorkflowUtils.class); /** * @param key * @return a String with the field name from given key. */ public static String getFieldNameFromKey(String key) { return getFieldFromKey(key).getName(); } /** * @param key * @return a Field object from given key. (Field or Custom Field). */ public static Field getFieldFromKey(String key) { FieldManager fieldManager = ManagerFactory.getFieldManager(); Field field; if (fieldManager.isCustomField(key)) { field = fieldManager.getCustomField(key); } else { field = fieldManager.getField(key); } if (field == null) { throw new IllegalArgumentException("Unable to find field '" + key + "'"); } return field; } /** * @param issue * an issue object. * @param field * a field object. (May be a Custom Field) * @return an Object * * It returns the value of a field within issue object. May be a Collection, * a List, a Strong, or any FildType within JIRA. * */ public static Object getFieldValueFromIssue(Issue issue, Field field) { FieldManager fldManager = ManagerFactory.getFieldManager(); Object retVal = null; try { if (fldManager.isCustomField(field)) { // Return the CustomField value. It could be any object. CustomField customField = (CustomField) field; Object value = issue.getCustomFieldValue(customField); // TODO Maybe for cascade we have to create separate manager if (CASCADING_SELECT_TYPE.equals(customField.getCustomFieldType().getKey())) { CustomFieldParams params = (CustomFieldParams) value; if (params != null) { Object parent = params.getFirstValueForNullKey(); Object child = params.getFirstValueForKey("1"); if (parent != null) { retVal = child.toString(); } } } else { retVal = value; } log.debug( "Get field value [object=" + retVal + ";class=" + ((retVal != null) ? retVal.getClass() : "") + "]" ); } else { String fieldId = field.getId(); Collection<?> retCollection = null; // Special treatment of fields. if (fieldId.equals(IssueFieldConstants.ATTACHMENT)) { // return a collection with the attachments associated to given issue. retCollection = issue.getAttachments(); if (retCollection != null && !retCollection.isEmpty()) { retVal = retCollection; } } else if (fieldId.equals(IssueFieldConstants.AFFECTED_VERSIONS)) { retCollection = issue.getAffectedVersions(); if (retCollection != null && !retCollection.isEmpty()) { retVal = retCollection; } } else if (fieldId.equals(IssueFieldConstants.COMMENT)) { // return a list with the comments of a given issue. try { retCollection = ManagerFactory.getIssueManager().getEntitiesByIssueObject( IssueRelationConstants.COMMENTS, issue ); if (retCollection != null && !retCollection.isEmpty()) { retVal = retCollection; } } catch (GenericEntityException e) { retVal = null; } } else if (fieldId.equals(IssueFieldConstants.COMPONENTS)) { retCollection = issue.getComponents(); if (retCollection != null && !retCollection.isEmpty()) { retVal = retCollection; } } else if (fieldId.equals(IssueFieldConstants.FIX_FOR_VERSIONS)) { retCollection = issue.getFixVersions(); if (retCollection != null && !retCollection.isEmpty()) { retVal = retCollection; } } else if (fieldId.equals(IssueFieldConstants.THUMBNAIL)) { // Not implemented, yet. } else if (fieldId.equals(IssueFieldConstants.ISSUE_TYPE)) { retVal = issue.getIssueTypeObject(); } else if (fieldId.equals(IssueFieldConstants.TIMETRACKING)) { // Not implemented, yet. } else if (fieldId.equals(IssueFieldConstants.ISSUE_LINKS)) { retVal = ComponentManager.getInstance().getIssueLinkManager().getIssueLinks(issue.getId()); } else if (fieldId.equals(IssueFieldConstants.WORKRATIO)) { retVal = String.valueOf(WorkRatio.getWorkRatio(issue)); } else if (fieldId.equals(IssueFieldConstants.ISSUE_KEY)) { retVal = issue.getKey(); } else if (fieldId.equals(IssueFieldConstants.SUBTASKS)) { retCollection = issue.getSubTaskObjects(); if (retCollection != null && !retCollection.isEmpty()) { retVal = retCollection; } } else if (fieldId.equals(IssueFieldConstants.PRIORITY)) { retVal = issue.getPriorityObject(); } else if (fieldId.equals(IssueFieldConstants.RESOLUTION)) { retVal = issue.getResolutionObject(); } else if (fieldId.equals(IssueFieldConstants.STATUS)) { retVal = issue.getStatusObject(); } else if (fieldId.equals(IssueFieldConstants.PROJECT)) { retVal = issue.getProjectObject(); } else if (fieldId.equals(IssueFieldConstants.SECURITY)) { retVal = issue.getSecurityLevel(); } else if (fieldId.equals(IssueFieldConstants.TIME_ESTIMATE)) { retVal = issue.getEstimate(); } else if (fieldId.equals(IssueFieldConstants.TIME_SPENT)) { retVal = issue.getTimeSpent(); } else if (fieldId.equals(IssueFieldConstants.ASSIGNEE)) { retVal = issue.getAssignee(); } else if (fieldId.equals(IssueFieldConstants.REPORTER)) { retVal = issue.getReporter(); } else if (fieldId.equals(IssueFieldConstants.DESCRIPTION)) { retVal = issue.getDescription(); } else if (fieldId.equals(IssueFieldConstants.ENVIRONMENT)) { retVal = issue.getEnvironment(); } else if (fieldId.equals(IssueFieldConstants.SUMMARY)) { retVal = issue.getSummary(); } else if (fieldId.equals(IssueFieldConstants.DUE_DATE)) { retVal = issue.getDueDate(); } else if (fieldId.equals(IssueFieldConstants.UPDATED)) { retVal = issue.getUpdated(); } else if (fieldId.equals(IssueFieldConstants.CREATED)) { retVal = issue.getCreated(); } else { log.warn("Issue field \"" + fieldId + "\" is not supported."); GenericValue gvIssue = issue.getGenericValue(); if (gvIssue != null) { retVal = gvIssue.get(fieldId); } } } } catch (NullPointerException e) { retVal = null; log.error("Unable to get field \"" + field.getId() + "\" value", e); } return retVal; } /** * Sets specified value to the field for the issue. * * @param issue * @param field * @param value */ public static void setFieldValue(MutableIssue issue, Field field, Object value, IssueChangeHolder changeHolder) { FieldManager fldManager = ManagerFactory.getFieldManager(); if (fldManager.isCustomField(field)) { CustomField customField = (CustomField) field; Object oldValue = issue.getCustomFieldValue(customField); FieldLayoutItem fieldLayoutItem; CustomFieldType cfType = customField.getCustomFieldType(); if (log.isDebugEnabled()) { log.debug( String.format( "Set custom field value " + "[field=%s,type=%s,oldValue=%s,newValueClass=%s,newValue=%s]", customField, cfType, oldValue, (value != null) ? value.getClass().getName() : "null", value ) ); } try { fieldLayoutItem = CommonPluginUtils.getFieldLayoutItem(issue, field); } catch (FieldLayoutStorageException e) { log.error("Unable to get field layout item", e); throw new IllegalStateException(e); } Object newValue = value; if (value instanceof IssueConstant) { newValue = ((IssueConstant) value).getName(); } else if (value instanceof Entity) { newValue = ((Entity) value).getName(); } if (newValue instanceof String) { //convert from string to Object CustomFieldParams fieldParams = new CustomFieldParamsImpl(customField, newValue); newValue = cfType.getValueFromCustomFieldParams(fieldParams); } else if (newValue instanceof Collection<?>) { //convert from string to Object CustomFieldParams fieldParams = new CustomFieldParamsImpl( customField, StringUtils.join((Collection<?>) newValue, ",") ); newValue = cfType.getValueFromCustomFieldParams(fieldParams); } if (log.isDebugEnabled()) { log.debug("Got new value [class=" + ((newValue != null) ? newValue.getClass().getName() : "null") + ",value=" + newValue + "]" ); } // Updating internal custom field value issue.setCustomFieldValue(customField, newValue); customField.updateValue( fieldLayoutItem, issue, new ModifiedValue(oldValue, newValue), changeHolder ); if (log.isDebugEnabled()) { log.debug( "Issue [" + issue + "] got modfied fields - [" + issue.getModifiedFields() + "]" ); } // Not new if (issue.getKey() != null) { // Remove duplicated issue update if (issue.getModifiedFields().containsKey(field.getId())) { issue.getModifiedFields().remove(field.getId()); } } } else { final String fieldId = field.getId(); // Special treatment of fields. if (fieldId.equals(IssueFieldConstants.ATTACHMENT)) { throw new UnsupportedOperationException("Not implemented"); // // return a collection with the attachments associated to given issue. // retCollection = (Collection)issue.getExternalFieldValue(fieldId); // if(retCollection==null || retCollection.isEmpty()){ // isEmpty = true; // }else{ // retVal = retCollection; } else if (fieldId.equals(IssueFieldConstants.AFFECTED_VERSIONS)) { if (value == null) { issue.setAffectedVersions(Collections.EMPTY_SET); } else if (value instanceof String) { VersionManager versionManager = ComponentManager.getInstance().getVersionManager(); Version v = versionManager.getVersion(issue.getProjectObject().getId(), (String) value); if (v != null) { issue.setAffectedVersions(Arrays.asList(v)); } else { throw new IllegalArgumentException("Wrong affected version value"); } } else if (value instanceof Version) { issue.setAffectedVersions(Arrays.asList((Version) value)); } else if (value instanceof Collection) { issue.setAffectedVersions((Collection) value); } else { throw new IllegalArgumentException("Wrong affected version value"); } } else if (fieldId.equals(IssueFieldConstants.COMMENT)) { throw new UnsupportedOperationException("Not implemented"); // // return a list with the comments of a given issue. // try { // retCollection = ManagerFactory.getIssueManager().getEntitiesByIssue(IssueRelationConstants.COMMENTS, issue.getGenericValue()); // if(retCollection==null || retCollection.isEmpty()){ // isEmpty = true; // }else{ // retVal = retCollection; // } catch (GenericEntityException e) { // retVal = null; } else if (fieldId.equals(IssueFieldConstants.COMPONENTS)) { if (value == null) { issue.setComponents(Collections.EMPTY_SET); } else if (value instanceof String) { ProjectComponentManager componentManager = ComponentManager.getInstance().getProjectComponentManager(); ProjectComponent v = componentManager.findByComponentName( issue.getProjectObject().getId(), (String) value ); if (v != null) { issue.setComponents(Arrays.asList(v.getGenericValue())); } } else if (value instanceof GenericValue) { issue.setComponents(Arrays.asList((GenericValue) value)); } else if (value instanceof Collection) { issue.setComponents((Collection) value); } else { throw new IllegalArgumentException("Wrong component value"); } } else if (fieldId.equals(IssueFieldConstants.FIX_FOR_VERSIONS)) { if (value == null) { issue.setFixVersions(Collections.EMPTY_SET); } else if (value instanceof String) { VersionManager versionManager = ComponentManager.getInstance().getVersionManager(); Version v = versionManager.getVersion(issue.getProjectObject().getId(), (String) value); if (v != null) { issue.setFixVersions(Arrays.asList(v)); } } else if (value instanceof Version) { issue.setFixVersions(Arrays.asList((Version) value)); } else if (value instanceof Collection) { issue.setFixVersions((Collection) value); } else { throw new IllegalArgumentException("Wrong fix version value"); } } else if (fieldId.equals(IssueFieldConstants.THUMBNAIL)) { throw new UnsupportedOperationException("Not implemented"); // // Not implemented, yet. // isEmpty = true; } else if (fieldId.equals(IssueFieldConstants.ISSUE_TYPE)) { throw new UnsupportedOperationException("Not implemented"); // retVal = issue.getIssueTypeObject(); } else if (fieldId.equals(IssueFieldConstants.TIMETRACKING)) { throw new UnsupportedOperationException("Not implemented"); // // Not implemented, yet. // isEmpty = true; } else if (fieldId.equals(IssueFieldConstants.ISSUE_LINKS)) { throw new UnsupportedOperationException("Not implemented"); // retVal = ComponentManager.getInstance().getIssueLinkManager().getIssueLinks(issue.getId()); } else if (fieldId.equals(IssueFieldConstants.WORKRATIO)) { throw new UnsupportedOperationException("Not implemented"); // retVal = String.valueOf(WorkRatio.getWorkRatio(issue)); } else if (fieldId.equals(IssueFieldConstants.ISSUE_KEY)) { throw new UnsupportedOperationException("Not implemented"); // retVal = issue.getKey(); } else if (fieldId.equals(IssueFieldConstants.SUBTASKS)) { throw new UnsupportedOperationException("Not implemented"); // retCollection = issue.getSubTasks(); // if(retCollection==null || retCollection.isEmpty()){ // isEmpty = true; // }else{ // retVal = retCollection; } else if (fieldId.equals(IssueFieldConstants.PRIORITY)) { if (value == null) { issue.setPriority(null); } else { throw new UnsupportedOperationException("Not implemented"); } } else if (fieldId.equals(IssueFieldConstants.RESOLUTION)) { if (value == null) { issue.setResolution(null); } else if (value instanceof GenericValue) { issue.setResolution((GenericValue) value); } else if (value instanceof Resolution) { issue.setResolutionId(((Resolution) value).getId()); } else if (value instanceof String) { Collection<Resolution> resolutions = ManagerFactory.getConstantsManager().getResolutionObjects(); Resolution resolution = null; String s = ((String) value).trim(); for (Resolution r : resolutions) { if (r.getName().equalsIgnoreCase(s)) { resolution = r; break; } } if (resolution != null) { issue.setResolutionId(resolution.getId()); } else { throw new IllegalArgumentException("Unable to find resolution with name \"" + value + "\""); } } else { throw new UnsupportedOperationException("Not implemented"); } } else if (fieldId.equals(IssueFieldConstants.STATUS)) { if (value == null) { issue.setStatus(null); } else if (value instanceof GenericValue) { issue.setStatus((GenericValue) value); } else if (value instanceof Status) { issue.setStatusId(((Status) value).getId()); } else if (value instanceof String) { Status status = ManagerFactory.getConstantsManager().getStatusByName((String) value); if (status != null) { issue.setStatusId(status.getId()); } else { throw new IllegalArgumentException("Unable to find status with name \"" + value + "\""); } } else { throw new UnsupportedOperationException("Not implemented"); } } else if (fieldId.equals(IssueFieldConstants.PROJECT)) { if (value == null) { issue.setProject(null); } else { throw new UnsupportedOperationException("Not implemented"); } } else if (fieldId.equals(IssueFieldConstants.SECURITY)) { if (value == null) { issue.setSecurityLevel(null); } else { throw new UnsupportedOperationException("Not implemented"); } } else if (fieldId.equals(IssueFieldConstants.ASSIGNEE)) { if (value == null) { issue.setAssignee(null); } else if (value instanceof User) { issue.setAssignee((User) value); } else if (value instanceof String) { try { User user = UserUtils.getUser((String) value); if (null != user) { issue.setAssignee(user); } } catch (EntityNotFoundException e) { throw new IllegalArgumentException(String.format("User \"%s\" not found", value)); } } } else if (fieldId.equals(IssueFieldConstants.DUE_DATE)) { if (value == null) { issue.setDueDate(null); } if (value instanceof Timestamp) { issue.setDueDate((Timestamp) value); } else if (value instanceof String) { ApplicationProperties properties = ManagerFactory.getApplicationProperties(); SimpleDateFormat formatter = new SimpleDateFormat( properties.getDefaultString(APKeys.JIRA_DATE_TIME_PICKER_JAVA_FORMAT) ); try { Date date = formatter.parse((String) value); if (date != null) { issue.setDueDate(new Timestamp(date.getTime())); } else { issue.setDueDate(null); } } catch (ParseException e) { throw new IllegalArgumentException("Wrong date format exception for \"" + value + "\""); } } } else if (fieldId.equals(IssueFieldConstants.REPORTER)) { if (value == null) { issue.setReporter(null); } else if (value instanceof User) { issue.setReporter((User) value); } else if (value instanceof String) { try { User user = UserUtils.getUser((String) value); if (user != null) { issue.setReporter(user); } } catch (EntityNotFoundException e) { throw new IllegalArgumentException(String.format("User \"%s\" not found", value)); } } } else { log.error("Issue field \"" + fieldId + "\" is not supported for setting."); } } } /** * Method sets value for issue field. Field was defined as string * * @param issue * Muttable issue for changing * @param fieldKey * Field name * @param value * Value for setting */ public static void setFieldValue( MutableIssue issue, String fieldKey, Object value, IssueChangeHolder changeHolder ) { final Field field = (Field) WorkflowUtils.getFieldFromKey(fieldKey); setFieldValue(issue, field, value, changeHolder); } /** * @param strGroups * @param splitter * @return a List of Group * * Get Groups from a string. * */ public static List<Group> getGroups(String strGroups, String splitter) { String[] groups = strGroups.split("\\Q" + splitter + "\\E"); List<Group> groupList = new ArrayList<Group>(groups.length); for (String s : groups) { Group group = GroupUtils.getGroup(s); groupList.add(group); } return groupList; } /** * @param group * @param splitter * @return a String with the groups selected. * * Get Groups as String. * */ public static String getStringGroup(Collection<Group> groups, String splitter) { StringBuilder sb = new StringBuilder(); for (Group g : groups) { sb.append(g.getName()).append(splitter); } return sb.toString(); } /** * @param strFields * @param splitter * @return a List of Field * * Get Fields from a string. * */ public static List<Field> getFields(String strFields, String splitter) { String[] fields = strFields.split("\\Q" + splitter + "\\E"); List<Field> fieldList = new ArrayList<Field>(fields.length); for (String s : fields) { final Field field = ManagerFactory.getFieldManager().getField(s); if (field != null) { fieldList.add(field); } } return CommonPluginUtils.sortFields(fieldList); } /** * @param fields * @param splitter * @return a String with the fields selected. * * Get Fields as String. * */ public static String getStringField(Collection<Field> fields, String splitter) { StringBuilder sb = new StringBuilder(); for (Field f : fields) { sb.append(f.getId()).append(splitter); } return sb.toString(); } /** * @param actionDescriptor * @return the FieldScreen of the transition. Or null, if the transition * hasn't a screen asociated. * * It obtains the fieldscreen for a transition, if it have one. * */ public static FieldScreen getFieldScreen(ActionDescriptor actionDescriptor) { return workflowActionsBean.getFieldScreenForView(actionDescriptor); } }
package com.atinternet.tracker.avinsights; import android.text.TextUtils; import android.util.SparseIntArray; import com.atinternet.tracker.Event; import com.atinternet.tracker.Events; import com.atinternet.tracker.RequiredPropertiesDataObject; import com.atinternet.tracker.Utility; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class Media extends RequiredPropertiesDataObject { private final int MIN_HEARTBEAT_DURATION = 5; private final int MIN_BUFFER_HEARTBEAT_DURATION = 1; private final Events events; private ScheduledExecutorService heartbeatExecutor; private final SparseIntArray heartbeatDurations; private final SparseIntArray bufferHeartbeatDurations; private final AVRunnable heartbeatRunnable; private final AVRunnable bufferHeartbeatRunnable; private final AVRunnable rebufferHeartbeatRunnable; private String sessionId; private String previousEvent = ""; private int previousCursorPositionMillis = 0; private int currentCursorPositionMillis = 0; private long eventDurationMillis = 0; private int sessionDurationMillis = 0; private long startSessionTimeMillis = 0; private long bufferTimeMillis = 0; private boolean isPlaying = false; private boolean isPlaybackActivated = false; private double playbackSpeed = 1; private boolean autoHeartbeat; private boolean autoBufferHeartbeat; public Media(Events events) { super(); this.events = events; heartbeatDurations = new SparseIntArray(); bufferHeartbeatDurations = new SparseIntArray(); heartbeatRunnable = new HeartbeatRunnable(this); bufferHeartbeatRunnable = new BufferHeartbeatRunnable(this); rebufferHeartbeatRunnable = new RebufferHeartbeatRunnable(this); } public Media(Events events, int heartbeat, int bufferHeartbeat, String sessionId) { this(events, null, null, sessionId); } private static SparseIntArray createHeartbeatStages(int heartbeat) { SparseIntArray s = new SparseIntArray(); s.append(0, heartbeat); s.append(1, 10); s.append(5, 20); s.append(15, 30); s.append(30, 60); return s; } public Media(Events events, SparseIntArray heartbeat, SparseIntArray bufferHeartbeat, String sessionId) { this(events); setHeartbeat(createHeartbeatStages(MIN_HEARTBEAT_DURATION)); setBufferHeartbeat(createHeartbeatStages(MIN_BUFFER_HEARTBEAT_DURATION)); this.sessionId = TextUtils.isEmpty(sessionId) ? UUID.randomUUID().toString() : sessionId; } /*** * Get session * @return String */ public synchronized String getSessionId() { return sessionId; } /*** * Set heartbeat value * @param heartbeat SparseIntArray * @return current Media instance */ Media setHeartbeat(SparseIntArray heartbeat) { if (heartbeat == null) { return this; } int size = heartbeat.size(); if (size == 0) { return this; } autoHeartbeat = true; heartbeatDurations.clear(); for (int i = 0; i < size; i++) { heartbeatDurations.put(heartbeat.keyAt(i), Math.max(heartbeat.valueAt(i), MIN_HEARTBEAT_DURATION)); } if (heartbeatDurations.indexOfKey(0) < 0) { heartbeatDurations.put(0, MIN_HEARTBEAT_DURATION); } return this; } /*** * Set buffer heartbeat value * @param bufferHeartbeat SparseIntArray * @return current Media instance */ Media setBufferHeartbeat(SparseIntArray bufferHeartbeat) { if (bufferHeartbeat == null) { return this; } int size = bufferHeartbeat.size(); if (size == 0) { return this; } autoBufferHeartbeat = true; bufferHeartbeatDurations.clear(); for (int i = 0; i < size; i++) { bufferHeartbeatDurations.put(bufferHeartbeat.keyAt(i), Math.max(bufferHeartbeat.valueAt(i), MIN_BUFFER_HEARTBEAT_DURATION)); } if (bufferHeartbeatDurations.indexOfKey(0) < 0) { bufferHeartbeatDurations.put(0, MIN_BUFFER_HEARTBEAT_DURATION); } return this; } public void track(String event, Map<String, Object> options, Map<String, Object> extraProps) { if (options == null) { options = new HashMap<>(); } switch (event) { case "av.heartbeat": heartbeat(Utility.parseInt(options.get("av_position"), -1), extraProps); break; case "av.buffer.heartbeat": bufferHeartbeat(extraProps); break; case "av.rebuffer.heartbeat": rebufferHeartbeat(extraProps); break; case "av.play": play(Utility.parseInt(options.get("av_position"), 0), extraProps); break; case "av.buffer.start": bufferStart(Utility.parseInt(options.get("av_position"), 0), extraProps); break; case "av.start": playbackStart(Utility.parseInt(options.get("av_position"), 0), extraProps); break; case "av.resume": playbackResumed(Utility.parseInt(options.get("av_position"), 0), extraProps); break; case "av.pause": playbackPaused(Utility.parseInt(options.get("av_position"), 0), extraProps); break; case "av.stop": playbackStopped(Utility.parseInt(options.get("av_position"), 0), extraProps); break; case "av.backward": seekBackward(Utility.parseInt(options.get("av_previous_position"), 0), Utility.parseInt(options.get("av_position"), 0), extraProps); break; case "av.forward": seekForward(Utility.parseInt(options.get("av_previous_position"), 0), Utility.parseInt(options.get("av_position"), 0), extraProps); break; case "av.seek.start": seekStart(Utility.parseInt(options.get("av_previous_position"), 0), extraProps); break; case "av.error": error(Utility.parseString(options.get("av_player_error")), extraProps); break; default: sendEvents(createEvent(event, false, extraProps)); } } /*** * Set a new playback speed and update session context * @param playbackSpeed double */ public synchronized void setPlaybackSpeed(double playbackSpeed) { if (this.playbackSpeed == playbackSpeed && playbackSpeed <= 0) { return; } stopHeartbeatService(); if (!isPlaying) { this.playbackSpeed = playbackSpeed; return; } heartbeat(-1, null); if (autoHeartbeat) { int diffMin = (int) ((Utility.currentTimeMillis() - startSessionTimeMillis) / 60_000); heartbeatExecutor.schedule(heartbeatRunnable, heartbeatDurations.get(diffMin, MIN_HEARTBEAT_DURATION), TimeUnit.SECONDS); } this.playbackSpeed = playbackSpeed; } /*** * Generate heartbeat event. */ public void heartbeat(int cursorPosition, Map<String, Object> extraProps) { processHeartbeat(cursorPosition, false, extraProps); } /*** * Generate heartbeat event during buffering. */ public void bufferHeartbeat(Map<String, Object> extraProps) { processBufferHeartbeat(false, extraProps); } /*** * Generate heartbeat event during rebuffering. */ public void rebufferHeartbeat(Map<String, Object> extraProps) { processRebufferHeartbeat(false, extraProps); } /*** * Generate play event (play attempt). * @param cursorPosition Cursor position (milliseconds) */ public synchronized void play(int cursorPosition, Map<String, Object> extraProps) { startSessionTimeMillis = startSessionTimeMillis == 0 ? Utility.currentTimeMillis() : startSessionTimeMillis; eventDurationMillis = 0; cursorPosition = Math.max(cursorPosition, 0); previousCursorPositionMillis = cursorPosition; currentCursorPositionMillis = cursorPosition; bufferTimeMillis = 0; isPlaying = false; isPlaybackActivated = false; stopHeartbeatService(); sendEvents(createEvent("av.play", true, extraProps)); } /*** * Player buffering start to initiate the launch of the media. * @param cursorPosition Cursor position (milliseconds) */ public synchronized void bufferStart(int cursorPosition, Map<String, Object> extraProps) { startSessionTimeMillis = startSessionTimeMillis == 0 ? Utility.currentTimeMillis() : startSessionTimeMillis; updateDuration(); previousCursorPositionMillis = currentCursorPositionMillis; currentCursorPositionMillis = Math.max(cursorPosition, 0); stopHeartbeatService(); if (isPlaybackActivated) { if (autoBufferHeartbeat) { bufferTimeMillis = bufferTimeMillis == 0 ? Utility.currentTimeMillis() : bufferTimeMillis; int diffMin = (int) ((Utility.currentTimeMillis() - bufferTimeMillis) / 60_000); heartbeatExecutor.schedule(rebufferHeartbeatRunnable, bufferHeartbeatDurations.get(diffMin, MIN_BUFFER_HEARTBEAT_DURATION), TimeUnit.SECONDS); } sendEvents(createEvent("av.rebuffer.start", true, extraProps)); } else { if (autoBufferHeartbeat) { bufferTimeMillis = bufferTimeMillis == 0 ? Utility.currentTimeMillis() : bufferTimeMillis; int diffMin = (int) ((Utility.currentTimeMillis() - bufferTimeMillis) / 60_000); heartbeatExecutor.schedule(bufferHeartbeatRunnable, bufferHeartbeatDurations.get(diffMin, MIN_BUFFER_HEARTBEAT_DURATION), TimeUnit.SECONDS); } sendEvents(createEvent("av.buffer.start", true, extraProps)); } } /*** * Media playback start (first frame of the media). * @param cursorPosition Cursor position (milliseconds) */ public synchronized void playbackStart(int cursorPosition, Map<String, Object> extraProps) { startSessionTimeMillis = startSessionTimeMillis == 0 ? Utility.currentTimeMillis() : startSessionTimeMillis; updateDuration(); cursorPosition = Math.max(cursorPosition, 0); previousCursorPositionMillis = cursorPosition; currentCursorPositionMillis = cursorPosition; bufferTimeMillis = 0; isPlaying = true; isPlaybackActivated = true; stopHeartbeatService(); if (autoHeartbeat) { int diffMin = (int) ((Utility.currentTimeMillis() - startSessionTimeMillis) / 60_000); heartbeatExecutor.schedule(heartbeatRunnable, heartbeatDurations.get(diffMin, MIN_HEARTBEAT_DURATION), TimeUnit.SECONDS); } sendEvents(createEvent("av.start", true, extraProps)); } /*** * Media playback restarted manually after a pause. * @param cursorPosition Cursor position (milliseconds) */ public synchronized void playbackResumed(int cursorPosition, Map<String, Object> extraProps) { startSessionTimeMillis = startSessionTimeMillis == 0 ? Utility.currentTimeMillis() : startSessionTimeMillis; updateDuration(); previousCursorPositionMillis = currentCursorPositionMillis; currentCursorPositionMillis = Math.max(cursorPosition, 0); bufferTimeMillis = 0; isPlaying = true; isPlaybackActivated = true; stopHeartbeatService(); if (autoHeartbeat) { int diffMin = (int) ((Utility.currentTimeMillis() - startSessionTimeMillis) / 60_000); heartbeatExecutor.schedule(heartbeatRunnable, heartbeatDurations.get(diffMin, MIN_HEARTBEAT_DURATION), TimeUnit.SECONDS); } sendEvents(createEvent("av.resume", true, extraProps)); } /*** * Media playback paused. * @param cursorPosition Cursor position (milliseconds) */ public synchronized void playbackPaused(int cursorPosition, Map<String, Object> extraProps) { startSessionTimeMillis = startSessionTimeMillis == 0 ? Utility.currentTimeMillis() : startSessionTimeMillis; updateDuration(); previousCursorPositionMillis = currentCursorPositionMillis; currentCursorPositionMillis = Math.max(cursorPosition, 0); bufferTimeMillis = 0; isPlaying = false; isPlaybackActivated = true; stopHeartbeatService(); sendEvents(createEvent("av.pause", true, extraProps)); } /*** * Media playback stopped. * @param cursorPosition Cursor position (milliseconds) */ public synchronized void playbackStopped(int cursorPosition, Map<String, Object> extraProps) { startSessionTimeMillis = startSessionTimeMillis == 0 ? Utility.currentTimeMillis() : startSessionTimeMillis; updateDuration(); previousCursorPositionMillis = currentCursorPositionMillis; currentCursorPositionMillis = Math.max(cursorPosition, 0); bufferTimeMillis = 0; isPlaying = false; isPlaybackActivated = false; stopHeartbeatService(); startSessionTimeMillis = 0; sessionDurationMillis = 0; bufferTimeMillis = 0; sendEvents(createEvent("av.stop", true, extraProps)); resetState(); } /*** * Measuring seek event. * @param oldCursorPosition Starting position (milliseconds) * @param newCursorPosition Ending position (milliseconds) */ public void seek(int oldCursorPosition, int newCursorPosition, Map<String, Object> extraProps) { if (oldCursorPosition > newCursorPosition) { seekBackward(oldCursorPosition, newCursorPosition, extraProps); } else { seekForward(oldCursorPosition, newCursorPosition, extraProps); } } /*** * Measuring seek backward. * @param oldCursorPosition Starting position (milliseconds) * @param newCursorPosition Ending position (milliseconds) */ public void seekBackward(int oldCursorPosition, int newCursorPosition, Map<String, Object> extraProps) { processSeek("backward", oldCursorPosition, newCursorPosition, extraProps); } /*** * Measuring seek forward. * @param oldCursorPosition Starting position (milliseconds) * @param newCursorPosition Ending position (milliseconds) */ public void seekForward(int oldCursorPosition, int newCursorPosition, Map<String, Object> extraProps) { processSeek("forward", oldCursorPosition, newCursorPosition, extraProps); } /*** * Measuring seek start. * @param oldCursorPosition Old Cursor position (milliseconds) */ public void seekStart(int oldCursorPosition, Map<String, Object> extraProps) { sendEvents(createSeekStart(oldCursorPosition, extraProps)); } /*** * Measuring media click (especially for ads). */ public void adClick(Map<String, Object> extraProps) { sendEvents(createEvent("av.ad.click", false, extraProps)); } /*** * Measuring media skip (especially for ads). */ public void adSkip(Map<String, Object> extraProps) { sendEvents(createEvent("av.ad.skip", false, extraProps)); } /*** * Error measurement preventing reading from continuing. */ public void error(String message, Map<String, Object> extraProps) { if (extraProps == null) { extraProps = new HashMap<>(); } extraProps.put("av_player_error", message); sendEvents(createEvent("av.error", false, extraProps)); } /*** * Measuring reco or Ad display. */ public void display(Map<String, Object> extraProps) { sendEvents(createEvent("av.display", false, extraProps)); } /*** * Measuring close action. */ public void close(Map<String, Object> extraProps) { sendEvents(createEvent("av.close", false, extraProps)); } /*** * Measurement of a volume change action. */ public void volume(Map<String, Object> extraProps) { sendEvents(createEvent("av.volume", false, extraProps)); } /*** * Measurement of activated subtitles. */ public void subtitleOn(Map<String, Object> extraProps) { sendEvents(createEvent("av.subtitle.on", false, extraProps)); } /*** * Measurement of deactivated subtitles. */ public void subtitleOff(Map<String, Object> extraProps) { sendEvents(createEvent("av.subtitle.off", false, extraProps)); } /*** * Measuring a full-screen display. */ public void fullscreenOn(Map<String, Object> extraProps) { sendEvents(createEvent("av.fullscreen.on", false, extraProps)); } /*** * Measuring a full screen deactivation. */ public void fullscreenOff(Map<String, Object> extraProps) { sendEvents(createEvent("av.fullscreen.off", false, extraProps)); } /*** * Measurement of a quality change action. */ public void quality(Map<String, Object> extraProps) { sendEvents(createEvent("av.quality", false, extraProps)); } /*** * Measurement of a speed change action. */ public void speed(Map<String, Object> extraProps) { sendEvents(createEvent("av.speed", false, extraProps)); } /*** * Measurement of a sharing action. */ public void share(Map<String, Object> extraProps) { sendEvents(createEvent("av.share", false, extraProps)); } synchronized void processHeartbeat(int cursorPosition, boolean fromAuto, Map<String, Object> extraProps) { startSessionTimeMillis = startSessionTimeMillis == 0 ? Utility.currentTimeMillis() : startSessionTimeMillis; updateDuration(); previousCursorPositionMillis = currentCursorPositionMillis; if (cursorPosition >= 0) { currentCursorPositionMillis = cursorPosition; } else { currentCursorPositionMillis += (eventDurationMillis * playbackSpeed); } if (fromAuto) { int diffMin = (int) ((Utility.currentTimeMillis() - startSessionTimeMillis) / 60_000); heartbeatExecutor.schedule(heartbeatRunnable, heartbeatDurations.get(diffMin, MIN_HEARTBEAT_DURATION), TimeUnit.SECONDS); } sendEvents(createEvent("av.heartbeat", true, extraProps)); } synchronized void processBufferHeartbeat(boolean fromAuto, Map<String, Object> extraProps) { startSessionTimeMillis = startSessionTimeMillis == 0 ? Utility.currentTimeMillis() : startSessionTimeMillis; updateDuration(); if (fromAuto) { bufferTimeMillis = bufferTimeMillis == 0 ? Utility.currentTimeMillis() : bufferTimeMillis; int diffMin = (int) ((Utility.currentTimeMillis() - bufferTimeMillis) / 60_000); heartbeatExecutor.schedule(bufferHeartbeatRunnable, bufferHeartbeatDurations.get(diffMin, MIN_BUFFER_HEARTBEAT_DURATION), TimeUnit.SECONDS); } sendEvents(createEvent("av.buffer.heartbeat", true, extraProps)); } synchronized void processRebufferHeartbeat(boolean fromAuto, Map<String, Object> extraProps) { startSessionTimeMillis = startSessionTimeMillis == 0 ? Utility.currentTimeMillis() : startSessionTimeMillis; updateDuration(); previousCursorPositionMillis = currentCursorPositionMillis; if (fromAuto) { bufferTimeMillis = bufferTimeMillis == 0 ? Utility.currentTimeMillis() : bufferTimeMillis; int diffMin = (int) ((Utility.currentTimeMillis() - bufferTimeMillis) / 60_000); heartbeatExecutor.schedule(rebufferHeartbeatRunnable, bufferHeartbeatDurations.get(diffMin, MIN_BUFFER_HEARTBEAT_DURATION), TimeUnit.SECONDS); } sendEvents(createEvent("av.rebuffer.heartbeat", true, extraProps)); } private synchronized Event createSeekStart(int oldCursorPosition, Map<String, Object> extraProps) { previousCursorPositionMillis = currentCursorPositionMillis; currentCursorPositionMillis = Math.max(oldCursorPosition, 0); if (isPlaying) { updateDuration(); } else { eventDurationMillis = 0; } return createEvent("av.seek.start", true, extraProps); } private synchronized void processSeek(String seekDirection, int oldCursorPosition, int newCursorPosition, Map<String, Object> extraProps) { Event seekStart = createSeekStart(oldCursorPosition, extraProps); eventDurationMillis = 0; previousCursorPositionMillis = Math.max(oldCursorPosition, 0); currentCursorPositionMillis = Math.max(newCursorPosition, 0); sendEvents(seekStart, createEvent("av." + seekDirection, true, extraProps)); } private synchronized Event createEvent(String name, boolean withOptions, Map<String, Object> extraProps) { Map<String, Object> props = new HashMap<>(this.getProps()); if (withOptions) { props.put("av_previous_position", this.previousCursorPositionMillis); props.put("av_position", this.currentCursorPositionMillis); props.put("av_duration", this.eventDurationMillis); props.put("av_previous_event", this.previousEvent); this.previousEvent = name; } props.put("av_session_id", sessionId); if (extraProps != null) { props.putAll(new HashMap<>(extraProps)); } return new Event(name).setData(props); } private void sendEvents(Event... events) { if (events.length == 0) { return; } for (Event e : events) { this.events.add(e); } this.events.send(); } private void updateDuration() { eventDurationMillis = Utility.currentTimeMillis() - startSessionTimeMillis - sessionDurationMillis; sessionDurationMillis += eventDurationMillis; } private void stopHeartbeatService() { if (heartbeatExecutor != null && !heartbeatExecutor.isShutdown()) { heartbeatExecutor.shutdownNow(); } heartbeatExecutor = Executors.newSingleThreadScheduledExecutor(); } private void resetState() { sessionId = UUID.randomUUID().toString(); previousEvent = ""; previousCursorPositionMillis = 0; currentCursorPositionMillis = 0; eventDurationMillis = 0; } }
package com.jasoncabot.gardenpath.db; import com.jasoncabot.gardenpath.core.Fence; import com.jasoncabot.gardenpath.core.Game; import org.skife.jdbi.v2.sqlobject.*; import org.skife.jdbi.v2.sqlobject.customizers.SingleValueResult; import java.util.Collection; import java.util.List; import java.util.Optional; public abstract class GameDao { private static final String FIELDS_FOR_SELECTION = "state, last_move_at, name, hashed_password, is_player_one_turn" + ", p1_id, p1_name, p1_position, p1_f1, p1_f2, p1_f3, p1_f4, p1_f5, p1_f6, p1_f7, p1_f8, p1_f9, p1_f10" + ", p2_id, p2_name, p2_position, p2_f1, p2_f2, p2_f3, p2_f4, p2_f5, p2_f6, p2_f7, p2_f8, p2_f9, p2_f10 "; private static final String PLAY_UPDATE = "UPDATE games SET state = :state, last_move_at = current_timestamp(), is_player_one_turn = NOT(is_player_one_turn) "; private static final String PLAY_UPDATE_WHERE = "WHERE id = :id " + "AND state = 'IN_PROGRESS' " + "AND ((is_player_one_turn AND p1_id = :player_id) OR (NOT(is_player_one_turn) AND p2_id = :player_id))"; private static final String JOIN_GAME_UPDATE = "p2_id = :playerId, " + "p2_name = :playerName, " + "is_player_one_turn = :player1Turn, " + "p1_position = 4, " + "p2_position = 76, " + "state = 'IN_PROGRESS', " + "last_move_at = current_timestamp() "; @SqlQuery("SELECT id, 0 as is_player_one, " + FIELDS_FOR_SELECTION + "FROM games " + "WHERE state = :state") public abstract Collection<Game> findAll(@Bind("state") final String state); @SingleValueResult(Game.class) @SqlQuery("SELECT id, (:player_id = p1_id) as is_player_one, " + FIELDS_FOR_SELECTION + "FROM games " + "WHERE id = :id AND (p1_id = :player_id OR p2_id = :player_id)") public abstract Optional<Game> find(@Bind("id") long gameId, @Bind("player_id") String playerId); @SingleValueResult(Game.class) @SqlQuery("SELECT id, (:player_id = p1_id) as is_player_one, " + FIELDS_FOR_SELECTION + "FROM games " + "WHERE name = :name AND hashed_password = :hashed_password AND (p1_id = :player_id OR p2_id = :player_id)") public abstract Optional<Game> find(@Bind("name") final String gameName, @Bind("hashed_password") final String gamePassword, @Bind("player_id") String playerId); @SingleValueResult(Game.class) @SqlQuery("SELECT id, (:player_id = p1_id) as is_player_one, " + FIELDS_FOR_SELECTION + "FROM games " + "WHERE id = :id AND (p1_id = :player_id OR p2_id = :player_id) AND state = :state") public abstract Optional<Game> find(@Bind("id") final long gameId, @Bind("player_id") final String playerId, @Bind("state") final String state); @SqlUpdate(PLAY_UPDATE + ", p1_position = :position " + PLAY_UPDATE_WHERE) public abstract void updatePlayerOnePosition(@Bind("id") final long gameId, @Bind("player_id") final String playerId, @Bind("position") final int position, @Bind("state") final String state); @SqlUpdate(PLAY_UPDATE + ", p2_position = :position " + PLAY_UPDATE_WHERE) public abstract void updatePlayerTwoPosition(@Bind("id") final long gameId, @Bind("player_id") final String playerId, @Bind("position") final int position, @Bind("state") final String state); @SqlUpdate(PLAY_UPDATE + ", p1_f1 = :fence1 " + ", p1_f2 = :fence2 " + ", p1_f3 = :fence3 " + ", p1_f4 = :fence4 " + ", p1_f5 = :fence5 " + ", p1_f6 = :fence6 " + ", p1_f7 = :fence7 " + ", p1_f8 = :fence8 " + ", p1_f9 = :fence9 " + ", p1_f10 = :fence10 " + PLAY_UPDATE_WHERE) public abstract void updatePlayerOneFences(@Bind("id") final long gameId, @Bind("player_id") final String playerId, @BindBean final FenceGameData fences, @Bind("state") final String state); @SqlUpdate(PLAY_UPDATE + ", p2_f1 = :fence1 " + ", p2_f2 = :fence2 " + ", p2_f3 = :fence3 " + ", p2_f4 = :fence4 " + ", p2_f5 = :fence5 " + ", p2_f6 = :fence6 " + ", p2_f7 = :fence7 " + ", p2_f8 = :fence8 " + ", p2_f9 = :fence9 " + ", p2_f10 = :fence10 " + PLAY_UPDATE_WHERE) public abstract void updatePlayerTwoFences(@Bind("id") final long gameId, @Bind("player_id") final String playerId, @BindBean final FenceGameData fences, @Bind("state") final String state); @SqlUpdate("UPDATE games SET " + JOIN_GAME_UPDATE + "WHERE id = :gameId AND state = 'WAITING_OPPONENT' AND p1_id != :playerId") public abstract void joinPublicGame(@BindBean final StartGameData data); @SqlUpdate("UPDATE games SET " + JOIN_GAME_UPDATE + "WHERE id = :gameId, state = 'WAITING_OPPONENT' AND p1_id != :playerId AND name = :gameName AND hashed_password = :gamePassword") public abstract void joinPrivateGame(@BindBean final StartGameData data); @GetGeneratedKeys @SqlUpdate("INSERT INTO games (state, last_move_at, p1_id, p1_name) VALUES ('WAITING_OPPONENT', current_timestamp(), :player_id, :player_name)") public abstract long createPublicGame(@Bind("player_id") final String playerId, @Bind("player_name") final String playerName); // TODO: optimistic locking WHERE NOT(exists(game_name, game_password, state='WAITING_OPPONENT')) @GetGeneratedKeys @SqlUpdate("INSERT INTO games (state, last_move_at, name, hashed_password, p1_id, p1_name) VALUES ('WAITING_OPPONENT', current_timestamp(), :game_name, :game_password, :player_id, :player_name)") public abstract long createPrivateGame(@Bind("player_id") final String playerId, @Bind("player_name") final String playerName, @Bind("game_name") final String gameName, @Bind("game_password") final String hashedPassword); public static class FenceGameData { final int fence1; final int fence2; final int fence3; final int fence4; final int fence5; final int fence6; final int fence7; final int fence8; final int fence9; final int fence10; public int getFence1() { return fence1; } public int getFence2() { return fence2; } public int getFence3() { return fence3; } public int getFence4() { return fence4; } public int getFence5() { return fence5; } public int getFence6() { return fence6; } public int getFence7() { return fence7; } public int getFence8() { return fence8; } public int getFence9() { return fence9; } public int getFence10() { return fence10; } public FenceGameData(final List<Fence> fences) { fence1 = fenceId(fences.get(0)); fence2 = fenceId(fences.get(1)); fence3 = fenceId(fences.get(2)); fence4 = fenceId(fences.get(3)); fence5 = fenceId(fences.get(4)); fence6 = fenceId(fences.get(5)); fence7 = fenceId(fences.get(6)); fence8 = fenceId(fences.get(7)); fence9 = fenceId(fences.get(8)); fence10 = fenceId(fences.get(9)); } private int fenceId(final Fence fence) { return fence.isValid() ? fence.hashCode() : 0; } } public static class StartGameData { final long gameId; final String playerId; final String playerName; final boolean isPlayer1Turn; final String gameName; final String gamePassword; public long getGameId() { return gameId; } public String getPlayerId() { return playerId; } public String getPlayerName() { return playerName; } public boolean isPlayer1Turn() { return isPlayer1Turn; } public String getGameName() { return gameName; } public String getGamePassword() { return gamePassword; } public StartGameData(final long gameId, final String playerId, final String playerName) { this.gameId = gameId; this.playerId = playerId; this.playerName = playerName; this.gameName = null; this.gamePassword = null; this.isPlayer1Turn = true; } public StartGameData(final String playerId, final String playerName, final String gameName, final String gamePassword) { this.gameId = -1; this.playerId = playerId; this.playerName = playerName; this.gameName = gameName; this.gamePassword = gamePassword; this.isPlayer1Turn = true; } } }
package net.f4fs.fspeer; import java.io.IOException; import java.net.Inet4Address; import java.net.InetAddress; import java.util.Collection; import java.util.Set; import net.f4fs.bootstrapserver.BootstrapServerAccess; import net.f4fs.config.Config; import net.f4fs.persistence.IPathPersistence; import net.f4fs.persistence.IPersistence; import net.f4fs.util.RandomDevice; import net.tomp2p.connection.Bindings; import net.tomp2p.connection.DiscoverNetworks; import net.tomp2p.connection.StandardProtocolFamily; import net.tomp2p.dht.PeerBuilderDHT; import net.tomp2p.dht.PeerDHT; import net.tomp2p.futures.FutureBootstrap; import net.tomp2p.futures.FutureDiscover; import net.tomp2p.p2p.PeerBuilder; import net.tomp2p.peers.Number160; import net.tomp2p.peers.PeerAddress; import net.tomp2p.storage.Data; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The file system peer * * @author Reto */ public class FSPeer { private PeerDHT peer; private IPersistence persistence; private IPathPersistence pathPersistence; private BootstrapServerAccess bootstrapServerAccess; private String myIp; private Logger logger; public FSPeer() { // this.persistence = PersistenceFactory.getVersionedDhtOperations(); this.persistence = PersistenceFactory.getChunkedDhtOperations(); this.pathPersistence = PersistenceFactory.getConsensusPathOperations(); this.bootstrapServerAccess = new BootstrapServerAccess(); this.logger = LoggerFactory.getLogger(FSPeer.class); } /** * Starts this peer as the first, i.e. bootstrap peer * * @throws Exception */ public void startAsBootstrapPeer() throws Exception { Bindings b = new Bindings().addProtocol(StandardProtocolFamily.INET).addAddress( Inet4Address.getLocalHost()); // b.addInterface("eth0"); peer = new PeerBuilderDHT(new PeerBuilder(new Number160(RandomDevice.INSTANCE.getRand())).ports(Config.DEFAULT.getPort()).bindings(b).start()).start(); setMyIp(); postIpPortPair(myIp, Config.DEFAULT.getPort()); logger.info("[Peer@" + myIp + "]: Server started listening to: " + DiscoverNetworks.discoverInterfaces(b)); logger.info("[Peer@" + myIp + "]: Address visible to outside is " + peer.peerAddress()); } /** * Starts this peer with the given parameters * * @param connectionIpAddress The IP address to which this peer should be connected * @param connectionPort The port to which this peer should be connected * @return True, if started successfully, false otherwise * * @throws Exception */ public boolean startPeer(String connectionIpAddress, int connectionPort) throws Exception { Bindings b = new Bindings().addProtocol(StandardProtocolFamily.INET).addAddress( Inet4Address.getLocalHost()); // b.addInterface("eth0"); peer = new PeerBuilderDHT(new PeerBuilder(new Number160(RandomDevice.INSTANCE.getRand())).ports(Config.DEFAULT.getPort()).bindings(b).start()).start(); setMyIp(); postIpPortPair(myIp, Config.DEFAULT.getPort()); logger.info("[Peer@" + myIp + "]: Client started and listening to: " + DiscoverNetworks.discoverInterfaces(b)); logger.info("[Peer@" + myIp + "]: Address visible to outside is " + peer.peerAddress()); InetAddress address = Inet4Address.getByName(connectionIpAddress); PeerAddress connectionPeerAddress = new PeerAddress(Number160.ZERO, address, connectionPort, connectionPort); logger.info("[Peer@" + myIp + "]: Connected to " + connectionPeerAddress); bootstrapServerAccess.postIpPortPair(myIp, Config.DEFAULT.getPort()); // Future Discover FutureDiscover futureDiscover = peer.peer().discover().inetAddress(address).ports(connectionPort).start(); futureDiscover.awaitUninterruptibly(); // Future Bootstrap - slave FutureBootstrap futureBootstrap = peer.peer().bootstrap().inetAddress(address).ports(connectionPort).start(); futureBootstrap.awaitUninterruptibly(); Collection<PeerAddress> addressList = peer.peerBean().peerMap().all(); logger.info("[Peer@" + myIp + "]: Address list size: " + addressList.size()); if (futureDiscover.isSuccess()) { logger.info("[Peer@" + myIp + "]: Outside IP address is " + futureDiscover.peerAddress()); return true; } logger.info("[Peer@" + myIp + "]: Failed " + futureDiscover.failedReason()); return false; } /** * Shuts down this peer */ public void shutdown() { removeIpPortPair(peer.peerAddress().toString(), Config.DEFAULT.getPort()); peer.shutdown(); } /** * Prints a list of connected peers to * stdout * * @throws InterruptedException */ public void printConnectedPeers() throws InterruptedException { logger.info("Listing connected peers: "); for (PeerAddress pa : peer.peerBean().peerMap().all()) { logger.info("[ConnectedPeer]: " + pa); } logger.info("Done"); } /** * Gets the value stored on the given key * * @param pKey The key to retrieve its value from * @return An object containing the stored data * * @throws ClassNotFoundException * @throws IOException * @throws InterruptedException If a failure happened during await of future */ public Data getData(Number160 pKey) throws ClassNotFoundException, IOException, InterruptedException { return this.persistence.getData(this.peer, pKey); } /** * Gets the assigned data (the path to the file) of the given content key on the default location key * * @param pContentKey The content key specifying the path of the file * * @return FutureGet to get the data * * @throws IOException * @throws InterruptedException If a failure happened during await of future * @throws ClassNotFoundException */ public String getPath(Number160 pContentKey) throws ClassNotFoundException, InterruptedException, IOException { return this.pathPersistence.getPath(this.peer, pContentKey); } /** * Gets all keys of all files stored in the dht * * @return keys List with all keys to the files in the dht * * @throws IOException * @throws InterruptedException If a failure happened during await of future * @throws ClassNotFoundException * * @throws Exception */ public Set<String> getAllPaths() throws ClassNotFoundException, InterruptedException, IOException { return this.pathPersistence.getAllPaths(this.peer); } /** * Stores the given data on the given key * * @param pKey The key to store the data * @param pValue The data to store * * @throws IOException * @throws InterruptedException If a failure happened during await of future * @throws ClassNotFoundException */ public void putData(Number160 pKey, Data pValue) throws InterruptedException, ClassNotFoundException, IOException { this.persistence.putData(this.peer, pKey, pValue); } /** * Stores the given data with the given content key on the default location key * * @param pContentKey The key to store the data * @param pValue The data to store * * @throws InterruptedException If a failure happened during await of future * @throws IOException * @throws ClassNotFoundException */ public void putPath(Number160 pContentKey, Data pValue) throws InterruptedException, ClassNotFoundException, IOException { this.pathPersistence.putPath(this.peer, pContentKey, pValue); } /** * Removes the assigned data from the peer * * @param pKey Key of which the data should be removed * * @throws InterruptedException If a failure happened during await of future */ public void removeData(Number160 pKey) throws InterruptedException { this.persistence.removeData(this.peer, pKey); } /** * Removes the file key from the file keys which are stored with the default location key * * @param pContentKey * * @throws InterruptedException If a failure happened during await of future */ public void removePath(Number160 pContentKey) throws InterruptedException { this.pathPersistence.removePath(this.peer, pContentKey); } public PeerDHT getPeerDHT() { return this.peer; } private void postIpPortPair(String ip, int port) { bootstrapServerAccess.postIpPortPair(ip, port); } private void removeIpPortPair(String ip, int port) { bootstrapServerAccess.removeIpPortPair(ip, port); } private void setMyIp() { if (peer != null) { myIp = peer.peerAddress().inetAddress().getHostAddress(); } } public String getMyIp() { return myIp; } }
package com.hkamran.mocking.servers; import java.io.EOFException; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.ArrayList; import java.util.List; import javax.websocket.ClientEndpoint; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; import org.apache.log4j.Logger; import org.json.JSONException; import com.hkamran.mocking.Filter; import com.hkamran.mocking.Payload; import com.hkamran.mocking.Proxies; import com.hkamran.mocking.Proxy; import com.hkamran.mocking.Request; import com.hkamran.mocking.Response; import com.hkamran.mocking.Tape; import com.hkamran.mocking.Filter.State; import com.hkamran.mocking.Payload.Action; @ClientEndpoint @ServerEndpoint(value = "/") public class WebSocket { private static Proxies proxies = new Proxies(); private final static Logger log = Logger.getLogger(WebSocket.class); static List<Session> sessions = new ArrayList<Session>(); @OnOpen public void OnWebSocketConnect(Session session) { sessions.add(session); log.info("Socket Opened: " + session.getId()); session.setMaxIdleTimeout(600000); WebSocket.send(session, Payload.create(-1, Action.UPDATE, Payload.Type.PROXIES, WebSocket.proxies)); for (Integer id : WebSocket.proxies.keySet()) { Proxy proxy = WebSocket.proxies.get(id); Filter filter = proxy.getFilter(); WebSocket.send(session, Payload.create(id, Payload.Action.UPDATE, Payload.Type.FILTER, filter)); WebSocket.send(session, Payload.create(id, Payload.Action.UPDATE, Payload.Type.TAPE, filter.getTape())); } } @OnMessage public void onWebSocketText(String message, Session session) { Payload payload = Payload.parseJSON(message); System.out.println("Received TEXT message: " + message); if (payload.type == Payload.Type.FILTER) { handleFilterUpdate(payload); } else if (payload.type == Payload.Type.TAPE) { handleTapeUpdate(payload); } else if (payload.type == Payload.Type.REQUEST) { handleRequestUpdate(session, payload); } else if (payload.type == Payload.Type.RESPONSE) { handleResponseUpdate(session, payload); } else if (payload.type == Payload.Type.PROXY) { handleProxyUpdate(session, payload); } } private void handleProxyUpdate(Session session, Payload payload) { Proxy proxy = (Proxy) payload.obj; if (payload.action == Payload.Action.INSERT) { Integer id = WebSocket.proxies.add(proxy.name, proxy.port); Proxy createProxy = WebSocket.proxies.get(id); Payload proxies = Payload.create(id, Payload.Action.INSERT, Payload.Type.PROXY, createProxy); WebSocket.broadcast(proxies); } else { Proxy updateProxy = WebSocket.proxies.get(proxy.id); if (updateProxy == null) { log.info("Unable to find proxy id " + proxy.id); return; } if (payload.action == Payload.Action.DELETE) { synchronized (proxies) { if (WebSocket.proxies.size() == 1) { return; } Proxy originalProxy = WebSocket.proxies.get(proxy.id); Payload payloadUpdate = Payload.create(-1, Payload.Action.DELETE, Payload.Type.PROXY, originalProxy); WebSocket.broadcast(payloadUpdate); log.info("Deleting proxy " + originalProxy.id + ":" + originalProxy.name); WebSocket.proxies.remove(proxy.id); return; } } else if (payload.action == Payload.Action.UPDATE) { Proxy curProxy = WebSocket.proxies.get(proxy.id); String name = curProxy.name; Integer port = curProxy.port; curProxy.name = name; if (port != curProxy.port) { curProxy.port = port; curProxy.stop(); curProxy.start(); } Payload proxies = Payload.create(-1, Payload.Action.UPDATE, Payload.Type.PROXIES, WebSocket.proxies); WebSocket.broadcast(proxies); log.info("Creating proxy " + curProxy.id + ":" + curProxy.name); return; } } } private void handleResponseUpdate(Session session, Payload payload) { if (!(payload.obj instanceof Response)) { return; } if (payload.action == Payload.Action.UPDATE) { Response response = (Response) payload.obj; Integer id = payload.id; Proxy proxy = proxies.get(id); Filter filter = proxy.getFilter(); Tape tape = filter.getTape(); Request request = tape.getRequest(response.getParent().toString()); List<Response> responses = tape.getResponses(request); responses.set(response.getId(), response); Payload updateTape = Payload.create(id, Payload.Action.UPDATE, Payload.Type.TAPE, filter.getTape()); WebSocket.broadcast(updateTape); Payload updatedResponse = Payload.create(id, Payload.Action.UPDATE, Payload.Type.RESPONSE, response); WebSocket.broadcast(updatedResponse); } } private void handleRequestUpdate(Session session, Payload payload) { if (!(payload.obj instanceof Request)) { return; } if (payload.action == Payload.Action.UPDATE) { Request request = (Request) payload.obj; Integer id = payload.id; Proxy proxy = proxies.get(id); Filter filter = proxy.getFilter(); filter.getTape().setRequest(request.pastID.toString(), request); Payload updateTape = Payload.create(id, Payload.Action.UPDATE, Payload.Type.TAPE, filter.getTape()); WebSocket.broadcast(updateTape); Payload updatedRequest = Payload.create(id, Payload.Action.UPDATE, Payload.Type.REQUEST, request); WebSocket.broadcast(updatedRequest); } } private void handleTapeUpdate(Payload payload) { if (!(payload.obj instanceof Tape)) { return; } if (payload.action == Payload.Action.UPDATE) { Tape tape = (Tape) payload.obj; Integer id = payload.id; Proxy proxy = proxies.get(id); Filter filter = proxy.getFilter(); filter.setTape(tape); Payload update = Payload.create(id, Payload.Action.UPDATE, Payload.Type.TAPE, filter.getTape()); log.info("Updating tape " + payload.id); WebSocket.broadcast(update); } } private void handleFilterUpdate(Payload payload) { if (!(payload.obj instanceof Filter)) { return; } if (payload.action == Payload.Action.UPDATE) { Filter updatedFilter = (Filter) payload.obj; String host = updatedFilter.host; Integer port = updatedFilter.port; Boolean redirect = updatedFilter.getRedirectState(); State state = updatedFilter.getState(); Integer id = payload.id; Proxy proxy = proxies.get(id); Filter filter = proxy.getFilter(); filter.setRedirectInfo(host, port); filter.setRedirectState(redirect); filter.setState(state); Payload filterPayload = Payload.create(id, Payload.Action.UPDATE, Payload.Type.FILTER, filter); WebSocket.broadcast(filterPayload); } } @OnClose public void onWebSocketClose(Session session) { System.out.println("Socket Closed: " + session.getId()); } @OnError public void onWebSocketError(Throwable cause) { if (cause instanceof EOFException) { return; } else if (cause instanceof SocketTimeoutException) { return; } cause.printStackTrace(System.err); } public static void send(Session session, Payload payload) { try { session.getBasicRemote().sendText(payload.toJSON().toString(2)); } catch (JSONException | IOException e) { e.printStackTrace(); } } public static void broadcast(Payload payload) { for (Session session : sessions) { if (session.isOpen()) { try { session.getBasicRemote().sendText(payload.toJSON().toString()); } catch (IOException e) { e.printStackTrace(); } } } } public static void setProxyManager(Proxies manager) { WebSocket.proxies = manager; } }
package net.katsuster.semu; /** * ARM9 CPU * * : ARMv5TE * * ARM Second Edition * ARM DDI 0100DJ-00 * * T Thumb * E DSP * * * @author katsuhiro */ public class CPU extends MasterCore64 implements Runnable { private int[] regs; private int[] regs_svc; private int[] regs_abt; private int[] regs_und; private int[] regs_irq; private int[] regs_fiq; private int cpsr; private CoProc[] coProcs; private MMU mmu; private boolean jumped; private boolean flagDisasm; private boolean flagPrintDisasm; private boolean flagPrintReg; public CPU() { StdCoProc stdCp; stdCp = new StdCoProc(15, this); regs = new int[17]; regs_svc = new int[17]; regs_abt = new int[17]; regs_und = new int[17]; regs_irq = new int[17]; regs_fiq = new int[17]; coProcs = new CoProc[16]; coProcs[15] = stdCp; mmu = new MMU(this, stdCp); } public boolean isDisasmMode() { return flagDisasm; } public void setDisasmMode(boolean b) { flagDisasm = b; } public boolean isPrintingDisasm() { return flagPrintDisasm; } public void setPrintingDisasm(boolean b) { flagPrintDisasm = b; } public boolean isPrintingRegs() { return flagPrintReg; } public void setPrintingRegs(boolean b) { flagPrintReg = b; } public void printDisasm(Instruction inst, String operation, String operand) { if (isPrintingDisasm()) { System.out.printf("%08x: %08x %-7s %s\n", getPC() - 8, inst.getInst(), operation, operand); } if (isPrintingRegs()) { printRegs(); } } public void printRegs() { for (int i = 0; i < 16; i += 4) { System.out.printf(" r%-2d: %08x, r%-2d: %08x, r%-2d: %08x, r%-2d: %08x, \n", i, getRegRaw(i), i + 1, getRegRaw(i + 1), i + 2, getRegRaw(i + 2), i + 3, getRegRaw(i + 3)); } System.out.printf(" cpsr:%08x(%s), spsr:%08x(%s)\n", getCPSR(), getPSRName(getCPSR()), getSPSR(), getPSRName(getSPSR())); } /** * * * @param v * @param n */ public static long signext(long v, int n) { long sb, mb; if (n == 0) { return 0; } sb = 1L << (n - 1); mb = (-1L << (n - 1)) << 1; v &= ~mb; if ((v & sb) != 0) { v = mb + v; } return v; } /** * Rn * * r15 +8 * * @param n 0 1516 SPSR * @return */ public int getRegRaw(int n) { switch (getCPSR_Mode()) { case MODE_USR: case MODE_SYS: return regs[n]; case MODE_SVC: if ((13 <= n && n <= 14) || n == 16) { return regs_svc[n]; } else { return regs[n]; } case MODE_ABT: if ((13 <= n && n <= 14) || n == 16) { return regs_abt[n]; } else { return regs[n]; } case MODE_UND: if ((13 <= n && n <= 14) || n == 16) { return regs_und[n]; } else { return regs[n]; } case MODE_IRQ: if ((13 <= n && n <= 14) || n == 16) { return regs_irq[n]; } else { return regs[n]; } case MODE_FIQ: if ((8 <= n && n <= 14) || n == 16) { return regs_fiq[n]; } else { return regs[n]; } default: //do nothing break; } throw new IllegalArgumentException("Illegal mode " + String.format("mode:0x%x.", getCPSR_Mode())); } /** * Rn * * r15 * * @param n 0 1516 SPSR * @param val */ public void setRegRaw(int n, int val) { switch (getCPSR_Mode()) { case MODE_USR: case MODE_SYS: regs[n] = val; return; case MODE_SVC: if ((13 <= n && n <= 14) || n == 16) { regs_svc[n] = val; return; } else { regs[n] = val; return; } case MODE_ABT: if ((13 <= n && n <= 14) || n == 16) { regs_abt[n] = val; return; } else { regs[n] = val; return; } case MODE_UND: if ((13 <= n && n <= 14) || n == 16) { regs_und[n] = val; return; } else { regs[n] = val; return; } case MODE_IRQ: if ((13 <= n && n <= 14) || n == 16) { regs_irq[n] = val; return; } else { regs[n] = val; return; } case MODE_FIQ: if ((8 <= n && n <= 14) || n == 16) { regs_fiq[n] = val; return; } else { regs[n] = val; return; } default: //do nothing break; } throw new IllegalArgumentException("Illegal mode " + String.format("mode:0x%x.", getCPSR_Mode())); } /** * Rn * * @param n 0 15 * @return */ public int getReg(int n) { if (n == 15) { return getRegRaw(n) + 8; } else { return getRegRaw(n); } } /** * Rn * * @param n 0 15 * @param val */ public void setReg(int n, int val) { if (n == 15) { setJumped(true); } setRegRaw(n, val); } /** * Rn * * @param n 0 15 * @return */ public static String getRegName(int n) { return String.format("r%d", n); } /** * Pn * * @param cpnum * @return */ public CoProc getCoproc(int cpnum) { return coProcs[cpnum]; } /** * CRn * * @param cpnum * @param n 0 7 * @return */ public static String getCoprocRegName(int cpnum, int n) { return String.format("cr%d", n); } /** * Cp15 * * @return */ public StdCoProc getStdCoProc() { return (StdCoProc)coProcs[15]; } /** * MMU * * @return MMU */ public MMU getMMU() { return mmu; } /** * PC * * * getReg(15) * * @return PC */ public int getPC() { return getReg(15); } /** * PC * * * setReg(15, val) * * @param val PC */ public void setPC(int val) { setReg(15, val); } public void nextPC() { if (isJumped()) { setJumped(false); } else { regs[15] += 4; } } /** * * * PC +8+ * PC * * PC 4 * * * @param val */ public void jumpRel(int val) { setPC(getPC() + val); setJumped(true); } /** * * * @return true false */ public boolean isJumped() { return jumped; } /** * * * @param b true false */ public void setJumped(boolean b) { jumped = b; } public static final int PSR_BIT_N = 31; public static final int PSR_BIT_Z = 30; public static final int PSR_BIT_C = 29; public static final int PSR_BIT_V = 28; public static final int PSR_BIT_I = 7; public static final int PSR_BIT_F = 6; public static final int PSR_BIT_T = 5; /** * CPSR * * @return CPSR */ public int getCPSR() { return cpsr; } /** * CPSR * * @param val CPSR */ public void setCPSR(int val) { cpsr = val; } /** * SPSR * * @return SPSR */ public int getSPSR() { return getReg(16); } /** * SPSR * * @param val SPSR */ public void setSPSR(int val) { setReg(16, val); } /** * APSR * * @return APSR */ public int getAPSR() { return getCPSR() & 0xf80f0000; } /** * APSR * * @param val APSR */ public void setAPSR(int val) { int r; //N, Z, C, V, Q, GE r = getCPSR(); r &= ~0xf80f0000; r |= val & 0xf80f0000; setCPSR(r); } public static final int MODE_USR = 0x10; public static final int MODE_FIQ = 0x11; public static final int MODE_IRQ = 0x12; public static final int MODE_SVC = 0x13; public static final int MODE_ABT = 0x17; public static final int MODE_UND = 0x1b; public static final int MODE_SYS = 0x1f; /** * PSR M * [4:0] * * @param val PSR * @return M */ public static int getPSR_Mode(int val) { return val & 0x1f; } /** * PSR M * [4:0] * * @param val PSR * @param mod * @return PSR */ public static int setPSR_Mode(int val, int mod) { int mask = 0x1f; val &= ~mask; val |= mod & mask; return val; } /** * * * @param mode * @return */ public static String getPSR_ModeName(int mode) { switch (mode) { case 0x10: return "usr"; case 0x11: return "fiq"; case 0x12: return "irq"; case 0x13: return "svc"; case 0x17: return "abt"; case 0x1b: return "und"; case 0x1f: return "sys"; default: return "???"; } } /** * PSR * * @param val PSR * @return PSR */ public static String getPSRName(int val) { return String.format("%s%s%s%s_%s%s%s%5s", BitOp.getBit(val, PSR_BIT_N) ? "N" : "n", BitOp.getBit(val, PSR_BIT_Z) ? "Z" : "z", BitOp.getBit(val, PSR_BIT_C) ? "C" : "c", BitOp.getBit(val, PSR_BIT_V) ? "V" : "v", BitOp.getBit(val, PSR_BIT_I) ? "I" : "i", BitOp.getBit(val, PSR_BIT_F) ? "F" : "f", BitOp.getBit(val, PSR_BIT_T) ? "T" : "t", getPSR_ModeName(getPSR_Mode(val))); } /** * CPSR * N 31 * * N 31 1 * 2 * N=0 N=1 * * @return N true, false */ public boolean getCPSR_N() { return BitOp.getBit(getCPSR(), PSR_BIT_N); } /** * CPSR * N 31 * * N 31 1 * 2 * N=0 N=1 * * @param nv N true, false */ public void setCPSR_N(boolean nv) { setCPSR(BitOp.setBit(getCPSR(), PSR_BIT_N, nv)); } /** * CPSR * Z 30 * * Z 0 * 0 Z=00 Z=1 * * @return Z true, false */ public boolean getCPSR_Z() { return BitOp.getBit(getCPSR(), PSR_BIT_Z); } /** * CPSR * Z 30 * * Z 0 * 0 Z=00 Z=1 * * @param nv Z true, false */ public void setCPSR_Z(boolean nv) { setCPSR(BitOp.setBit(getCPSR(), PSR_BIT_Z, nv)); } /** * CPSR * C 29 * * C * * * * - * C=0 * C=1 * - * C=0 * C=1 * - 0 C=0 * 1 C=1 * * @return C true, false */ public boolean getCPSR_C() { return BitOp.getBit(getCPSR(), PSR_BIT_C); } /** * CPSR * C 29 * * C * * * * - * C=0 * C=1 * - * C=0 * C=1 * - 0 C=0 * 1 C=1 * * @param nv C true, false */ public void setCPSR_C(boolean nv) { setCPSR(BitOp.setBit(getCPSR(), PSR_BIT_C, nv)); } /** * CPSR * V 28 * * V * * - * V=0 * V=1 * * @return V true, false */ public boolean getCPSR_V() { return BitOp.getBit(getCPSR(), PSR_BIT_V); } /** * CPSR * V 28 * * V * * - * V=0 * V=1 * * @param nv V true, false */ public void setCPSR_V(boolean nv) { setCPSR(BitOp.setBit(getCPSR(), PSR_BIT_V, nv)); } /** * CPSR * I 7 * * I=0 IRQ * I=1 IRQ * * @return I true, false */ public boolean getCPSR_I() { return BitOp.getBit(getCPSR(), PSR_BIT_I); } /** * CPSR * I 7 * * I=0 IRQ * I=1 IRQ * * @param nv I true, false */ public void setCPSR_I(boolean nv) { setCPSR(BitOp.setBit(getCPSR(), PSR_BIT_I, nv)); } /** * CPSR * F 6 * * F=0 FIQ * F=1 FIQ * * @return F true, false */ public boolean getCPSR_F() { return BitOp.getBit(getCPSR(), PSR_BIT_F); } /** * CPSR * F 6 * * F=0 FIQ * F=1 FIQ * * @param nv F true, false */ public void setCPSR_F(boolean nv) { setCPSR(BitOp.setBit(getCPSR(), PSR_BIT_F, nv)); } /** * CPSR * T 5 * * T=0 ARM * T=1 Thumb * * ARMv5 T Thumb * T=1 * * @return T true, false */ public boolean getCPSR_T() { return BitOp.getBit(getCPSR(), PSR_BIT_T); } /** * CPSR * T 5 * * T=0 ARM * T=1 Thumb * * ARMv5 T Thumb * T=1 * * @param nv T true, false */ public void setCPSR_T(boolean nv) { setCPSR(BitOp.setBit(getCPSR(), PSR_BIT_T, nv)); } /** * * * CPSR M [4:0] * * @return */ public int getCPSR_Mode() { return getPSR_Mode(getCPSR()); } /** * * * CPSR M [4:0] * * @param mod */ public void setCPSR_Mode(int mod) { setCPSR(setPSR_Mode(getCPSR(), mod)); } /** * * * * @param left * @param right * @return true false */ public static boolean carryFrom(int left, int right) { long ll = left & 0xffffffffL; long lr = right & 0xffffffffL; return ((ll + lr) & ~0xffffffffL) != 0; } /** * * * * @param left * @param right * @return true false */ public static boolean borrowFrom(int left, int right) { long ll = left & 0xffffffffL; long lr = right & 0xffffffffL; return lr > ll; } /** * * * * @param left * @param right * @param add true false * @return true false */ public static boolean overflowFrom(int left, int right, boolean add) { int dest; boolean cond1, cond2; if (add) { dest = left + right; //left right cond1 = (left >= 0 && right >= 0) || (left < 0 && right < 0); // left, right dest cond2 = (left < 0 && dest >= 0) || (left >= 0 && dest < 0); } else { dest = left - right; //left right cond1 = (left < 0 && right >= 0) || (left >= 0 && right < 0); // left dest cond2 = (left < 0 && dest >= 0) || (left >= 0 && dest < 0); } return cond1 && cond2; } /** * 1 - * * @param inst ARM * @return */ public int getShifterOperand(Instruction inst) { boolean i = inst.getIBit(); boolean b7 = inst.getBit(7); boolean b4 = inst.getBit(4); if (i) { //32bits return getShifterOperandImm(inst); } else if (!b4) { return getShifterOperandImmShift(inst); } else if (b4 && !b7) { return getShifterOperandRegShift(inst); } else { throw new IllegalArgumentException("Unknown shifter_operand " + String.format("0x%08x, I:%b, b7:%b, b4:%b.", inst.getInst(), i, b7, b4)); } } /** * 1 - * 32 * * : * I [25]: 1 * * rotate_imm: [11:8] * immed_8: [7:0] * imm32 * * imm32 = rotateRight(immed_8, rotate_imm * 2) * * @param inst ARM * @return */ public int getShifterOperandImm(Instruction inst) { int rotR = (inst.getInst() >> 8) & 0xf; int imm8 = inst.getInst() & 0xff; return Integer.rotateRight(imm8, rotR * 2); } /** * 1 - * * * : * I [25]: 0 * [4]: 0 * * : * [6:4] * 0b000: - * 0b000: - * 0b010: - * 0b100: - * 0b110: - * 0b110: - * * @param inst ARM * @return */ public int getShifterOperandImmShift(Instruction inst) { int shift_imm = (inst.getInst() >> 7) & 0x1f; int shift = (inst.getInst() >> 5) & 0x3; int rm = inst.getRmField(); switch (shift) { case 0: if (shift_imm == 0) { return getReg(rm); } else { return getReg(rm) << shift_imm; } case 1: if (shift_imm == 0) { return 0; } else { return getReg(rm) >>> shift_imm; } case 2: if (shift_imm == 0) { if (BitOp.getBit(getReg(rm), 31)) { return 0xffffffff; } else { return 0; } } else { return getReg(rm) >> shift_imm; } case 3: if (shift_imm == 0) { if (getCPSR_C()) { return (1 << 31) | (getReg(rm) >>> 1); } else { return getReg(rm) >>> 1; } } else { return Integer.rotateRight(getReg(rm), shift_imm); } default: //do nothing break; } throw new IllegalArgumentException("Unknown Imm Shift " + String.format("0x%08x, shift:%d.", inst.getInst(), shift)); } public int getShifterOperandRegShift(Instruction inst) { //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); } /** * 1 - * * @param inst ARM * @return true false */ public boolean getShifterCarry(Instruction inst) { boolean i = inst.getIBit(); boolean b7 = inst.getBit(7); boolean b4 = inst.getBit(4); if (i) { //32bits return getShifterCarryImm(inst); } else if (!b4) { return getShifterCarryImmShift(inst); } else if (b4 && !b7) { return getShifterCarryRegShift(inst); } else { throw new IllegalArgumentException("Unknown shifter_operand " + String.format("0x%08x, I:%b, b7:%b, b4:%b.", inst.getInst(), i, b7, b4)); } } /** * 1 - * 32 * * @param inst ARM * @return true false */ public boolean getShifterCarryImm(Instruction inst) { int rotR = (inst.getInst() >> 8) & 0xf; if (rotR == 0) { return getCPSR_C(); } else { return BitOp.getBit(getShifterOperandImm(inst), 31); } } /** * 1 - * * * : * I [25]: 0 * [4]: 0 * * : * [6:4] * 0b000: - * 0b000: - * 0b010: - * 0b100: - * 0b110: - * 0b110: - * * @param inst ARM * @return true false */ public boolean getShifterCarryImmShift(Instruction inst) { int shift_imm = (inst.getInst() >> 7) & 0x1f; int shift = (inst.getInst() >> 5) & 0x3; int rm = inst.getRmField(); switch (shift) { case 0: if (shift_imm == 0) { return getCPSR_C(); } else { return BitOp.getBit(getReg(rm), 32 - shift_imm); } case 1: if (shift_imm == 0) { return BitOp.getBit(getReg(rm), 31); } else { return BitOp.getBit(getReg(rm), shift_imm - 1); } case 2: if (shift_imm == 0) { return BitOp.getBit(getReg(rm), 31); } else { return BitOp.getBit(getReg(rm), shift_imm - 1); } case 3: if (shift_imm == 0) { return BitOp.getBit(getReg(rm), 0); } else { return BitOp.getBit(getReg(rm), shift_imm - 1); } default: //do nothing break; } throw new IllegalArgumentException("Unknown Imm Shift " + String.format("0x%08x, shift:%d.", inst.getInst(), shift)); } public boolean getShifterCarryRegShift(Instruction inst) { //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); } /** * 1 - * * @param inst ARM * @return */ public String getShifterOperandName(Instruction inst) { boolean i = inst.getIBit(); boolean b7 = inst.getBit(7); boolean b4 = inst.getBit(4); if (i) { //32bits return getShifterOperandImm32Name(inst); } else if (!b4) { return getShifterOperandImmShiftName(inst); } else if (b4 && !b7) { return getShifterOperandRegShiftName(inst); } else { throw new IllegalArgumentException("Unknown shifter_operand " + String.format("0x%08x, I:%b, b7:%b, b4:%b.", inst.getInst(), i, b7, b4)); } } /** * 1 - * 32 * * @param inst * @return */ public String getShifterOperandImm32Name(Instruction inst) { int imm32 = getShifterOperandImm(inst); return String.format("#%d ; 0x%x", imm32, imm32); } /** * 1 - * * * : * I [25]: 0 * [4]: 0 * * : * [6:4] * 0b000: - * 0b000: - * 0b010: - * 0b100: - * 0b110: - * 0b110: - * * @param inst ARM * @return */ public String getShifterOperandImmShiftName(Instruction inst) { int shift_imm = (inst.getInst() >> 7) & 0x1f; int shift = (inst.getInst() >> 5) & 0x3; int rm = inst.getRmField(); switch (shift) { case 0: if (shift_imm == 0) { return getRegName(rm); } else { return String.format("%s, lsl getRegName(rm), shift_imm); } case 1: return String.format("%s, lsr getRegName(rm), shift_imm); case 2: return String.format("%s, asr getRegName(rm), shift_imm); case 3: if (shift_imm == 0) { return String.format("%s, rrx", getRegName(rm)); } else { return String.format("%s, ror getRegName(rm), shift_imm); } default: //do nothing break; } throw new IllegalArgumentException("Unknown Imm Shift " + String.format("0x%08x, shift:%d.", inst.getInst(), shift)); } public String getShifterOperandRegShiftName(Instruction inst) { //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); } /** * 2 - / * * * I * I=0 * I=1 * * * * * * * * @param inst ARM * @return */ public int getOffsetAddress(Instruction inst) { boolean i = inst.getIBit(); boolean u = inst.getBit(23); int rn = inst.getRnField(); int shift_imm = (inst.getInst() >> 7) & 0x1f; int shift = (inst.getInst() >> 5) & 0x3; int offset; if (!i) { //12bits offset = getOffsetAddressImm(inst); } else if (shift_imm == 0 && shift == 0) { offset = getOffsetAddressReg(inst); } else { offset = getOffsetAddressScaled(inst); } if (!u) { offset = -offset; } return getReg(rn) + offset; } /** * 2 - / * 12bits * * @param inst ARM * @return */ public int getOffsetAddressImm(Instruction inst) { int offset12 = inst.getInst() & 0xfff; return offset12; } /** * 2 - / * * * 1 - * shifter_operand * * @param inst ARM * @return */ public int getOffsetAddressReg(Instruction inst) { return getShifterOperandImmShift(inst); } /** * 2 - / * * * 1 - * shifter_operand * * @param inst ARM * @return */ public int getOffsetAddressScaled(Instruction inst) { return getShifterOperandImmShift(inst); } /** * 2 - / * * * I * I=0 * I=1 * * @param inst ARM * @return */ public String getOffsetAddressName(Instruction inst) { boolean i = inst.getIBit(); boolean p = inst.getBit(24); boolean u = inst.getBit(23); boolean b = inst.getBit(22); boolean w = inst.getBit(21); int rn = inst.getRnField(); int shift_imm = (inst.getInst() >> 7) & 0x1f; int shift = (inst.getInst() >> 5) & 0x3; int rm = inst.getRmField(); String strOffset; if (!i) { //12bits return getOffsetAddressImmName(inst); } else if (shift_imm == 0 && shift == 0) { strOffset = getOffsetAddressRegName(inst); } else { strOffset = getOffsetAddressScaledName(inst); } if (p && !w) { return String.format("[%s, %s%s]", getRegName(rn), (u) ? "" : "-", strOffset); } else if (p && w) { return String.format("[%s, %s%s]!", getRegName(rn), (u) ? "" : "-", strOffset); } else if (!p) { return String.format("[%s], %s%s", getRegName(rn), (u) ? "" : "-", strOffset); } else { throw new IllegalArgumentException("Illegal P,W bits " + String.format("p:%b, w:%b.", p, w)); } } /** * 2 - / * 12bits * * * * # * 16 * * @param inst ARM * @return */ public String getOffsetAddressImmName(Instruction inst) { boolean p = inst.getBit(24); boolean u = inst.getBit(23); boolean b = inst.getBit(22); boolean w = inst.getBit(21); int rn = inst.getRnField(); int offset12 = inst.getInst() & 0xfff; if (p && !w) { return String.format("[%s, #%s%d] ; 0x%x", getRegName(rn), (u) ? "" : "-", offset12, offset12); } else if (p && w) { return String.format("[%s, #%s%d]! ; 0x%x", getRegName(rn), (u) ? "" : "-", offset12, offset12); } else if (!p) { return String.format("[%s], #%s%d ; 0x%x", getRegName(rn), (u) ? "" : "-", offset12, offset12); } else { throw new IllegalArgumentException("Illegal P,W bits " + String.format("p:%b, w:%b.", p, w)); } } /** * 2 - / * * * 1 - * shifter_operand * * @param inst ARM * @return */ public String getOffsetAddressRegName(Instruction inst) { return getShifterOperandImmShiftName(inst); } /** * 2 - / * * * 1 - * shifter_operand * * @param inst ARM * @return */ public String getOffsetAddressScaledName(Instruction inst) { return getShifterOperandImmShiftName(inst); } /** * 3 - / * * * @param inst ARM * @return */ public int getOffsetHalf(Instruction inst) { boolean u = inst.getBit(23); boolean b = inst.getBit(22); int rn = inst.getRnField(); int offset; if (b) { offset = getOffsetHalfImm(inst); } else { offset = getOffsetHalfReg(inst); } if (!u) { offset = -offset; } return getReg(rn) + offset; } /** * 3 - / * / * * @param inst ARM * @return */ public int getOffsetHalfImm(Instruction inst) { int immh = (inst.getInst() >> 8) & 0xf; int imml = inst.getInst() & 0xf; return (immh << 4) | imml; } /** * 3 - / * / * * @param inst ARM * @return */ public int getOffsetHalfReg(Instruction inst) { int rm = inst.getRmField(); return getReg(rm); } /** * 3 - / * * * @param inst ARM * @return */ public String getOffsetHalfName(Instruction inst) { boolean b = inst.getBit(22); if (b) { return getOffsetHalfImmName(inst); } else { return getOffsetHalfRegName(inst); } } /** * 3 - / * / * * @param inst ARM * @return */ public String getOffsetHalfImmName(Instruction inst) { boolean p = inst.getBit(24); boolean u = inst.getBit(23); boolean w = inst.getBit(21); int rn = inst.getRnField(); int imm8 = getOffsetHalfImm(inst); if (p && !w) { return String.format("[%s, #%s%d] ; 0x%x", getRegName(rn), (u) ? "" : "-", imm8, imm8); } else if (p && w) { return String.format("[%s, #%s%d]! ; 0x%x", getRegName(rn), (u) ? "" : "-", imm8, imm8); } else if (!p) { return String.format("[%s], #%s%d ; 0x%x", getRegName(rn), (u) ? "" : "-", imm8, imm8); } else { throw new IllegalArgumentException("Illegal P,W bits " + String.format("p:%b, w:%b.", p, w)); } } /** * 3 - / * / * * @param inst ARM * @return */ public String getOffsetHalfRegName(Instruction inst) { boolean p = inst.getBit(24); boolean u = inst.getBit(23); boolean w = inst.getBit(21); int rn = inst.getRnField(); int rm = inst.getRmField(); if (p && !w) { return String.format("[%s, %s%s]", getRegName(rn), (u) ? "" : "-", getRegName(rm)); } else if (p && w) { return String.format("[%s, %s%s]!", getRegName(rn), (u) ? "" : "-", getRegName(rm)); } else if (!p) { return String.format("[%s], %s%s", getRegName(rn), (u) ? "" : "-", getRegName(rm)); } else { throw new IllegalArgumentException("Illegal P,W bits " + String.format("p:%b, w:%b.", p, w)); } } /** * 4 - / * * * @param pu P, U * @param rn * @param rlist * @return */ public int getRegistersStartAddress(int pu, int rn, int rlist) { switch (pu) { case Instruction.PU_ADDR4_IA: return getReg(rn); case Instruction.PU_ADDR4_IB: return getReg(rn) + 4; case Instruction.PU_ADDR4_DA: return getReg(rn) - (Integer.bitCount(rlist) * 4) + 4; case Instruction.PU_ADDR4_DB: return getReg(rn) - (Integer.bitCount(rlist) * 4); default: //do nothing break; } throw new IllegalArgumentException("Illegal PU field " + pu + "."); } /** * 4 - / * * * @param pu P, U * @param rlist * @return */ public int getRegistersLength(int pu, int rlist) { switch (pu) { case Instruction.PU_ADDR4_IA: case Instruction.PU_ADDR4_IB: return Integer.bitCount(rlist) * 4; case Instruction.PU_ADDR4_DA: case Instruction.PU_ADDR4_DB: return -(Integer.bitCount(rlist) * 4); default: //do nothing break; } throw new IllegalArgumentException("Illegal PU field " + pu + "."); } /** * * * @param inst ARM * @param exec true false */ public void executeMrs(Instruction inst, boolean exec) { boolean r = inst.getBit(22); int sbo = (inst.getInst() >> 16) & 0xf; int rd = inst.getRdField(); int dest; if (!exec) { printDisasm(inst, String.format("mrs%s", inst.getCondFieldName()), String.format("%s, %s", getRegName(rd), (r) ? "spsr" : "cpsr")); return; } if (!inst.satisfiesCond(getCPSR())) { return; } if (sbo != 0xf) { System.out.println("Warning: Illegal instruction, " + String.format("mrs SBO[19:16](0x%01x) != 0xf.", sbo)); } if (r) { dest = getSPSR(); } else { dest = getCPSR(); } setReg(rd, dest); } /** * * * @param inst ARM * @param exec true false */ public void executeMsr(Instruction inst, boolean exec) { boolean i = inst.getIBit(); boolean r = inst.getBit(22); boolean mask_f = inst.getBit(19); boolean mask_s = inst.getBit(18); boolean mask_x = inst.getBit(17); boolean mask_c = inst.getBit(16); int sbo = (inst.getInst() >> 12) & 0xf; int opr = getShifterOperand(inst); int dest, m = 0; if (!exec) { printDisasm(inst, String.format("msr%s", inst.getCondFieldName()), String.format("%s_%s%s%s%s, %s", (r) ? "SPSR" : "CPSR", (mask_f) ? "f" : "", (mask_s) ? "s" : "", (mask_x) ? "x" : "", (mask_c) ? "c" : "", getShifterOperandName(inst))); return; } if (!inst.satisfiesCond(getCPSR())) { return; } if (sbo != 0xf) { System.out.println("Warning: Illegal instruction, " + String.format("msr SBO[15:12](0x%01x) != 0xf.", sbo)); } if (!r) { dest = getCPSR(); } else { dest = getSPSR(); } if (mask_c) { m |= 0x000000ff; } if (mask_x) { m |= 0x0000ff00; } if (mask_s) { m |= 0x00ff0000; } if (mask_f) { m |= 0xff000000; } dest &= ~m; dest |= opr & m; if (!r) { setCPSR(dest); } else { setSPSR(dest); } } /** * * * * and, eor, sub, rsb, * add, adc, sbc, rsc, * tst, teq, cmp, cmn, * orr, mov, bic, mvn, * * @param inst ARM * @param exec true false * @param id S ID */ public void executeALU(Instruction inst, boolean exec, int id) { boolean s = inst.getSBit(); int rn = inst.getRnField(); int rd = inst.getRdField(); String strInst, strOperand; if (!exec) { switch (id) { case Instruction.OPCODE_S_ADC: case Instruction.OPCODE_S_ADD: case Instruction.OPCODE_S_AND: case Instruction.OPCODE_S_BIC: case Instruction.OPCODE_S_EOR: case Instruction.OPCODE_S_ORR: case Instruction.OPCODE_S_RSB: case Instruction.OPCODE_S_RSC: case Instruction.OPCODE_S_SBC: case Instruction.OPCODE_S_SUB: //with S bit strInst = String.format("%s%s%s", inst.getOpcodeFieldName(), inst.getCondFieldName(), (s) ? "s" : ""); //rd, rn, shifter_operand strOperand = String.format("%s, %s, %s", getRegName(rd), getRegName(rn), getShifterOperandName(inst)); break; case Instruction.OPCODE_S_MOV: case Instruction.OPCODE_S_MVN: //with S bit strInst = String.format("%s%s%s", inst.getOpcodeFieldName(), inst.getCondFieldName(), (s) ? "s" : ""); //rd, shifter_operand strOperand = String.format("%s, %s", getRegName(rd), getShifterOperandName(inst)); break; case Instruction.OPCODE_S_CMN: case Instruction.OPCODE_S_CMP: case Instruction.OPCODE_S_TEQ: case Instruction.OPCODE_S_TST: //S bit is 1 strInst = String.format("%s%s", inst.getOpcodeFieldName(), inst.getCondFieldName()); //rn, shifter_operand strOperand = String.format("%s, %s", getRegName(rn), getShifterOperandName(inst)); break; default: throw new IllegalArgumentException("Unknown opcode S-bit ID " + String.format("%d.", id)); } printDisasm(inst, strInst, strOperand); return; } if (!inst.satisfiesCond(getCPSR())) { return; } switch (id) { case Instruction.OPCODE_S_AND: executeALUAnd(inst, exec); break; case Instruction.OPCODE_S_EOR: //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); //break; case Instruction.OPCODE_S_SUB: executeALUSub(inst, exec); break; case Instruction.OPCODE_S_RSB: executeALURsb(inst, exec); break; case Instruction.OPCODE_S_ADD: executeALUAdd(inst, exec); break; case Instruction.OPCODE_S_ADC: //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); //break; case Instruction.OPCODE_S_SBC: //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); //break; case Instruction.OPCODE_S_RSC: //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); //break; case Instruction.OPCODE_S_TST: executeALUTst(inst, exec); break; case Instruction.OPCODE_S_TEQ: executeALUTeq(inst, exec); break; case Instruction.OPCODE_S_CMP: executeALUCmp(inst, exec); break; case Instruction.OPCODE_S_CMN: executeALUCmn(inst, exec); break; case Instruction.OPCODE_S_ORR: executeALUOrr(inst, exec); break; case Instruction.OPCODE_S_MOV: executeALUMov(inst, exec); break; case Instruction.OPCODE_S_BIC: executeALUBic(inst, exec); break; case Instruction.OPCODE_S_MVN: executeALUMvn(inst, exec); break; default: throw new IllegalArgumentException("Unknown opcode S-bit ID " + String.format("%d.", id)); } } /** * * * @param inst ARM * @param exec true false */ public void executeALUAnd(Instruction inst, boolean exec) { boolean s = inst.getSBit(); int rn = inst.getRnField(); int rd = inst.getRdField(); int opr = getShifterOperand(inst); int left, right, dest; left = getReg(rn); right = opr; dest = left & right; if (s && rd == 15) { setCPSR(getSPSR()); } else if (s) { setCPSR_N(BitOp.getBit(dest, 31)); setCPSR_Z(dest == 0); setCPSR_C(getShifterCarry(inst)); //V flag is unaffected } setReg(rd, dest); } /** * * * @param inst ARM * @param exec true false */ public void executeALUSub(Instruction inst, boolean exec) { boolean s = inst.getSBit(); int rn = inst.getRnField(); int rd = inst.getRdField(); int opr = getShifterOperand(inst); int left, right, dest; left = getReg(rn); right = opr; dest = left - right; if (s && rd == 15) { setCPSR(getSPSR()); } else if (s) { setCPSR_N(BitOp.getBit(dest, 31)); setCPSR_Z(dest == 0); setCPSR_C(!borrowFrom(left, right)); setCPSR_V(overflowFrom(left, right, false)); } setReg(rd, dest); } /** * * * @param inst ARM * @param exec true false */ public void executeALURsb(Instruction inst, boolean exec) { boolean s = inst.getSBit(); int rn = inst.getRnField(); int rd = inst.getRdField(); int opr = getShifterOperand(inst); int left, right, dest; left = opr; right = getReg(rn); dest = left - right; if (s && rd == 15) { setCPSR(getSPSR()); } else if (s) { setCPSR_N(BitOp.getBit(dest, 31)); setCPSR_Z(dest == 0); setCPSR_C(!borrowFrom(left, right)); setCPSR_V(overflowFrom(left, right, false)); } setReg(rd, dest); } /** * * * @param inst ARM * @param exec true false */ public void executeALUAdd(Instruction inst, boolean exec) { boolean s = inst.getSBit(); int rn = inst.getRnField(); int rd = inst.getRdField(); int opr = getShifterOperand(inst); int left, right, dest; left = getReg(rn); right = opr; dest = left + right; if (s && rd == 15) { setCPSR(getSPSR()); } else if (s) { setCPSR_N(BitOp.getBit(dest, 31)); setCPSR_Z(dest == 0); setCPSR_C(carryFrom(left, right)); setCPSR_V(overflowFrom(left, right, true)); } setReg(rd, dest); } /** * * * @param inst ARM * @param exec true false */ public void executeALUTst(Instruction inst, boolean exec) { int rn = inst.getRnField(); int sbz = (inst.getInst() >> 12) & 0xf; int opr = getShifterOperand(inst); int left, right, dest; if (sbz != 0x0) { System.out.println("Warning: Illegal instruction, " + String.format("tst SBZ[15:12](0x%01x) != 0x0.", sbz)); } left = getReg(rn); right = opr; dest = left & right; setCPSR_N(BitOp.getBit(dest, 31)); setCPSR_Z(dest == 0); setCPSR_C(getShifterCarry(inst)); //V flag is unaffected } /** * * * @param inst ARM * @param exec true false */ public void executeALUTeq(Instruction inst, boolean exec) { int rn = inst.getRnField(); int sbz = (inst.getInst() >> 12) & 0xf; int opr = getShifterOperand(inst); int left, right, dest; if (sbz != 0x0) { System.out.println("Warning: Illegal instruction, " + String.format("teq SBZ[15:12](0x%01x) != 0x0.", sbz)); } left = getReg(rn); right = opr; dest = left ^ right; setCPSR_N(BitOp.getBit(dest, 31)); setCPSR_Z(dest == 0); setCPSR_C(getShifterCarry(inst)); //V flag is unaffected } /** * * * @param inst ARM * @param exec true false */ public void executeALUCmp(Instruction inst, boolean exec) { int rn = inst.getRnField(); int sbz = (inst.getInst() >> 12) & 0xf; int opr = getShifterOperand(inst); int left, right, dest; if (sbz != 0x0) { System.out.println("Warning: Illegal instruction, " + String.format("cmp SBZ[15:12](0x%01x) != 0x0.", sbz)); } left = getReg(rn); right = opr; dest = left - right; setCPSR_N(BitOp.getBit(dest, 31)); setCPSR_Z(dest == 0); setCPSR_C(!borrowFrom(left, right)); setCPSR_V(overflowFrom(left, right, false)); } /** * * * @param inst ARM * @param exec true false */ public void executeALUCmn(Instruction inst, boolean exec) { int rn = inst.getRnField(); int sbz = (inst.getInst() >> 12) & 0xf; int opr = getShifterOperand(inst); int left, right, dest; if (sbz != 0x0) { System.out.println("Warning: Illegal instruction, " + String.format("cmp SBZ[15:12](0x%01x) != 0x0.", sbz)); } left = getReg(rn); right = opr; dest = left + right; setCPSR_N(BitOp.getBit(dest, 31)); setCPSR_Z(dest == 0); setCPSR_C(carryFrom(left, right)); setCPSR_V(overflowFrom(left, right, true)); } /** * * * @param inst ARM * @param exec true false */ public void executeALUOrr(Instruction inst, boolean exec) { boolean s = inst.getSBit(); int rn = inst.getRnField(); int rd = inst.getRdField(); int opr = getShifterOperand(inst); int left, right, dest; left = getReg(rn); right = opr; dest = left | right; if (s && rd == 15) { setCPSR(getSPSR()); } else if (s) { setCPSR_N(BitOp.getBit(dest, 31)); setCPSR_Z(dest == 0); setCPSR_C(getShifterCarry(inst)); //V flag is unaffected } setReg(rd, dest); } /** * * * @param inst ARM * @param exec true false */ public void executeALUMov(Instruction inst, boolean exec) { boolean s = inst.getSBit(); int sbz = (inst.getInst() >> 16) & 0xf; int rd = inst.getRdField(); int opr = getShifterOperand(inst); int right, dest; if (sbz != 0x0) { System.out.println("Warning: Illegal instruction, " + String.format("mov SBZ[19:16](0x%01x) != 0x0.", sbz)); } right = opr; dest = right; if (s && rd == 15) { setCPSR(getSPSR()); } else if (s) { setCPSR_N(BitOp.getBit(dest, 31)); setCPSR_Z(dest == 0); setCPSR_C(getShifterCarry(inst)); //V flag is unaffected } setReg(rd, dest); } /** * * * @param inst ARM * @param exec true false */ public void executeALUBic(Instruction inst, boolean exec) { boolean s = inst.getSBit(); int rn = inst.getRnField(); int rd = inst.getRdField(); int opr = getShifterOperand(inst); int left, right, dest; left = getReg(rn); right = opr; dest = left & ~right; if (s && rd == 15) { setCPSR(getSPSR()); } else if (s) { setCPSR_N(BitOp.getBit(dest, 31)); setCPSR_Z(dest == 0); setCPSR_C(getShifterCarry(inst)); //V flag is unaffected } setReg(rd, dest); } /** * * * @param inst ARM * @param exec true false */ public void executeALUMvn(Instruction inst, boolean exec) { boolean s = inst.getSBit(); int rd = inst.getRdField(); int opr = getShifterOperand(inst); int left, right, dest; right = opr; dest = ~right; if (s && rd == 15) { setCPSR(getSPSR()); } else if (s) { setCPSR_N(BitOp.getBit(dest, 31)); setCPSR_Z(dest == 0); setCPSR_C(getShifterCarry(inst)); //V flag is unaffected } setReg(rd, dest); } public void executeLdrt(Instruction inst, boolean exec) { //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); } public void executeLdrbt(Instruction inst, boolean exec) { //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); } public void executeLdrb(Instruction inst, boolean exec) { boolean p = inst.getBit(24); boolean w = inst.getBit(21); int rn = inst.getRnField(); int rd = inst.getRdField(); int offset = getOffsetAddress(inst); int vaddr, paddr, value; if (!exec) { printDisasm(inst, String.format("ldr%sb", inst.getCondFieldName()), String.format("%s, %s", getRegName(rd), getOffsetAddressName(inst))); return; } if (!inst.satisfiesCond(getCPSR())) { return; } if (p) { vaddr = offset; } else { vaddr = getReg(rn); } paddr = getMMU().translate(vaddr, false); value = (int)(read8(paddr)) & 0xff; setReg(rd, value); if (!p || w) { // !(p && !w) P, W setReg(rn, offset); } } public void executeLdr(Instruction inst, boolean exec) { boolean p = inst.getBit(24); boolean w = inst.getBit(21); int rn = inst.getRnField(); int rd = inst.getRdField(); int offset = getOffsetAddress(inst); int vaddr, paddr, rot, value; if (!exec) { printDisasm(inst, String.format("ldr%s", inst.getCondFieldName()), String.format("%s, %s", getRegName(rd), getOffsetAddressName(inst))); return; } if (!inst.satisfiesCond(getCPSR())) { return; } if (p) { vaddr = offset; } else { vaddr = getReg(rn); } rot = vaddr & 0x3; paddr = getMMU().translate(vaddr, false); value = read32(paddr); switch (rot) { case 0: //do nothing break; case 1: value = Integer.rotateRight(value, 8); break; case 2: value = Integer.rotateRight(value, 16); break; case 3: value = Integer.rotateRight(value, 24); break; default: throw new IllegalArgumentException("Illegal address " + String.format("inst:0x%08x, rot:%d.", inst.getInst(), rot)); } if (rd == 15) { setPC(value & 0xfffffffe); setCPSR_T(BitOp.getBit(value, 0)); } else { setReg(rd, value); } if (!p || w) { // !(p && !w) P, W setReg(rn, offset); } } public void executePld(Instruction inst, boolean exec) { boolean r = inst.getBit(22); if (!exec) { printDisasm(inst, String.format("pld%s", (r) ? "" : "w"), String.format("%s", getOffsetAddressName(inst))); return; } //pld cond NV //do noting } public void executeStrt(Instruction inst, boolean exec) { //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); } public void executeStrbt(Instruction inst, boolean exec) { //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); } public void executeStrb(Instruction inst, boolean exec) { boolean p = inst.getBit(24); boolean w = inst.getBit(21); int rn = inst.getRnField(); int rd = inst.getRdField(); int offset = getOffsetAddress(inst); int vaddr, paddr; if (!exec) { printDisasm(inst, String.format("str%sb", inst.getCondFieldName()), String.format("%s, %s", getRegName(rd), getOffsetAddressName(inst))); return; } if (!inst.satisfiesCond(getCPSR())) { return; } if (p) { vaddr = offset; } else { vaddr = getReg(rn); } paddr = getMMU().translate(vaddr, false); write8(paddr, (byte) getReg(rd)); if (!p || w) { // !(p && !w) P, W setReg(rn, offset); } } public void executeStr(Instruction inst, boolean exec) { boolean p = inst.getBit(24); boolean w = inst.getBit(21); int rn = inst.getRnField(); int rd = inst.getRdField(); int offset = getOffsetAddress(inst); int vaddr, paddr; if (!exec) { printDisasm(inst, String.format("str%s", inst.getCondFieldName()), String.format("%s, %s", getRegName(rd), getOffsetAddressName(inst))); return; } if (!inst.satisfiesCond(getCPSR())) { return; } if (p) { vaddr = offset; } else { vaddr = getReg(rn); } paddr = getMMU().translate(vaddr, false); write32(paddr, getReg(rd)); if (!p || w) { // !(p && !w) P, W setReg(rn, offset); } } public void executeStrh(Instruction inst, boolean exec) { boolean p = inst.getBit(24); boolean w = inst.getBit(21); int rn = inst.getRnField(); int rd = inst.getRdField(); int offset = getOffsetHalf(inst); int vaddr, paddr; if (!exec) { printDisasm(inst, String.format("str%sh", inst.getCondFieldName()), String.format("%s, %s", getRegName(rd), getOffsetHalfName(inst))); return; } if (!inst.satisfiesCond(getCPSR())) { return; } if (p) { vaddr = offset; } else { vaddr = getReg(rn); } paddr = getMMU().translate(vaddr, false); write16(paddr, (short)getReg(rd)); if (!p || w) { // !(p && !w) P, W setReg(rn, offset); } } public void executeLdm1(Instruction inst, boolean exec) { boolean w = inst.getBit(21); int rn = inst.getRnField(); int rlist = inst.getRegListField(); int vaddr, paddr, len; if (!exec) { printDisasm(inst, String.format("ldm%s%s", inst.getCondFieldName(), inst.getPUFieldName()), String.format("%s%s, {%s}", getRegName(rn), (w) ? "!" : "", inst.getRegListFieldName())); return; } if (!inst.satisfiesCond(getCPSR())) { return; } //r15 vaddr = getRegistersStartAddress(inst.getPUField(), rn, rlist); len = getRegistersLength(inst.getPUField(), rlist); for (int i = 0; i < 15; i++) { if ((rlist & (1 << i)) == 0) { continue; } paddr = getMMU().translate(vaddr, false); setReg(i, read32(paddr)); vaddr += 4; } //r15 if (BitOp.getBit(rlist, 15)) { int v; paddr = getMMU().translate(vaddr, false); v = read32(paddr); setPC(v & 0xfffffffe); setCPSR_T(BitOp.getBit(v, 0)); vaddr += 4; } if (w) { setReg(rn, getReg(rn) + len); } } public void executeLdm2(Instruction inst, boolean exec) { //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); } public void executeLdm3(Instruction inst, boolean exec) { //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); } public void executeStm1(Instruction inst, boolean exec) { int pu = inst.getPUField(); boolean w = inst.getBit(21); int rn = inst.getRnField(); int rlist = inst.getRegListField(); int vaddr, paddr, len; if (!exec) { printDisasm(inst, String.format("stm%s%s", inst.getCondFieldName(), inst.getPUFieldName()), String.format("%s%s, {%s}", getRegName(rn), (w) ? "!" : "", inst.getRegListFieldName())); return; } if (!inst.satisfiesCond(getCPSR())) { return; } vaddr = getRegistersStartAddress(pu, rn, rlist); len = getRegistersLength(pu, rlist); for (int i = 0; i < 16; i++) { if ((rlist & (1 << i)) == 0) { continue; } paddr = getMMU().translate(vaddr, false); write32(paddr, getReg(i)); vaddr += 4; } if (w) { setReg(rn, getReg(rn) + len); } } public void executeStm2(Instruction inst, boolean exec) { //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); } public void executeBl(Instruction inst, boolean exec) { boolean l = inst.getBit(24); int imm24 = inst.getInst() & 0xffffff; int simm24 = (int)signext(imm24, 24) << 2; if (!exec) { printDisasm(inst, String.format("b%s%s", (l) ? "l" : "", inst.getCondFieldName()), String.format("%08x", getPC() + simm24)); return; } if (!inst.satisfiesCond(getCPSR())) { return; } if (l) { setReg(14, getPC() - 4); } jumpRel(simm24); } public void executeBlx1(Instruction inst, boolean exec) { boolean h = inst.getBit(24); int vh = BitOp.toBit(h) << 1; int imm24 = inst.getInst() & 0xffffff; int simm24 = (int)signext(imm24, 24) << 2; if (!exec) { printDisasm(inst, String.format("blx"), String.format("%08x", getPC() + simm24 + vh)); return; } //blx cond NV setReg(14, getPC() - 4); setCPSR(getCPSR() | 0x20); jumpRel(simm24 + vh); //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); } public void executeCdp(Instruction inst, boolean exec) { //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); } public void executeMcr(Instruction inst, boolean exec) { int opcode1 = (inst.getInst() >> 21) & 0x7; int crn = (inst.getInst() >> 16) & 0xf; int rd = inst.getRdField(); int cpnum = (inst.getInst() >> 8) & 0xf; int opcode2 = (inst.getInst() >> 5) & 0x7; int crm = inst.getInst() & 0xf; CoProc cp; int crid; if (!exec) { printDisasm(inst, String.format("mcr%s", inst.getCondFieldName()), String.format("%s, %d, %s, %s, %s, {%d}", getCoproc(cpnum).toString(), opcode1, getRegName(rd), getCoprocRegName(cpnum, crn), getCoprocRegName(cpnum, crm), opcode2)); return; } if (!inst.satisfiesCond(getCPSR())) { return; } cp = getCoproc(cpnum); if (cp == null) { exceptionUndefined("Unimplemented coprocessor, " + String.format("p%d selected.", cpnum)); return; } crid = CoProc.getCRegID(crn, opcode1, crm, opcode2); if (!cp.validCRegNumber(crid)) { exceptionUndefined("Unimplemented coprocessor register, " + String.format("p%d id(%08x, crn:%d, opc1:%d, crm:%d, opc2:%d) selected.", cpnum, crid, crn, opcode1, crm, opcode2)); return; } cp.setCReg(crid, getReg(rd)); } public void executeMrc(Instruction inst, boolean exec) { int opcode1 = (inst.getInst() >> 21) & 0x7; int crn = (inst.getInst() >> 16) & 0xf; int rd = inst.getRdField(); int cpnum = (inst.getInst() >> 8) & 0xf; int opcode2 = (inst.getInst() >> 5) & 0x7; int crm = inst.getInst() & 0xf; CoProc cp; int crid, crval, rval; if (!exec) { printDisasm(inst, String.format("mrc%s", inst.getCondFieldName()), String.format("%s, %d, %s, %s, %s, {%d}", getCoproc(cpnum).toString(), opcode1, getRegName(rd), getCoprocRegName(cpnum, crn), getCoprocRegName(cpnum, crm), opcode2)); return; } if (!inst.satisfiesCond(getCPSR())) { return; } cp = getCoproc(cpnum); if (cp == null) { exceptionUndefined("Unimplemented coprocessor, " + String.format("p%d selected.", cpnum)); return; } crid = CoProc.getCRegID(crn, opcode1, crm, opcode2); if (!cp.validCRegNumber(crid)) { exceptionUndefined("Unimplemented coprocessor register, " + String.format("p%d id(%08x, crn:%d, opc1:%d, crm:%d, opc2:%d) selected.", cpnum, crid, crn, opcode1, crm, opcode2)); return; } crval = cp.getCReg(crid); if (rd == 15) { //r15 r15 APSR N, Z, C, V rval = getSPSR(); rval &= ~0xf0000000; rval |= crval & 0xf0000000; setAPSR(rval); } else { setReg(rd, crval); } } public void executeSwi(Instruction inst, boolean exec) { //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); } public void executeUnd(Instruction inst, boolean exec) { if (!exec) { printDisasm(inst, String.format("und%s", inst.getCondFieldName()), ""); return; } exceptionPrefetch("Warning: Undefined instruction " + String.format("inst:0x%08x.", inst.getInst())); } /** * * * @param inst ARM * @param exec true false */ public void execute(Instruction inst, boolean exec) { int cond = inst.getCondField(); int subcode = inst.getSubCodeField(); switch (subcode) { case Instruction.SUBCODE_USEALU: executeSubALU(inst, exec); return; case Instruction.SUBCODE_LDRSTR: executeSubLdrStr(inst, exec); return; case Instruction.SUBCODE_LDMSTM: executeSubLdmStm(inst, exec); return; case Instruction.SUBCODE_COPSWI: executeSubCopSwi(inst, exec); return; default: //do nothing break; } throw new IllegalArgumentException("Unknown Subcode" + String.format("(%d).", subcode)); } /** * * * subcode = 0b00 * * @param inst ARM * @param exec true false */ public void executeSubALU(Instruction inst, boolean exec) { boolean i = inst.getIBit(); boolean b7 = inst.getBit(7); boolean b4 = inst.getBit(4); if (!i) { //b7, b4 // 0, 0: // 1, 0: // 0, 1: // 1, 1: if (!b4) { executeSubALUShiftImm(inst, exec); } else if (!b7 && b4) { executeSubALUShiftReg(inst, exec); } else { int cond = inst.getCondField(); boolean p = inst.getBit(24); int op = (inst.getInst() >> 5) & 0x3; if (cond != Instruction.COND_NV && !p && op == 0) { executeSubExtALU(inst, exec); } else { executeSubExtLdrStr(inst, exec); } } } else { executeSubALUImm(inst, exec); } } /** * * * * @param inst ARM * @param exec true false */ public void executeSubALUShiftImm(Instruction inst, boolean exec) { int id = inst.getOpcodeSBitShiftID(); switch (id) { case Instruction.OPCODE_S_OTH: executeSubALUShiftImmOther(inst, exec); break; default: executeALU(inst, exec, id); break; } } /** * * * * @param inst ARM * @param exec true false */ public void executeSubALUShiftReg(Instruction inst, boolean exec) { int id = inst.getOpcodeSBitShiftID(); switch (id) { case Instruction.OPCODE_S_OTH: //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); //break; default: executeALU(inst, exec, id); break; } } /** * * * * cond != NV * bit[27:24] = 0b0000 * bit[7:4] = 0b1001 * * @param inst ARM * @param exec true false */ public void executeSubExtALU(Instruction inst, boolean exec) { //U, B, W [23:21] int ubw = (inst.getInst() >> 21) & 0x7; switch (ubw) { case 1: //mla //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); //break; case 0: //mul //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); //break; case 7: //smlal //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); //break; case 6: //smull //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); //break; case 5: //umlal //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); //break; case 4: //umlul //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); //break; default: //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); } } /** * * * * cond != NV * bit[27:25] = 0b000 * bit[7] = 0b1 * bit[4] = 0b1 * * * * bit[24] = 0b0 * bit[6:5] = 0b00 * * @param inst ARM * @param exec true false */ public void executeSubExtLdrStr(Instruction inst, boolean exec) { boolean p = inst.getBit(24); //U, B, W [23:21] int ubw = (inst.getInst() >> 21) & 0x7; boolean l = inst.getBit(20); int op = (inst.getInst() >> 5) & 0x3; if (p && op == 0) { switch (ubw) { case 0: //swp //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); //break; case 1: //swpb //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); //break; default: //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); } } else if (op == 1) { if (l) { //ldrh //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); } else { //strh executeStrh(inst, exec); } } else if (op == 2) { if (l) { //ldrsb //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); } else { //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); } } else if (op == 3) { if (l) { //ldrsh //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); } else { //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); } } else { //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); } } /** * * * * * * * @param inst ARM * @param exec true false */ public void executeSubALUImm(Instruction inst, boolean exec) { int id = inst.getOpcodeSBitImmID(); switch (id) { case Instruction.OPCODE_S_MSR: executeMsr(inst, exec); break; case Instruction.OPCODE_S_UND: executeUnd(inst, exec); break; default: executeALU(inst, exec, id); break; } } public void executeSubALUShiftImmOther(Instruction inst, boolean exec) { int cond = inst.getCondField(); boolean b22 = BitOp.getBit(inst.getInst(), 22); boolean b21 = BitOp.getBit(inst.getInst(), 21); int type = (inst.getInst() >> 4) & 0xf; switch (type) { case 0x0: if (!b21) { //mrs executeMrs(inst, exec); } else { //msr executeMsr(inst, exec); } break; case 0x1: if (!b22 && b21) { //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); } else if (b22 && b21) { //clz //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); } else { executeUnd(inst, exec); } break; case 0x3: if (!b22 && b21) { //blx(2) //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); } else { executeUnd(inst, exec); } break; case 0x7: if (cond == Instruction.COND_AL && !b22 && b21) { //bkpt //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); } else { executeUnd(inst, exec); } break; default: //executeUnd(inst, exec); //break; //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); } } public void executeSubLdrStr(Instruction inst, boolean exec) { int cond = inst.getCondField(); boolean i = inst.getBit(25); boolean p = inst.getBit(24); boolean b = inst.getBit(22); boolean w = inst.getBit(21); boolean l = inst.getLBit(); int rd = inst.getRdField(); boolean b4 = inst.getBit(4); if (i && b4) { executeUnd(inst, exec); } else if (l) { if (!p && !b && w) { //ldrt executeLdrt(inst, exec); } else if (!p && b && w) { //ldrbt executeLdrbt(inst, exec); } else if (b) { if (cond == inst.COND_NV && p && !w && rd == 15) { //pld executePld(inst, exec); } else { //ldrb executeLdrb(inst, exec); } } else if (!b) { //ldr executeLdr(inst, exec); } else { throw new IllegalArgumentException("Illegal P,B,W bits " + String.format("p:%b, b:%b, w:%b.", p, b, w)); } } else if (!l) { if (!p && !b && w) { //strt executeStrt(inst, exec); } else if (!p && b && w) { //strbt executeStrbt(inst, exec); } else if (b) { //strb executeStrb(inst, exec); } else if (!b) { //str executeStr(inst, exec); } else { throw new IllegalArgumentException("Illegal P,B,W bits " + String.format("p:%b, b:%b, w:%b.", p, b, w)); } } else { throw new IllegalArgumentException("Illegal P,B,W,L bits " + String.format("p:%b, b:%b, w:%b, l:%b.", p, b, w, l)); } } /** * * * subcode = 0b10 * * @param inst ARM * @param exec true false */ public void executeSubLdmStm(Instruction inst, boolean exec) { int cond = inst.getCondField(); boolean b25 = inst.getBit(25); boolean l = inst.getLBit(); if (!b25) { if (cond == Instruction.COND_NV) { executeUnd(inst, exec); } else { if (l) { //ldm(1), ldm(2), ldm(3) executeSubLdm(inst, exec); } else { //stm(1), stm(2) executeSubStm(inst, exec); } } } else { if (cond == Instruction.COND_NV) { //blx executeBlx1(inst, exec); } else { //b, bl executeBl(inst, exec); } } } /** * * * subcode = 0b10 * * @param inst ARM * @param exec true false */ public void executeSubLdm(Instruction inst, boolean exec) { boolean s = inst.getBit(22); boolean b15 = inst.getBit(15); if (!s) { //ldm(1) executeLdm1(inst, exec); } else { if (!b15) { //ldm(2) executeLdm2(inst, exec); } else { //ldm(3) executeLdm3(inst, exec); } } } /** * * * subcode = 0b10 * * @param inst ARM * @param exec true false */ public void executeSubStm(Instruction inst, boolean exec) { boolean s = inst.getBit(22); boolean w = inst.getBit(21); if (!s) { //stm(1) executeStm1(inst, exec); } else { if (!w) { //stm(2) executeStm2(inst, exec); } else { executeUnd(inst, exec); } } } /** * * * subcode = 0b11 * * @param inst ARM * @param exec true false */ public void executeSubCopSwi(Instruction inst, boolean exec) { int cond = inst.getCondField(); int subsub = (inst.getInst() >> 24) & 0x3; boolean b20 = inst.getBit(20); boolean b4 = inst.getBit(4); switch (subsub) { case 0: case 1: //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); //break; case 2: if (!b4) { //cdp executeCdp(inst, exec); } else { if (!b20) { //mcr executeMcr(inst, exec); } else { //mrc executeMrc(inst, exec); } } return; case 3: if (cond == Instruction.COND_NV) { executeUnd(inst, exec); } else { //swi executeSwi(inst, exec); } return; default: //do nothing break; } throw new IllegalArgumentException("Illegal b25, b24 bits " + String.format("b25b24:%d.", subsub)); } public void step() { Instruction inst; int v, vaddr, paddr; //for debug int target_address = 0xc015dbb0; vaddr = getPC() - 8; paddr = getMMU().translate(vaddr, true); v = read32(paddr); inst = new Instruction(v); try { if (getPC() - 8 == target_address) { setPrintingDisasm(true); setPrintingRegs(true); } if (isDisasmMode()) { execute(inst, false); } if (isPrintingRegs()) { int a = 0; } execute(inst, true); } catch (IllegalArgumentException e) { System.out.printf("pc:%08x, inst:%08x, %s\n", getPC() - 8, inst.getInst(), e); printRegs(); //abort throw e; } nextPC(); } public void run() { while (true) { step(); } } /** * * * @param dbgmsg */ public void exceptionReset(String dbgmsg) { int spsrOrg; System.out.printf("Exception: Reset by '%s'.\n", dbgmsg); //cpsr spsrOrg = getCPSR(); //ARM setCPSR_Mode(MODE_SVC); setCPSR_T(false); setCPSR_F(true); setCPSR_I(true); //spsr cpsr setSPSR(spsrOrg); if (getStdCoProc().isHighVector()) { setPC(0xffff0000); } else { setPC(0x00000000); } } /** * * * * * * @param dbgmsg */ public void exceptionUndefined(String dbgmsg) { int pcOrg, spsrOrg; System.out.printf("Exception: Undefined by '%s'.\n", dbgmsg); //pc, cpsr pcOrg = getPC() - 4; spsrOrg = getCPSR(); //ARM setCPSR_Mode(MODE_UND); setCPSR_T(false); //F flag is not affected setCPSR_I(true); //lr, spsr pc, cpsr setReg(14, pcOrg); setSPSR(spsrOrg); if (getStdCoProc().isHighVector()) { setPC(0xffff0004); } else { setPC(0x00000004); } //tentative... //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); } /** * * * swi * * @param dbgmsg */ public void exceptionSoftware(String dbgmsg) { int pcOrg, spsrOrg; System.out.printf("Exception: Software by '%s'.\n", dbgmsg); //pc, cpsr pcOrg = getPC() - 4; spsrOrg = getCPSR(); //ARM setCPSR_Mode(MODE_SVC); setCPSR_T(false); //F flag is not affected setCPSR_I(true); //lr, spsr pc, cpsr setReg(14, pcOrg); setSPSR(spsrOrg); if (getStdCoProc().isHighVector()) { setPC(0xffff0008); } else { setPC(0x00000008); } //tentative... //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); } /** * * * * * @param dbgmsg */ public void exceptionPrefetch(String dbgmsg) { int pcOrg, spsrOrg; System.out.printf("Exception: Prefetch by '%s'.\n", dbgmsg); //pc, cpsr pcOrg = getPC() - 4; spsrOrg = getCPSR(); //ARM setCPSR_Mode(MODE_ABT); setCPSR_T(false); //F flag is not affected setCPSR_I(true); //lr, spsr pc, cpsr setReg(14, pcOrg); setSPSR(spsrOrg); if (getStdCoProc().isHighVector()) { setPC(0xffff000c); } else { setPC(0x0000000c); } //tentative... //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); } /** * * * * * @param dbgmsg */ public void exceptionData(String dbgmsg) { int pcOrg, spsrOrg; System.out.printf("Exception: Data by '%s'.\n", dbgmsg); //pc, cpsr pcOrg = getPC() - 4; spsrOrg = getCPSR(); //ARM setCPSR_Mode(MODE_ABT); setCPSR_T(false); //F flag is not affected setCPSR_I(true); //lr, spsr pc, cpsr setReg(14, pcOrg); setSPSR(spsrOrg); if (getStdCoProc().isHighVector()) { setPC(0xffff0010); } else { setPC(0x00000010); } //tentative... //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); } /** * * * IRQ * * @param dbgmsg */ public void exceptionIRQ(String dbgmsg) { int pcOrg, spsrOrg; System.out.printf("Exception: IRQ by '%s'.\n", dbgmsg); //pc, cpsr pcOrg = getPC() - 4; spsrOrg = getCPSR(); //IRQ ARM setCPSR_Mode(MODE_IRQ); setCPSR_T(false); //F flag is not affected setCPSR_I(true); //lr, spsr pc, cpsr setReg(14, pcOrg); setSPSR(spsrOrg); //IRQ if (getStdCoProc().isHighVector()) { setPC(0xffff0018); } else { setPC(0x00000018); } //tentative... //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); } /** * * * FIQ * * @param dbgmsg */ public void exceptionFIQ(String dbgmsg) { int pcOrg, spsrOrg; System.out.printf("Exception: FIQ by '%s'.\n", dbgmsg); //pc, cpsr pcOrg = getPC() - 4; spsrOrg = getCPSR(); //FIQ ARM setCPSR_Mode(MODE_FIQ); setCPSR_T(false); setCPSR_F(true); setCPSR_I(true); //lr, spsr pc, cpsr setReg(14, pcOrg); setSPSR(spsrOrg); //FIQ if (getStdCoProc().isHighVector()) { setPC(0xffff001c); } else { setPC(0x0000001c); } //tentative... //TODO: Not implemented throw new IllegalArgumentException("Sorry, not implemented."); } }
package com.jarvis.cache; import java.util.concurrent.ConcurrentHashMap; import org.apache.log4j.Logger; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import com.jarvis.cache.annotation.Cache; import com.jarvis.cache.annotation.CacheDelete; import com.jarvis.cache.annotation.CacheDeleteKey; import com.jarvis.cache.annotation.ExCache; import com.jarvis.cache.serializer.HessianSerializer; import com.jarvis.cache.serializer.ISerializer; import com.jarvis.cache.to.AutoLoadConfig; import com.jarvis.cache.to.AutoLoadTO; import com.jarvis.cache.to.CacheKeyTO; import com.jarvis.cache.to.CacheWrapper; import com.jarvis.cache.to.ProcessingTO; import com.jarvis.cache.type.CacheOpType; /** * * @author jiayu.qiu */ public abstract class AbstractCacheManager implements ICacheManager { private static final Logger logger=Logger.getLogger(AbstractCacheManager.class); // java.lang.NoSuchMethodError:java.util.Map.putIfAbsent private final ConcurrentHashMap<String, ProcessingTO> processing=new ConcurrentHashMap<String, ProcessingTO>(); private AutoLoadHandler autoLoadHandler; private String namespace; /** * Hessian2 */ private ISerializer<Object> serializer=new HessianSerializer(); public AbstractCacheManager(AutoLoadConfig config) { autoLoadHandler=new AutoLoadHandler(this, config); } public ISerializer<Object> getSerializer() { return serializer; } public void setSerializer(ISerializer<Object> serializer) { this.serializer=serializer; } @Override public AutoLoadHandler getAutoLoadHandler() { return this.autoLoadHandler; } public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace=namespace; } /** * KeyTO * @param className * @param methodName * @param arguments * @param _key key * @param _hfield hfield * @param result * @return CacheKeyTO */ private CacheKeyTO getCacheKey(String className, String methodName, Object[] arguments, String _key, String _hfield, Object result) { String key=null; String hfield=null; if(null != _key && _key.trim().length() > 0) { key=CacheUtil.getDefinedCacheKey(_key, arguments, result); if(null != _hfield && _hfield.trim().length() > 0) { hfield=CacheUtil.getDefinedCacheKey(_hfield, arguments, result); } } else { key=CacheUtil.getDefaultCacheKey(className, methodName, arguments); } if(null == key || key.trim().length() == 0) { logger.error(className + "." + methodName + "; cache key is empty"); return null; } CacheKeyTO to=new CacheKeyTO(); to.setNamespace(namespace); to.setKey(key); to.setHfield(hfield); return to; } /** * Key * @param pjp * @param cache * @return String Key */ private CacheKeyTO getCacheKey(ProceedingJoinPoint pjp, Cache cache) { String className=pjp.getTarget().getClass().getName(); String methodName=pjp.getSignature().getName(); Object[] arguments=pjp.getArgs(); String _key=cache.key(); String _hfield=cache.hfield(); return getCacheKey(className, methodName, arguments, _key, _hfield, null); } /** * Key * @param pjp * @param cache * @param result * @return Key */ private CacheKeyTO getCacheKey(ProceedingJoinPoint pjp, Cache cache, Object result) { String className=pjp.getTarget().getClass().getName(); String methodName=pjp.getSignature().getName(); Object[] arguments=pjp.getArgs(); String _key=cache.key(); String _hfield=cache.hfield(); return getCacheKey(className, methodName, arguments, _key, _hfield, result); } /** * Key * @param pjp * @param cache * @param result * @return Key */ private CacheKeyTO getCacheKey(ProceedingJoinPoint pjp, ExCache cache, Object result) { String className=pjp.getTarget().getClass().getName(); String methodName=pjp.getSignature().getName(); Object[] arguments=pjp.getArgs(); String _key=cache.key(); String _hfield=cache.hfield(); return getCacheKey(className, methodName, arguments, _key, _hfield, result); } /** * Key * @param jp * @param cacheDeleteKey * @param retVal * @return Key */ private CacheKeyTO getCacheKey(JoinPoint jp, CacheDeleteKey cacheDeleteKey, Object retVal) { String className=jp.getTarget().getClass().getName(); String methodName=jp.getSignature().getName(); Object[] arguments=jp.getArgs(); String _key=cacheDeleteKey.value(); String _hfield=cacheDeleteKey.hfield(); return getCacheKey(className, methodName, arguments, _key, _hfield, retVal); } private void writeExCache(ProceedingJoinPoint pjp, Cache cache, Object result) { ExCache[] exCaches=cache.exCache(); if(null != exCaches && exCaches.length > 0) { Object[] arguments=pjp.getArgs(); for(ExCache exCache: exCaches) { if(!CacheUtil.isCacheable(exCache, arguments, result)) { continue; } CacheKeyTO cacheKey1=getCacheKey(pjp, exCache, result); Object result1=null; if(null == exCache.cacheObject() || exCache.cacheObject().length() == 0) { result1=result; } else { result1=CacheUtil.getElValue(exCache.cacheObject(), arguments, result, Object.class); } writeCache(result1, cacheKey1, exCache.expire()); } } } /** * @Cache * @param pjp * @param cache * @return T * @throws Exception */ public Object proceed(ProceedingJoinPoint pjp, Cache cache) throws Throwable { Object[] arguments=pjp.getArgs(); // Signature signature=pjp.getSignature(); // MethodSignature methodSignature=(MethodSignature)signature; // Class returnType=methodSignature.getReturnType(); // // System.out.println("returnType:" + returnType.getName()); int expire=cache.expire(); if(null != cache.opType() && cache.opType() == CacheOpType.WRITE) { Object result=getData(pjp, null); if(CacheUtil.isCacheable(cache, arguments, result)) { CacheKeyTO cacheKey=getCacheKey(pjp, cache, result); writeCache(result, cacheKey, expire); writeExCache(pjp, cache, result); } return result; } if(!CacheUtil.isCacheable(cache, arguments)) { return getData(pjp, null); } CacheKeyTO cacheKey=getCacheKey(pjp, cache); if(null == cacheKey) { return getData(pjp, null); } AutoLoadTO autoLoadTO=null; if(CacheUtil.isAutoload(cache, arguments)) { autoLoadTO=autoLoadHandler.getAutoLoadTO(cacheKey); if(null == autoLoadTO) { AutoLoadTO tmp=autoLoadHandler.putIfAbsent(cacheKey, pjp, expire, cache.requestTimeout(), serializer); if(null != tmp) { autoLoadTO=tmp; } } autoLoadTO.setLastRequestTime(System.currentTimeMillis()); } CacheWrapper cacheWrapper=this.get(cacheKey); if(null != cacheWrapper && !cacheWrapper.isExpired()) { if(null != autoLoadTO && cacheWrapper.getLastLoadTime() > autoLoadTO.getLastLoadTime()) { autoLoadTO.setLastLoadTime(cacheWrapper.getLastLoadTime()); } return cacheWrapper.getCacheObject(); } return loadData(pjp, autoLoadTO, cacheKey, cache);// DAO } /** * * @param result * @param cacheKey Key * @param expire */ private CacheWrapper writeCache(Object result, CacheKeyTO cacheKey, int expire) { if(null == cacheKey) { return null; } CacheWrapper tmp=new CacheWrapper(result, expire); this.setCache(cacheKey, tmp); return tmp; } /** * ProceedingJoinPoint * @param pjp * @param autoLoadTO * @param cacheKey * @param cache * @return * @throws Exception */ private Object loadData(ProceedingJoinPoint pjp, AutoLoadTO autoLoadTO, CacheKeyTO cacheKey, Cache cache) throws Throwable { String fullKey=cacheKey.getFullKey(); ProcessingTO isProcessing=processing.get(fullKey); ProcessingTO processingTO=null; if(null == isProcessing) { processingTO=new ProcessingTO(); ProcessingTO _isProcessing=processing.putIfAbsent(fullKey, processingTO); if(null != _isProcessing) { isProcessing=_isProcessing;// ProcessingTO } } int expire=cache.expire(); Object lock=null; Object result=null; // String tname=Thread.currentThread().getName(); if(null == isProcessing) { lock=processingTO; try { // System.out.println(tname + " first thread!"); result=getData(pjp, autoLoadTO); CacheWrapper cacheWrapper=writeCache(result, cacheKey, expire); processingTO.setCache(cacheWrapper); writeExCache(pjp, cache, result); } catch(Throwable e) { processingTO.setError(e); throw e; } finally { processingTO.setFirstFinished(true); processing.remove(fullKey); synchronized(lock) { lock.notifyAll(); } } } else { lock=isProcessing; long startWait=isProcessing.getStartTime(); CacheWrapper cacheWrapper=null; do { if(null == isProcessing) { break; } if(isProcessing.isFirstFinished()) { cacheWrapper=isProcessing.getCache(); // System.out.println(tname + " do FirstFinished" + " is null :" + (null == cacheWrapper)); if(null != cacheWrapper) { return cacheWrapper.getCacheObject(); } Throwable error=isProcessing.getError(); if(null != error) {// DAO // System.out.println(tname + " do error"); throw error; } break; } else { synchronized(lock) { // System.out.println(tname + " do wait"); try { lock.wait(50);// lockwait } catch(InterruptedException ex) { logger.error(ex.getMessage(), ex); } } } } while(System.currentTimeMillis() - startWait < cache.waitTimeOut()); try { result=getData(pjp, autoLoadTO); writeCache(result, cacheKey, expire); writeExCache(pjp, cache, result); } catch(Throwable e) { throw e; } finally { synchronized(lock) { lock.notifyAll(); } } } return result; } private Object getData(ProceedingJoinPoint pjp, AutoLoadTO autoLoadTO) throws Throwable { try { if(null != autoLoadTO) { autoLoadTO.setLoading(true); } long startTime=System.currentTimeMillis(); Object result=pjp.proceed(); long useTime=System.currentTimeMillis() - startTime; AutoLoadConfig config=autoLoadHandler.getConfig(); if(config.isPrintSlowLog() && useTime >= config.getSlowLoadTime()) { String className=pjp.getTarget().getClass().getName(); logger.error(className + "." + pjp.getSignature().getName() + ", use time:" + useTime + "ms"); } if(null != autoLoadTO) { autoLoadTO.setLastLoadTime(startTime); autoLoadTO.addUseTotalTime(useTime); } return result; } catch(Throwable e) { throw e; } finally { if(null != autoLoadTO) { autoLoadTO.setLoading(false); } } } /** * @CacheDelete * @param jp * @param cacheDelete * @param retVal */ public void deleteCache(JoinPoint jp, CacheDelete cacheDelete, Object retVal) { Object[] arguments=jp.getArgs(); CacheDeleteKey[] keys=cacheDelete.value(); if(null == keys || keys.length == 0) { return; } for(int i=0; i < keys.length; i++) { CacheDeleteKey keyConfig=keys[i]; if(!CacheUtil.isCanDelete(keyConfig, arguments, retVal)) { continue; } CacheKeyTO key=getCacheKey(jp, keyConfig, retVal); if(null != key) { this.delete(key); } } } @Override public void destroy() { autoLoadHandler.shutdown(); autoLoadHandler=null; logger.info("cache destroy ... ... ..."); } }
package org.jetel.connection.jdbc; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ParameterMetaData; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jetel.connection.jdbc.specific.impl.DefaultJdbcSpecific; import org.jetel.data.Defaults; import org.jetel.database.sql.JdbcSpecific; import org.jetel.metadata.DataFieldMetadata; import org.jetel.metadata.DataRecordMetadata; /** * Various utilities for working with Databases * * @author dpavlis * @since September 25, 2002 * @created January 24, 2003 */ public class SQLUtil { private final static String DEFAULT_DELIMITER = ";"; private final static String END_RECORD_DELIMITER = "\n"; public final static String BLOB_FORMAT_STRING = "blob"; public final static String BINARY_FORMAT_STRING = "binary"; static Log logger = LogFactory.getLog(SQLUtil.class); /** * Creates SQL insert statement based on metadata describing data flow and * supplied table name * * @param metadata Metadata describing data flow from which to feed database * @param tableName Table name into which insert data * @param specific Used JDBC specific. * @return string containing SQL insert statement * @since October 2, 2002 */ public static String assembleInsertSQLStatement(DataRecordMetadata metadata, String tableName, JdbcSpecific specific) { StringBuffer strBuf = new StringBuffer(); //StringBuffer strBuf2 = new StringBuffer(); strBuf.append(" values("); for (int i = 0; i < metadata.getNumFields(); i++) { //strBuf2.append(metadata.getField(i).getName()); strBuf.append("?"); if (i < metadata.getNumFields() - 1) { strBuf.append(","); //strBuf2.append(","); } } //strBuf.insert(0, strBuf2.toString()); //strBuf.insert(0, " ("); strBuf.insert(0, specific.quoteString(tableName)); strBuf.insert(0, "insert into "); strBuf.append(")"); if (logger.isDebugEnabled()) { logger.debug(strBuf.toString()); } return strBuf.toString(); } /** * Description of the Method * * @param tableName Description of the Parameter * @param dbFields Description of the Parameter * @param specific Used JDBC specific. * @return Description of the Return Value */ public static String assembleInsertSQLStatement(String tableName, String[] dbFields, JdbcSpecific specific) { String quotedTableName = specific.quoteString(tableName); String[] quotedDbFields = new String[dbFields.length]; for (int i = 0; i < dbFields.length; i++) { quotedDbFields[i] = specific.quoteString(dbFields[i]); } return assembleInsertSQLStatement(quotedTableName, quotedDbFields); } public static String assembleInsertSQLStatement(String quotedTableName, String[] quotedDbFields) { StringBuffer strBuf = new StringBuffer("insert into "); strBuf.append(quotedTableName).append(" ("); for (int i = 0; i < quotedDbFields.length; i++) { strBuf.append(quotedDbFields[i]); if (i < quotedDbFields.length - 1) { strBuf.append(", "); } } strBuf.append(") values ("); for (int i = 0; i < quotedDbFields.length; i++) { strBuf.append("?"); if (i < quotedDbFields.length - 1) { strBuf.append(","); } } strBuf.append(")"); return strBuf.toString(); } /** * Same as dbMetadata2jetel(name, dbMetadata, sqlIndex, jdbcSpecific, true) */ public static DataFieldMetadata dbMetadata2jetel(String name, ResultSetMetaData dbMetadata, int sqlIndex, JdbcSpecific jdbcSpecific) throws SQLException{ return dbMetadata2jetel(name, dbMetadata, sqlIndex, jdbcSpecific, true); } /** * Creates clover data field metadata compatible with database column metadata * * @param name clover field name * @param dbMetadata result set metadata * @param sqlIndex index of result set column (1 based) * @param jdbcSpecific * @param failIfUknownType indicates whether to throw exception if there is unknown column type in DB metadata. * @return clover data field metadata compatible with database column metadata * @throws SQLException */ public static DataFieldMetadata dbMetadata2jetel(String name, ResultSetMetaData dbMetadata, int sqlIndex, JdbcSpecific jdbcSpecific, boolean failIfUnknownType) throws SQLException{ return dbMetadata2jetel(name, new ResultSetDbMetadata(dbMetadata), sqlIndex, jdbcSpecific, failIfUnknownType); } public static DataFieldMetadata dbMetadata2jetel(String name, ParameterMetaData dbMetadata, int sqlIndex, JdbcSpecific jdbcSpecific) throws SQLException{ return dbMetadata2jetel(name, new ParameterDbMetadata(dbMetadata), sqlIndex, jdbcSpecific, true); } public static DataFieldMetadata dbMetadata2jetel(String name, DbMetadata dbMetadata, int sqlIndex, JdbcSpecific jdbcSpecific, boolean failIfUnknownType) throws SQLException{ DataFieldMetadata fieldMetadata = new DataFieldMetadata(name, null); fieldMetadata.setLabel(name); int type = dbMetadata.getType(sqlIndex); char cloverType; int precision = dbMetadata.getPrecision(sqlIndex); try { cloverType = jdbcSpecific.sqlType2jetel(type, precision); } catch (IllegalArgumentException e) { if (failIfUnknownType) throw e; cloverType = DataFieldMetadata.UNKNOWN_FIELD; } //set length and scale for decimal field if (cloverType == DataFieldMetadata.DECIMAL_FIELD) { int scale = 0; int length = 0; try { scale = dbMetadata.getScale(sqlIndex); if (scale < 0) { cloverType = DataFieldMetadata.NUMERIC_FIELD; }else{ fieldMetadata.setProperty(DataFieldMetadata.SCALE_ATTR, Integer.toString(scale)); } } catch (SQLException e) { cloverType = DataFieldMetadata.NUMERIC_FIELD; } try { length = dbMetadata.getPrecision(sqlIndex); if (length <= scale) { cloverType = DataFieldMetadata.NUMERIC_FIELD; }else{ fieldMetadata.setProperty(DataFieldMetadata.LENGTH_ATTR, Integer.toString(length)); } } catch (SQLException e) { cloverType = DataFieldMetadata.NUMERIC_FIELD; } } fieldMetadata.setType(cloverType); //for Date Data Field set proper format switch (type) { case Types.DATE: fieldMetadata.setFormatStr(Defaults.DEFAULT_DATE_FORMAT); break; case Types.TIME: fieldMetadata.setFormatStr(Defaults.DEFAULT_TIME_FORMAT); break; case Types.TIMESTAMP: fieldMetadata.setFormatStr(Defaults.DEFAULT_DATETIME_FORMAT); break; } if (dbMetadata.isNullable(sqlIndex) == ResultSetMetaData.columnNullable) { fieldMetadata.setNullable(true); } return fieldMetadata; } public static void setSizeAttributeToColumnSizeIfPossible(DataRecordMetadata recordMetadata, ResultSetMetaData rsMetaData, JdbcSpecific jdbcSpecific, DatabaseMetaData dbMetaData, String tableName) { ResultSet rsColumns; try { rsColumns = dbMetaData.getColumns(null, null, tableName, null); } catch (SQLException e1) { return; } for (int i = 0; i < recordMetadata.getFields().length; i++) { boolean limitedField = true; int precision = 0; char cloverType = 0; try { limitedField = true; int type = rsMetaData.getColumnType(i + 1); precision = rsMetaData.getPrecision(i + 1); try { cloverType = jdbcSpecific.sqlType2jetel(type, precision); } catch (IllegalArgumentException e) { cloverType = DataFieldMetadata.UNKNOWN_FIELD; } rsColumns.next(); if (isUnlimitedType(rsColumns.getString("TYPE_NAME"))) { limitedField = false; } } catch (Exception e) { } finally { if (limitedField && cloverType != DataFieldMetadata.DECIMAL_FIELD) { // Serves as default size in case user decides to switch field to fixed size (see issue #3938) if (precision > 0) { recordMetadata.getFields()[i].setProperty(DataFieldMetadata.SIZE_ATTR, Integer.toString(precision)); } } } } } /** * Same as dbMetadata2jetel(dbMetadata, jdbcSpecific, true) */ public static DataRecordMetadata dbMetadata2jetel(ResultSetMetaData dbMetadata, JdbcSpecific jdbcSpecific) throws SQLException { return dbMetadata2jetel(dbMetadata, jdbcSpecific, true); } /** * Converts SQL metadata into Clover's DataRecordMetadata * * @param dbMetadata SQL ResultSet metadata describing which columns are * returned by query * @param failIfUknownType indicates whether to throw exception if there is unknown column type in DB metadata. * @return DataRecordMetadata which correspond to the SQL * ResultSet * @exception SQLException Description of the Exception */ public static DataRecordMetadata dbMetadata2jetel(ResultSetMetaData dbMetadata, JdbcSpecific jdbcSpecific, boolean failIfUknownType) throws SQLException { DataFieldMetadata fieldMetadata; DataRecordMetadata jetelMetadata = new DataRecordMetadata(DataRecordMetadata.EMPTY_NAME, DataRecordMetadata.DELIMITED_RECORD); jetelMetadata.setLabel(getTableName(dbMetadata)); jetelMetadata.setFieldDelimiter(DEFAULT_DELIMITER); jetelMetadata.setRecordDelimiter(END_RECORD_DELIMITER); for (int i = 1; i <= dbMetadata.getColumnCount(); i++) { fieldMetadata = dbMetadata2jetel(DataFieldMetadata.EMPTY_NAME, dbMetadata, i, jdbcSpecific, failIfUknownType); fieldMetadata.setLabel(dbMetadata.getColumnName(i)); jetelMetadata.addField(fieldMetadata); } jetelMetadata.normalize(); return jetelMetadata; } private static String getTableName(ResultSetMetaData dbMetadata) { try { return dbMetadata.getTableName(1); } catch (SQLException e) { return null; } } @Deprecated public static DataRecordMetadata dbMetadata2jetel(ResultSetMetaData dbMetadata) throws SQLException { return dbMetadata2jetel(dbMetadata, DefaultJdbcSpecific.getInstance()); } public static DataRecordMetadata dbMetadata2jetel(ParameterMetaData dbMetadata, String metadataName, JdbcSpecific jdbcSpecific) throws SQLException { DataFieldMetadata fieldMetadata; DataRecordMetadata jetelMetadata = new DataRecordMetadata(metadataName, DataRecordMetadata.DELIMITED_RECORD); jetelMetadata.setLabel(metadataName); jetelMetadata.setFieldDelimiter(DEFAULT_DELIMITER); jetelMetadata.setRecordDelimiter(END_RECORD_DELIMITER); String colName; for (int i = 1; i <= dbMetadata.getParameterCount(); i++) { colName = "field" + i; fieldMetadata = dbMetadata2jetel(colName, dbMetadata, i, jdbcSpecific); jetelMetadata.addField(fieldMetadata); } jetelMetadata.normalize(); return jetelMetadata; } @Deprecated public static DataRecordMetadata dbMetadata2jetel(ParameterMetaData dbMetadata, String metadataName) throws SQLException { return dbMetadata2jetel(dbMetadata, metadataName, DefaultJdbcSpecific.getInstance()); } /** * For specified table returns names of individual fileds * * @param conn database connection * @param tableName name of DB table * @return array of field names */ public static String[] getColumnNames(Connection conn, String tableName) { List<String> tmp = new ArrayList<String>(); String[] out = null; try { ResultSet rs = conn.getMetaData().getColumns(null, null, tableName, "%"); while (rs.next()) { // FIELD NAME - 4 column in resultset // get DATA TYPE - 5 column in result set from Database metadata //out.add(rs.getString(4).toUpperCase(), new Integer(rs.getInt(5))); tmp.add(rs.getString(4)); } out = new String[tmp.size()]; tmp.toArray(out); } catch (Exception e) { e.printStackTrace(); } if (out.length == 0) { logger.warn("Table " + tableName + " does not exist or has no columns"); } return out; } /** * Gets the FieldTypes of fields present in specified DB table * * @param metadata Description of Parameter * @param tableName name of the table for which to get metadata (field names, types) * @return list of JDBC FieldTypes * @exception SQLException Description of Exception * @since October 4, 2002 * @see java.sql.DatabaseMetaData */ public static List<Integer> getFieldTypes(DatabaseMetaData metadata, String tableName) throws SQLException { String[] tableSpec = new String[]{null, tableName.toUpperCase()}; if (tableName.indexOf(".") != -1) { tableSpec = tableName.toUpperCase().split("\\.", 2); } ResultSet rs = null; try { rs = metadata.getColumns(null, tableSpec[0], tableSpec[1], "%");//null as last parm List<Integer> fieldTypes = new LinkedList<Integer>(); while (rs.next()) { // get DATA TYPE - fifth column in result set from Database metadata fieldTypes.add(new Integer(rs.getInt(5))); } if (fieldTypes.size() == 0) { //throw new RuntimeException("No metadata obtained for table: " + tableName); //Warn ! logger.warn("No metadata obtained for table: \"" + tableName + "\", using workaround ..."); // WE HAVE SOME PATCH, but ... ResultSetMetaData fieldsMetadata = getTableFieldsMetadata(metadata.getConnection(), tableName); for (int i = 0; i < fieldsMetadata.getColumnCount(); i++) { fieldTypes.add(new Integer(fieldsMetadata.getColumnType(i + 1))); } } return fieldTypes; } finally { if (rs != null) rs.close(); } } /** * Gets the FieldTypes of fields (enumerated in dbFields) present in specified DB table * * @param metadata Description of the Parameter * @param tableName name of the table for which to get metadata (field names, types) * @param dbFields array of field names * @return list of JDBC FieldTypes * @exception SQLException Description of the Exception */ public static List<Integer> getFieldTypes(DatabaseMetaData metadata, String tableName, String[] dbFields) throws SQLException { String[] tableSpec = new String[]{null, tableName.toUpperCase()}; // if schema defined in table name, extract schema & table name into separate fields if (tableName.indexOf(".") != -1) { tableSpec = tableName.toUpperCase().split("\\.", 2); } ResultSet rs = metadata.getColumns(null, tableSpec[0], tableSpec[1], "%");//null as last parm Map<String, Integer> dbFieldsMap = new HashMap<String, Integer>(); List<Integer> fieldTypes = new LinkedList<Integer>(); Integer dataType; while (rs.next()) { // FIELD NAME - fourth columnt in resutl set // get DATA TYPE - fifth column in result set from Database metadata dbFieldsMap.put(rs.getString(4).toUpperCase(), new Integer(rs.getInt(5))); } if (dbFieldsMap.size() == 0) { //throw new RuntimeException("No metadata obtained for table: " + tableName); //Warn ! logger.warn("No metadata obtained for table: \"" + tableName + "\", using workaround ..."); // WE HAVE SOME PATCH, but ... ResultSetMetaData fieldsMetadata = getTableFieldsMetadata(metadata.getConnection(), tableName); for (int i = 0; i < fieldsMetadata.getColumnCount(); i++) { dbFieldsMap.put(fieldsMetadata.getColumnName(i + 1).toUpperCase(), new Integer(fieldsMetadata.getColumnType(i + 1))); } } for (int i = 0; i < dbFields.length; i++) { dataType = (Integer) dbFieldsMap.get(dbFields[i].toUpperCase()); if (dataType == null) { throw new SQLException("Field \"" + dbFields[i] + "\" does not exists in table \"" + tableName + "\""); } fieldTypes.add(dataType); } return fieldTypes; } /** * Gets the fieldTypes attribute of the SQLUtil class * * @param metadata Description of the Parameter * @return The fieldTypes value * @exception SQLException Description of the Exception */ public static List<Integer> getFieldTypes(ParameterMetaData metadata) throws SQLException { List<Integer> fieldTypes = new LinkedList<Integer>(); for (int i = 1; i <= metadata.getParameterCount(); i++) { fieldTypes.add(new Integer(metadata.getParameterType(i))); } return fieldTypes; } /** * Gets the fieldTypes attribute of the SQLUtil class * * @param metadata Description of the Parameter * @return The fieldTypes value * @exception SQLException Description of the Exception */ public static List<Integer> getFieldTypes(ResultSetMetaData metadata) throws SQLException { List<Integer> fieldTypes = new LinkedList<Integer>(); for (int i = 1; i <= metadata.getColumnCount(); i++) { fieldTypes.add(new Integer(metadata.getColumnType(i))); } return fieldTypes; } /** * Gets the fieldTypes attribute of the SQLUtil class * * @param metadata Description of the Parameter * @param cloverFields Description of the Parameter * @return The fieldTypes value * @exception SQLException Description of the Exception */ @Deprecated public static List<Integer> getFieldTypes(DataRecordMetadata metadata, String[] cloverFields) { return getFieldTypes(metadata, cloverFields, DefaultJdbcSpecific.getInstance()); } public static List<Integer> getFieldTypes(DataRecordMetadata metadata, String[] cloverFields, JdbcSpecific jdbcSpecific) { List<Integer> fieldTypes = new LinkedList<Integer>(); DataFieldMetadata fieldMeta; for (int i = 0; i < cloverFields.length; i++) { if ((fieldMeta = metadata.getField(cloverFields[i])) != null) { fieldTypes.add(new Integer(jdbcSpecific.jetelType2sql(fieldMeta))); } else { throw new RuntimeException("Field name [" + cloverFields[i] + "] not found in " + metadata.getName()); } } return fieldTypes; } /** * Gets the fieldTypes attribute of the SQLUtil class * * @param metadata Description of the Parameter * @return The fieldTypes value * @exception SQLException Description of the Exception */ public static List<Integer> getFieldTypes(DataRecordMetadata metadata, JdbcSpecific jdbcSpecific) { List<Integer> fieldTypes = new LinkedList<Integer>(); for (int i = 0; i < metadata.getNumFields(); i++) { fieldTypes.add(new Integer(jdbcSpecific.jetelType2sql(metadata.getField(i)))); } return fieldTypes; } @Deprecated public static List<Integer> getFieldTypes(DataRecordMetadata metadata) { return getFieldTypes(metadata, DefaultJdbcSpecific.getInstance()); } /** * Gets the tableFieldsMetadata attribute of the SQLUtil class * * @param con Description of the Parameter * @param tableName Description of the Parameter * @return The tableFieldsMetadata value * @exception SQLException Description of the Exception */ public static ResultSetMetaData getTableFieldsMetadata(Connection con, String tableName) throws SQLException { String queryStr = "select * from " + tableName + " where 1=0 "; ResultSet rs = con.createStatement().executeQuery(queryStr); return rs.getMetaData(); } /** * Converts Jetel/Clover datatype into String * * @param fieldType Jetel datatype * @return Corresponding string name */ public static String jetelType2Str(char fieldType) { return DataFieldMetadata.type2Str(fieldType); } /** * Converts sql type into string. * @param sqlType * @return */ public static String sqlType2str(int sqlType) { switch(sqlType) { case Types.BIT: return "BIT"; case Types.TINYINT: return "TINYINT"; case Types.SMALLINT: return "SMALLINT"; case Types.INTEGER: return "INTEGER"; case Types.BIGINT: return "BIGINT"; case Types.FLOAT: return "FLOAT"; case Types.REAL: return "REAL"; case Types.DOUBLE: return "DOUBLE"; case Types.NUMERIC: return "NUMERIC"; case Types.DECIMAL: return "DECIMAL"; case Types.CHAR: return "CHAR"; case Types.VARCHAR: return "VARCHAR"; case Types.LONGVARCHAR: return "LONGVARCHAR"; case Types.DATE: return "DATE"; case Types.TIME: return "TIME"; case Types.TIMESTAMP: return "TIMESTAMP"; case Types.BINARY: return "BINARY"; case Types.VARBINARY: return "VARBINARY"; case Types.LONGVARBINARY: return "LONGVARBINARY"; case Types.NULL: return "NULL"; case Types.OTHER: return "OTHER"; case Types.JAVA_OBJECT: return "JAVA_OBJECT"; case Types.DISTINCT: return "DISTINCT"; case Types.STRUCT: return "STRUCT"; case Types.ARRAY: return "ARRAY"; case Types.BLOB: return "BLOB"; case Types.CLOB: return "CLOB"; case Types.REF: return "REF"; case Types.DATALINK: return "DATALINK"; case Types.BOOLEAN: return "BOOLEAN"; default: return "<unknown sql type>"; } } /** * Checks whether connection is valid/open. It * sends simple SQL query to DB and waits if * any exception occures * * @param conn JDBC connection object * @return true if connection valid/open otherwise false */ public static boolean isActive(Connection conn){ try{ conn.createStatement().execute("select 1"); return true; }catch(Exception ex){ return false; } } /** * method checks if text contains only closed pairs of bars. * for example: "(select 1)), (select " return false; * @param text * @return true if only closed pairs are contained in text */ private static boolean isAllBarPairsClosed(String text) { int currentOpen = 0; for (int i = 0; i < text.length(); i++) { char current = text.charAt(i); switch (current) { case '(': { currentOpen++; break; } case ')': { if (currentOpen > 0) { currentOpen break; } else { return false; } } } } return currentOpen == 0; } static String SELECT_KW = "select"; //we need to ignore case static Pattern FROM_KW = Pattern.compile("(?i)\\s+from\\s+"); static String selectDelim = ","; /** * Searches select clause for function calls or other unnamed fields and generates * names for them * @param select * @param specific * @return */ public static String removeUnnamedFields(String select, JdbcSpecific specific) { if (select == null) { return null; } String selectlc = select.toLowerCase(); int selectKwOffset = 0; int contentOffset; String selectPart; String parts[]; int starti = 0; StringBuilder newQuery = new StringBuilder(); while((selectKwOffset = selectlc.indexOf(SELECT_KW, selectKwOffset)) >= 0) { contentOffset = selectKwOffset + SELECT_KW.length(); newQuery.append(select.substring(starti, contentOffset)); selectPart = select.substring(contentOffset); Matcher m = FROM_KW.matcher(selectPart.toLowerCase()); boolean founded = false; while (m.find()) { // we can't just cut it there, it breaks up this case: select a, (select b from t2 ) from t1; if (isAllBarPairsClosed(selectPart.substring(0, m.start()))) { selectPart = selectPart.substring(0, m.start()); founded = true; break; } } // select without from ? could be something like: select (select 1) from ... - inner select if (!founded) { int inPosition; inPosition = selectPart.indexOf(')'); while (inPosition > -1 ) { if (isAllBarPairsClosed(selectPart.substring(0, inPosition))) { selectPart = selectPart.substring(0, inPosition); break; } inPosition = selectPart.indexOf(')',inPosition+1); } } // from original string - select what from ... - what contains another select ! String innerSelectPart; if (selectPart.indexOf(SELECT_KW) != -1) { innerSelectPart = removeUnnamedFields(selectPart, specific); } else { innerSelectPart = selectPart; } parts = innerSelectPart.split(selectDelim); StringBuilder newSelectPart = new StringBuilder(); for(int i = 0; parts != null && i < parts.length; i++) { // we can't just add it on ')', it breaks up this case: func1(func2(aaa),bbb,ccc); // ignoring delimiter as it is not important for bars if (parts[i].trim().endsWith(")") && (isAllBarPairsClosed(newSelectPart.toString()+parts[i]) || specific.isCaseStatement(parts[i]))) { parts[i] += " as AUTOCOLUMN" + String.valueOf(Math.round(Math.random() * 100000)); } if (i > 0) { newSelectPart.append(selectDelim); } newSelectPart.append(parts[i]); } newQuery.append(newSelectPart); starti = contentOffset + selectPart.length(); selectKwOffset = starti; } newQuery.append(select.substring(starti)); return newQuery.toString(); } /** * Method individually close all given JDBC instances in separate try-catch blocks or * omit closing when given parameter is null. * @param rs ResultSet * @param stmt Statement * @param conn Connection */ public static void closeConnection(ResultSet rs, Statement stmt, Connection conn) { if(rs != null) { try { rs.close(); } catch (SQLException ex) { logger.error(ex); } } if(stmt != null) { try { stmt.close(); } catch (SQLException ex) { logger.error(ex); } } if(conn != null) { try { conn.close(); } catch (SQLException ex) { logger.error(ex); } } } private static boolean isUnlimitedType(String typeName) { if (typeName != null) { typeName = typeName.toLowerCase(); if (typeName.indexOf("text") >= 0 || typeName.equals("clob") || typeName.equals("blob")) { return true; } } return false; } /** * The aim of this interface together with delegating classes {@link ResultSetMetaData} and * {@link ParameterDbMetadata} is to have common interface for ResultSetMetaData and ParameterMetaData classes. */ private interface DbMetadata { /** Retrieves the designated SQL type of column/parameter */ public int getType(int index) throws SQLException; /** Gets the designated column/parameter's number of digits to right of the decimal point */ public int getScale(int index) throws SQLException; /** Get the designated column/parameter's specified column size. */ public int getPrecision(int index) throws SQLException; /** Indicates the nullability of values in the designated column/parameter */ public int isNullable(int index) throws SQLException; } /** Delegates methods to ResultSetMetaData instance. */ private static class ResultSetDbMetadata implements DbMetadata { private ResultSetMetaData dbMetadata; public ResultSetDbMetadata(ResultSetMetaData dbMetadata) { this.dbMetadata = dbMetadata; } @Override public int getType(int column) throws SQLException { return dbMetadata.getColumnType(column); } @Override public int isNullable(int column) throws SQLException { return dbMetadata.isNullable(column); } @Override public int getPrecision(int column) throws SQLException { return dbMetadata.getPrecision(column); } @Override public int getScale(int column) throws SQLException { return dbMetadata.getScale(column); } } /** Delegates methods to ParameterMetaData instance. */ private static class ParameterDbMetadata implements DbMetadata { private ParameterMetaData dbMetadata; public ParameterDbMetadata(ParameterMetaData dbMetadata) { this.dbMetadata = dbMetadata; } @Override public int getType(int param) throws SQLException { return dbMetadata.getParameterType(param); } @Override public int isNullable(int param) throws SQLException { return dbMetadata.isNullable(param); } @Override public int getPrecision(int param) throws SQLException { return dbMetadata.getPrecision(param); } @Override public int getScale(int param) throws SQLException { return dbMetadata.getScale(param); } } private static class SQLSplitter { private enum State { DEFAULT, STRING, ONELINE_COMMENT, MULTILINE_COMMENT } private static final char DEFAULT_DELIMITER = ';'; private final String input; private StringBuilder sb = new StringBuilder(); private List<String> result = new ArrayList<String>(); private State state = State.DEFAULT; private char previous = 0; private String customDelimiter; /** * @param input * @param customDelimiter if <code>null</code>, default ";" will be used. */ public SQLSplitter(String input, String customDelimiter) { this.input = input; if (customDelimiter != null && !String.valueOf(DEFAULT_DELIMITER).equals(customDelimiter)) { this.customDelimiter = customDelimiter; } } private void flush() { if (sb.length() > 0) { result.add(sb.toString()); } sb.setLength(0); previous = 0; } private void setState(State state) { this.state = state; this.previous = 0; // reset the previous character } private void run() { int length = input.length(); for (int i = 0; i < length; i++) { char c = input.charAt(i); switch (state) { case DEFAULT: if (customDelimiter == null) { if (c == DEFAULT_DELIMITER) { flush(); continue; // stay in the DEFAULT state, do not append ';' to the StringBuilder } } else { if (input.startsWith(customDelimiter, i)) { flush(); i += customDelimiter.length() - 1; continue; // stay in the DEFAULT state, do not append whole customDelimiter to the StringBuilder } } switch (c) { case '-': if (previous == '-') { setState(State.ONELINE_COMMENT); } break; case '*': if (previous == '/') { setState(state = State.MULTILINE_COMMENT); } break; case '\'': setState(State.STRING); break; } break; case STRING: if (c == '\'') { setState(State.DEFAULT); } break; case ONELINE_COMMENT: if ((c == '\r') || (c == '\n')) { setState(State.DEFAULT); } break; case MULTILINE_COMMENT: if ((c == '/') && (previous == '*')) { setState(State.DEFAULT); } break; } sb.append(c); previous = c; } flush(); } private String[] getResult() { return result.toArray(new String[result.size()]); } } /** * Splits a string into individual queries, * ignores semicolons within strings and comments. * @param sql * @return individual queries */ public static String[] split(String sql) { return split(sql, null); } /** * Splits a string into individual queries, * ignores SQL statements separator within strings and comments. * * @param sql * @param delimiter string separating individual SQL statements in the input <code>sql<code>. * If <code>null</code>, default ";" separator will be used. * @return individual SQL statements */ public static String[] split(String sql, String delimiter) { SQLSplitter splitter = new SQLSplitter(sql, delimiter); splitter.run(); return splitter.getResult(); } }
package com.jarvis.cache; import java.util.concurrent.ConcurrentHashMap; import org.apache.log4j.Logger; import com.jarvis.cache.annotation.Cache; import com.jarvis.cache.annotation.CacheDelete; import com.jarvis.cache.annotation.CacheDeleteKey; import com.jarvis.cache.annotation.ExCache; import com.jarvis.cache.aop.CacheAopProxyChain; import com.jarvis.cache.aop.DeleteCacheAopProxyChain; import com.jarvis.cache.serializer.HessianSerializer; import com.jarvis.cache.serializer.ISerializer; import com.jarvis.cache.to.AutoLoadConfig; import com.jarvis.cache.to.AutoLoadTO; import com.jarvis.cache.to.CacheKeyTO; import com.jarvis.cache.to.CacheWrapper; import com.jarvis.cache.to.ProcessingTO; import com.jarvis.cache.type.CacheOpType; /** * * @author jiayu.qiu */ public abstract class AbstractCacheManager implements ICacheManager { private static final Logger logger=Logger.getLogger(AbstractCacheManager.class); // java.lang.NoSuchMethodError:java.util.Map.putIfAbsent private final ConcurrentHashMap<String, ProcessingTO> processing=new ConcurrentHashMap<String, ProcessingTO>(); private AutoLoadHandler autoLoadHandler; private String namespace; /** * Hessian2 */ private ISerializer<Object> serializer=new HessianSerializer(); public AbstractCacheManager(AutoLoadConfig config) { autoLoadHandler=new AutoLoadHandler(this, config); } public ISerializer<Object> getSerializer() { return serializer; } public void setSerializer(ISerializer<Object> serializer) { this.serializer=serializer; } @Override public AutoLoadHandler getAutoLoadHandler() { return this.autoLoadHandler; } public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace=namespace; } /** * @Cache * @param pjp * @param cache * @return T * @throws Exception */ public Object proceed(CacheAopProxyChain pjp, Cache cache) throws Throwable { Object[] arguments=pjp.getArgs(); // Signature signature=pjp.getSignature(); // MethodSignature methodSignature=(MethodSignature)signature; // Class returnType=methodSignature.getReturnType(); // // System.out.println("returnType:" + returnType.getName()); if(null != cache.opType() && cache.opType() == CacheOpType.WRITE) { CacheWrapper cacheWrapper=getCacheWrapper(pjp, null, cache, null); Object result=cacheWrapper.getCacheObject(); if(CacheUtil.isCacheable(cache, arguments, result)) { CacheKeyTO cacheKey=getCacheKey(pjp, cache, result); writeCache(pjp, null, cache, cacheKey, cacheWrapper); } return result; } if(!CacheUtil.isCacheable(cache, arguments)) { return getData(pjp); } CacheKeyTO cacheKey=getCacheKey(pjp, cache); if(null == cacheKey) { return getData(pjp); } CacheWrapper cacheWrapper=this.get(cacheKey); if(null != cacheWrapper && !cacheWrapper.isExpired()) { AutoLoadTO autoLoadTO=getAutoLoadTO(pjp, arguments, cache, cacheKey, cacheWrapper); if(null != autoLoadTO) { autoLoadTO.setLastRequestTime(System.currentTimeMillis()); autoLoadTO.setLastLoadTime(cacheWrapper.getLastLoadTime()); autoLoadTO.setExpire(cacheWrapper.getExpire()); } return cacheWrapper.getCacheObject(); } return loadData(pjp, null, cacheKey, cache);// DAO } /** * @CacheDelete * @param jp * @param cacheDelete * @param retVal */ public void deleteCache(DeleteCacheAopProxyChain jp, CacheDelete cacheDelete, Object retVal) { Object[] arguments=jp.getArgs(); CacheDeleteKey[] keys=cacheDelete.value(); if(null == keys || keys.length == 0) { return; } for(int i=0; i < keys.length; i++) { CacheDeleteKey keyConfig=keys[i]; if(!CacheUtil.isCanDelete(keyConfig, arguments, retVal)) { continue; } CacheKeyTO key=getCacheKey(jp, keyConfig, retVal); if(null != key) { this.delete(key); } } } /** * CacheAopProxyChain * @param pjp CacheAopProxyChain * @param autoLoadTO AutoLoadTO * @param cacheKey CacheKeyTO * @param cache Cache * @return * @throws Throwable */ @Override public Object loadData(CacheAopProxyChain pjp, AutoLoadTO autoLoadTO, CacheKeyTO cacheKey, Cache cache) throws Throwable { String fullKey=cacheKey.getFullKey(); ProcessingTO isProcessing=processing.get(fullKey); ProcessingTO processingTO=null; if(null == isProcessing) { processingTO=new ProcessingTO(); ProcessingTO _isProcessing=processing.putIfAbsent(fullKey, processingTO); if(null != _isProcessing) { isProcessing=_isProcessing;// ProcessingTO } } Object lock=null; CacheWrapper cacheWrapper=null; // String tname=Thread.currentThread().getName(); if(null == isProcessing) { lock=processingTO; try { // System.out.println(tname + " first thread!"); cacheWrapper=getCacheWrapper(pjp, autoLoadTO, cache, cacheKey); writeCache(pjp, autoLoadTO, cache, cacheKey, cacheWrapper); processingTO.setCache(cacheWrapper); } catch(Throwable e) { processingTO.setError(e); throw e; } finally { processingTO.setFirstFinished(true); processing.remove(fullKey); synchronized(lock) { lock.notifyAll(); } } } else { lock=isProcessing; long startWait=isProcessing.getStartTime(); do { if(null == isProcessing) { break; } if(isProcessing.isFirstFinished()) { cacheWrapper=isProcessing.getCache(); // System.out.println(tname + " do FirstFinished" + " is null :" + (null == cacheWrapper)); if(null != cacheWrapper) { return cacheWrapper.getCacheObject(); } Throwable error=isProcessing.getError(); if(null != error) {// DAO // System.out.println(tname + " do error"); throw error; } break; } else { synchronized(lock) { // System.out.println(tname + " do wait"); try { lock.wait(50);// lockwait } catch(InterruptedException ex) { logger.error(ex.getMessage(), ex); } } } } while(System.currentTimeMillis() - startWait < cache.waitTimeOut()); try { cacheWrapper=getCacheWrapper(pjp, autoLoadTO, cache, cacheKey); writeCache(pjp, autoLoadTO, cache, cacheKey, cacheWrapper); } catch(Throwable e) { throw e; } finally { synchronized(lock) { lock.notifyAll(); } } } if(null != cacheWrapper) { return cacheWrapper.getCacheObject(); } return null; } /** * * @param pjp CacheAopProxyChain * @return Object * @throws Throwable */ private Object getData(CacheAopProxyChain pjp) throws Throwable { try { long startTime=System.currentTimeMillis(); Object[] arguments=pjp.getArgs(); Object result=pjp.doProxyChain(arguments); long useTime=System.currentTimeMillis() - startTime; AutoLoadConfig config=autoLoadHandler.getConfig(); if(config.isPrintSlowLog() && useTime >= config.getSlowLoadTime()) { String className=pjp.getTargetClass().getName(); logger.error(className + "." + pjp.getMethod().getName() + ", use time:" + useTime + "ms"); } return result; } catch(Throwable e) { throw e; } } /** * * @param pjp CacheAopProxyChain * @param autoLoadTO AutoLoadTO * @param cache Cache * @param cacheKey CacheKeyTO * @return CacheWrapper * @throws Throwable */ private CacheWrapper getCacheWrapper(CacheAopProxyChain pjp, AutoLoadTO autoLoadTO, Cache cache, CacheKeyTO cacheKey) throws Throwable { try { long startTime=System.currentTimeMillis(); Object[] arguments; if(null == autoLoadTO) { arguments=pjp.getArgs(); } else { arguments=autoLoadTO.getArgs(); autoLoadTO.setLoading(true); } Object result=pjp.doProxyChain(arguments); long useTime=System.currentTimeMillis() - startTime; AutoLoadConfig config=autoLoadHandler.getConfig(); if(config.isPrintSlowLog() && useTime >= config.getSlowLoadTime()) { String className=pjp.getTargetClass().getName(); logger.error(className + "." + pjp.getMethod().getName() + ", use time:" + useTime + "ms"); } int expire=CacheUtil.getRealExpire(cache.expire(), cache.expireExpression(), arguments, result); CacheWrapper cacheWrapper=new CacheWrapper(result, expire); if(null != cacheKey && null == autoLoadTO) { autoLoadTO=getAutoLoadTO(pjp, arguments, cache, cacheKey, cacheWrapper); } if(null != autoLoadTO) { autoLoadTO.setLastRequestTime(startTime); autoLoadTO.setLastLoadTime(startTime); autoLoadTO.addUseTotalTime(useTime); } return cacheWrapper; } catch(Throwable e) { throw e; } finally { if(null != autoLoadTO) { autoLoadTO.setLoading(false); } } } /** * * @param pjp CacheAopProxyChain * @param autoLoadTO AutoLoadTO * @param cache Cache annotation * @param cacheKey Cache Key * @param cacheWrapper CacheWrapper * @return CacheWrapper */ private CacheWrapper writeCache(CacheAopProxyChain pjp, AutoLoadTO autoLoadTO, Cache cache, CacheKeyTO cacheKey, CacheWrapper cacheWrapper) { if(null == cacheKey) { return null; } this.setCache(cacheKey, cacheWrapper); ExCache[] exCaches=cache.exCache(); if(null != exCaches && exCaches.length > 0) { Object[] arguments=pjp.getArgs(); if(null != autoLoadTO) { arguments=autoLoadTO.getArgs(); } Object result=cacheWrapper.getCacheObject(); for(ExCache exCache: exCaches) { if(!CacheUtil.isCacheable(exCache, arguments, result)) { continue; } CacheKeyTO exCacheKey=getCacheKey(pjp, autoLoadTO, exCache, result); if(null == exCacheKey) { continue; } Object exResult=null; if(null == exCache.cacheObject() || exCache.cacheObject().length() == 0) { exResult=result; } else { exResult=CacheUtil.getElValue(exCache.cacheObject(), arguments, result, true, Object.class); } int exCacheExpire=CacheUtil.getRealExpire(exCache.expire(), exCache.expireExpression(), arguments, exResult); CacheWrapper exCacheWrapper=new CacheWrapper(exResult, exCacheExpire); AutoLoadTO tmpAutoLoadTO=this.autoLoadHandler.getAutoLoadTO(exCacheKey); if(null != tmpAutoLoadTO) { tmpAutoLoadTO.setExpire(exCacheExpire); tmpAutoLoadTO.setLastLoadTime(exCacheWrapper.getLastLoadTime()); } this.setCache(exCacheKey, exCacheWrapper); } } return cacheWrapper; } @Override public void destroy() { autoLoadHandler.shutdown(); autoLoadHandler=null; logger.info("cache destroy ... ... ..."); } /** * KeyTO * @param className * @param methodName * @param arguments * @param _key key * @param _hfield hfield * @param result * @return CacheKeyTO */ private CacheKeyTO getCacheKey(String className, String methodName, Object[] arguments, String _key, String _hfield, Object result, boolean hasRetVal) { String key=null; String hfield=null; if(null != _key && _key.trim().length() > 0) { key=CacheUtil.getDefinedCacheKey(_key, arguments, result, hasRetVal); if(null != _hfield && _hfield.trim().length() > 0) { hfield=CacheUtil.getDefinedCacheKey(_hfield, arguments, result, hasRetVal); } } else { key=CacheUtil.getDefaultCacheKey(className, methodName, arguments); } if(null == key || key.trim().length() == 0) { logger.error(className + "." + methodName + "; cache key is empty"); return null; } CacheKeyTO to=new CacheKeyTO(); to.setNamespace(namespace); to.setKey(key); to.setHfield(hfield); return to; } /** * Key * @param pjp * @param cache * @return String Key */ private CacheKeyTO getCacheKey(CacheAopProxyChain pjp, Cache cache) { String className=pjp.getTargetClass().getName(); String methodName=pjp.getMethod().getName(); Object[] arguments=pjp.getArgs(); String _key=cache.key(); String _hfield=cache.hfield(); return getCacheKey(className, methodName, arguments, _key, _hfield, null, false); } /** * Key * @param pjp * @param cache * @param result * @return Key */ private CacheKeyTO getCacheKey(CacheAopProxyChain pjp, Cache cache, Object result) { String className=pjp.getTargetClass().getName(); String methodName=pjp.getMethod().getName(); Object[] arguments=pjp.getArgs(); String _key=cache.key(); String _hfield=cache.hfield(); return getCacheKey(className, methodName, arguments, _key, _hfield, result, true); } /** * Key * @param pjp * @param cache * @param result * @return Key */ private CacheKeyTO getCacheKey(CacheAopProxyChain pjp, AutoLoadTO autoLoadTO, ExCache cache, Object result) { String className=pjp.getTargetClass().getName(); String methodName=pjp.getMethod().getName(); Object[] arguments=pjp.getArgs(); if(null != autoLoadTO) { arguments=autoLoadTO.getArgs(); } String _key=cache.key(); if(null == _key || _key.trim().length() == 0) { return null; } String _hfield=cache.hfield(); return getCacheKey(className, methodName, arguments, _key, _hfield, result, true); } /** * Key * @param jp * @param cacheDeleteKey * @param retVal * @return Key */ private CacheKeyTO getCacheKey(DeleteCacheAopProxyChain jp, CacheDeleteKey cacheDeleteKey, Object retVal) { String className=jp.getTargetClass().getName(); String methodName=jp.getMethod().getName(); Object[] arguments=jp.getArgs(); String _key=cacheDeleteKey.value(); String _hfield=cacheDeleteKey.hfield(); return getCacheKey(className, methodName, arguments, _key, _hfield, retVal, true); } /** * AutoLoadTO * @param pjp * @param arguments * @param cache * @param cacheKey * @param cacheWrapper * @return */ private AutoLoadTO getAutoLoadTO(CacheAopProxyChain pjp, Object[] arguments, Cache cache, CacheKeyTO cacheKey, CacheWrapper cacheWrapper) { AutoLoadTO autoLoadTO=null; if(CacheUtil.isAutoload(cache, arguments, cacheWrapper.getCacheObject())) { autoLoadTO=autoLoadHandler.getAutoLoadTO(cacheKey); if(null == autoLoadTO) { AutoLoadTO tmp=autoLoadHandler.putIfAbsent(cacheKey, pjp, cache, serializer, cacheWrapper); if(null != tmp) { autoLoadTO=tmp; } } } return autoLoadTO; } }
package com.kodedu.config; //import com.dooapp.fxform.annotation.Accessor; import com.dooapp.fxform.FXForm; import com.dooapp.fxform.builder.FXFormBuilder; import com.dooapp.fxform.handler.NamedFieldHandler; import com.dooapp.fxform.view.factory.DefaultFactoryProvider; import com.kodedu.component.SliderBuilt; import com.kodedu.config.factory.FileChooserEditableFactory; import com.kodedu.config.factory.SliderFactory; import com.kodedu.config.factory.SpinnerFactory; import com.kodedu.controller.ApplicationController; import com.kodedu.helper.IOHelper; import com.kodedu.service.ThreadService; import com.kodedu.service.ui.TabService; import com.kodedu.terminalfx.config.TerminalConfig; import com.kodedu.terminalfx.helper.FxHelper; import javafx.application.Platform; import javafx.beans.property.*; import javafx.event.ActionEvent; import javafx.geometry.Insets; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.Spinner; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.json.JsonReader; import java.io.Reader; import java.nio.file.Path; import java.util.ResourceBundle; @Component public class TerminalConfigBean extends ConfigurationBase { private StringProperty terminalWinCommand = new SimpleStringProperty("cmd.exe"); private StringProperty terminalNixCommand = new SimpleStringProperty("/bin/bash -i"); private ObjectProperty<Color> backgroundColor = new SimpleObjectProperty<>(Color.rgb(16, 16, 16)); private ObjectProperty<Color> cursorColor = new SimpleObjectProperty<>(Color.WHITE); private ObjectProperty<Color> foregroundColor = new SimpleObjectProperty<>(Color.rgb(240, 240, 240)); private BooleanProperty clearSelectionAfterCopy = new SimpleBooleanProperty(true); private BooleanProperty copyOnSelect = new SimpleBooleanProperty(false); private BooleanProperty ctrlCCopy = new SimpleBooleanProperty(true); private BooleanProperty ctrlVPaste = new SimpleBooleanProperty(true); private BooleanProperty cursorBlink = new SimpleBooleanProperty(false); private BooleanProperty enableClipboardNotice = new SimpleBooleanProperty(true); private BooleanProperty scrollbarVisible = new SimpleBooleanProperty(true); private BooleanProperty useDefaultWindowCopy = new SimpleBooleanProperty(true); private StringProperty fontFamily = new SimpleStringProperty("'DejaVu Sans Mono', 'Everson Mono', FreeMono, 'Menlo', 'Terminal', monospace"); private IntegerProperty fontSize = new SimpleIntegerProperty(14); private DoubleProperty scrollWhellMoveMultiplier = new SimpleDoubleProperty(0.1); private StringProperty receiveEncoding = new SimpleStringProperty("utf-8"); private StringProperty sendEncoding = new SimpleStringProperty("raw"); private StringProperty userCss = new SimpleStringProperty("data:text/plain;base64,eC1zY3JlZW4geyBjdXJzb3I6IGF1dG87IH0="); private BooleanProperty initialized = new SimpleBooleanProperty(false); public boolean isInitialized() { return initialized.get(); } public BooleanProperty initializedProperty() { return initialized; } public void setInitialized(boolean initialized) { this.initialized.set(initialized); } public String getTerminalWinCommand() { return terminalWinCommand.getValue(); } public StringProperty terminalWinCommandProperty() { return terminalWinCommand; } public void setTerminalWinCommand(String terminalWinCommand) { this.terminalWinCommand.set(terminalWinCommand); } public String getTerminalNixCommand() { return terminalNixCommand.getValue(); } public StringProperty terminalNixCommandProperty() { return terminalNixCommand; } public void setTerminalNixCommand(String terminalNixCommand) { this.terminalNixCommand.set(terminalNixCommand); } public Color getBackgroundColor() { return backgroundColor.getValue(); } public ObjectProperty<Color> backgroundColorProperty() { return backgroundColor; } public void setBackgroundColor(Color backgroundColor) { this.backgroundColor.set(backgroundColor); } public Color getCursorColor() { return cursorColor.getValue(); } public ObjectProperty<Color> cursorColorProperty() { return cursorColor; } public void setCursorColor(Color cursorColor) { this.cursorColor.set(cursorColor); } public Color getForegroundColor() { return foregroundColor.getValue(); } public ObjectProperty<Color> foregroundColorProperty() { return foregroundColor; } public void setForegroundColor(Color foregroundColor) { this.foregroundColor.set(foregroundColor); } public Boolean isClearSelectionAfterCopy() { return clearSelectionAfterCopy.getValue(); } public BooleanProperty clearSelectionAfterCopyProperty() { return clearSelectionAfterCopy; } public void setClearSelectionAfterCopy(boolean clearSelectionAfterCopy) { this.clearSelectionAfterCopy.set(clearSelectionAfterCopy); } public Boolean isCopyOnSelect() { return copyOnSelect.getValue(); } public BooleanProperty copyOnSelectProperty() { return copyOnSelect; } public void setCopyOnSelect(boolean copyOnSelect) { this.copyOnSelect.set(copyOnSelect); } public Boolean isCtrlCCopy() { return ctrlCCopy.getValue(); } public BooleanProperty ctrlCCopyProperty() { return ctrlCCopy; } public void setCtrlCCopy(boolean ctrlCCopy) { this.ctrlCCopy.set(ctrlCCopy); } public Boolean isCtrlVPaste() { return ctrlVPaste.getValue(); } public BooleanProperty ctrlVPasteProperty() { return ctrlVPaste; } public void setCtrlVPaste(boolean ctrlVPaste) { this.ctrlVPaste.set(ctrlVPaste); } public boolean isCursorBlink() { return cursorBlink.getValue(); } public BooleanProperty cursorBlinkProperty() { return cursorBlink; } public void setCursorBlink(boolean cursorBlink) { this.cursorBlink.set(cursorBlink); } public Boolean isEnableClipboardNotice() { return enableClipboardNotice.getValue(); } public BooleanProperty enableClipboardNoticeProperty() { return enableClipboardNotice; } public void setEnableClipboardNotice(boolean enableClipboardNotice) { this.enableClipboardNotice.set(enableClipboardNotice); } public Boolean isScrollbarVisible() { return scrollbarVisible.getValue(); } public BooleanProperty scrollbarVisibleProperty() { return scrollbarVisible; } public void setScrollbarVisible(boolean scrollbarVisible) { this.scrollbarVisible.set(scrollbarVisible); } public Boolean isUseDefaultWindowCopy() { return useDefaultWindowCopy.getValue(); } public BooleanProperty useDefaultWindowCopyProperty() { return useDefaultWindowCopy; } public void setUseDefaultWindowCopy(boolean useDefaultWindowCopy) { this.useDefaultWindowCopy.set(useDefaultWindowCopy); } public String getFontFamily() { return fontFamily.getValue(); } public StringProperty fontFamilyProperty() { return fontFamily; } public void setFontFamily(String fontFamily) { this.fontFamily.set(fontFamily); } public Integer getFontSize() { return fontSize.getValue(); } public IntegerProperty fontSizeProperty() { return fontSize; } public void setFontSize(int fontSize) { this.fontSize.set(fontSize); } public Double getScrollWhellMoveMultiplier() { return scrollWhellMoveMultiplier.getValue(); } public DoubleProperty scrollWhellMoveMultiplierProperty() { return scrollWhellMoveMultiplier; } public void setScrollWhellMoveMultiplier(double scrollWhellMoveMultiplier) { this.scrollWhellMoveMultiplier.set(scrollWhellMoveMultiplier); } public String getReceiveEncoding() { return receiveEncoding.getValue(); } public StringProperty receiveEncodingProperty() { return receiveEncoding; } public void setReceiveEncoding(String receiveEncoding) { this.receiveEncoding.set(receiveEncoding); } public String getSendEncoding() { return sendEncoding.getValue(); } public StringProperty sendEncodingProperty() { return sendEncoding; } public void setSendEncoding(String sendEncoding) { this.sendEncoding.set(sendEncoding); } public String getUserCss() { return userCss.getValue(); } public StringProperty userCssProperty() { return userCss; } public void setUserCss(String userCss) { this.userCss.set(userCss); } private Logger logger = LoggerFactory.getLogger(TerminalConfigBean.class); private final ApplicationController controller; private final ThreadService threadService; private final TabService tabService; private final Button saveButton = new Button("Save"); private final Button loadButton = new Button("Load"); private final Label infoLabel = new Label(); @Autowired public TerminalConfigBean(ApplicationController controller, ThreadService threadService, TabService tabService) { super(controller, threadService); this.controller = controller; this.threadService = threadService; this.tabService = tabService; } @Override public String formName() { return "Terminal Settings"; } @Override public VBox createForm() { FXForm editorConfigForm = new FXFormBuilder<>() .resourceBundle(ResourceBundle.getBundle("terminalConfig")) .includeAndReorder( "terminalWinCommand", "terminalNixCommand", "backgroundColor", "cursorColor", "foregroundColor", "clearSelectionAfterCopy", "copyOnSelect", "ctrlCCopy", "ctrlVPaste", "cursorBlink", "enableClipboardNotice", "scrollbarVisible", "useDefaultWindowCopy", "fontFamily", "fontSize", "scrollWhellMoveMultiplier", "receiveEncoding", "sendEncoding", "userCss") .build(); DefaultFactoryProvider editorConfigFormProvider = new DefaultFactoryProvider(); editorConfigFormProvider.addFactory(new NamedFieldHandler("scrollWhellMoveMultiplier"), new SliderFactory(SliderBuilt.create(0.0, 1, 0.1).step(0.1))); editorConfigFormProvider.addFactory(new NamedFieldHandler("fontSize"), new SpinnerFactory(new Spinner(8, 32, 14))); FileChooserEditableFactory fileChooserEditableFactory = new FileChooserEditableFactory(); editorConfigForm.setEditorFactoryProvider(editorConfigFormProvider); fileChooserEditableFactory.setOnEdit(tabService::addTab); editorConfigForm.setSource(this); VBox vBox = new VBox(); vBox.getChildren().add(editorConfigForm); saveButton.setOnAction(this::save); loadButton.setOnAction(this::load); HBox box = new HBox(5, saveButton, loadButton, infoLabel); box.setPadding(new Insets(0, 0, 15, 5)); vBox.getChildren().add(box); return vBox; } @Override public Path getConfigPath() { return super.resolveConfigPath("terminal_config.json"); } @Override public void load(Path configPath, ActionEvent... actionEvent) { fadeOut(infoLabel, "Loading..."); Reader fileReader = IOHelper.fileReader(configPath); JsonReader jsonReader = Json.createReader(fileReader); JsonObject jsonObject = jsonReader.readObject(); String terminalWinCommand = jsonObject.getString("terminalWinCommand", this.terminalWinCommand.getValue()); String terminalNixCommand = jsonObject.getString("terminalNixCommand", this.terminalNixCommand.getValue()); String backgroundColor = jsonObject.getString("backgroundColor", FxHelper.colorToHex(this.backgroundColor.getValue())); String cursorColor = jsonObject.getString("cursorColor", FxHelper.colorToHex(this.backgroundColor.getValue())); String foregroundColor = jsonObject.getString("foregroundColor", FxHelper.colorToHex(this.backgroundColor.getValue())); Boolean clearSelectionAfterCopy = jsonObject.getBoolean("clearSelectionAfterCopy", this.clearSelectionAfterCopy.getValue()); Boolean copyOnSelect = jsonObject.getBoolean("copyOnSelect", this.copyOnSelect.getValue()); Boolean ctrlCCopy = jsonObject.getBoolean("ctrlCCopy", this.ctrlCCopy.getValue()); Boolean ctrlVPaste = jsonObject.getBoolean("ctrlVPaste", this.ctrlVPaste.getValue()); Boolean cursorBlink = jsonObject.getBoolean("cursorBlink", this.cursorBlink.getValue()); Boolean enableClipboardNotice = jsonObject.getBoolean("enableClipboardNotice", this.enableClipboardNotice.getValue()); Boolean scrollbarVisible = jsonObject.getBoolean("scrollbarVisible", this.scrollbarVisible.getValue()); Boolean useDefaultWindowCopy = jsonObject.getBoolean("useDefaultWindowCopy", this.useDefaultWindowCopy.getValue()); String fontFamily = jsonObject.getString("fontFamily", this.fontFamily.getValue()); Integer fontSize = jsonObject.getInt("fontSize", this.fontSize.getValue()); String receiveEncoding = jsonObject.getString("receiveEncoding", this.receiveEncoding.getValue()); String sendEncoding = jsonObject.getString("sendEncoding", this.sendEncoding.getValue()); String userCss = jsonObject.getString("userCss", this.userCss.getValue()); Boolean initialized = jsonObject.getBoolean("initialized", this.initialized.getValue()); IOHelper.close(jsonReader, fileReader); threadService.runActionLater(() -> { this.setTerminalWinCommand(terminalWinCommand); this.setTerminalNixCommand(terminalNixCommand); this.setBackgroundColor(Color.web(backgroundColor)); this.setCursorColor(Color.web(cursorColor)); this.setForegroundColor(Color.web(foregroundColor)); this.setClearSelectionAfterCopy(clearSelectionAfterCopy); this.setCopyOnSelect(copyOnSelect); this.setCtrlCCopy(ctrlCCopy); this.setCtrlVPaste(ctrlVPaste); this.setCursorBlink(cursorBlink); this.setEnableClipboardNotice(enableClipboardNotice); this.setScrollbarVisible(scrollbarVisible); this.setUseDefaultWindowCopy(useDefaultWindowCopy); this.setFontFamily(fontFamily); this.setFontSize(fontSize); this.setReceiveEncoding(receiveEncoding); this.setSendEncoding(sendEncoding); this.setUserCss(userCss); this.setInitialized(initialized); if (jsonObject.containsKey("scrollWhellMoveMultiplier")) { this.setScrollWhellMoveMultiplier(jsonObject.getJsonNumber("scrollWhellMoveMultiplier").doubleValue()); } fadeOut(infoLabel, "Loaded..."); }); } @Override public void save(ActionEvent... actionEvent) { infoLabel.setText("Saving..."); saveJson(getJSON()); fadeOut(infoLabel, "Saved..."); } @Override public JsonObject getJSON() { JsonObjectBuilder objectBuilder = Json.createObjectBuilder(); objectBuilder .add("terminalWinCommand", getTerminalWinCommand()) .add("terminalNixCommand", getTerminalNixCommand()) .add("backgroundColor", FxHelper.colorToHex(getBackgroundColor())) .add("cursorColor", FxHelper.colorToHex(getCursorColor())) .add("foregroundColor", FxHelper.colorToHex(getForegroundColor())) .add("clearSelectionAfterCopy", isClearSelectionAfterCopy()) .add("copyOnSelect", isCopyOnSelect()) .add("ctrlCCopy", isCtrlCCopy()) .add("ctrlVPaste", isCtrlVPaste()) .add("cursorBlink", isCursorBlink()) .add("enableClipboardNotice", isEnableClipboardNotice()) .add("scrollbarVisible", isScrollbarVisible()) .add("useDefaultWindowCopy", isUseDefaultWindowCopy()) .add("fontFamily", getFontFamily()) .add("fontSize", getFontSize()) .add("scrollWhellMoveMultiplier", getScrollWhellMoveMultiplier()) .add("receiveEncoding", getReceiveEncoding()) .add("sendEncoding", getSendEncoding()) .add("userCss", getUserCss()) .add("initialized", isInitialized()); return objectBuilder.build(); } public TerminalConfig createTerminalConfig() { TerminalConfig terminalConfig = new TerminalConfig(); terminalConfig.setBackgroundColor(getBackgroundColor()); terminalConfig.setCursorColor(getCursorColor()); terminalConfig.setForegroundColor(getForegroundColor()); terminalConfig.setClearSelectionAfterCopy(isClearSelectionAfterCopy()); terminalConfig.setCopyOnSelect(isCopyOnSelect()); terminalConfig.setCtrlCCopy(isCtrlCCopy()); terminalConfig.setCtrlVPaste(isCtrlVPaste()); terminalConfig.setCursorBlink(isCursorBlink()); terminalConfig.setEnableClipboardNotice(isEnableClipboardNotice()); terminalConfig.setScrollbarVisible(isScrollbarVisible()); terminalConfig.setUseDefaultWindowCopy(isUseDefaultWindowCopy()); terminalConfig.setFontFamily(getFontFamily()); terminalConfig.setFontSize(getFontSize()); terminalConfig.setScrollWhellMoveMultiplier(getScrollWhellMoveMultiplier()); terminalConfig.setUserCss(getUserCss()); terminalConfig.setWindowsTerminalStarter(getTerminalWinCommand()); terminalConfig.setUnixTerminalStarter(getTerminalNixCommand()); return terminalConfig; } public void changeTheme(EditorConfigBean.Theme theme) { if (initialized.get()) { return; } initialized.set(true); Platform.runLater(() -> { if (theme.getThemeName().equals("Dark")) { setBackgroundColor(Color.rgb(16, 16, 16)); setForegroundColor(Color.rgb(240, 240, 240)); setCursorColor(Color.WHITE); } else if (theme.getThemeName().equals("Default")) { setBackgroundColor(Color.WHITE); setForegroundColor(Color.BLACK); setCursorColor(Color.BLACK); } }); } }
package nu.nerd.easyrider; import java.util.HashSet; import java.util.Set; import java.util.UUID; import java.util.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.entity.AbstractHorse; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Horse; import org.bukkit.entity.Llama; import org.bukkit.entity.Player; import org.bukkit.entity.SkeletonHorse; import org.bukkit.entity.ZombieHorse; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.metadata.FixedMetadataValue; import me.libraryaddict.disguise.DisguiseAPI; import me.libraryaddict.disguise.disguisetypes.DisguiseType; import me.libraryaddict.disguise.disguisetypes.MobDisguise; /** * Utility functions that don't necessarily belong in a specific class. */ public class Util { /** * Return true if the specified entity is trackable. * * Trackable entities have their location, appearance and some inventory * state tracked. They are guaranteed to be instances of AbstractHorse. * * @param entity an entity. * @return true if the specified entity is trackable. */ public static boolean isTrackable(Entity entity) { return entity instanceof AbstractHorse; } /** * Return true if the entity can have its attributes improved through * training. * * Horses, SkeletonHorses and ZombieHorses are trainable; Llamas are not. * * @param entity an entity. * @return true if the entity can have its attributes improved through * training. */ public static boolean isTrainable(Entity entity) { return isTrackable(entity) && !(entity instanceof Llama); } /** * Return true if the specified entity is a skeleton horse or zombie horse. * * @return true if the specified entity is a skeleton horse or zombie horse. */ public static boolean isUndeadHorse(Entity entity) { return entity instanceof SkeletonHorse || entity instanceof ZombieHorse; } /** * Return a human-readable entity type name. * * @param entity the Entity. * @return a human-readable entity type name. */ public static String entityTypeName(Entity entity) { return entity.getType().name().toLowerCase().replace('_', ' '); } /** * Find the AbstractHorse entity with the specified UUID near the specified * location. * * A square of chunks around the location are loaded if necessary. If that * area does not contain the AbstractHorse, all loaded chunks in all worlds * are searched, starting with the world containing the specified Location. * * @param uuid the AbstractHorse's UUID. * @param loc the Location where the AbstractHorse was last seen; if null, * it is not used. * @param chunkRadius the radius of a square, expressed in chunks, around * the Location that will be searched. This number should be small as * loading chunks can be time-consuming and may lag out the server. * @return the matching AbstractHorse, if found, or null. */ public static AbstractHorse findHorse(UUID uuid, Location loc, int chunkRadius) { if (loc == null) { return findHorse(uuid); } World centreWorld = loc.getWorld(); Chunk centreChunk = loc.getChunk(); AbstractHorse horse = findHorse(uuid, centreChunk); if (horse != null) { return horse; } for (int r = 1; r < chunkRadius; ++r) { // Top and bottom rows of chunks around centreChunk. for (int x = -chunkRadius; x <= chunkRadius; ++x) { int chunkX = centreChunk.getX() + x; Chunk chunk = centreWorld.getChunkAt(chunkX, centreChunk.getZ() - chunkRadius); horse = findHorse(uuid, chunk); if (horse != null) { return horse; } chunk = centreWorld.getChunkAt(chunkX, centreChunk.getZ() + chunkRadius); horse = findHorse(uuid, chunk); if (horse != null) { return horse; } } // Left and right columns of chunks, excluding top/bottom row. for (int z = -chunkRadius + 1; z <= chunkRadius - 1; ++z) { int chunkZ = centreChunk.getZ() + z; Chunk chunk = centreWorld.getChunkAt(centreChunk.getX() - chunkRadius, chunkZ); horse = findHorse(uuid, chunk); if (horse != null) { return horse; } chunk = centreWorld.getChunkAt(centreChunk.getX() + chunkRadius, chunkZ); horse = findHorse(uuid, chunk); if (horse != null) { return horse; } } } // Search loaded chunks, starting with original World. horse = findHorse(uuid, centreWorld); if (horse != null) { return horse; } for (String worldName : EasyRider.CONFIG.SCAN_WORLD_RADIUS.keySet()) { World world = Bukkit.getWorld(worldName); if (world != null && world != centreWorld) { horse = findHorse(uuid, world); if (horse != null) { return horse; } } } return null; } /** * Search all loaded chunks of all configured worlds, in arbitrary order, * for an AbstractHorse with the specified UUID. * * @param uuid the AbstractHorse's UUID. * @return the AbstractHorse entity or null if not found. */ public static AbstractHorse findHorse(UUID uuid) { for (String worldName : EasyRider.CONFIG.SCAN_WORLD_RADIUS.keySet()) { World world = Bukkit.getWorld(worldName); if (world != null) { AbstractHorse horse = findHorse(uuid, world); if (horse != null) { return horse; } } } return null; } /** * Find the AbstractHorse entity with the specified UUID in the specified * chunk. * * @param uuid the AbstractHorse's UUID. * @param chunk the chunk to search. * @return the matching AbstractHorse, if found, or null. */ public static AbstractHorse findHorse(UUID uuid, Chunk chunk) { if (!chunk.isLoaded() && !chunk.load(false)) { return null; } for (Entity entity : chunk.getEntities()) { if (entity.getUniqueId().equals(uuid)) { return (AbstractHorse) entity; } } return null; } /** * Find the AbstractHorse entity with the specified UUID in the currently * loaded chunks of the specified World. * * @param uuid the AbstractHorse's UUID. * @param chunk the chunk to search. * @return the matching AbstractHorse, if found, or null. */ public static AbstractHorse findHorse(UUID uuid, World world) { for (Entity entity : world.getEntities()) { if (entity.getUniqueId().equals(uuid)) { return (AbstractHorse) entity; } } return null; } /** * Return the appearance of the specified AbstractHorse as a displayable * String. * * @param abstractHorse the horse-like creature. * @return the appearance of the specified AbstractHorse as a displayable * String. */ public static String getAppearance(AbstractHorse abstractHorse) { if (abstractHorse instanceof Horse) { Horse horse = (Horse) abstractHorse; return COLOR_TO_APPEARANCE[horse.getColor().ordinal()] + STYLE_TO_APPEARANCE[horse.getStyle().ordinal()]; } else if (abstractHorse instanceof Llama) { Llama llama = (Llama) abstractHorse; Llama.Color colour = llama.getColor(); return colour.name().toLowerCase() + " llama"; } else { return entityTypeName(abstractHorse); } } /** * Re-apply disguises to all disguised steeds when a player joins. */ public static void refreshSaddleDisguises() { for (Player onlinePlayer : Bukkit.getOnlinePlayers()) { if (onlinePlayer.getVehicle() instanceof AbstractHorse) { AbstractHorse abstractHorse = (AbstractHorse) onlinePlayer.getVehicle(); EntityType disguiseEntityType = Util.getSaddleDisguiseType(abstractHorse); if (disguiseEntityType != null) { boolean showToRider = Util.isSaddleDisguiseVisibleToRider(abstractHorse); Util.applySaddleDisguise(abstractHorse, onlinePlayer, disguiseEntityType, showToRider); } } } } /** * Disguise a horse as a specified EntityType and notify a player when it is * still disguised. * * @param abstractHorse the horse-like entity. * @param rider the rider, to be notified if a disguise is applied. * @param disguiseEntityType the EntityType of the disguise. * @param showToRider if true, the disguise is visible to the rider. */ public static void applySaddleDisguise(AbstractHorse abstractHorse, Player rider, EntityType disguiseEntityType, boolean showToRider) { if (disguiseEntityType == null) { return; } DisguiseType disguiseType = DisguiseType.getType(disguiseEntityType); if (disguiseType != null) { MobDisguise disguise = new MobDisguise(disguiseType); Set<Player> players = new HashSet<>(Bukkit.getOnlinePlayers()); if (!showToRider) { players.remove(rider); } DisguiseAPI.undisguiseToAll(abstractHorse); DisguiseAPI.disguiseToPlayers(abstractHorse, disguise, players); rider.sendMessage(ChatColor.GOLD + "Your steed is disguised as " + disguiseEntityType + "!"); abstractHorse.removeMetadata(SELF_DISGUISE_KEY, EasyRider.PLUGIN); if (showToRider) { abstractHorse.setMetadata(SELF_DISGUISE_KEY, new FixedMetadataValue(EasyRider.PLUGIN, null)); } } else { Logger logger = EasyRider.PLUGIN.getLogger(); logger.warning("Horse " + abstractHorse.getUniqueId() + " accessed by " + rider.getName() + " has a saddle with unsupported disguise " + disguiseEntityType + "."); } } /** * Return true if the saddle disguise of the specified horse is visible to * the rider. * * @param abstractHorse the horse-like entity. * @return true if the saddle disguise of the specified horse is visible to * the rider. */ public static boolean isSaddleDisguiseVisibleToRider(AbstractHorse abstractHorse) { return !abstractHorse.getMetadata(SELF_DISGUISE_KEY).isEmpty(); } /** * Return the EntityType of the disguise associated with a horse's saddle, * or null if the saddle doesn't confer a disguise (or it's not a saddle). * * @param abstractHorse the horse-like entity. * @return the EntityType of the disguise, or null if no disguise should be * applied. */ public static EntityType getSaddleDisguiseType(AbstractHorse abstractHorse) { ItemStack saddle = getSaddleItemStack(abstractHorse); if (saddle == null || saddle.getType() != Material.SADDLE) { return null; } ItemMeta meta = saddle.getItemMeta(); if (meta != null && meta.hasLore()) { for (String lore : meta.getLore()) { if (lore.startsWith(EasyRider.DISGUISE_PREFIX)) { String entityTypeName = lore.substring(EasyRider.DISGUISE_PREFIX.length()).trim().toUpperCase(); try { return EntityType.valueOf(entityTypeName); } catch (IllegalArgumentException ex) { } } } } return null; } /** * Get the ItemStack in the saddle slot of a horse, donkey or mule. * * @param abstractHorse the horse-like entity (includes llamas). * @return the ItemStack in the saddle slot, or null if there is no saddle * slot (as in the case of llamas). */ public static ItemStack getSaddleItemStack(AbstractHorse abstractHorse) { if (abstractHorse instanceof Llama) { return null; } // Mules, donkeys, zombie- and skeletal- horses do not have a // HorseInventory. So get the saddle by ID rather than calling // HorseInventory.getSaddle(). return abstractHorse.getInventory().getItem(0); } /** * Return the horizontal distance from a to b, ignoring Y coordinate * changes. * * @return the horizontal distance from a to b. */ public static double getHorizontalDistance(Location a, Location b) { if (a.getWorld().equals(b.getWorld())) { double dx = b.getX() - a.getX(); double dz = b.getZ() - a.getZ(); return Math.sqrt(dx * dx + dz * dz); } else { return 0.0; } } /** * Limit a string to the specified maximum length, showing trailing elipses * if truncated. * * @param s the string. * @param maxLength the maximum length of the result, including the elipses. * @return the string limited to the specified maximum length. */ public static String limitString(String s, int maxLength) { return s.length() <= maxLength ? s : s.substring(0, maxLength - 1) + "\u2026"; } /** * Change the first letter of a string to upper case. * * @param s the string. * @return the string, with the first letter changed to upper case. */ public static String capitalise(String s) { return s.isEmpty() ? s : s.charAt(0) + s.substring(1); } /** * Format a location as "(x, y, z) world", with integer coordinates. * * @param loc the location. * @return the location as a formatted String. */ public static String formatLocation(Location loc) { return new StringBuilder().append('(') .append(loc.getBlockX()).append(", ") .append(loc.getBlockY()).append(", ") .append(loc.getBlockZ()).append(") ") .append(loc.getWorld().getName()).toString(); } /** * Return the linear interpolation between min and max. * * @param min the value to return for the minimum value of frac (0.0). * @param max the value to return for the maximum value of frac (1.0). * @param frac the fraction, in the range [0,1] of the max argument, with * the remainder coming from the min argument. NOTE: if frac exceeds * 1.0, extrapolate linearly. * @return the interpolation between min and max. */ public static double linterp(double min, double max, double frac) { return min + frac * (max - min); } /** * The string form of Horse.Color constants as returned by getAppearance(), * listed in the same order as the enum. */ private static final String[] COLOR_TO_APPEARANCE = { "white", "creamy", "chestnut", "brown", "black", "gray", "dark brown" }; /** * The string form of Horse.Style constants as returned by getAppearance(), * listed in the same order as the enum. */ private static final String[] STYLE_TO_APPEARANCE = { "", ", socks", ", whitefield", ", white dots", ", black dots" }; /** * Metadata key for metadata signifying that a saddle disguise is visible to * the rider. * * If metadata with this key is absent, the rider cannot see the disguise. */ private static final String SELF_DISGUISE_KEY = "EasyRider_self_disguise"; } // class Util
package com.kodcu.config; import java.util.Objects; import java.util.Optional; import org.apache.log4j.Logger; import org.elasticsearch.client.Client; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings.Builder; import org.elasticsearch.common.transport.InetSocketTransportAddress; import java.net.InetAddress; public class ElasticConfiguration { private final Logger logger = Logger.getLogger(ElasticConfiguration.class); private final YamlConfiguration config; private Client client; public ElasticConfiguration(final YamlConfiguration config) { this.config = config; this.prepareClient(); } private void prepareClient() { try { Builder settingsBuilder = Settings.builder(); settingsBuilder.put("client.transport.ping_timeout", "15s"); settingsBuilder.put("client.transport.nodes_sampler_interval", "5s"); // YG: to ensure reliable connection & resolve NoNodeAvailableException settingsBuilder.put("client.transport.sniff", true); settingsBuilder.put("network.bind_host", 0); // YG: for supporting ES Auth with ES Shield Optional.ofNullable(config.getElastic().getAuth()).ifPresent(auth -> settingsBuilder.put("shield.user", String.join(":", auth.getUser(), auth.getPwd()))); if (Objects.nonNull(config.getElastic().getClusterName())) { settingsBuilder.put("cluster.name", config.getElastic().getClusterName()); } else { settingsBuilder.put("client.transport.ignore_cluster_name", true); } InetSocketTransportAddress ista = new InetSocketTransportAddress(InetAddress.getByName(config.getElastic().getHost()), config.getElastic().getPort()); client = TransportClient.builder().settings(settingsBuilder.build()).build().addTransportAddress(ista); } catch (Exception ex) { logger.error(ex.getMessage(), ex.fillInStackTrace()); } } public void closeNode() { client.close(); } public Client getClient() { return client; } }
package org.openmrs.layout.web.name; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openmrs.api.context.Context; import org.openmrs.layout.web.LayoutSupport; /** * @deprecated * @see org.openmrs.layout.name.NameSupport */ @Deprecated public class NameSupport extends LayoutSupport<NameTemplate> { private static volatile NameSupport singleton; static Log log = LogFactory.getLog(NameSupport.class); public NameSupport() { if (singleton == null) { singleton = this; } } public static synchronized NameSupport getInstance() { if (singleton == null) { throw new RuntimeException("Not Yet Instantiated"); } else { return singleton; } } public String getDefaultLayoutFormat() { String ret = Context.getAdministrationService().getGlobalProperty("layout.name.format"); return (ret != null && ret.length() > 0) ? ret : defaultLayoutFormat; } }
package com.llnw.storage.client; import com.google.common.base.Function; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; import com.google.gson.stream.MalformedJsonException; import com.llnw.storage.client.io.ActivityCallback; import com.llnw.storage.client.io.Chunk; import com.llnw.storage.client.io.HeartbeatInputStream; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.Charsets; import org.apache.commons.io.IOUtils; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.InputStreamEntity; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.InputStreamBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.joda.time.Duration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import javax.annotation.concurrent.NotThreadSafe; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.channels.ClosedByInterruptException; import java.nio.channels.FileChannel; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.TimeUnit; @NotThreadSafe public class EndpointHTTP implements EndpointMultipart { private static final Logger log = LoggerFactory.getLogger(EndpointHTTP.class); private static final String AUTH_HEADER = "X-Agile-Authorization"; private static final String JSON_RPC_PATH = "/jsonrpc"; private final URL endpoint; private final String username; private final String password; private final HttpClient client = new DefaultHttpClient(); private final Gson gson = new Gson(); private final JsonParser parser = new JsonParser(); private int id; private String auth; private String mpid; private int chunks; public EndpointHTTP(URL endpoint, String username, String password) { this.endpoint = endpoint; this.username = username; this.password = password; } @Override public void deleteDirectory(String path) throws IOException { int returnCode = execute(new RPC("deleteDir", "path", path)).getAsInt(); if (returnCode != 0) { // 0 indicates success throw throwAndLog("Couldn't delete directory: " + returnCode); } } @Override public void deleteFile(String path) throws IOException { final int returnCode = execute(new RPC("deleteFile", "path", path)).getAsInt(); if (returnCode != 0) { // 0 indicates success throw throwAndLog("Couldn't delete file: " + returnCode); } } @Override public void close() throws IOException { try { final JsonElement element = execute(new RPC("logout")); if (element.isJsonNull()) { throw throwAndLog("Couldn't logout"); } final int returnCode = element.getAsInt(); if (returnCode != 0) { // 0 indicates success throw throwAndLog("Couldn't logout: " + returnCode); } } finally { auth = null; client.getConnectionManager().closeIdleConnections(0, TimeUnit.MILLISECONDS); } } @Override public void makeDirectory(String path) throws IOException { // 0 indicates success, -2, -1 or 1 indicates the path already exists final ImmutableSet<Integer> successErrorCodes = ImmutableSet.of(-2, -1, 0, 1); final int returnCode = execute(new RPC("makeDir2", "path", path)).getAsInt(); if (!successErrorCodes.contains(returnCode)) { throw throwAndLog("Couldn't make directory: " + returnCode); } // Otherwise success, do nothing } @Override public List<String> listFiles(String path) throws IOException { final RPC call = new RPC("listFile", "path", path); final JsonElement list = execute(call).getAsJsonObject().get("list"); if (list == null) { return Lists.newArrayList(); } final List<NameUnmangler> nameUnmanglers = Arrays.asList(gson.fromJson(list, NameUnmangler[].class)); return Lists.newArrayList(Lists.transform(nameUnmanglers, new Function<NameUnmangler, String>() { @Override public String apply(@Nullable NameUnmangler o) { return o == null ? "" : o.name; } })); } @Override public boolean exists(String path) throws IOException { final RPC call = new RPC("stat", "path", path); final JsonElement stat = execute(call).getAsJsonObject().get("code"); return stat.getAsInt() == 0; } @Override public void noop() throws IOException { execute(new RPC("noop", "operation", "lvp")); } @Override public String startMultipartUpload(String path, String name) throws IOException { final RPC call = new RPC("createMultipart", "path", path + "/" + name); final JsonElement mpid = execute(call).getAsJsonObject().get("mpid"); this.mpid = mpid.getAsString(); chunks = 1; return this.mpid; } @Override public void completeMultipartUpload() throws IOException { if (mpid == null) throw new IllegalArgumentException("Must call startUpload before completeUpload"); final RPC call = new RPC("completeMultipart", "mpid", mpid); final JsonObject result = execute(call).getAsJsonObject(); final int returnCode = result.get("code").getAsInt(); final int returnedChunks = result.get("numpieces").getAsInt(); if (returnCode != 0 || returnedChunks != chunks - 1) { // 0 indicates success throw throwAndLog("Couldn't complete multipart upload with mpid(" + mpid + "): " + returnCode); } } @Override public void abortMultipartUpload() throws IOException { if (mpid == null) throw new IllegalArgumentException("Must call startUpload before abortUpload"); final RPC call = new RPC("abortMultipart", "mpid", mpid); final int returnCode = execute(call).getAsJsonObject().get("code").getAsInt(); if (returnCode != 0) { // 0 indicates success throw throwAndLog("Couldn't abort multipart upload with mpid(" + mpid + "): " + returnCode); } this.mpid = null; } @Override public void uploadPart(File file, Iterator<Chunk> chunkIterator, @Nullable ActivityCallback callback) throws IOException { requireAuth(); if (mpid == null) throw new IllegalArgumentException("Must call startUpload before uploadPart"); @SuppressWarnings("resource") final FileChannel fc = new FileInputStream(file).getChannel(); try { while(chunkIterator.hasNext()) { final Chunk chunk = chunkIterator.next(); int toUploadChunk = chunks; if (!chunk.appending) { // Need to figure out which chunk this is updating final int pageSize = 100; int startChunk = 1; int ret = -1; while (startChunk < chunks && (ret = whichChunkOffset(startChunk, chunk.offset, pageSize)) == -1) { startChunk += pageSize; } if (startChunk > chunks) { throw throwAndLog("Couldn't find chunk with offset: " + chunk.offset); } toUploadChunk = ret; } final HttpPost post = new HttpPost(endpoint.toString() + "/multipart/piece"); try { post.addHeader(AUTH_HEADER, auth); post.addHeader("X-Agile-Part", Integer.toString(toUploadChunk)); post.addHeader("X-Agile-Multipart", mpid); final InputStream is = HeartbeatInputStream.wrap(fc, chunk, callback); final String sha256 = DigestUtils.sha256Hex(is); is.reset(); final InputStreamEntity entity = new InputStreamEntity(is, chunk.length); post.setEntity(entity); final HttpResponse response = client.execute(post); final int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_OK) { final Map<String, String> headerChecks = ImmutableMap.of( "X-Agile-Status", "0", "X-Agile-Size", Long.toString(chunk.length), "X-Agile-Checksum", sha256); checkHeaders(response, headerChecks); } else { log.warn("Got status: " + status + " from upload." + " Response: " + responseToString(response)); throw throwAndLog("Got status: " + response.getStatusLine().getStatusCode() + " from upload"); } } finally { post.releaseConnection(); } if (toUploadChunk == chunks) { // This was appending, so increment the number of chunks chunks++; } } } catch (IOException e) { throw unwindInterruptException(e); } finally { fc.close(); } } @Override public void upload(File file, String path, String name, @Nullable ActivityCallback callback) throws IOException { requireAuth(); final HttpPost post = new HttpPost(endpoint.toString() + "/post/file"); try { post.addHeader(AUTH_HEADER, auth); final MultipartEntity entity = new MultipartEntity(); entity.addPart("directory", new StringBody(path, Charsets.UTF_8)); entity.addPart("basename", new StringBody(name, Charsets.UTF_8)); final InputStreamBody body = new InputStreamBody(new HeartbeatInputStream(file, callback), file.getName()); entity.addPart("uploadFile", body); post.setEntity(entity); final HttpResponse response = client.execute(post); final int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_OK) { final String sha256 = DigestUtils.sha256Hex(new HeartbeatInputStream(file, callback)); final Map<String, String> headerChecks = ImmutableMap.of( "X-Agile-Status", "0", "X-Agile-Size", Long.toString(file.length()), "X-Agile-Checksum", sha256); checkHeaders(response, headerChecks); } else { log.warn("Got status: " + status + " from upload." + " Response: " + responseToString(response)); throw throwAndLog("Got status: " + response.getStatusLine().getStatusCode() + " from upload"); } } catch (IOException e) { throw unwindInterruptException(e); } finally { post.releaseConnection(); } } @Override public void setMpid(String mpid) { this.mpid = mpid; } @Override public void resumeMultipartUpload() throws IOException { final MultipartStatus status = getMultipartStatus(); // will throw if invalid mpid if (!MultipartStatus.READY.equals(status)) { throw throwAndLog("Got incorrect status(" + status + ") from getMultipartStatus"); } } @Override public MultipartStatus getMultipartStatus() throws IOException { if (mpid == null) throw new IllegalArgumentException("Must call startUpload or setMpid before this"); final RPC call = new RPC("getMultipartStatus", "mpid", mpid); final JsonObject elem = execute(call).getAsJsonObject(); int code = 0; if (!elem.has("code") || (code = elem.get("code").getAsInt()) != 0) { throw throwAndLog("Invalid mpid: " + code + " obj: " + elem); } final int state; if (!elem.has("state")) { throw throwAndLog("Invalid returned object"); } state = elem.get("state").getAsInt(); if (state < 0 || state >= MultipartStatus.values().length) { throw throwAndLog("State out of supported range"); } return MultipartStatus.values()[state]; } private int whichChunkOffset(final int startingChunk, final long targetOffset, final int pageSize) throws IOException { final RPC call = new RPC("listMultipartPiece", "mpid", mpid, "lastpiece", Integer.toString(startingChunk), "pagesize", Integer.toString(pageSize)); final JsonObject ret = execute(call).getAsJsonObject(); int code = 0; if (!ret.has("code") || (code = ret.get("code").getAsInt()) != 0 || !ret.has("pieces")) { // Failure throw throwAndLog("Invalid code for listMultipartPiece: " + code + " obj: " + ret); } final JsonArray pieces = ret.get("pieces").getAsJsonArray(); long offset = 0; int chunk = startingChunk; for (JsonElement elem : pieces) { final JsonObject obj = elem.getAsJsonObject(); offset += obj.get("size").getAsLong(); if (offset > targetOffset) return chunk; else chunk++; } return -1; // not found } private void checkHeaders(HttpResponse response, Map<String, String> headerChecks) throws EndpointException { for (Entry<String, String> headerCheck : headerChecks.entrySet()) { final Header h = response.getFirstHeader(headerCheck.getKey()); if (h == null || !h.getValue().equalsIgnoreCase(headerCheck.getValue())) { throw throwAndLog(headerCheck.getKey() + ", got: " + h.getValue() + ", expected: " + headerCheck.getValue()); } } } private JsonElement execute(RPC args) throws IOException { return execute(args, null); } private JsonElement execute(RPC args, @Nullable Map<String, String> checkHeaders) throws IOException { requireAuth(); final HttpPost post = new HttpPost(endpoint.toString() + JSON_RPC_PATH); post.addHeader(AUTH_HEADER, auth); args.params.put("token", auth); final String message = gson.toJson(args); String response = ""; try { post.setEntity(new StringEntity(message)); final HttpResponse httpResponse = client.execute(post); response = responseToString(httpResponse); final int status = httpResponse.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) { log.warn("Got status " + status + " from " + args.method + "(" + args.params.toString() + ")." + " Response: " + response); throw throwAndLog("Got status: " + status + " from method: " + args.method); } else if (checkHeaders != null) { checkHeaders(httpResponse, checkHeaders); } final JsonObject obj = parser.parse(response).getAsJsonObject(); if (obj.has("result")) { return obj.get("result"); } else { final String msg = String.format("No result field from %s(%s) response: %s", args.method, args.params.toString(), response); throw throwAndLog(msg); } } catch (JsonSyntaxException e) { log.error("JsonSyntaxException from {}", response, e); throw e; } catch (MalformedJsonException e) { log.error("Bad JSON {}", response, e); throw e; } catch (IOException e) { throw unwindInterruptException(e); } finally { post.releaseConnection(); } } private JsonElement getResult(String response) throws IOException { try { final JsonObject obj = parser.parse(response).getAsJsonObject(); final JsonElement err = obj.get("error"); if (err != null && !err.isJsonNull()) { throw throwAndLog(obj.get("error").getAsString()); } return obj.get("result"); } catch (JsonSyntaxException e) { log.error("JsonSyntaxException from {} in getResult", response, e); throw e; } } private String responseToString(final HttpResponse response) throws IOException { return IOUtils.toString(response.getEntity().getContent(), Charsets.UTF_8); } private void requireAuth() throws IOException { if (!Strings.isNullOrEmpty(auth)) return; final HttpPost post = new HttpPost(endpoint.toString() + JSON_RPC_PATH); final String message = gson.toJson(new RPC("login", "username", username, "password", password)); try { post.setEntity(new StringEntity(message)); final String response = responseToString(client.execute(post)); final JsonArray array = getResult(response).getAsJsonArray(); auth = gson.fromJson(array.get(0), String.class); if (Strings.isNullOrEmpty(auth)) { throw throwAndLog("Null or empty auth, response: " + response); } } finally { post.releaseConnection(); } } private IOException unwindInterruptException(IOException e) throws IOException { // This is dumb. Sometimes httpcomponents will throw a ClientProtocolException which wraps the real // exception we want to throw when interrupted, ClosedByInterruptException. So, try to find that // exception in the stack, and then throw that one instead Throwable t = e.getCause(); int i = 10; // cause depth limit while (i-- > 0 && t != null && !(t instanceof ClosedByInterruptException)) { t = t.getCause(); } if (t instanceof ClosedByInterruptException) { throw (IOException)t; } else { throw e; } } private EndpointException throwAndLog(String message) throws EndpointException { log.error(message); throw new EndpointException(message); } @SuppressWarnings({"unused", "serial"}) private class RPC { private final String jsonrpc = "2.0"; private final String method; private final Map<String,String> params; private final int id; private RPC(final String method) { this(method, new HashMap<String, String>()); } private RPC(final String method, final String paramOneName, final String paramOneValue) { this(method, new HashMap<String, String>() {{ put(paramOneName, paramOneValue); }}); } private RPC(final String method, final String paramOneName, final String paramOneValue, final String paramTwoName, final String paramTwoValue) { this(method, new HashMap<String, String>() {{ put(paramOneName, paramOneValue); put(paramTwoName, paramTwoValue); }}); } private RPC(final String method, final String paramOneName, final String paramOneValue, final String paramTwoName, final String paramTwoValue, final String paramThreeName, final String paramThreeValue) { this(method, new HashMap<String, String>() {{ put(paramOneName, paramOneValue); put(paramTwoName, paramTwoValue); put(paramThreeName, paramThreeValue); }}); } private RPC(String method, Map<String, String> params) { this.method = method; this.params = params; this.id = ++EndpointHTTP.this.id; } } @SuppressWarnings("unused") private class NameUnmangler { private final String name; private final int type; private NameUnmangler(String name, int type) { this.name = name; this.type = type; } } }
package com.philihp.weblabora.action; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import com.philihp.weblabora.form.GameForm; import com.philihp.weblabora.jpa.Game; import com.philihp.weblabora.jpa.User; public class ShowGame extends BaseAction { @Override public ActionForward execute(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response, User user) throws Exception { EntityManager em = (EntityManager)request.getAttribute("em"); GameForm form = (GameForm)actionForm; if(form.getGameId() == null) { return mapping.findForward("no-game"); } Game game = findGame(em, form.getGameId()); user.setActiveGame(game); request.setAttribute("game", game); if(form.getStateId() == null) { form.setStateId(game.getState().getStateId()); } return mapping.findForward("game-state"); } protected static Game.Player findPlayerInGame(Game game, User user) { if(user == null) return null; String facebookId = user.getFacebookId(); if(facebookId == null) return null; for(Game.Player player : game.getAllPlayers()) { if(player != null && player.getUser() != null && player.getUser().getFacebookId() != null && player.getUser().getFacebookId().equals(facebookId)) { return player; } } return null; } protected static Game findGame(EntityManager em, int gameId) { return em.find(Game.class, gameId); } protected static List<Game> findGamesForUser(EntityManager em, User user) { TypedQuery<Game> query = em .createQuery( "SELECT g " + "FROM Game g " + "WHERE g.player1.user = :user " + "OR g.player2.user = :user " + "OR g.player3.user = :user " + "OR g.player4.user = :user " + "ORDER BY g.gameId", Game.class); query.setParameter("user", user); List<Game> results = query.getResultList(); return results; } }
package omnikryptec.postprocessing.main; import de.codemakers.io.file.AdvancedFile; import java.awt.image.BufferedImage; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.time.LocalDateTime; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import javax.imageio.ImageIO; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import org.lwjgl.opengl.GL14; import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GL30; import omnikryptec.display.Display; import omnikryptec.graphics.OpenGL; import omnikryptec.resource.texture.Texture; import omnikryptec.settings.GameSettings; import omnikryptec.util.EnumCollection.DepthbufferType; import omnikryptec.util.Instance; import omnikryptec.util.exceptions.IllegalAccessException; import omnikryptec.util.logger.Logger; public class FrameBufferObject extends Texture { private final int width; private final int height; private int frameBuffer; private int depthTexture; private int depthBuffer; private int[] colBuffers; private int multisample = GameSettings.NO_MULTISAMPLING; private boolean multitarget = false; private RenderTarget[] targets; private DepthbufferType type; private static List<FrameBufferObject> fbos = new ArrayList<>(); private static ArrayDeque<FrameBufferObject> history = new ArrayDeque<>(); /** * Creates an FBO of a specified width and height, with the desired type of * depth buffer attachment. * * @param width - the width of the FBO. * @param height - the height of the FBO. * @param type - an int indicating the type of depth buffer attachment that * this FBO should use. */ public FrameBufferObject(int width, int height, DepthbufferType type, RenderTarget... targets) { super("", true); this.width = width; this.height = height; this.targets = targets; this.multitarget = targets.length > 1; initialiseFrameBuffer(type); } public FrameBufferObject(int width, int height, DepthbufferType type) { this(width, height, type, new RenderTarget(GL30.GL_COLOR_ATTACHMENT0)); } /** * only for the engine * * @param width * @param height * @param multisamples */ public FrameBufferObject(int width, int height, int multisamples, RenderTarget... targets) { super("", true); this.width = width; this.height = height; this.multisample = multisamples; this.targets = targets; this.multitarget = targets.length > 1; initialiseFrameBuffer(DepthbufferType.DEPTH_RENDER_BUFFER); } public FrameBufferObject(int width, int height, int multisamples, RenderTarget[] add, RenderTarget... targets) { super("", true); this.width = width; this.height = height; this.multisample = multisamples; this.targets = new RenderTarget[add.length + targets.length]; for (int i = 0; i < targets.length; i++) { this.targets[i] = targets[i]; } for (int i = 0; i < add.length; i++) { this.targets[i + targets.length] = add[i]; } this.multitarget = this.targets.length > 1; initialiseFrameBuffer(DepthbufferType.DEPTH_RENDER_BUFFER); } public FrameBufferObject(int width, int height, int multisamples) { this(width, height, multisamples, new RenderTarget(GL30.GL_COLOR_ATTACHMENT0)); } public boolean isMultisampled() { return multisample != GameSettings.NO_MULTISAMPLING; } public boolean isMultitarget() { return multitarget; } public RenderTarget[] getTargets() { return targets; } /** * Deletes the frame buffer and its attachments when the game closes. */ public void delete() { GL30.glDeleteFramebuffers(frameBuffer); GL11.glDeleteTextures(depthTexture); GL30.glDeleteRenderbuffers(depthBuffer); for (int i = 0; i < colBuffers.length; i++) { if (multisample != GameSettings.NO_MULTISAMPLING) { GL30.glDeleteRenderbuffers(colBuffers[i]); } else { GL11.glDeleteTextures(colBuffers[i]); } } } public void bindFrameBuffer() { bindFrameBuffer(false); } /** * Binds the frame buffer, setting it as the current render target. Anything * rendered after this will be rendered to this FBO, and not to the screen. */ public void bindFrameBuffer(boolean ar) { history.push(this); GL30.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, frameBuffer); if(ar) { OpenGL.gl11viewport(Display.calculateViewport(width, height)); }else { OpenGL.gl11viewport(0, 0, width, height); } } /** * Unbinds the frame buffer, setting the default frame buffer as the current * render target. Anything rendered after this will be rendered to the * screen, and not this FBO. */ public void unbindFrameBuffer() { GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0); history.pop(); if(!history.isEmpty()){ history.pop().bindFrameBuffer(); }else { Display.resetViewport(); } } /** * Binds the current FBO to be read from (not used in tutorial 43). */ public void bindToRead(int attachment) { Texture.unbindActive(); GL30.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, frameBuffer); GL11.glReadBuffer(attachment); } /** * @return The texture containing the FBOs depth buffer. */ public int getDepthTexture() { return depthTexture; } public DepthbufferType getDepthbufferType() { return type; } public int getTexture(int index) { if (multisample != GameSettings.NO_MULTISAMPLING) { throw new IllegalAccessException("This framebuffer is multisampled and has no textures."); } return colBuffers[index]; } public void resolveToFbo(FrameBufferObject out, int attachment) { resolveToFbo(out, attachment, true); } public void resolveToFbo(FrameBufferObject out, int attachment, boolean depth) { GL30.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, out.frameBuffer); GL30.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, frameBuffer); GL11.glReadBuffer(attachment); GL30.glBlitFramebuffer(0, 0, width, height, 0, 0, out.width, out.height, GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT, GL11.GL_NEAREST); GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0); if (depth) { resolveDepth(out); } } public void resolveDepth(FrameBufferObject out) { GL30.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, out.frameBuffer); GL30.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, frameBuffer); GL11.glReadBuffer(GL30.GL_DEPTH_ATTACHMENT); GL30.glBlitFramebuffer(0, 0, width, height, 0, 0, out.width, out.height, GL11.GL_DEPTH_BUFFER_BIT, GL11.GL_NEAREST); GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0); } public void resolveToScreen() { GL30.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, 0); GL30.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, frameBuffer); GL11.glDrawBuffer(GL11.GL_BACK); GL30.glBlitFramebuffer(0, 0, width, height, 0, 0, Display.getWidth(), Display.getHeight(), GL11.GL_COLOR_BUFFER_BIT, GL11.GL_NEAREST); GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0); } /** * Creates the FBO along with a colour buffer texture attachment, and * possibly a depth buffer. * * @param type - the type of depth buffer attachment to be attached to the * FBO. */ private void initialiseFrameBuffer(DepthbufferType type) { this.type = type; fbos.add(this); colBuffers = new int[targets.length]; frameBuffer = GL30.glGenFramebuffers(); bindFrameBuffer(); determineDrawBuffers(); if (multisample != GameSettings.NO_MULTISAMPLING) { for (int i = 0; i < targets.length; i++) { colBuffers[i] = createMultisampleColourAttachment(targets[i].target, targets[i].extended); //? GL30.GL_RGBA32F : GL11.GL_RGBA8); } } else { for (int i = 0; i < targets.length; i++) { colBuffers[i] = createTextureAttachment(targets[i].target, targets[i].extended); //? GL30.GL_RGBA32F : GL11.GL_RGBA8); } } if (type == DepthbufferType.DEPTH_RENDER_BUFFER) { createDepthBufferAttachment(); } else if (type == DepthbufferType.DEPTH_TEXTURE) { createDepthTextureAttachment(); } unbindFrameBuffer(); } private void determineDrawBuffers() { IntBuffer drawBuffers = BufferUtils.createIntBuffer(targets.length); for (int i = 0; i < targets.length; i++) { drawBuffers.put(targets[i].target); } drawBuffers.flip(); GL20.glDrawBuffers(drawBuffers); } private int createMultisampleColourAttachment(int attachment, int level) { int colourBuffer = GL30.glGenRenderbuffers(); GL30.glBindRenderbuffer(GL30.GL_RENDERBUFFER, colourBuffer); GL30.glRenderbufferStorageMultisample(GL30.GL_RENDERBUFFER, multisample, level, width, height); GL30.glFramebufferRenderbuffer(GL30.GL_FRAMEBUFFER, attachment, GL30.GL_RENDERBUFFER, colourBuffer); return colourBuffer; } /** * Creates a texture and sets it as the colour buffer attachment for this * FBO. */ private int createTextureAttachment(int attachment, int level) { int colourTexture = GL11.glGenTextures(); Texture.bindAndReset(GL11.GL_TEXTURE_2D, colourTexture); GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, level, width, height, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, (ByteBuffer) null); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE); GL30.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, attachment, GL11.GL_TEXTURE_2D, colourTexture, 0); return colourTexture; } /** * Adds a depth buffer to the FBO in the form of a texture, which can later * be sampled. */ private void createDepthTextureAttachment() { depthTexture = GL11.glGenTextures(); Texture.bindAndReset(GL11.GL_TEXTURE_2D, depthTexture); GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL14.GL_DEPTH_COMPONENT24, width, height, 0, GL11.GL_DEPTH_COMPONENT, GL11.GL_FLOAT, (ByteBuffer) null); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); GL30.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_DEPTH_ATTACHMENT, GL11.GL_TEXTURE_2D, depthTexture, 0); } /** * Adds a depth buffer to the FBO in the form of a render buffer. This can't * be used for sampling in the shaders. */ private void createDepthBufferAttachment() { depthBuffer = GL30.glGenRenderbuffers(); GL30.glBindRenderbuffer(GL30.GL_RENDERBUFFER, depthBuffer); if (multisample != GameSettings.NO_MULTISAMPLING) { GL30.glRenderbufferStorageMultisample(GL30.GL_RENDERBUFFER, multisample, GL14.GL_DEPTH_COMPONENT24, width, height); } else { GL30.glRenderbufferStorage(GL30.GL_RENDERBUFFER, GL14.GL_DEPTH_COMPONENT24, width, height); } GL30.glFramebufferRenderbuffer(GL30.GL_FRAMEBUFFER, GL30.GL_DEPTH_ATTACHMENT, GL30.GL_RENDERBUFFER, depthBuffer); } /** * info[0] is the attachmentindex to use */ @Override protected void bindToUnit(int unit, int... info) { if (info == null || info.length == 0) { info = new int[]{0}; } OpenGL.gl13activeTextureZB(unit); super.bindTexture(GL11.GL_TEXTURE_2D, getTexture(info[0])); } public void bindDepthTexture(int unit) { OpenGL.gl13activeTextureZB(unit); super.bindTexture(GL11.GL_TEXTURE_2D, getDepthTexture()); } public static void cleanup() { for (int i = 0; i < fbos.size(); i++) { fbos.get(i).delete(); } fbos.clear(); history.clear(); } public final BufferedImage toBufferedImage() { return toBufferedImage(true); } public final BufferedImage toBufferedImage(boolean withTransparency) { // if(multisample != GameSettings.NO_MULTISAMPLING) { // throw new UnsupportedOperationException("Multisampled FBOs are not supported!"); //DONE Weil muessen erst auf ein einziges gerendert werden FrameBufferObject my = new FrameBufferObject(this.width, this.height, DepthbufferType.NONE); this.resolveToFbo(my, GL30.GL_COLOR_ATTACHMENT0); try { final FloatBuffer buffer = BufferUtils.createFloatBuffer(width * height * (withTransparency ? 4 : 3)); my.bindToRead(GL30.GL_COLOR_ATTACHMENT0); GL11.glReadPixels(0, 0, width, height, (withTransparency ? GL11.GL_RGBA : GL11.GL_RGB), GL11.GL_FLOAT, buffer); GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0); buffer.rewind(); final int[] rgbArray = new int[width * height]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { final int r = (int) (buffer.get() * 255) << 16; final int g = (int) (buffer.get() * 255) << 8; final int b = (int) (buffer.get() * 255); int a = (255 << 24); if (withTransparency) { a = (int) (buffer.get() * 255) << 24; } final int i = ((height - 1) - y) * width + x; rgbArray[i] = (r + g + b + a); } } final BufferedImage image = new BufferedImage(width, height, (withTransparency ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB)); image.setRGB(0, 0, width, height, rgbArray, 0, width); return image; } catch (Exception ex) { if (Logger.isDebugMode()) { Logger.logErr("Error while converting FBO to BufferedImage: " + ex, ex); } return null; } } public final boolean saveAsScreenshotInFolder(AdvancedFile folder) { return saveAsScreenshotInFolder(folder, "screenshot"); } public final boolean saveAsScreenshotInFolder(AdvancedFile folder, String name) { return saveAsScreenshotInFolder(folder, name, "png"); } public final boolean saveAsScreenshotInFolder(AdvancedFile folder, String name, String format) { return saveAsScreenshotInFolder(folder, name, format, false); } public final boolean saveAsScreenshotInFolder(AdvancedFile folder, String name, String format, boolean withTimestamp) { return saveAsScreenshotInFolder(folder, name, format, withTimestamp, true); } public final boolean saveAsScreenshotInFolder(AdvancedFile folder, String name, String format, boolean withTimestamp, boolean withTransparency) { AdvancedFile file = null; if (withTimestamp) { file = new AdvancedFile(folder, String.format("%s_%s.%s", name, LocalDateTime.now().format(Instance.DATETIMEFORMAT_TIMESTAMP), format)); } else { int i = 1; while (file == null || file.exists()) { file = new AdvancedFile(folder, String.format("%s_%d.%s", name, i, format)); i++; } } return saveAsScreenshot(file, format, withTransparency); } public final boolean saveAsScreenshot(AdvancedFile file) { return saveAsScreenshot(file, "png"); } public final boolean saveAsScreenshot(AdvancedFile file, String format) { return saveAsScreenshot(file, format, true); } public final boolean saveAsScreenshot(AdvancedFile file, String format, boolean withTransparency) { try { final BufferedImage image = toBufferedImage(withTransparency); if (image != null) { file.createAdvancedFile(); if (!file.exists() || !file.isFile()) { return false; } ImageIO.write(image, format, file.createOutputstream(false)); return true; } else { return false; } } catch (Exception ex) { if (Logger.isDebugMode()) { Logger.logErr("Error while saving Screenshot: " + ex, ex); } return false; } } @Override public float getWidth() { return width; } @Override public float getHeight() { return height; } }
package br.com.caelum.parsac.util; import br.com.caelum.parsac.modelo.Aberto; import br.com.caelum.parsac.modelo.Alternativa; import br.com.caelum.parsac.modelo.MultiplaEscolha; import br.com.caelum.parsac.modelo.Secao; import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; public class SecaoConverter implements Converter { public boolean canConvert(Class clazz) { return clazz.equals(Secao.class); } public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) { Secao secao = (Secao) value; writer.startNode("numero"); writer.setValue(String.valueOf(secao.getNumero())); writer.endNode(); writer.startNode("titulo"); writer.setValue(String.valueOf(secao.getTitulo())); writer.endNode(); writer.startNode("explicacao"); writer.setValue(String.valueOf(secao.getExplicacao())); writer.endNode(); } public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { Secao secao = new Secao(); reader.moveDown(); secao.setNumero(Integer.parseInt(reader.getValue())); reader.moveUp(); reader.moveDown(); secao.setTitulo(reader.getValue()); reader.moveUp(); reader.moveDown(); secao.setExplicacao(reader.getValue()); reader.moveUp(); reader.moveDown(); while (reader.hasMoreChildren()) { reader.moveDown(); if (reader.getNodeName().equals("exercicio-aberto")) { Aberto aberto = new Aberto(); reader.moveDown(); aberto.setEnunciado(reader.getValue()); reader.moveUp(); reader.moveDown(); aberto.setResposta(reader.getValue()); reader.moveUp(); secao.getExerciciosAbertos().add(aberto); } else if (reader.getNodeName().equals("exercicio-multiplaEscolha")) { MultiplaEscolha exercicio = new MultiplaEscolha(); reader.moveDown(); exercicio.setEnunciado(reader.getValue()); reader.moveUp(); reader.moveDown(); if (reader.getNodeName().equals("alternativas")) { while (reader.hasMoreChildren()) { reader.moveDown(); reader.moveDown(); exercicio.getAlternativas().add( new Alternativa(reader.getValue())); reader.moveUp(); reader.moveUp(); } reader.moveUp(); reader.moveDown(); } if (reader.getNodeName().equals("resposta")) { reader.moveDown(); reader.moveDown(); exercicio.setResposta(reader.getValue()); reader.moveUp(); reader.moveUp(); } secao.getExerciciosMultiplaEscolhas().add(exercicio); } reader.moveUp(); } reader.moveUp(); return secao; } }
// of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // all copies or substantial portions of the Software. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package com.microsoft.graph.core; import javax.annotation.Nullable; import javax.annotation.Nonnull; import com.google.gson.JsonElement; import com.microsoft.graph.content.BatchRequestBuilder; import com.microsoft.graph.http.IHttpProvider; import com.microsoft.graph.logger.ILogger; import com.microsoft.graph.serializer.ISerializer; /** * A client that communications with an OData service * @param <nativeRequestType> type of a request for the native http client */ public interface IBaseClient<nativeRequestType> { /** * Gets the service root * * @return the service root */ @Nonnull String getServiceRoot(); /** * Sets the service root * * @param value the service root */ void setServiceRoot(@Nonnull final String value); /** * Gets the HTTP provider * * @return the HTTP provider */ @Nullable IHttpProvider<nativeRequestType> getHttpProvider(); /** * Gets the logger * * @return the logger */ @Nullable ILogger getLogger(); /** * Gets the serializer * * @return the serializer */ @Nullable ISerializer getSerializer(); /** * Gets a builder to execute a custom request * * @return the custom request builder * @param url the url to send the request to * @param responseType the class to deserialize the response to * @param <T> the type to deserialize the response to */ @Nonnull <T> CustomRequestBuilder<T> customRequest(@Nonnull final String url, @Nonnull final Class<T> responseType); /** * Gets a builder to execute a custom request with a generic JSONObject response * * @return the custom request builder * @param url the url to send the request to */ @Nonnull CustomRequestBuilder<JsonElement> customRequest(@Nonnull final String url); /** * Get the batch request builder. * @return a request builder to execute a batch. */ @Nonnull BatchRequestBuilder batch(); /** * Gets the service SDK version if the service SDK is in use, null otherwise * @return the service SDK version if the service SDK is in use, null otherwise */ @Nullable String getServiceSDKVersion(); }
package org.adligo.tests4j_4jacoco.plugin; import java.util.Collections; import java.util.HashSet; import java.util.Set; /** * this provides a way to load classes (mostly interfaces) in the default class loader * so that they are the same in child class loaders. * * @author scott * */ public class SharedClassList { public static Set<String> WHITELIST = getSharedClassWhitelist(); private static Set<String> getSharedClassWhitelist() { Set<String> toRet = new HashSet<String>(); toRet.add("org.adligo.tests4j.models.shared.asserts.common.I_AssertCompareFailure"); toRet.add("org.adligo.tests4j.models.shared.asserts.common.I_AssertCommand"); toRet.add("org.adligo.tests4j.models.shared.asserts.common.I_AssertionData"); toRet.add("org.adligo.tests4j.models.shared.asserts.common.I_AssertThrownFailure"); toRet.add("org.adligo.tests4j.models.shared.asserts.common.I_Asserts"); toRet.add("org.adligo.tests4j.models.shared.asserts.common.I_AssertType"); toRet.add("org.adligo.tests4j.models.shared.asserts.common.I_CollectionContainsAssertionData"); toRet.add("org.adligo.tests4j.models.shared.asserts.common.I_CollectionAssertionData"); toRet.add("org.adligo.tests4j.models.shared.asserts.common.I_CompareAssertCommand"); toRet.add("org.adligo.tests4j.models.shared.asserts.common.I_CompareAssertionData"); toRet.add("org.adligo.tests4j.models.shared.asserts.common.I_ExpectedThrownData"); toRet.add("org.adligo.tests4j.models.shared.asserts.common.I_SimpleAssertCommand"); toRet.add("org.adligo.tests4j.models.shared.asserts.common.I_SimpleCompareAssertCommand"); toRet.add("org.adligo.tests4j.models.shared.asserts.common.I_AssertType"); toRet.add("org.adligo.tests4j.models.shared.asserts.common.I_TestFailure"); toRet.add("org.adligo.tests4j.models.shared.asserts.common.I_TestFailureType"); toRet.add("org.adligo.tests4j.models.shared.asserts.common.I_ThrowableInfo"); toRet.add("org.adligo.tests4j.models.shared.asserts.common.I_Thrower"); toRet.add("org.adligo.tests4j.models.shared.asserts.common.I_ThrownAssertCommand"); toRet.add("org.adligo.tests4j.models.shared.asserts.common.I_ThrownAssertionData"); toRet.add("org.adligo.tests4j.models.shared.asserts.line_text.I_DiffIndexes"); toRet.add("org.adligo.tests4j.models.shared.asserts.line_text.I_DiffIndexesPair"); toRet.add("org.adligo.tests4j.models.shared.asserts.line_text.I_LineDiff"); toRet.add("org.adligo.tests4j.models.shared.asserts.line_text.I_LineDiffType"); toRet.add("org.adligo.tests4j.models.shared.asserts.line_text.I_TextLines"); toRet.add("org.adligo.tests4j.models.shared.asserts.line_text.I_TextLinesCompareResult"); toRet.add("org.adligo.tests4j.models.shared.asserts.uniform.I_Evaluation"); toRet.add("org.adligo.tests4j.models.shared.asserts.uniform.I_EvaluatorLookup"); toRet.add("org.adligo.tests4j.models.shared.asserts.uniform.I_UniformAssertionCommand"); toRet.add("org.adligo.tests4j.models.shared.asserts.uniform.I_UniformAssertionEvaluator"); toRet.add("org.adligo.tests4j.models.shared.asserts.uniform.I_UniformThrownAssertionCommand"); toRet.add("org.adligo.tests4j.models.shared.asserts.uniform.I_UniformThrownAssertionEvaluator"); toRet.add("org.adligo.tests4j.models.shared.common.I_TrialType"); toRet.add("org.adligo.tests4j.models.shared.common.I_Platform"); toRet.add("org.adligo.tests4j.models.shared.common.I_PlatformContainer"); toRet.add("org.adligo.tests4j.models.shared.common.I_Immutable"); toRet.add("org.adligo.tests4j.models.shared.common.I_System"); toRet.add("org.adligo.tests4j.models.shared.coverage.I_CoverageUnits"); toRet.add("org.adligo.tests4j.models.shared.coverage.I_CoverageUnitsContainer"); toRet.add("org.adligo.tests4j.models.shared.coverage.I_LineCoverage"); toRet.add("org.adligo.tests4j.models.shared.coverage.I_LineCoverageSegment"); toRet.add("org.adligo.tests4j.models.shared.coverage.I_PackageCoverage"); toRet.add("org.adligo.tests4j.models.shared.coverage.I_SourceFileCoverage"); toRet.add("org.adligo.tests4j.models.shared.dependency.I_ClassAlias"); toRet.add("org.adligo.tests4j.models.shared.dependency.I_ClassAliasLocal"); toRet.add("org.adligo.tests4j.models.shared.dependency.I_ClassAttributes"); toRet.add("org.adligo.tests4j.models.shared.dependency.I_ClassFilter"); toRet.add("org.adligo.tests4j.models.shared.dependency.I_ClassFilterModel"); toRet.add("org.adligo.tests4j.models.shared.dependency.I_ClassParents"); toRet.add("org.adligo.tests4j.models.shared.dependency.I_ClassParentsCache"); toRet.add("org.adligo.tests4j.models.shared.dependency.I_ClassParentsLocal"); toRet.add("org.adligo.tests4j.models.shared.dependency.I_ClassDependencies"); toRet.add("org.adligo.tests4j.models.shared.dependency.I_ClassDependenciesCache"); toRet.add("org.adligo.tests4j.models.shared.dependency.I_ClassDependenciesLocal"); toRet.add("org.adligo.tests4j.models.shared.dependency.I_FieldSignature"); toRet.add("org.adligo.tests4j.models.shared.dependency.I_Dependency"); toRet.add("org.adligo.tests4j.models.shared.dependency.I_DependencyGroup"); toRet.add("org.adligo.tests4j.models.shared.dependency.I_MethodSignature"); toRet.add("org.adligo.tests4j.models.shared.metadata.I_SourceInfoMetadata"); toRet.add("org.adligo.tests4j.models.shared.metadata.I_TestMetadata"); toRet.add("org.adligo.tests4j.models.shared.metadata.I_TrialMetadata"); toRet.add("org.adligo.tests4j.models.shared.metadata.I_TrialRunMetadata"); toRet.add("org.adligo.tests4j.models.shared.metadata.I_UseCaseMetadata"); toRet.add("org.adligo.tests4j.models.shared.results.I_ApiTrialResult"); toRet.add("org.adligo.tests4j.models.shared.results.I_Duration"); toRet.add("org.adligo.tests4j.models.shared.results.I_SourceFileTrialResult"); toRet.add("org.adligo.tests4j.models.shared.results.I_TestResult"); toRet.add("org.adligo.tests4j.models.shared.results.I_TrialFailure"); toRet.add("org.adligo.tests4j.models.shared.results.I_TrialResult"); toRet.add("org.adligo.tests4j.models.shared.results.I_TrialRunResult"); toRet.add("org.adligo.tests4j.models.shared.results.I_UseCaseTrialResult"); toRet.add("org.adligo.tests4j.models.shared.system.I_Tests4J_AssertListener"); toRet.add("org.adligo.tests4j.models.shared.system.I_Tests4J_Controls"); toRet.add("org.adligo.tests4j.models.shared.system.I_Tests4J_CoveragePlugin"); toRet.add("org.adligo.tests4j.models.shared.system.I_Tests4J_CoveragePluginParams"); toRet.add("org.adligo.tests4j.models.shared.system.I_Tests4J_CoverageRecorder"); toRet.add("org.adligo.tests4j.models.shared.system.I_Tests4J_CoverageTrialInstrumentation"); toRet.add("org.adligo.tests4j.models.shared.system.I_Tests4J_Delegate"); toRet.add("org.adligo.tests4j.models.shared.system.I_Tests4J_DelegateFactory"); toRet.add("org.adligo.tests4j.models.shared.system.I_Tests4J_Listener"); toRet.add("org.adligo.tests4j.models.shared.system.I_Tests4J_Params"); toRet.add("org.adligo.tests4j.models.shared.system.I_Tests4J_ProcessInfo"); toRet.add("org.adligo.tests4j.models.shared.system.I_Tests4J_ProgressMonitor"); toRet.add("org.adligo.tests4j.models.shared.system.I_Tests4J_RemoteInfo"); toRet.add("org.adligo.tests4j.models.shared.system.I_Tests4J_Runnable"); toRet.add("org.adligo.tests4j.models.shared.system.I_Tests4J_TestFinishedListener"); toRet.add("org.adligo.tests4j.models.shared.system.I_Tests4J_TrialList"); toRet.add("org.adligo.tests4j.models.shared.system.I_Tests4J_TrialProgress"); toRet.add("org.adligo.tests4j.models.shared.i18n.I_Tests4J_AnnotationErrors"); toRet.add("org.adligo.tests4j.models.shared.i18n.I_Tests4J_AssertionInputMessages"); toRet.add("org.adligo.tests4j.models.shared.i18n.I_Tests4J_ResultMessages"); toRet.add("org.adligo.tests4j.models.shared.i18n.I_Tests4J_Constants"); toRet.add("org.adligo.tests4j.models.shared.i18n.I_Tests4J_EclipseErrors"); toRet.add("org.adligo.tests4j.models.shared.i18n.I_Tests4J_LineDiffTextDisplayMessages"); toRet.add("org.adligo.tests4j.models.shared.i18n.I_Tests4J_ParamReaderMessages"); toRet.add("org.adligo.tests4j.models.shared.i18n.I_Tests4J_ReportMessages"); toRet.add("org.adligo.tests4j.models.shared.trials.AfterTrial"); toRet.add("org.adligo.tests4j.models.shared.trials.BeforeTrial"); toRet.add("org.adligo.tests4j.models.shared.trials.I_AbstractTrial"); toRet.add("org.adligo.tests4j.models.shared.trials.I_ApiTrial"); toRet.add("org.adligo.tests4j.models.shared.trials.I_CircularDependencies"); toRet.add("org.adligo.tests4j.models.shared.trials.IgnoreTest"); toRet.add("org.adligo.tests4j.models.shared.trials.IgnoreTrial"); toRet.add("org.adligo.tests4j.models.shared.trials.I_Trial"); toRet.add("org.adligo.tests4j.models.shared.trials.I_MetaTrialInputData"); toRet.add("org.adligo.tests4j.models.shared.trials.I_MetaTrialParams"); toRet.add("org.adligo.tests4j.models.shared.trials.I_MetaTrialParamsAware"); toRet.add("org.adligo.tests4j.models.shared.trials.I_TrialParams"); toRet.add("org.adligo.tests4j.models.shared.trials.I_TrialParamsAware"); toRet.add("org.adligo.tests4j.models.shared.trials.I_TrialParamsFactory"); toRet.add("org.adligo.tests4j.models.shared.trials.I_TrialBindings"); toRet.add("org.adligo.tests4j.models.shared.trials.I_MetaTrial"); toRet.add("org.adligo.tests4j.models.shared.trials.I_Progress"); toRet.add("org.adligo.tests4j.models.shared.trials.I_SourceFileTrial"); toRet.add("org.adligo.tests4j.models.shared.trials.I_SubProgress"); toRet.add("org.adligo.tests4j.models.shared.trials.I_UseCaseTrial"); toRet.add("org.adligo.tests4j.models.shared.trials.PackageScope"); toRet.add("org.adligo.tests4j.models.shared.trials.SourceFileScope"); toRet.add("org.adligo.tests4j.models.shared.trials.SuppressOutput"); toRet.add("org.adligo.tests4j.models.shared.trials.Test"); toRet.add("org.adligo.tests4j.models.shared.trials.TrialTypeAnnotation"); toRet.add("org.adligo.tests4j.models.shared.trials.UseCaseScope"); toRet.add("org.adligo.tests4j.models.shared.xml.I_XML_Builder"); toRet.add("org.adligo.tests4j.models.shared.xml.I_XML_Consumer"); toRet.add("org.adligo.tests4j.models.shared.xml.I_XML_Producer"); toRet.add("org.adligo.tests4j.shared.output.I_ConcurrentOutputDelegator"); toRet.add("org.adligo.tests4j.shared.output.I_OutputBuffer"); toRet.add("org.adligo.tests4j.shared.output.I_OutputDelegateor"); toRet.add("org.adligo.tests4j.shared.output.I_ToggleOutputBuffer"); toRet.add("org.adligo.tests4j.shared.output.I_Tests4J_Log"); toRet.add("org.adligo.tests4j.run.helpers.I_CachedClassBytesClassLoader"); toRet.add("org.adligo.tests4j.run.helpers.I_Tests4J_Memory"); toRet.add("org.adligo.tests4j.run.remote.socket_api.I_AfterMessageHandler"); add4JacocoAndAsmClasses(toRet); for (String clazz: toRet) { checkClass(clazz); } return Collections.unmodifiableSet(toRet); } protected static void add4JacocoAndAsmClasses(Set<String> toRet) { toRet.add("org.adligo.tests4j_4jacoco.plugin.common.I_ClassInstrumenter"); toRet.add("org.adligo.tests4j_4jacoco.plugin.common.I_ClassInstrumenterFactory"); toRet.add("org.adligo.tests4j_4jacoco.plugin.common.I_CoveragePluginMemory"); toRet.add("org.adligo.tests4j_4jacoco.plugin.common.I_LoggerDataAccessorFactory"); toRet.add("org.adligo.tests4j_4jacoco.plugin.common.I_ObtainProbesStrategy"); toRet.add("org.adligo.tests4j_4jacoco.plugin.common.I_OrderedClassDependencies"); toRet.add("org.adligo.tests4j_4jacoco.plugin.common.I_OrderedClassDiscovery"); toRet.add("org.adligo.tests4j_4jacoco.plugin.common.I_OrderedClassDiscoveryFactory"); toRet.add("org.adligo.tests4j_4jacoco.plugin.common.I_ProbeDataAccessorFactory"); toRet.add("org.adligo.tests4j_4jacoco.plugin.common.I_Runtime"); toRet.add("org.adligo.tests4j_4jacoco.plugin.common.I_StackHelper"); toRet.add("org.adligo.tests4j_4jacoco.plugin.common.I_TrialInstrumenter"); toRet.add("org.adligo.tests4j_4jacoco.plugin.common.I_TrialInstrumenterFactory"); toRet.add("org.adligo.tests4j_4jacoco.plugin.data.common.I_Probes"); toRet.add("org.adligo.tests4j_4jacoco.plugin.data.common.I_ClassProbes"); toRet.add("org.adligo.tests4j_4jacoco.plugin.data.common.I_ClassProbesMutant"); toRet.add("org.adligo.tests4j_4jacoco.plugin.data.common.I_MultiRecordingProbeDataStore"); toRet.add("org.adligo.tests4j_4jacoco.plugin.data.common.I_ProbesDataStore"); toRet.add("org.adligo.tests4j_4jacoco.plugin.data.common.I_ProbesDataStoreAdaptor"); toRet.add("org.adligo.tests4j_4jacoco.plugin.instrumentation.AbstractProbeInserter"); toRet.add("org.adligo.tests4j_4jacoco.plugin.instrumentation.I_ProbeInserterFactory"); toRet.add("org.adligo.tests4j_4jacoco.plugin.instrumentation.common.I_ClassInstrumentationInfo"); toRet.add("org.adligo.tests4j_4jacoco.plugin.instrumentation.common.I_ClassProbesVisitor"); toRet.add("org.adligo.tests4j_4jacoco.plugin.instrumentation.common.I_MethodProbesVisitor"); toRet.add("org.adligo.tests4j_4jacoco.plugin.instrumentation.common.I_ProbeIdGenerator"); toRet.add("org.adligo.tests4j_4jacoco.plugin.instrumentation.common.I_ObtainProbesOfType"); toRet.add("org.objectweb.asm.MethodVisitor"); } /** * extracted so it can be tested for the runtime exception * @param clazz */ public static void checkClass(String clazz) { try { //actually load all of the classes using the default classloader here Class.forName(clazz, false, ClassLoader.getSystemClassLoader()); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } }
package broadwick.stochastic; import com.google.common.collect.Table; import com.google.common.collect.TreeBasedTable; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import lombok.Getter; import lombok.Setter; import lombok.Synchronized; import lombok.extern.slf4j.Slf4j; @Slf4j public abstract class StochasticSimulator { /** * Creates a new simulator using a given amount manager. * @param amountManager the amount manager used in the simulator. * @param transitionKernel the transition kernel to be used with the stochastic solver. */ public StochasticSimulator(final AmountManager amountManager, final TransitionKernel transitionKernel) { this(amountManager, transitionKernel, false); } /** * Creates a new simulator. * @param amountManager the amount manager used in the simulator. * @param transitionKernel the transition kernel to be used with the stochastic solver. * @param reverseTime true if we wish to go backwards in time. */ public StochasticSimulator(final AmountManager amountManager, final TransitionKernel transitionKernel, final boolean reverseTime) { this.amountManager = amountManager; this.transitionKernel = transitionKernel; this.reverseTime = reverseTime; this.thetaQueue = new ThetaQueue(); } /** * Starts the simulation up to a given time. It just uses a {@link DefaultController} and calls * {@link StochasticSimulator#start(SimulationController)}. * @param time simulation time */ public final void start(final double time) { if (controller == null) { controller = new DefaultController(time); } start(); } /** * Start the simulation with the given {@link SimulationController}. */ public final void start() { // If we haven't set a controller for the process then set the default one with a max time of 5 // (unknonw units). if (controller == null) { controller = new DefaultController(5); } init(); // tell our observers that the simulation has started for (Observer observer : observers) { observer.started(); } while (controller.goOn(this)) { // The performStep() method is implemented by the specifc stochastic algorithm (e.g. Gillespie's) performStep(); // tell our observers that the step has been completed. for (Observer observer : observers) { observer.step(); } } // tell our observers that the simulation has finished. for (Observer observer : observers) { observer.finished(); } } /** * Initializes the algorithm. <ul><li>set currentTime=0</li><li>reset the {@link AmountManager}</li><li>recalculate * the propensities</li></ul> Gets called at the very beginning of * <code>start</code> */ public final void init() { currentTime = startTime; } /** * Fires a reaction. It calls the observers and the {@link AmountManager}. * @param mu reaction to be fired. * @param t time at which the firing occurs. */ protected final void doEvent(final SimulationEvent mu, final double t) { doEvent(mu, t, 1); } /** * Perform an event by informing the subscribed observers and the amountManager. * @param event event to be performed. * @param t time at which the firing occurs. * @param n the number of times mu is to be fired. */ protected final void doEvent(final SimulationEvent event, final double t, final int n) { log.trace("Performing event {}", event); for (Observer observer : observers) { observer.performEvent(event, t, n); } // change the amount of the reactants if (!Double.isInfinite(t)) { amountManager.performEvent(event, n); } } /** * Gets called when the simulator reaches the predetermined time of a theta event. All the observers for the events * that are configured for this time are notified and given a list of events that are triggered. */ protected final void doThetaEvent() { final double nextThetaEventTime = thetaQueue.getNextThetaEventTime(); log.trace("Performing theta events at t = {}", nextThetaEventTime); final Map<Observer, Collection<Object>> nextEvents = thetaQueue.getNextEventDataAndRemove(); for (Map.Entry<Observer, Collection<Object>> entry : nextEvents.entrySet()) { final Observer observer = entry.getKey(); final Collection<Object> events = entry.getValue(); if (events != null) { log.trace("Informing observer of theta events {}", events.toString()); observer.theta(nextThetaEventTime, events); } } log.trace("Finished theta events next = {}", thetaQueue.getNextThetaEventTime()); } /** * Add an observer to the engines list of observers. * @param observer the observer. */ public final void addObserver(final Observer observer) { if (observer.getProcess() != this) { throw new IllegalArgumentException("Observer doesn't belong to this simulator!"); } this.getObservers().add(observer); } /** * Theta defines a moment, where the simulator has to invoke <TT>theta</TT> of a observers. It is used e.g. to * determine the amounts of species at one moments. Extending class just have to call * {@link Simulator#doThetaEvent()} which basically calls the observers. * @return the theta */ public final double getNextThetaEventTime() { return thetaQueue.getNextThetaEventTime(); } /** * Register a new theta event that is triggered at a given time. * @param obs the observers which is registering. * @param thetaTime the time the theta event occurs. * @param event the theta event. */ public final void registerNewTheta(final Observer obs, final double thetaTime, final Object event) { thetaQueue.pushTheta(thetaTime, obs, event); } /** * Get the default observer for the stochastic process. The default observer is first one defined. * @return the default observer. */ public final Observer getDefaultObserver() { return observers.toArray(new Observer[observers.size()])[0]; } /** * Manages the registered theta events. Each registered theta event is stored in a table containing the time of the * event the list of observers for that event and the list of events for that time. */ private class ThetaQueue { /** * Construct an empty theta queue. */ public ThetaQueue() { thetas = TreeBasedTable.create(); if (reverseTime) { nextThetaEventTime = Double.NEGATIVE_INFINITY; } else { nextThetaEventTime = Double.POSITIVE_INFINITY; } } /** * Add a new theta event to the registry, including the time, collection of observers and collection of events. * Each event is stored as an object where it is assumed that the observer * @param time the time the theta event occurs. * @param obs the observers. * @param theta the theta event. */ @Synchronized public void pushTheta(final double time, final Observer obs, final Object theta) { log.trace("Adding new theta event {} at t={}", theta, time); Collection<Object> events = thetas.get(time, obs); if (events == null) { try { log.trace("No theta events registered at t={}; Creating new list", time); events = new HashSet<>(); events.add(theta); thetas.put(time, obs, events); } catch (UnsupportedOperationException | ClassCastException | IllegalArgumentException | IllegalStateException e) { log.error("Could not register theta. {}", e.getLocalizedMessage()); } } else { log.trace("Found {} theta events for t={}; Adding new event", events.size(), time); events.add(theta); } if (reverseTime) { nextThetaEventTime = Math.max(nextThetaEventTime, time); } else { nextThetaEventTime = Math.min(nextThetaEventTime, time); } } /** * Get the next observer and the collection of events they are subscribed to and remove it from the theta queue. * @return a map of the observers and their subscribed data. */ public Map<Observer, Collection<Object>> getNextEventDataAndRemove() { final Map<Observer, Collection<Object>> nextEventData = thetas.row(nextThetaEventTime); // we have a view of the underlying data that we want to return, copy it first then delete the // underlying data. final Map<Observer, Collection<Object>> eventData = new HashMap<>(nextEventData); log.trace("Found {} configured events and observers at t={}", eventData.size(), nextThetaEventTime); for (Observer obs : eventData.keySet()) { final Collection<Object> removed = thetas.remove(nextThetaEventTime, obs); log.trace("Removed {} items from registered theta list", removed.size()); } // Now we need to update the nextThetaEventTime if (reverseTime) { if (thetas.rowKeySet().isEmpty()) { nextThetaEventTime = Double.NEGATIVE_INFINITY; } else { nextThetaEventTime = Collections.max(thetas.rowKeySet()); } } else { if (thetas.rowKeySet().isEmpty()) { nextThetaEventTime = Double.POSITIVE_INFINITY; } else { nextThetaEventTime = Collections.min(thetas.rowKeySet()); } } return eventData; } @Getter private Table<Double, Observer, Collection<Object>> thetas; @Getter private double nextThetaEventTime; } /** * Reset propensities when a event has been executed. */ public abstract void reinitialize(); /** * Performs one simulation step. Between steps the terminating condition is checked. The simulators controller is * passed, if an extending class wants to check it within one step. Implementing algorithms cannot be sure that the * propensities are correct at the beginning of a step (e.g. if the volume changed). They should override * {@link Simulator#setAmount(int, long)} and {@link Simulator#setVolume(double)} if they need correct values! */ public abstract void performStep(); /** * Gets the name of the algorithm. * @return name of the algorithm */ public abstract String getName(); /** * Seed the RNG if required. * @param seed the RNG seed. */ public abstract void setRngSeed(final int seed); @Setter private int startTime = 0; @Setter @Getter @SuppressWarnings("PMD.UnusedPrivateField") private TransitionKernel transitionKernel; @Getter private AmountManager amountManager; @Setter @Getter @SuppressWarnings("PMD.UnusedPrivateField") private double currentTime = 0; @Getter @Setter private SimulationController controller = null; private ThetaQueue thetaQueue = new ThetaQueue(); @Getter private Set<Observer> observers = new HashSet<>(1); protected boolean reverseTime = false; }
package org.wangzw.plugin.cppstyle; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.eclipse.cdt.core.formatter.CodeFormatter; import org.eclipse.cdt.ui.ICEditor; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.QualifiedName; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.Region; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Display; import org.eclipse.text.edits.MalformedTreeException; import org.eclipse.text.edits.MultiTextEdit; import org.eclipse.text.edits.ReplaceEdit; import org.eclipse.text.edits.TextEdit; import org.eclipse.text.undo.DocumentUndoManagerRegistry; import org.eclipse.text.undo.IDocumentUndoManager; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.console.ConsolePlugin; import org.eclipse.ui.console.IConsole; import org.eclipse.ui.console.IConsoleManager; import org.eclipse.ui.console.MessageConsoleStream; import org.wangzw.plugin.cppstyle.ui.CppStyleConsolePatternMatchListener; import org.wangzw.plugin.cppstyle.ui.CppStyleConstants; import org.wangzw.plugin.cppstyle.ui.CppStyleMessageConsole; public class CppCodeFormatter extends CodeFormatter { private CppStyleMessageConsole console = null; private CppStyleConsolePatternMatchListener listener = null; private MessageConsoleStream out = null; private MessageConsoleStream err = null; public CppCodeFormatter() { super(); setupConsoleStream(); } @Override public String createIndentationString(int indentationLevel) { return super.createIndentationString(indentationLevel); } @Override public void setOptions(Map<String, ?> arg0) { } @Override public TextEdit format(int kind, String source, int offset, int length, int arg4, String lineSeparator) { TextEdit[] edits = format(kind, source, new IRegion[] { new Region( offset, length) }, lineSeparator); if (edits != null) { return edits[0]; } return null; } @Override public TextEdit[] format(int kind, String source, IRegion[] regions, String lineSeparator) { IWorkbenchPage page = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage(); IEditorPart editor = page.getActiveEditor(); return format(source, editor, regions); } public void formatAndApply(ICEditor editor) { TextEdit rootEdit = new MultiTextEdit(); IDocument doc = editor.getDocumentProvider().getDocument( editor.getEditorInput()); TextEdit[] editors = format(doc.get(), editor, null); if (editors == null) { return; } for (TextEdit e : editors) { rootEdit.addChild(e); } IDocumentUndoManager manager = DocumentUndoManagerRegistry .getDocumentUndoManager(doc); manager.beginCompoundChange(); try { rootEdit.apply(doc); } catch (MalformedTreeException e) { err.print(e.getMessage()); } catch (BadLocationException e) { err.print(e.getMessage()); } manager.endCompoundChange(); } private TextEdit[] format(String source, IEditorPart editor, IRegion[] regions) { String root = null; String path = null; String conf = null; String formatArg = ""; showConsoleView(); if (checkClangFormat() == false) { return null; } String clangFormat = getClangFormatPath(); if (editor != null && editor instanceof ICEditor) { ICEditor ceditor = (ICEditor) editor; IFile file = ((IFileEditorInput) ceditor.getEditorInput()) .getFile(); path = file.getLocation().toOSString(); root = file.getProject().getLocation().toOSString(); } else { root = ResourcesPlugin.getWorkspace().getRoot().getLocation() .toOSString(); path = new File(root, "a.cc").getAbsolutePath(); } conf = getClangForamtConfigureFile(path); if (conf == null) { err.println("Cannot find clang-format configure file under any level parent directories of path (" + path + ")."); err.println("Run clang-format with Google style by default."); formatArg = "-style=Google"; } else { out.println("Use clang-format configure file (" + conf + ")"); } StringBuffer sb = new StringBuffer(); List<String> commands = new ArrayList<String>(); commands.add(clangFormat); commands.add("-assume-filename=" + path); if (regions != null) { for (IRegion region : regions) { commands.add("-offset=" + region.getOffset()); commands.add("-length=" + region.getLength()); sb.append("-offset="); sb.append(region.getOffset()); sb.append(" -length="); sb.append(region.getLength()); sb.append(' '); } } if (!formatArg.isEmpty()) { sb.append(formatArg); commands.add(formatArg); } String command = clangFormat + " -assume-filename=" + path + " " + sb.toString(); ProcessBuilder builder = new ProcessBuilder(commands); builder.directory(new File(root)); builder.redirectErrorStream(true); try { Process process = builder.start(); out.println("Run clang-format command: " + command); OutputStreamWriter output = new OutputStreamWriter( process.getOutputStream()); output.write(source); output.flush(); output.close(); InputStreamReader reader = new InputStreamReader( process.getInputStream()); final char[] buffer = new char[1024]; final StringBuilder out = new StringBuilder(); for (;;) { int rsz = reader.read(buffer, 0, buffer.length); if (rsz < 0) { break; } out.append(buffer, 0, rsz); } String newSource = out.toString(); int code = process.waitFor(); if (code != 0) { err.println("clang-format return error (" + code + ")."); err.println(newSource); return null; } if (0 == source.compareTo(newSource)) { return null; } TextEdit[] retval = new TextEdit[1]; // skip the common prefix int start = 0, suffix = 0; int lenSource = source.length(); int lenNewSource = newSource.length(); int minLength = Math.min(lenSource, lenNewSource); for (; start < minLength; ++start) { if (source.charAt(start) != newSource.charAt(start)) { break; } } // skip the common suffix for (; suffix < minLength - start; ++suffix) { if (source.charAt(lenSource - suffix - 1) != newSource .charAt(lenNewSource - suffix - 1)) { break; } } retval[0] = new ReplaceEdit(start, source.length() - start - suffix, newSource.substring( start, lenNewSource - suffix)); return retval; } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } return null; } private String getClangForamtConfigureFile(String path) { File file = new File(path); while (file != null) { File dir = file.getParentFile(); File conf = new File(dir, ".clang-format"); if (dir != null && conf.exists()) { return conf.getAbsolutePath(); } else { file = dir; } } return null; } public boolean checkClangFormat() { String clangformat = getClangFormatPath(); if (clangformat == null) { err.println("clang-format is not specified."); return false; } File file = new File(clangformat); if (!file.exists()) { err.println("clang-format (" + clangformat + ") does not exist."); return false; } if (!file.canExecute()) { err.println("clang-format (" + clangformat + ") is not executable."); return false; } return true; } public void checkFileFormat(IFile file) { try { showConsoleView(); String path = file.getLocation().toOSString(); String cpplint = getCpplintPath(); String projectRoot = file.getProject().getLocation().toOSString(); String root = getCpplintRoot(file); List<String> commands = new ArrayList<String>(); commands.add(cpplint); if (root != null) { commands.add("--root=" + root); } commands.add(path); StringBuffer sb = new StringBuffer(); for (String arg : commands) { sb.append(arg); sb.append(' '); } ProcessBuilder builder = new ProcessBuilder(commands); builder.directory(new File(projectRoot)); builder.redirectErrorStream(true); Process process = builder.start(); out.println("Run cpplint.py command: " + sb.toString()); BufferedReader reader = new BufferedReader(new InputStreamReader( process.getInputStream())); parserCpplintOutput(file, reader); process.waitFor(); } catch (IOException e) { err.println(e.getMessage()); } catch (InterruptedException e) { err.println(e.getMessage()); } } private void parserCpplintOutput(IFile file, BufferedReader reader) { String line = null; String pattern = CppStyleConstants.CPPLINT_OUTPUT_PATTERN; Pattern p = Pattern.compile(pattern); int lineNumGroup = CppStyleConstants.CPPLINT_OUTPUT_PATTERN_LINE_NO_GROUP; int msgGroup = CppStyleConstants.CPPLINT_OUTPUT_PATTERN_MSG_GROUP; listener.setFile(file); try { while ((line = reader.readLine()) != null) { Matcher m = p.matcher(line); if (m.matches()) { String ln = m.group(lineNumGroup); String msg = m.group(msgGroup); if (ln != null && msg != null) { int lineno = Integer.parseInt(ln); createIssueMarker(file, lineno == 0 ? 1 : lineno, msg); } err.println(CppStyleConstants.CPPLINT_CONSOLE_ERROR_PREFIX + line); } else { if (line.startsWith("Done") || line.startsWith("Total")) { out.println(CppStyleConstants.CPPLINT_CONSOLE_PREFIX + line); } else { err.println(CppStyleConstants.CPPLINT_CONSOLE_PREFIX + line); } } } } catch (IOException e) { err.println(e.getMessage()); } } public void createIssueMarker(IResource resource, int line, String msg) { try { IMarker marker = resource .createMarker(CppStyleConstants.CPPLINT_MARKER); marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR); marker.setAttribute(IMarker.MESSAGE, msg); marker.setAttribute(IMarker.LINE_NUMBER, line); marker.setAttribute(IMarker.PROBLEM, true); } catch (CoreException e) { err.println(e.getMessage()); } } public void deleteAllMarkers(IResource target) { String type = CppStyleConstants.CPPLINT_MARKER; try { IMarker[] markers = target.findMarkers(type, true, IResource.DEPTH_INFINITE); for (IMarker marker : markers) { marker.delete(); } } catch (CoreException e) { err.println(e.getMessage()); } } private boolean enableCpplintOnSave(IResource resource) { boolean enable = CppStyle.getDefault().getPreferenceStore() .getBoolean(CppStyleConstants.ENABLE_CPPLINT_ON_SAVE); try { IProject project = resource.getProject(); String enableProjectSpecific = project .getPersistentProperty(new QualifiedName("", CppStyleConstants.PROJECTS_PECIFIC_PROPERTY)); if (enableProjectSpecific != null && Boolean.parseBoolean(enableProjectSpecific)) { String value = project.getPersistentProperty(new QualifiedName( "", CppStyleConstants.ENABLE_CPPLINT_PROPERTY)); if (value != null) { return Boolean.parseBoolean(value); } return false; } } catch (CoreException e) { e.printStackTrace(); } return enable; } public boolean runCpplintOnSave(IResource resource) { if (!enableCpplintOnSave(resource)) { return false; } String cpplint = getCpplintPath(); showConsoleView(); if (cpplint == null) { err.println("cpplint.py is not specified."); return false; } File file = new File(cpplint); if (!file.exists()) { err.println("cpplint.py (" + cpplint + ") does not exist."); return false; } if (!file.canExecute()) { err.println("cpplint.py (" + cpplint + ") is not executable."); return false; } return true; } private boolean enableClangFormatOnSave(IResource resource) { boolean enable = CppStyle.getDefault().getPreferenceStore() .getBoolean(CppStyleConstants.ENABLE_CLANGFORMAT_ON_SAVE); try { IProject project = resource.getProject(); String enableProjectSpecific = project .getPersistentProperty(new QualifiedName("", CppStyleConstants.PROJECTS_PECIFIC_PROPERTY)); if (enableProjectSpecific != null && Boolean.parseBoolean(enableProjectSpecific)) { String value = project.getPersistentProperty(new QualifiedName( "", CppStyleConstants.ENABLE_CLANGFORMAT_PROPERTY)); if (value != null) { return Boolean.parseBoolean(value); } return false; } } catch (CoreException e) { e.printStackTrace(); } return enable; } public boolean runClangFormatOnSave(IResource resource) { if (!enableClangFormatOnSave(resource)) { return false; } String clangFormat = getClangFormatPath(); showConsoleView(); if (clangFormat == null) { err.println("clang-format is not specified."); return false; } File file = new File(clangFormat); if (!file.exists()) { err.println("clang-format (" + clangFormat + ") does not exist."); return false; } if (!file.canExecute()) { err.println("clang-format (" + clangFormat + ") is not executable."); return false; } return true; } public static String getClangFormatPath() { return CppStyle.getDefault().getPreferenceStore() .getString(CppStyleConstants.CLANG_FORMAT_PATH); } public static String getCpplintPath() { return CppStyle.getDefault().getPreferenceStore() .getString(CppStyleConstants.CPPLINT_PATH); } static String getVersionControlRoot(IFile file) { File current = file.getLocation().toFile(); File dir = current.getParentFile(); while (dir != null) { for (final File entry : dir.listFiles()) { String name = entry.getName(); if (name.equals(".git") || name.equals(".hg") || name.equals(".svn")) { return dir.getPath(); } } dir = dir.getParentFile(); } return null; } public static String getCpplintRoot(IFile file) { IProject project = file.getProject(); String rootSpec; try { rootSpec = project.getPersistentProperty(new QualifiedName("", CppStyleConstants.CPPLINT_PROJECT_ROOT)); if (rootSpec == null || rootSpec.isEmpty()) { return null; } } catch (CoreException e) { return null; } String rootVc = getVersionControlRoot(file); if (rootVc == null) { return null; } String relative = new File(rootVc).toURI() .relativize(new File(rootSpec).toURI()).getPath(); if (relative.endsWith("" + Path.SEPARATOR)) { return relative.substring(0, relative.length() - 1); } return relative; } private void setupConsoleStream() { ConsolePlugin plugin = ConsolePlugin.getDefault(); IConsoleManager conMan = plugin.getConsoleManager(); IConsole[] existing = conMan.getConsoles(); for (int i = 0; i < existing.length; i++) { if (CppStyleConstants.CONSOLE_NAME.equals(existing[i].getName())) { console = (CppStyleMessageConsole) existing[i]; console.clearConsole(); listener = console.getListener(); } } if (console == null) { // no console found, so create a new one listener = new CppStyleConsolePatternMatchListener(); console = new CppStyleMessageConsole(listener); conMan.addConsoles(new IConsole[] { console }); } out = console.newMessageStream(); err = console.newMessageStream(); out.setActivateOnWrite(true); err.setActivateOnWrite(true); err.setColor(Display.getDefault().getSystemColor(SWT.COLOR_RED)); } private void showConsoleView() { ConsolePlugin.getDefault().getConsoleManager().showConsoleView(console); } }
package org.appwork.swing.exttable; import java.awt.Color; import java.awt.Component; import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.JTableHeader; import org.appwork.resources.AWUTheme; import org.appwork.utils.logging.Log; import sun.swing.DefaultLookup; /** * @author thomas * */ public class ExtTableHeaderRenderer extends DefaultTableCellRenderer implements javax.swing.plaf.UIResource { private static final long serialVersionUID = 1L; private final ExtColumn<?> column; private boolean paintIcon; private Color focusForeground; private Color focusBackground; private final Color foregroundC; private final Color backgroundC; private Border focusBorder; private Border cellBorder; private final ImageIcon lockedWidth; /** * @param extColumn * @param jTableHeader */ public ExtTableHeaderRenderer(final ExtColumn<?> extColumn, final JTableHeader header) { this.column = extColumn; // this.setHorizontalTextPosition(10); this.lockedWidth = AWUTheme.I().getIcon("exttable/widthLocked", -1); try { try { this.focusForeground = DefaultLookup.getColor(this, this.ui, "TableHeader.focusCellForeground"); this.focusBackground = DefaultLookup.getColor(this, this.ui, "TableHeader.focusCellBackground"); } catch (final NoSuchMethodError e) { // DefaultLookup is sun.swing, any may not be // available // e.gh. in 1.6.0_01-b06 this.focusForeground = (Color) UIManager.get("TableHeader.focusCellForeground", this.getLocale()); this.focusBackground = (Color) UIManager.get("TableHeader.focusCellBackground", this.getLocale()); } } catch (final Throwable e) { Log.exception(e); } if (this.focusForeground == null) { this.focusForeground = header.getForeground(); } if (this.focusBackground == null) { this.focusBackground = header.getBackground(); } this.foregroundC = header.getForeground(); this.backgroundC = header.getBackground(); try { try { this.focusBorder = DefaultLookup.getBorder(this, this.ui, "TableHeader.focusCellBorder"); this.cellBorder = DefaultLookup.getBorder(this, this.ui, "TableHeader.cellBorder"); } catch (final NoSuchMethodError e) { // DefaultLookup is sun.swing, any may not be available // e.gh. in 1.6.0_01-b06 this.focusBorder = (Border) UIManager.get("TableHeader.focusCellBorder", this.getLocale()); this.cellBorder = (Border) UIManager.get("TableHeader.focusCellBackground", this.getLocale()); } } catch (final Throwable e) { Log.exception(e); // avoid that the block above kills edt } if (this.focusBorder == null) { this.focusBorder = BorderFactory.createEmptyBorder(0, 10, 0, 10); } if (this.cellBorder == null) { this.cellBorder = BorderFactory.createEmptyBorder(0, 10, 0, 10); } this.setFont(header.getFont()); } @Override public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) { this.setForeground(hasFocus ? this.focusForeground : this.foregroundC); this.setBackground(hasFocus ? this.focusBackground : this.backgroundC); // sort column is no current column if (this.column.getModel().getSortColumn() == null || this.column.getModel().getSortColumn() != this.column) { this.paintIcon = false; } else { this.paintIcon = true; } this.setText(value == null ? "" : value.toString()); this.setBorder(hasFocus ? this.focusBorder : this.cellBorder); // this.setBackground(Color.RED); // this.setOpaque(true); // System.out.println(this.getPreferredSize()); return this; } @Override public void paintComponent(final Graphics g) { super.paintComponent(g); try { if (this.paintIcon) { final int left = 2; final Icon icon = this.column.getModel().getSortColumn().getSortIcon(); if (icon != null) { final Graphics2D g2 = (Graphics2D) g; // final Composite comp = g2.getComposite(); // g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, // 0.5f)); icon.paintIcon(this, g2, left, (this.getHeight() - icon.getIconHeight()) / 2); // g2.setComposite(comp); } } if (!this.column.isResizable() && this.column.isPaintWidthLockIcon()) { // lockedWidth final Graphics2D g2 = (Graphics2D) g; // final Composite comp = g2.getComposite(); // g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, // 0.5f)); this.lockedWidth.paintIcon(this, g2, this.getWidth() - this.lockedWidth.getIconWidth() - 2, (this.getHeight() - this.lockedWidth.getIconHeight()) / 2); // g2.setComposite(comp); } } catch (RuntimeException e) { Log.exception(e); } } }
package com.rox.emu.processor.mos6502; import com.rox.emu.env.RoxByte; import com.rox.emu.env.RoxWord; import com.rox.emu.mem.Memory; import com.rox.emu.processor.mos6502.op.OpCode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.rox.emu.processor.mos6502.Registers.*; /** * A emulated representation of MOS 6502, 8 bit * microprocessor functionality. * * XXX: At this point, we are only emulating the NES custom version of the 6502 * * @author Ross Drew */ public class Mos6502 { private final Logger log = LoggerFactory.getLogger(this.getClass()); private final Memory memory; private final Registers registers = new Registers(); private final Mos6502Alu alu = new Mos6502Alu(registers); public Mos6502(Memory memory) { this.memory = memory; } /** * Reset the CPU; akin to firing the Reset pin on a 6502.<br/> * <br/> * This will * <ul> * <li>Set Accumulator &rarr; <code>0</code></li> * <li>Set Indexes &rarr; <code>0</code></li> * <li>Status register &rarr; <code>0x34</code></li> * <li>Set PC to the values at <code>0xFFFC</code> and <code>0xFFFD</code></li> * <li>Reset Stack Pointer &rarr; 0xFF</li> * </ul> * <br/> * Note: IRL this takes 6 CPU cycles but we'll cross that bridge IF we come to it- */ public void reset(){ log.debug("RESETTING..."); setRegisterValue(Register.ACCUMULATOR, 0x0); setRegisterValue(Register.X_INDEX, 0x0); setRegisterValue(Register.Y_INDEX, 0x0); setRegisterValue(Register.STATUS_FLAGS, 0x34); setRegisterValue(Register.PROGRAM_COUNTER_HI, getByteOfMemoryAt(0xFFFC)); setRegisterValue(Register.PROGRAM_COUNTER_LOW, getByteOfMemoryAt(0xFFFD)); setRegisterValue(Register.STACK_POINTER_HI, 0xFF); log.debug("...READY!"); } /** * Fire an <b>I</b>nterrupt <b>R</b>e<b>Q</b>uest; akin to setting the IRQ pin on a 6502.<br/> * <br> * This will stash the PC and Status registers and set the Program Counter to the values at * <code>0xFFFE</code> and <code>0xFFFF</code> where the <b>I</b>nterrupt <b>S</b>ervice * <b>R</b>outine is expected to be */ public void irq() { log.debug("IRQ!"); registers.setFlag(Flag.IRQ_DISABLE); pushRegister(Register.PROGRAM_COUNTER_HI); pushRegister(Register.PROGRAM_COUNTER_LOW); pushRegister(Register.STATUS_FLAGS); setRegisterValue(Register.PROGRAM_COUNTER_HI, getByteOfMemoryAt(0xFFFe)); setRegisterValue(Register.PROGRAM_COUNTER_LOW, getByteOfMemoryAt(0xFFFF)); } /** * Fire a <b>N</b>on <b>M</b>askable <b>I</b>nterrupt; akin to setting the NMI pin on a 6502.<br/> * <br> * This will stash the PC and Status registers and set the Program Counter to the values at <code>0xFFFA</code> * and <code>0xFFFB</code> where the <b>I</b>nterrupt <b>S</b>ervice <b>R</b>outine is expected to be */ public void nmi() { log.debug("NMI!"); registers.setFlag(Flag.IRQ_DISABLE); pushRegister(Register.PROGRAM_COUNTER_HI); pushRegister(Register.PROGRAM_COUNTER_LOW); pushRegister(Register.STATUS_FLAGS); setRegisterValue(Register.PROGRAM_COUNTER_HI, getByteOfMemoryAt(0xFFFA)); setRegisterValue(Register.PROGRAM_COUNTER_LOW, getByteOfMemoryAt(0xFFFB)); } /** * @return the {@link Registers} being used */ public Registers getRegisters(){ return registers; } /** * Execute the next program instruction as per {@link Registers#getNextProgramCounter()} * * @param steps number of instructions to execute */ public void step(int steps){ for (int i=0; i<steps; i++) step(); } /** * Execute the next program instruction as per {@link Registers#getNextProgramCounter()} */ public void step() { log.debug("STEP >>>"); final int opCodeByte = nextProgramByte(); final OpCode opCode = OpCode.from(opCodeByte); //Execute the opcode log.debug("Instruction: {0}...", opCode.getOpCodeName()); switch (opCode){ case ASL_A: withRegister(Register.ACCUMULATOR, this::performASL); break; case ASL_Z: withByteAt(nextProgramByte(), this::performASL); break; case ASL_Z_IX: withByteXIndexedAt(nextProgramByte(), this::performASL); break; case ASL_ABS_IX: withByteXIndexedAt(nextProgramWord(), this::performASL); break; case ASL_ABS: withByteAt(nextProgramWord(), this::performASL); break; case LSR_A: withRegister(Register.ACCUMULATOR, this::performLSR); break; case LSR_Z: withByteAt(nextProgramByte(), this::performLSR); break; case LSR_Z_IX: withByteXIndexedAt(nextProgramByte(), this::performLSR); break; case LSR_ABS: withByteAt(nextProgramWord(), this::performLSR); break; case LSR_ABS_IX: withByteXIndexedAt(nextProgramWord(), this::performLSR); break; case ROL_A: withRegister(Register.ACCUMULATOR, this::performROL); break; case ROL_Z: withByteAt(nextProgramByte(), this::performROL); break; case ROL_Z_IX: withByteXIndexedAt(nextProgramByte(), this::performROL); break; case ROL_ABS: withByteAt(nextProgramWord(), this::performROL); break; case ROL_ABS_IX: withByteXIndexedAt(nextProgramWord(), this::performROL); break; case ROR_A: withRegister(Register.ACCUMULATOR, this::performROR); break; case SEC: registers.setFlag(Flag.CARRY); break; case CLC: registers.clearFlag(Flag.CARRY); break; case CLV: registers.clearFlag(Flag.OVERFLOW); break; case INC_Z: withByteAt(nextProgramByte(), this::performINC); break; case INC_Z_IX: withByteXIndexedAt(nextProgramByte(), this::performINC); break; case INC_ABS: withByteAt(nextProgramWord(), this::performINC);break; case INC_ABS_IX: withByteXIndexedAt(nextProgramWord(), this::performINC); break; case DEC_Z: withByteAt(nextProgramByte(), this::performDEC); break; case DEC_Z_IX: withByteXIndexedAt(nextProgramByte(), this::performDEC); break; case DEC_ABS: withByteAt(nextProgramWord(), this::performDEC); break; case DEC_ABS_IX: withByteXIndexedAt(nextProgramWord(), this::performDEC); break; case INX: withRegister(Register.X_INDEX, this::performINC); break; case DEX: withRegister(Register.X_INDEX, this::performDEC); break; case INY: withRegister(Register.Y_INDEX, this::performINC); break; case DEY: withRegister(Register.Y_INDEX, this::performDEC); break; case LDX_I: registers.setRegisterAndFlags(Register.X_INDEX, nextProgramByte()); break; case LDX_Z: registers.setRegisterAndFlags(Register.X_INDEX, getByteOfMemoryAt(nextProgramByte())); break; case LDX_Z_IY: registers.setRegisterAndFlags(Register.X_INDEX, getByteOfMemoryYIndexedAt(nextProgramByte())); break; case LDX_ABS: registers.setRegisterAndFlags(Register.X_INDEX, getByteOfMemoryAt(nextProgramWord())); break; case LDX_ABS_IY: registers.setRegisterAndFlags(Register.X_INDEX, getByteOfMemoryYIndexedAt(nextProgramWord())); break; case LDY_I: registers.setRegisterAndFlags(Register.Y_INDEX, nextProgramByte()); break; case LDY_Z: registers.setRegisterAndFlags(Register.Y_INDEX, getByteOfMemoryAt(nextProgramByte())); break; case LDY_Z_IX: registers.setRegisterAndFlags(Register.Y_INDEX, getByteOfMemoryXIndexedAt(nextProgramByte())); break; case LDY_ABS: registers.setRegisterAndFlags(Register.Y_INDEX, getByteOfMemoryAt(nextProgramWord())); break; case LDY_ABS_IX: registers.setRegisterAndFlags(Register.Y_INDEX, getByteOfMemoryXIndexedAt(nextProgramWord())); break; case LDA_I: registers.setRegisterAndFlags(Register.ACCUMULATOR, nextProgramByte()); break; case LDA_Z: registers.setRegisterAndFlags(Register.ACCUMULATOR, getByteOfMemoryAt(nextProgramByte())); break; case LDA_Z_IX: registers.setRegisterAndFlags(Register.ACCUMULATOR, getByteOfMemoryXIndexedAt(nextProgramByte())); break; case LDA_ABS: registers.setRegisterAndFlags(Register.ACCUMULATOR, getByteOfMemoryAt(nextProgramWord())); break; case LDA_ABS_IY: registers.setRegisterAndFlags(Register.ACCUMULATOR, getByteOfMemoryYIndexedAt(nextProgramWord())); break; case LDA_ABS_IX: registers.setRegisterAndFlags(Register.ACCUMULATOR, getByteOfMemoryXIndexedAt(nextProgramWord())); break; case LDA_IND_IX: { //TODO this needs to be wrappable for zero page addressing int pointerLocation = getWordOfMemoryXIndexedAt(nextProgramByte()); registers.setRegisterAndFlags(Register.ACCUMULATOR, getByteOfMemoryAt(pointerLocation)); }break; case LDA_IND_IY: { final int pointerLocation = getWordOfMemoryAt(nextProgramByte()) + getRegisterValue(Register.Y_INDEX); registers.setRegisterAndFlags(Register.ACCUMULATOR, getByteOfMemoryAt(pointerLocation)); }break; case AND_Z: withRegisterAndByteAt(Register.ACCUMULATOR, nextProgramByte(), this::performAND); break; case AND_ABS: withRegisterAndByteAt(Register.ACCUMULATOR, nextProgramWord(), this::performAND); break; case AND_I: withRegisterAndByte(Register.ACCUMULATOR, nextProgramByte(), this::performAND); break; case AND_Z_IX: withRegisterAndByteXIndexedAt(Register.ACCUMULATOR, nextProgramByte(), this::performAND); break; case AND_ABS_IX: withRegisterAndByteXIndexedAt(Register.ACCUMULATOR, nextProgramWord(), this::performAND); break; case AND_ABS_IY: withRegisterAndByteYIndexedAt(Register.ACCUMULATOR, nextProgramWord(), this::performAND); break; case AND_IND_IX: { int pointerLocation = getWordOfMemoryXIndexedAt(nextProgramByte()); withRegisterAndByteAt(Register.ACCUMULATOR, pointerLocation, this::performAND); }break; case AND_IND_IY: { int pointerLocation = getWordOfMemoryAt(nextProgramByte()) + getRegisterValue(Register.Y_INDEX); withRegisterAndByteAt(Register.ACCUMULATOR, pointerLocation, this::performAND); }break; case BIT_Z: performBIT(getByteOfMemoryAt(nextProgramByte())); break; case BIT_ABS: performBIT(getByteOfMemoryAt(nextProgramWord())); break; case ORA_I: withRegisterAndByte(Register.ACCUMULATOR, nextProgramByte(), this::performORA); break; case ORA_Z: withRegisterAndByteAt(Register.ACCUMULATOR, nextProgramByte(), this::performORA); break; case ORA_Z_IX: withRegisterAndByteXIndexedAt(Register.ACCUMULATOR, nextProgramByte(), this::performORA); break; case ORA_ABS: withRegisterAndByteAt(Register.ACCUMULATOR, nextProgramWord(), this::performORA); break; case ORA_ABS_IX: withRegisterAndByteXIndexedAt(Register.ACCUMULATOR, nextProgramWord(), this::performORA); break; case ORA_ABS_IY: withRegisterAndByteYIndexedAt(Register.ACCUMULATOR, nextProgramWord(), this::performORA); break; case ORA_IND_IX: { int pointerLocation = getWordOfMemoryXIndexedAt(nextProgramByte()); withRegisterAndByteAt(Register.ACCUMULATOR, pointerLocation, this::performORA); }break; case ORA_IND_IY: { int pointerLocation = getWordOfMemoryAt(nextProgramByte()) + getRegisterValue(Register.Y_INDEX); withRegisterAndByteAt(Register.ACCUMULATOR, pointerLocation, this::performORA); }break; case EOR_I: withRegisterAndByte(Register.ACCUMULATOR, nextProgramByte(), this::performEOR); break; case EOR_Z: withRegisterAndByteAt(Register.ACCUMULATOR, nextProgramByte(), this::performEOR); break; case EOR_Z_IX: withRegisterAndByteXIndexedAt(Register.ACCUMULATOR, nextProgramByte(), this::performEOR); break; case EOR_ABS: withRegisterAndByteAt(Register.ACCUMULATOR, nextProgramWord(), this::performEOR); break; case EOR_ABS_IX: withRegisterAndByteXIndexedAt(Register.ACCUMULATOR, nextProgramWord(), this::performEOR); break; case EOR_ABS_IY: withRegisterAndByteYIndexedAt(Register.ACCUMULATOR, nextProgramWord(), this::performEOR); break; case EOR_IND_IX: { int pointerLocation = getWordOfMemoryXIndexedAt(nextProgramByte()); withRegisterAndByteAt(Register.ACCUMULATOR, pointerLocation, this::performEOR); }break; case EOR_IND_IY: { int pointerLocation = getWordOfMemoryAt(nextProgramByte()) + getRegisterValue(Register.Y_INDEX); withRegisterAndByteAt(Register.ACCUMULATOR, pointerLocation, this::performEOR); }break; case ADC_Z: withRegisterAndByteAt(Register.ACCUMULATOR, nextProgramByte(), this::performADC); break; case ADC_I: withRegisterAndByte(Register.ACCUMULATOR, nextProgramByte(), this::performADC); break; case ADC_ABS: withRegisterAndByteAt(Register.ACCUMULATOR, nextProgramWord(), this::performADC); break; case ADC_ABS_IX: withRegisterAndByteXIndexedAt(Register.ACCUMULATOR, nextProgramWord(), this::performADC); break; case ADC_ABS_IY: withRegisterAndByteYIndexedAt(Register.ACCUMULATOR, nextProgramWord(), this::performADC); break; case ADC_Z_IX: withRegisterAndByteXIndexedAt(Register.ACCUMULATOR, nextProgramByte(), this::performADC); break; case ADC_IND_IX: { int pointerLocation = getWordOfMemoryXIndexedAt(nextProgramByte()); withRegisterAndByteAt(Register.ACCUMULATOR, pointerLocation, this::performADC); }break; case ADC_IND_IY: { int pointerLocation = getWordOfMemoryAt(nextProgramByte()) + getRegisterValue(Register.Y_INDEX); withRegisterAndByteAt(Register.ACCUMULATOR, pointerLocation, this::performADC); }break; case CMP_I: performCMP(nextProgramByte(), Register.ACCUMULATOR); break; case CMP_Z: performCMP(getByteOfMemoryAt(nextProgramByte()), Register.ACCUMULATOR); break; case CMP_Z_IX: performCMP(getByteOfMemoryXIndexedAt(nextProgramByte()), Register.ACCUMULATOR); break; case CMP_ABS: performCMP(getByteOfMemoryAt(nextProgramWord()), Register.ACCUMULATOR); break; case CMP_ABS_IX: performCMP(getByteOfMemoryXIndexedAt(nextProgramWord()), Register.ACCUMULATOR); break; case CMP_ABS_IY: performCMP(getByteOfMemoryYIndexedAt(nextProgramWord()), Register.ACCUMULATOR); break; case CMP_IND_IX: { int pointerLocation = getWordOfMemoryXIndexedAt(nextProgramByte()); performCMP(getByteOfMemoryAt(pointerLocation), Register.ACCUMULATOR); }break; case CMP_IND_IY: { int pointerLocation = getWordOfMemoryAt(nextProgramByte()) + getRegisterValue(Register.Y_INDEX); performCMP(getByteOfMemoryAt(pointerLocation), Register.ACCUMULATOR); }break; case CPX_I: performCMP(nextProgramByte(), Register.X_INDEX); break; case CPX_Z: performCMP(getByteOfMemoryAt(nextProgramByte()), Register.X_INDEX); break; case CPX_ABS: performCMP(getByteOfMemoryAt(nextProgramWord()), Register.X_INDEX); break; case CPY_I: performCMP(nextProgramByte(), Register.Y_INDEX); break; case CPY_Z: performCMP(getByteOfMemoryAt(nextProgramByte()), Register.Y_INDEX); break; case CPY_ABS: performCMP(getByteOfMemoryAt(nextProgramWord()), Register.Y_INDEX); break; case SBC_I: withRegisterAndByte(Register.ACCUMULATOR, nextProgramByte(), this::performSBC); break; case SBC_Z: withRegisterAndByteAt(Register.ACCUMULATOR, nextProgramByte(), this::performSBC); break; case SBC_Z_IX: withRegisterAndByteXIndexedAt(Register.ACCUMULATOR, nextProgramByte(), this::performSBC); break; case SBC_ABS: withRegisterAndByteAt(Register.ACCUMULATOR, nextProgramWord(), this::performSBC); break; case SBC_ABS_IX: withRegisterAndByteXIndexedAt(Register.ACCUMULATOR, nextProgramWord(), this::performSBC); break; case SBC_ABS_IY: withRegisterAndByteYIndexedAt(Register.ACCUMULATOR, nextProgramWord(), this::performSBC); break; case SBC_IND_IX: { int pointerLocation = getWordOfMemoryXIndexedAt(nextProgramByte()); withRegisterAndByteAt(Register.ACCUMULATOR, pointerLocation, this::performSBC); }break; case SBC_IND_IY: { int pointerLocation = getWordOfMemoryAt(nextProgramByte()) + getRegisterValue(Register.Y_INDEX); withRegisterAndByteAt(Register.ACCUMULATOR, pointerLocation, this::performSBC); }break; case STY_Z: setByteOfMemoryAt(nextProgramByte(), getRegisterValue(Register.Y_INDEX)); break; case STY_ABS: setByteOfMemoryAt(nextProgramWord(), getRegisterValue(Register.Y_INDEX)); break; case STY_Z_IX: setByteOfMemoryXIndexedAt(nextProgramByte(), getRegisterValue(Register.Y_INDEX)); break; case STA_Z: setByteOfMemoryAt(nextProgramByte(), getRegisterValue(Register.ACCUMULATOR)); break; case STA_ABS: setByteOfMemoryAt(nextProgramWord(), getRegisterValue(Register.ACCUMULATOR)); break; case STA_Z_IX: setByteOfMemoryXIndexedAt(nextProgramByte(), getRegisterValue(Register.ACCUMULATOR)); break; case STA_ABS_IX: setByteOfMemoryXIndexedAt(nextProgramWord(), getRegisterValue(Register.ACCUMULATOR)); break; case STA_ABS_IY: setByteOfMemoryYIndexedAt(nextProgramWord(), getRegisterValue(Register.ACCUMULATOR)); break; case STA_IND_IX: { int pointerLocation = getWordOfMemoryXIndexedAt(nextProgramByte()); setByteOfMemoryAt(pointerLocation, getRegisterValue(Register.ACCUMULATOR)); }break; case STA_IND_IY: { int pointerLocation = getWordOfMemoryAt(nextProgramByte()) + getRegisterValue(Register.Y_INDEX); setByteOfMemoryAt(pointerLocation, getRegisterValue(Register.ACCUMULATOR)); }break; case STX_Z: setByteOfMemoryAt(nextProgramByte(), getRegisterValue(Register.X_INDEX)); break; case STX_Z_IY: setByteOfMemoryYIndexedAt(nextProgramByte(), getRegisterValue(Register.X_INDEX)); break; case STX_ABS: setByteOfMemoryAt(nextProgramWord(), getRegisterValue(Register.X_INDEX)); break; case PHA: pushRegister(Register.ACCUMULATOR); break; case PLA: registers.setRegisterAndFlags(Register.ACCUMULATOR, pop()); break; case PHP: pushRegister(Register.STATUS_FLAGS); break; case PLP: registers.setRegister(Register.STATUS_FLAGS, pop()); break; case JMP_ABS: { int h = nextProgramByte(); int l = nextProgramByte(); registers.setRegister(Register.PROGRAM_COUNTER_HI, h); setRegisterValue(Register.PROGRAM_COUNTER_LOW, l); }break; case JMP_IND: { final RoxByte h = RoxByte.fromLiteral(nextProgramByte()); final RoxByte l = RoxByte.fromLiteral(nextProgramByte()); int pointer = RoxWord.from(h,l).getAsInt(); registers.setPC(getWordOfMemoryAt(pointer)); }break; case BCS: branchIf(registers.getFlag(Flag.CARRY)); break; case BCC: branchIf(!registers.getFlag(Flag.CARRY)); break; case BEQ: branchIf(registers.getFlag(Flag.ZERO)); break; case BNE: branchIf(!registers.getFlag(Flag.ZERO)); break; case BMI: branchIf(registers.getFlag(Flag.NEGATIVE)); break; case JSR: int hi = nextProgramByte(); int lo = nextProgramByte(); pushRegister(Register.PROGRAM_COUNTER_HI); pushRegister(Register.PROGRAM_COUNTER_LOW); setRegisterValue(Register.PROGRAM_COUNTER_HI, hi); setRegisterValue(Register.PROGRAM_COUNTER_LOW, lo); break; case BPL: branchIf(!registers.getFlag(Flag.NEGATIVE)); break; case BVS: branchIf(registers.getFlag(Flag.OVERFLOW)); break; case BVC: branchIf(!registers.getFlag(Flag.OVERFLOW)); break; case TAX: setRegisterValue(Register.X_INDEX, getRegisterValue(Register.ACCUMULATOR)); break; case TAY: setRegisterValue(Register.Y_INDEX, getRegisterValue(Register.ACCUMULATOR)); break; case TYA: setRegisterValue(Register.ACCUMULATOR, getRegisterValue(Register.Y_INDEX)); break; case TXA: setRegisterValue(Register.ACCUMULATOR, getRegisterValue(Register.X_INDEX)); break; case TXS: setRegisterValue(Register.STACK_POINTER_HI, getRegisterValue(Register.X_INDEX)); break; case TSX: setRegisterValue(Register.X_INDEX, getRegisterValue(Register.STACK_POINTER_HI)); registers.setFlagsBasedOn(getRegisterValue(Register.X_INDEX)); break; case NOP: //Do nothing break; case SEI: registers.setFlag(Flag.IRQ_DISABLE); break; case CLI: registers.clearFlag(Flag.IRQ_DISABLE); break; case SED: registers.setFlag(Flag.DECIMAL_MODE); break; case CLD: registers.clearFlag(Flag.DECIMAL_MODE); break; case RTS: setRegisterValue(Register.PROGRAM_COUNTER_LOW, pop()); setRegisterValue(Register.PROGRAM_COUNTER_HI, pop()); break; case RTI: setRegisterValue(Register.STATUS_FLAGS, pop()); setRegisterValue(Register.PROGRAM_COUNTER_LOW, pop()); setRegisterValue(Register.PROGRAM_COUNTER_HI, pop()); break; case BRK: default: //XXX Why do we do this at all? A program of [BRK] will push 0x03 as the PC...why is that right? registers.setPC(performSilently(this::performADC, registers.getPC(), 2, false)); push(registers.getRegister(Register.PROGRAM_COUNTER_HI)); push(registers.getRegister(Register.PROGRAM_COUNTER_LOW)); push(registers.getRegister(Register.STATUS_FLAGS) | Flag.BREAK.getPlaceValue()); registers.setRegister(Register.PROGRAM_COUNTER_HI, getByteOfMemoryAt(0xFFFE)); registers.setRegister(Register.PROGRAM_COUNTER_LOW, getByteOfMemoryAt(0xFFFF)); break; } } private int getRegisterValue(Register registerID){ return registers.getRegister(registerID); } private void setRegisterValue(Register registerID, int value){ registers.setRegister(registerID, value); } /** * Get the value of the 16 bit Program Counter (PC) and increment */ private int getAndStepPC(){ final int originalPC = registers.getPC(); registers.setPC(originalPC + 1); return originalPC; } /** * Return the next byte from program memory, as defined * by the Program Counter.<br/> * <br/> * <em>Increments the Program Counter by 1</em> * * @return byte {@code from mem[ PC[0] ]} */ private int nextProgramByte(){ int memoryLocation = getAndStepPC(); return getByteOfMemoryAt(memoryLocation); } /** * Combine the next two bytes in program memory, as defined by * the Program Counter into a word so that:- * * PC[0] = high order byte * PC[1] = low order byte *<br/><br/> * <em>Increments the Program Counter by 1</em> * * @return word made up of both bytes */ private int nextProgramWord(){ int byte1 = nextProgramByte(); return RoxWord.from(RoxByte.fromLiteral(byte1), RoxByte.fromLiteral(nextProgramByte())).getAsInt(); } /** * Pop value from stack * * @return popped value */ private int pop(){ setRegisterValue(Register.STACK_POINTER_HI, getRegisterValue(Register.STACK_POINTER_HI) + 1); int address = 0x0100 | getRegisterValue(Register.STACK_POINTER_HI); int value = getByteOfMemoryAt(address); debug("POP {0}(0b{1}) from mem[0x{2}]", Integer.toString(value), Integer.toBinaryString(value), Integer.toHexString(address).toUpperCase()); return value; } private void debug(final String message, String ... args){ if (!log.isDebugEnabled()) return; log.debug(message, args); } private void pushRegister(Register registerID){ push(getRegisterValue(registerID)); } /** * Push to stack * * @param value value to push */ private void push(int value){ debug("PUSH {0}(0b{1}) to mem[0x{2}]", Integer.toString(value), Integer.toBinaryString(value), Integer.toHexString(getRegisterValue(Register.STACK_POINTER_HI)).toUpperCase()); setByteOfMemoryAt(0x0100 | getRegisterValue(Register.STACK_POINTER_HI), value); setRegisterValue(Register.STACK_POINTER_HI, getRegisterValue(Register.STACK_POINTER_HI) - 1); } private int getByteOfMemoryXIndexedAt(int location){ return getByteOfMemoryAt(location, getRegisterValue(Register.X_INDEX)); } private int getByteOfMemoryYIndexedAt(int location){ return getByteOfMemoryAt(location, getRegisterValue(Register.Y_INDEX)); } private void setByteOfMemoryYIndexedAt(int location, int newByte){ setByteOfMemoryAt(location, getRegisterValue(Register.Y_INDEX), newByte); } private int getByteOfMemoryAt(int location){ return getByteOfMemoryAt(location, 0); } private int getByteOfMemoryAt(int location, int index){ final int memoryByte = memory.getByte(location + index); debug("Got 0x{0} from mem[{1}]", Integer.toHexString(memoryByte), (location + (index != 0 ? "[" + index + "]" : ""))); return memoryByte; } private void setByteOfMemoryXIndexedAt(int location, int newByte){ setByteOfMemoryAt(location, getRegisterValue(Register.X_INDEX), newByte); } private void setByteOfMemoryAt(int location, int newByte){ setByteOfMemoryAt(location, 0, newByte); } private void setByteOfMemoryAt(int location, int index, int newByte){ memory.setByteAt(location + index, newByte); debug("Stored 0x{0} at mem[{1}]", Integer.toHexString(newByte), (location + (index != 0 ? "[" + index + "]" : ""))); } private int getWordOfMemoryXIndexedAt(int location){ int indexedLocation = location + getRegisterValue(Register.X_INDEX); return getWordOfMemoryAt(indexedLocation); } private int getWordOfMemoryAt(int location) { int memoryWord = memory.getWord(location); debug("Got 0x{0} from mem[{1}]", Integer.toHexString(memoryWord), Integer.toString(location)); return memoryWord; } /** * Call {@link Mos6502#branchTo(int)} with next program byte * * @param condition if {@code true} then branch is followed */ private void branchIf(boolean condition){ int location = nextProgramByte(); debug("Branch:0x{0} by {1} {2}", Integer.toHexString(registers.getPC()), Integer.toBinaryString(location), (condition ? "YES->" : "NO...")); if (condition) branchTo(location); } /** * Branch to a relative location as defined by a signed byte * * @param displacement relative (-127 &rarr; 128) location from end of branch instruction */ private void branchTo(int displacement) { //possible improvement? // int v = performSilently(this::performADC, getRegisterValue(Register.PROGRAM_COUNTER_LOW), displacement, registers.getFlag(STATUS_FLAG_CARRY)); // setRegisterValue(Register.PROGRAM_COUNTER_LOW, v); final RoxByte displacementByte = RoxByte.fromLiteral(displacement); if (displacementByte.isNegative()) setRegisterValue(Register.PROGRAM_COUNTER_LOW, getRegisterValue(Register.PROGRAM_COUNTER_LOW) - displacementByte.asOnesCompliment().getRawValue()); else setRegisterValue(Register.PROGRAM_COUNTER_LOW, getRegisterValue(Register.PROGRAM_COUNTER_LOW) + displacementByte.getRawValue()); } private int fromOnesComplimented(int byteValue){ return (~byteValue) & 0xFF; } private int fromTwosComplimented(int byteValue){ return fromOnesComplimented(byteValue) - 1; } private void performCMP(int value, Register toRegister){ int result = performSilently(this::performSBC, getRegisterValue(toRegister), value, true); registers.setFlagsBasedOn(result & 0xFF); registers.setFlagTo(Flag.CARRY, (fromTwosComplimented(result) >=0)); } @FunctionalInterface private interface SingleByteOperation { int perform(int byteValue); } private void withByteAt(int location, SingleByteOperation singleByteOperation){ int b = getByteOfMemoryAt(location); setByteOfMemoryAt(location, singleByteOperation.perform(b)); } private void withByteXIndexedAt(int location, SingleByteOperation singleByteOperation){ int b = getByteOfMemoryXIndexedAt(location); setByteOfMemoryXIndexedAt(location, singleByteOperation.perform(b)); } private void withRegister(Register registerId, SingleByteOperation singleByteOperation){ int b = getRegisterValue(registerId); setRegisterValue(registerId, singleByteOperation.perform(b)); } private int performASL(int byteValue){ int newValue = alu.asl(RoxByte.fromLiteral(byteValue)).getRawValue(); registers.setFlagsBasedOn(newValue); return newValue; } private int performROL(int initialValue){ int rotatedValue = alu.rol(RoxByte.fromLiteral(initialValue)).getRawValue(); registers.setFlagsBasedOn(rotatedValue); return rotatedValue; } private int performROR(int initialValue){ int rotatedValue = alu.ror(RoxByte.fromLiteral(initialValue)).getRawValue(); registers.setFlagsBasedOn(rotatedValue); return rotatedValue; } private int performLSR(int initialValue){ int rotatedValue = alu.lsr(RoxByte.fromLiteral(initialValue)).getRawValue(); registers.setFlagsBasedOn(rotatedValue); return rotatedValue; } private int performINC(int initialValue){ int incrementedValue = performSilently(this::performADC, initialValue, 1,false); registers.setFlagsBasedOn(incrementedValue); return incrementedValue; } private int performDEC(int initialValue){ int incrementedValue = performSilently(this::performSBC, initialValue, 1,true); registers.setFlagsBasedOn(incrementedValue); return incrementedValue; } private void performBIT(int memData) { registers.setFlagTo(Flag.ZERO, ((memData & getRegisterValue(Register.ACCUMULATOR)) == memData)); //Set N, V to bits 7 and 6 of memory data setRegisterValue(Register.STATUS_FLAGS, (memData & 0b11000000) | (getRegisterValue(Register.STATUS_FLAGS) & 0b00111111)); } @FunctionalInterface private interface TwoByteOperation { int perform(int byteValueOne, int byteValueTwo); } /** * Perform byteA given operation and have the state of the registers be the same as before the operation was performed * * @param operation operation to perform * @param byteA byte A to pass into the operation * @param byteB byte B to pass into the operation * @param carryInState the state in which to assume the carry flag is in at the start of the operation * @return the result of the operation. */ private int performSilently(TwoByteOperation operation, int byteA, int byteB, boolean carryInState){ int statusState = registers.getRegister(Register.STATUS_FLAGS); registers.setFlagTo(Flag.CARRY, carryInState); //To allow ignore of the carry: ignore = 0 for ADC, 1 for SBC int result = operation.perform(byteA, byteB); registers.setRegister(Register.STATUS_FLAGS, statusState); return result; } private void withRegisterAndByteAt(Register registerId, int memoryLocation, TwoByteOperation twoByteOperation){ withRegisterAndByte(registerId, getByteOfMemoryAt(memoryLocation), twoByteOperation); } private void withRegisterAndByteXIndexedAt(Register registerId, int memoryLocation, TwoByteOperation twoByteOperation){ withRegisterAndByte(registerId, getByteOfMemoryXIndexedAt(memoryLocation), twoByteOperation); } private void withRegisterAndByteYIndexedAt(Register registerId, int memoryLocation, TwoByteOperation twoByteOperation){ withRegisterAndByte(registerId, getByteOfMemoryYIndexedAt(memoryLocation), twoByteOperation); } private void withRegisterAndByte(Register registerId, int byteValue, TwoByteOperation twoByteOperation){ int registerByte = getRegisterValue(registerId); registers.setRegisterAndFlags(registerId, twoByteOperation.perform(registerByte, byteValue)); } private int performAND(int byteValueA, int byteValueB){ return alu.and(RoxByte.fromLiteral(byteValueA), RoxByte.fromLiteral(byteValueB)).getRawValue(); } private int performEOR(int byteValueA, int byteValueB){ return alu.xor(RoxByte.fromLiteral(byteValueA), RoxByte.fromLiteral(byteValueB)).getRawValue(); } private int performORA(int byteValueA, int byteValueB){ return alu.or(RoxByte.fromLiteral(byteValueA), RoxByte.fromLiteral(byteValueB)).getRawValue(); } private int performADC(int byteValueA, int byteValueB){ return alu.adc(RoxByte.fromLiteral(byteValueA), RoxByte.fromLiteral(byteValueB)).getRawValue(); } private int performSBC(int byteValueA, int byteValueB){ return alu.sbc(RoxByte.fromLiteral(byteValueA), RoxByte.fromLiteral(byteValueB)).getRawValue(); } }
package com.pesegato.MonkeySheet.batch; import com.jme3.math.Vector2f; import com.jme3.math.Vector3f; import com.jme3.scene.Geometry; import com.jme3.scene.Mesh; import com.jme3.scene.VertexBuffer; import com.jme3.util.BufferUtils; import java.nio.FloatBuffer; import java.nio.IntBuffer; import static com.jme3.scene.VertexBuffer.Type.*; public class BNode { Mesh mesh; FloatBuffer posData, texData, msPosData; VertexBuffer posBuffer, texBuffer, msPosBuffer, idxBuffer; IntBuffer idxData; BGeometry[] quads; int[] indexes; int slotFreeIdx=0; boolean slotBusy[]; public BNode(int size){ mesh = new Mesh(); quads = new BGeometry[size]; slotBusy = new boolean[size]; indexes = new int[6 * size]; posData = BufferUtils.createFloatBuffer(new Vector3f[4 * size]); msPosData = BufferUtils.createFloatBuffer(new float[4 * size]); texData = BufferUtils.createFloatBuffer(new Vector2f[4 * size]); idxData = BufferUtils.createIntBuffer(indexes); mesh.setBuffer(Position, 3, posData); mesh.setBuffer(TexCoord, 2, texData); mesh.setBuffer(TexCoord2, 1, msPosData); mesh.setBuffer(Index, 3, idxData); posBuffer=mesh.getBuffer(Position); texBuffer=mesh.getBuffer(TexCoord); msPosBuffer=mesh.getBuffer(TexCoord2); idxBuffer=mesh.getBuffer(Index); } public void remove(int idx){ idxData.position(idx*6); idxData.put(0); idxData.put(0); idxData.put(0); idxData.put(0); idxData.put(0); idxData.put(0); } public void removeAll(){ idxData.position(0); for (int i=0;i<quads.length*6;i++){ idxData.put(0); } slotFreeIdx=0; updateData(); } public int addQuad(float x, float y){ if (slotBusy.length<=slotFreeIdx){ System.err.println("No more free slot available for BGeometries on "+this+"!"); System.exit(-1); } slotBusy[slotFreeIdx]=true; quads[slotFreeIdx] = new BGeometry(slotFreeIdx, posData, texData, idxData, msPosData); quads[slotFreeIdx].setPosition(x, y); texBuffer.updateData(texData); posBuffer.updateData(posData); idxBuffer.updateData(idxData); slotFreeIdx++; return slotFreeIdx-1; } public void addQuad(int i, int x, int y){ quads[i] = new BGeometry(i, posData, texData, idxData, msPosData); quads[i].setPosition(x, y); texBuffer.updateData(texData); posBuffer.updateData(posData); idxBuffer.updateData(idxData); } public void updateData(){ texBuffer.updateData(texData); posBuffer.updateData(posData); idxBuffer.updateData(idxData); msPosBuffer.updateData(msPosData); } public Geometry makeGeo(){ idxBuffer.updateData(idxData); mesh.updateBound(); return new Geometry("batchedSpatial", mesh); } public BGeometry[] getQuads(){ return quads; } }
package org.bouncycastle.cms; import org.bouncycastle.asn1.ASN1OctetString; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DERObjectIdentifier; import org.bouncycastle.asn1.DEREncodable; import org.bouncycastle.asn1.cms.PasswordRecipientInfo; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import javax.crypto.Cipher; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.io.InputStream; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Provider; /** * the RecipientInfo class for a recipient who has been sent a message * encrypted using a password. */ public class PasswordRecipientInformation extends RecipientInformation { private PasswordRecipientInfo _info; private AlgorithmIdentifier _encAlg; public PasswordRecipientInformation( PasswordRecipientInfo info, AlgorithmIdentifier encAlg, InputStream data) { super(encAlg, AlgorithmIdentifier.getInstance(info.getKeyEncryptionAlgorithm()), data); this._info = info; this._encAlg = encAlg; this._rid = new RecipientId(); } /** * return the object identifier for the key derivation algorithm, or null * if there is none present. * * @return OID for key derivation algorithm, if present. */ public String getKeyDerivationAlgOID() { if (_info.getKeyDerivationAlgorithm() != null) { return _info.getKeyDerivationAlgorithm().getObjectId().getId(); } return null; } /** * return the ASN.1 encoded key dervivation algorithm parameters, or null if * there aren't any. * @return ASN.1 encoding of key derivation algorithm parameters. */ public byte[] getKeyDerivationAlgParams() { try { if (_info.getKeyDerivationAlgorithm() != null) { DEREncodable params = _info.getKeyDerivationAlgorithm().getParameters(); if (params != null) { return params.getDERObject().getEncoded(); } } return null; } catch (Exception e) { throw new RuntimeException("exception getting encryption parameters " + e); } } /** * decrypt the content and return an input stream. */ public CMSTypedStream getContentStream( Key key, String prov) throws CMSException, NoSuchProviderException { return getContentStream(key, CMSUtils.getProvider(prov)); } /** * decrypt the content and return an input stream. */ public CMSTypedStream getContentStream( Key key, Provider prov) throws CMSException { try { AlgorithmIdentifier kekAlg = AlgorithmIdentifier.getInstance(_info.getKeyEncryptionAlgorithm()); ASN1Sequence kekAlgParams = (ASN1Sequence)kekAlg.getParameters(); byte[] encryptedKey = _info.getEncryptedKey().getOctets(); String kekAlgName = DERObjectIdentifier.getInstance(kekAlgParams.getObjectAt(0)).getId(); Cipher keyCipher = Cipher.getInstance( CMSEnvelopedHelper.INSTANCE.getRFC3211WrapperName(kekAlgName), prov); IvParameterSpec ivSpec = new IvParameterSpec(ASN1OctetString.getInstance(kekAlgParams.getObjectAt(1)).getOctets()); keyCipher.init(Cipher.UNWRAP_MODE, new SecretKeySpec(((CMSPBEKey)key).getEncoded(kekAlgName), kekAlgName), ivSpec); AlgorithmIdentifier aid = _encAlg; String alg = aid.getObjectId().getId(); Key sKey = keyCipher.unwrap( encryptedKey, alg, Cipher.SECRET_KEY); return getContentFromSessionKey(sKey, prov); } catch (NoSuchAlgorithmException e) { throw new CMSException("can't find algorithm.", e); } catch (InvalidKeyException e) { throw new CMSException("key invalid in message.", e); } catch (NoSuchPaddingException e) { throw new CMSException("required padding not supported.", e); } catch (InvalidAlgorithmParameterException e) { throw new CMSException("invalid iv.", e); } } }
package ca.wescook.nutrition.utility; import ca.wescook.nutrition.capabilities.CapProvider; import ca.wescook.nutrition.nutrients.Nutrient; import ca.wescook.nutrition.nutrients.NutrientList; import net.minecraft.command.CommandBase; import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraft.util.math.BlockPos; import net.minecraft.util.text.TextComponentString; import org.apache.commons.lang3.math.NumberUtils; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class ChatCommand extends CommandBase { private String helpString = "/nutrition <player> <get/set/add/subtract/reset> <nutrient> <value>"; private enum actions {SET, ADD, SUBTRACT} @Override public String getName() { return "nutrition"; } @Override public String getUsage(ICommandSender sender) { return helpString; } @Override public int getRequiredPermissionLevel() { return 2; } @Override public List<String> getTabCompletions(MinecraftServer server, ICommandSender sender, String[] args, @Nullable BlockPos targetPos) { if (args.length == 1) { // Player list return getListOfStringsMatchingLastWord(args, server.getOnlinePlayerNames()); } else if (args.length == 2) { // Sub-commands list return getListOfStringsMatchingLastWord(args, Arrays.asList("get", "set", "add", "subtract")); } else if (args.length == 3) { // Nutrients list List<String> nutrientList = new ArrayList<>(); for (Nutrient nutrient : NutrientList.get()) nutrientList.add(nutrient.name); return getListOfStringsMatchingLastWord(args, nutrientList); } // Default return Collections.emptyList(); } @Override public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException { // Get player EntityPlayerMP player = null; if (args.length != 0) player = CommandBase.getPlayer(server, sender, args[0]); // Which sub-command to execute if (args.length == 0 || args[0].equals("help")) commandHelp(sender); else if (args[1].equals("get")) commandGetNutrition(player, sender, args); else if (args[1].equals("set")) commandSetNutrition(player, sender, args, actions.SET); else if (args[1].equals("add")) commandSetNutrition(player, sender, args, actions.ADD); else if (args[1].equals("subtract")) commandSetNutrition(player, sender, args, actions.SUBTRACT); else if (args[1].equals("reset")) commandResetNutrition(player, sender, args); } private void commandHelp(ICommandSender sender) { sender.sendMessage(new TextComponentString(helpString)); } private void commandGetNutrition(EntityPlayer player, ICommandSender sender, String[] args) { // Write nutrient name and percentage to chat Nutrient nutrient = NutrientList.getByName(args[2]); if (nutrient != null) { Float nutrientValue = player.getCapability(CapProvider.NUTRITION_CAPABILITY, null).get(nutrient); sender.sendMessage(new TextComponentString(nutrient.name + ": " + String.format("%.2f", nutrientValue) + "%")); } else // Write error message sender.sendMessage(new TextComponentString("'" + args[1] + "' is not a valid nutrient.")); } // Used to set, add, and subtract nutrients (defined under actions) private void commandSetNutrition(EntityPlayer player, ICommandSender sender, String[] args, actions action) { // Sanity checking if (!validNumber(sender, args[3])) return; // Set nutrient value and output Nutrient nutrient = NutrientList.getByName(args[2]); if (nutrient != null) { // Update nutrition based on action type if (action == actions.SET) player.getCapability(CapProvider.NUTRITION_CAPABILITY, null).set(nutrient, Float.parseFloat(args[3]), true); else if (action == actions.ADD) player.getCapability(CapProvider.NUTRITION_CAPABILITY, null).add(nutrient, Float.parseFloat(args[3]), true); else if (action == actions.SUBTRACT) player.getCapability(CapProvider.NUTRITION_CAPABILITY, null).subtract(nutrient, Float.parseFloat(args[3]), true); // Update chat sender.sendMessage(new TextComponentString(nutrient.name + " updated!")); } else // Write error message sender.sendMessage(new TextComponentString("'" + args[1] + "' is not a valid nutrient.")); } private void commandResetNutrition(EntityPlayer player, ICommandSender sender, String[] args) { // Reset single nutrient if (args.length == 3) { Nutrient nutrient = NutrientList.getByName(args[2]); if (nutrient != null) { player.getCapability(CapProvider.NUTRITION_CAPABILITY, null).set(nutrient, (float) Config.startingNutrition, true); sender.sendMessage(new TextComponentString("Nutrient " + nutrient.name + " reset for " + player.getName() + "!")); } } // Reset all nutrients else if (args.length == 2) { for (Nutrient nutrient : NutrientList.get()) player.getCapability(CapProvider.NUTRITION_CAPABILITY, null).set(nutrient, (float) Config.startingNutrition, false); player.getCapability(CapProvider.NUTRITION_CAPABILITY, null).resync(); sender.sendMessage(new TextComponentString("Nutrition reset for " + player.getName() + "!")); } } // Checks if the supplied nutrient value is valid and in an acceptable range // Spits out an error if problem is met private boolean validNumber(ICommandSender sender, String value) { // Valid number check Float newValue; if (NumberUtils.isCreatable(value)) newValue = Float.parseFloat(value); else { sender.sendMessage(new TextComponentString("'" + value + "' is not a number.")); return false; } // Range check (don't sue me Oracle) if (!(newValue >= 0 && newValue <= 100)) { sender.sendMessage(new TextComponentString("'" + value + "' is not a number between 0 and 100.")); return false; } return true; } }
package org.citygml4j.model.citygml.building; import java.util.List; import org.citygml4j.builder.copy.CopyBuilder; import org.citygml4j.model.citygml.CityGMLClass; import org.citygml4j.model.citygml.ade.ADEComponent; import org.citygml4j.model.common.child.ChildList; import org.citygml4j.model.common.visitor.FeatureFunctor; import org.citygml4j.model.common.visitor.FeatureVisitor; import org.citygml4j.model.common.visitor.GMLFunctor; import org.citygml4j.model.common.visitor.GMLVisitor; import org.citygml4j.model.module.citygml.BuildingModule; public class BuildingPart extends AbstractBuilding { private List<ADEComponent> ade; public BuildingPart() { } public BuildingPart(BuildingModule module) { super(module); } public void addGenericApplicationPropertyOfBuildingPart(ADEComponent ade) { if (this.ade == null) this.ade = new ChildList<ADEComponent>(this); this.ade.add(ade); } public List<ADEComponent> getGenericApplicationPropertyOfBuildingPart() { if (ade == null) ade = new ChildList<ADEComponent>(this); return ade; } public boolean isSetGenericApplicationPropertyOfBuildingPart() { return ade != null && !ade.isEmpty(); } public void setGenericApplicationPropertyOfBuildingPart(List<ADEComponent> ade) { this.ade = new ChildList<ADEComponent>(this, ade); } public void unsetGenericApplicationPropertyOfBuildingPart() { if (isSetGenericApplicationPropertyOfBuildingPart()) ade.clear(); ade = null; } public boolean unsetGenericApplicationPropertyOfBuildingPart(ADEComponent ade) { return isSetGenericApplicationPropertyOfBuildingPart() ? this.ade.remove(ade) : false; } public CityGMLClass getCityGMLClass() { return CityGMLClass.BUILDING_PART; } public Object copy(CopyBuilder copyBuilder) { return copyTo(new BuildingPart(), copyBuilder); } @Override public Object copyTo(Object target, CopyBuilder copyBuilder) { AbstractBuilding copy = (target == null) ? new BuildingPart() : (AbstractBuilding)target; super.copyTo(copy, copyBuilder); if (copy.getCityGMLClass() == CityGMLClass.BUILDING_PART) { if (isSetGenericApplicationPropertyOfBuildingPart()) { for (ADEComponent part : ade) { ADEComponent copyPart = (ADEComponent)copyBuilder.copy(part); ((BuildingPart)copy).addGenericApplicationPropertyOfBuildingPart(copyPart); if (part != null && copyPart == part) part.setParent(this); } } } return copy; } public void accept(FeatureVisitor visitor) { visitor.visit(this); } public <T> T accept(FeatureFunctor<T> visitor) { return visitor.apply(this); } public void accept(GMLVisitor visitor) { visitor.visit(this); } public <T> T accept(GMLFunctor<T> visitor) { return visitor.apply(this); } }
package opendap.bes; import opendap.coreServlet.Scrub; import opendap.ppt.PPTException; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.Vector; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReentrantLock; public class BESManager { private static org.slf4j.Logger _log; private static AtomicBoolean _initialized; private static Vector<BesGroup> _besCollection; private static BesGroup rootGroup; private static AtomicBoolean _isConfigured; private static Element _config; private static ReentrantLock _lock; static { _log = LoggerFactory.getLogger(BESManager.class); _besCollection = new Vector<>(); _initialized = new AtomicBoolean(false); _isConfigured = new AtomicBoolean(false); _config = null; _lock = new ReentrantLock(); } public void init(Element config) throws Exception{ _lock.lock(); try { if (_initialized.get()) return; _config = (Element) config.clone(); configure(config); _log.info("Initialized."); _initialized.set(true); } finally { _lock.unlock(); } } public static boolean isInitialized(){ return _initialized.get(); } public void destroy(){ shutdown(); _log.info("Destroy complete."); } public static Element getConfig(){ return (Element) _config.clone(); } private void configure(Element besConfiguration) throws Exception { if(_isConfigured.get()) return; List besList = besConfiguration.getChildren("BES"); if (besList.isEmpty()) throw new BadConfigurationException("OLFS Configuration must " + "contain at LEAST one BES configuration element. And " + "the value of it's prefix element must be \"/\"."); boolean foundRootBES = false; BES bes; BESConfig besConfig; Element besConfigElement; for (Object o : besList) { besConfigElement = (Element) o; besConfig = new BESConfig(besConfigElement); bes = new BES(besConfig); BesGroup groupForThisPrefix = getBesGroup(bes.getPrefix()); // Since the BES with prefix '/' will always match we have to check to make sure // that if a non null group is returned that it's prefix does in fact match the one // for the new BES - if it doesn't match the returned group prefix then we need to make a new group. if (groupForThisPrefix == null || !groupForThisPrefix.getGroupPrefix().equals(bes.getPrefix())) { groupForThisPrefix = new BesGroup(bes.getPrefix()); _besCollection.add(groupForThisPrefix); } groupForThisPrefix.add(bes); if (groupForThisPrefix.getGroupPrefix().equals("/")) { rootGroup = groupForThisPrefix; foundRootBES = true; } } if (!foundRootBES) throw new BadConfigurationException("OLFS Configuration must " + "contain at LEAST one BES configuration element. Whose " + "prefix is \"/\". (Why? Think about it...)"); _isConfigured.set(true); } public static void addBes(BES bes) throws Exception { Iterator<BesGroup> i = BESManager.getBesGroups(); BesGroup bg, myGroup = null; while(i.hasNext()){ bg = i.next(); if(bg.getGroupPrefix().equals(bes.getPrefix())){ myGroup = bg; } } if(myGroup != null){ myGroup.add(bes.getNickName(),bes); } else { myGroup = new BesGroup(bes.getPrefix()); myGroup.add(bes); _besCollection.add(myGroup); } } public static boolean isConfigured(){ return _isConfigured.get(); } public static BES getBES(String path) throws BadConfigurationException { if(path==null) path = "/"; if(path.indexOf("/")!=0){ _log.debug("Pre-pending / to path: "+ path); path = "/"+path; } BesGroup besGroupToServicePath = null; String prefix; for(BesGroup besGroup : _besCollection){ prefix = besGroup.getGroupPrefix(); if(path.indexOf(prefix) == 0){ if(besGroupToServicePath == null){ besGroupToServicePath = besGroup; } else { if(prefix.length() > besGroupToServicePath.getGroupPrefix().length()) besGroupToServicePath = besGroup; } } } BES bes = null; if(besGroupToServicePath!=null) bes = besGroupToServicePath.getNext(); if (bes == null) { String msg = "There is no BES to handle the requested data source: " + Scrub.urlContent(path); _log.error(msg); throw new BadConfigurationException(msg); } return bes; } public static BesGroup getBesGroup(String path){ if(path==null) path = "/"; if(path.indexOf("/")!=0){ _log.debug("Pre-pending / to path: "+ path); path = "/"+path; } BesGroup result = null; String prefix; for(BesGroup besGroup : _besCollection){ prefix = besGroup.getGroupPrefix(); if(path.indexOf(prefix) == 0){ if(result == null){ result = besGroup; } else { if(prefix.length() > result.getGroupPrefix().length()) result = besGroup; } } } if(result == null) result = rootGroup; return result; } public static Iterator<BesGroup> getBesGroups(){ return _besCollection.listIterator(); } public static void shutdown(){ for(BesGroup besGroup : _besCollection){ _log.debug("Shutting down BesGroup for prefix '" + besGroup.getGroupPrefix()+"'"); besGroup.destroy(); } _log.debug("All BesGroup's have been shut down."); } public static Document getCombinedVersionDocument() throws JDOMException, IOException, PPTException, BadConfigurationException, BESError { Document doc = new Document(); doc.setRootElement(new Element("HyraxCombinedVersion")); // Add a version element for Hyrax (which is a combination of many things) doc.getRootElement().addContent(opendap.bes.Version.getHyraxVersionElement()); // Add a version element for this, the OLFS server doc.getRootElement().addContent(opendap.bes.Version.getOLFSVersionElement()); //doc.getRootElement().addNamespaceDeclaration(); // Maybe someday? Element besVer; Document tmp; for(BesGroup besGroup : _besCollection){ Document besGroupVerDoc = besGroup.getGroupVersion(); doc.getRootElement().addContent(besGroupVerDoc.detachRootElement()); } return doc; } public static Document getGroupVersionDocument(String path) throws Exception { return getBesGroup(path).getGroupVersion(); } public static Document getVersionDocument(String path, String besName) throws Exception { BesGroup besGroup = getBesGroup(path); BES bes = besGroup.get(besName); return bes.getVersionDocument(); } // public static void removeThreadCache(Thread t){ // threadCache.remove(t); // _log.info("Removing ThreadCache for thread "+t.getName()); }
package crazypants.enderio.conduit.redstone; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import net.minecraft.block.Block; import net.minecraft.client.renderer.texture.IconRegister; import net.minecraft.item.ItemStack; import net.minecraft.util.Icon; import net.minecraft.world.World; import net.minecraftforge.common.ForgeDirection; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import crazypants.enderio.EnderIO; import crazypants.enderio.ModObject; import crazypants.enderio.conduit.AbstractConduit; import crazypants.enderio.conduit.AbstractConduitNetwork; import crazypants.enderio.conduit.ConduitUtil; import crazypants.enderio.conduit.IConduit; import crazypants.enderio.conduit.geom.CollidableComponent; import crazypants.render.IconUtil; import crazypants.util.BlockCoord; public class RedstoneConduit extends AbstractConduit implements IRedstoneConduit { static final Map<String, Icon> ICONS = new HashMap<String, Icon>(); @SideOnly(Side.CLIENT) public static void initIcons() { IconUtil.addIconProvider(new IconUtil.IIconProvider() { @Override public void registerIcons(IconRegister register) { ICONS.put(KEY_CORE_OFF_ICON, register.registerIcon(KEY_CORE_OFF_ICON)); ICONS.put(KEY_CORE_ON_ICON, register.registerIcon(KEY_CORE_ON_ICON)); ICONS.put(KEY_CONDUIT_ICON, register.registerIcon(KEY_CONDUIT_ICON)); ICONS.put(KEY_TRANSMISSION_ICON, register.registerIcon(KEY_TRANSMISSION_ICON)); } @Override public int getTextureType() { return 0; } }); } protected RedstoneConduitNetwork network; protected final Set<Signal> externalSignals = new HashSet<Signal>(); public RedstoneConduit() { } @Override public ItemStack createItem() { return new ItemStack(ModObject.itemRedstoneConduit.actualId, 1, 0); } @Override public Class<? extends IConduit> getBaseConduitType() { return IRedstoneConduit.class; } @Override public AbstractConduitNetwork<IRedstoneConduit> getNetwork() { return network; } @Override public boolean setNetwork(AbstractConduitNetwork<?> network) { this.network = (RedstoneConduitNetwork) network; return true; } @Override public boolean canConnectToExternal(ForgeDirection direction) { return false; } @Override public void updateNetwork() { World world = getBundle().getEntity().worldObj; if(world != null) { updateNetwork(world); } } protected boolean acceptSignalsForDir(ForgeDirection dir) { BlockCoord loc = getLocation().getLocation(dir); return ConduitUtil.getConduit(getBundle().getEntity().getWorldObj(), loc.x, loc.y, loc.z, IRedstoneConduit.class) == null; } @Override public Set<Signal> getNetworkInputs() { return getNetworkInputs(null); } @Override public Set<Signal> getNetworkInputs(ForgeDirection side) { if(network != null) { network.setNetworkEnabled(false); } Set<Signal> res = new HashSet<Signal>(); for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS) { if((side == null || dir == side) && acceptSignalsForDir(dir)) { int input = getExternalPowerLevel(dir); if(input > 1) { // need to degrade external signals by one as they // enter BlockCoord loc = getLocation().getLocation(dir); Signal signal = new Signal(loc.x, loc.y, loc.z, dir, input - 1, getSignalColor(dir)); res.add(signal); } } } if(network != null) { network.setNetworkEnabled(true); } return res; } @Override public SignalColor getSignalColor(ForgeDirection dir) { return SignalColor.RED; } @Override public Set<Signal> getNetworkOutputs(ForgeDirection side) { if(network == null) { return Collections.emptySet(); } return network.getSignals(); } @Override public boolean onNeighborBlockChange(int blockId) { World world = getBundle().getEntity().worldObj; if(world.isRemote) { return false; } if(blockId == EnderIO.blockConduitBundle.blockID) { return false; } boolean res = super.onNeighborBlockChange(blockId); if(network == null || network.updatingNetwork) { return false; } if(blockId <= 0) { return res; } if(blockId > 0 && Block.blocksList[blockId].canProvidePower() && network != null) { // TODO: Just recalculate the signals, no need for a full rebuild network.destroyNetwork(); updateNetwork(world); return false; } return res; } protected int getExternalPowerLevel(ForgeDirection dir) { World world = getBundle().getEntity().worldObj; BlockCoord loc = getLocation(); loc = loc.getLocation(dir); return world.getIndirectPowerLevelTo(loc.x, loc.y, loc.z, dir.ordinal()); } @Override public int isProvidingStrongPower(ForgeDirection toDirection) { return 0; } @Override public int isProvidingWeakPower(ForgeDirection toDirection) { if(network == null || !network.isNetworkEnabled()) { return 0; } int result = 0; for (Signal signal : getNetworkOutputs(toDirection.getOpposite())) { result = Math.max(result, signal.strength); } return result; } @Override public Icon getTextureForState(CollidableComponent component) { if(component.dir == ForgeDirection.UNKNOWN) { return isActive() ? ICONS.get(KEY_CORE_ON_ICON) : ICONS.get(KEY_CORE_OFF_ICON); } return isActive() ? ICONS.get(KEY_TRANSMISSION_ICON) : ICONS.get(KEY_CONDUIT_ICON); } @Override public Icon getTransmitionTextureForState(CollidableComponent component) { return null; } @Override public String toString() { return "RedstoneConduit [network=" + network + " connections=" + conduitConnections + " active=" + active + "]"; } @Override public int[] getOutputValues(World world, int x, int y, int z, ForgeDirection side) { int[] result = new int[16]; Set<Signal> outs = getNetworkOutputs(side); if(outs != null) { for (Signal s : outs) { result[s.color.ordinal()] = s.strength; } } return result; } @Override public int getOutputValue(World world, int x, int y, int z, ForgeDirection side, int subnet) { Set<Signal> outs = getNetworkOutputs(side); if(outs != null) { for (Signal s : outs) { if(subnet == s.color.ordinal()) { return s.strength; } } } return 0; } }
package ch.tkuhn.memetools; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.supercsv.io.CsvListReader; import org.supercsv.io.CsvListWriter; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; public class CalculatePaperSuccess { @Parameter(description = "chronologically-sorted-input-file", required = true) private List<String> parameters = new ArrayList<String>(); private File inputFile; @Parameter(names = "-t", description = "File with terms", required = true) private File termsFile; @Parameter(names = "-tcol", description = "Index or name of column to read terms (if term file is in CSV format)") private String termCol = "TERM"; @Parameter(names = "-y", description = "Number of years for which to count article citations") private int citationYears = 3; @Parameter(names = "-d", description = "Set delta parameter (controlled noise level)") private int delta = 3; @Parameter(names = "-r", description = "Relative frequency threshold") private double relFreqThreshold = 0.15; private File logFile; public static final void main(String[] args) { CalculatePaperSuccess obj = new CalculatePaperSuccess(); JCommander jc = new JCommander(obj); try { jc.parse(args); } catch (ParameterException ex) { jc.usage(); System.exit(1); } if (obj.parameters.size() != 1) { System.err.println("ERROR: Exactly one main argument is needed"); jc.usage(); System.exit(1); } obj.inputFile = new File(obj.parameters.get(0)); obj.run(); } private File outputTempFile, outputFile, outputMatrixFile; private MemeScorer ms; private List<String> terms; private BufferedReader reader; private Map<String,Long> paperDates; private Map<String,Integer> paperCitations; private Map<String,String> cpyMapKeys; private Map<String,Long> cpyLastDay; private Map<String,Long> cpyPaperDays; private Map<String,Integer> cpyPaperCount; private Map<String,Integer> cpyCitationCount; private long lastDay; public CalculatePaperSuccess() { } public void run() { init(); try { readTerms(); processEntries(); writeSuccessColumn(); } catch (Throwable th) { log(th); System.exit(1); } log("Finished"); } private void init() { logFile = new File(MemeUtils.getLogDir(), getOutputFileName() + ".log"); log("=========="); outputTempFile = new File(MemeUtils.getOutputDataDir(), getOutputFileName() + "-temp.csv"); outputFile = new File(MemeUtils.getOutputDataDir(), getOutputFileName() + ".csv"); outputMatrixFile = new File(MemeUtils.getOutputDataDir(), getOutputFileName() + "-matrix.csv"); ms = new MemeScorer(MemeScorer.GIVEN_TERMLIST_MODE); terms = new ArrayList<String>(); paperDates = new HashMap<String,Long>(); paperCitations = new HashMap<String,Integer>(); cpyMapKeys = new HashMap<String,String>(); cpyLastDay = new HashMap<String,Long>(); cpyPaperDays = new HashMap<String,Long>(); cpyPaperCount = new HashMap<String,Integer>(); cpyCitationCount = new HashMap<String,Integer>(); } private void readTerms() throws IOException { log("Reading terms from " + termsFile + " ..."); if (termsFile.toString().endsWith(".csv")) { readTermsCsv(); } else { readTermsTxt(); } log("Number of terms: " + terms.size()); } private void readTermsTxt() throws IOException { BufferedReader reader = new BufferedReader(new FileReader(termsFile)); String line; while ((line = reader.readLine()) != null) { String term = MemeUtils.normalize(line); ms.addTerm(term); terms.add(term); } reader.close(); } private void readTermsCsv() throws IOException { BufferedReader r = new BufferedReader(new FileReader(termsFile)); CsvListReader csvReader = new CsvListReader(r, MemeUtils.getCsvPreference()); List<String> header = csvReader.read(); int col; if (termCol.matches("[0-9]+")) { col = Integer.parseInt(termCol); } else { col = header.indexOf(termCol); } List<String> line; while ((line = csvReader.read()) != null) { String term = MemeUtils.normalize(line.get(col)); ms.addTerm(term); terms.add(term); } csvReader.close(); } private void processEntries() throws IOException { CsvListWriter csvWriter = null; try { log("Processing entries and writing CSV file..."); Writer w = new BufferedWriter(new FileWriter(outputTempFile)); csvWriter = new CsvListWriter(w, MemeUtils.getCsvPreference()); csvWriter.write("ID", "JOURNAL-C/PY", "FIRSTAUTHOR-C/PY", "AUTHOR-MAX-C/PY", "SELFCIT-MAX-C/Y", "TOP-PS", "TOP-PS-MEME", "TOP-MS", "TOP-MS-MEME"); reader = new BufferedReader(new FileReader(inputFile)); int progress = 0; String line; while ((line = reader.readLine()) != null) { progress++; logProgress(progress); DataEntry d = new DataEntry(line); // Calculate C/PY values long thisDay = getDayCount(d.getDate()); String doi = d.getId(); paperDates.put(doi, thisDay); paperCitations.put(doi, 0); List<String> authList = Arrays.asList(d.getAuthors().split(" ")); String journal = PrepareApsData.getJournalFromDoi(doi); String journalKey = "J:" + journal; double journalCpy = updateCpyData(journalKey, thisDay); double firstAuthorCpy = -2.0; double authorMaxCpy = -2.0; for (String author : authList) { String authorKey = "A:" + author; double authorCpy = updateCpyData(authorKey, thisDay); if (firstAuthorCpy == -2.0) { firstAuthorCpy = authorCpy; } if (authorCpy > authorMaxCpy) { authorMaxCpy = authorCpy; } } double selfcitMaxCy = 0.0; for (String cit : d.getCitations().split(" ")) { // Ignore citations that are not backwards in time: if (!cpyMapKeys.containsKey(cit)) continue; for (String k : cpyMapKeys.get(cit).split(" ")) { if (!k.startsWith("A:")) continue; k = k.substring(2); if (authList.contains(k)) { double selfcitCy = getPaperCy(cit, thisDay); if (selfcitCy > selfcitMaxCy) selfcitMaxCy = selfcitCy; continue; } } } // Calculate meme scores List<String> memes = new ArrayList<String>(); ms.recordTerms(d, memes); double topPs = 0; double topMs = 0; String topPsMeme = ""; String topMsMeme = ""; for (String meme : memes) { if (ms.getRelF(meme) > relFreqThreshold) continue; // ignore frequent terms double[] msValues = ms.calculateMemeScoreValues(meme, delta); double thisMs = msValues[3]; if (thisMs > topMs) { topMs = thisMs; topMsMeme = meme; } double thisPs = msValues[2]; if (thisPs > topMs) { topPs = thisPs; topPsMeme = meme; } } csvWriter.write(doi, journalCpy, firstAuthorCpy, authorMaxCpy, selfcitMaxCy, topPs, topPsMeme, topMs, topMsMeme); addCpyPaper(journalKey); String cpyKeys = journalKey; for (String author : authList) { String authorKey = "A:" + author; addCpyPaper(authorKey); cpyKeys += " " + authorKey; } String[] citList = d.getCitations().split(" "); for (String cit : citList) { // Ignore citations that are not backwards in time: if (!cpyMapKeys.containsKey(cit)) continue; for (String k : cpyMapKeys.get(cit).split(" ")) { addCpyCitation(k); } long date = paperDates.get(cit); if (thisDay < date + 365*citationYears) { paperCitations.put(cit, paperCitations.get(cit) + 1); } } cpyMapKeys.put(doi, cpyKeys); lastDay = thisDay; } } finally { if (csvWriter != null) csvWriter.close(); if (reader != null) reader.close(); } } private void writeSuccessColumn() throws IOException { BufferedReader r = new BufferedReader(new FileReader(outputTempFile)); CsvListReader csvReader = new CsvListReader(r, MemeUtils.getCsvPreference()); Writer w = new BufferedWriter(new FileWriter(outputFile)); CsvListWriter csvWriter = new CsvListWriter(w, MemeUtils.getCsvPreference()); Writer wm = new BufferedWriter(new FileWriter(outputMatrixFile)); CsvListWriter csvMatrixWriter = new CsvListWriter(wm, MemeUtils.getCsvPreference()); // Process header: List<String> line = csvReader.read(); line.add("CITATIONS-" + citationYears + "Y"); csvWriter.write(line); line.remove(line.size()-2); line.remove(0); csvMatrixWriter.write(line); while ((line = csvReader.read()) != null) { String doi = line.get(0); long date = paperDates.get(doi); boolean completeRow = false; if (lastDay >= date + 365*citationYears) { line.add(paperCitations.get(doi).toString()); completeRow = true; } else { line.add("-1"); } csvWriter.write(line); if (completeRow) { line.remove(line.size()-2); line.remove(0); csvMatrixWriter.write(line); } } csvWriter.close(); csvMatrixWriter.close(); csvReader.close(); } private double updateCpyData(String key, long thisDay) { Long lastDay = cpyLastDay.get(key); if (lastDay == null) lastDay = 0l; long dayDiff = thisDay - lastDay; Integer paperCount = cpyPaperCount.get(key); if (paperCount == null) paperCount = 0; Integer citationCount = cpyCitationCount.get(key); if (citationCount == null) citationCount = 0; Long paperDays = cpyPaperDays.get(key); if (paperDays == null) paperDays = 0l; paperDays = paperDays + paperCount*dayDiff; cpyPaperDays.put(key, paperDays); cpyLastDay.put(key, thisDay); return (citationCount * 365.0) / (paperDays + 1); } private double getPaperCy(String doi, long thisDay) { long dayDiff = thisDay - paperDates.get(doi); return (paperCitations.get(doi) * 365.0) / (dayDiff + 1); } private void addCpyPaper(String key) { Integer paperCount = cpyPaperCount.get(key); if (paperCount == null) paperCount = 0; cpyPaperCount.put(key, paperCount + 1); } private void addCpyCitation(String key) { Integer citationCount = cpyCitationCount.get(key); if (citationCount == null) citationCount = 0; cpyCitationCount.put(key, citationCount + 1); } private static long getDayCount(String date) { return TimeUnit.DAYS.convert(parseDate(date).getTime(), TimeUnit.MILLISECONDS); } private static final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); private static Date parseDate(String s) { try { return formatter.parse(s); } catch (ParseException ex) { throw new RuntimeException(ex); } } private String getOutputFileName() { return "su-" + inputFile.getName().replaceAll("-chronologic", "").replaceAll("\\..*$", ""); } private void logProgress(int p) { if (p % 100000 == 0) log(p + "..."); } private void log(Object obj) { MemeUtils.log(logFile, obj); } }
package org.neo4j.impl.nioneo.xa; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.transaction.xa.XAException; import org.neo4j.api.core.Node; import org.neo4j.api.core.Relationship; import org.neo4j.api.core.RelationshipType; import org.neo4j.impl.core.LockReleaser; import org.neo4j.impl.core.PropertyIndex; import org.neo4j.impl.core.RawPropertyIndex; import org.neo4j.impl.event.Event; import org.neo4j.impl.event.EventData; import org.neo4j.impl.event.EventManager; import org.neo4j.impl.nioneo.store.DynamicRecord; import org.neo4j.impl.nioneo.store.NeoStore; import org.neo4j.impl.nioneo.store.NodeRecord; import org.neo4j.impl.nioneo.store.NodeStore; import org.neo4j.impl.nioneo.store.PropertyData; import org.neo4j.impl.nioneo.store.PropertyIndexRecord; import org.neo4j.impl.nioneo.store.PropertyIndexStore; import org.neo4j.impl.nioneo.store.PropertyRecord; import org.neo4j.impl.nioneo.store.PropertyStore; import org.neo4j.impl.nioneo.store.PropertyType; import org.neo4j.impl.nioneo.store.Record; import org.neo4j.impl.nioneo.store.RelationshipData; import org.neo4j.impl.nioneo.store.RelationshipRecord; import org.neo4j.impl.nioneo.store.RelationshipStore; import org.neo4j.impl.nioneo.store.RelationshipTypeRecord; import org.neo4j.impl.nioneo.store.RelationshipTypeStore; import org.neo4j.impl.nioneo.store.StoreFailureException; import org.neo4j.impl.transaction.LockManager; import org.neo4j.impl.transaction.LockType; import org.neo4j.impl.transaction.xaframework.XaCommand; import org.neo4j.impl.transaction.xaframework.XaLogicalLog; import org.neo4j.impl.transaction.xaframework.XaTransaction; /** * Transaction containing {@link Command commands} reflecting the operations * performed in the transaction. */ class NeoTransaction extends XaTransaction { private final Map<Integer,NodeRecord> nodeRecords = new HashMap<Integer,NodeRecord>(); private final Map<Integer,PropertyRecord> propertyRecords = new HashMap<Integer,PropertyRecord>(); private final Map<Integer,RelationshipRecord> relRecords = new HashMap<Integer,RelationshipRecord>(); private final Map<Integer,RelationshipTypeRecord> relTypeRecords = new HashMap<Integer,RelationshipTypeRecord>(); private final Map<Integer,PropertyIndexRecord> propIndexRecords = new HashMap<Integer,PropertyIndexRecord>(); private final ArrayList<Command.NodeCommand> nodeCommands = new ArrayList<Command.NodeCommand>(); private final ArrayList<Command.PropertyCommand> propCommands = new ArrayList<Command.PropertyCommand>(); private final ArrayList<Command.PropertyIndexCommand> propIndexCommands = new ArrayList<Command.PropertyIndexCommand>(); private final ArrayList<Command.RelationshipCommand> relCommands = new ArrayList<Command.RelationshipCommand>(); private final ArrayList<Command.RelationshipTypeCommand> relTypeCommands = new ArrayList<Command.RelationshipTypeCommand>(); private final NeoStore neoStore; private boolean committed = false; private boolean prepared = false; private final LockReleaser lockReleaser; private final LockManager lockManager; private final EventManager eventManager; NeoTransaction( int identifier, XaLogicalLog log, NeoStore neoStore, LockReleaser lockReleaser, LockManager lockManager, EventManager eventManager ) { super( identifier, log ); this.neoStore = neoStore; this.lockReleaser = lockReleaser; this.lockManager = lockManager; this.eventManager = eventManager; } public boolean isReadOnly() { if ( isRecovered() ) { if ( nodeCommands.size() == 0 && propCommands.size() == 0 && relCommands.size() == 0 && relTypeCommands.size() == 0 && propIndexCommands.size() == 0 ) { return true; } return false; } if ( nodeRecords.size() == 0 && relRecords.size() == 0 && relTypeRecords.size() == 0 && propertyRecords.size() == 0 && propIndexRecords.size() == 0 ) { return true; } return false; } public void doAddCommand( XaCommand command ) { // override } @Override protected void doPrepare() throws XAException { if ( committed ) { throw new XAException( "Cannot prepare committed transaction[" + getIdentifier() + "]" ); } if ( prepared ) { throw new XAException( "Cannot prepare prepared transaction[" + getIdentifier() + "]" ); } // generate records then write to logical log via addCommand method prepared = true; for ( RelationshipTypeRecord record : relTypeRecords.values() ) { Command.RelationshipTypeCommand command = new Command.RelationshipTypeCommand( neoStore.getRelationshipTypeStore(), record ); relTypeCommands.add( command ); addCommand( command ); } for ( NodeRecord record : nodeRecords.values() ) { if ( !record.inUse() && record.getNextRel() != Record.NO_NEXT_RELATIONSHIP.intValue() ) { throw new StoreFailureException( "Node record " + record + " still has relationships" ); } Command.NodeCommand command = new Command.NodeCommand( neoStore.getNodeStore(), record ); nodeCommands.add( command ); if ( !record.inUse() ) { removeNodeFromCache( record.getId() ); } addCommand( command ); } for ( RelationshipRecord record : relRecords.values() ) { Command.RelationshipCommand command = new Command.RelationshipCommand( neoStore.getRelationshipStore(), record ); relCommands.add( command ); if ( !record.inUse() ) { removeRelationshipFromCache( record.getId() ); } addCommand( command ); } for ( PropertyIndexRecord record : propIndexRecords.values() ) { Command.PropertyIndexCommand command = new Command.PropertyIndexCommand( neoStore.getPropertyStore().getIndexStore(), record ); propIndexCommands.add( command ); addCommand( command ); } for ( PropertyRecord record : propertyRecords.values() ) { Command.PropertyCommand command = new Command.PropertyCommand( neoStore.getPropertyStore(), record ); propCommands.add( command ); addCommand( command ); } } @Override protected void injectCommand( XaCommand xaCommand ) { if ( xaCommand instanceof Command.NodeCommand ) { nodeCommands.add( (Command.NodeCommand) xaCommand ); } else if ( xaCommand instanceof Command.RelationshipCommand ) { relCommands.add( (Command.RelationshipCommand) xaCommand ); } else if ( xaCommand instanceof Command.PropertyCommand ) { propCommands.add( (Command.PropertyCommand) xaCommand ); } else if ( xaCommand instanceof Command.PropertyIndexCommand ) { propIndexCommands.add( (Command.PropertyIndexCommand) xaCommand ); } else if ( xaCommand instanceof Command.RelationshipTypeCommand ) { relTypeCommands.add( (Command.RelationshipTypeCommand) xaCommand ); } else { throw new RuntimeException( "Unkown command " + xaCommand ); } } public void doRollback() throws XAException { if ( committed ) { throw new XAException( "Cannot rollback partialy commited " + "transaction[" + getIdentifier() + "]. Recover and " + "commit" ); } try { for ( RelationshipTypeRecord record : relTypeRecords.values() ) { if ( record.isCreated() ) { getRelationshipTypeStore().freeId( record.getId() ); for ( DynamicRecord dynamicRecord : record.getTypeRecords() ) { if ( dynamicRecord.isCreated() ) { getRelationshipTypeStore().freeBlockId( dynamicRecord.getId() ); } } } removeRelationshipTypeFromCache( record.getId() ); } for ( NodeRecord record : nodeRecords.values() ) { if ( record.isCreated() ) { getNodeStore().freeId( record.getId() ); } removeNodeFromCache( record.getId() ); } for ( RelationshipRecord record : relRecords.values() ) { if ( record.isCreated() ) { getRelationshipStore().freeId( record.getId() ); } removeRelationshipFromCache( record.getId() ); } for ( PropertyIndexRecord record : propIndexRecords.values() ) { if ( record.isCreated() ) { getPropertyStore().getIndexStore().freeId( record.getId() ); for ( DynamicRecord dynamicRecord : record.getKeyRecords() ) { if ( dynamicRecord.isCreated() ) { getPropertyStore().getIndexStore().freeBlockId( dynamicRecord.getId() ); } } } } for ( PropertyRecord record : propertyRecords.values() ) { if ( record.getNodeId() != -1 ) { removeNodeFromCache( record.getNodeId() ); } else if ( record.getRelId() != -1 ) { removeRelationshipFromCache( record.getRelId() ); } if ( record.isCreated() ) { getPropertyStore().freeId( record.getId() ); for ( DynamicRecord dynamicRecord : record .getValueRecords() ) { if ( dynamicRecord.isCreated() ) { if ( dynamicRecord.getType() == PropertyType.STRING.intValue() ) { getPropertyStore().freeStringBlockId( dynamicRecord.getId() ); } else if ( dynamicRecord.getType() == PropertyType.ARRAY.intValue() ) { getPropertyStore().freeArrayBlockId( dynamicRecord.getId() ); } else { throw new RuntimeException( "Unkown type" ); } } } } } } finally { nodeRecords.clear(); propertyRecords.clear(); relRecords.clear(); relTypeRecords.clear(); propIndexRecords.clear(); nodeCommands.clear(); propCommands.clear(); propIndexCommands.clear(); relCommands.clear(); relTypeCommands.clear(); } } private void removeRelationshipTypeFromCache( int id ) { eventManager.generateProActiveEvent( Event.PURGE_REL_TYPE, new EventData( id ) ); } private void removeRelationshipFromCache( int id ) { eventManager.generateProActiveEvent( Event.PURGE_REL, new EventData( id ) ); } private void removeNodeFromCache( int id ) { eventManager.generateProActiveEvent( Event.PURGE_NODE, new EventData( id ) ); } public void doCommit() throws XAException { if ( !isRecovered() && !prepared ) { throw new XAException( "Cannot commit non prepared transaction[" + getIdentifier() + "]" ); } try { committed = true; CommandSorter sorter = new CommandSorter(); // reltypes java.util.Collections.sort( relTypeCommands, sorter ); for ( Command.RelationshipTypeCommand command : relTypeCommands ) { command.execute(); } // nodes java.util.Collections.sort( nodeCommands, sorter ); for ( Command.NodeCommand command : nodeCommands ) { command.execute(); } // relationships java.util.Collections.sort( relCommands, sorter ); for ( Command.RelationshipCommand command : relCommands ) { command.execute(); } java.util.Collections.sort( propIndexCommands, sorter ); for ( Command.PropertyIndexCommand command : propIndexCommands ) { command.execute(); } // properties java.util.Collections.sort( propCommands, sorter ); for ( Command.PropertyCommand command : propCommands ) { command.execute(); } } finally { nodeRecords.clear(); propertyRecords.clear(); relRecords.clear(); relTypeRecords.clear(); propIndexRecords.clear(); nodeCommands.clear(); propCommands.clear(); propIndexCommands.clear(); relCommands.clear(); relTypeCommands.clear(); } } private RelationshipTypeStore getRelationshipTypeStore() { return neoStore.getRelationshipTypeStore(); } private NodeStore getNodeStore() { return neoStore.getNodeStore(); } private RelationshipStore getRelationshipStore() { return neoStore.getRelationshipStore(); } private PropertyStore getPropertyStore() { return neoStore.getPropertyStore(); } public boolean nodeLoadLight( int nodeId ) { NodeRecord nodeRecord = getNodeRecord( nodeId ); if ( nodeRecord != null ) { return nodeRecord.inUse(); } return getNodeStore().loadLightNode( nodeId ); } public RelationshipData relationshipLoad( int id ) { RelationshipRecord relRecord = getRelationshipRecord( id ); if ( relRecord != null ) { if ( !relRecord.inUse() ) { return null; } return new RelationshipData( id, relRecord.getFirstNode(), relRecord.getSecondNode(), relRecord.getType() ); } relRecord = getRelationshipStore().getLightRel( id ); if ( relRecord != null ) { return new RelationshipData( id, relRecord.getFirstNode(), relRecord.getSecondNode(), relRecord.getType() ); } return null; } void nodeDelete( int nodeId ) { NodeRecord nodeRecord = getNodeRecord( nodeId ); if ( nodeRecord == null ) { nodeRecord = getNodeStore().getRecord( nodeId ); addNodeRecord( nodeRecord ); } if ( !nodeRecord.inUse() ) { throw new IllegalStateException( "Unable to delete Node[" + nodeId + "] since it has already been deleted." ); } nodeRecord.setInUse( false ); int nextProp = nodeRecord.getNextProp(); while ( nextProp != Record.NO_NEXT_PROPERTY.intValue() ) { PropertyRecord propRecord = getPropertyRecord( nextProp ); if ( propRecord == null ) { propRecord = getPropertyStore().getRecord( nextProp ); addPropertyRecord( propRecord ); } if ( propRecord.isLight() ) { getPropertyStore().makeHeavy( propRecord ); } nextProp = propRecord.getNextProp(); propRecord.setInUse( false ); // TODO: update count on property index record for ( DynamicRecord valueRecord : propRecord.getValueRecords() ) { valueRecord.setInUse( false ); } } } void relDelete( int id ) { RelationshipRecord record = getRelationshipRecord( id ); if ( record == null ) { record = getRelationshipStore().getRecord( id ); addRelationshipRecord( record ); } if ( !record.inUse() ) { throw new IllegalStateException( "Unable to delete relationship[" + id + "] since it is already deleted." ); } int nextProp = record.getNextProp(); while ( nextProp != Record.NO_NEXT_PROPERTY.intValue() ) { PropertyRecord propRecord = getPropertyRecord( nextProp ); if ( propRecord == null ) { propRecord = getPropertyStore().getRecord( nextProp ); addPropertyRecord( propRecord ); } if ( propRecord.isLight() ) { getPropertyStore().makeHeavy( propRecord ); } nextProp = propRecord.getNextProp(); propRecord.setInUse( false ); // TODO: update count on property index record for ( DynamicRecord valueRecord : propRecord.getValueRecords() ) { valueRecord.setInUse( false ); } } disconnectRelationship( record ); updateNodes( record ); record.setInUse( false ); } private void disconnectRelationship( RelationshipRecord rel ) { // update first node prev if ( rel.getFirstPrevRel() != Record.NO_NEXT_RELATIONSHIP.intValue() ) { Relationship lockableRel = new LockableRelationship( rel.getFirstPrevRel() ); getWriteLock( lockableRel ); RelationshipRecord prevRel = getRelationshipRecord( rel.getFirstPrevRel() ); if ( prevRel == null ) { prevRel = getRelationshipStore().getRecord( rel.getFirstPrevRel() ); addRelationshipRecord( prevRel ); } if ( prevRel.getFirstNode() == rel.getFirstNode() ) { prevRel.setFirstNextRel( rel.getFirstNextRel() ); } else if ( prevRel.getSecondNode() == rel.getFirstNode() ) { prevRel.setSecondNextRel( rel.getFirstNextRel() ); } else { throw new RuntimeException( prevRel + " don't match " + rel ); } } // update first node next if ( rel.getFirstNextRel() != Record.NO_NEXT_RELATIONSHIP.intValue() ) { Relationship lockableRel = new LockableRelationship( rel.getFirstNextRel() ); getWriteLock( lockableRel ); RelationshipRecord nextRel = getRelationshipRecord( rel.getFirstNextRel() ); if ( nextRel == null ) { nextRel = getRelationshipStore().getRecord( rel.getFirstNextRel() ); addRelationshipRecord( nextRel ); } if ( nextRel.getFirstNode() == rel.getFirstNode() ) { nextRel.setFirstPrevRel( rel.getFirstPrevRel() ); } else if ( nextRel.getSecondNode() == rel.getFirstNode() ) { nextRel.setSecondPrevRel( rel.getFirstPrevRel() ); } else { throw new RuntimeException( nextRel + " don't match " + rel ); } } // update second node prev if ( rel.getSecondPrevRel() != Record.NO_NEXT_RELATIONSHIP.intValue() ) { Relationship lockableRel = new LockableRelationship( rel.getSecondPrevRel() ); getWriteLock( lockableRel ); RelationshipRecord prevRel = getRelationshipRecord( rel.getSecondPrevRel() ); if ( prevRel == null ) { prevRel = getRelationshipStore().getRecord( rel.getSecondPrevRel() ); addRelationshipRecord( prevRel ); } if ( prevRel.getFirstNode() == rel.getSecondNode() ) { prevRel.setFirstNextRel( rel.getSecondNextRel() ); } else if ( prevRel.getSecondNode() == rel.getSecondNode() ) { prevRel.setSecondNextRel( rel.getSecondNextRel() ); } else { throw new RuntimeException( prevRel + " don't match " + rel ); } } // update second node next if ( rel.getSecondNextRel() != Record.NO_NEXT_RELATIONSHIP.intValue() ) { Relationship lockableRel = new LockableRelationship( rel.getSecondNextRel() ); getWriteLock( lockableRel ); RelationshipRecord nextRel = getRelationshipRecord( rel.getSecondNextRel() ); if ( nextRel == null ) { nextRel = getRelationshipStore().getRecord( rel.getSecondNextRel() ); addRelationshipRecord( nextRel ); } if ( nextRel.getFirstNode() == rel.getSecondNode() ) { nextRel.setFirstPrevRel( rel.getSecondPrevRel() ); } else if ( nextRel.getSecondNode() == rel.getSecondNode() ) { nextRel.setSecondPrevRel( rel.getSecondPrevRel() ); } else { throw new RuntimeException( nextRel + " don't match " + rel ); } } } private void getWriteLock( Relationship lockableRel ) { lockManager.getWriteLock( lockableRel ); lockReleaser.addLockToTransaction( lockableRel, LockType.WRITE ); } public RelationshipData[] nodeGetRelationships( int nodeId ) { NodeRecord nodeRecord = getNodeRecord( nodeId ); if ( nodeRecord == null ) { nodeRecord = getNodeStore().getRecord( nodeId ); } int nextRel = nodeRecord.getNextRel(); List<RelationshipData> rels = new ArrayList<RelationshipData>(); while ( nextRel != Record.NO_NEXT_RELATIONSHIP.intValue() ) { RelationshipRecord relRecord = getRelationshipRecord( nextRel ); if ( relRecord == null ) { relRecord = getRelationshipStore().getRecord( nextRel ); } int firstNode = relRecord.getFirstNode(); int secondNode = relRecord.getSecondNode(); rels.add( new RelationshipData( nextRel, firstNode, secondNode, relRecord.getType() ) ); if ( firstNode == nodeId ) { nextRel = relRecord.getFirstNextRel(); } else if ( secondNode == nodeId ) { nextRel = relRecord.getSecondNextRel(); } else { throw new RuntimeException( "GAH" ); } } return rels.toArray( new RelationshipData[rels.size()] ); } private void updateNodes( RelationshipRecord rel ) { if ( rel.getFirstPrevRel() == Record.NO_PREV_RELATIONSHIP.intValue() ) { NodeRecord firstNode = getNodeRecord( rel.getFirstNode() ); if ( firstNode == null ) { firstNode = getNodeStore().getRecord( rel.getFirstNode() ); addNodeRecord( firstNode ); } firstNode.setNextRel( rel.getFirstNextRel() ); } if ( rel.getSecondPrevRel() == Record.NO_PREV_RELATIONSHIP.intValue() ) { NodeRecord secondNode = getNodeRecord( rel.getSecondNode() ); if ( secondNode == null ) { secondNode = getNodeStore().getRecord( rel.getSecondNode() ); addNodeRecord( secondNode ); } secondNode.setNextRel( rel.getSecondNextRel() ); } } void relRemoveProperty( int relId, int propertyId ) { RelationshipRecord relRecord = getRelationshipRecord( relId ); if ( relRecord == null ) { relRecord = getRelationshipStore().getRecord( relId ); } if ( !relRecord.inUse() ) { throw new IllegalStateException( "Property remove on relationship[" + relId + "] illegal since it has been deleted." ); } PropertyRecord propRecord = getPropertyRecord( propertyId ); if ( propRecord == null ) { propRecord = getPropertyStore().getRecord( propertyId ); addPropertyRecord( propRecord ); } propRecord.setRelId( relId ); if ( propRecord.isLight() ) { getPropertyStore().makeHeavy( propRecord ); } propRecord.setInUse( false ); // TODO: update count on property index record for ( DynamicRecord valueRecord : propRecord.getValueRecords() ) { if ( valueRecord.inUse() ) { valueRecord.setInUse( false, propRecord.getType().intValue() ); } } int prevProp = propRecord.getPrevProp(); int nextProp = propRecord.getNextProp(); if ( relRecord.getNextProp() == propertyId ) { relRecord.setNextProp( nextProp ); // re-adding not a problem addRelationshipRecord( relRecord ); } if ( prevProp != Record.NO_PREVIOUS_PROPERTY.intValue() ) { PropertyRecord prevPropRecord = getPropertyRecord( prevProp ); if ( prevPropRecord == null ) { prevPropRecord = getPropertyStore().getLightRecord( prevProp ); addPropertyRecord( prevPropRecord ); } prevPropRecord.setNextProp( nextProp ); } if ( nextProp != Record.NO_NEXT_PROPERTY.intValue() ) { PropertyRecord nextPropRecord = getPropertyRecord( nextProp ); if ( nextPropRecord == null ) { nextPropRecord = getPropertyStore().getLightRecord( nextProp ); addPropertyRecord( nextPropRecord ); } nextPropRecord.setPrevProp( prevProp ); } } public PropertyData[] relGetProperties( int relId ) { RelationshipRecord relRecord = getRelationshipRecord( relId ); if ( relRecord == null ) { relRecord = getRelationshipStore().getRecord( relId ); } int nextProp = relRecord.getNextProp(); List<PropertyData> properties = new ArrayList<PropertyData>(); while ( nextProp != Record.NO_NEXT_PROPERTY.intValue() ) { PropertyRecord propRecord = getPropertyRecord( nextProp ); if ( propRecord == null ) { propRecord = getPropertyStore().getLightRecord( nextProp ); } properties.add( new PropertyData( propRecord.getId(), propRecord.getKeyIndexId(), propertyGetValueOrNull( propRecord ) ) ); nextProp = propRecord.getNextProp(); } return properties.toArray( new PropertyData[properties.size()] ); } public PropertyData[] nodeGetProperties( int nodeId ) { NodeRecord nodeRecord = getNodeRecord( nodeId ); if ( nodeRecord == null ) { nodeRecord = getNodeStore().getRecord( nodeId ); } int nextProp = nodeRecord.getNextProp(); List<PropertyData> properties = new ArrayList<PropertyData>(); while ( nextProp != Record.NO_NEXT_PROPERTY.intValue() ) { PropertyRecord propRecord = getPropertyRecord( nextProp ); if ( propRecord == null ) { propRecord = getPropertyStore().getLightRecord( nextProp ); } properties.add( new PropertyData( propRecord.getId(), propRecord.getKeyIndexId(), propertyGetValueOrNull( propRecord ) ) ); nextProp = propRecord.getNextProp(); } return properties.toArray( new PropertyData[properties.size()] ); } public Object propertyGetValueOrNull( PropertyRecord propertyRecord ) { PropertyType type = propertyRecord.getType(); if ( type == PropertyType.INT ) { return (int) propertyRecord.getPropBlock(); } if ( type == PropertyType.STRING ) { return null; } if ( type == PropertyType.BOOL ) { if ( propertyRecord.getPropBlock() == 1 ) { return Boolean.valueOf( true ); } return Boolean.valueOf( false ); } if ( type == PropertyType.DOUBLE ) { return new Double( Double.longBitsToDouble( propertyRecord.getPropBlock() ) ); } if ( type == PropertyType.FLOAT ) { return new Float( Float.intBitsToFloat( (int) propertyRecord.getPropBlock() ) ); } if ( type == PropertyType.LONG ) { return propertyRecord.getPropBlock(); } if ( type == PropertyType.BYTE ) { return (byte) propertyRecord.getPropBlock(); } if ( type == PropertyType.CHAR ) { return (char) propertyRecord.getPropBlock(); } if ( type == PropertyType.ARRAY ) { return null; } if ( type == PropertyType.SHORT ) { return (short) propertyRecord.getPropBlock(); } throw new RuntimeException( "Unkown type: " + type ); } public Object propertyGetValue( int id ) { PropertyRecord propertyRecord = getPropertyRecord( id ); if ( propertyRecord == null ) { propertyRecord = getPropertyStore().getRecord( id ); } if ( propertyRecord.isLight() ) { getPropertyStore().makeHeavy( propertyRecord ); } PropertyType type = propertyRecord.getType(); if ( type == PropertyType.INT ) { return (int) propertyRecord.getPropBlock(); } if ( type == PropertyType.STRING ) { return getPropertyStore().getStringFor( propertyRecord ); } if ( type == PropertyType.BOOL ) { if ( propertyRecord.getPropBlock() == 1 ) { return Boolean.valueOf( true ); } return Boolean.valueOf( false ); } if ( type == PropertyType.DOUBLE ) { return new Double( Double.longBitsToDouble( propertyRecord.getPropBlock() ) ); } if ( type == PropertyType.FLOAT ) { return new Float( Float.intBitsToFloat( (int) propertyRecord.getPropBlock() ) ); } if ( type == PropertyType.LONG ) { return propertyRecord.getPropBlock(); } if ( type == PropertyType.BYTE ) { return (byte) propertyRecord.getPropBlock(); } if ( type == PropertyType.CHAR ) { return (char) propertyRecord.getPropBlock(); } if ( type == PropertyType.ARRAY ) { return getPropertyStore().getArrayFor( propertyRecord ); } if ( type == PropertyType.SHORT ) { return (short) propertyRecord.getPropBlock(); } throw new RuntimeException( "Unkown type: " + type ); } void nodeRemoveProperty( int nodeId, int propertyId ) { NodeRecord nodeRecord = getNodeRecord( nodeId ); if ( nodeRecord == null ) { nodeRecord = getNodeStore().getRecord( nodeId ); } if ( !nodeRecord.inUse() ) { throw new IllegalStateException( "Property remove on node[" + nodeId + "] illegal since it has been deleted." ); } PropertyRecord propRecord = getPropertyRecord( propertyId ); if ( propRecord == null ) { propRecord = getPropertyStore().getRecord( propertyId ); addPropertyRecord( propRecord ); } propRecord.setNodeId( nodeId ); if ( propRecord.isLight() ) { getPropertyStore().makeHeavy( propRecord ); } propRecord.setInUse( false ); // TODO: update count on property index record for ( DynamicRecord valueRecord : propRecord.getValueRecords() ) { if ( valueRecord.inUse() ) { valueRecord.setInUse( false, propRecord.getType().intValue() ); } } int prevProp = propRecord.getPrevProp(); int nextProp = propRecord.getNextProp(); if ( nodeRecord.getNextProp() == propertyId ) { nodeRecord.setNextProp( nextProp ); // re-adding not a problem addNodeRecord( nodeRecord ); } if ( prevProp != Record.NO_PREVIOUS_PROPERTY.intValue() ) { PropertyRecord prevPropRecord = getPropertyRecord( prevProp ); if ( prevPropRecord == null ) { prevPropRecord = getPropertyStore().getLightRecord( prevProp ); } prevPropRecord.setNextProp( nextProp ); addPropertyRecord( prevPropRecord ); } if ( nextProp != Record.NO_NEXT_PROPERTY.intValue() ) { PropertyRecord nextPropRecord = getPropertyRecord( nextProp ); if ( nextPropRecord == null ) { nextPropRecord = getPropertyStore().getLightRecord( nextProp ); } nextPropRecord.setPrevProp( prevProp ); addPropertyRecord( nextPropRecord ); } } void relChangeProperty( int relId, int propertyId, Object value ) { RelationshipRecord relRecord = getRelationshipRecord( relId ); if ( relRecord == null ) { relRecord = getRelationshipStore().getRecord( relId ); } if ( !relRecord.inUse() ) { throw new IllegalStateException( "Property change on relationship[" + relId + "] illegal since it has been deleted." ); } PropertyRecord propertyRecord = getPropertyRecord( propertyId ); if ( propertyRecord == null ) { propertyRecord = getPropertyStore().getRecord( propertyId ); addPropertyRecord( propertyRecord ); } propertyRecord.setRelId( relId ); if ( propertyRecord.isLight() ) { getPropertyStore().makeHeavy( propertyRecord ); } if ( propertyRecord.getType() == PropertyType.STRING ) { for ( DynamicRecord record : propertyRecord.getValueRecords() ) { if ( record.inUse() ) { record.setInUse( false, PropertyType.STRING.intValue() ); } } } else if ( propertyRecord.getType() == PropertyType.ARRAY ) { for ( DynamicRecord record : propertyRecord.getValueRecords() ) { if ( record.inUse() ) { record.setInUse( false, PropertyType.ARRAY.intValue() ); } } } getPropertyStore().encodeValue( propertyRecord, value ); addPropertyRecord( propertyRecord ); } void nodeChangeProperty( int nodeId, int propertyId, Object value ) { NodeRecord nodeRecord = getNodeRecord( nodeId ); if ( nodeRecord == null ) { nodeRecord = getNodeStore().getRecord( nodeId ); } if ( !nodeRecord.inUse() ) { throw new IllegalStateException( "Property change on node[" + nodeId + "] illegal since it has been deleted." ); } PropertyRecord propertyRecord = getPropertyRecord( propertyId ); if ( propertyRecord == null ) { propertyRecord = getPropertyStore().getRecord( propertyId ); addPropertyRecord( propertyRecord ); } propertyRecord.setNodeId( nodeId ); if ( propertyRecord.isLight() ) { getPropertyStore().makeHeavy( propertyRecord ); } if ( propertyRecord.getType() == PropertyType.STRING ) { for ( DynamicRecord record : propertyRecord.getValueRecords() ) { if ( record.inUse() ) { record.setInUse( false, PropertyType.STRING.intValue() ); } } } else if ( propertyRecord.getType() == PropertyType.ARRAY ) { for ( DynamicRecord record : propertyRecord.getValueRecords() ) { if ( record.inUse() ) { record.setInUse( false, PropertyType.ARRAY.intValue() ); } } } getPropertyStore().encodeValue( propertyRecord, value ); addPropertyRecord( propertyRecord ); } void relAddProperty( int relId, int propertyId, PropertyIndex index, Object value ) { RelationshipRecord relRecord = getRelationshipRecord( relId ); if ( relRecord == null ) { relRecord = getRelationshipStore().getRecord( relId ); addRelationshipRecord( relRecord ); } if ( !relRecord.inUse() ) { throw new IllegalStateException( "Property add on relationship[" + relId + "] illegal since it has been deleted." ); } PropertyRecord propertyRecord = new PropertyRecord( propertyId ); propertyRecord.setInUse( true ); propertyRecord.setCreated(); if ( relRecord.getNextProp() != Record.NO_NEXT_RELATIONSHIP.intValue() ) { PropertyRecord prevProp = getPropertyRecord( relRecord.getNextProp() ); if ( prevProp == null ) { prevProp = getPropertyStore().getLightRecord( relRecord.getNextProp() ); addPropertyRecord( prevProp ); } assert prevProp.getPrevProp() == Record.NO_PREVIOUS_PROPERTY.intValue(); prevProp.setPrevProp( propertyId ); propertyRecord.setNextProp( prevProp.getId() ); } int keyIndexId = index.getKeyId(); propertyRecord.setKeyIndexId( keyIndexId ); getPropertyStore().encodeValue( propertyRecord, value ); relRecord.setNextProp( propertyId ); addPropertyRecord( propertyRecord ); } void nodeAddProperty( int nodeId, int propertyId, PropertyIndex index, Object value ) { NodeRecord nodeRecord = getNodeRecord( nodeId ); if ( nodeRecord == null ) { nodeRecord = getNodeStore().getRecord( nodeId ); addNodeRecord( nodeRecord ); } if ( !nodeRecord.inUse() ) { throw new IllegalStateException( "Property add on node[" + nodeId + "] illegal since it has been deleted." ); } PropertyRecord propertyRecord = new PropertyRecord( propertyId ); propertyRecord.setInUse( true ); propertyRecord.setCreated(); // encoding has to be set here before anything is change // (exception is thrown in encodeValue now and tx not marked // rollback only getPropertyStore().encodeValue( propertyRecord, value ); if ( nodeRecord.getNextProp() != Record.NO_NEXT_PROPERTY.intValue() ) { PropertyRecord prevProp = getPropertyRecord( nodeRecord.getNextProp() ); if ( prevProp == null ) { prevProp = getPropertyStore().getLightRecord( nodeRecord.getNextProp() ); addPropertyRecord( prevProp ); } assert prevProp.getPrevProp() == Record.NO_PREVIOUS_PROPERTY.intValue(); prevProp.setPrevProp( propertyId ); propertyRecord.setNextProp( prevProp.getId() ); } int keyIndexId = index.getKeyId(); propertyRecord.setKeyIndexId( keyIndexId ); nodeRecord.setNextProp( propertyId ); addPropertyRecord( propertyRecord ); } void relationshipCreate( int id, int firstNodeId, int secondNodeId, int type ) { NodeRecord firstNode = getNodeRecord( firstNodeId ); if ( firstNode == null ) { firstNode = getNodeStore().getRecord( firstNodeId ); addNodeRecord( firstNode ); } if ( !firstNode.inUse() ) { throw new IllegalStateException( "First node[" + firstNodeId + "] is deleted and cannot be used to create a relationship" ); } NodeRecord secondNode = getNodeRecord( secondNodeId ); if ( secondNode == null ) { secondNode = getNodeStore().getRecord( secondNodeId ); addNodeRecord( secondNode ); } if ( !secondNode.inUse() ) { throw new IllegalStateException( "Second node[" + secondNodeId + "] is deleted and cannot be used to create a relationship" ); } RelationshipRecord record = new RelationshipRecord( id, firstNodeId, secondNodeId, type ); record.setInUse( true ); record.setCreated(); addRelationshipRecord( record ); connectRelationship( firstNode, secondNode, record ); } private void connectRelationship( NodeRecord firstNode, NodeRecord secondNode, RelationshipRecord rel ) { assert firstNode.getNextRel() != rel.getId(); assert secondNode.getNextRel() != rel.getId(); rel.setFirstNextRel( firstNode.getNextRel() ); rel.setSecondNextRel( secondNode.getNextRel() ); if ( firstNode.getNextRel() != Record.NO_NEXT_RELATIONSHIP.intValue() ) { Relationship lockableRel = new LockableRelationship( firstNode.getNextRel() ); getWriteLock( lockableRel ); RelationshipRecord nextRel = getRelationshipRecord( firstNode.getNextRel() ); if ( nextRel == null ) { nextRel = getRelationshipStore().getRecord( firstNode.getNextRel() ); addRelationshipRecord( nextRel ); } if ( nextRel.getFirstNode() == firstNode.getId() ) { nextRel.setFirstPrevRel( rel.getId() ); } else if ( nextRel.getSecondNode() == firstNode.getId() ) { nextRel.setSecondPrevRel( rel.getId() ); } else { throw new RuntimeException( firstNode + " dont match " + nextRel ); } } if ( secondNode.getNextRel() != Record.NO_NEXT_RELATIONSHIP.intValue() ) { Relationship lockableRel = new LockableRelationship( secondNode.getNextRel() ); getWriteLock( lockableRel ); RelationshipRecord nextRel = getRelationshipRecord( secondNode.getNextRel() ); if ( nextRel == null ) { nextRel = getRelationshipStore().getRecord( secondNode.getNextRel() ); addRelationshipRecord( nextRel ); } if ( nextRel.getFirstNode() == secondNode.getId() ) { nextRel.setFirstPrevRel( rel.getId() ); } else if ( nextRel.getSecondNode() == secondNode.getId() ) { nextRel.setSecondPrevRel( rel.getId() ); } else { throw new RuntimeException( firstNode + " dont match " + nextRel ); } } firstNode.setNextRel( rel.getId() ); secondNode.setNextRel( rel.getId() ); } void nodeCreate( int nodeId ) { NodeRecord nodeRecord = new NodeRecord( nodeId ); nodeRecord.setInUse( true ); nodeRecord.setCreated(); addNodeRecord( nodeRecord ); } String getPropertyIndex( int id ) { PropertyIndexStore indexStore = getPropertyStore().getIndexStore(); PropertyIndexRecord index = getPropertyIndexRecord( id ); if ( index == null ) { index = indexStore.getRecord( id ); } if ( index.isLight() ) { indexStore.makeHeavy( index ); } return indexStore.getStringFor( index ); } RawPropertyIndex[] getPropertyIndexes( int count ) { PropertyIndexStore indexStore = getPropertyStore().getIndexStore(); return indexStore.getPropertyIndexes( count ); } void createPropertyIndex( int id, String key ) { PropertyIndexRecord record = new PropertyIndexRecord( id ); record.setInUse( true ); record.setCreated(); PropertyIndexStore propIndexStore = getPropertyStore().getIndexStore(); int keyBlockId = propIndexStore.nextKeyBlockId(); record.setKeyBlockId( keyBlockId ); int length = key.length(); char[] chars = new char[length]; key.getChars( 0, length, chars, 0 ); Collection<DynamicRecord> keyRecords = propIndexStore.allocateKeyRecords( keyBlockId, chars ); for ( DynamicRecord keyRecord : keyRecords ) { record.addKeyRecord( keyRecord ); } addPropertyIndexRecord( record ); } void relationshipTypeAdd( int id, String name ) { RelationshipTypeRecord record = new RelationshipTypeRecord( id ); record.setInUse( true ); record.setCreated(); int blockId = getRelationshipTypeStore().nextBlockId(); record.setTypeBlock( blockId ); int length = name.length(); char[] chars = new char[length]; name.getChars( 0, length, chars, 0 ); Collection<DynamicRecord> typeNameRecords = getRelationshipTypeStore().allocateTypeNameRecords( blockId, chars ); for ( DynamicRecord typeRecord : typeNameRecords ) { record.addTypeRecord( typeRecord ); } addRelationshipTypeRecord( record ); } static class CommandSorter implements Comparator<Command>, Serializable { public int compare( Command o1, Command o2 ) { int id1 = o1.getKey(); int id2 = o2.getKey(); return id1 - id2; } public boolean equals( Object o ) { if ( o instanceof CommandSorter ) { return true; } return false; } public int hashCode() { return 3217; } } void addNodeRecord( NodeRecord record ) { nodeRecords.put( record.getId(), record ); } NodeRecord getNodeRecord( int nodeId ) { return nodeRecords.get( nodeId ); } void addRelationshipRecord( RelationshipRecord record ) { relRecords.put( record.getId(), record ); } RelationshipRecord getRelationshipRecord( int relId ) { return relRecords.get( relId ); } void addPropertyRecord( PropertyRecord record ) { propertyRecords.put( record.getId(), record ); } PropertyRecord getPropertyRecord( int propertyId ) { return propertyRecords.get( propertyId ); } void addRelationshipTypeRecord( RelationshipTypeRecord record ) { relTypeRecords.put( record.getId(), record ); } void addPropertyIndexRecord( PropertyIndexRecord record ) { propIndexRecords.put( record.getId(), record ); } PropertyIndexRecord getPropertyIndexRecord( int id ) { return propIndexRecords.get( id ); } private static class LockableRelationship implements Relationship { private final int id; LockableRelationship( int id ) { this.id = id; } public void delete() { throw new UnsupportedOperationException( "Lockable rel" ); } public Node getEndNode() { throw new UnsupportedOperationException( "Lockable rel" ); } public long getId() { return this.id; } public Node[] getNodes() { throw new UnsupportedOperationException( "Lockable rel" ); } public Node getOtherNode( Node node ) { throw new UnsupportedOperationException( "Lockable rel" ); } public Object getProperty( String key ) { throw new UnsupportedOperationException( "Lockable rel" ); } public Object getProperty( String key, Object defaultValue ) { throw new UnsupportedOperationException( "Lockable rel" ); } public Iterable<String> getPropertyKeys() { throw new UnsupportedOperationException( "Lockable rel" ); } public Iterable<Object> getPropertyValues() { throw new UnsupportedOperationException( "Lockable rel" ); } public Node getStartNode() { throw new UnsupportedOperationException( "Lockable rel" ); } public RelationshipType getType() { throw new UnsupportedOperationException( "Lockable rel" ); } public boolean isType( RelationshipType type ) { throw new UnsupportedOperationException( "Lockable rel" ); } public boolean hasProperty( String key ) { throw new UnsupportedOperationException( "Lockable rel" ); } public Object removeProperty( String key ) { throw new UnsupportedOperationException( "Lockable rel" ); } public void setProperty( String key, Object value ) { throw new UnsupportedOperationException( "Lockable rel" ); } public boolean equals( Object o ) { if ( !(o instanceof Relationship) ) { return false; } return this.getId() == ((Relationship) o).getId(); } public int hashCode() { return id; } public String toString() { return "Lockable relationship #" + this.getId(); } } }
package com.sdl.selenium.extjs6.slider; import com.sdl.selenium.utils.config.WebDriverConfig; import com.sdl.selenium.web.WebLocator; import org.openqa.selenium.interactions.Actions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Slider extends WebLocator { private static final Logger LOGGER = LoggerFactory.getLogger(Slider.class); public Slider() { withClassName("Slider"); withBaseCls("x-slider"); } public Slider(WebLocator container) { this(); withContainer(container); } public Slider(WebLocator container, String label) { this(container); withLabel(label); } public boolean move(int distance) { boolean exists = true; WebLocator element = new WebLocator(this).setTag("descendant::*").setClasses("x-slider-thumb"); if (element.ready()) { element.mouseOver(); boolean done = false; int distanceTemp = distance; do { int value = Integer.parseInt(getAttribute("aria-valuenow")); if (value > distance) { distanceTemp = -(value - distance); } else if (value < distance) { distanceTemp = distance - value; } else { done = true; } if (!done) { LOGGER.info("not done for: {}", distance); if (distanceTemp == 1 || distanceTemp == 2) { distanceTemp = distanceTemp + (distanceTemp == 1 ? 5 : 2); } else if (distanceTemp == -1 || distanceTemp == -2) { distanceTemp = distanceTemp - (distanceTemp == -1 ? 5 : 2); } else { distanceTemp = distanceTemp * 2 + 1; } new Actions(WebDriverConfig.getDriver()).dragAndDropBy(element.getWebElement(), distanceTemp, 1).build().perform(); element.mouseOver(); } } while (!done); } else { LOGGER.warn("The slider for " + getPathBuilder().getLabel() + " has not been selected or is missing"); exists = false; } return exists; } }
package org.ensembl.healthcheck.eg_gui; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.ensembl.healthcheck.DatabaseRegistry; import org.ensembl.healthcheck.DatabaseRegistryEntry; import org.ensembl.healthcheck.DatabaseType; import org.ensembl.healthcheck.eg_gui.DatabaseListPanel; import org.ensembl.healthcheck.eg_gui.DatabaseRadioButton; import org.ensembl.healthcheck.eg_gui.DatabaseTypeGUIComparator; import org.ensembl.healthcheck.eg_gui.TabChangeListener; /** * <p> * A class that extends JTabbedPane and provides a method for getting all the selected databases. * Also highlights currently-selected tab. * </p> * */ public class DatabaseTabbedPane extends JTabbedPane { /** * * <p> * Creates a map that maps a DatabaseRegistryEntry to the JRadioButton * that will represent for selection in the gui. * </p> * * @param databaseRegistry * @return Map<DatabaseRegistryEntry, JRadioButton> * */ protected Map<DatabaseRegistryEntry, JRadioButton> createRadioButtonsForDb(DatabaseRegistryEntry[] allDbEntries) { Map<DatabaseRegistryEntry, JRadioButton> checkBoxMap = new HashMap<DatabaseRegistryEntry, JRadioButton>(); for (DatabaseRegistryEntry currentEntry : allDbEntries) { DatabaseRadioButton dbcb = new DatabaseRadioButton(currentEntry, false); checkBoxMap.put(currentEntry, dbcb); } return checkBoxMap; } /** * * <p> * Searches through an array of allDbEntries and creates a list of * DatabaseRegistryEntry with the specified filterForType. * </p> * * @param allDbEntries * @param filterForType * @return * */ private List<DatabaseRegistryEntry> filterForDbsOfType(DatabaseRegistryEntry[] allDbEntries, DatabaseType filterForType) { List<DatabaseRegistryEntry> dbRegistryEntryWithOfType = new ArrayList<DatabaseRegistryEntry>(); for (DatabaseRegistryEntry currentEntry : allDbEntries) { if (currentEntry.getType() == filterForType) { dbRegistryEntryWithOfType.add(currentEntry); } } return dbRegistryEntryWithOfType; } /** * * <p> * Creates the database tabbed pane from which the user can select the * database on which he wants to run his tests. * </p> * * @param databaseRegistry * */ public DatabaseTabbedPane(DatabaseRegistry databaseRegistry) { init(databaseRegistry); } public void init(DatabaseRegistry databaseRegistry) { this.removeAll(); DatabaseRegistryEntry[] allDbEntries = databaseRegistry.getAll(); if (allDbEntries.length==0) { addTab( "Problem", new JLabel("No databases found! Possibly the server can't be reached.") ); } Map<DatabaseRegistryEntry, JRadioButton> checkBoxMap = createRadioButtonsForDb(allDbEntries); DatabaseType[] types = databaseRegistry.getTypes(); Arrays.sort(types, new DatabaseTypeGUIComparator()); // One Buttongroup for all radio buttons across all the database // tabs. ButtonGroup myOneAndOnlyButtonGroup = new ButtonGroup(); for (DatabaseType currentDbType : types) { // Create a list of databases on the server with the currentDbType. List<DatabaseRegistryEntry> dbsOnServerWithThisType = filterForDbsOfType( databaseRegistry.getAll(), currentDbType ); // Create Radiobuttons for them for the user to select. List<JRadioButton> checkBoxesTabForCurrentType = new ArrayList<JRadioButton>(); for (DatabaseRegistryEntry currentEntry : dbsOnServerWithThisType) { checkBoxesTabForCurrentType.add(checkBoxMap.get(currentEntry)); } addTab( currentDbType.toString(), new DatabaseListPanel(checkBoxesTabForCurrentType, myOneAndOnlyButtonGroup) ); } addChangeListener(new TabChangeListener()); } public DatabaseRegistryEntry[] getSelectedDatabases() { List result = new ArrayList(); // get all the selected databases for each tab in turn for (int i = 0; i < getTabCount(); i++) { DatabaseListPanel dblp = (DatabaseListPanel) getComponentAt(i); DatabaseRegistryEntry[] panelSelected = dblp.getSelected(); for (int j = 0; j < panelSelected.length; j++) { result.add(panelSelected[j]); } } return (DatabaseRegistryEntry[]) result.toArray(new DatabaseRegistryEntry[result.size()]); } // getSelectedDatabases } // DatabaseTabbedPane /** * A JCheckBox that stores a reference to a DatabaseRegistryEntry. */ class DatabaseRadioButton extends JRadioButton { private DatabaseRegistryEntry database; public DatabaseRadioButton(DatabaseRegistryEntry database, boolean selected) { super(database.getName(), selected); this.database = database; //this.addChangeListener(l); //setBackground(Color.WHITE); } public DatabaseRegistryEntry getDatabase() { return database; } public void setDatabase(DatabaseRegistryEntry database) { this.database = database; } } /** * A class that creates a panel (in a JScrollPane) containing a list of DatabseCheckBoxes, and * provides methods for accessing the selected ones. */ class DatabaseListPanel extends JScrollPane { private List<JRadioButton> dbSelectionRadioButtons; private final ButtonGroup buttonGroup; /** * * <p> * This constructor allows the user to set a ButtonGroup explicitly. That * way the same ButtonGroup can be used * </p> * * @param dbSelectionRadioButtons * @param buttonGroup * */ public DatabaseListPanel(List<JRadioButton> dbSelectionRadioButtons, ButtonGroup buttonGroup) { this.dbSelectionRadioButtons = dbSelectionRadioButtons; this.buttonGroup = buttonGroup; JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); JPanel allDatabasesPanel = new JPanel(); allDatabasesPanel.setLayout(new BoxLayout(allDatabasesPanel, BoxLayout.Y_AXIS)); Iterator<JRadioButton> it = dbSelectionRadioButtons.iterator(); while (it.hasNext()) { JPanel radioButtonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0)); JRadioButton currentDatabaseRadioButton = it.next(); radioButtonPanel.add(currentDatabaseRadioButton); buttonGroup .add(currentDatabaseRadioButton); allDatabasesPanel.add(radioButtonPanel); } final DatabaseListPanel localDBLP = this; panel.add(allDatabasesPanel, BorderLayout.CENTER); setViewportView(panel); } /** * <p> * Default Constructor. * </p> * * @param dbSelectionRadioButtons * */ public DatabaseListPanel(List<JRadioButton> dbSelectionRadioButtons) { this(dbSelectionRadioButtons, new ButtonGroup()); } /** * Get the databases that are selected on this panel. * * @return the selected databases. */ public DatabaseRegistryEntry[] getSelected() { List selected = new ArrayList(); Iterator it = dbSelectionRadioButtons.iterator(); while (it.hasNext()) { DatabaseRadioButton dbcb = (DatabaseRadioButton) it.next(); if (dbcb.isSelected()) { selected.add(dbcb.getDatabase()); } } return (DatabaseRegistryEntry[]) selected.toArray(new DatabaseRegistryEntry[selected.size()]); } } /** * <p> * Fiddle things so that generic database types are moved to the front. * </p> */ class DatabaseTypeGUIComparator implements Comparator { public int compare(Object o1, Object o2) { if (!(o1 instanceof DatabaseType) || !(o2 instanceof DatabaseType)) { throw new RuntimeException("Arguments to DatabaseTypeGUIComparator must be DatabaseType!"); } DatabaseType t1 = (DatabaseType) o1; DatabaseType t2 = (DatabaseType) o2; if (t1.isGeneric() && !t2.isGeneric()) { return -1; } else if (!t1.isGeneric() && t2.isGeneric()) { return 1; } else { return t1.toString().compareTo(t2.toString()); } } } /** * Highlight the currently-selected tab of a JTabbedPane. */ class TabChangeListener implements ChangeListener { public void stateChanged(ChangeEvent e) {} }
package com.sixtyfour.compression; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Locale; import com.sixtyfour.Assembler; import com.sixtyfour.Loader; import com.sixtyfour.cbmnative.shell.FileData; import com.sixtyfour.config.CompilerConfig; import com.sixtyfour.system.FileWriter; import com.sixtyfour.system.Program; import com.sixtyfour.system.ProgramPart; /** * A simple compressor that can compress and uncompress byte[]-arrays based on a * simple and most likely inefficient sliding window pattern matching algorithm * that I came up with while being half asleep. It uses a pattern based * approach, no huffman encoding. That's why it's less efficient but should * decompress rather quickly. It can also compress a compiled C64 program, link * the decompressor to it and return the executable result. * * @author EgonOlsen * */ public class Compressor { private static final boolean FAST = true; private static final int MAX_WINDOW_SIZE_1 = 32; private static final int MAX_WINDOW_SIZE_2 = 128; private static final int MIN_WINDOW_SIZE = 12; private static final int CHUNK_SIZE = 32768; public static void main(String[] args) throws Exception { testCompressor("E:\\src\\workspace2018\\Adventure\\build\\++xam.prg", "C:\\Users\\EgonOlsen\\Desktop\\++xam_c.prg", -1); testCompressor("E:\\src\\workspace2018\\Adventure\\build\\++brotquest.prg", "C:\\Users\\EgonOlsen\\Desktop\\++brotquest_c.prg", -1); testCompressor("E:\\src\\workspace2018\\basicv2\\compiled\\++affine.prg", "C:\\Users\\EgonOlsen\\Desktop\\++affine_c.prg", -1); testCompressor("E:\\src\\workspace2018\\basicv2\\compiled\\+xtris2.prg", "C:\\Users\\EgonOlsen\\Desktop\\++xtris2_c.prg", -1); testCompressor("E:\\src\\workspace2018\\basicv2\\compiled\\+19 - StarDuel.prg", "C:\\Users\\EgonOlsen\\Desktop\\++StarDuel_c.prg", -1); testCompressor("E:\\src\\workspace2018\\basicv2\\compiled\\+30 - Invaders_15000.prg", "C:\\Users\\EgonOlsen\\Desktop\\++Invaders_c.prg", 15000); } private static void testCompressor(String fileName, String resultFile, int startAddr) throws Exception { byte[] bytes = loadProgram(fileName); Program prg = compressAndLinkNative(bytes, startAddr); if (prg != null) { FileWriter.writeAsPrg(prg, resultFile, false); } } /** * Compresses a given byte array and returns the comressed array or null, if no * compression has been performed. * * @param dump the byte array to compress * @param windowSize the size of the sliding window * @param watchSize if true, no compression will be performed if the result * will actually increase in size * @return the compressed array or null */ public static byte[] compress(byte[] dump, int windowSize, boolean watchSize) { long time = System.currentTimeMillis(); int minSize = MIN_WINDOW_SIZE; int len = dump.length; if (len > 65536) { throw new RuntimeException("This compressor can't compress anything larger than 64KB!"); } byte[] window = new byte[windowSize]; fillWindow(dump, window, 0); List<Part> parts = findMatches(dump, windowSize, minSize, len, window, FAST); byte[] bos = compress(parts, dump); if (bos.length >= len && watchSize) { log("No further compression possible!"); return null; } log("Binary compressed from " + len + " to " + bos.length + " bytes in " + (System.currentTimeMillis() - time) + "ms"); DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.ENGLISH); DecimalFormat decFor = new DecimalFormat("###.##", symbols); log("Bytes saved: " + (len - bos.length)); log("Compression ratio: 1:" + decFor.format(((float) len / bos.length))); return bos; } /** * Decompresses the compressed data * * @param bytes * @return */ public static byte[] decompress(byte[] bytes) { long time = System.currentTimeMillis(); int clen = bytes.length; int data = readLowHigh(bytes, 0); int compLen = readLowHigh(bytes, 2); int ucLen = readLowHigh(bytes, 4); int headerOffset = 6; int dataPos = headerOffset; byte[] res = new byte[65536]; int pos = 0; for (int i = data; i < clen;) { int start = readLowHigh(bytes, i); int target = 0; i += 2; do { int len = bytes[i] & 0xFF; i++; target = 0; if (len != 0) { target = readLowHigh(bytes, i); int copyLen = target - pos; if (copyLen > 0) { System.arraycopy(bytes, dataPos, res, pos, copyLen); dataPos += copyLen; pos = target; } System.arraycopy(res, start, res, target, len); pos += len; i += 2; } else { i++; } } while (target > 0); } if (dataPos < data) { int len = data - dataPos; System.arraycopy(bytes, dataPos, res, pos, len); pos += len; } if (pos != ucLen) { throw new RuntimeException("Failed to decompress, size mismatch: " + pos + "/" + ucLen); } log("Decompressed from " + compLen + " to " + ucLen + " bytes in " + (System.currentTimeMillis() - time) + "ms!"); return Arrays.copyOf(res, pos); } /** * Decompresses the compressed data but unlike decompress(), it does that in one * block of 64K memory just like the real machine would have to do it. * * @param bytes the compressed data * @return the uncompressed data */ public static byte[] decompressInMemory(byte[] bytes) { long time = System.currentTimeMillis(); int data = readLowHigh(bytes, 0); int compLen = readLowHigh(bytes, 2); int ucLen = readLowHigh(bytes, 4); int memStart = 2049; int memEnd = 65535; int headerOffset = 6; int byteCount = 0; int totalLen = compLen - headerOffset; try { byte[] res = new byte[65536]; // Copy into memory just like it would be located on a real machine... System.arraycopy(bytes, headerOffset, res, memStart, totalLen); // Copy compressed data to the end of memory... int dataPos = memEnd - totalLen; data -= headerOffset; int compPos = dataPos + data; System.arraycopy(res, memStart, res, dataPos, totalLen); int pos = memStart; for (int i = compPos; i < memEnd;) { int start = readLowHigh(res, i) + memStart; int target = 0; i += 2; do { int len = res[i] & 0xFF; i++; target = 0; if (len != 0) { target = readLowHigh(res, i) + memStart; int copyLen = target - pos; if (copyLen != 0) { // Copy uncompressed data back down into memory... byteCount += moveData(res, dataPos, pos, copyLen); dataPos += copyLen; pos = target; } byteCount += moveData(res, start, target, len); pos += len; i += 2; } else { i++; } } while (target != 0); } int left = compPos - dataPos; if (left > 0) { byteCount += moveData(res, dataPos, pos, left); pos += left; } int newLen = pos - memStart; if (newLen != ucLen) { return null; } log("Decompressed from " + compLen + " to " + ucLen + " bytes in " + (System.currentTimeMillis() - time) + "ms! (" + byteCount + " bytes moved)"); return Arrays.copyOfRange(res, memStart, memStart + ucLen); } catch (ArrayIndexOutOfBoundsException e) { return null; } } /** * Compress a compiled program and link the decompressor onto it. * * @param bytes the program * @param startAddr the start address of the program. If given, the decompressed * program will be copied to that memory address and started * directly. If not given, the program will reside on the start * of BASIC memory and started with RUN. * @return the executable, compressed program or null, if no compression was * possible */ public static Program compressAndLinkNative(byte[] bytes, int startAddr) { log("Trying to find best compression settings..."); byte[] compressedBytes = compress(bytes, MAX_WINDOW_SIZE_1, startAddr == -1); byte[] compressedBytes2 = compress(bytes, MAX_WINDOW_SIZE_2, startAddr == -1); if (compressedBytes == null) { compressedBytes = compressedBytes2; } else if (compressedBytes2 == null) { compressedBytes2 = compressedBytes; } if (compressedBytes == null) { return null; } if (compressedBytes2.length < compressedBytes.length) { compressedBytes = compressedBytes2; log("Setting 2 used!"); } else { log("Setting 1 used!"); } byte[] uncompressed = decompressInMemory(compressedBytes); if (uncompressed == null || !Arrays.equals(uncompressed, bytes)) { log("Uncompressed data and data table overlap, no compression performed!"); return null; } Program prg = compileHeader(startAddr); ProgramPart first = prg.getParts().get(0); ProgramPart pp = new ProgramPart(); pp.setBytes(convert(compressedBytes)); pp.setAddress(first.getEndAddress()); pp.setEndAddress(pp.getAddress() + pp.getBytes().length); prg.addPart(pp); int size = pp.getEndAddress() - first.getAddress(); if (size >= bytes.length) { log("No further compression possible!"); if (startAddr == -1) { return null; } } return prg; } /** * Loads a file into a byte array. * * @param fileName * @return the file in a byte array */ public static byte[] loadProgram(String fileName) { return loadProgramData(fileName).getData(); } /** * Loads a file into a byte array. * * @param fileName * @return the file's data */ public static FileData loadProgramData(String fileName) { log("Loading " + fileName); byte[] bytes = Loader.loadBlob(fileName); FileData fd = new FileData(); fd.setData(Arrays.copyOfRange(bytes, 2, bytes.length)); fd.setAddress((bytes[0] & 0xff) + (bytes[1] & 0xff) << 8); return fd; } private static Program compileHeader(int startAddr) { log("Assembling decompressor..."); String[] decrunchCode = Loader.loadProgram(Compressor.class.getResourceAsStream("/compressor/decruncher.asm")); if (startAddr > 0) { // set SYSADDR flag/value if needed. Otherwise, the decruncher will just call // RUN List<String> code = new ArrayList<>(Arrays.asList(decrunchCode)); code.add(1, "SYSADDR=" + startAddr); decrunchCode = code.toArray(new String[code.size()]); } Assembler assy = new Assembler(decrunchCode); assy.compile(new CompilerConfig()); ProgramPart prg = assy.getProgram().getParts().get(0); log("Assembling decompression header..."); String[] headerCode = Loader.loadProgram(Compressor.class.getResourceAsStream("/compressor/header.asm")); List<String> code = new ArrayList<>(Arrays.asList(headerCode)); List<String> res = new ArrayList<>(); for (int i = 0; i < code.size(); i++) { String line = code.get(i); if (line.contains("{code}")) { int[] bytes = prg.getBytes(); int cnt = 0; String nl = ".byte"; for (int p = 0; p < bytes.length; p++) { nl += " $" + Integer.toHexString(bytes[p] & 0xff); cnt++; if (cnt == 16) { res.add(nl); nl = ".byte"; cnt = 0; } } if (nl.length() > 5) { res.add(nl); } } else { res.add(line); } } // res.forEach(p -> System.out.println(p)); assy = new Assembler(res.toArray(new String[res.size()])); assy.compile(new CompilerConfig()); return assy.getProgram(); } private static int moveData(byte[] res, int dataPos, int pos, int dataLen) { System.arraycopy(res, dataPos, res, pos, dataLen); return dataLen; } private static byte[] compress(List<Part> parts, byte[] dump) { ByteArrayOutputStream footer = new ByteArrayOutputStream(); ByteArrayOutputStream data = new ByteArrayOutputStream(); int pos = 0; int lastStart = -1; for (Part part : parts) { int start = part.sourceAddress; int target = part.targetAddress; if (target > pos) { data.write(dump, pos, target - pos); pos = target; } pos += part.size; if (start != lastStart) { if (lastStart != -1) { writeEndFlag(footer); } writeLowHigh(footer, start); } lastStart = start; footer.write(part.size); writeLowHigh(footer, part.targetAddress); } data.write(dump, pos, dump.length - pos); writeEndFlag(footer); ByteArrayOutputStream res = new ByteArrayOutputStream(); int dataLen = data.size() + 6; writeLowHigh(res, dataLen); writeLowHigh(res, dataLen + footer.size()); writeLowHigh(res, dump.length); try { res.write(data.toByteArray()); res.write(footer.toByteArray()); } catch (IOException e) { } return res.toByteArray(); } private static void writeEndFlag(ByteArrayOutputStream header) { header.write(0); header.write(0); } private static int readLowHigh(byte[] bytes, int pos) { return (bytes[pos] & 0xFF) + ((bytes[pos + 1] & 0xFF) << 8); } private static void writeLowHigh(ByteArrayOutputStream header, int start) { header.write((start & 0xFF)); header.write((start >> 8)); } /** * This is O(n*n) and therefore quite inefficient...anyway, it will do for * now... * * @param dump * @param windowSize * @param minSize * @param len * @param windowPos * @param window * @param fastMode Less compression, but a lot faster. * @return */ private static List<Part> findMatches(byte[] dump, int windowSize, int minSize, int len, byte[] window, boolean fastMode) { int curSize = windowSize; int largest = 0; int windowPos = 0; List<Part> parts = new ArrayList<>(); byte[] covered = new byte[len]; int chunkSize = CHUNK_SIZE; for (int lenPart = Math.min(len, chunkSize); lenPart <= len;) { do { for (int i = windowPos + curSize; i < lenPart - curSize; i++) { if (covered[i] > 0) { continue; } boolean match = true; for (int p = 0; p < curSize; p++) { if (covered[i + p] != 0) { match = false; break; } if (dump[i + p] != window[p]) { match = false; if (p > largest) { largest = p; } break; } } if (match) { for (int h = i; h < i + curSize; h++) { covered[h] = 1; } Part part = new Part(windowPos, i, curSize); parts.add(part); i += curSize - 1; } } if (largest >= minSize) { curSize = largest; largest = 0; } else { if (fastMode) { windowPos += Math.max(largest >> 1, 1); if (windowPos + windowSize >= lenPart) { windowPos -= (windowPos + windowSize - lenPart); } } else { windowPos++; } curSize = windowSize; largest = 0; fillWindow(dump, window, windowPos); } } while (windowPos + curSize < lenPart); windowPos = lenPart - curSize; if (lenPart < len && lenPart + chunkSize > len) { lenPart = len; } else { lenPart += chunkSize; } } Collections.sort(parts, new Comparator<Part>() { @Override public int compare(Part p1, Part p2) { return p1.targetAddress - p2.targetAddress; } }); // parts.forEach(p -> System.out.println(p)); // log("Iterations taken: " + cnt); return parts; } private static void fillWindow(byte[] dump, byte[] window, int pos) { System.arraycopy(dump, pos, window, 0, window.length); } private static void log(String txt) { System.out.println(txt); } private static int[] convert(byte[] bytes) { int[] res = new int[bytes.length]; for (int i = 0; i < bytes.length; i++) { res[i] = bytes[i] & 0xff; } return res; } private static class Part { Part(int source, int target, int size) { this.sourceAddress = source; this.targetAddress = target; this.size = size; } int sourceAddress; int targetAddress; int size; @Override public String toString() { return "block@ " + sourceAddress + "/" + targetAddress + "/" + size; } } }
package com.sdm.core.util.mail; import com.sdm.core.Setting; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.ws.rs.core.Response; import org.apache.log4j.Logger; /** * * @author Htoonlin */ public class WebMailService implements IBaseMailService { private static final Logger LOG = Logger.getLogger(WebMailService.class.getName()); private static WebMailService instance; private final String MAIL_SOCKET_FACTORY = "javax.net.ssl.SSLSocketFactory"; private Session mailSession; public WebMailService() throws IOException { Properties settingProps = new Properties(); settingProps.put("mail.smtp.host", Setting.getInstance().MAIL_HOST); settingProps.put("mail.smtp.socketFactory.port", Setting.getInstance().MAIL_PORT); settingProps.put("mail.smtp.socketFactory.class", MAIL_SOCKET_FACTORY); settingProps.put("mail.smtp.auth", Setting.getInstance().MAIL_NEED_AUTH); settingProps.put("mail.smtp.port", Setting.getInstance().MAIL_PORT); mailSession = Session.getDefaultInstance(settingProps, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(Setting.getInstance().MAIL_USER, Setting.getInstance().MAIL_PASSWORD); } }); } public static synchronized WebMailService getInstance() { if (instance == null) { try { instance = new WebMailService(); } catch (IOException e) { LOG.error(e); } } return instance; } private Message buildMessage(MailInfo mailInfo) throws MessagingException { try { Message message = new MimeMessage(mailSession); message.setHeader("X-Priority", "1"); if (mailInfo.getFrom() == null || mailInfo.getFrom().isEmpty()) { mailInfo.setFrom(Setting.getInstance().MAIL_USER); } message.setFrom(new InternetAddress(mailInfo.getFrom())); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mailInfo.getTo())); if (mailInfo.getCc() != null) { message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(mailInfo.getCc())); } if (mailInfo.getBcc() != null) { message.addRecipients(Message.RecipientType.BCC, InternetAddress.parse(mailInfo.getBcc())); } message.setSubject(mailInfo.getSubject()); return message; } catch (MessagingException ex) { LOG.error(ex); throw ex; } } @Override public Response sendAttachments(MailInfo mailInfo, List<File> attachments) { Response response = Response.ok().build(); try { Message message = buildMessage(mailInfo); MimeBodyPart textBody = new MimeBodyPart(); textBody.setContent(mailInfo.getBody(), "text/html; charset=utf-8"); Multipart bodyPart = new MimeMultipart(); bodyPart.addBodyPart(textBody); for (File attachment : attachments) { MimeBodyPart attachmentBody = new MimeBodyPart(); DataSource dataSource = new FileDataSource(attachment); attachmentBody.setDataHandler(new DataHandler(dataSource)); attachmentBody.setFileName(attachment.getName()); bodyPart.addBodyPart(attachmentBody); } message.setContent(bodyPart); Transport.send(message); } catch (MessagingException ex) { response = Response.serverError().build(); LOG.error(ex); } return response; } @Override public Response sendAttachment(MailInfo mailInfo, File attachment) { List<File> files = new ArrayList<>(); return this.sendAttachments(mailInfo, files); } @Override public Response sendHTML(MailInfo mailInfo) throws Exception { Response response = Response.ok().build(); try { Message message = buildMessage(mailInfo); message.setContent(mailInfo.getBody(), "text/html; charset=utf-8"); Transport.send(message); } catch (MessagingException ex) { response = Response.serverError().build(); throw ex; } return response; } @Override public Response sendRaw(MailInfo mailInfo) throws Exception { Response response = Response.ok().build(); try { Message message = buildMessage(mailInfo); message.setText(mailInfo.getBody()); Transport.send(message); } catch (MessagingException ex) { response = Response.serverError().build(); throw ex; } return response; } }
/* * @author <a href="mailto:novotny@aei.mpg.de">Jason Novotny</a> * @version $Id$ */ package org.gridlab.gridsphere.servlets; import org.gridlab.gridsphere.core.persistence.PersistenceManagerFactory; import org.gridlab.gridsphere.core.persistence.hibernate.DBTask; import org.gridlab.gridsphere.layout.PortletLayoutEngine; import org.gridlab.gridsphere.portlet.*; import org.gridlab.gridsphere.portlet.impl.*; import org.gridlab.gridsphere.portlet.service.PortletServiceException; import org.gridlab.gridsphere.portlet.service.spi.impl.SportletServiceFactory; import org.gridlab.gridsphere.portletcontainer.impl.GridSphereEventImpl; import org.gridlab.gridsphere.portletcontainer.impl.SportletMessageManager; import org.gridlab.gridsphere.portletcontainer.*; import org.gridlab.gridsphere.services.core.registry.PortletManagerService; import org.gridlab.gridsphere.services.core.security.acl.AccessControlManagerService; import org.gridlab.gridsphere.services.core.security.auth.AuthorizationException; import org.gridlab.gridsphere.services.core.security.auth.AuthenticationException; import org.gridlab.gridsphere.services.core.user.LoginService; import org.gridlab.gridsphere.services.core.user.UserManagerService; import org.gridlab.gridsphere.services.core.user.UserSessionManager; import org.gridlab.gridsphere.services.core.request.RequestService; import org.gridlab.gridsphere.services.core.request.GenericRequest; import org.gridlab.gridsphere.services.core.tracker.TrackerService; import org.gridlab.gridsphere.services.core.tracker.impl.TrackerServiceImpl; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.servlet.*; import javax.servlet.http.*; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.*; import java.net.SocketException; /** * The <code>GridSphereServlet</code> is the GridSphere portlet container. * All portlet requests get proccessed by the GridSphereServlet before they * are rendered. */ public class GridSphereServlet extends HttpServlet implements ServletContextListener, HttpSessionAttributeListener, HttpSessionListener, HttpSessionActivationListener { /* GridSphere logger */ private static PortletLog log = SportletLog.getInstance(GridSphereServlet.class); /* GridSphere service factory */ private static SportletServiceFactory factory = null; /* GridSphere Portlet Registry Service */ private static PortletManagerService portletManager = null; /* GridSphere Access Control Service */ private static AccessControlManagerService aclService = null; private static UserManagerService userManagerService = null; private static LoginService loginService = null; private static TrackerService trackerService = null; private PortletMessageManager messageManager = SportletMessageManager.getInstance(); /* GridSphere Portlet layout Engine handles rendering */ private static PortletLayoutEngine layoutEngine = null; /* Session manager maps users to sessions */ private UserSessionManager userSessionManager = UserSessionManager.getInstance(); /* creates cookie requests */ private RequestService requestService = null; private PortletContext context = null; private static Boolean firstDoGet = Boolean.TRUE; private static PortletSessionManager sessionManager = PortletSessionManager.getInstance(); //private static PortletRegistry registry = PortletRegistry.getInstance(); private static final String COOKIE_REQUEST = "cookie-request"; private int COOKIE_EXPIRATION_TIME = 60 * 60 * 24 * 7; // 1 week (in secs) private PortletGroup coreGroup = null; private boolean isTCK = false; /** * Initializes the GridSphere portlet container * * @param config the <code>ServletConfig</code> * @throws ServletException if an error occurs during initialization */ public final void init(ServletConfig config) throws ServletException { super.init(config); GridSphereConfig.setServletConfig(config); //SportletLog.setConfigureURL(GridSphereConfig.getServletContext().getRealPath("/WEB-INF/classes/log4j.properties")); this.context = new SportletContext(config); factory = SportletServiceFactory.getInstance(); factory.init(); layoutEngine = PortletLayoutEngine.getInstance(); log.debug("in init of GridSphereServlet"); } public synchronized void initializeServices() throws PortletServiceException { requestService = (RequestService) factory.createPortletService(RequestService.class, getServletConfig().getServletContext(), true); log.debug("Creating access control manager service"); aclService = (AccessControlManagerService) factory.createPortletService(AccessControlManagerService.class, getServletConfig().getServletContext(), true); // create root user in default group if necessary log.debug("Creating user manager service"); userManagerService = (UserManagerService) factory.createPortletService(UserManagerService.class, getServletConfig().getServletContext(), true); loginService = (LoginService) factory.createPortletService(LoginService.class, getServletConfig().getServletContext(), true); log.debug("Creating portlet manager service"); portletManager = (PortletManagerService) factory.createPortletService(PortletManagerService.class, getServletConfig().getServletContext(), true); trackerService = (TrackerService) factory.createPortletService(TrackerService.class, getServletConfig().getServletContext(), true); } /** * Processes GridSphere portal framework requests * * @param req the <code>HttpServletRequest</code> * @param res the <code>HttpServletResponse</code> * @throws IOException if an I/O error occurs * @throws ServletException if a servlet error occurs */ public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { processRequest(req, res); } public void setHeaders(HttpServletResponse res) { res.setContentType("text/html; charset=utf-8"); // Necessary to display UTF-8 encoded characters res.setHeader("Cache-Control","no-cache"); //Forces caches to obtain a new copy of the page from the origin server res.setHeader("Cache-Control","no-store"); //Directs caches not to store the page under any circumstance res.setDateHeader("Expires", 0); //Causes the proxy cache to see the page as "stale" res.setHeader("Pragma","no-cache"); //HTTP 1.0 backward compatibility } public void processRequest(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { setHeaders(res); GridSphereEvent event = new GridSphereEventImpl(context, req, res); PortletRequest portletReq = event.getPortletRequest(); // If first time being called, instantiate all portlets if (firstDoGet.equals(Boolean.TRUE)) { synchronized (firstDoGet) { firstDoGet = Boolean.FALSE; log.debug("Testing Database"); // checking if database setup is correct DBTask dt = new DBTask(); dt.setAction(DBTask.ACTION_CHECKDB); dt.setConfigDir(GridSphereConfig.getServletContext().getRealPath("")); try { dt.execute(); } catch (Exception e) { RequestDispatcher rd = req.getRequestDispatcher("/jsp/errors/database_error.jsp"); log.error("Check DB failed: ", e); req.setAttribute("error", "DB Error! Please contact your GridSphere/Database Administrator!"); rd.forward(req, res); return; } log.debug("Initializing portlets and services"); try { // initialize needed services initializeServices(); // create a root user if none available userManagerService.initRootUser(); // initialize all portlets PortletResponse portletRes = event.getPortletResponse(); PortletInvoker.initAllPortlets(portletReq, portletRes); // deep inside a service is used which is why this must follow the factory.init layoutEngine.init(); } catch (Exception e) { log.error("GridSphere initialization failed!", e); RequestDispatcher rd = req.getRequestDispatcher("/jsp/errors/init_error.jsp"); req.setAttribute("error", e); rd.forward(req, res); return; } coreGroup = aclService.getCoreGroup(); } } setUserAndGroups(portletReq); String trackme = req.getParameter(TrackerService.TRACK_PARAM); if (trackme != null) { trackerService.trackURL(trackme, req.getHeader("user-agent"), portletReq.getUser().getUserName()); String url = req.getParameter(TrackerService.REDIRECT_URL); if (url != null) { System.err.println("redirect: " + url); res.sendRedirect(url); } } checkUserHasCookie(event); // Used for TCK tests if (isTCK) setTCKUser(portletReq); // Handle user login and logout if (event.hasAction()) { if (event.getAction().getName().equals(SportletProperties.LOGIN)) { login(event); //event = new GridSphereEventImpl(aclService, context, req, res); } if (event.getAction().getName().equals(SportletProperties.LOGOUT)) { logout(event); // since event is now invalidated, must create new one event = new GridSphereEventImpl(context, req, res); } } layoutEngine.actionPerformed(event); // is this a file download operation? downloadFile(event); // Handle any outstanding messages // This needs work certainly!!! Map portletMessageLists = messageManager.retrieveAllMessages(); if (!portletMessageLists.isEmpty()) { Set keys = portletMessageLists.keySet(); Iterator it = keys.iterator(); String concPortletID = null; List messages = null; while (it.hasNext()) { concPortletID = (String) it.next(); messages = (List) portletMessageLists.get(concPortletID); Iterator newit = messages.iterator(); while (newit.hasNext()) { PortletMessage msg = (PortletMessage) newit.next(); layoutEngine.messageEvent(concPortletID, msg, event); } } messageManager.removeAllMessages(); } setUserAndGroups(portletReq); // Used for TCK tests if (isTCK) setTCKUser(portletReq); layoutEngine.service(event); //log.debug("Session stats"); //userSessionManager.dumpSessions(); //log.debug("Portlet service factory stats"); //factory.logStatistics(); /* log.debug("Portlet page factory stats"); try { PortletPageFactory pageFactory = PortletPageFactory.getInstance(); pageFactory.logStatistics(); } catch (Exception e) { log.error("Unable to get page factory", e); } */ } public void setTCKUser(PortletRequest req) { //String tck = (String)req.getPortletSession(true).getAttribute("tck"); String[] portletNames = req.getParameterValues("portletName"); if ((isTCK) || (portletNames != null)) { log.info("Setting a TCK user"); SportletUserImpl u = new SportletUserImpl(); u.setUserName("tckuser"); u.setUserID("tckuser"); u.setID("500"); Map l = new HashMap(); l.put(coreGroup, PortletRole.USER); req.setAttribute(SportletProperties.PORTLET_USER, u); req.setAttribute(SportletProperties.PORTLETGROUPS, l); req.setAttribute(SportletProperties.PORTLET_ROLE, PortletRole.USER); isTCK = true; } } public void setUserAndGroups(PortletRequest req) { // Retrieve user if there is one User user = null; if (req.getPortletSession() != null) { String uid = (String) req.getPortletSession().getAttribute(SportletProperties.PORTLET_USER); if (uid != null) { user = userManagerService.getUser(uid); } } HashMap groups = new HashMap(); PortletRole role = PortletRole.GUEST; if (user == null) { user = GuestUser.getInstance(); groups = new HashMap(); groups.put(coreGroup, PortletRole.GUEST); } else { List mygroups = aclService.getGroups(user); Iterator it = mygroups.iterator(); while (it.hasNext()) { PortletGroup g = (PortletGroup) it.next(); role = aclService.getRoleInGroup(user, g); groups.put(g, role); } } // req.getPortletRole returns the role user has in core gridsphere group role = aclService.getRoleInGroup(user, coreGroup); // set user, role and groups in request req.setAttribute(SportletProperties.PORTLET_GROUP, coreGroup); req.setAttribute(SportletProperties.PORTLET_USER, user); req.setAttribute(SportletProperties.PORTLETGROUPS, groups); req.setAttribute(SportletProperties.PORTLET_ROLE, role); } protected void checkUserHasCookie(GridSphereEvent event) { PortletRequest req = event.getPortletRequest(); User user = req.getUser(); if (user instanceof GuestUser) { Cookie[] cookies = req.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { Cookie c = cookies[i]; System.err.println("found a cookie:"); System.err.println("name=" + c.getName()); System.err.println("value=" + c.getValue()); if (c.getName().equals("gsuid")) { String cookieVal = c.getValue(); int hashidx = cookieVal.indexOf(" if (hashidx > 0) { String uid = cookieVal.substring(0, hashidx); System.err.println("uid = " + uid); String reqid = cookieVal.substring(hashidx+1); System.err.println("reqid = " + reqid); GenericRequest genreq = requestService.getRequest(reqid, COOKIE_REQUEST); if (genreq != null) { if (genreq.getUserID().equals(uid)) { User newuser = userManagerService.getUser(uid); if (newuser != null) { setUserSettings(event, newuser); } } } } } } } } } protected void setUserCookie(GridSphereEvent event) { PortletRequest req = event.getPortletRequest(); PortletResponse res = event.getPortletResponse(); User user = req.getUser(); GenericRequest request = requestService.createRequest(COOKIE_REQUEST); Cookie cookie = new Cookie("gsuid", user.getID() + "#" + request.getOid()); request.setUserID(user.getID()); long time = Calendar.getInstance().getTime().getTime() + COOKIE_EXPIRATION_TIME * 1000; request.setLifetime(new Date(time)); requestService.saveRequest(request); // COOKIE_EXPIRATION_TIME is specified in secs cookie.setMaxAge(COOKIE_EXPIRATION_TIME); res.addCookie(cookie); System.err.println("adding a cookie"); } protected void removeUserCookie(GridSphereEvent event) { PortletRequest req = event.getPortletRequest(); PortletResponse res = event.getPortletResponse(); Cookie[] cookies = req.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { Cookie c = cookies[i]; if (c.getName().equals("gsuid")) { int idx = c.getValue().indexOf(" if (idx > 0) { String reqid = c.getValue().substring(idx+1); System.err.println("reqid= " + reqid); GenericRequest request = requestService.getRequest(reqid, COOKIE_REQUEST); if (request != null) requestService.deleteRequest(request); } c.setMaxAge(0); res.addCookie(c); } } } } /** * Handles login requests * * @param event a <code>GridSphereEvent</code> */ protected void login(GridSphereEvent event) { log.debug("in login of GridSphere Servlet"); String LOGIN_ERROR_FLAG = "LOGIN_FAILED"; PortletRequest req = event.getPortletRequest(); try { User user = loginService.login(req); setUserSettings(event, user); String remme = req.getParameter("remlogin"); if (remme != null) { setUserCookie(event); } else { removeUserCookie(event); } } catch (AuthorizationException err) { log.debug(err.getMessage()); req.setAttribute(LOGIN_ERROR_FLAG, err.getMessage()); } catch (AuthenticationException err) { log.debug(err.getMessage()); req.setAttribute(LOGIN_ERROR_FLAG, err.getMessage()); } } public void setUserSettings(GridSphereEvent event, User user) { PortletRequest req = event.getPortletRequest(); PortletSession session = req.getPortletSession(true); req.setAttribute(SportletProperties.PORTLET_USER, user); session.setAttribute(SportletProperties.PORTLET_USER, user.getID()); if (user.getAttribute(User.LOCALE) != null) { session.setAttribute(User.LOCALE, new Locale((String)user.getAttribute(User.LOCALE), "", "")); } if (aclService.hasSuperRole(user)) { log.debug("User: " + user.getUserName() + " logged in as SUPER"); } setUserAndGroups(req); log.debug("Adding User: " + user.getID() + " with session:" + session.getId() + " to usersessionmanager"); userSessionManager.addSession(user, session); layoutEngine.loginPortlets(event); } /** * Handles logout requests * * @param event a <code>GridSphereEvent</code> */ protected void logout(GridSphereEvent event) { log.debug("in logout of GridSphere Servlet"); PortletRequest req = event.getPortletRequest(); removeUserCookie(event); PortletSession session = req.getPortletSession(); session.removeAttribute(SportletProperties.PORTLET_USER); userSessionManager.removeSessions(req.getUser()); layoutEngine.logoutPortlets(event); } /** * Method to set the response headers to perform file downloads to a browser * * @param event the gridsphere event * @throws PortletException */ public void downloadFile(GridSphereEvent event) throws PortletException { PortletResponse res = event.getPortletResponse(); PortletRequest req = event.getPortletRequest(); try { String fileName = (String) req.getAttribute(SportletProperties.FILE_DOWNLOAD_NAME); String path = (String) req.getAttribute(SportletProperties.FILE_DOWNLOAD_PATH); if ((fileName == null) || (path == null)) return; log.debug("in downloadFile"); log.debug("filename: " + fileName + " filepath= " + path); File f = new File(path); FileDataSource fds = new FileDataSource(f); res.setContentType(fds.getContentType()); res.setHeader("Content-Disposition", "attachment; filename=" + fileName); res.setHeader("Content-Length", String.valueOf(f.length())); DataHandler handler = new DataHandler(fds); handler.writeTo(res.getOutputStream()); } catch (FileNotFoundException e) { log.error("Unable to find file!", e); } catch (SecurityException e) { // this gets thrown if a security policy applies to the file. see java.io.File for details. log.error("A security exception occured!", e); } catch (SocketException e) { log.error("Caught SocketException: " + e.getMessage()); } catch (IOException e) { log.error("Caught IOException", e); //response.sendError(HttpServletResponse.SC_INTERNAL_SERVER,e.getMessage()); } } /** * @see #doGet */ public final void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { doGet(req, res); } /** * Return the servlet info. * * @return a string with the servlet information. */ public final String getServletInfo() { return "GridSphere Servlet 2.0.1"; } /** * Shuts down the GridSphere portlet container */ public final void destroy() { log.debug("in destroy: Shutting down services"); userSessionManager.destroy(); layoutEngine.destroy(); // Shutdown services factory.shutdownServices(); // shutdown the persistencemanagers PersistenceManagerFactory.shutdown(); System.gc(); } /** * Record the fact that a servlet context attribute was added. * * @param event The session attribute event */ public void attributeAdded(HttpSessionBindingEvent event) { log.debug("attributeAdded('" + event.getSession().getId() + "', '" + event.getName() + "', '" + event.getValue() + "')"); } /** * Record the fact that a servlet context attribute was removed. * * @param event The session attribute event */ public void attributeRemoved(HttpSessionBindingEvent event) { log.debug("attributeRemoved('" + event.getSession().getId() + "', '" + event.getName() + "', '" + event.getValue() + "')"); } /** * Record the fact that a servlet context attribute was replaced. * * @param event The session attribute event */ public void attributeReplaced(HttpSessionBindingEvent event) { log.debug("attributeReplaced('" + event.getSession().getId() + "', '" + event.getName() + "', '" + event.getValue() + "')"); } /** * Record the fact that this ui application has been destroyed. * * @param event The servlet context event */ public void contextDestroyed(ServletContextEvent event) { ServletContext ctx = event.getServletContext(); log.debug("contextDestroyed()"); log.debug("contextName: " + ctx.getServletContextName()); log.debug("context path: " + ctx.getRealPath("")); } /** * Record the fact that this ui application has been initialized. * * @param event The servlet context event */ public void contextInitialized(ServletContextEvent event) { System.err.println("contextInitialized()"); ServletContext ctx = event.getServletContext(); GridSphereConfig.setServletContext(ctx); log.debug("contextName: " + ctx.getServletContextName()); log.debug("context path: " + ctx.getRealPath("")); } /** * Record the fact that a session has been created. * * @param event The session event */ public void sessionCreated(HttpSessionEvent event) { log.debug("sessionCreated('" + event.getSession().getId() + "')"); sessionManager.sessionCreated(event); } /** * Record the fact that a session has been destroyed. * * @param event The session event */ public void sessionDestroyed(HttpSessionEvent event) { sessionManager.sessionDestroyed(event); log.debug("sessionDestroyed('" + event.getSession().getId() + "')"); } /** * Record the fact that a session has been created. * * @param event The session event */ public void sessionDidActivate(HttpSessionEvent event) { log.debug("sessionDidActivate('" + event.getSession().getId() + "')"); sessionManager.sessionCreated(event); } /** * Record the fact that a session has been destroyed. * * @param event The session event */ public void sessionWillPassivate(HttpSessionEvent event) { sessionManager.sessionDestroyed(event); log.debug("sessionWillPassivate('" + event.getSession().getId() + "')"); } }
package com.sportdataconnect.geometry; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * Representation of a point in 2D space. * * @author sportdataconnect */ public final class Point2D { private static final Logger LOG = LogManager.getLogger(Point2D.class); private final double x; private final double y; private final double length; public Point2D(final double x, final double y) { this.x = x; this.y = y; length = Math.sqrt( this.x * this.x + this.y * this.y); } public double getX() { return x; } public double getY() { return y; } /** * Returns the distance of the point from the origin. The vector length. * @return Returns the distance of the point from the origin */ public double getLength() { return length; } /** * Returns the sum of this point and the supplied rhs parameter. The vector sum. * @param rhs * @return Returns the sum of this point and the supplied rhs parameter. */ public Point2D add(final Point2D rhs) { return new Point2D(this.x + rhs.x, this.y + rhs.y); } /** * Returns this point after being scaled by the supplied value. Scalar multiplication. * @param scaleFactor * @return Returns this point after being scaled by the supplied value */ public Point2D scale(final double scaleFactor) { return new Point2D(this.x * scaleFactor, this.y * scaleFactor); } /** * Returns this point after being scaled such that it's length is one. The * unit vector with the same direction) * @return Returns this point after being scaled such that it's length is one. */ public Point2D normalize() { return this.scale(1.0 / length); } @Override public String toString() { return "Point3D{" + "x=" + x + ", y=" + y + "}"; } /** * Returns the result of subtracting the supplied point from this one. Vector * subtraction * @param rhs * @return Returns the result of subtracting the supplied point from this one */ public Point2D subtract(final Point2D rhs) { return new Point2D(this.x - rhs.x, this.y - rhs.y); } /** * Returns the cross product of this vector and the supplied vector * @param rhs * @return Returns the cross product of this vector and the supplied vector */ public double crossProduct(final Point2D rhs) { return this.x * rhs.y - this.y * rhs.x; } /** * Returns the direction that is perpendicular to this point * @return Returns the direction that is perpendicular to this point */ public Point2D crossDir() { Point3D pt3D = new Point3D(x, y, 0.0); Point3D crossDir3D = pt3D.crossProduct(Point3D.Z_AXIS_DIR).normalize(); return new Point2D(crossDir3D.getX(), crossDir3D.getY()); } /** * Returns the angle anti-clockwise angle between this vector and the X-axis * @return Returns the angle anti-clockwise angle between this vector and the X-axis */ public double polarAngle() { if (y < 0) { return 2 * Math.PI + Math.atan2(y, x); } else { return Math.atan2(y, x); } } /** * Returns the distance of this point from the specified point * @param point * @return Returns the distance of this point from the specified point */ public double distanceFrom(final Point2D point) { double dx = point.x - this.x; double dy = point.y - this.y; return Math.sqrt(dx * dx + dy * dy); } /** * Returns the average location of the points in the collection * @param pts * @return Returns the average location of the points in the collection */ public static Point2D findAverage(final Collection<Point2D> pts) { double sumX = 0; double sumY = 0; for (Point2D pt : pts) { sumX += pt.x; sumY += pt.y; } return new Point2D(sumX / pts.size(), sumY / pts.size()); } /** * Returns the smallest possible convex polygon that contains all of the supplied points. * The points are returned anti-clockwise. * @param points * @return Returns the smallest possible convex polygon that contains all of the supplied points */ public static List<Point2D> createConvexPolygon(final Collection<Point2D> points) { LOG.debug(">>"); Set<Point2D> remainingPoints = new HashSet<Point2D>(points); Point2D previousPoint = findBottomPoint(remainingPoints); Point2D firstPoint = previousPoint; LOG.debug("Adding point " + previousPoint); List<Point2D> resultPoints = new LinkedList<Point2D>(); resultPoints.add(previousPoint); Point2D nextPoint = findNextPoint(remainingPoints, previousPoint, 0); while (nextPoint != null && nextPoint != firstPoint) { LOG.debug("Adding point " + nextPoint); resultPoints.add(nextPoint); remainingPoints.remove(nextPoint); double angle = nextPoint.subtract(previousPoint).polarAngle(); previousPoint = nextPoint; LOG.debug("Current angle " + Math.toDegrees(angle)); nextPoint = findNextPoint(remainingPoints, nextPoint, angle); } LOG.debug("<<"); return resultPoints; } private static Point2D findBottomPoint(final Collection<Point2D> points) { if (points.size() < 0) { throw new IllegalArgumentException("Cannot find left most point from an empty set"); } Iterator<Point2D> iter = points.iterator(); Point2D lowest = iter.next(); while (iter.hasNext()) { Point2D candidate = iter.next(); if (lowest.getY() > candidate.getY()) { lowest = candidate; } } return lowest; } private static Point2D findNextPoint(final Collection<Point2D> points, final Point2D currentPoint, final double startingAngle) { //LOG.debug(">>findNextPoint"); Iterator<Point2D> iter = points.iterator(); Point2D closest = null; Double closestAngle = null; while (iter.hasNext()) { Point2D candidate = iter.next(); //LOG.debug("candiate angle = " + Math.toDegrees(candidate.subtract(currentPoint).polarAngle())); //LOG.debug("starting angle angle = " + Math.toDegrees(startingAngle)); double nextAngle = candidate.subtract(currentPoint).polarAngle() - startingAngle; if (nextAngle > 0.0) { if (closest == null) { closest = candidate; closestAngle = nextAngle; } else if (nextAngle < closestAngle) { closest = candidate; closestAngle = nextAngle; } } } if (closestAngle != null) { //LOG.debug("CLOSEST ANGLE FOUND = " + Math.toDegrees(closestAngle)); } //LOG.debug("<<findNextPoint"); return closest; } }
package com.bananity.controllers; // Bananity Classes import com.bananity.models.IndexModelBean; import com.bananity.text.TextNormalizer; import com.bananity.util.SearchTerm; import com.bananity.util.SearchTermFactory; import com.bananity.util.SortedLists; import com.bananity.util.StorageItemComparator; // Cache import com.google.common.cache.Cache; // Java utils import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.io.IOException; import java.io.PrintWriter; import javax.ejb.EJB; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * This webservlet allows to insert items into the index collections (and remove it) * * @author Andreu Correa Casablanca * @version 0.5 */ @WebServlet("/index") public class IndexController extends BaseController { /** * IndexModelBean reference */ @EJB private IndexModelBean imB; /** * Handles Post requests, and calls insert or remove methods * * @see javax.servlet.http.HttpServlet#doPost */ @Override public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Here we take care of possible excessive memory usage long freeMem = Runtime.getRuntime().freeMemory(); long usedMem = Runtime.getRuntime().totalMemory(); long maxMem = Runtime.getRuntime().maxMemory(); if ( ((double)(maxMem-usedMem+freeMem))/((double)maxMem) < 0.10 ) { cB.freeSpace(); } try { String method = request.getParameter("m"); String collName = request.getParameter("c"); String item = TextNormalizer.normalizeText(request.getParameter("item"), true); if (collName == null || collName.length() == 0 || item == null || item.length() == 0) { throw new Exception( "Invalid parameters" ); } if (method.equals("insert")) { insertLogic(collName, item); } else if (method.equals("remove")) { removeLogic(collName, item); } else { throw new Exception("Inexistent method : m="+method); } sendResponse(request, response, HttpServletResponse.SC_OK, 0, null); } catch (OutOfMemoryError oome) { cB.hardFreeSpace(); log.error("Out of Memory Error", oome); sendResponse(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 1, null); } catch (Exception e) { log.warn("BAD_REQUEST from "+request.getRemoteAddr()+", params: "+request.getQueryString()+", body: "+request.getReader().readLine(), e); sendResponse(request, response, HttpServletResponse.SC_BAD_REQUEST, 1, null); } } /** * Insert an item into the specifiec collection (and updates caches) * * @param collName Index collection name * @param item Item to be inserted in the collection */ private void insertLogic (String collName, String item) throws Exception { SearchTerm stItem = SearchTermFactory.get(item); imB.insert(collName, stItem); addToCache(collName, stItem); } /** * Removes an item from the specifiec collection (and updates caches) * * @param collName Index collection name * @param item Item to be inserted in the collection */ private void removeLogic (String collName, String item) throws Exception { // WARNING : There aren't locks SearchTerm stItem = SearchTermFactory.get(item); imB.remove(collName, stItem); removeFromCache(collName, stItem); } /** * Adds an item to the results cache tied to the specified collection * * @param collName Index collection name * @param item Item to be inserted in the collection */ private void addToCache (String collName, SearchTerm item) throws Exception { Cache<String, ArrayList<SearchTerm>> cache = cB.getResultCache(collName); if (cache == null) { throw new Exception("¡Cache not foud for collection \""+collName+"\"!"); } HashSet<String> expandedCacheKeyBase = item.getLcFlattenStrings().getUniqueByLength(2); for (String cacheKeyBaseItem : expandedCacheKeyBase) { addToCacheToken (cache, item, cacheKeyBaseItem, 5); addToCacheToken (cache, item, cacheKeyBaseItem, 10); addToCacheToken (cache, item, cacheKeyBaseItem, 15); addToCacheToken (cache, item, cacheKeyBaseItem, 20); } } /** * Removes an item from the results cache tied to the specified collection * * @param collName Index collection name * @param item Item to be removed from the collection */ private void removeFromCache (String collName, SearchTerm item) throws Exception { Cache<String, ArrayList<SearchTerm>> cache = cB.getResultCache(collName); if (cache == null) { throw new Exception("¡Cache not foud for collection \""+collName+"\"!"); } HashSet<String> expandedCacheKeyBase = item.getLcFlattenStrings().getUniqueByLength(2); for (String cacheKeyBaseItem : expandedCacheKeyBase) { removeCacheToken (cache, cacheKeyBaseItem, 5); removeCacheToken (cache, cacheKeyBaseItem, 10); removeCacheToken (cache, cacheKeyBaseItem, 15); removeCacheToken (cache, cacheKeyBaseItem, 20); } } /** * Adds an item to a results cache value (given with the key cacheKeyBaseItem@limit) * * @param cache cache to be updated * @param item item * @param cacheKeyBaseItem complete or partial searchTerm (as a part of cache key) * @param limit limit imposed to search result size (as a part of cache key) */ private void addToCacheToken (Cache<String, ArrayList<SearchTerm>> cache, SearchTerm item, String cacheKeyBaseItem, int limit) throws Exception { String cacheKey = new StringBuilder(cacheKeyBaseItem).append("@").append(limit).toString(); ArrayList<SearchTerm> cachedResult = cache.getIfPresent(cacheKey); if (cachedResult == null) return; SortedLists.sortedInsert(new StorageItemComparator(cacheKeyBaseItem), cachedResult, limit, item); } /** * Removes an item from the results cache tied to the specified collection (given a result length) * * @param cache cache to be updated * @param cacheKeyBaseItem complete or partial searchTem (as a part of cache key) * @param limit limit imposed to search result size (as a part of cache key) */ private void removeCacheToken (Cache<String, ArrayList<SearchTerm>> cache, String cacheKeyBaseItem, int limit) { String cacheKey = new StringBuilder(cacheKeyBaseItem).append("@").append(limit).toString(); cache.invalidate(cacheKey); } }
package org.objectweb.proactive.core.xml; import org.apache.log4j.Logger; import org.objectweb.proactive.core.descriptor.xml.VariablesHandler; import org.objectweb.proactive.core.util.log.Loggers; import org.objectweb.proactive.core.util.log.ProActiveLogger; import java.io.FileInputStream; import java.io.Serializable; import java.util.HashMap; import java.util.Iterator; import java.util.Properties; /** * This class provides a Variable Contract between the deployment descriptor and the application program. * Variables can be defined of different types, thus inforcing different requirements to the contract. * @author The ProActive Team */ public class VariableContract implements Serializable { static Logger logger = ProActiveLogger.getLogger(Loggers.DEPLOYMENT); public static VariableContract xmlproperties = null; public static final Lock lock = new Lock(); private boolean closed; private class PropertiesDatas { public String value; public VariableContractType type; public String setFrom; //Descriptor, Program public String toString() { StringBuffer sb = new StringBuffer(); sb.append(value).append(" type=").append(type).append(" setFrom=") .append(setFrom); return sb.toString(); } } private HashMap list; /** * Constructor of the class. Creates a new instance. * */ public VariableContract() { list = new HashMap(); closed = false; } /** * Marks the contract as closed. No more variables can be defined or set. */ public void close() { closed = true; } /** * Tells wether this contract is closed or not. * @return True if it is closed, false otherwise. */ public boolean isClosed() { return closed; } public void setVariableFromProgram(String name, String value, VariableContractType type) { setVariableFrom(name, value, type, "Program"); } private void setVariableFrom(String name, String value, VariableContractType type, String from) { if (logger.isDebugEnabled()) { logger.debug("Setting from " + from + ": " + type + " " + name + "=" + value); } if (closed) { throw new IllegalArgumentException( "Variable Contract is Closed. Variables can no longer be set"); } checkGenericLogic(name, value, type); if ((value.length() > 0) && !type.hasSetAbility(from)) { throw new IllegalArgumentException("Variable " + name + " can not be set from " + from + " for type: " + type); } if ((value.length() <= 0) && !type.hasSetEmptyAbility(from)) { throw new IllegalArgumentException("Variable " + name + " can not be set empty from " + from + " for type: " + type); } if (list.containsKey(name)) { PropertiesDatas var = (PropertiesDatas) list.get(name); if (!type.hasPriority(var.setFrom, from)) { if (logger.isDebugEnabled()) { logger.debug("Skipping, lower priority (" + from + " < " + var.setFrom + ") for type: " + type); } return; } } if (type.equals(VariableContractType.JavaPropertyVariable)) { String prop_value; try { prop_value = System.getProperty(value); if (prop_value == null) { throw new Exception(); } } catch (Exception ex) { throw new IllegalArgumentException( "Unable to get System Property: " + value); } value = prop_value; } unsafeAdd(name, value, type, from); } public void setVariableFromProgram(HashMap map, VariableContractType type) throws NullPointerException { if ((map == null) || (type == null)) { throw new NullPointerException("Null arguments"); } String name; java.util.Iterator it = map.keySet().iterator(); while (it.hasNext()) { name = (String) it.next(); setVariableFromProgram(name, (String) map.get(name), type); } } public void setDescriptorVariable(String name, String value, VariableContractType type) { setVariableFrom(name, value, type, "Descriptor"); } /** * Loads the variable contract from a Java Properties file format * @param file The file location. * @throws org.xml.sax.SAXException */ public void load(String file) throws org.xml.sax.SAXException { Properties properties = new Properties(); if (logger.isDebugEnabled()) { logger.debug("Loading propeties file:" + file); } // Open the file try { FileInputStream stream = new FileInputStream(file); properties.load(stream); } catch (Exception ex) { if (logger.isDebugEnabled()) { logger.debug("Curret Working Directory: " + System.getProperty("user.dir")); } throw new org.xml.sax.SAXException( "Tag property cannot open file : [" + file + "]"); } String name; String value; Iterator it = properties.keySet().iterator(); while (it.hasNext()) { name = (String) it.next(); value = properties.getProperty(name); setDescriptorVariable(name, value, VariableContractType.DescriptorVariable); } } /** * Loads a file with Variable Contract tags into the this instance. * @param file */ public void loadXML(String file) { if (logger.isDebugEnabled()) { logger.debug("Loading XML variable file:" + file); } VariablesHandler.createVariablesHandler(file, this); } /** * Returns the value of the variable name passed as parameter. * @param name The name of the variable. * @return The value of the variable. */ public String getValue(String name) { if (list.containsKey(name)) { PropertiesDatas var = (PropertiesDatas) list.get(name); return var.value; } return null; } /** * TODO * Method to transform a variable to it's value. * @param text Text with properties inside to translates. * @return string with properties swapped to their text value. */ public String transform(String text) { //if ( text==null || text.equals("")) return text; do { // try to find the begining of property int begin = text.indexOf("${"); if (begin < 0) { break; } begin += 2; // find the end of proprety name int end = text.indexOf("}"); if (end < 0) { break; } String endText = text.substring(end + 1, text.length()); // the name is empty ? if (begin == end) { if (begin > 2) { text = text.substring(0, begin - 2) + endText; } else { text = endText; } continue; } // build the name of the proterty String name = text.substring(begin, end); // if the property name does'n exist just return. if (list.containsKey(name) != true) { break; } PropertiesDatas datas = (PropertiesDatas) list.get(name); // check if there are some chars to keep at the begining of text. if (begin > 2) { text = text.substring(0, begin - 2) + datas.value + endText; } else { text = datas.value + endText; } } while (true); return text; } /** * Checks common parameters. * @param name Must be not null or empty * @param value Must be not null * @param type Checks if variable is already defined with different type */ private void checkGenericLogic(String name, String value, VariableContractType type) { /* * Generic Logical checks */ if (name == null) { throw new NullPointerException("Variable Name is null."); } if (name.length() <= 0) { throw new IllegalArgumentException("Variable Name is empty."); } if (value == null) { throw new NullPointerException("Variable Value is null."); } if (list.containsKey(name) && !((PropertiesDatas) list.get(name)).type.equals(type)) { throw new IllegalArgumentException("Variable " + name + " is already defined with type: " + ((PropertiesDatas) list.get(name)).type); } if (type == null) { throw new NullPointerException("Variable Type is null."); } } private void unsafeAdd(String name, String value, VariableContractType type, String setFrom) throws NullPointerException, IllegalArgumentException { if (name == null) { throw new NullPointerException("XML Variable Name is null."); } if (name.length() <= 0) { throw new IllegalArgumentException("XML Variable Name is empty."); } if (value == null) { throw new NullPointerException("XML Variable Value is null."); } PropertiesDatas data; if (list.containsKey(name)) { data = (PropertiesDatas) list.get(name); if (logger.isDebugEnabled()) { logger.debug("...Modifying variable registry"); } } else { data = new PropertiesDatas(); if (logger.isDebugEnabled()) { logger.debug("...Creating new registry for variable"); } } data.type = type; data.value = value; data.setFrom = setFrom; list.put(name, data); } /** * Checks if there are empty values in the contract. All errors are printed through * the logger. * @return True if the contract has no empty values. */ public boolean checkContract() { boolean retval = true; String name; java.util.Iterator it = list.keySet().iterator(); while (it.hasNext()) { name = (String) it.next(); PropertiesDatas data = (PropertiesDatas) list.get(name); if (data.type.equals(VariableContractType.DescriptorVariable) && (data.value.length() <= 0)) { logger.error("Contract breached. Variable " + name + " has no value. The value must be set in the Descriptor."); retval = false; } if (data.type.equals(VariableContractType.ProgramVariable) && (data.value.length() <= 0)) { logger.error("Contract breached. Variable " + name + " has no value. The value must be set in the Program."); retval = false; } if (data.type.equals(VariableContractType.ProgramDefaultVariable) && (data.value.length() <= 0)) { logger.error("Contract breached. Variable " + name + " has no value. The value should be set in the Program."); retval = false; } if (data.type.equals(VariableContractType.DescriptorDefaultVariable) && (data.value.length() <= 0)) { logger.error("Contract breached. Variable " + name + " has no value. The value should be set in the Descriptor."); retval = false; } } return retval; } public String toString() { StringBuffer sb = new StringBuffer(); PropertiesDatas var; String name; java.util.Iterator it = list.keySet().iterator(); while (it.hasNext()) { name = (String) it.next(); var = (PropertiesDatas) list.get(name); sb.append(name).append("=").append(var).append("\n"); } return sb.toString(); } public void setDescriptorVariableOLD(String name, String value, VariableContractType type) { if (logger.isDebugEnabled()) { logger.debug("Setting from descriptor: " + type + " " + name + "=" + value + "."); } checkGenericLogic(name, value, type); /* DescriptorVariable * -Priority: XML * -Set Ability: XML * -Default: XML */ if (type.equals(VariableContractType.DescriptorVariable) && (value.length() <= 0)) { throw new IllegalArgumentException("Variable " + name + " value must be specified for type: " + type); } /* ProgramVariable * -Priority: Program * -Set Ability: Program * -Default: Program */ if (type.equals(VariableContractType.ProgramVariable)) { if (value.length() > 0) { throw new IllegalArgumentException("Variable " + name + " can not be set from descriptor for type: " + type); } if (list.containsKey(name)) { if (logger.isDebugEnabled()) { logger.debug("Skipping " + type + " " + name + "=" + value + ". Program already set variable with value."); } return; } } /* DescriptorDefaultVariable * -Priority: Program * -Set Ability: Program, XML * -Default: XML */ if (type.equals(VariableContractType.DescriptorDefaultVariable)) { if (value.length() < 0) { throw new IllegalArgumentException("Variable " + name + " value must be specified for type: " + type); } //Priority is lost if Program set the variable if (list.containsKey(name)) { PropertiesDatas var = (PropertiesDatas) list.get(name); //skipe if program already set a value if (var.setFrom.equals("Program") && (var.value.length() > 0)) { if (logger.isDebugEnabled()) { logger.debug("Skipping variable " + name + " type: " + type + ". Program already set variable with higher priority"); } return; } } } /* ProgramDefaultVariable * -Priority: XML * -Set Ability: Program, XML * -Default: Program */ if (type.equals(VariableContractType.ProgramDefaultVariable) && (value.length() <= 0)) { if (logger.isDebugEnabled()) { logger.debug("Variable " + name + ", not setting to empty value"); } return; } /* JavaPropertyVariable * -Priority: JavaProperty * -Set Ability: JavaProperty * -Default: JavaProperty */ if (type.equals(VariableContractType.JavaPropertyVariable)) { String prop_value = null; if (value.length() <= 0) { throw new IllegalArgumentException("Variable " + name + " value can not be empty for type " + type); } try { prop_value = System.getProperty(value); if (prop_value == null) { throw new Exception(); } } catch (Exception ex) { throw new IllegalArgumentException( "Unable to get System Property: " + value); } value = prop_value; } //defineVariable(type, name); unsafeAdd(name, value, type, "Descriptor"); } public void setVariableFromProgramOLD(String name, String value, VariableContractType type) throws NullPointerException, IllegalArgumentException { if (logger.isDebugEnabled()) { logger.debug("Setting from program: " + type + " " + name + "=" + value); } checkGenericLogic(name, value, type); /* DescriptorVariable * -Priority: XML * -Set Ability: XML * -Default: XML */ if (type.equals(VariableContractType.DescriptorVariable)) { if (value.length() > 0) { throw new IllegalArgumentException("Variable " + name + " can not be set from program for type: " + type); } if (list.containsKey(name)) { if (logger.isDebugEnabled()) { logger.debug("Skipping " + type + " " + name + "=" + value + ". Descriptor already set variable with value."); } return; } } /* ProgramVariable * -Priority: Program * -Set Ability: Program * -Default: Program */ if (type.equals(VariableContractType.ProgramVariable) && (value.length() <= 0)) { throw new IllegalArgumentException("Variable " + name + " value must be specified for type: " + type); } /* DescriptorDefaultVariable * -Priority: Program * -Set Ability: Program, XML * -Default: XML */ if (type.equals(VariableContractType.DescriptorDefaultVariable) && (value.length() <= 0)) { if (logger.isDebugEnabled()) { logger.debug("Variable " + name + ", not setting to empty value"); } return; } /* ProgramDefaultVariable * -Priority: XML * -Set Ability: Program, XML * -Default: Program */ if (type.equals(VariableContractType.ProgramDefaultVariable)) { if (value.length() < 0) { throw new IllegalArgumentException("Variable " + name + " value must be specified for type: " + type); } if (list.containsKey(name)) { PropertiesDatas var = (PropertiesDatas) list.get(name); //skipe if descriptor already set a value if (var.setFrom.equals("Descriptor") && (var.value.length() > 0)) { if (logger.isDebugEnabled()) { logger.debug("Skipping variable " + name + " type: " + type + ". Descriptor already set variable with higher priority"); } return; } } } /* JavaPropertyVariable * -Priority: JavaProperty * -Set Ability: JavaProperty * -Default: JavaProperty */ if (type.equals(VariableContractType.JavaPropertyVariable)) { String prop_value = null; if (value.length() <= 0) { throw new IllegalArgumentException("Variable " + name + " value can not be empty for type " + type); } try { prop_value = System.getProperty(value); if (prop_value == null) { throw new Exception(); } } catch (Exception ex) { throw new IllegalArgumentException( "Unable to get System Property: " + value); } value = prop_value; } //defineVariable(type, name); unsafeAdd(name, value, type, "Program"); } /** * Class used for exclusive acces to global static variable: * org.objectweb.proactive.core.xml.XMLProperties.xmlproperties * * @author The ProActive Team */ static public class Lock { private boolean locked; private Lock() { locked = false; } /** * Call this method to release the lock on the XMLProperty variable. * This method will also clean the variable contents. */ public synchronized void release() { locked = false; notify(); } /** * Call this method to get the lock on the XMLProperty object instance. */ public synchronized void aquire() { while (locked) { try { wait(); } catch (InterruptedException e) { } } locked = true; } } }
package com.uchicom.zouni.servlet; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * MVCView. * @author Shigeki Uchiyama * */ public class ViewServlet extends HttpServlet { private static final long serialVersionUID = 1L; private StringBuffer script = new StringBuffer(); public ViewServlet(File templateFile) throws FileNotFoundException, IOException { try (FileInputStream fis = new FileInputStream(templateFile);) { byte[] bytes = new byte[1024 * 4]; int length = 0; boolean program = false; byte prev = 0; while ((length = fis.read(bytes)) > 0) { int startIndex = 0; int index = -1; while ((index = indexOf(bytes, startIndex, length - 1, (byte)'%')) >= 0) { if (program) { program = false; if (index != length - 1) { prev = bytes[index + 1]; } System.out.println(startIndex + ":a" + (index - startIndex)); System.out.println(new String(bytes, startIndex, index - startIndex)); if (bytes[startIndex] == '=') { script.append("out.print("); script.append(new String(bytes, startIndex + 1, index - (startIndex+1))); script.append(");\n"); } else { script.append(new String(bytes, startIndex, index - startIndex)); } script.append("\n"); startIndex = index + 2; } else { if (index != 0) { prev = bytes[index - 1]; if (prev == '<') { program = true; if (index != 1) { script.append("out.print(\""); System.out.println(startIndex + ":b" + (index - 1 - startIndex)); System.out.println(new String(bytes, startIndex, index - 1 - startIndex).replaceAll("\"", "\\\\\"").replaceAll("\n", "\\\\n").replaceAll("\r", "\\\\r")); script.append(new String(bytes, startIndex, index - 1 - startIndex).replaceAll("\"", "\\\\\"").replaceAll("\n", "\\\\n").replaceAll("\r", "\\\\r")); script.append("\");\n"); } startIndex = index + 1; } else { script.append("out.print(\""); System.out.println(startIndex + ":c" + (index - startIndex)); System.out.println(new String(bytes, startIndex, index - startIndex + 1).replaceAll("\"", "\\\\\"").replaceAll("\n", "\\\\n").replaceAll("\r", "\\\\r")); script.append(new String(bytes, startIndex, index - startIndex + 1).replaceAll("\"", "\\\\\"").replaceAll("\n", "\\\\n").replaceAll("\r", "\\\\r")); script.append("\");\n"); startIndex = index + 1; } } } } if (startIndex < length - 1) { if (program) { System.out.println(startIndex + ":d" + (length - startIndex)); System.out.println(new String(bytes, startIndex, length - startIndex)); if (bytes[startIndex] == '=') { script.append("out.print("); script.append(new String(bytes, startIndex + 1, index - (startIndex+1))); script.append(");\n"); } else { script.append(new String(bytes, startIndex, index - startIndex)); } script.append("\n"); } else { script.append("out.print(\""); System.out.println(startIndex + ":e" + (length - startIndex)); System.out.println(new String(bytes, startIndex, length - startIndex).replaceAll("\"", "\\\\\"").replaceAll("\n", "\\\\n").replaceAll("\r", "\\\\r")); script.append(new String(bytes, startIndex, length - startIndex).replaceAll("\"", "\\\\\"").replaceAll("\n", "\\\\n").replaceAll("\r", "\\\\r")); script.append("\");\n"); } } } script.append("out.flush();\n"); System.out.println(script); } } private int indexOf(byte[] bytes, int fromIndex, int toIndex, byte value) { for (int i = fromIndex; i <= toIndex; i++) { if (bytes[i] == value) return i; } return -1; } protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doPost(req, res); } protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { ScriptEngineManager sem = new ScriptEngineManager(); ScriptEngine se = sem.getEngineByName("JavaScript"); se.put("out", res.getPrintWriter()); se.put("request", req); se.put("session", req.getSession()); se.put("response", res); se.eval(script.toString()); } catch (ScriptException e) { e.printStackTrace(); throw new ServletException(e); } } }
package com.turn.ttorrent.client; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Paths; import java.util.BitSet; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import java.util.concurrent.ExecutorService; import com.turn.ttorrent.common.RTTorrentFileDescriptor; /** * @author Arnaud Durand * */ public class RTGenerator implements Runnable { public static final String rtgenPath = "C:\\rainbowcrack-1.5-win64\\"; private static Random rand = new Random(); private String hashAlgorithm; private String charset; private int plaintextLenMin; private int plaintextLenMax; /* * This is the rainbow chain length. Longer rainbow chain stores more * plaintexts and requires longer time to generate. */ private int chainLength; /* * Number of rainbow chains to generate. Rainbow table is simply an array of * rainbow chains. Size of each rainbow chain is 16 bytes. */ long chainNum; private SharedTorrent torrent; private Set<RTGenerationListener> listeners; private ExecutorService executor; private Thread thread; public RTGenerator(SharedTorrent torrent) { this.torrent = torrent; this.listeners = new HashSet<RTGenerationListener>(); this.thread = null; } public void start() { if (this.thread == null || !this.thread.isAlive()) { this.thread = new Thread(this); this.thread.setName("rt-generator"); this.thread.start(); } } /** * @author Arnaud Durand * @author Mikael Gasparian * */ public Piece generatePiece(int pieceIndex) throws InterruptedException, IOException, Exception { RTTorrentFileDescriptor descriptor = null; long offset = 0L; List<? extends RTTorrentFileDescriptor> descriptors = torrent .getFileDescriptors(); for (RTTorrentFileDescriptor d : descriptors) { if (pieceIndex * torrent.getPieceLength() <= offset) { descriptor = d; break; } offset += d.getLength(); } /* * The table_index parameter selects the reduction function. Rainbow * table with different table_index parameter uses different reduction * function. */ int tableIndex = descriptor.getTableIndex(); /* * To store a large rainbow table in many smaller files, use different * number in this parameter for each part and keep all other parameters * identical. */ int partIndex = (int) (pieceIndex % offset); Runtime rt = Runtime.getRuntime(); Process pr; pr = rt.exec(new String[] { rtgenPath + "rtgen.exe", hashAlgorithm, charset, Integer.toString(plaintextLenMin), Integer.toString(plaintextLenMax), Integer.toString(tableIndex), Integer.toString(chainLength), Long.toString(chainNum), Integer.toString(partIndex) }); int exitVal; if ((exitVal = pr.waitFor()) != 0) throw new Exception("rtgen exited with error code " + exitVal); pr = rt.exec(new String[] { rtgenPath + "rtsort.exe", descriptor.getPath() }); if ((exitVal = pr.waitFor()) != 0) throw new Exception("rtsort exited with error code " + exitVal); Piece p = torrent.getPiece(pieceIndex); String rtFilename=hashAlgorithm+"_"+charset+"#"+plaintextLenMin+"-"+plaintextLenMax+"_"+tableIndex+"_"+chainLength+"x"+chainNum+"_"+partIndex+".rt"; ByteBuffer generatdFileAsByteBuffer=ByteBuffer.wrap((Files.readAllBytes(Paths.get(rtgenPath+rtFilename)))); p.record(generatdFileAsByteBuffer, 0); return p; } public void run() { hashAlgorithm = torrent.getHashAlgorithm(); charset = torrent.getCharset(); plaintextLenMin = torrent.getPlaintextLenMin(); plaintextLenMax = torrent.getPlaintextLenMax(); chainLength = torrent.getChainLength(); chainNum = torrent.getPieceLength() / 16; BitSet unavailablePieces = torrent.getUnavailablePieces(); while (!unavailablePieces.isEmpty()) { // Choose a random unavailable piece for generation. int n = unavailablePieces.cardinality(); int[] indices = new int[n]; for (int i = 0, j = 0; i < n; i++) { j = torrent.getUnavailablePieces().nextSetBit(j); indices[i] = j++; } // Pick random unavailable piece. int pieceIndex = indices[rand.nextInt(indices.length)]; Piece p; try { p=generatePiece(pieceIndex); } catch (IOException | InterruptedException e) { e.printStackTrace(); continue; } catch (Exception e) { e.printStackTrace(); break; } try { p.validate(); this.firePieceCompleted(p); } catch (IOException e) { e.printStackTrace(); } // UnavailablePieces should be updated because race conditions can // change. unavailablePieces = torrent.getUnavailablePieces(); } } /** * Register a new incoming connection listener. * * @param listener * The listener who wants to receive connection notifications. */ public void register(RTGenerationListener listener) { this.listeners.add(listener); } /** * @author Arnaud Durand * * Fire the piece completion event to all registered listeners. * * <p> * The event contains the piece number that was completed. * </p> * * @param piece * The completed piece. */ private void firePieceCompleted(Piece piece) throws IOException { for (RTGenerationListener listener : this.listeners) { listener.handlePieceGenerationCompleted(piece); } } }
package org.odk.collect.android.receivers; import java.util.ArrayList; import java.util.HashMap; import org.odk.collect.android.R; import org.odk.collect.android.listeners.InstanceUploaderListener; import org.odk.collect.android.preferences.PreferencesActivity; import org.odk.collect.android.provider.InstanceProviderAPI; import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns; import org.odk.collect.android.tasks.InstanceUploaderTask; import org.odk.collect.android.utilities.WebUtils; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Environment; import android.preference.PreferenceManager; public class NetworkReceiver extends BroadcastReceiver implements InstanceUploaderListener { // turning on wifi often gets two CONNECTED events. we only want to run one thread at a time public static boolean running = false; InstanceUploaderTask mInstanceUploaderTask; @Override public void onReceive(Context context, Intent intent) { // make sure sd card is ready, if not don't try to send if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { return; } String action = intent.getAction(); NetworkInfo currentNetworkInfo = (NetworkInfo) intent .getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { if (currentNetworkInfo != null && currentNetworkInfo.getState() == NetworkInfo.State.CONNECTED) { if (interfaceIsEnabled(context, currentNetworkInfo)) { uploadForms(context); } } } else if (action.equals("org.odk.collect.android.FormSaved")) { ConnectivityManager connectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = connectivityManager.getActiveNetworkInfo(); if (ni == null || !ni.isConnected()) { // not connected, do nothing } else { if (interfaceIsEnabled(context, ni)) { uploadForms(context); } } } } private boolean interfaceIsEnabled(Context context, NetworkInfo currentNetworkInfo) { // make sure autosend is enabled on the given connected interface SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(context); boolean sendwifi = sharedPreferences.getBoolean( PreferencesActivity.KEY_AUTOSEND_WIFI, false); boolean sendnetwork = sharedPreferences.getBoolean( PreferencesActivity.KEY_AUTOSEND_NETWORK, false); return (currentNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI && sendwifi || currentNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE && sendnetwork); } private void uploadForms(Context context) { if (!running) { running = true; String selection = InstanceColumns.STATUS + "=? or " + InstanceColumns.STATUS + "=?"; String selectionArgs[] = { InstanceProviderAPI.STATUS_COMPLETE, InstanceProviderAPI.STATUS_SUBMISSION_FAILED }; Cursor c = context.getContentResolver().query(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, null); ArrayList<Long> toUpload = new ArrayList<Long>(); if (c != null && c.getCount() > 0) { c.move(-1); while (c.moveToNext()) { Long l = c.getLong(c.getColumnIndex(InstanceColumns._ID)); toUpload.add(Long.valueOf(l)); } // get the username, password, and server from preferences SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); String storedUsername = settings.getString(PreferencesActivity.KEY_USERNAME, null); String storedPassword = settings.getString(PreferencesActivity.KEY_PASSWORD, null); String server = settings.getString(PreferencesActivity.KEY_SERVER_URL, context.getString(R.string.default_server_url)); String url = server + settings.getString(PreferencesActivity.KEY_FORMLIST_URL, context.getString(R.string.default_odk_formlist)); Uri u = Uri.parse(url); WebUtils.addCredentials(storedUsername, storedPassword, u.getHost()); mInstanceUploaderTask = new InstanceUploaderTask(); mInstanceUploaderTask.setUploaderListener(this); Long[] toSendArray = new Long[toUpload.size()]; toUpload.toArray(toSendArray); mInstanceUploaderTask.execute(toSendArray); } else { running = false; } } } @Override public void uploadingComplete(HashMap<String, String> result) { // task is done mInstanceUploaderTask.setUploaderListener(null); running = false; } @Override public void progressUpdate(int progress, int total) { // do nothing } @Override public void authRequest(Uri url, HashMap<String, String> doneSoFar) { // if we get an auth request, just fail mInstanceUploaderTask.setUploaderListener(null); running = false; } }
package com.unit16.z.function; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; public class FluentConsumer<T> implements Consumer<T> { private final Consumer<? super T> wrapped; private FluentConsumer(Consumer<? super T> w) { wrapped = w; } public static <P> FluentConsumer<P> on(Consumer<? super P> w) { return new FluentConsumer<P>(w); } @Override public final void accept(T t) { wrapped.accept(t); } public final FluentConsumer<T> filter(final Predicate<T> pred) { return new Filters<>(pred, wrapped); } public final <S> FluentConsumer<S> map(final Function<S, T> func) { return new MapsTo<>(func, wrapped); } private static final class Filters<S> extends FluentConsumer<S> { private Filters(Predicate<? super S> pred, Consumer<? super S> ct) { super(new Consumer<S>(){ @Override public void accept(S t) { if (pred.test(t)) ct.accept(t); }}); } } private static final class MapsTo<S, T> extends FluentConsumer<S> { private MapsTo(Function<? super S, ? extends T> map, Consumer<? super T> ct) { super(new Consumer<S>(){ @Override public void accept(S t) { ct.accept(map.apply(t)); }}); } } }
package com.censoredsoftware.demigods.util; import com.censoredsoftware.demigods.Demigods; import com.censoredsoftware.demigods.structure.Structure; import com.google.common.base.Predicate; import com.google.common.collect.Iterators; import com.sk89q.worldguard.protection.regions.ProtectedRegion; import org.bukkit.Location; import org.bukkit.entity.Player; public class Zones { /** * Returns true if <code>location</code> is within a no-PVP zone. * * @param location the location to check. * @return true/false depending on if it's a no-PVP zone or not. */ public static boolean zoneNoPVP(Location location) { if(Demigods.config.getSettingBoolean("zones.allow_skills_anywhere")) return false; if(Demigods.worldguard != null) return Structures.isInRadiusWithFlag(location, Structure.Flag.NO_PVP) || !canWorldGuardDynamicPVP(location); return Structures.isInRadiusWithFlag(location, Structure.Flag.NO_PVP); } private static boolean canWorldGuardDynamicPVP(Location location) { return !Iterators.any(Demigods.worldguard.getRegionManager(location.getWorld()).getApplicableRegions(location).iterator(), new Predicate<ProtectedRegion>() { @Override public boolean apply(ProtectedRegion region) { return region.getId().toLowerCase().contains("nopvp"); } }); } /** * Returns true if <code>location</code> is within a no-build zone * for <code>player</code>. * * @param player the player to check. * @param location the location to check. * @return true/false depending on the position of the <code>player</code>. */ public static boolean zoneNoBuild(Player player, Location location) { return !Demigods.worldguard.canBuild(player, location); } }
package cronapi.database; import java.util.LinkedList; import java.util.concurrent.Callable; import org.apache.commons.lang3.ArrayUtils; import org.springframework.data.domain.PageRequest; import org.springframework.http.HttpStatus; import com.google.gson.JsonObject; import cronapi.ErrorResponse; import cronapi.QueryManager; import cronapi.Var; public class DatabaseQueryManager { private boolean isolatedTransaction = true; private String id; private JsonObject query; private boolean isDatabase = true; public DatabaseQueryManager(final String id) { this.id = id; this.query = QueryManager.getQuery(id); this.isDatabase = this.query.get("sourceType").getAsString().equals("entityFullName"); } public DatabaseQueryManager(final String id, final boolean isolatedTransaction) { this.id = id; this.isolatedTransaction = isolatedTransaction; this.query = QueryManager.getQuery(id); } public boolean isDatabase() { return this.isDatabase; } public Var get(final Object ... params) throws Exception { return get(null, params); } private Var[] toVarArray(Object[] list) { Var[] vars = new Var[list.length]; for(int i = 0; i < list.length; i++) { vars[i] = Var.valueOf(list[i]); } return vars; } public Var get(final PageRequest paramPage, final Object ... objParams) throws Exception { final PageRequest page = paramPage == null ? new PageRequest(0, 100) : paramPage; final Var[] params = toVarArray(objParams); return runIntoTransaction(() -> { if(QueryManager.getType(query).equals("blockly")) { return QueryManager.executeBlockly(query, "GET", params); } else { DataSource ds = new DataSource(query.get("entityFullName").getAsString()); String jpql = query.get("query") != null ? query.get("query").getAsString() : null; ds.filter(jpql, page, params); QueryManager.executeNavigateEvent(query, ds); return Var.valueOf(ds.getPage().getContent()); } }); } public Var insert(final Object objData, final Object ... extraObjParams) throws Exception { final Var[] extraParams = toVarArray(extraObjParams); final Var data = Var.valueOf(objData); return runIntoTransaction(() -> { if(QueryManager.getType(query).equals("blockly")) { Var[] params = (Var[])ArrayUtils.addAll(new Var[] { data }, extraParams); QueryManager.executeEvent(query, data, "beforeInsert"); Var inserted = QueryManager.executeBlockly(query, "POST", params); QueryManager.executeEvent(query, data, "afterInsert"); return inserted; } else { DataSource ds = new DataSource(query.get("entityFullName").getAsString()); ds.insert(data.getObject()); QueryManager.addDefaultValues(query, ds, true); QueryManager.executeEvent(query, ds, "beforeInsert"); Object inserted = ds.save(false); QueryManager.executeEvent(query, ds, "afterInsert"); return Var.valueOf(inserted); } }); } public Var update(final Var objData, final Object ... extraObjParams) throws Exception { final Var[] extraParams = toVarArray(extraObjParams); final Var data = Var.valueOf(objData); return runIntoTransaction(() -> { if(QueryManager.getType(query).equals("blockly")) { Var[] params = (Var[])ArrayUtils.addAll(new Var[] { data }, extraParams); QueryManager.executeEvent(query, data, "beforeUpdate"); Var modified = QueryManager.executeBlockly(query, "PUT", params); QueryManager.executeEvent(query, data, "beforeUpdate"); return modified; } else { DataSource ds = new DataSource(query.get("entityFullName").getAsString()); ds.filter(data, null); QueryManager.executeEvent(query, ds, "beforeUpdate"); ds.update(data); Var saved = Var.valueOf(ds.save()); QueryManager.executeEvent(query, ds, "afterUpdate"); return saved; } }); } public void delete(final Object ... extraObjParams) throws Exception { final Var[] extraParams = toVarArray(extraObjParams); runIntoTransaction(() -> { if(QueryManager.getType(query).equals("blockly")) { QueryManager.executeEvent(query, "beforeDelete", extraParams); QueryManager.executeBlockly(query, "DELETE", extraParams); QueryManager.executeEvent(query, "afterDelete", extraParams); } else { DataSource ds = new DataSource(query.get("entityFullName").getAsString()); ds.filter(null, new PageRequest(1, 1), extraParams); QueryManager.executeEvent(query, ds, "beforeDelete"); ds.delete(); QueryManager.executeEvent(query, ds, "afterDelete"); } return null; }); } private Var runIntoTransaction(Callable<Var> callable) throws Exception { Var var = Var.VAR_NULL; try { var = callable.call(); if (isolatedTransaction) TransactionManager.commit(); } catch(Exception ex) { if (isolatedTransaction) TransactionManager.rollback(); ErrorResponse errorResponse = new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), ex, "GET"); throw new Exception(errorResponse.getError(), ex); } return var; } }
package com.cidic.sdx.controllers; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.jgroups.util.UUID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.PathVariable; 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 com.cidic.sdx.exception.SdxException; import com.cidic.sdx.model.ListResultModel; import com.cidic.sdx.model.ResultModel; import com.cidic.sdx.model.Style; import com.cidic.sdx.model.User; import com.cidic.sdx.model.UserStyle; import com.cidic.sdx.services.UserService; @Controller @RequestMapping("/user") public class UserController { private static final Logger logger = LoggerFactory.getLogger(StyleController.class); @Autowired @Qualifier(value="userServiceImpl") private UserService userServiceImpl; private ResultModel resultModel = null; @ExceptionHandler(SdxException.class) public @ResponseBody ResultModel handleCustomException(SdxException ex) { ResultModel resultModel = new ResultModel(); resultModel.setResultCode(ex.getErrCode()); resultModel.setMessage(ex.getErrMsg()); return resultModel; } @RequestMapping(value = "/userMgr", method = RequestMethod.GET) public String userMgr(Locale locale, Model model) { return "userMgr"; } @RequestMapping(value = "/showUserChoose/{userId}", method = RequestMethod.GET) public String showUserChoose(Locale locale, Model model,@PathVariable String userId) { List<Style> list; try { list = userServiceImpl.getStyleListByUser(userId); model.addAttribute("list", list ); } catch (ParseException e) { e.printStackTrace(); } return "showUserChoose"; } @RequestMapping(value = "/insert", method = RequestMethod.POST) @ResponseBody public ResultModel insert(HttpServletRequest request,HttpServletResponse response,@RequestParam String userId,@RequestParam String styleIds){ response.setContentType("text/html;charset=UTF-8"); response.addHeader("Access-Control-Allow-Origin","*"); if("IE".equals(request.getParameter("type"))){ response.addHeader("XDomainRequestAllowed","1"); } try{ User user = new User(); user.setUserId(userId); user.setCreateTime(new Date()); String[] styles = styleIds.split(","); List<UserStyle> userStyleList = new ArrayList<UserStyle>(); for (String s : styles){ Style style1 = new Style(); style1.setId(Integer.parseInt(s)); UserStyle userStyle1 = new UserStyle(); userStyle1.setUser(user); userStyle1.setStyle(style1); userStyle1.setCreateTime(new Date()); userStyleList.add(userStyle1); } user.setUserStyleList(userStyleList); userServiceImpl.insertUser(user); resultModel = new ResultModel(); resultModel.setResultCode(200); } catch(Exception e){ throw new SdxException(500, "дݳ"); } return resultModel; } @RequestMapping(value = "/list", method = RequestMethod.GET, produces="application/json") @ResponseBody public ListResultModel listUser(@RequestParam int iDisplayLength, @RequestParam int iDisplayStart,@RequestParam String sEcho){ ListResultModel listResultModel = new ListResultModel(); try{ List<User> list = userServiceImpl.getDataByPage(iDisplayLength, iDisplayStart, sEcho); listResultModel.setAaData(list); listResultModel.setsEcho(sEcho); listResultModel.setiTotalRecords(list.size()); listResultModel.setiTotalDisplayRecords(iDisplayStart + list.size()); listResultModel.setSuccess(true); } catch(Exception e){ listResultModel.setSuccess(false); } return listResultModel; } @RequestMapping(value = "/detailResult/{userId}", method = RequestMethod.GET, produces="application/json") @ResponseBody public ResultModel getUserResultDetailById(@PathVariable String userId){ try{ List<Style> list = userServiceImpl.getStyleListByUser(userId); resultModel = new ResultModel(); resultModel.setResultCode(200); resultModel.setObject(list); } catch(Exception e){ throw new SdxException(500, "дݳ"); } return resultModel; } }
package de.codescape.bitvunit.ruleset; import com.gargoylesoftware.htmlunit.html.HtmlPage; import de.codescape.bitvunit.rule.Rule; import de.codescape.bitvunit.rule.Violations; import java.util.List; /** * Interface that must be implemented by all rule sets that should be checked with this framework. You should always * extend {@link BasicRuleSet} which gives you some convenience functionality instead of implementing this interface * directly. */ public interface RuleSet { /** * Returns a list of all rules contained in that rule set. * * @return list of all rules contained in that rule set */ List<Rule> getRules(); /** * Applies that rule set to the given {@link HtmlPage} and returns all {@link Violations} of the rules contained in * this rule set. * * @param htmlPage {@link HtmlPage} under test * @return all {@link Violations} of rules contained in this rule set */ Violations applyTo(HtmlPage htmlPage); }
package com.youbenzi.mdtool.markdown; import java.util.LinkedHashMap; import java.util.Map; public class MDToken { public static final String QUOTE = ">"; public static final String CODE = "```"; public static final String CODE_BLANK = " "; public static final String HEADLINE = " public static final String IMG = "!["; public static final String LINK = "["; public static final String UNORDERED_LIST1 = "* "; public static final String UNORDERED_LIST2 = "- "; public static final String UNORDERED_LIST3 = "+ "; public static final String TODO_LIST_UNCHECKED = "[ ]"; public static final String TODO_LIST_CHECKED = "[x]"; public static final String BOLD_WORD1 = "**"; public static final String BOLD_WORD2 = "__"; public static final String ITALIC_WORD = "_"; public static final String ITALIC_WORD_2 = "*"; public static final String STRIKE_WORD = "~~"; public static final String CODE_WORD = "`"; public static final String ROW = " "; public static final Map<String, String> PLACEHOLDER_MAP = new LinkedHashMap<String, String>() { private static final long serialVersionUID = 5649442662460683378L; { put("\\\\", "$BACKSLASH"); put("\\" + IMG, "$IMG"); put("\\" + LINK, "$LINK"); // put("\\" + BOLD_WORD, "$BOLDWORD"); // ITALIC_WORD_2 put("\\" + ITALIC_WORD, "$ITALICWORD"); put("\\" + ITALIC_WORD_2, "$2ITALICWORD"); put("\\" + STRIKE_WORD, "$STRIKEWORD"); put("\\" + CODE_WORD, "$CODEWORD"); put("\\", ""); } }; public static BlockType convert(String mdToken) { if (mdToken.equals(QUOTE)) { return BlockType.QUOTE; } else if (mdToken.equals(CODE)) { return BlockType.CODE; } else if (mdToken.equals(HEADLINE)) { return BlockType.HEADLINE; } else if (mdToken.equals(IMG)) { return BlockType.IMG; } else if (mdToken.equals(BOLD_WORD1) || mdToken.equals(BOLD_WORD2)) { return BlockType.BOLD_WORD; } else if (mdToken.equals(ITALIC_WORD) || mdToken.equals(ITALIC_WORD_2)) { return BlockType.ITALIC_WORD; } else if (mdToken.equals(STRIKE_WORD)) { return BlockType.STRIKE_WORD; } else if (mdToken.equals(CODE_WORD)) { return BlockType.CODE_WORD; } else if (mdToken.equals(LINK)) { return BlockType.LINK; } else if (mdToken.equals(ROW)) { return BlockType.ROW; } else { return BlockType.NONE; } } }
package com.zfgc.services.users; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.CharBuffer; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.PostConstruct; import javax.mail.internet.InternetAddress; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.time.DateUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.client.RestTemplate; import com.zfgc.config.ZfgcGeneralConfig; import com.zfgc.dao.LookupDao; import com.zfgc.dataprovider.EmailAddressDataProvider; import com.zfgc.dataprovider.IpDataProvider; import com.zfgc.dataprovider.UserConnectionDataProvider; import com.zfgc.dataprovider.UserCurrentActionDataProvider; import com.zfgc.dataprovider.UserEmailViewDataProvider; import com.zfgc.dataprovider.UsersDataProvider; import com.zfgc.exception.ZfgcNotFoundException; import com.zfgc.exception.ZfgcValidationException; import com.zfgc.model.users.AuthCredentials; import com.zfgc.model.users.AuthToken; import com.zfgc.model.users.EmailAddress; import com.zfgc.model.users.IpAddress; import com.zfgc.model.users.MemberListingView; import com.zfgc.model.users.MembersView; import com.zfgc.model.users.UserConnection; import com.zfgc.model.users.UserContactInfo; import com.zfgc.model.users.UserCurrentAction; import com.zfgc.model.users.UserEmailView; import com.zfgc.model.users.UserSecurityInfo; import com.zfgc.model.users.Users; import com.zfgc.model.users.profile.PersonalInfo; import com.zfgc.requiredfields.users.UsersRequiredFieldsChecker; import com.zfgc.rules.users.UsersRuleChecker; import com.zfgc.services.AbstractService; import com.zfgc.services.RuleRunService; import com.zfgc.services.authentication.AuthenticationService; import com.zfgc.services.avatar.AvatarService; import com.zfgc.services.ip.IpAddressService; import com.zfgc.services.lookups.LookupService; import com.zfgc.services.pm.PmService; import com.zfgc.util.ZfgcEmailUtils; import com.zfgc.util.security.RsaKeyPair; import com.zfgc.util.security.ZfgcSecurityUtils; import com.zfgc.util.time.ZfgcTimeUtils; import com.zfgc.validation.uservalidation.UserValidator; import com.zfgc.model.avatar.Avatar; import com.zfgc.model.online.OnlineUser; @Service public class UsersService extends AbstractService { @Autowired AuthenticationService authenticationService; @Autowired UsersDataProvider usersDataProvider; @Autowired IpAddressService ipAddressService; @Autowired EmailAddressDataProvider emailAddressDataProvider; @Autowired private ZfgcEmailUtils zfgcEmailUtils; @Autowired UsersRequiredFieldsChecker requiredFieldsChecker; @Autowired UserValidator validator; @Autowired UsersRuleChecker ruleChecker; @Autowired PmService pmService; @Autowired RuleRunService<Users> ruleRunner; @Autowired UserConnectionDataProvider userConnectionDataProvider; @Autowired UserCurrentActionDataProvider userCurrentActionDataProvider; @Autowired ZfgcGeneralConfig zfgcGeneralConfig; @Autowired private UserEmailViewDataProvider userEmailViewDataProvider; @Autowired private AvatarService avatarService; @Value("${clausius.client}") private String clientId; @Value("${clausius.password}") private String clientSecret; @Value("${clausius.authEndpoint}") private String authEndpoint; private Logger LOGGER = LogManager.getLogger(UsersService.class); private void getUserInternal(Users user) { user.setPrimaryIpAddress(ipAddressService.getIpAddress(user.getPrimaryIp())); user.setPersonalInfo(usersDataProvider.getPersonalInfo(user.getUsersId())); user.getPersonalInfo().setAvatar(avatarService.getAvatarRecord(user.getPersonalInfo().getAvatarId())); } public Users getUser(Integer usersId) { Users user = usersDataProvider.getUser(usersId); getUserInternal(user); return user; } public Users getUser(String username) { Users user = usersDataProvider.getUser(username); getUserInternal(user); return user; } public Users getUserByEmail(String email) { UserEmailView emailView = userEmailViewDataProvider.getActiveUserEmailReverse(email); return getUser(emailView.getLoginName()); } public List<Integer> getUsersByConversation(Integer conversationId) throws RuntimeException{ List<Users> result = null; result = usersDataProvider.getUsersByConversation(conversationId); List<Integer> Ids = new ArrayList<>(result.size()); for(Users user : result) { Ids.add(user.getUsersId()); } return Ids; } private void registerUserAtIdentity(Users user) { RestTemplate template = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.setBasicAuth(clientId, clientSecret); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity ent = new HttpEntity("{ 'username' : '" + user.getUserContactInfo().getEmail().getEmailAddress() + "', 'password' : '" + user.getUserSecurityInfo().getNewPassword() + "' }", headers); template.exchange(authEndpoint + "/users/register", HttpMethod.POST, ent, String.class); } @Transactional public Users createNewUser(Users user, HttpServletRequest requestHeader) throws RuntimeException{ try { user.setTimeOffsetLkup(lookupService.getLkupValue(LookupService.TIMEZONE, user.getTimeOffset())); ruleRunner.runRules(validator, requiredFieldsChecker, ruleChecker, user, user); } catch(ZfgcValidationException ex){ ex.printStackTrace(); throw ex; } catch (RuntimeException ex) { ex.printStackTrace(); throw ex; } if(!user.getErrors().hasErrors()){ registerUserAtIdentity(user); user.setDateRegistered(ZfgcTimeUtils.getToday(user.getTimeOffsetLkup())); user.setActiveFlag(false); user.setPrimaryMemberGroupId(2); generateUniqueActivationCode(user); IpAddress potentialIp = null; //does the remote Ip exist? try { IpAddress ipCheck = ipAddressService.getIpAddress(requestHeader.getRemoteAddr()); potentialIp = ipCheck; } catch(ZfgcNotFoundException ex) { potentialIp = ipAddressService.createIpAddress(requestHeader.getRemoteAddr()); } catch(RuntimeException ex) { ex.printStackTrace(); throw ex; } user.setPrimaryIpAddress(potentialIp); user.setPrimaryIp(potentialIp.getIpAddressId()); try { setUserIsSpammer(user); user.getUserContactInfo().setEmail(emailAddressDataProvider.createNewEmail(user.getUserContactInfo().getEmail())); Avatar avatar = new Avatar(); avatar.setAvatarTypeId(1); user.getPersonalInfo().setAvatar(avatar); user = usersDataProvider.createUser(user); loggingService.logAction(7, "User account created for " + user.getLoginName(), user.getUsersId(), user.getPrimaryIpAddress().getIpAddress()); if(!user.getUserContactInfo().getEmail().getIsSpammerFlag()) { String subject = "New Account Activation For ZFGC"; String body = "Hello " + user.getDisplayName() + ", below you will find an activation link for your account on ZFGC.<br>" + "If you think you have received this email in error, please ignore it.<br><br>" + zfgcGeneralConfig.getUiUrl() + "/useractivation?activationCode=" + user.getEmailActivationCode(); InternetAddress to = new InternetAddress(user.getUserContactInfo().getEmail().getEmailAddress(), user.getDisplayName()); zfgcEmailUtils.sendEmail(subject, body, to); } //generate rsa key pair for PM, then AES encrypt the private key - base it off of the password for now //todo: when the encryption system for PMs is redone, update this to be a separate field distinct from the password pmService.createKeyPairs(user.getUsersId(), user.getUserSecurityInfo().getNewPassword()); } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException(ex); } } return user; } public void setUserIsSpammer(Users user) throws RuntimeException{ user.getPrimaryIpAddress().setIsSpammerFlag(authenticationService.checkIpIsSpammer(user.getPrimaryIpAddress())); user.getUserContactInfo().getEmail().setIsSpammerFlag(authenticationService.checkEmailIsSpammer(user.getUserContactInfo().getEmail())); } public Boolean doesLoginNameExist(String loginName) throws RuntimeException { return usersDataProvider.doesLoginNameExist(loginName); } public Boolean doesDisplayNameExist(String loginName) throws RuntimeException { return usersDataProvider.doesDisplayNameExist(loginName); } public Users getLoggedInUser(Users user) throws RuntimeException{ if(user.getUsersId() == null || user.getUsersId() == -1){ Users guest = new Users(); guest.setDisplayName("Guest"); guest.setPrimaryMemberGroupId(0); return guest; } user.setUnreadPmCount(pmService.getUnreadPmCount(user)); return user; } public Users getDisplayName(Integer usersId){ Users user = new Users(); user.setUsersId(usersId); user.setDisplayName(usersDataProvider.getDisplayName(usersId)); return user; } public MembersView getMemberListingView(Users user, Integer pageNumber, Integer range) throws RuntimeException{ List<MemberListingView> result = usersDataProvider.getMemberListing(pageNumber - 1, range); Long totalUsers = usersDataProvider.getActiveUsersCount(); MembersView members = new MembersView(); members.setTotalCount(totalUsers); members.setMembers(result); return members; } public void setUserOnline(Users user, String sessionId) throws RuntimeException{ user.setActiveConnections(user.getActiveConnections() + 1); user.setLastLogin(ZfgcTimeUtils.getToday()); usersDataProvider.setUserOnline(user); String result = null; //create a connection entry for the user try { URL url = new URL("http: HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setConnectTimeout(3000); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("User-Agent", ""); InputStream stream = conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(stream)); result = br.readLine(); br.close(); } catch (IOException ex) { ex.printStackTrace(); } catch (RuntimeException ex){ throw ex; } UserConnection onlineUser = userConnectionDataProvider.getUserConnectionTemplate(user); onlineUser.setSessionId(user.getSessionMatchup()); if(result != null) { String[] params = result.split(";"); Map<String, String> mappedParams = new HashMap<>(); for(String param : params) { String[] split = param.split("="); mappedParams.put(split[0], split.length > 1 ? split[1] : null); } onlineUser.setAgentName(mappedParams.get("agent_name")); onlineUser.setAgentType(mappedParams.get("agent_type")); onlineUser.setAgentVersion(mappedParams.get("agent_version")); onlineUser.setOsName(mappedParams.get("os_name")); onlineUser.setOsType(mappedParams.get("os_type")); onlineUser.setOsVersionName(mappedParams.get("os_versionName")); onlineUser.setOsVersionNumber(mappedParams.get("os_versionNumber")); } UserCurrentAction currentAction = new UserCurrentAction(); currentAction.setUsersId(user.getUsersId()); currentAction.setLocationId(7); userCurrentActionDataProvider.updateUserAction(currentAction); onlineUser.setUserActionId(currentAction.getUserCurrentActionId()); userConnectionDataProvider.insertNewConnection(onlineUser); user.setUserConnectionId(onlineUser.getUserConnectionId()); } @Transactional public void updateUserActions(String sessionId, Integer actionId, Users zfgcUser, String ... param) { UserCurrentAction action = new UserCurrentAction(); action.setLocationId(actionId); action.setUsersId(zfgcUser.getUsersId()); action.setParam(Integer.parseInt(param[0])); userCurrentActionDataProvider.updateUserAction(action); //get their existing connection UserConnection onlineUser = userConnectionDataProvider.getUserConnectionBySessionId(sessionId); onlineUser.setUserActionId(action.getUserCurrentActionId()); userConnectionDataProvider.insertNewConnection(onlineUser); } public void setUserOffline(Users user, String sessionId) throws Exception{ user.setActiveConnections(user.getActiveConnections() - 1); if(user.getActiveConnections() < 0){ user.setActiveConnections(0); } user.setLastLogin(ZfgcTimeUtils.getToday()); usersDataProvider.setUserOffline(user); userConnectionDataProvider.deleteUserConnection(sessionId); } public Users getNewUserTemplate() { Users user = new Users(); user.setActiveFlag(false); user.setUserContactInfo(new UserContactInfo()); user.getUserContactInfo().setEmail(new EmailAddress()); user.setUserSecurityInfo(new UserSecurityInfo()); user.setPersonalInfo(new PersonalInfo()); return user; } private void generateUniqueActivationCode(Users user) { user.setEmailActivationCode(ZfgcSecurityUtils.generateCryptoString(32)); } public void activateUserAccount(String activationCode) throws RuntimeException{ usersDataProvider.activateUser(activationCode); getMostRecentUser(); } public void activateUserAccount(Integer usersId, Users zfgcUser) throws RuntimeException{ //todo check the user role usersDataProvider.activateUser(usersId); getMostRecentUser(); } public Users getMostRecentUser() { Users recent = usersDataProvider.getMostRecentMember(); if(recent != null) { super.websocketMessaging.convertAndSend("/socket/members/recentMember", recent); } return recent; } public String getLoginToken(AuthCredentials credentials) { RestTemplate template = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.setBasicAuth(clientId, clientSecret); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); //lets see if this user even exists first. //we need their email address for authentication anyway UserEmailView userEmail = userEmailViewDataProvider.getActiveUserEmail(credentials.getUsername()); //todo: move these paramters into the request body HttpEntity ent = new HttpEntity("grant_type=password&scope=all&username=" + userEmail.getEmailAddress() + "&password=" + credentials.getPassword(), headers); ResponseEntity<String> result = template.exchange(authEndpoint + "/oauth/token", HttpMethod.POST, ent, String.class); return result.getBody(); } @PostConstruct public void resetAllActiveConnections() throws Exception { LOGGER.info("Resetting all active connection counts to 0..."); usersDataProvider.resetActiveConnectionCounts(); LOGGER.info("Finished resetting all active connection counts to 0."); LOGGER.info("Clearing out user connections..."); userConnectionDataProvider.deleteAllUserConnections(); userCurrentActionDataProvider.deleteAllUserActions(); LOGGER.info("Finished clearing out user connections."); } }
package org.zstack.compute.vm; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.zstack.compute.allocator.HostAllocatorManager; import org.zstack.core.cascade.CascadeConstant; import org.zstack.core.cascade.CascadeFacade; import org.zstack.core.cloudbus.*; import org.zstack.core.componentloader.PluginRegistry; import org.zstack.core.db.DatabaseFacade; import org.zstack.core.db.SimpleQuery; import org.zstack.core.db.SimpleQuery.Op; import org.zstack.core.defer.Defer; import org.zstack.core.defer.Deferred; import org.zstack.core.jsonlabel.JsonLabel; import org.zstack.core.scheduler.SchedulerFacade; import org.zstack.core.thread.ChainTask; import org.zstack.core.thread.SyncTaskChain; import org.zstack.core.thread.ThreadFacade; import org.zstack.core.workflow.FlowChainBuilder; import org.zstack.core.workflow.ShareFlow; import org.zstack.header.allocator.*; import org.zstack.header.apimediator.ApiMessageInterceptionException; import org.zstack.header.cluster.ClusterInventory; import org.zstack.header.cluster.ClusterVO; import org.zstack.header.cluster.ClusterVO_; import org.zstack.header.configuration.*; import org.zstack.header.core.Completion; import org.zstack.header.core.NoErrorCompletion; import org.zstack.header.core.NopeCompletion; import org.zstack.header.core.ReturnValueCompletion; import org.zstack.header.core.scheduler.SchedulerInventory; import org.zstack.header.core.scheduler.SchedulerVO; import org.zstack.header.core.workflow.*; import org.zstack.header.errorcode.ErrorCode; import org.zstack.header.errorcode.OperationFailureException; import org.zstack.header.errorcode.SysErrors; import org.zstack.header.exception.CloudRuntimeException; import org.zstack.header.host.*; import org.zstack.header.image.*; import org.zstack.header.image.ImageConstant.ImageMediaType; import org.zstack.header.message.*; import org.zstack.header.network.l3.*; import org.zstack.header.storage.primary.*; import org.zstack.header.vm.*; import org.zstack.header.vm.ChangeVmMetaDataMsg.AtomicHostUuid; import org.zstack.header.vm.ChangeVmMetaDataMsg.AtomicVmState; import org.zstack.header.vm.VmAbnormalLifeCycleStruct.VmAbnormalLifeCycleOperation; import org.zstack.header.vm.VmInstanceConstant.Capability; import org.zstack.header.vm.VmInstanceConstant.Params; import org.zstack.header.vm.VmInstanceConstant.VmOperation; import org.zstack.header.vm.VmInstanceDeletionPolicyManager.VmInstanceDeletionPolicy; import org.zstack.header.vm.VmInstanceSpec.HostName; import org.zstack.header.vm.VmInstanceSpec.IsoSpec; import org.zstack.header.volume.*; import org.zstack.identity.AccountManager; import org.zstack.tag.SystemTagCreator; import org.zstack.utils.CollectionUtils; import org.zstack.utils.DebugUtils; import org.zstack.utils.ObjectUtils; import org.zstack.utils.Utils; import org.zstack.utils.function.ForEachFunction; import org.zstack.utils.function.Function; import org.zstack.utils.gson.JSONObjectUtil; import org.zstack.utils.logging.CLogger; import static org.zstack.core.Platform.operr; import javax.persistence.TypedQuery; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.zstack.utils.CollectionDSL.*; public class VmInstanceBase extends AbstractVmInstance { protected static final CLogger logger = Utils.getLogger(VmInstanceBase.class); @Autowired protected CloudBus bus; @Autowired protected DatabaseFacade dbf; @Autowired protected ThreadFacade thdf; @Autowired protected VmInstanceManager vmMgr; @Autowired protected VmInstanceExtensionPointEmitter extEmitter; @Autowired protected VmInstanceNotifyPointEmitter notifyEmitter; @Autowired protected CascadeFacade casf; @Autowired protected AccountManager acntMgr; @Autowired protected EventFacade evtf; @Autowired protected PluginRegistry pluginRgty; @Autowired protected VmInstanceDeletionPolicyManager deletionPolicyMgr; @Autowired private SchedulerFacade schedulerFacade; @Autowired private HostAllocatorManager hostAllocatorMgr; protected VmInstanceVO self; protected VmInstanceVO originalCopy; protected String syncThreadName; private void checkState(final String hostUuid, final NoErrorCompletion completion) { CheckVmStateOnHypervisorMsg msg = new CheckVmStateOnHypervisorMsg(); msg.setVmInstanceUuids(list(self.getUuid())); msg.setHostUuid(hostUuid); bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, hostUuid); bus.send(msg, new CloudBusCallBack(completion) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { //TODO logger.warn(String.format("unable to check state of the vm[uuid:%s] on the host[uuid:%s], %s." + " Put the vm to Unknown state", self.getUuid(), hostUuid, reply.getError())); self = dbf.reload(self); changeVmStateInDb(VmInstanceStateEvent.unknown); completion.done(); return; } CheckVmStateOnHypervisorReply r = reply.castReply(); String state = r.getStates().get(self.getUuid()); self = dbf.reload(self); if (state == null) { changeVmStateInDb(VmInstanceStateEvent.unknown); } if (VmInstanceState.Running.toString().equals(state)) { self.setHostUuid(hostUuid); changeVmStateInDb(VmInstanceStateEvent.running); } else if (VmInstanceState.Stopped.toString().equals(state)) { changeVmStateInDb(VmInstanceStateEvent.stopped); } else { throw new CloudRuntimeException(String.format( "CheckVmStateOnHypervisorMsg should only report states[Running or Stopped]," + "but it reports %s for the vm[uuid:%s] on the host[uuid:%s]", state, self.getUuid(), hostUuid)); } completion.done(); } }); } protected void destroy(final VmInstanceDeletionPolicy deletionPolicy, final Completion completion) { if (deletionPolicy == VmInstanceDeletionPolicy.DBOnly) { completion.success(); return; } final VmInstanceInventory inv = VmInstanceInventory.valueOf(self); VmInstanceSpec spec = buildSpecFromInventory(inv, VmOperation.Destroy); self = changeVmStateInDb(VmInstanceStateEvent.destroying); FlowChain chain = getDestroyVmWorkFlowChain(inv); setFlowMarshaller(chain); chain.setName(String.format("destroy-vm-%s", self.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); chain.getData().put(Params.DeletionPolicy, deletionPolicy); chain.done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(final ErrorCode errCode, Map data) { if (originalCopy.getState() == VmInstanceState.Running) { checkState(originalCopy.getHostUuid(), new NoErrorCompletion(completion) { @Override public void done() { completion.fail(errCode); } }); } else { self = dbf.reload(self); changeVmStateInDb(VmInstanceStateEvent.unknown); completion.fail(errCode); } } }).start(); } protected VmInstanceVO getSelf() { return self; } protected VmInstanceInventory getSelfInventory() { return VmInstanceInventory.valueOf(self); } public VmInstanceBase(VmInstanceVO vo) { this.self = vo; this.syncThreadName = "Vm-" + vo.getUuid(); this.originalCopy = ObjectUtils.newAndCopy(vo, vo.getClass()); } protected VmInstanceVO refreshVO() { return refreshVO(false); } protected VmInstanceVO refreshVO(boolean noException) { VmInstanceVO vo = self; self = dbf.findByUuid(self.getUuid(), VmInstanceVO.class); if (self == null && noException) { return null; } if (self == null) { throw new OperationFailureException(operr("vm[uuid:%s, name:%s] has been deleted", vo.getUuid(), vo.getName())); } originalCopy = ObjectUtils.newAndCopy(vo, vo.getClass()); return self; } protected FlowChain getCreateVmWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getCreateVmWorkFlowChain(inv); } protected FlowChain getStopVmWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getStopVmWorkFlowChain(inv); } protected FlowChain getRebootVmWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getRebootVmWorkFlowChain(inv); } protected FlowChain getStartVmWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getStartVmWorkFlowChain(inv); } protected FlowChain getDestroyVmWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getDestroyVmWorkFlowChain(inv); } protected FlowChain getExpungeVmWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getExpungeVmWorkFlowChain(inv); } protected FlowChain getMigrateVmWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getMigrateVmWorkFlowChain(inv); } protected FlowChain getAttachUninstantiatedVolumeWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getAttachUninstantiatedVolumeWorkFlowChain(inv); } protected FlowChain getAttachIsoWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getAttachIsoWorkFlowChain(inv); } protected FlowChain getDetachIsoWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getDetachIsoWorkFlowChain(inv); } protected FlowChain getPauseVmWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getPauseWorkFlowChain(inv); } protected FlowChain getResumeVmWorkFlowChain(VmInstanceInventory inv) { return vmMgr.getResumeVmWorkFlowChain(inv); } protected VmInstanceVO changeVmStateInDb(VmInstanceStateEvent stateEvent) { VmInstanceState bs = self.getState(); final VmInstanceState state = self.getState().nextState(stateEvent); if (state == VmInstanceState.Stopped) { // cleanup the hostUuid if the VM is stopped if (self.getHostUuid() != null) { self.setLastHostUuid(self.getHostUuid()); } self.setHostUuid(null); } self.setState(state); self = dbf.updateAndRefresh(self); if (bs != state) { logger.debug(String.format("vm[uuid:%s] changed state from %s to %s in db", self.getUuid(), bs, self.getState())); VmCanonicalEvents.VmStateChangedData data = new VmCanonicalEvents.VmStateChangedData(); data.setVmUuid(self.getUuid()); data.setOldState(bs.toString()); data.setNewState(state.toString()); data.setInventory(getSelfInventory()); evtf.fire(VmCanonicalEvents.VM_FULL_STATE_CHANGED_PATH, data); VmInstanceInventory inv = getSelfInventory(); CollectionUtils.safeForEach(pluginRgty.getExtensionList(VmStateChangedExtensionPoint.class), new ForEachFunction<VmStateChangedExtensionPoint>() { @Override public void run(VmStateChangedExtensionPoint ext) { ext.vmStateChanged(inv, bs, self.getState()); } }); //TODO: remove this notifyEmitter.notifyVmStateChange(VmInstanceInventory.valueOf(self), bs, state); } return self; } @Override @MessageSafe public void handleMessage(final Message msg) { if (msg instanceof APIMessage) { handleApiMessage((APIMessage) msg); } else { handleLocalMessage(msg); } } protected void handleLocalMessage(Message msg) { if (msg instanceof StartNewCreatedVmInstanceMsg) { handle((StartNewCreatedVmInstanceMsg) msg); } else if (msg instanceof StartVmInstanceMsg) { handle((StartVmInstanceMsg) msg); } else if (msg instanceof StopVmInstanceMsg) { handle((StopVmInstanceMsg) msg); } else if (msg instanceof RebootVmInstanceMsg) { handle((RebootVmInstanceMsg) msg); } else if (msg instanceof ChangeVmStateMsg) { handle((ChangeVmStateMsg) msg); } else if (msg instanceof DestroyVmInstanceMsg) { handle((DestroyVmInstanceMsg) msg); } else if (msg instanceof AttachNicToVmMsg) { handle((AttachNicToVmMsg) msg); } else if (msg instanceof CreateTemplateFromVmRootVolumeMsg) { handle((CreateTemplateFromVmRootVolumeMsg) msg); } else if (msg instanceof VmInstanceDeletionMsg) { handle((VmInstanceDeletionMsg) msg); } else if (msg instanceof VmAttachNicMsg) { handle((VmAttachNicMsg) msg); } else if (msg instanceof MigrateVmMsg) { handle((MigrateVmMsg) msg); } else if (msg instanceof DetachDataVolumeFromVmMsg) { handle((DetachDataVolumeFromVmMsg) msg); } else if (msg instanceof AttachDataVolumeToVmMsg) { handle((AttachDataVolumeToVmMsg) msg); } else if (msg instanceof GetVmMigrationTargetHostMsg) { handle((GetVmMigrationTargetHostMsg) msg); } else if (msg instanceof ChangeVmMetaDataMsg) { handle((ChangeVmMetaDataMsg) msg); } else if (msg instanceof LockVmInstanceMsg) { handle((LockVmInstanceMsg) msg); } else if (msg instanceof DetachNicFromVmMsg) { handle((DetachNicFromVmMsg) msg); } else if (msg instanceof VmStateChangedOnHostMsg) { handle((VmStateChangedOnHostMsg) msg); } else if (msg instanceof VmCheckOwnStateMsg) { handle((VmCheckOwnStateMsg) msg); } else if (msg instanceof ExpungeVmMsg) { handle((ExpungeVmMsg) msg); } else if (msg instanceof HaStartVmInstanceMsg) { handle((HaStartVmInstanceMsg) msg); } else { VmInstanceBaseExtensionFactory ext = vmMgr.getVmInstanceBaseExtensionFactory(msg); if (ext != null) { VmInstance v = ext.getVmInstance(self); v.handleMessage(msg); } else { bus.dealWithUnknownMessage(msg); } } } private void handle(final APIGetVmStartingCandidateClustersHostsMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { getStartingCandidateHosts(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return "get-starting-candidate-hosts"; } }); } private void getStartingCandidateHosts(final APIGetVmStartingCandidateClustersHostsMsg msg, final NoErrorCompletion completion) { refreshVO(); ErrorCode err = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (err != null) { throw new OperationFailureException(err); } final DesignatedAllocateHostMsg amsg = new DesignatedAllocateHostMsg(); amsg.setCpuCapacity(self.getCpuNum()); amsg.setMemoryCapacity(self.getMemorySize()); amsg.setVmInstance(VmInstanceInventory.valueOf(self)); amsg.setServiceId(bus.makeLocalServiceId(HostAllocatorConstant.SERVICE_ID)); amsg.setAllocatorStrategy(self.getAllocatorStrategy()); amsg.setVmOperation(VmOperation.Start.toString()); amsg.setL3NetworkUuids(CollectionUtils.transformToList(self.getVmNics(), new Function<String, VmNicVO>() { @Override public String call(VmNicVO arg) { return arg.getL3NetworkUuid(); } })); amsg.setDryRun(true); amsg.setListAllHosts(true); final APIGetVmStartingCandidateClustersHostsReply reply = new APIGetVmStartingCandidateClustersHostsReply(); bus.send(amsg, new CloudBusCallBack(completion) { @Override public void run(MessageReply re) { if (!re.isSuccess()) { if (HostAllocatorError.NO_AVAILABLE_HOST.toString().equals(re.getError().getCode())) { reply.setHostInventories(new ArrayList<>()); reply.setClusterInventories(new ArrayList<>()); } else { reply.setError(re.getError()); } } else { List<HostInventory> hosts = ((AllocateHostDryRunReply) re).getHosts(); if (!hosts.isEmpty()) { List<String> cuuids = CollectionUtils.transformToList(hosts, new Function<String, HostInventory>() { @Override public String call(HostInventory arg) { return arg.getClusterUuid(); } }); SimpleQuery<ClusterVO> cq = dbf.createQuery(ClusterVO.class); cq.add(ClusterVO_.uuid, Op.IN, cuuids); List<ClusterVO> cvos = cq.list(); reply.setClusterInventories(ClusterInventory.valueOf(cvos)); reply.setHostInventories(hosts); } else { reply.setHostInventories(hosts); reply.setClusterInventories(new ArrayList<>()); } } bus.reply(msg, reply); completion.done(); } }); } private void handle(final HaStartVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { refreshVO(); HaStartVmJudger judger; try { Class clz = Class.forName(msg.getJudgerClassName()); judger = (HaStartVmJudger) clz.newInstance(); } catch (Exception e) { throw new CloudRuntimeException(e); } final HaStartVmInstanceReply reply = new HaStartVmInstanceReply(); if (!judger.whetherStartVm(getSelfInventory())) { bus.reply(msg, reply); chain.next(); return; } logger.debug(String.format("HaStartVmJudger[%s] says the VM[uuid:%s, name:%s] is qualified for HA start, now we are starting it", judger.getClass(), self.getUuid(), self.getName())); self.setState(VmInstanceState.Stopped); dbf.update(self); startVm(msg, new Completion(msg, chain) { @Override public void success() { bus.reply(msg, reply); chain.next(); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); chain.next(); } }); } @Override public String getName() { return "ha-start-vm"; } }); } private void changeVmIp(final String l3Uuid, final String ip, final Completion completion) { final VmNicVO targetNic = CollectionUtils.find(self.getVmNics(), new Function<VmNicVO, VmNicVO>() { @Override public VmNicVO call(VmNicVO arg) { return l3Uuid.equals(arg.getL3NetworkUuid()) ? arg : null; } }); if (targetNic == null) { throw new OperationFailureException(operr("the vm[uuid:%s] has no nic on the L3 network[uuid:%s]", self.getUuid(), l3Uuid)); } if (ip.equals(targetNic.getIp())) { completion.success(); return; } final UsedIpInventory oldIp = new UsedIpInventory(); oldIp.setIp(targetNic.getIp()); oldIp.setGateway(targetNic.getGateway()); oldIp.setNetmask(targetNic.getNetmask()); oldIp.setL3NetworkUuid(targetNic.getL3NetworkUuid()); oldIp.setUuid(targetNic.getUsedIpUuid()); final FlowChain chain = FlowChainBuilder.newShareFlowChain(); chain.setName(String.format("change-vm-ip-to-%s-l3-%s-vm-%s", ip, l3Uuid, self.getUuid())); chain.then(new ShareFlow() { UsedIpInventory newIp; String oldIpUuid = targetNic.getUsedIpUuid(); @Override public void setup() { flow(new Flow() { String __name__ = "acquire-new-ip"; @Override public void run(final FlowTrigger trigger, Map data) { AllocateIpMsg amsg = new AllocateIpMsg(); amsg.setL3NetworkUuid(l3Uuid); amsg.setRequiredIp(ip); bus.makeTargetServiceIdByResourceUuid(amsg, L3NetworkConstant.SERVICE_ID, l3Uuid); bus.send(amsg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { trigger.fail(reply.getError()); } else { AllocateIpReply r = reply.castReply(); newIp = r.getIpInventory(); trigger.next(); } } }); } @Override public void rollback(FlowRollback trigger, Map data) { if (newIp != null) { ReturnIpMsg rmsg = new ReturnIpMsg(); rmsg.setL3NetworkUuid(newIp.getL3NetworkUuid()); rmsg.setUsedIpUuid(newIp.getUuid()); bus.makeTargetServiceIdByResourceUuid(rmsg, L3NetworkConstant.SERVICE_ID, newIp.getL3NetworkUuid()); bus.send(rmsg); } trigger.rollback(); } }); flow(new NoRollbackFlow() { String __name__ = "change-ip-in-database"; @Override public void run(FlowTrigger trigger, Map data) { targetNic.setUsedIpUuid(newIp.getUuid()); targetNic.setGateway(newIp.getGateway()); targetNic.setNetmask(newIp.getNetmask()); targetNic.setIp(newIp.getIp()); dbf.update(targetNic); trigger.next(); } }); flow(new NoRollbackFlow() { String __name__ = "return-old-ip"; @Override public void run(FlowTrigger trigger, Map data) { ReturnIpMsg rmsg = new ReturnIpMsg(); rmsg.setUsedIpUuid(oldIpUuid); rmsg.setL3NetworkUuid(targetNic.getL3NetworkUuid()); bus.makeTargetServiceIdByResourceUuid(rmsg, L3NetworkConstant.SERVICE_ID, targetNic.getL3NetworkUuid()); bus.send(rmsg); trigger.next(); } }); done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { final VmInstanceInventory vm = getSelfInventory(); final VmNicInventory nic = VmNicInventory.valueOf(targetNic); CollectionUtils.safeForEach(pluginRgty.getExtensionList(VmIpChangedExtensionPoint.class), new ForEachFunction<VmIpChangedExtensionPoint>() { @Override public void run(VmIpChangedExtensionPoint ext) { ext.vmIpChanged(vm, nic, oldIp, newIp); } }); completion.success(); } }); error(new FlowErrorHandler(completion) { @Override public void handle(ErrorCode errCode, Map data) { completion.fail(errCode); } }); } }).start(); } private void handle(final ExpungeVmMsg msg) { final ExpungeVmReply reply = new ExpungeVmReply(); thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { expunge(msg, new Completion(msg, chain) { @Override public void success() { bus.reply(msg, reply); chain.next(); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); chain.next(); } }); } @Override public String getName() { return "expunge-vm"; } }); } private void expunge(Message msg, final Completion completion) { refreshVO(); final VmInstanceInventory inv = getSelfInventory(); CollectionUtils.safeForEach(pluginRgty.getExtensionList(VmBeforeExpungeExtensionPoint.class), new ForEachFunction<VmBeforeExpungeExtensionPoint>() { @Override public void run(VmBeforeExpungeExtensionPoint arg) { arg.vmBeforeExpunge(inv); } }); ErrorCode error = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (error != null) { throw new OperationFailureException(error); } if (inv.getAllVolumes().size() > 1) { throw new CloudRuntimeException(String.format("why the deleted vm[uuid:%s] has data volumes??? %s", self.getUuid(), JSONObjectUtil.toJsonString(inv.getAllVolumes()))); } VmInstanceSpec spec = buildSpecFromInventory(inv, VmOperation.Expunge); FlowChain chain = getExpungeVmWorkFlowChain(inv); setFlowMarshaller(chain); chain.setName(String.format("expunge-vm-%s", self.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); chain.getData().put(Params.DeletionPolicy, VmInstanceDeletionPolicy.Direct); chain.done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { dbf.removeCollection(self.getVmNics(), VmNicVO.class); dbf.remove(self); logger.debug(String.format("successfully expunged the vm[uuid:%s]", self.getUuid())); completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(final ErrorCode errCode, Map data) { completion.fail(errCode); } }).start(); } private void handle(final VmCheckOwnStateMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { refreshVO(); final VmCheckOwnStateReply reply = new VmCheckOwnStateReply(); if (self.getHostUuid() == null) { // no way to check bus.reply(msg, reply); chain.next(); return; } final CheckVmStateOnHypervisorMsg cmsg = new CheckVmStateOnHypervisorMsg(); cmsg.setVmInstanceUuids(list(self.getUuid())); cmsg.setHostUuid(self.getHostUuid()); bus.makeTargetServiceIdByResourceUuid(cmsg, HostConstant.SERVICE_ID, self.getHostUuid()); bus.send(cmsg, new CloudBusCallBack(msg, chain) { @Override public void run(MessageReply r) { if (!r.isSuccess()) { reply.setError(r.getError()); bus.reply(msg, r); chain.next(); return; } CheckVmStateOnHypervisorReply cr = r.castReply(); String s = cr.getStates().get(self.getUuid()); VmInstanceState state = VmInstanceState.valueOf(s); if (state != self.getState()) { VmStateChangedOnHostMsg vcmsg = new VmStateChangedOnHostMsg(); vcmsg.setHostUuid(self.getHostUuid()); vcmsg.setVmInstanceUuid(self.getUuid()); vcmsg.setStateOnHost(state); bus.makeTargetServiceIdByResourceUuid(vcmsg, VmInstanceConstant.SERVICE_ID, self.getUuid()); bus.send(vcmsg); } bus.reply(msg, reply); chain.next(); } }); } @Override public String getName() { return "check-state"; } }); } private void handle(final VmStateChangedOnHostMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { vmStateChangeOnHost(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("vm-%s-state-change-on-the-host-%s", self.getUuid(), msg.getHostUuid()); } }); } private VmAbnormalLifeCycleOperation getVmAbnormalLifeCycleOperation(String originalHostUuid, String currentHostUuid, VmInstanceState originalState, VmInstanceState currentState) { if (originalState == VmInstanceState.Stopped && currentState == VmInstanceState.Running) { return VmAbnormalLifeCycleOperation.VmRunningOnTheHost; } if (originalState == VmInstanceState.Running && currentState == VmInstanceState.Stopped && currentHostUuid.equals(originalHostUuid)) { return VmAbnormalLifeCycleOperation.VmStoppedOnTheSameHost; } if (VmInstanceState.intermediateStates.contains(originalState) && currentState == VmInstanceState.Running) { return VmAbnormalLifeCycleOperation.VmRunningFromIntermediateState; } if (VmInstanceState.intermediateStates.contains(originalState) && currentState == VmInstanceState.Stopped) { return VmAbnormalLifeCycleOperation.VmStoppedFromIntermediateState; } if (originalState == VmInstanceState.Running && currentState == VmInstanceState.Paused && currentHostUuid.equals(originalHostUuid)) { return VmAbnormalLifeCycleOperation.VmPausedFromRunningStateHostNotChanged; } if (originalState == VmInstanceState.Unknown && currentState == VmInstanceState.Paused && currentHostUuid.equals(originalHostUuid)) { return VmAbnormalLifeCycleOperation.VmPausedFromUnknownStateHostNotChanged; } if (originalState == VmInstanceState.Unknown && currentState == VmInstanceState.Running && currentHostUuid.equals(originalHostUuid)) { return VmAbnormalLifeCycleOperation.VmRunningFromUnknownStateHostNotChanged; } if (originalState == VmInstanceState.Unknown && currentState == VmInstanceState.Running && !currentHostUuid.equals(originalHostUuid)) { return VmAbnormalLifeCycleOperation.VmRunningFromUnknownStateHostChanged; } if (originalState == VmInstanceState.Unknown && currentState == VmInstanceState.Stopped && currentHostUuid.equals(originalHostUuid)) { return VmAbnormalLifeCycleOperation.VmStoppedOnTheSameHost; } if (originalState == VmInstanceState.Unknown && currentState == VmInstanceState.Stopped && originalHostUuid == null && currentHostUuid.equals(self.getLastHostUuid())) { return VmAbnormalLifeCycleOperation.VmStoppedFromUnknownStateHostNotChanged; } if (originalState == VmInstanceState.Running && originalState == currentState && !currentHostUuid.equals(originalHostUuid)) { return VmAbnormalLifeCycleOperation.VmMigrateToAnotherHost; } if (originalState == VmInstanceState.Paused && currentState == VmInstanceState.Running && currentHostUuid.equals(originalHostUuid)) { return VmAbnormalLifeCycleOperation.VmRunningFromPausedStateHostNotChanged; } if (originalState == VmInstanceState.Paused && currentState == VmInstanceState.Stopped && currentHostUuid.equals(originalHostUuid)) { return VmAbnormalLifeCycleOperation.VmStoppedFromPausedStateHostNotChanged; } throw new CloudRuntimeException(String.format("unknown VM[uuid:%s] abnormal state combination[original state: %s," + " current state: %s, original host:%s, current host:%s]", self.getUuid(), originalState, currentState, originalHostUuid, currentHostUuid)); } private void vmStateChangeOnHost(final VmStateChangedOnHostMsg msg, final NoErrorCompletion completion) { final VmStateChangedOnHostReply reply = new VmStateChangedOnHostReply(); if (refreshVO(true) == null) { // the vm has been deleted reply.setError(operr("the vm has been deleted")); bus.reply(msg, reply); completion.done(); return; } if (msg.getVmStateAtTracingMoment() != null) { // the vm tracer periodically reports vms's state. It catches an old state // before an vm operation(start, stop, reboot, migrate) completes. Ignore this VmInstanceState expected = VmInstanceState.valueOf(msg.getVmStateAtTracingMoment()); if (expected != self.getState()) { bus.reply(msg, reply); completion.done(); return; } } final String originalHostUuid = self.getHostUuid(); final String currentHostUuid = msg.getHostUuid(); final VmInstanceState originalState = self.getState(); final VmInstanceState currentState = VmInstanceState.valueOf(msg.getStateOnHost()); if (originalState == currentState && originalHostUuid != null && currentHostUuid.equals(originalHostUuid)) { logger.debug(String.format("vm[uuid:%s]'s state[%s] is inline with its state on the host[uuid:%s], ignore VmStateChangeOnHostMsg", self.getUuid(), originalState, originalHostUuid)); bus.reply(msg, reply); completion.done(); return; } if (originalState == VmInstanceState.Stopped && currentState == VmInstanceState.Unknown) { bus.reply(msg, reply); completion.done(); return; } final Runnable fireEvent = new Runnable() { @Override public void run() { VmTracerCanonicalEvents.VmStateChangedOnHostData data = new VmTracerCanonicalEvents.VmStateChangedOnHostData(); data.setVmUuid(self.getUuid()); data.setFrom(originalState); data.setTo(self.getState()); data.setOriginalHostUuid(originalHostUuid); data.setCurrentHostUuid(self.getHostUuid()); evtf.fire(VmTracerCanonicalEvents.VM_STATE_CHANGED_PATH, data); } }; if (currentState == VmInstanceState.Unknown) { changeVmStateInDb(VmInstanceStateEvent.unknown); fireEvent.run(); bus.reply(msg, reply); completion.done(); return; } VmAbnormalLifeCycleOperation operation = getVmAbnormalLifeCycleOperation(originalHostUuid, currentHostUuid, originalState, currentState); if (operation == VmAbnormalLifeCycleOperation.VmRunningFromUnknownStateHostNotChanged) { // the vm is detected on the host again. It's largely because the host disconnected before // and now reconnected self.setHostUuid(msg.getHostUuid()); changeVmStateInDb(VmInstanceStateEvent.running); fireEvent.run(); bus.reply(msg, reply); completion.done(); return; } else if (operation == VmAbnormalLifeCycleOperation.VmStoppedFromUnknownStateHostNotChanged) { // the vm comes out of the unknown state to the stopped state // it happens when an operation failure led the vm from the stopped state to the unknown state, // and later on the vm was detected as stopped on the host again self.setHostUuid(null); changeVmStateInDb(VmInstanceStateEvent.stopped); fireEvent.run(); bus.reply(msg, reply); completion.done(); return; } else if (operation == VmAbnormalLifeCycleOperation.VmStoppedFromPausedStateHostNotChanged) { self.setHostUuid(msg.getHostUuid()); changeVmStateInDb(VmInstanceStateEvent.stopped); fireEvent.run(); bus.reply(msg, reply); completion.done(); return; } else if (operation == VmAbnormalLifeCycleOperation.VmPausedFromUnknownStateHostNotChanged) { //some reason led vm to unknown state and the paused vm are detected on the host again self.setHostUuid(msg.getHostUuid()); changeVmStateInDb(VmInstanceStateEvent.paused); fireEvent.run(); bus.reply(msg, reply); completion.done(); return; } else if (operation == VmAbnormalLifeCycleOperation.VmPausedFromRunningStateHostNotChanged) { // just synchronize database self.setHostUuid(msg.getHostUuid()); changeVmStateInDb(VmInstanceStateEvent.paused); fireEvent.run(); bus.reply(msg, reply); completion.done(); return; } else if (operation == VmAbnormalLifeCycleOperation.VmRunningFromPausedStateHostNotChanged) { // just synchronize database self.setHostUuid(msg.getHostUuid()); changeVmStateInDb(VmInstanceStateEvent.running); fireEvent.run(); bus.reply(msg, reply); completion.done(); return; } List<VmAbnormalLifeCycleExtensionPoint> exts = pluginRgty.getExtensionList(VmAbnormalLifeCycleExtensionPoint.class); VmAbnormalLifeCycleStruct struct = new VmAbnormalLifeCycleStruct(); struct.setCurrentHostUuid(currentHostUuid); struct.setCurrentState(currentState); struct.setOriginalHostUuid(originalHostUuid); struct.setOriginalState(originalState); struct.setVmInstance(getSelfInventory()); struct.setOperation(operation); logger.debug(String.format("the vm[uuid:%s]'s state changed abnormally on the host[uuid:%s]," + " ZStack is going to take the operation[%s]," + "[original state: %s, current state: %s, original host: %s, current host:%s]", self.getUuid(), currentHostUuid, operation, originalState, currentState, originalHostUuid, currentHostUuid)); FlowChain chain = FlowChainBuilder.newSimpleFlowChain(); chain.setName(String.format("handle-abnormal-lifecycle-of-vm-%s", self.getUuid())); chain.getData().put(Params.AbnormalLifeCycleStruct, struct); chain.allowEmptyFlow(); for (VmAbnormalLifeCycleExtensionPoint ext : exts) { Flow flow = ext.createVmAbnormalLifeCycleHandlingFlow(struct); chain.then(flow); } chain.done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { if (currentState == VmInstanceState.Running) { self.setHostUuid(currentHostUuid); changeVmStateInDb(VmInstanceStateEvent.running); } else if (currentState == VmInstanceState.Stopped) { self.setHostUuid(null); changeVmStateInDb(VmInstanceStateEvent.stopped); } fireEvent.run(); bus.reply(msg, reply); completion.done(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(ErrorCode errCode, Map data) { //TODO logger.warn(String.format("failed to handle abnormal lifecycle of the vm[uuid:%s, original state: %s, current state:%s," + "original host: %s, current host: %s], %s", self.getUuid(), originalState, currentState, originalHostUuid, currentHostUuid, errCode)); reply.setError(errCode); bus.reply(msg, reply); completion.done(); } }).start(); } private String buildUserdata() { return new UserdataBuilder().buildByVmUuid(self.getUuid()); } private void handle(final DetachNicFromVmMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { final DetachNicFromVmReply reply = new DetachNicFromVmReply(); refreshVO(); if (self.getState() == VmInstanceState.Destroyed) { // the cascade framework may send this message when // the vm has been destroyed VmNicVO nic = CollectionUtils.find(self.getVmNics(), new Function<VmNicVO, VmNicVO>() { @Override public VmNicVO call(VmNicVO arg) { return msg.getVmNicUuid().equals(arg.getUuid()) ? arg : null; } }); if (nic != null) { dbf.remove(nic); } bus.reply(msg, reply); chain.next(); return; } final ErrorCode allowed = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (allowed != null) { reply.setError(allowed); bus.reply(msg, reply); chain.next(); return; } detachNic(msg.getVmNicUuid(), new Completion(msg, chain) { @Override public void success() { bus.reply(msg, reply); chain.next(); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); chain.next(); } }); } @Override public String getName() { return "detach-nic"; } }); } private void handle(final LockVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { logger.debug(String.format("locked vm[uuid:%s] for %s", self.getUuid(), msg.getReason())); evtf.on(LockResourceMessage.UNLOCK_CANONICAL_EVENT_PATH, new AutoOffEventCallback() { @Override public boolean run(Map tokens, Object data) { if (msg.getUnlockKey().equals(data)) { logger.debug(String.format("unlocked vm[uuid:%s] that was locked by %s", self.getUuid(), msg.getReason())); chain.next(); return true; } return false; } }); LockVmInstanceReply reply = new LockVmInstanceReply(); bus.reply(msg, reply); } @Override public String getName() { return String.format("lock-vm-%s", self.getUuid()); } }); } private void handle(final ChangeVmMetaDataMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { changeMetaData(msg); chain.next(); } @Override public String getName() { return String.format("change-meta-data-of-vm-%s", self.getUuid()); } }); } private void changeMetaData(ChangeVmMetaDataMsg msg) { ChangeVmMetaDataReply reply = new ChangeVmMetaDataReply(); refreshVO(); if (self == null) { bus.reply(msg, reply); return; } AtomicVmState s = msg.getState(); AtomicHostUuid h = msg.getHostUuid(); if (msg.isNeedHostAndStateBothMatch()) { if (s != null && h != null && s.getExpected() == self.getState()) { if ((h.getExpected() == null && self.getHostUuid() == null) || (h.getExpected() != null && h.getExpected().equals(self.getHostUuid()))) { changeVmStateInDb(s.getValue().getDrivenEvent()); reply.setChangeStateDone(true); self.setHostUuid(h.getValue()); dbf.update(self); reply.setChangeHostUuidDone(true); } } } else { if (s != null && s.getExpected() == self.getState()) { changeVmStateInDb(s.getValue().getDrivenEvent()); reply.setChangeStateDone(true); } if (h != null) { if ((h.getExpected() == null && self.getHostUuid() == null) || (h.getExpected() != null && h.getExpected().equals(self.getHostUuid()))) { self.setHostUuid(h.getValue()); dbf.update(self); reply.setChangeHostUuidDone(true); } } } bus.reply(msg, reply); } private void getVmMigrationTargetHost(Message msg, final ReturnValueCompletion<List<HostInventory>> completion) { refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), VmErrors.MIGRATE_ERROR); if (allowed != null) { completion.fail(allowed); return; } if (self.getVmNics().size() == 0) { completion.fail(operr("cannot get target migration host without any nics on vm")); return; } final DesignatedAllocateHostMsg amsg = new DesignatedAllocateHostMsg(); amsg.setCpuCapacity(self.getCpuNum()); amsg.setMemoryCapacity(self.getMemorySize()); amsg.getAvoidHostUuids().add(self.getHostUuid()); if (msg instanceof GetVmMigrationTargetHostMsg) { GetVmMigrationTargetHostMsg gmsg = (GetVmMigrationTargetHostMsg) msg; if (gmsg.getAvoidHostUuids() != null) { amsg.getAvoidHostUuids().addAll(gmsg.getAvoidHostUuids()); } } amsg.setVmInstance(VmInstanceInventory.valueOf(self)); amsg.setServiceId(bus.makeLocalServiceId(HostAllocatorConstant.SERVICE_ID)); amsg.setAllocatorStrategy(HostAllocatorConstant.MIGRATE_VM_ALLOCATOR_TYPE); amsg.setVmOperation(VmOperation.Migrate.toString()); amsg.setL3NetworkUuids(CollectionUtils.transformToList(self.getVmNics(), new Function<String, VmNicVO>() { @Override public String call(VmNicVO arg) { return arg.getL3NetworkUuid(); } })); amsg.setDryRun(true); amsg.setAllowNoL3Networks(true); bus.send(amsg, new CloudBusCallBack(completion) { @Override public void run(MessageReply re) { if (!re.isSuccess()) { if (HostAllocatorError.NO_AVAILABLE_HOST.toString().equals(re.getError().getCode())) { completion.success(new ArrayList<HostInventory>()); } else { completion.fail(re.getError()); } } else { completion.success(((AllocateHostDryRunReply) re).getHosts()); } } }); } private void handle(final GetVmMigrationTargetHostMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { final GetVmMigrationTargetHostReply reply = new GetVmMigrationTargetHostReply(); getVmMigrationTargetHost(msg, new ReturnValueCompletion<List<HostInventory>>(msg, chain) { @Override public void success(List<HostInventory> returnValue) { reply.setHosts(returnValue); bus.reply(msg, reply); chain.next(); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); chain.next(); } }); } @Override public String getName() { return String.format("get-migration-target-host-for-vm-%s", self.getUuid()); } }); } private void handle(final AttachDataVolumeToVmMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { attachDataVolume(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("attach-volume-%s-to-vm-%s", msg.getVolume().getUuid(), msg.getVmInstanceUuid()); } }); } private void handle(final DetachDataVolumeFromVmMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { detachVolume(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return String.format("detach-volume-%s-from-vm-%s", msg.getVolume().getUuid(), msg.getVmInstanceUuid()); } }); } private void handle(final MigrateVmMsg msg) { final MigrateVmReply reply = new MigrateVmReply(); thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { migrateVm(msg, new Completion(chain) { @Override public void success() { bus.reply(msg, reply); chain.next(); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); chain.next(); } }); } @Override public String getName() { return String.format("migrate-vm-%s", self.getUuid()); } }); } private void attachNic(final Message msg, final String l3Uuid, final ReturnValueCompletion<VmNicInventory> completion) { thdf.chainSubmit(new ChainTask(completion) { @Override public String getSyncSignature() { return syncThreadName; } @Override @Deferred public void run(final SyncTaskChain chain) { refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (allowed != null) { completion.fail(allowed); return; } class SetDefaultL3Network { private boolean isSet = false; void set() { if (self.getDefaultL3NetworkUuid() == null) { self.setDefaultL3NetworkUuid(l3Uuid); self = dbf.updateAndRefresh(self); isSet = true; } } void rollback() { if (isSet) { self.setDefaultL3NetworkUuid(null); dbf.update(self); } } } class SetStaticIp { private boolean isSet = false; void set() { if (!(msg instanceof APIAttachL3NetworkToVmMsg)) { return; } APIAttachL3NetworkToVmMsg amsg = (APIAttachL3NetworkToVmMsg) msg; if (amsg.getStaticIp() == null) { return; } new StaticIpOperator().setStaticIp(self.getUuid(), amsg.getL3NetworkUuid(), amsg.getStaticIp()); isSet = true; } void rollback() { if (isSet) { APIAttachL3NetworkToVmMsg amsg = (APIAttachL3NetworkToVmMsg) msg; new StaticIpOperator().deleteStaticIpByVmUuidAndL3Uuid(self.getUuid(), amsg.getL3NetworkUuid()); } } } final SetDefaultL3Network setDefaultL3Network = new SetDefaultL3Network(); setDefaultL3Network.set(); Defer.guard(new Runnable() { @Override public void run() { setDefaultL3Network.rollback(); } }); final SetStaticIp setStaticIp = new SetStaticIp(); setStaticIp.set(); Defer.guard(new Runnable() { @Override public void run() { setStaticIp.rollback(); } }); final VmInstanceSpec spec = buildSpecFromInventory(getSelfInventory(), VmOperation.AttachNic); spec.setVmInventory(VmInstanceInventory.valueOf(self)); L3NetworkVO l3vo = dbf.findByUuid(l3Uuid, L3NetworkVO.class); final L3NetworkInventory l3 = L3NetworkInventory.valueOf(l3vo); final VmInstanceInventory vm = getSelfInventory(); for (VmPreAttachL3NetworkExtensionPoint ext : pluginRgty.getExtensionList(VmPreAttachL3NetworkExtensionPoint.class)) { ext.vmPreAttachL3Network(vm, l3); } spec.setL3Networks(list(l3)); spec.setDestNics(new ArrayList<VmNicInventory>()); CollectionUtils.safeForEach(pluginRgty.getExtensionList(VmBeforeAttachL3NetworkExtensionPoint.class), new ForEachFunction<VmBeforeAttachL3NetworkExtensionPoint>() { @Override public void run(VmBeforeAttachL3NetworkExtensionPoint arg) { arg.vmBeforeAttachL3Network(vm, l3); } }); FlowChain flowChain = FlowChainBuilder.newSimpleFlowChain(); setFlowMarshaller(flowChain); flowChain.setName(String.format("attachNic-vm-%s-l3-%s", self.getUuid(), l3Uuid)); flowChain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); flowChain.then(new VmAllocateNicFlow()); flowChain.then(new VmSetDefaultL3NetworkOnAttachingFlow()); if (self.getState() == VmInstanceState.Running) { flowChain.then(new VmInstantiateResourceOnAttachingNicFlow()); flowChain.then(new VmAttachNicOnHypervisorFlow()); } flowChain.done(new FlowDoneHandler(chain) { @Override public void handle(Map data) { CollectionUtils.safeForEach(pluginRgty.getExtensionList(VmAfterAttachL3NetworkExtensionPoint.class), new ForEachFunction<VmAfterAttachL3NetworkExtensionPoint>() { @Override public void run(VmAfterAttachL3NetworkExtensionPoint arg) { arg.vmAfterAttachL3Network(vm, l3); } }); VmNicInventory nic = spec.getDestNics().get(0); completion.success(nic); chain.next(); } }).error(new FlowErrorHandler(chain) { @Override public void handle(final ErrorCode errCode, Map data) { CollectionUtils.safeForEach(pluginRgty.getExtensionList(VmFailToAttachL3NetworkExtensionPoint.class), new ForEachFunction<VmFailToAttachL3NetworkExtensionPoint>() { @Override public void run(VmFailToAttachL3NetworkExtensionPoint arg) { arg.vmFailToAttachL3Network(vm, l3, errCode); } }); setDefaultL3Network.rollback(); setStaticIp.rollback(); completion.fail(errCode); chain.next(); } }).start(); } @Override public String getName() { return String.format("attachNic-vm-%s-l3-%s", self.getUuid(), l3Uuid); } }); } private void handle(final VmAttachNicMsg msg) { final VmAttachNicReply reply = new VmAttachNicReply(); attachNic(msg, msg.getL3NetworkUuid(), new ReturnValueCompletion<VmNicInventory>(msg) { @Override public void success(VmNicInventory nic) { reply.setInventroy(nic); bus.reply(msg, reply); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); } }); } protected void doDestroy(final VmInstanceDeletionPolicy deletionPolicy, final Completion completion) { final VmInstanceInventory inv = VmInstanceInventory.valueOf(self); extEmitter.beforeDestroyVm(inv); destroy(deletionPolicy, new Completion(completion) { @Override public void success() { extEmitter.afterDestroyVm(inv); logger.debug(String.format("successfully deleted vm instance[name:%s, uuid:%s]", self.getName(), self.getUuid())); if (deletionPolicy == VmInstanceDeletionPolicy.Direct || deletionPolicy == VmInstanceDeletionPolicy.DBOnly) { dbf.remove(getSelf()); } else if (deletionPolicy == VmInstanceDeletionPolicy.Delay) { self = dbf.reload(self); self.setHostUuid(null); changeVmStateInDb(VmInstanceStateEvent.destroyed); } else if (deletionPolicy == VmInstanceDeletionPolicy.Never) { logger.warn(String.format("the vm[uuid:%s] is deleted, but by it's deletion policy[Never]," + " the root volume is not deleted on the primary storage", self.getUuid())); self = dbf.reload(self); self.setHostUuid(null); changeVmStateInDb(VmInstanceStateEvent.destroyed); } completion.success(); } @Override public void fail(ErrorCode errorCode) { extEmitter.failedToDestroyVm(inv, errorCode); logger.debug(String.format("failed to delete vm instance[name:%s, uuid:%s], because %s", self.getName(), self.getUuid(), errorCode)); completion.fail(errorCode); } }); } private VmInstanceDeletionPolicy getVmDeletionPolicy(final VmInstanceDeletionMsg msg) { if (self.getState() == VmInstanceState.Created) { return VmInstanceDeletionPolicy.DBOnly; } return msg.getDeletionPolicy() == null ? deletionPolicyMgr.getDeletionPolicy(self.getUuid()) : VmInstanceDeletionPolicy.valueOf(msg.getDeletionPolicy()); } private void handle(final VmInstanceDeletionMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { final VmInstanceDeletionReply r = new VmInstanceDeletionReply(); final VmInstanceDeletionPolicy deletionPolicy = getVmDeletionPolicy(msg); self = dbf.findByUuid(self.getUuid(), VmInstanceVO.class); if (self == null || self.getState() == VmInstanceState.Destroyed) { // the vm has been destroyed, most likely by rollback if (deletionPolicy != VmInstanceDeletionPolicy.DBOnly) { bus.reply(msg, r); chain.next(); return; } } destroyHook(deletionPolicy, new Completion(msg, chain) { @Override public void success() { bus.reply(msg, r); chain.next(); } @Override public void fail(ErrorCode errorCode) { r.setError(errorCode); bus.reply(msg, r); chain.next(); } }); } @Override public String getName() { return "delete-vm"; } }); } protected void destroyHook(VmInstanceDeletionPolicy deletionPolicy, Completion completion) { doDestroy(deletionPolicy, completion); } private void handle(final RebootVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getName() { return String.format("reboot-vm-%s", self.getUuid()); } @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { rebootVm(msg, chain); } }); } private void rebootVm(final RebootVmInstanceMsg msg, final SyncTaskChain chain) { rebootVm(msg, new Completion(chain) { @Override public void success() { RebootVmInstanceReply reply = new RebootVmInstanceReply(); VmInstanceInventory inv = VmInstanceInventory.valueOf(self); reply.setInventory(inv); bus.reply(msg, reply); chain.next(); } @Override public void fail(ErrorCode errorCode) { RebootVmInstanceReply reply = new RebootVmInstanceReply(); reply.setError(errf.instantiateErrorCode(VmErrors.REBOOT_ERROR, errorCode)); bus.reply(msg, reply); chain.next(); } }); } private void handle(final StopVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getName() { return String.format("stop-vm-%s", self.getUuid()); } @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { stopVm(msg, chain); } }); } private void stopVm(final StopVmInstanceMsg msg, final SyncTaskChain chain) { stopVm(msg, new Completion(chain) { @Override public void success() { StopVmInstanceReply reply = new StopVmInstanceReply(); VmInstanceInventory inv = VmInstanceInventory.valueOf(self); reply.setInventory(inv); bus.reply(msg, reply); chain.next(); } @Override public void fail(ErrorCode errorCode) { StopVmInstanceReply reply = new StopVmInstanceReply(); reply.setError(errf.instantiateErrorCode(VmErrors.STOP_ERROR, errorCode)); bus.reply(msg, reply); chain.next(); } }); } private void handle(final StartVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getName() { return String.format("start-vm-%s", self.getUuid()); } @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { startVm(msg, chain); } }); } private void createTemplateFromRootVolume(final CreateTemplateFromVmRootVolumeMsg msg, final SyncTaskChain chain) { boolean callNext = true; try { refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (allowed != null) { bus.replyErrorByMessageType(msg, allowed); return; } final CreateTemplateFromVmRootVolumeReply reply = new CreateTemplateFromVmRootVolumeReply(); CreateTemplateFromVolumeOnPrimaryStorageMsg cmsg = new CreateTemplateFromVolumeOnPrimaryStorageMsg(); cmsg.setVolumeInventory(msg.getRootVolumeInventory()); cmsg.setBackupStorageUuid(msg.getBackupStorageUuid()); cmsg.setImageInventory(msg.getImageInventory()); bus.makeTargetServiceIdByResourceUuid(cmsg, PrimaryStorageConstant.SERVICE_ID, msg.getRootVolumeInventory().getPrimaryStorageUuid()); bus.send(cmsg, new CloudBusCallBack(chain) { private void fail(ErrorCode errorCode) { String err = String.format("failed to create template from root volume[uuid:%s] on primary storage[uuid:%s]", msg.getRootVolumeInventory().getUuid(), msg.getRootVolumeInventory().getPrimaryStorageUuid()); logger.warn(err); reply.setError(errf.instantiateErrorCode(SysErrors.OPERATION_ERROR, err, errorCode)); bus.reply(msg, reply); } @Override public void run(MessageReply r) { if (!r.isSuccess()) { fail(r.getError()); } else { CreateTemplateFromVolumeOnPrimaryStorageReply creply = (CreateTemplateFromVolumeOnPrimaryStorageReply) r; reply.setInstallPath(creply.getTemplateBackupStorageInstallPath()); reply.setFormat(creply.getFormat()); bus.reply(msg, reply); } chain.next(); } }); callNext = false; } finally { if (callNext) { chain.next(); } } } private void handle(final CreateTemplateFromVmRootVolumeMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getName() { return String.format("create-template-from-%s", self.getUuid()); } @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { createTemplateFromRootVolume(msg, chain); } }); } private void handle(final AttachNicToVmMsg msg) { ErrorCode allowed = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (allowed != null) { bus.replyErrorByMessageType(msg, allowed); return; } AttachNicToVmOnHypervisorMsg amsg = new AttachNicToVmOnHypervisorMsg(); amsg.setVmUuid(self.getUuid()); amsg.setHostUuid(self.getHostUuid()); amsg.setNics(msg.getNics()); bus.makeTargetServiceIdByResourceUuid(amsg, HostConstant.SERVICE_ID, self.getHostUuid()); bus.send(amsg, new CloudBusCallBack(msg) { @Override public void run(MessageReply reply) { if (self.getDefaultL3NetworkUuid() == null) { self.setDefaultL3NetworkUuid(msg.getNics().get(0).getL3NetworkUuid()); self = dbf.updateAndRefresh(self); logger.debug(String.format("set the VM[uuid: %s]'s default L3 network[uuid:%s], as it doen't have one before", self.getUuid(), self.getDefaultL3NetworkUuid())); } AttachNicToVmReply r = new AttachNicToVmReply(); if (!reply.isSuccess()) { r.setError(errf.instantiateErrorCode(VmErrors.ATTACH_NETWORK_ERROR, r.getError())); } bus.reply(msg, r); } }); } private void handle(final DestroyVmInstanceMsg msg) { final DestroyVmInstanceReply reply = new DestroyVmInstanceReply(); final String issuer = VmInstanceVO.class.getSimpleName(); VmDeletionStruct s = new VmDeletionStruct(); s.setDeletionPolicy(deletionPolicyMgr.getDeletionPolicy(self.getUuid())); s.setInventory(getSelfInventory()); final List<VmDeletionStruct> ctx = list(s); final FlowChain chain = FlowChainBuilder.newSimpleFlowChain(); chain.setName(String.format("destory-vm-%s", self.getUuid())); chain.then(new NoRollbackFlow() { @Override public void run(final FlowTrigger trigger, Map data) { casf.asyncCascade(CascadeConstant.DELETION_FORCE_DELETE_CODE, issuer, ctx, new Completion(trigger) { @Override public void success() { trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }).done(new FlowDoneHandler(msg) { @Override public void handle(Map data) { casf.asyncCascadeFull(CascadeConstant.DELETION_CLEANUP_CODE, issuer, ctx, new NopeCompletion()); bus.reply(msg, reply); } }).error(new FlowErrorHandler(msg) { @Override public void handle(final ErrorCode errCode, Map data) { reply.setError(errCode); bus.reply(msg, reply); } }).start(); } protected void handle(final ChangeVmStateMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getName() { return String.format("change-vm-state-%s", self.getUuid()); } @Override public String getSyncSignature() { return syncThreadName; } @Override @Deferred public void run(SyncTaskChain chain) { refreshVO(); Defer.defer(new Runnable() { @Override public void run() { ChangeVmStateReply reply = new ChangeVmStateReply(); bus.reply(msg, reply); } }); if (self == null) { // vm has been deleted by previous request // this happens when delete vm request queued before // change state request from vm tracer. // in this case, ignore change state request logger.debug(String.format("vm[uuid:%s] has been deleted, ignore change vm state request from vm tracer", msg.getVmInstanceUuid())); chain.next(); return; } changeVmStateInDb(VmInstanceStateEvent.valueOf(msg.getStateEvent())); chain.next(); } }); } protected void setFlowMarshaller(FlowChain chain) { chain.setFlowMarshaller(new FlowMarshaller() { @Override public Flow marshalTheNextFlow(String previousFlowClassName, String nextFlowClassName, FlowChain chain, Map data) { Flow nflow = null; for (MarshalVmOperationFlowExtensionPoint mext : pluginRgty.getExtensionList(MarshalVmOperationFlowExtensionPoint.class)) { VmInstanceSpec spec = (VmInstanceSpec) data.get(VmInstanceConstant.Params.VmInstanceSpec.toString()); nflow = mext.marshalVmOperationFlow(previousFlowClassName, nextFlowClassName, chain, spec); if (nflow != null) { logger.debug(String.format("a VM[uuid: %s, operation: %s] operation flow[%s] is changed to the flow[%s] by %s", self.getUuid(), spec.getCurrentVmOperation(), nextFlowClassName, nflow.getClass(), mext.getClass())); break; } } return nflow; } }); } protected void selectBootOrder(VmInstanceSpec spec) { if (spec.getCurrentVmOperation() == null) { throw new CloudRuntimeException("selectBootOrder must be called after VmOperation is set"); } if (spec.getCurrentVmOperation() == VmOperation.NewCreate && spec.getDestIso() != null) { spec.setBootOrders(list(VmBootDevice.CdRom.toString())); } else { String order = VmSystemTags.BOOT_ORDER.getTokenByResourceUuid(self.getUuid(), VmSystemTags.BOOT_ORDER_TOKEN); if (order == null) { spec.setBootOrders(list(VmBootDevice.HardDisk.toString())); } else { spec.setBootOrders(list(order.split(","))); } } } protected void startVmFromNewCreate(final StartNewCreatedVmInstanceMsg msg, final SyncTaskChain taskChain) { refreshVO(); ErrorCode error = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (error != null) { throw new OperationFailureException(error); } error = extEmitter.preStartNewCreatedVm(msg.getVmInstanceInventory()); if (error != null) { throw new OperationFailureException(error); } StartNewCreatedVmInstanceReply reply = new StartNewCreatedVmInstanceReply(); startVmFromNewCreate(StartVmFromNewCreatedStruct.fromMessage(msg), new Completion(msg, taskChain) { @Override public void success() { self = dbf.reload(self); reply.setVmInventory(getSelfInventory()); bus.reply(msg, reply); taskChain.next(); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); taskChain.next(); } }); } protected void handle(final StartNewCreatedVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getName() { return String.format("create-vm-%s", self.getUuid()); } @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { startVmFromNewCreate(msg, chain); } }); } protected void handleApiMessage(APIMessage msg) { if (msg instanceof APIStopVmInstanceMsg) { handle((APIStopVmInstanceMsg) msg); } else if (msg instanceof APICreateStopVmInstanceSchedulerMsg) { handle((APICreateStopVmInstanceSchedulerMsg) msg); } else if (msg instanceof APIRebootVmInstanceMsg) { handle((APIRebootVmInstanceMsg) msg); } else if (msg instanceof APICreateRebootVmInstanceSchedulerMsg) { handle((APICreateRebootVmInstanceSchedulerMsg) msg); } else if (msg instanceof APIDestroyVmInstanceMsg) { handle((APIDestroyVmInstanceMsg) msg); } else if (msg instanceof APIStartVmInstanceMsg) { handle((APIStartVmInstanceMsg) msg); } else if (msg instanceof APICreateStartVmInstanceSchedulerMsg) { handle((APICreateStartVmInstanceSchedulerMsg) msg); } else if (msg instanceof APIMigrateVmMsg) { handle((APIMigrateVmMsg) msg); } else if (msg instanceof APIAttachL3NetworkToVmMsg) { handle((APIAttachL3NetworkToVmMsg) msg); } else if (msg instanceof APIGetVmMigrationCandidateHostsMsg) { handle((APIGetVmMigrationCandidateHostsMsg) msg); } else if (msg instanceof APIGetVmAttachableDataVolumeMsg) { handle((APIGetVmAttachableDataVolumeMsg) msg); } else if (msg instanceof APIUpdateVmInstanceMsg) { handle((APIUpdateVmInstanceMsg) msg); } else if (msg instanceof APIChangeInstanceOfferingMsg) { handle((APIChangeInstanceOfferingMsg) msg); } else if (msg instanceof APIDetachL3NetworkFromVmMsg) { handle((APIDetachL3NetworkFromVmMsg) msg); } else if (msg instanceof APIGetVmAttachableL3NetworkMsg) { handle((APIGetVmAttachableL3NetworkMsg) msg); } else if (msg instanceof APIAttachIsoToVmInstanceMsg) { handle((APIAttachIsoToVmInstanceMsg) msg); } else if (msg instanceof APIDetachIsoFromVmInstanceMsg) { handle((APIDetachIsoFromVmInstanceMsg) msg); } else if (msg instanceof APIExpungeVmInstanceMsg) { handle((APIExpungeVmInstanceMsg) msg); } else if (msg instanceof APIRecoverVmInstanceMsg) { handle((APIRecoverVmInstanceMsg) msg); } else if (msg instanceof APISetVmBootOrderMsg) { handle((APISetVmBootOrderMsg) msg); } else if (msg instanceof APISetVmConsolePasswordMsg) { handle((APISetVmConsolePasswordMsg) msg); } else if (msg instanceof APIGetVmBootOrderMsg) { handle((APIGetVmBootOrderMsg) msg); } else if (msg instanceof APIDeleteVmConsolePasswordMsg) { handle((APIDeleteVmConsolePasswordMsg) msg); } else if (msg instanceof APIGetVmConsolePasswordMsg) { handle((APIGetVmConsolePasswordMsg) msg); } else if (msg instanceof APIGetVmConsoleAddressMsg) { handle((APIGetVmConsoleAddressMsg) msg); } else if (msg instanceof APISetVmHostnameMsg) { handle((APISetVmHostnameMsg) msg); } else if (msg instanceof APIDeleteVmHostnameMsg) { handle((APIDeleteVmHostnameMsg) msg); } else if (msg instanceof APISetVmStaticIpMsg) { handle((APISetVmStaticIpMsg) msg); } else if (msg instanceof APIDeleteVmStaticIpMsg) { handle((APIDeleteVmStaticIpMsg) msg); } else if (msg instanceof APIGetVmHostnameMsg) { handle((APIGetVmHostnameMsg) msg); } else if (msg instanceof APIGetVmStartingCandidateClustersHostsMsg) { handle((APIGetVmStartingCandidateClustersHostsMsg) msg); } else if (msg instanceof APIGetVmCapabilitiesMsg) { handle((APIGetVmCapabilitiesMsg) msg); } else if (msg instanceof APISetVmSshKeyMsg) { handle((APISetVmSshKeyMsg) msg); } else if (msg instanceof APIGetVmSshKeyMsg) { handle((APIGetVmSshKeyMsg) msg); } else if (msg instanceof APIDeleteVmSshKeyMsg) { handle((APIDeleteVmSshKeyMsg) msg); } else if (msg instanceof APIGetCandidateIsoForAttachingVmMsg) { handle((APIGetCandidateIsoForAttachingVmMsg) msg); } else if (msg instanceof APIPauseVmInstanceMsg) { handle((APIPauseVmInstanceMsg) msg); } else if (msg instanceof APIResumeVmInstanceMsg) { handle((APIResumeVmInstanceMsg) msg); } else if (msg instanceof APIReimageVmInstanceMsg) { handle((APIReimageVmInstanceMsg) msg); } else { VmInstanceBaseExtensionFactory ext = vmMgr.getVmInstanceBaseExtensionFactory(msg); if (ext != null) { VmInstance v = ext.getVmInstance(self); v.handleMessage(msg); } else { bus.dealWithUnknownMessage(msg); } } } @Transactional(readOnly = true) private void handle(APIGetCandidateIsoForAttachingVmMsg msg) { APIGetCandidateIsoForAttachingVmReply reply = new APIGetCandidateIsoForAttachingVmReply(); if (self.getState() != VmInstanceState.Running && self.getState() != VmInstanceState.Stopped) { reply.setInventories(new ArrayList<>()); bus.reply(msg, reply); return; } String psUuid = getSelfInventory().getRootVolume().getPrimaryStorageUuid(); PrimaryStorageVO ps = dbf.getEntityManager().find(PrimaryStorageVO.class, psUuid); PrimaryStorageType psType = PrimaryStorageType.valueOf(ps.getType()); List<String> bsUuids = psType.findBackupStorage(psUuid); if (bsUuids == null) { String sql = "select img" + " from ImageVO img, ImageBackupStorageRefVO ref, BackupStorageVO bs" + " where ref.imageUuid = img.uuid" + " and img.mediaType = :imgType" + " and img.status = :status" + " and bs.uuid = ref.backupStorageUuid" + " and bs.type in (:bsTypes)"; TypedQuery<ImageVO> q = dbf.getEntityManager().createQuery(sql, ImageVO.class); q.setParameter("imgType", ImageMediaType.ISO); q.setParameter("status", ImageStatus.Ready); q.setParameter("bsTypes", hostAllocatorMgr.getBackupStorageTypesByPrimaryStorageTypeFromMetrics(ps.getType())); reply.setInventories(ImageInventory.valueOf(q.getResultList())); } else if (!bsUuids.isEmpty()) { String sql = "select img" + " from ImageVO img, ImageBackupStorageRefVO ref, BackupStorageVO bs" + " where ref.imageUuid = img.uuid" + " and img.mediaType = :imgType" + " and img.status = :status" + " and bs.uuid = ref.backupStorageUuid" + " and bs.uuid in (:bsUuids)"; TypedQuery<ImageVO> q = dbf.getEntityManager().createQuery(sql, ImageVO.class); q.setParameter("imgType", ImageMediaType.ISO); q.setParameter("status", ImageStatus.Ready); q.setParameter("bsUuids", bsUuids); reply.setInventories(ImageInventory.valueOf(q.getResultList())); } else { reply.setInventories(new ArrayList<>()); } bus.reply(msg, reply); } private void handle(APIGetVmCapabilitiesMsg msg) { APIGetVmCapabilitiesReply reply = new APIGetVmCapabilitiesReply(); Map<String, Object> ret = new HashMap<>(); checkPrimaryStorageCapabilities(ret); checkImageMediaTypeCapabilities(ret); reply.setCapabilities(ret); bus.reply(msg, reply); } private void checkPrimaryStorageCapabilities(Map<String, Object> ret) { VolumeInventory rootVolume = getSelfInventory().getRootVolume(); if (rootVolume == null) { ret.put(Capability.LiveMigration.toString(), false); ret.put(Capability.VolumeMigration.toString(), false); } else { SimpleQuery<PrimaryStorageVO> q = dbf.createQuery(PrimaryStorageVO.class); q.select(PrimaryStorageVO_.type); q.add(PrimaryStorageVO_.uuid, Op.EQ, rootVolume.getPrimaryStorageUuid()); String type = q.findValue(); PrimaryStorageType psType = PrimaryStorageType.valueOf(type); ret.put(Capability.LiveMigration.toString(), psType.isSupportVmLiveMigration()); ret.put(Capability.VolumeMigration.toString(), psType.isSupportVolumeMigration()); } } private void checkImageMediaTypeCapabilities(Map<String, Object> ret) { ImageVO vo = null; ImageMediaType imageMediaType; if (self.getImageUuid() != null) { vo = dbf.findByUuid(self.getImageUuid(), ImageVO.class); } if (vo == null) { imageMediaType = null; } else { imageMediaType = vo.getMediaType(); } if (imageMediaType == ImageMediaType.ISO || imageMediaType == null) { ret.put(Capability.Reimage.toString(), false); } else { ret.put(Capability.Reimage.toString(), true); } } private void handle(APIGetVmHostnameMsg msg) { String hostname = VmSystemTags.HOSTNAME.getTokenByResourceUuid(self.getUuid(), VmSystemTags.HOSTNAME_TOKEN); APIGetVmHostnameReply reply = new APIGetVmHostnameReply(); reply.setHostname(hostname); bus.reply(msg, reply); } private void handle(final APIDeleteVmStaticIpMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { APIDeleteVmStaticIpEvent evt = new APIDeleteVmStaticIpEvent(msg.getId()); new StaticIpOperator().deleteStaticIpByVmUuidAndL3Uuid(self.getUuid(), msg.getL3NetworkUuid()); bus.publish(evt); chain.next(); } @Override public String getName() { return "delete-static-ip"; } }); } private void handle(final APISetVmStaticIpMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { setStaticIp(msg, new NoErrorCompletion(msg, chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return "set-static-ip"; } }); } private void setStaticIp(final APISetVmStaticIpMsg msg, final NoErrorCompletion completion) { refreshVO(); ErrorCode error = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (error != null) { throw new OperationFailureException(error); } final APISetVmStaticIpEvent evt = new APISetVmStaticIpEvent(msg.getId()); changeVmIp(msg.getL3NetworkUuid(), msg.getIp(), new Completion(msg, completion) { @Override public void success() { new StaticIpOperator().setStaticIp(self.getUuid(), msg.getL3NetworkUuid(), msg.getIp()); bus.publish(evt); completion.done(); } @Override public void fail(ErrorCode errorCode) { evt.setError(errorCode); bus.publish(evt); completion.done(); } }); } private void handle(APIDeleteVmHostnameMsg msg) { APIDeleteVmHostnameEvent evt = new APIDeleteVmHostnameEvent(msg.getId()); VmSystemTags.HOSTNAME.delete(self.getUuid()); bus.publish(evt); } private void handle(APISetVmHostnameMsg msg) { if (!VmSystemTags.HOSTNAME.hasTag(self.getUuid())) { SystemTagCreator creator = VmSystemTags.HOSTNAME.newSystemTagCreator(self.getUuid()); creator.setTagByTokens(map( e(VmSystemTags.HOSTNAME_TOKEN, msg.getHostname()) )); creator.create(); } else { VmSystemTags.HOSTNAME.update(self.getUuid(), VmSystemTags.HOSTNAME.instantiateTag( map(e(VmSystemTags.HOSTNAME_TOKEN, msg.getHostname())) )); } APISetVmHostnameEvent evt = new APISetVmHostnameEvent(msg.getId()); bus.publish(evt); } private void handle(final APIGetVmConsoleAddressMsg msg) { ErrorCode error = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (error != null) { throw new OperationFailureException(error); } final APIGetVmConsoleAddressReply creply = new APIGetVmConsoleAddressReply(); GetVmConsoleAddressFromHostMsg hmsg = new GetVmConsoleAddressFromHostMsg(); hmsg.setHostUuid(self.getHostUuid()); hmsg.setVmInstanceUuid(self.getUuid()); bus.makeTargetServiceIdByResourceUuid(hmsg, HostConstant.SERVICE_ID, self.getHostUuid()); bus.send(hmsg, new CloudBusCallBack(msg) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { creply.setError(reply.getError()); } else { GetVmConsoleAddressFromHostReply hr = reply.castReply(); creply.setHostIp(hr.getHostIp()); creply.setPort(hr.getPort()); creply.setProtocol(hr.getProtocol()); } bus.reply(msg, creply); } }); } private void handle(APIGetVmBootOrderMsg msg) { APIGetVmBootOrderReply reply = new APIGetVmBootOrderReply(); String order = VmSystemTags.BOOT_ORDER.getTokenByResourceUuid(self.getUuid(), VmSystemTags.BOOT_ORDER_TOKEN); if (order == null) { reply.setOrder(list(VmBootDevice.HardDisk.toString())); } else { reply.setOrder(list(order.split(","))); } bus.reply(msg, reply); } private void handle(APISetVmBootOrderMsg msg) { APISetVmBootOrderEvent evt = new APISetVmBootOrderEvent(msg.getId()); if (msg.getBootOrder() != null) { SystemTagCreator creator = VmSystemTags.BOOT_ORDER.newSystemTagCreator(self.getUuid()); creator.inherent = true; creator.recreate = true; creator.setTagByTokens(map(e(VmSystemTags.BOOT_ORDER_TOKEN, StringUtils.join(msg.getBootOrder(), ",")))); creator.create(); } else { VmSystemTags.BOOT_ORDER.deleteInherentTag(self.getUuid()); } evt.setInventory(getSelfInventory()); bus.publish(evt); } private void handle(APISetVmConsolePasswordMsg msg) { APISetVmConsolePasswordEvent evt = new APISetVmConsolePasswordEvent(msg.getId()); SystemTagCreator creator = VmSystemTags.CONSOLE_PASSWORD.newSystemTagCreator(self.getUuid()); creator.setTagByTokens(map(e(VmSystemTags.CONSOLE_PASSWORD_TOKEN, msg.getConsolePassword()))); creator.recreate = true; creator.create(); evt.setInventory(getSelfInventory()); bus.publish(evt); } private void handle(APIGetVmConsolePasswordMsg msg) { APIGetVmConsolePasswordReply reply = new APIGetVmConsolePasswordReply(); String consolePassword = VmSystemTags.CONSOLE_PASSWORD.getTokenByResourceUuid(self.getUuid(), VmSystemTags.CONSOLE_PASSWORD_TOKEN); reply.setConsolePassword(consolePassword); bus.reply(msg, reply); } private void handle(APIDeleteVmConsolePasswordMsg msg) { APIDeleteVmConsolePasswordEvent evt = new APIDeleteVmConsolePasswordEvent(msg.getId()); VmSystemTags.CONSOLE_PASSWORD.delete(self.getUuid()); evt.setInventory(getSelfInventory()); bus.publish(evt); } private void handle(APISetVmSshKeyMsg msg) { APISetVmSshKeyEvent evt = new APISetVmSshKeyEvent(msg.getId()); SystemTagCreator creator = VmSystemTags.SSHKEY.newSystemTagCreator(self.getUuid()); creator.setTagByTokens(map(e(VmSystemTags.SSHKEY_TOKEN, msg.getSshKey()))); creator.recreate = true; creator.create(); evt.setInventory(getSelfInventory()); bus.publish(evt); } private void handle(APIGetVmSshKeyMsg msg) { APIGetVmSshKeyReply reply = new APIGetVmSshKeyReply(); String sshKey = VmSystemTags.SSHKEY.getTokenByResourceUuid(self.getUuid(), VmSystemTags.SSHKEY_TOKEN); reply.setSshKey(sshKey); bus.reply(msg, reply); } private void handle(APIDeleteVmSshKeyMsg msg) { APIDeleteVmSshKeyEvent evt = new APIDeleteVmSshKeyEvent(msg.getId()); VmSystemTags.SSHKEY.delete(self.getUuid()); evt.setInventory(getSelfInventory()); bus.publish(evt); } private boolean ipExists(final String l3uuid, final String ipAddress) { SimpleQuery<VmNicVO> q = dbf.createQuery(VmNicVO.class); q.add(VmNicVO_.l3NetworkUuid, Op.EQ, l3uuid); q.add(VmNicVO_.ip, Op.EQ, ipAddress); return q.isExists(); } // If the VM is assigned static IP and it is now occupied, we will // remove the static IP tag so that it can acquire IP dynamically. // c.f. issue #1639 private void checkIpConflict(final String vmUuid) { StaticIpOperator ipo = new StaticIpOperator(); for (Map.Entry<String, String> entry : ipo.getStaticIpbyVmUuid(vmUuid).entrySet()) { if (ipExists(entry.getKey(), entry.getValue())) { ipo.deleteStaticIpByVmUuidAndL3Uuid(vmUuid, entry.getKey()); } } } private void recoverVm(final Completion completion) { final VmInstanceInventory vm = getSelfInventory(); final List<RecoverVmExtensionPoint> exts = pluginRgty.getExtensionList(RecoverVmExtensionPoint.class); for (RecoverVmExtensionPoint ext : exts) { ext.preRecoverVm(vm); } CollectionUtils.forEach(exts, new ForEachFunction<RecoverVmExtensionPoint>() { @Override public void run(RecoverVmExtensionPoint ext) { ext.beforeRecoverVm(vm); } }); FlowChain chain = FlowChainBuilder.newShareFlowChain(); chain.setName(String.format("recover-vm-%s", self.getUuid())); chain.then(new ShareFlow() { @Override public void setup() { flow(new NoRollbackFlow() { String __name__ = "check-ip-conflict"; @Override public void run(FlowTrigger trigger, Map data) { checkIpConflict(vm.getUuid()); trigger.next(); } }); flow(new NoRollbackFlow() { String __name__ = "recover-root-volume"; @Override public void run(final FlowTrigger trigger, Map data) { RecoverVolumeMsg msg = new RecoverVolumeMsg(); msg.setVolumeUuid(self.getRootVolumeUuid()); bus.makeTargetServiceIdByResourceUuid(msg, VolumeConstant.SERVICE_ID, self.getRootVolumeUuid()); bus.send(msg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { trigger.fail(reply.getError()); } else { trigger.next(); } } }); } }); flow(new NoRollbackFlow() { String __name__ = "recover-vm"; @Override public void run(FlowTrigger trigger, Map data) { self = changeVmStateInDb(VmInstanceStateEvent.stopped); CollectionUtils.forEach(exts, new ForEachFunction<RecoverVmExtensionPoint>() { @Override public void run(RecoverVmExtensionPoint ext) { ext.afterRecoverVm(vm); } }); trigger.next(); } }); done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { completion.success(); } }); error(new FlowErrorHandler(completion) { @Override public void handle(ErrorCode errCode, Map data) { completion.fail(errCode); } }); } }).start(); } private void handle(final APIRecoverVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { final APIRecoverVmInstanceEvent evt = new APIRecoverVmInstanceEvent(msg.getId()); refreshVO(); ErrorCode error = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (error != null) { evt.setError(error); bus.publish(evt); chain.next(); return; } recoverVm(new Completion(msg, chain) { @Override public void success() { evt.setInventory(getSelfInventory()); bus.publish(evt); chain.next(); } @Override public void fail(ErrorCode errorCode) { evt.setError(errorCode); bus.publish(evt); chain.next(); } }); } @Override public String getName() { return "recover-vm"; } }); } private void handle(final APIExpungeVmInstanceMsg msg) { final APIExpungeVmInstanceEvent evt = new APIExpungeVmInstanceEvent(msg.getId()); thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { expunge(msg, new Completion(msg, chain) { @Override public void success() { bus.publish(evt); chain.next(); } @Override public void fail(ErrorCode errorCode) { evt.setError(errorCode); bus.publish(evt); chain.next(); } }); } @Override public String getName() { return "expunge-vm-by-api"; } }); } private void handle(final APIDetachIsoFromVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { final APIDetachIsoFromVmInstanceEvent evt = new APIDetachIsoFromVmInstanceEvent(msg.getId()); refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (allowed != null) { evt.setError(allowed); bus.publish(evt); chain.next(); return; } detachIso(new Completion(msg, chain) { @Override public void success() { self = dbf.reload(self); evt.setInventory(getSelfInventory()); bus.publish(evt); chain.next(); } @Override public void fail(ErrorCode errorCode) { evt.setError(errorCode); bus.publish(evt); chain.next(); } }); } @Override public String getName() { return String.format("detach-iso-from-vm-%s", self.getUuid()); } }); } private void detachIso(final Completion completion) { if (self.getState() == VmInstanceState.Stopped) { new IsoOperator().detachIsoFromVm(self.getUuid()); completion.success(); return; } if (!new IsoOperator().isIsoAttachedToVm(self.getUuid())) { completion.success(); return; } VmInstanceSpec spec = buildSpecFromInventory(getSelfInventory(), VmOperation.DetachIso); if (spec.getDestIso() == null) { // the image ISO has been deleted from backup storage // try to detach it from the VM anyway String isoUuid = new IsoOperator().getIsoUuidByVmUuid(self.getUuid()); IsoSpec isoSpec = new IsoSpec(); isoSpec.setImageUuid(isoUuid); spec.setDestIso(isoSpec); logger.debug(String.format("the iso[uuid:%s] has been deleted, try to detach it from the VM[uuid:%s] anyway", isoUuid, self.getUuid())); } FlowChain chain = getDetachIsoWorkFlowChain(spec.getVmInventory()); chain.setName(String.format("detach-iso-%s-from-vm-%s", spec.getDestIso().getImageUuid(), self.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); setFlowMarshaller(chain); chain.done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { new IsoOperator().detachIsoFromVm(self.getUuid()); completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(ErrorCode errCode, Map data) { completion.fail(errCode); } }).start(); } @Transactional(readOnly = true) private List<L3NetworkInventory> getAttachableL3Network(String accountUuid) { List<String> l3Uuids = acntMgr.getResourceUuidsCanAccessByAccount(accountUuid, L3NetworkVO.class); if (l3Uuids != null && l3Uuids.isEmpty()) { return new ArrayList<L3NetworkInventory>(); } String sql; TypedQuery<L3NetworkVO> q; if (self.getVmNics().isEmpty()) { if (l3Uuids == null) { // accessed by a system admin sql = "select l3" + " from L3NetworkVO l3, VmInstanceVO vm, L2NetworkVO l2, L2NetworkClusterRefVO l2ref" + " where vm.uuid = :uuid" + " and vm.clusterUuid = l2ref.clusterUuid" + " and l2ref.l2NetworkUuid = l2.uuid" + " and l2.uuid = l3.l2NetworkUuid" + " and l3.state = :l3State" + " group by l3.uuid"; q = dbf.getEntityManager().createQuery(sql, L3NetworkVO.class); } else { // accessed by a normal account sql = "select l3" + " from L3NetworkVO l3, VmInstanceVO vm, L2NetworkVO l2, L2NetworkClusterRefVO l2ref" + " where vm.uuid = :uuid" + " and vm.clusterUuid = l2ref.clusterUuid" + " and l2ref.l2NetworkUuid = l2.uuid" + " and l2.uuid = l3.l2NetworkUuid" + " and l3.state = :l3State" + " and l3.uuid in (:l3uuids)" + " group by l3.uuid"; q = dbf.getEntityManager().createQuery(sql, L3NetworkVO.class); q.setParameter("l3uuids", l3Uuids); } } else { if (l3Uuids == null) { // accessed by a system admin sql = "select l3" + " from L3NetworkVO l3, VmInstanceVO vm, L2NetworkVO l2, L2NetworkClusterRefVO l2ref" + " where l3.uuid not in" + " (select nic.l3NetworkUuid from VmNicVO nic where nic.vmInstanceUuid = :uuid)" + " and vm.uuid = :uuid" + " and vm.clusterUuid = l2ref.clusterUuid" + " and l2ref.l2NetworkUuid = l2.uuid" + " and l2.uuid = l3.l2NetworkUuid" + " and l3.state = :l3State" + " group by l3.uuid"; q = dbf.getEntityManager().createQuery(sql, L3NetworkVO.class); } else { // accessed by a normal account sql = "select l3" + " from L3NetworkVO l3, VmInstanceVO vm, L2NetworkVO l2, L2NetworkClusterRefVO l2ref" + " where l3.uuid not in" + " (select nic.l3NetworkUuid from VmNicVO nic where nic.vmInstanceUuid = :uuid)" + " and vm.uuid = :uuid" + " and vm.clusterUuid = l2ref.clusterUuid" + " and l2ref.l2NetworkUuid = l2.uuid" + " and l2.uuid = l3.l2NetworkUuid" + " and l3.state = :l3State" + " and l3.uuid in (:l3uuids)" + " group by l3.uuid"; q = dbf.getEntityManager().createQuery(sql, L3NetworkVO.class); q.setParameter("l3uuids", l3Uuids); } } q.setParameter("l3State", L3NetworkState.Enabled); q.setParameter("uuid", self.getUuid()); List<L3NetworkVO> l3s = q.getResultList(); return L3NetworkInventory.valueOf(l3s); } private void handle(APIGetVmAttachableL3NetworkMsg msg) { APIGetVmAttachableL3NetworkReply reply = new APIGetVmAttachableL3NetworkReply(); reply.setInventories(getAttachableL3Network(msg.getSession().getAccountUuid())); bus.reply(msg, reply); } private void handle(final APIAttachIsoToVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { final APIAttachIsoToVmInstanceEvent evt = new APIAttachIsoToVmInstanceEvent(msg.getId()); refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (allowed != null) { evt.setError(allowed); bus.publish(evt); chain.next(); return; } attachIso(msg.getIsoUuid(), new Completion(msg, chain) { @Override public void success() { self = dbf.reload(self); evt.setInventory(getSelfInventory()); bus.publish(evt); chain.next(); } @Override public void fail(ErrorCode errorCode) { evt.setError(errorCode); bus.publish(evt); chain.next(); } }); } @Override public String getName() { return String.format("attach-iso-%s-to-vm-%s", msg.getIsoUuid(), self.getUuid()); } }); } private void attachIso(final String isoUuid, final Completion completion) { checkIfIsoAttachable(isoUuid); if (self.getState() == VmInstanceState.Stopped) { new IsoOperator().attachIsoToVm(self.getUuid(), isoUuid); completion.success(); return; } VmInstanceSpec spec = buildSpecFromInventory(getSelfInventory(), VmOperation.AttachIso); IsoSpec isoSpec = new IsoSpec(); isoSpec.setImageUuid(isoUuid); spec.setDestIso(isoSpec); FlowChain chain = getAttachIsoWorkFlowChain(spec.getVmInventory()); chain.setName(String.format("attach-iso-%s-to-vm-%s", isoUuid, self.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); setFlowMarshaller(chain); chain.done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { new IsoOperator().attachIsoToVm(self.getUuid(), isoUuid); completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(ErrorCode errCode, Map data) { completion.fail(errCode); } }).start(); } @Transactional(readOnly = true) private void checkIfIsoAttachable(String isoUuid) { String psUuid = getSelfInventory().getRootVolume().getPrimaryStorageUuid(); String sql = "select count(i)" + " from ImageCacheVO i" + " where i.primaryStorageUuid = :psUuid" + " and i.imageUuid = :isoUuid"; TypedQuery<Long> q = dbf.getEntityManager().createQuery(sql, Long.class); q.setParameter("psUuid", psUuid); q.setParameter("isoUuid", isoUuid); Long count = q.getSingleResult(); if (count > 0) { // on the same primary storage return; } PrimaryStorageVO psvo = dbf.getEntityManager().find(PrimaryStorageVO.class, psUuid); PrimaryStorageType type = PrimaryStorageType.valueOf(psvo.getType()); List<String> bsUuids = type.findBackupStorage(psUuid); if (bsUuids == null) { List<String> possibleBsTypes = hostAllocatorMgr.getBackupStorageTypesByPrimaryStorageTypeFromMetrics(psvo.getType()); sql = "select count(bs)" + " from BackupStorageVO bs, ImageBackupStorageRefVO ref" + " where bs.uuid = ref.backupStorageUuid" + " and ref.imageUuid = :imgUuid" + " and bs.type in (:bsTypes)"; q = dbf.getEntityManager().createQuery(sql, Long.class); q.setParameter("imgUuid", isoUuid); q.setParameter("bsTypes", possibleBsTypes); count = q.getSingleResult(); if (count > 0) { return; } } else if (!bsUuids.isEmpty()) { sql = "select count(bs)" + " from BackupStorageVO bs, ImageBackupStorageRefVO ref" + " where bs.uuid = ref.backupStorageUuid" + " and ref.imageUuid = :imgUuid" + " and bs.uuid in (:bsUuids)"; q = dbf.getEntityManager().createQuery(sql, Long.class); q.setParameter("imgUuid", isoUuid); q.setParameter("bsUuids", bsUuids); count = q.getSingleResult(); if (count > 0) { return; } } throw new OperationFailureException(operr("the ISO[uuid:%s] is on backup storage that is not compatible of the primary storage[uuid:%s]" + " where the VM[name:%s, uuid:%s] is on", isoUuid, psUuid, self.getName(), self.getUuid())); } private void handle(final APIDetachL3NetworkFromVmMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { final APIDetachL3NetworkFromVmEvent evt = new APIDetachL3NetworkFromVmEvent(msg.getId()); refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (allowed != null) { evt.setError(allowed); bus.publish(evt); chain.next(); return; } detachNic(msg.getVmNicUuid(), new Completion(msg, chain) { @Override public void success() { self = dbf.reload(self); evt.setInventory(getSelfInventory()); bus.publish(evt); chain.next(); } @Override public void fail(ErrorCode errorCode) { evt.setError(errorCode); bus.publish(evt); chain.next(); } }); } @Override public String getName() { return "detach-nic"; } }); } protected void selectDefaultL3(VmNicInventory nic) { if (self.getDefaultL3NetworkUuid() != null && self.getDefaultL3NetworkUuid().equals(nic.getL3NetworkUuid())) { return; } final VmInstanceInventory vm = getSelfInventory(); final String previousDefaultL3 = vm.getDefaultL3NetworkUuid(); // the nic has been removed, reload self = dbf.reload(self); final VmNicVO candidate = CollectionUtils.find(self.getVmNics(), new Function<VmNicVO, VmNicVO>() { @Override public VmNicVO call(VmNicVO arg) { return arg.getUuid().equals(nic.getUuid()) ? null : arg; } }); if (candidate != null) { CollectionUtils.safeForEach( pluginRgty.getExtensionList(VmDefaultL3NetworkChangedExtensionPoint.class), new ForEachFunction<VmDefaultL3NetworkChangedExtensionPoint>() { @Override public void run(VmDefaultL3NetworkChangedExtensionPoint ext) { ext.vmDefaultL3NetworkChanged(vm, previousDefaultL3, candidate.getL3NetworkUuid()); } }); self.setDefaultL3NetworkUuid(candidate.getL3NetworkUuid()); logger.debug(String.format( "after detaching the nic[uuid:%s, L3 uuid:%s], change the default L3 of the VM[uuid:%s]" + " to the L3 network[uuid: %s]", nic.getUuid(), nic.getL3NetworkUuid(), self.getUuid(), candidate.getL3NetworkUuid())); } else { self.setDefaultL3NetworkUuid(null); logger.debug(String.format( "after detaching the nic[uuid:%s, L3 uuid:%s], change the default L3 of the VM[uuid:%s]" + " to null, as the VM has no other nics", nic.getUuid(), nic.getL3NetworkUuid(), self.getUuid())); } self = dbf.updateAndRefresh(self); } private void detachNic(final String nicUuid, final Completion completion) { final VmNicInventory nic = VmNicInventory.valueOf( CollectionUtils.find(self.getVmNics(), new Function<VmNicVO, VmNicVO>() { @Override public VmNicVO call(VmNicVO arg) { return arg.getUuid().equals(nicUuid) ? arg : null; } }) ); for (VmDetachNicExtensionPoint ext : pluginRgty.getExtensionList(VmDetachNicExtensionPoint.class)) { ext.preDetachNic(nic); } CollectionUtils.safeForEach(pluginRgty.getExtensionList(VmDetachNicExtensionPoint.class), new ForEachFunction<VmDetachNicExtensionPoint>() { @Override public void run(VmDetachNicExtensionPoint arg) { arg.beforeDetachNic(nic); } }); final VmInstanceSpec spec = buildSpecFromInventory(getSelfInventory(), VmOperation.DetachNic); spec.setVmInventory(VmInstanceInventory.valueOf(self)); spec.setDestNics(list(nic)); spec.setL3Networks(list(L3NetworkInventory.valueOf(dbf.findByUuid(nic.getL3NetworkUuid(), L3NetworkVO.class)))); FlowChain flowChain = FlowChainBuilder.newSimpleFlowChain(); flowChain.setName(String.format("detachNic-vm-%s-nic-%s", self.getUuid(), nicUuid)); setFlowMarshaller(flowChain); flowChain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); if (self.getState() == VmInstanceState.Running) { flowChain.then(new VmDetachNicOnHypervisorFlow()); } flowChain.then(new VmReleaseResourceOnDetachingNicFlow()); flowChain.then(new VmDetachNicFlow()); flowChain.done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { selectDefaultL3(nic); removeStaticIp(); CollectionUtils.safeForEach(pluginRgty.getExtensionList(VmDetachNicExtensionPoint.class), new ForEachFunction<VmDetachNicExtensionPoint>() { @Override public void run(VmDetachNicExtensionPoint arg) { arg.afterDetachNic(nic); } }); completion.success(); } private void removeStaticIp() { new StaticIpOperator().deleteStaticIpByVmUuidAndL3Uuid(self.getUuid(), nic.getL3NetworkUuid()); } }).error(new FlowErrorHandler(completion) { @Override public void handle(final ErrorCode errCode, Map data) { CollectionUtils.safeForEach(pluginRgty.getExtensionList(VmDetachNicExtensionPoint.class), new ForEachFunction<VmDetachNicExtensionPoint>() { @Override public void run(VmDetachNicExtensionPoint arg) { arg.failedToDetachNic(nic, errCode); } }); completion.fail(errCode); } }).start(); } private void handle(final APIChangeInstanceOfferingMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { changeOffering(msg); chain.next(); } @Override public String getName() { return "change-instance-offering"; } }); } private void changeOffering(APIChangeInstanceOfferingMsg msg) { APIChangeInstanceOfferingEvent evt = new APIChangeInstanceOfferingEvent(msg.getId()); refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (allowed != null) { bus.replyErrorByMessageType(msg, allowed); return; } final InstanceOfferingVO newOfferingVO = dbf.findByUuid(msg.getInstanceOfferingUuid(), InstanceOfferingVO.class); final InstanceOfferingInventory inv = InstanceOfferingInventory.valueOf(newOfferingVO); final VmInstanceInventory vm = getSelfInventory(); List<ChangeInstanceOfferingExtensionPoint> exts = pluginRgty.getExtensionList(ChangeInstanceOfferingExtensionPoint.class); for (ChangeInstanceOfferingExtensionPoint ext : exts) { ext.preChangeInstanceOffering(vm, inv); } CollectionUtils.safeForEach(exts, new ForEachFunction<ChangeInstanceOfferingExtensionPoint>() { @Override public void run(ChangeInstanceOfferingExtensionPoint arg) { arg.beforeChangeInstanceOffering(vm, inv); } }); if (self.getState() == VmInstanceState.Stopped) { changeInstanceOfferingForStoppedVm(exts, newOfferingVO, vm, inv, evt); return; } else { if (self.getState() != VmInstanceState.Running) { throw new OperationFailureException(operr("The state of vm[uuid:%s] is %s. Only these state[%s] is allowed.", self.getUuid(), self.getState(), StringUtils.join(list(VmInstanceState.Running, VmInstanceState.Stopped), ","))); } } String instanceOfferingOnlineChange = VmSystemTags.INSTANCEOFFERING_ONLIECHANGE .getTokenByResourceUuid(self.getUuid(), VmSystemTags.INSTANCEOFFERING_ONLINECHANGE_TOKEN); if ((instanceOfferingOnlineChange != null && instanceOfferingOnlineChange.equals("true")) && self.getCpuNum() <= newOfferingVO.getCpuNum() && self.getMemorySize() <= newOfferingVO.getMemorySize()) { stretchInstanceOfferingForRunningVm(exts, newOfferingVO, vm, inv, evt); } else { pendingChangeInstanceOfferingForRunningVmNextStart(exts, newOfferingVO, vm, inv, evt); } } private void pendingChangeInstanceOfferingForRunningVmNextStart(List<ChangeInstanceOfferingExtensionPoint> exts, final InstanceOfferingVO newOfferingVO, final VmInstanceInventory vm, final InstanceOfferingInventory inv, APIChangeInstanceOfferingEvent evt) { pendingCpuAndMemoryForNextStart(newOfferingVO.getCpuNum(), newOfferingVO.getCpuSpeed(), newOfferingVO.getMemorySize()); self.setInstanceOfferingUuid(newOfferingVO.getUuid()); self = dbf.updateAndRefresh(self); CollectionUtils.safeForEach(exts, new ForEachFunction<ChangeInstanceOfferingExtensionPoint>() { @Override public void run(ChangeInstanceOfferingExtensionPoint arg) { arg.afterChangeInstanceOffering(vm, inv); } }); evt.setInventory(getSelfInventory()); bus.publish(evt); } private void pendingCpuAndMemoryForNextStart(int cpuNum, long cpuSpeed, long memorySize) { Map m = new HashMap(); m.put(VmSystemTags.PENDING_CAPACITY_CHNAGE_CPU_NUM_TOKEN, cpuNum); m.put(VmSystemTags.PENDING_CAPACITY_CHNAGE_CPU_SPEED_TOKEN, cpuSpeed); m.put(VmSystemTags.PENDING_CAPACITY_CHNAGE_MEMORY_TOKEN, memorySize); SystemTagCreator creator = VmSystemTags.PENDING_CAPACITY_CHANGE.newSystemTagCreator(self.getUuid()); creator.inherent = true; creator.recreate = true; creator.setTagByTokens(m); creator.create(); } private void changeInstanceOfferingForStoppedVm(List<ChangeInstanceOfferingExtensionPoint> exts, final InstanceOfferingVO newOfferingVO, final VmInstanceInventory vm, final InstanceOfferingInventory inv, APIChangeInstanceOfferingEvent evt) { self.setInstanceOfferingUuid(newOfferingVO.getUuid()); self.setCpuNum(newOfferingVO.getCpuNum()); self.setCpuSpeed(newOfferingVO.getCpuSpeed()); self.setMemorySize(newOfferingVO.getMemorySize()); self = dbf.updateAndRefresh(self); CollectionUtils.safeForEach(exts, new ForEachFunction<ChangeInstanceOfferingExtensionPoint>() { @Override public void run(ChangeInstanceOfferingExtensionPoint arg) { arg.afterChangeInstanceOffering(vm, inv); } }); evt.setInventory(getSelfInventory()); bus.publish(evt); } private void stretchInstanceOfferingForRunningVm(List<ChangeInstanceOfferingExtensionPoint> exts, final InstanceOfferingVO newOfferingVO, final VmInstanceInventory vm, final InstanceOfferingInventory inv, APIChangeInstanceOfferingEvent evt) { OnlineChangeVmCpuMemoryMsg hmsg = new OnlineChangeVmCpuMemoryMsg(); hmsg.setVmInstanceUuid(self.getUuid()); hmsg.setHostUuid(self.getHostUuid()); hmsg.setInstanceOfferingInventory(inv); bus.makeTargetServiceIdByResourceUuid(hmsg, HostConstant.SERVICE_ID, self.getHostUuid()); bus.send(hmsg, new CloudBusCallBack(null) { @Override public void run(MessageReply reply) { if (!reply.isSuccess()) { evt.setError(reply.getError()); } else { OnlineChangeVmCpuMemoryReply hr = reply.castReply(); self.setInstanceOfferingUuid(newOfferingVO.getUuid()); self.setCpuNum(hr.getInstanceOfferingInventory().getCpuNum()); self.setMemorySize(hr.getInstanceOfferingInventory().getMemorySize()); self = dbf.updateAndRefresh(self); CollectionUtils.safeForEach(exts, new ForEachFunction<ChangeInstanceOfferingExtensionPoint>() { @Override public void run(ChangeInstanceOfferingExtensionPoint arg) { arg.afterChangeInstanceOffering(vm, inv); } }); evt.setInventory(getSelfInventory()); } bus.publish(evt); } }); } private void handle(final APIUpdateVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { refreshVO(); List<Runnable> extensions = new ArrayList<Runnable>(); final VmInstanceInventory vm = getSelfInventory(); boolean update = false; if (msg.getName() != null) { self.setName(msg.getName()); update = true; } if (msg.getDescription() != null) { self.setDescription(msg.getDescription()); update = true; } if (msg.getState() != null) { self.setState(VmInstanceState.valueOf(msg.getState())); update = true; if (!vm.getState().equals(msg.getState())) { extensions.add(new Runnable() { @Override public void run() { logger.debug(String.format("vm[uuid:%s] changed state from %s to %s", self.getUuid(), vm.getState(), msg.getState())); VmCanonicalEvents.VmStateChangedData data = new VmCanonicalEvents.VmStateChangedData(); data.setVmUuid(self.getUuid()); data.setOldState(vm.getState()); data.setNewState(msg.getState()); data.setInventory(getSelfInventory()); evtf.fire(VmCanonicalEvents.VM_FULL_STATE_CHANGED_PATH, data); } }); } } if (msg.getDefaultL3NetworkUuid() != null) { self.setDefaultL3NetworkUuid(msg.getDefaultL3NetworkUuid()); update = true; if (!msg.getDefaultL3NetworkUuid().equals(vm.getDefaultL3NetworkUuid())) { extensions.add(new Runnable() { @Override public void run() { for (VmDefaultL3NetworkChangedExtensionPoint ext : pluginRgty.getExtensionList(VmDefaultL3NetworkChangedExtensionPoint.class)) { ext.vmDefaultL3NetworkChanged(vm, vm.getDefaultL3NetworkUuid(), msg.getDefaultL3NetworkUuid()); } } }); } } if (msg.getPlatform() != null) { self.setPlatform(msg.getPlatform()); update = true; } if (msg.getCpuNum() != null || msg.getMemorySize() != null) { changeCpuAndMemory(msg); update = true; } if (update) { self = dbf.updateAndRefresh(self); } CollectionUtils.safeForEach(extensions, new ForEachFunction<Runnable>() { @Override public void run(Runnable arg) { arg.run(); } }); APIUpdateVmInstanceEvent evt = new APIUpdateVmInstanceEvent(msg.getId()); evt.setInventory(getSelfInventory()); bus.publish(evt); chain.next(); } @Override public String getName() { return "update-vm-info"; } }); } @Transactional(readOnly = true) private List<VolumeVO> getAttachableVolume(String accountUuid) { List<String> volUuids = acntMgr.getResourceUuidsCanAccessByAccount(accountUuid, VolumeVO.class); if (volUuids != null && volUuids.isEmpty()) { return new ArrayList<>(); } List<String> formats = VolumeFormat.getVolumeFormatSupportedByHypervisorTypeInString(self.getHypervisorType()); if (formats.isEmpty()) { throw new CloudRuntimeException(String.format("cannot find volume formats for the hypervisor type[%s]", self.getHypervisorType())); } String sql; List<VolumeVO> vos; if (volUuids == null) { // accessed by a system admin sql = "select vol" + " from VolumeVO vol, VmInstanceVO vm, PrimaryStorageClusterRefVO ref" + " where vol.type = :type" + " and vol.state = :volState" + " and vol.status = :volStatus" + " and vol.format in (:formats)" + " and vol.vmInstanceUuid is null" + " and vm.clusterUuid = ref.clusterUuid" + " and ref.primaryStorageUuid = vol.primaryStorageUuid" + " and vm.uuid = :vmUuid" + " group by vol.uuid"; TypedQuery<VolumeVO> q = dbf.getEntityManager().createQuery(sql, VolumeVO.class); q.setParameter("volState", VolumeState.Enabled); q.setParameter("volStatus", VolumeStatus.Ready); q.setParameter("formats", formats); q.setParameter("vmUuid", self.getUuid()); q.setParameter("type", VolumeType.Data); vos = q.getResultList(); sql = "select vol" + " from VolumeVO vol" + " where vol.type = :type" + " and vol.status = :volStatus" + " and vol.state = :volState" + " group by vol.uuid"; q = dbf.getEntityManager().createQuery(sql, VolumeVO.class); q.setParameter("type", VolumeType.Data); q.setParameter("volState", VolumeState.Enabled); q.setParameter("volStatus", VolumeStatus.NotInstantiated); vos.addAll(q.getResultList()); } else { // accessed by a normal account sql = "select vol" + " from VolumeVO vol, VmInstanceVO vm, PrimaryStorageClusterRefVO ref" + " where vol.type = :type" + " and vol.state = :volState" + " and vol.status = :volStatus" + " and vol.format in (:formats)" + " and vol.vmInstanceUuid is null" + " and vm.clusterUuid = ref.clusterUuid" + " and ref.primaryStorageUuid = vol.primaryStorageUuid" + " and vol.uuid in (:volUuids)" + " and vm.uuid = :vmUuid" + " group by vol.uuid"; TypedQuery<VolumeVO> q = dbf.getEntityManager().createQuery(sql, VolumeVO.class); q.setParameter("volState", VolumeState.Enabled); q.setParameter("volStatus", VolumeStatus.Ready); q.setParameter("vmUuid", self.getUuid()); q.setParameter("formats", formats); q.setParameter("type", VolumeType.Data); q.setParameter("volUuids", volUuids); vos = q.getResultList(); sql = "select vol" + " from VolumeVO vol" + " where vol.type = :type" + " and vol.status = :volStatus" + " and vol.state = :volState" + " and vol.uuid in (:volUuids)" + " group by vol.uuid"; q = dbf.getEntityManager().createQuery(sql, VolumeVO.class); q.setParameter("type", VolumeType.Data); q.setParameter("volState", VolumeState.Enabled); q.setParameter("volUuids", volUuids); q.setParameter("volStatus", VolumeStatus.NotInstantiated); vos.addAll(q.getResultList()); } for (GetAttachableVolumeExtensionPoint ext : pluginRgty.getExtensionList(GetAttachableVolumeExtensionPoint.class)) { if (!vos.isEmpty()) { vos = ext.returnAttachableVolumes(getSelfInventory(), vos); } } return vos; } private void changeCpuAndMemory(APIUpdateVmInstanceMsg msg) { // add some systemTag and can be appliance for the next start int cpuNum = msg.getCpuNum() == null ? self.getCpuNum() : msg.getCpuNum(); long memory = msg.getMemorySize() == null ? self.getMemorySize() : msg.getMemorySize(); pendingCpuAndMemoryForNextStart(cpuNum, self.getCpuSpeed(), memory); self.setCpuNum(cpuNum); self.setMemorySize(memory); self = dbf.updateAndRefresh(self); } private void handle(APIGetVmAttachableDataVolumeMsg msg) { APIGetVmAttachableDataVolumeReply reply = new APIGetVmAttachableDataVolumeReply(); reply.setInventories(VolumeInventory.valueOf(getAttachableVolume(msg.getSession().getAccountUuid()))); bus.reply(msg, reply); } private void handle(final APIGetVmMigrationCandidateHostsMsg msg) { final APIGetVmMigrationCandidateHostsReply reply = new APIGetVmMigrationCandidateHostsReply(); getVmMigrationTargetHost(msg, new ReturnValueCompletion<List<HostInventory>>(msg) { @Override public void success(List<HostInventory> returnValue) { reply.setInventories(returnValue); bus.reply(msg, reply); } @Override public void fail(ErrorCode errorCode) { reply.setError(errorCode); bus.reply(msg, reply); } }); } private void handle(final APIAttachL3NetworkToVmMsg msg) { final APIAttachL3NetworkToVmEvent evt = new APIAttachL3NetworkToVmEvent(msg.getId()); attachNic(msg, msg.getL3NetworkUuid(), new ReturnValueCompletion<VmNicInventory>(msg) { @Override public void success(VmNicInventory returnValue) { self = dbf.reload(self); evt.setInventory(VmInstanceInventory.valueOf(self)); bus.publish(evt); } @Override public void fail(ErrorCode errorCode) { evt.setError(errorCode); bus.publish(evt); } }); } private void detachVolume(final DetachDataVolumeFromVmMsg msg, final NoErrorCompletion completion) { final DetachDataVolumeFromVmReply reply = new DetachDataVolumeFromVmReply(); refreshVO(true); if (self == null || VmInstanceState.Destroyed == self.getState()) { // the vm is destroyed, the data volume must have been detached bus.reply(msg, reply); completion.done(); return; } ErrorCode allowed = validateOperationByState(msg, self.getState(), VmErrors.DETACH_VOLUME_ERROR); if (allowed != null) { throw new OperationFailureException(allowed); } final VolumeInventory volume = msg.getVolume(); extEmitter.preDetachVolume(getSelfInventory(), volume); extEmitter.beforeDetachVolume(getSelfInventory(), volume); if (self.getState() == VmInstanceState.Stopped) { extEmitter.afterDetachVolume(getSelfInventory(), volume); bus.reply(msg, reply); completion.done(); return; } // VmInstanceState.Running String hostUuid = self.getHostUuid(); DetachVolumeFromVmOnHypervisorMsg dmsg = new DetachVolumeFromVmOnHypervisorMsg(); dmsg.setVmInventory(VmInstanceInventory.valueOf(self)); dmsg.setInventory(volume); dmsg.setHostUuid(hostUuid); bus.makeTargetServiceIdByResourceUuid(dmsg, HostConstant.SERVICE_ID, hostUuid); bus.send(dmsg, new CloudBusCallBack(msg, completion) { @Override public void run(final MessageReply r) { if (!r.isSuccess()) { reply.setError(r.getError()); extEmitter.failedToDetachVolume(getSelfInventory(), volume, r.getError()); } else { extEmitter.afterDetachVolume(getSelfInventory(), volume); } bus.reply(msg, reply); completion.done(); } }); } protected void attachDataVolume(final AttachDataVolumeToVmMsg msg, final NoErrorCompletion completion) { final AttachDataVolumeToVmReply reply = new AttachDataVolumeToVmReply(); refreshVO(); ErrorCode err = validateOperationByState(msg, self.getState(), VmErrors.ATTACH_VOLUME_ERROR); if (err != null) { throw new OperationFailureException(err); } final VolumeInventory volume = msg.getVolume(); extEmitter.preAttachVolume(getSelfInventory(), volume); extEmitter.beforeAttachVolume(getSelfInventory(), volume); VmInstanceSpec spec = new VmInstanceSpec(); spec.setMessage(msg); spec.setVmInventory(VmInstanceInventory.valueOf(self)); spec.setCurrentVmOperation(VmOperation.AttachVolume); spec.setDestDataVolumes(list(volume)); FlowChain chain; if (volume.getStatus().equals(VolumeStatus.Ready.toString())) { chain = FlowChainBuilder.newSimpleFlowChain(); chain.then(new VmAssignDeviceIdToAttachingVolumeFlow()); chain.then(new VmAttachVolumeOnHypervisorFlow()); } else { chain = getAttachUninstantiatedVolumeWorkFlowChain(spec.getVmInventory()); } setFlowMarshaller(chain); chain.setName(String.format("vm-%s-attach-volume-%s", self.getUuid(), volume.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); chain.getData().put(VmInstanceConstant.Params.AttachingVolumeInventory.toString(), volume); chain.done(new FlowDoneHandler(msg, completion) { @Override public void handle(Map data) { extEmitter.afterAttachVolume(getSelfInventory(), volume); reply.setHypervisorType(self.getHypervisorType()); bus.reply(msg, reply); completion.done(); } }).error(new FlowErrorHandler(msg, completion) { @Override public void handle(final ErrorCode errCode, Map data) { extEmitter.failedToAttachVolume(getSelfInventory(), volume, errCode); reply.setError(errf.instantiateErrorCode(VmErrors.ATTACH_VOLUME_ERROR, errCode)); bus.reply(msg, reply); completion.done(); } }).start(); } protected void migrateVm(final Message msg, final Completion completion) { refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), VmErrors.MIGRATE_ERROR); if (allowed != null) { completion.fail(allowed); return; } VmInstanceInventory pinv = getSelfInventory(); for (VmPreMigrationExtensionPoint ext : pluginRgty.getExtensionList(VmPreMigrationExtensionPoint.class)) { ext.preVmMigration(pinv); } VmInstanceInventory inv = VmInstanceInventory.valueOf(self); final VmInstanceSpec spec = buildSpecFromInventory(inv, VmOperation.Migrate); final VmInstanceState originState = self.getState(); changeVmStateInDb(VmInstanceStateEvent.migrating); spec.setMessage(msg); FlowChain chain = getMigrateVmWorkFlowChain(inv); setFlowMarshaller(chain); chain.setName(String.format("migrate-vm-%s", self.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); chain.done(new FlowDoneHandler(completion) { @Override public void handle(final Map data) { VmInstanceSpec spec = (VmInstanceSpec) data.get(VmInstanceConstant.Params.VmInstanceSpec.toString()); HostInventory host = spec.getDestHost(); self.setZoneUuid(host.getZoneUuid()); self.setClusterUuid(host.getClusterUuid()); self.setLastHostUuid(self.getHostUuid()); self.setHostUuid(host.getUuid()); self = changeVmStateInDb(VmInstanceStateEvent.running); VmInstanceInventory vm = VmInstanceInventory.valueOf(self); extEmitter.afterMigrateVm(vm, vm.getLastHostUuid()); completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(final ErrorCode errCode, Map data) { extEmitter.failedToMigrateVm(VmInstanceInventory.valueOf(self), spec.getDestHost().getUuid(), errCode); if (HostErrors.FAILED_TO_MIGRATE_VM_ON_HYPERVISOR.isEqual(errCode.getCode())) { checkState(originalCopy.getHostUuid(), new NoErrorCompletion(completion) { @Override public void done() { completion.fail(errCode); } }); } else { self.setState(originState); self = dbf.updateAndRefresh(self); completion.fail(errCode); } } }).start(); } protected void handle(final APIMigrateVmMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getName() { return String.format("migrate-vm-%s", self.getUuid()); } @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { migrateVm(msg, new Completion(chain) { @Override public void success() { APIMigrateVmEvent evt = new APIMigrateVmEvent(msg.getId()); evt.setInventory(VmInstanceInventory.valueOf(self)); bus.publish(evt); chain.next(); } @Override public void fail(ErrorCode errorCode) { APIMigrateVmEvent evt = new APIMigrateVmEvent(msg.getId()); evt.setError(errorCode); bus.publish(evt); chain.next(); } }); } }); } protected void applyPendingCapacityChangeIfNeed() { String pendingCapacityChange = VmSystemTags.PENDING_CAPACITY_CHANGE.getTag(self.getUuid()); if (pendingCapacityChange != null) { // the instance offering had been changed, apply new capacity to myself Map<String, String> tokens = VmSystemTags.PENDING_CAPACITY_CHANGE.getTokensByTag(pendingCapacityChange); int cpuNum = Integer.valueOf(tokens.get(VmSystemTags.PENDING_CAPACITY_CHNAGE_CPU_NUM_TOKEN)); int cpuSpeed = Integer.valueOf(tokens.get(VmSystemTags.PENDING_CAPACITY_CHNAGE_CPU_SPEED_TOKEN)); long memory = Long.valueOf(tokens.get(VmSystemTags.PENDING_CAPACITY_CHNAGE_MEMORY_TOKEN)); self.setCpuNum(cpuNum); self.setCpuSpeed(cpuSpeed); self.setMemorySize(memory); self = dbf.updateAndRefresh(self); VmSystemTags.PENDING_CAPACITY_CHANGE.deleteInherentTag(self.getUuid()); } } protected void startVm(final Message msg, final Completion completion) { refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), null); if (allowed != null) { completion.fail(allowed); return; } if (self.getState() == VmInstanceState.Created) { StartVmFromNewCreatedStruct struct = new JsonLabel().get( StartVmFromNewCreatedStruct.makeLabelKey(self.getUuid()), StartVmFromNewCreatedStruct.class); startVmFromNewCreate(struct, completion); return; } applyPendingCapacityChangeIfNeed(); VmInstanceInventory inv = VmInstanceInventory.valueOf(self); ErrorCode preStart = extEmitter.preStartVm(inv); if (preStart != null) { completion.fail(preStart); return; } final VmInstanceSpec spec = buildSpecFromInventory(inv, VmOperation.Start); spec.setMessage(msg); if (msg instanceof APIStartVmInstanceMsg) { APIStartVmInstanceMsg amsg = (APIStartVmInstanceMsg) msg; spec.setRequiredClusterUuid(amsg.getClusterUuid()); spec.setRequiredHostUuid(amsg.getHostUuid()); } if (spec.getDestNics().isEmpty()) { throw new OperationFailureException(operr("unable to start the vm[uuid:%s]." + " It doesn't have any nic, please attach a nic and try again", self.getUuid())); } final VmInstanceState originState = self.getState(); changeVmStateInDb(VmInstanceStateEvent.starting); extEmitter.beforeStartVm(VmInstanceInventory.valueOf(self)); FlowChain chain = getStartVmWorkFlowChain(inv); setFlowMarshaller(chain); chain.setName(String.format("start-vm-%s", self.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); chain.done(new FlowDoneHandler(completion) { @Override public void handle(final Map data) { VmInstanceSpec spec = (VmInstanceSpec) data.get(VmInstanceConstant.Params.VmInstanceSpec.toString()); // reload self because some nics may have been deleted in start phase because a former L3Network deletion. // reload to avoid JPA EntityNotFoundException self = dbf.reload(self); self.setLastHostUuid(self.getHostUuid()); self.setHostUuid(spec.getDestHost().getUuid()); self.setClusterUuid(spec.getDestHost().getClusterUuid()); self.setZoneUuid(spec.getDestHost().getZoneUuid()); self = changeVmStateInDb(VmInstanceStateEvent.running); logger.debug(String.format("vm[uuid:%s] is running ..", self.getUuid())); VmInstanceInventory inv = VmInstanceInventory.valueOf(self); extEmitter.afterStartVm(inv); completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(final ErrorCode errCode, Map data) { // reload self because some nics may have been deleted in start phase because a former L3Network deletion. // reload to avoid JPA EntityNotFoundException self = dbf.reload(self); extEmitter.failedToStartVm(VmInstanceInventory.valueOf(self), errCode); VmInstanceSpec spec = (VmInstanceSpec) data.get(VmInstanceConstant.Params.VmInstanceSpec.toString()); if (HostErrors.FAILED_TO_START_VM_ON_HYPERVISOR.isEqual(errCode.getCode())) { checkState(spec.getDestHost().getUuid(), new NoErrorCompletion(completion) { @Override public void done() { completion.fail(errCode); } }); } else { self.setState(originState); self = dbf.updateAndRefresh(self); completion.fail(errCode); } } }).start(); } private void startVmFromNewCreate(StartVmFromNewCreatedStruct struct, Completion completion) { VmInstanceInventory inv = getSelfInventory(); final VmInstanceSpec spec = new VmInstanceSpec(); spec.setRequiredPrimaryStorageUuidForRootVolume(struct.getPrimaryStorageUuidForRootVolume()); spec.setVmInventory(inv); if (struct.getL3NetworkUuids() != null && !struct.getL3NetworkUuids().isEmpty()) { SimpleQuery<L3NetworkVO> nwquery = dbf.createQuery(L3NetworkVO.class); nwquery.add(L3NetworkVO_.uuid, Op.IN, struct.getL3NetworkUuids()); List<L3NetworkVO> vos = nwquery.list(); List<L3NetworkInventory> nws = L3NetworkInventory.valueOf(vos); // order L3 networks by the order they specified in the API List<L3NetworkInventory> l3s = new ArrayList<>(nws.size()); for (final String l3Uuid : struct.getL3NetworkUuids()) { L3NetworkInventory l3 = CollectionUtils.find(nws, new Function<L3NetworkInventory, L3NetworkInventory>() { @Override public L3NetworkInventory call(L3NetworkInventory arg) { return arg.getUuid().equals(l3Uuid) ? arg : null; } }); DebugUtils.Assert(l3 != null, "where is the L3???"); l3s.add(l3); } spec.setL3Networks(l3s); } else { spec.setL3Networks(new ArrayList<>()); } if (struct.getDataDiskOfferingUuids() != null && !struct.getDataDiskOfferingUuids().isEmpty()) { SimpleQuery<DiskOfferingVO> dquery = dbf.createQuery(DiskOfferingVO.class); dquery.add(DiskOfferingVO_.uuid, SimpleQuery.Op.IN, struct.getDataDiskOfferingUuids()); List<DiskOfferingVO> vos = dquery.list(); // allow create multiple data volume from the same disk offering List<DiskOfferingInventory> disks = new ArrayList<>(); for (final String duuid : struct.getDataDiskOfferingUuids()) { DiskOfferingVO dvo = CollectionUtils.find(vos, new Function<DiskOfferingVO, DiskOfferingVO>() { @Override public DiskOfferingVO call(DiskOfferingVO arg) { if (duuid.equals(arg.getUuid())) { return arg; } return null; } }); disks.add(DiskOfferingInventory.valueOf(dvo)); } spec.setDataDiskOfferings(disks); } else { spec.setDataDiskOfferings(new ArrayList<>()); } if (struct.getRootDiskOfferingUuid() != null) { DiskOfferingVO rootDisk = dbf.findByUuid(struct.getRootDiskOfferingUuid(), DiskOfferingVO.class); spec.setRootDiskOffering(DiskOfferingInventory.valueOf(rootDisk)); } ImageVO imvo = dbf.findByUuid(spec.getVmInventory().getImageUuid(), ImageVO.class); if (imvo.getMediaType() == ImageMediaType.ISO) { new IsoOperator().attachIsoToVm(self.getUuid(), imvo.getUuid()); IsoSpec isoSpec = new IsoSpec(); isoSpec.setImageUuid(imvo.getUuid()); spec.setDestIso(isoSpec); } spec.getImageSpec().setInventory(ImageInventory.valueOf(imvo)); spec.setCurrentVmOperation(VmOperation.NewCreate); if (self.getZoneUuid() != null || self.getClusterUuid() != null || self.getHostUuid() != null) { spec.setHostAllocatorStrategy(HostAllocatorConstant.DESIGNATED_HOST_ALLOCATOR_STRATEGY_TYPE); } buildHostname(spec); spec.setUserdata(buildUserdata()); selectBootOrder(spec); String instanceOfferingOnlineChange = VmSystemTags.INSTANCEOFFERING_ONLIECHANGE. getTokenByResourceUuid(self.getUuid(), VmSystemTags.INSTANCEOFFERING_ONLINECHANGE_TOKEN); if (instanceOfferingOnlineChange != null && instanceOfferingOnlineChange.equals("true")) { spec.setInstanceOfferingOnlineChange(true); } spec.setConsolePassword(VmSystemTags.CONSOLE_PASSWORD. getTokenByResourceUuid(self.getUuid(), VmSystemTags.CONSOLE_PASSWORD_TOKEN)); changeVmStateInDb(VmInstanceStateEvent.starting); CollectionUtils.safeForEach(pluginRgty.getExtensionList(BeforeStartNewCreatedVmExtensionPoint.class), new ForEachFunction<BeforeStartNewCreatedVmExtensionPoint>() { @Override public void run(BeforeStartNewCreatedVmExtensionPoint ext) { ext.beforeStartNewCreatedVm(spec); } }); extEmitter.beforeStartNewCreatedVm(VmInstanceInventory.valueOf(self)); FlowChain chain = getCreateVmWorkFlowChain(inv); setFlowMarshaller(chain); chain.setName(String.format("create-vm-%s", self.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); chain.done(new FlowDoneHandler(completion) { @Override public void handle(final Map data) { VmInstanceSpec spec = (VmInstanceSpec) data.get(VmInstanceConstant.Params.VmInstanceSpec.toString()); self.setLastHostUuid(spec.getDestHost().getUuid()); self.setHostUuid(spec.getDestHost().getUuid()); self.setClusterUuid(spec.getDestHost().getClusterUuid()); self.setZoneUuid(spec.getDestHost().getZoneUuid()); self.setHypervisorType(spec.getDestHost().getHypervisorType()); self.setRootVolumeUuid(spec.getDestRootVolume().getUuid()); changeVmStateInDb(VmInstanceStateEvent.running); logger.debug(String.format("vm[uuid:%s] is running ..", self.getUuid())); VmInstanceInventory inv = VmInstanceInventory.valueOf(self); extEmitter.afterStartNewCreatedVm(inv); completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(final ErrorCode errCode, Map data) { extEmitter.failedToStartNewCreatedVm(VmInstanceInventory.valueOf(self), errCode); dbf.remove(self); // clean up EO, otherwise API-retry may cause conflict if // the resource uuid is set dbf.eoCleanup(VmInstanceVO.class); completion.fail(errf.instantiateErrorCode(SysErrors.OPERATION_ERROR, errCode)); } }).start(); } protected void startVm(final StartVmInstanceMsg msg, final SyncTaskChain taskChain) { startVm(msg, new Completion(taskChain) { @Override public void success() { VmInstanceInventory inv = VmInstanceInventory.valueOf(self); StartVmInstanceReply reply = new StartVmInstanceReply(); reply.setInventory(inv); bus.reply(msg, reply); taskChain.next(); } @Override public void fail(ErrorCode errorCode) { StartVmInstanceReply reply = new StartVmInstanceReply(); reply.setError(errf.instantiateErrorCode(VmErrors.START_ERROR, errorCode)); bus.reply(msg, reply); taskChain.next(); } }); } protected void startVm(final APIStartVmInstanceMsg msg, final SyncTaskChain taskChain) { startVm(msg, new Completion(taskChain) { @Override public void success() { VmInstanceInventory inv = VmInstanceInventory.valueOf(self); APIStartVmInstanceEvent evt = new APIStartVmInstanceEvent(msg.getId()); evt.setInventory(inv); bus.publish(evt); taskChain.next(); } @Override public void fail(ErrorCode errorCode) { APIStartVmInstanceEvent evt = new APIStartVmInstanceEvent(msg.getId()); evt.setError(errf.instantiateErrorCode(VmErrors.START_ERROR, errorCode)); bus.publish(evt); taskChain.next(); } }); } protected void handle(final APIStartVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getName() { return String.format("start-vm-%s", self.getUuid()); } @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { startVm(msg, chain); } }); } protected void handle(final APIDestroyVmInstanceMsg msg) { final APIDestroyVmInstanceEvent evt = new APIDestroyVmInstanceEvent(msg.getId()); destroyVm(msg, new Completion(msg) { @Override public void success() { bus.publish(evt); } @Override public void fail(ErrorCode errorCode) { evt.setError(errorCode); bus.publish(evt); } }); } private void destroyVm(APIDestroyVmInstanceMsg msg, final Completion completion) { final String issuer = VmInstanceVO.class.getSimpleName(); final List<VmDeletionStruct> ctx = new ArrayList<VmDeletionStruct>(); VmDeletionStruct s = new VmDeletionStruct(); s.setInventory(getSelfInventory()); s.setDeletionPolicy(deletionPolicyMgr.getDeletionPolicy(self.getUuid())); ctx.add(s); FlowChain chain = FlowChainBuilder.newSimpleFlowChain(); chain.setName(String.format("delete-vm-%s", msg.getUuid())); if (msg.getDeletionMode() == APIDeleteMessage.DeletionMode.Permissive) { chain.then(new NoRollbackFlow() { @Override public void run(final FlowTrigger trigger, Map data) { casf.asyncCascade(CascadeConstant.DELETION_CHECK_CODE, issuer, ctx, new Completion(trigger) { @Override public void success() { trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }).then(new NoRollbackFlow() { @Override public void run(final FlowTrigger trigger, Map data) { casf.asyncCascade(CascadeConstant.DELETION_DELETE_CODE, issuer, ctx, new Completion(trigger) { @Override public void success() { trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }); } else { chain.then(new NoRollbackFlow() { @Override public void run(final FlowTrigger trigger, Map data) { casf.asyncCascade(CascadeConstant.DELETION_FORCE_DELETE_CODE, issuer, ctx, new Completion(trigger) { @Override public void success() { trigger.next(); } @Override public void fail(ErrorCode errorCode) { trigger.fail(errorCode); } }); } }); } chain.done(new FlowDoneHandler(msg) { @Override public void handle(Map data) { casf.asyncCascadeFull(CascadeConstant.DELETION_CLEANUP_CODE, issuer, ctx, new NopeCompletion()); completion.success(); } }).error(new FlowErrorHandler(msg) { @Override public void handle(ErrorCode errCode, Map data) { completion.fail(errf.instantiateErrorCode(SysErrors.DELETE_RESOURCE_ERROR, errCode)); } }).start(); } protected void buildHostname(VmInstanceSpec spec) { String defaultHostname = VmSystemTags.HOSTNAME.getTag(self.getUuid()); if (defaultHostname == null) { return; } HostName dhname = new HostName(); dhname.setL3NetworkUuid(self.getDefaultL3NetworkUuid()); dhname.setHostname(VmSystemTags.HOSTNAME.getTokenByTag(defaultHostname, VmSystemTags.HOSTNAME_TOKEN)); spec.getHostnames().add(dhname); } protected VmInstanceSpec buildSpecFromInventory(VmInstanceInventory inv, VmOperation operation) { VmInstanceSpec spec = new VmInstanceSpec(); spec.setUserdata(buildUserdata()); // for L3Network that has been deleted List<String> nicUuidToDel = CollectionUtils.transformToList(inv.getVmNics(), new Function<String, VmNicInventory>() { @Override public String call(VmNicInventory arg) { return arg.getL3NetworkUuid() == null ? arg.getUuid() : null; } }); if (!nicUuidToDel.isEmpty()) { dbf.removeByPrimaryKeys(nicUuidToDel, VmNicVO.class); self = dbf.findByUuid(inv.getUuid(), VmInstanceVO.class); inv = VmInstanceInventory.valueOf(self); } spec.setDestNics(inv.getVmNics()); List<String> l3Uuids = CollectionUtils.transformToList(inv.getVmNics(), new Function<String, VmNicInventory>() { @Override public String call(VmNicInventory arg) { return arg.getL3NetworkUuid(); } }); spec.setL3Networks(L3NetworkInventory.valueOf(dbf.listByPrimaryKeys(l3Uuids, L3NetworkVO.class))); String huuid = inv.getHostUuid() == null ? inv.getLastHostUuid() : inv.getHostUuid(); if (huuid != null) { HostVO hvo = dbf.findByUuid(huuid, HostVO.class); if (hvo != null) { spec.setDestHost(HostInventory.valueOf(hvo)); } } List<VolumeInventory> dataVols = new ArrayList<VolumeInventory>(); for (VolumeInventory vol : inv.getAllVolumes()) { if (vol.getUuid().equals(inv.getRootVolumeUuid())) { spec.setDestRootVolume(vol); } else { dataVols.add(vol); } } List<BuildVolumeSpecExtensionPoint> exts = pluginRgty.getExtensionList( BuildVolumeSpecExtensionPoint.class); String vmUuid = inv.getUuid(); exts.forEach(e -> dataVols.addAll(e.supplyAdditionalVolumesForVmInstance(vmUuid))); spec.setDestDataVolumes(dataVols); // When starting an imported VM, we might not have an image UUID. if (inv.getImageUuid() != null) { ImageVO imgvo = dbf.findByUuid(inv.getImageUuid(), ImageVO.class); ImageInventory imginv = null; if (imgvo == null) { // the image has been deleted, use EO instead ImageEO imgeo = dbf.findByUuid(inv.getImageUuid(), ImageEO.class); imginv = ImageInventory.valueOf(imgeo); } else { imginv = ImageInventory.valueOf(imgvo); } spec.getImageSpec().setInventory(imginv); } spec.setVmInventory(inv); buildHostname(spec); String isoUuid = new IsoOperator().getIsoUuidByVmUuid(inv.getUuid()); if (isoUuid != null) { if (dbf.isExist(isoUuid, ImageVO.class)) { IsoSpec isoSpec = new IsoSpec(); isoSpec.setImageUuid(isoUuid); spec.setDestIso(isoSpec); } else { //TODO logger.warn(String.format("iso[uuid:%s] is deleted, however, the VM[uuid:%s] still has it attached", isoUuid, self.getUuid())); } } spec.setCurrentVmOperation(operation); selectBootOrder(spec); String instanceOfferingOnlineChange = VmSystemTags.INSTANCEOFFERING_ONLIECHANGE. getTokenByResourceUuid(self.getUuid(), VmSystemTags.INSTANCEOFFERING_ONLINECHANGE_TOKEN); if (instanceOfferingOnlineChange != null && instanceOfferingOnlineChange.equals("true")) { spec.setInstanceOfferingOnlineChange(true); } else { spec.setInstanceOfferingOnlineChange(false); } spec.setConsolePassword(VmSystemTags.CONSOLE_PASSWORD. getTokenByResourceUuid(self.getUuid(), VmSystemTags.CONSOLE_PASSWORD_TOKEN)); return spec; } protected void rebootVm(final Message msg, final Completion completion) { refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), null); if (allowed != null) { completion.fail(allowed); return; } VmInstanceInventory inv = VmInstanceInventory.valueOf(self); ErrorCode preReboot = extEmitter.preRebootVm(inv); if (preReboot != null) { completion.fail(preReboot); return; } final VmInstanceSpec spec = buildSpecFromInventory(inv, VmOperation.Reboot); spec.setDestHost(HostInventory.valueOf(dbf.findByUuid(self.getHostUuid(), HostVO.class))); final VmInstanceState originState = self.getState(); changeVmStateInDb(VmInstanceStateEvent.rebooting); extEmitter.beforeRebootVm(VmInstanceInventory.valueOf(self)); spec.setMessage(msg); FlowChain chain = getRebootVmWorkFlowChain(inv); setFlowMarshaller(chain); chain.setName(String.format("reboot-vm-%s", self.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); chain.done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { self = changeVmStateInDb(VmInstanceStateEvent.running); VmInstanceInventory inv = VmInstanceInventory.valueOf(self); extEmitter.afterRebootVm(inv); completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(final ErrorCode errCode, Map data) { extEmitter.failedToRebootVm(VmInstanceInventory.valueOf(self), errCode); if (HostErrors.FAILED_TO_STOP_VM_ON_HYPERVISOR.isEqual(errCode.getCode()) || HostErrors.FAILED_TO_START_VM_ON_HYPERVISOR.isEqual(errCode.getCode())) { checkState(originalCopy.getHostUuid(), new NoErrorCompletion(completion) { @Override public void done() { completion.fail(errCode); } }); } else { self.setState(originState); self = dbf.updateAndRefresh(self); completion.fail(errCode); } } }).start(); } protected void rebootVm(final APIRebootVmInstanceMsg msg, final SyncTaskChain taskChain) { rebootVm(msg, new Completion(taskChain) { @Override public void success() { APIRebootVmInstanceEvent evt = new APIRebootVmInstanceEvent(msg.getId()); VmInstanceInventory inv = VmInstanceInventory.valueOf(self); evt.setInventory(inv); bus.publish(evt); taskChain.next(); } @Override public void fail(ErrorCode errorCode) { APIRebootVmInstanceEvent evt = new APIRebootVmInstanceEvent(msg.getId()); evt.setError(errf.instantiateErrorCode(VmErrors.REBOOT_ERROR, errorCode)); bus.publish(evt); taskChain.next(); } }); } protected void handle(final APIRebootVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getName() { return String.format("reboot-vm-%s", self.getUuid()); } @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { rebootVm(msg, chain); } }); } protected void stopVm(final APIStopVmInstanceMsg msg, final SyncTaskChain taskChain) { stopVm(msg, new Completion(taskChain) { @Override public void success() { APIStopVmInstanceEvent evt = new APIStopVmInstanceEvent(msg.getId()); VmInstanceInventory inv = VmInstanceInventory.valueOf(self); evt.setInventory(inv); bus.publish(evt); taskChain.next(); } @Override public void fail(ErrorCode errorCode) { APIStopVmInstanceEvent evt = new APIStopVmInstanceEvent(msg.getId()); evt.setError(errf.instantiateErrorCode(VmErrors.STOP_ERROR, errorCode)); bus.publish(evt); taskChain.next(); } }); } private void stopVm(final Message msg, final Completion completion) { refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), null); if (allowed != null) { completion.fail(allowed); return; } if (self.getState() == VmInstanceState.Stopped) { completion.success(); return; } VmInstanceInventory inv = VmInstanceInventory.valueOf(self); ErrorCode preStop = extEmitter.preStopVm(inv); if (preStop != null) { completion.fail(preStop); return; } final VmInstanceSpec spec = buildSpecFromInventory(inv, VmOperation.Stop); spec.setMessage(msg); if (msg instanceof StopVmInstanceMsg) { spec.setGcOnStopFailure(((StopVmInstanceMsg) msg).isGcOnFailure()); } final VmInstanceState originState = self.getState(); changeVmStateInDb(VmInstanceStateEvent.stopping); extEmitter.beforeStopVm(VmInstanceInventory.valueOf(self)); FlowChain chain = getStopVmWorkFlowChain(inv); setFlowMarshaller(chain); chain.setName(String.format("stop-vm-%s", self.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); chain.done(new FlowDoneHandler(completion) { @Override public void handle(Map data) { self.setLastHostUuid(self.getHostUuid()); self.setHostUuid(null); self = changeVmStateInDb(VmInstanceStateEvent.stopped); VmInstanceInventory inv = VmInstanceInventory.valueOf(self); extEmitter.afterStopVm(inv); completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(final ErrorCode errCode, Map data) { VmInstanceInventory inv = VmInstanceInventory.valueOf(self); extEmitter.failedToStopVm(inv, errCode); if (HostErrors.FAILED_TO_STOP_VM_ON_HYPERVISOR.isEqual(errCode.getCode())) { checkState(originalCopy.getHostUuid(), new NoErrorCompletion(completion) { @Override public void done() { completion.fail(errCode); } }); } else { self.setState(originState); self = dbf.updateAndRefresh(self); completion.fail(errCode); } } }).start(); } protected void handle(final APIStopVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getName() { return String.format("stop-vm-%s", self.getUuid()); } @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { stopVm(msg, chain); } }); } protected void handle(final APICreateStopVmInstanceSchedulerMsg msg) { APICreateStopVmInstanceSchedulerEvent evt = new APICreateStopVmInstanceSchedulerEvent(msg.getId()); StopVmInstanceJob job = new StopVmInstanceJob(msg); job.setVmUuid(msg.getVmInstanceUuid()); job.setTargetResourceUuid(msg.getVmInstanceUuid()); SchedulerVO schedulerVO = schedulerFacade.runScheduler(job); acntMgr.createAccountResourceRef(msg.getSession().getAccountUuid(), schedulerVO.getUuid(), SchedulerVO.class); if (schedulerVO != null) { schedulerVO = dbf.reload(schedulerVO); SchedulerInventory sinv = SchedulerInventory.valueOf(schedulerVO); evt.setInventory(sinv); } bus.publish(evt); } protected void handle(final APICreateStartVmInstanceSchedulerMsg msg) { APICreateStartVmInstanceSchedulerEvent evt = new APICreateStartVmInstanceSchedulerEvent(msg.getId()); StartVmInstanceJob job = new StartVmInstanceJob(msg); job.setVmUuid(msg.getVmInstanceUuid()); job.setTargetResourceUuid(msg.getVmInstanceUuid()); SchedulerVO schedulerVO = schedulerFacade.runScheduler(job); acntMgr.createAccountResourceRef(msg.getSession().getAccountUuid(), schedulerVO.getUuid(), SchedulerVO.class); if (schedulerVO != null) { schedulerVO = dbf.reload(schedulerVO); SchedulerInventory sinv = SchedulerInventory.valueOf(schedulerVO); evt.setInventory(sinv); } bus.publish(evt); } protected void handle(final APICreateRebootVmInstanceSchedulerMsg msg) { APICreateRebootVmInstanceSchedulerEvent evt = new APICreateRebootVmInstanceSchedulerEvent(msg.getId()); RebootVmInstanceJob job = new RebootVmInstanceJob(msg); job.setVmUuid(msg.getVmInstanceUuid()); job.setTargetResourceUuid(msg.getVmInstanceUuid()); SchedulerVO schedulerVO = schedulerFacade.runScheduler(job); acntMgr.createAccountResourceRef(msg.getSession().getAccountUuid(), schedulerVO.getUuid(), SchedulerVO.class); if (schedulerVO != null) { schedulerVO = dbf.reload(schedulerVO); SchedulerInventory sinv = SchedulerInventory.valueOf(schedulerVO); evt.setInventory(sinv); } bus.publish(evt); } protected void pauseVm(final APIPauseVmInstanceMsg msg, final SyncTaskChain taskChain) { pauseVm(msg, new Completion(taskChain) { @Override public void success() { APIPauseVmInstanceEvent evt = new APIPauseVmInstanceEvent(msg.getId()); VmInstanceInventory inv = VmInstanceInventory.valueOf(self); evt.setInventory(inv); bus.publish(evt); taskChain.next(); } @Override public void fail(ErrorCode errorCode) { APIPauseVmInstanceEvent evt = new APIPauseVmInstanceEvent(msg.getId()); evt.setError(errf.instantiateErrorCode(VmErrors.SUSPEND_ERROR, errorCode)); bus.publish(evt); taskChain.next(); } }); } protected void pauseVm(final Message msg, Completion completion) { refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), null); if (allowed != null) { completion.fail(allowed); return; } if (self.getState() == VmInstanceState.Paused) { completion.success(); return; } VmInstanceInventory inv = VmInstanceInventory.valueOf(self); final VmInstanceSpec spec = buildSpecFromInventory(inv, VmOperation.Pause); spec.setMessage(msg); final VmInstanceState originState = self.getState(); changeVmStateInDb(VmInstanceStateEvent.pausing); FlowChain chain = getPauseVmWorkFlowChain(inv); setFlowMarshaller(chain); chain.setName(String.format("pause-vm-%s", self.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); chain.done(new FlowDoneHandler(completion) { @Override public void handle(Map Data) { self = changeVmStateInDb(VmInstanceStateEvent.paused); completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(final ErrorCode errCode, Map data) { self.setState(originState); self = dbf.updateAndRefresh(self); completion.fail(errCode); } }).start(); } protected void handle(final APIPauseVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { pauseVm(msg, chain); } @Override public String getName() { return String.format("pause-vm-%s", msg.getVmInstanceUuid()); } }); } protected void resumeVm(final APIResumeVmInstanceMsg msg, final SyncTaskChain taskChain) { resumeVm(msg, new Completion(taskChain) { @Override public void success() { APIResumeVmInstanceEvent evt = new APIResumeVmInstanceEvent(msg.getId()); VmInstanceInventory inv = VmInstanceInventory.valueOf(self); evt.setInventory(inv); bus.publish(evt); taskChain.next(); } @Override public void fail(ErrorCode errorCode) { APIResumeVmInstanceEvent evt = new APIResumeVmInstanceEvent(msg.getId()); evt.setError(errf.instantiateErrorCode(VmErrors.RESUME_ERROR, errorCode)); bus.publish(evt); taskChain.next(); } }); } protected void resumeVm(final Message msg, Completion completion) { refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), null); if (allowed != null) { completion.fail(allowed); return; } VmInstanceInventory inv = VmInstanceInventory.valueOf(self); final VmInstanceSpec spec = buildSpecFromInventory(inv, VmOperation.Resume); spec.setMessage(msg); final VmInstanceState originState = self.getState(); changeVmStateInDb(VmInstanceStateEvent.resuming); FlowChain chain = getResumeVmWorkFlowChain(inv); setFlowMarshaller(chain); chain.setName(String.format("resume-vm-%s", self.getUuid())); chain.getData().put(VmInstanceConstant.Params.VmInstanceSpec.toString(), spec); chain.done(new FlowDoneHandler(completion) { @Override public void handle(Map Data) { self = changeVmStateInDb(VmInstanceStateEvent.running); completion.success(); } }).error(new FlowErrorHandler(completion) { @Override public void handle(final ErrorCode errCode, Map data) { self.setState(originState); self = dbf.updateAndRefresh(self); completion.fail(errCode); } }).start(); } protected void handle(final APIResumeVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { resumeVm(msg, chain); } @Override public String getName() { return String.format("resume-vm-%s", msg.getVmInstanceUuid()); } }); } private void handle(final APIReimageVmInstanceMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(final SyncTaskChain chain) { reimageVmInstance(msg, new NoErrorCompletion(chain) { @Override public void done() { chain.next(); } }); } @Override public String getName() { return "reimage-vminstance"; } }); } private void reimageVmInstance(final APIReimageVmInstanceMsg msg, NoErrorCompletion completion) { final APIReimageVmInstanceEvent evt = new APIReimageVmInstanceEvent(msg.getId()); self = refreshVO(); VolumeVO rootVolume = dbf.findByUuid(self.getRootVolumeUuid(), VolumeVO.class); VolumeInventory rootVolumeInventory = VolumeInventory.valueOf(rootVolume); // check vm stopped { if (self.getState() != VmInstanceState.Stopped) { throw new ApiMessageInterceptionException(errf.instantiateErrorCode( VmErrors.RE_IMAGE_VM_NOT_IN_STOPPED_STATE, String.format("unable to reset volume[uuid:%s] to origin image[uuid:%s]," + " the vm[uuid:%s] volume attached to is not in Stopped state, current state is %s", rootVolume.getUuid(), rootVolume.getRootImageUuid(), rootVolume.getVmInstanceUuid(), self.getState()) )); } } // check image cache to ensure image type is not ISO { SimpleQuery<ImageCacheVO> q = dbf.createQuery(ImageCacheVO.class); q.select(ImageCacheVO_.mediaType); q.add(ImageCacheVO_.imageUuid, Op.EQ, rootVolume.getRootImageUuid()); q.setLimit(1); ImageMediaType imageMediaType = q.findValue(); if (imageMediaType == null) { throw new OperationFailureException(errf.instantiateErrorCode( VmErrors.RE_IMAGE_CANNOT_FIND_IMAGE_CACHE, String.format("unable to reset volume[uuid:%s] to origin image[uuid:%s]," + " cannot find image cache.", rootVolume.getUuid(), rootVolume.getRootImageUuid()) )); } if (imageMediaType.toString().equals("ISO")) { throw new OperationFailureException(errf.instantiateErrorCode( VmErrors.RE_IMAGE_IMAGE_MEDIA_TYPE_SHOULD_NOT_BE_ISO, String.format("unable to reset volume[uuid:%s] to origin image[uuid:%s]," + " for image type is ISO", rootVolume.getUuid(), rootVolume.getRootImageUuid()) )); } } // do the re-image op FlowChain chain = FlowChainBuilder.newShareFlowChain(); chain.setName(String.format("reset-root-volume-%s-from-image-%s", rootVolume.getUuid(), rootVolume.getRootImageUuid())); chain.then(new ShareFlow() { String newVolumeInstallPath; @Override public void setup() { flow(new NoRollbackFlow() { String __name__ = "reset-root-volume-from-image-on-primary-storage"; @Override public void run(final FlowTrigger trigger, Map data) { ReInitRootVolumeFromTemplateOnPrimaryStorageMsg rmsg = new ReInitRootVolumeFromTemplateOnPrimaryStorageMsg(); rmsg.setVolume(rootVolumeInventory); bus.makeTargetServiceIdByResourceUuid(rmsg, PrimaryStorageConstant.SERVICE_ID, rootVolumeInventory.getPrimaryStorageUuid()); bus.send(rmsg, new CloudBusCallBack(trigger) { @Override public void run(MessageReply reply) { if (reply.isSuccess()) { ReInitRootVolumeFromTemplateOnPrimaryStorageReply re = (ReInitRootVolumeFromTemplateOnPrimaryStorageReply) reply; newVolumeInstallPath = re.getNewVolumeInstallPath(); trigger.next(); } else { trigger.fail(reply.getError()); } } }); } }); done(new FlowDoneHandler(msg, completion) { @Override public void handle(Map data) { rootVolume.setInstallPath(newVolumeInstallPath); dbf.update(rootVolume); List<AfterReimageVmInstanceExtensionPoint> list = pluginRgty.getExtensionList( AfterReimageVmInstanceExtensionPoint.class); for (AfterReimageVmInstanceExtensionPoint ext : list) { ext.afterReimageVmInstance(rootVolumeInventory); } self = dbf.reload(self); evt.setInventory(VmInstanceInventory.valueOf(self)); bus.publish(evt); completion.done(); } }); error(new FlowErrorHandler(msg, completion) { @Override public void handle(ErrorCode errCode, Map data) { logger.warn(String.format("failed to restore volume[uuid:%s] to image[uuid:%s], %s", rootVolumeInventory.getUuid(), rootVolumeInventory.getRootImageUuid(), errCode)); evt.setError(errCode); bus.publish(evt); completion.done(); } }); } }).start(); } }
package de.prob2.ui.animations; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Singleton; import de.prob.model.representation.AbstractElement; import de.prob.model.representation.AbstractModel; import de.prob.scripting.ModelTranslationError; import de.prob.statespace.AnimationSelector; import de.prob.statespace.IAnimationChangeListener; import de.prob.statespace.Trace; import de.prob.statespace.Transition; import de.prob2.ui.beditor.BEditorStage; import de.prob2.ui.internal.StageManager; import de.prob2.ui.prob2fx.CurrentTrace; import javafx.application.Platform; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.ContextMenu; import javafx.scene.control.MenuItem; import javafx.scene.control.TableColumn; import javafx.scene.control.TableRow; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.MouseButton; import javafx.scene.layout.AnchorPane; @Singleton public final class AnimationsView extends AnchorPane implements IAnimationChangeListener { @FXML private TableView<Animation> animationsTable; @FXML private TableColumn<Animation, String> machine; @FXML private TableColumn<Animation, String> lastop; @FXML private TableColumn<Animation, String> tracelength; @FXML private TableColumn<Animation, String> time; private static final Logger LOGGER = LoggerFactory.getLogger(AnimationsView.class); private final AnimationSelector animations; private final CurrentTrace currentTrace; private final StageManager stageManager; private int currentIndex; private int previousSize = 0; private Injector injector; @Inject private AnimationsView(final Injector injector, final AnimationSelector animations, final StageManager stageManager, CurrentTrace currentTrace) { this.injector = injector; this.animations = animations; this.animations.registerAnimationChangeListener(this); this.currentTrace = currentTrace; this.stageManager = stageManager; this.stageManager.loadFXML(this, "animations_view.fxml"); } @FXML public void initialize() { machine.setCellValueFactory(new PropertyValueFactory<>("modelName")); lastop.setCellValueFactory(new PropertyValueFactory<>("lastOperation")); tracelength.setCellValueFactory(new PropertyValueFactory<>("steps")); time.setCellValueFactory(new PropertyValueFactory<>("time")); animationsTable.setRowFactory(tableView -> { final TableRow<Animation> row = new TableRow<>(); final MenuItem removeMenuItem = new MenuItem("Remove Trace"); removeMenuItem.setOnAction(event -> { Animation a = row.getItem(); animations.removeTrace(a.getTrace()); animationsTable.getItems().remove(a); }); removeMenuItem.disableProperty().bind(row.emptyProperty()); final MenuItem removeAllMenuItem = new MenuItem("Remove All Traces"); removeAllMenuItem.setOnAction(event -> { removeAllTraces(); }); final MenuItem reloadMenuItem = new MenuItem("Reload"); reloadMenuItem.setOnAction(event -> { try { currentTrace.reload(row.getItem().getTrace()); } catch (IOException | ModelTranslationError e) { LOGGER.error("Model reload failed", e); stageManager.makeAlert(Alert.AlertType.ERROR, "Failed to reload model:\n" + e).showAndWait(); } }); reloadMenuItem.disableProperty().bind(row.emptyProperty()); row.setContextMenu(new ContextMenu(removeMenuItem, removeAllMenuItem, reloadMenuItem)); row.setOnMouseClicked(event -> { if (!row.isEmpty() && event.getButton() == MouseButton.PRIMARY) { currentIndex = row.getIndex(); Trace trace = row.getItem().getTrace(); animations.changeCurrentAnimation(trace); } }); return row; }); this.traceChange(animations.getCurrentTrace(), true); animationsTable.setOnMouseClicked(e -> { Animation selectedItem = animationsTable.getSelectionModel().getSelectedItem(); if (e.getClickCount() >= 2 && selectedItem != null) { selectedItem.openEditor(); } }); } private void removeAllTraces() { ObservableList<Animation> animationsList = animationsTable.getItems(); for (Animation a : animationsList) { animations.removeTrace(a.getTrace()); } animationsList.clear(); } @Override public void traceChange(Trace currentTrace, boolean currentAnimationChanged) { List<Trace> traces = animations.getTraces(); List<Animation> animList = new ArrayList<>(); for (Trace t : traces) { AbstractModel model = t.getModel(); AbstractElement mainComponent = t.getStateSpace().getMainComponent(); String modelName = mainComponent == null ? model.getModelFile().getName() : mainComponent.toString(); Transition op = t.getCurrentTransition(); String lastOp = op == null ? "" : op.getPrettyRep().replace("< String steps = Integer.toString(t.getTransitionList().size()); boolean isCurrent = t.equals(currentTrace); boolean isProtected = animations.getProtectedTraces().contains(t.getUUID()); Animation a = new Animation(modelName, lastOp, steps, t, isCurrent, isProtected, getEditorStage(model)); Animation aa = contains(animationsTable, a); if (aa == null) { a.setTime(LocalDateTime.now()); } else { a.setTime(LocalDateTime.parse(aa.getTime(), DateTimeFormatter.ofPattern("HH:mm:ss d MMM uuuu"))); } animList.add(a); } Platform.runLater(() -> { ObservableList<Animation> animationsList = animationsTable.getItems(); animationsList.clear(); animationsList.addAll(animList); if (previousSize < animationsList.size()) { currentIndex = animationsList.size() - 1; } else if (previousSize > animationsList.size() && currentIndex > 0) { currentIndex } animationsTable.getFocusModel().focus(currentIndex); previousSize = animationsList.size(); }); } private BEditorStage getEditorStage(AbstractModel model) { BEditorStage editorStage = injector.getInstance(BEditorStage.class); String text = ""; Path path = null; try { path = model.getModelFile().toPath(); text = Files.lines(path).collect(Collectors.joining(System.lineSeparator())); } catch (IOException e) { LOGGER.error("File not found", e); } editorStage.setEditorText(text, path); editorStage.setTitle(model.getModelFile().getName()); return editorStage; } private Animation contains(TableView<Animation> animTable, Animation animation) { if (animTable != null) { for (Animation a : animTable.getItems()) { if (a.getTrace().getUUID().equals(animation.getTrace().getUUID())) { return a; } } } return null; } @Override public void animatorStatus(boolean busy) { // Not used } public TableView<Animation> getTable() { return animationsTable; } }
package cubicchunks.converter.lib.util; import com.flowpowered.nbt.ByteArrayTag; import com.flowpowered.nbt.ByteTag; import com.flowpowered.nbt.CompoundMap; import com.flowpowered.nbt.CompoundTag; import com.flowpowered.nbt.IntArrayTag; import com.flowpowered.nbt.IntTag; import com.flowpowered.nbt.ListTag; import com.flowpowered.nbt.stream.NBTInputStream; import com.flowpowered.nbt.stream.NBTOutputStream; import cubicchunks.regionlib.impl.EntryLocation3D; import cubicchunks.regionlib.util.CheckedConsumer; import cubicchunks.regionlib.util.CheckedFunction; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.nio.ByteBuffer; import java.nio.file.DirectoryStream; import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.Collections; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import java.util.zip.InflaterInputStream; import static java.util.Collections.emptyList; public class Utils { /** * Returns a consumer that checks for interruption, and throws {@link UncheckedInterruptedException} * if thread is interrupted. */ public static <T, E extends Throwable> CheckedConsumer<T, E> interruptibleConsumer(CheckedConsumer<T, E> cons) { return x -> { if (Thread.interrupted()) { throw new UncheckedInterruptedException(); } cons.accept(x); }; } public static <IN, OUT> Function<IN, OUT> propagateExceptions(CheckedFunction<IN, OUT, ?> func) { return x -> { try { return func.apply(x); } catch (Throwable t) { return throwUnchecked(t); } }; } @SuppressWarnings("unchecked") private static <T, E extends Throwable> T throwUnchecked(Throwable t) throws E { throw (E) t; } // Files.createDirectories doesn't handle symlinks public static void createDirectories(Path dir) throws IOException { if (Files.isDirectory(dir)) { return; } createDirectories(dir.getParent()); try { Files.createDirectory(dir); } catch (FileAlreadyExistsException ex) {} } public static boolean isValidPath(String text) { try { Files.exists(Paths.get(text)); return true; } catch (InvalidPathException e) { return false; } } public static boolean fileExists(String text) { try { return Files.exists(Paths.get(text)); } catch (InvalidPathException e) { return false; } } public static int countFiles(Path f) throws IOException { try { return countFiles_do(f); } catch (UncheckedIOException e) { throw e.getCause(); } } private static int countFiles_do(Path f) { if (Files.isRegularFile(f)) { return 1; } else if (!Files.isDirectory(f)) { throw new UnsupportedOperationException(); } try (Stream<Path> stream = Files.list(f)) { return stream.mapToInt(Utils::countFiles_do).sum(); } catch (IOException e) { throw new UncheckedIOException(e); } } public static void copyEverythingExcept(Path file, Path srcDir, Path dstDir, Predicate<Path> excluded, Consumer<Path> onCopy) throws IOException { try (Stream<Path> stream = Files.list(file)) { stream.forEach(f -> { if (!excluded.test(f)) { try { copyFile(f, srcDir, dstDir); if (Files.isRegularFile(f)) { onCopy.accept(f); } if (Files.isDirectory(f)) { copyEverythingExcept(f, srcDir, dstDir, excluded, onCopy); } else if (!Files.isRegularFile(f)) { throw new UnsupportedOperationException(); } } catch (IOException e) { throw new UncheckedIOException(e); } } }); } catch (UncheckedIOException e) { throw e.getCause(); } } public static void copyFile(Path srcFile, Path srcDir, Path dstDir) throws IOException { Path relative = srcDir.relativize(srcFile); Path dstFile = dstDir.resolve(relative); // TODO: handle symlinks Files.createDirectories(dstFile.getParent()); if (Files.isDirectory(srcFile)) { if(!Files.exists(dstFile)) { Files.createDirectories(dstFile); } return; } Files.copy(srcFile, dstFile, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); } public static CompoundTag readCompressed(InputStream is) throws IOException { int i = is.read(); BufferedInputStream data; if (i == 1) { data = new BufferedInputStream(new GZIPInputStream(is)); } else if (i == 2) { data = new BufferedInputStream(new InflaterInputStream(is)); } else { throw new UnsupportedOperationException(); } return (CompoundTag) new NBTInputStream(data, false).readTag(); } public static CompoundTag readCompressedCC(InputStream is) throws IOException { BufferedInputStream data = new BufferedInputStream(new GZIPInputStream(is)); return (CompoundTag) new NBTInputStream(data, false).readTag(); } public static ByteBuffer writeCompressed(CompoundTag tag, boolean prefixFormat) throws IOException { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); if (prefixFormat) { bytes.write(1); // mark as GZIP } NBTOutputStream nbtOut = new NBTOutputStream(new BufferedOutputStream(new GZIPOutputStream(bytes)), false); nbtOut.writeTag(tag); nbtOut.close(); bytes.flush(); return ByteBuffer.wrap(bytes.toByteArray()); } public static ByteBuffer createAirCubeBuffer(EntryLocation3D loc) { CompoundTag compoundTag = Utils.emptyCube(loc.getEntryX(), loc.getEntryY(), loc.getEntryZ()); try { return Utils.writeCompressed(compoundTag, false); } catch(IOException e) { throw new Error("Writing known NBT to ByteBuffer shouldn't throw IOException", e); } } public static CompoundTag emptyCube(int x, int y, int z) { CompoundMap root = new CompoundMap(); { CompoundMap level = new CompoundMap(); { level.put(new ByteTag("v", (byte) 1)); level.put(new IntTag("x", x)); level.put(new IntTag("y", y)); level.put(new IntTag("z", z)); level.put(new ByteTag("populated", true)); level.put(new ByteTag("fullyPopulated", true)); level.put(new ByteTag("isSurfaceTracked", true)); // it's empty, no need to re-track level.put(new ListTag<>("Sections", CompoundTag.class, Collections.singletonList(createEmptySectionTag()))); level.put(new ByteTag("initLightDone", false)); level.put(new ListTag<>("Entities", CompoundTag.class, emptyList())); level.put(new ListTag<>("TileEntities", CompoundTag.class, emptyList())); level.put(makeEmptyLightingInfo()); } root.put(new CompoundTag("Level", level)); } return new CompoundTag("", root); } public static CompoundTag createEmptySectionTag() { CompoundMap sectionData = new CompoundMap(); sectionData.put("Blocks", new ByteArrayTag("Blocks", new byte[4096])); sectionData.put("Data", new ByteArrayTag("Data", new byte[2048])); sectionData.put("BlockLight", new ByteArrayTag("BlockLight", new byte[2048])); sectionData.put("SkyLight", new ByteArrayTag("SkyLight", new byte[2048])); return new CompoundTag("", sectionData); } private static CompoundTag makeEmptyLightingInfo() { IntArrayTag heightmap = new IntArrayTag("LastHeightMap", new int[256]); CompoundMap lightingInfoMap = new CompoundMap(); lightingInfoMap.put(heightmap); return new CompoundTag("LightingInfo", lightingInfoMap); } /** * Deletes the specified file or directory, recursively */ public static void rm(Path toDelete) throws IOException { if (Files.isDirectory(toDelete)) { try (Stream<Path> files = Files.list(toDelete)) { for (Path path : files.collect(Collectors.toList())) { rm(path); } } Files.delete(toDelete); } else { Files.delete(toDelete); } } public static boolean isEmpty(final Path directory) throws IOException { if (!Files.exists(directory)) { return true; } try(DirectoryStream<Path> dirStream = Files.newDirectoryStream(directory)) { return !dirStream.iterator().hasNext(); } } public static <E extends Throwable> void forEachDirectory(Path directory, CheckedConsumer<Path, E> consumer) throws E, IOException { try(DirectoryStream<Path> dirStream = Files.newDirectoryStream(directory)) { for (Path path : dirStream) { if (Files.isDirectory(path)) { consumer.accept(path); } } } } private enum OS { WINDOWS, MACOS, SOLARIS, LINUX, UNKNOWN; } private static OS getPlatform() { String osName = System.getProperty("os.name").toLowerCase(); if (osName.contains("win")) { return OS.WINDOWS; } if (osName.contains("mac")) { return OS.MACOS; } if (osName.contains("linux")) { return OS.LINUX; } if (osName.contains("unix")) { return OS.LINUX; } return OS.UNKNOWN; } public static Path getApplicationDirectory() { String userHome = System.getProperty("user.home", "."); Path workingDirectory; switch (getPlatform()) { case LINUX: case SOLARIS: workingDirectory = Paths.get(userHome, ".minecraft/"); break; case WINDOWS: String applicationData = System.getenv("APPDATA"); String folder = applicationData != null ? applicationData : userHome; workingDirectory = Paths.get(folder, ".minecraft/"); break; case MACOS: workingDirectory = Paths.get(userHome, "Library/Application Support/minecraft"); break; default: workingDirectory = Paths.get(userHome, "minecraft/"); } return workingDirectory; } }
package pitt.search.semanticvectors; import java.io.File; import java.io.IOException; import java.lang.RuntimeException; import java.util.Hashtable; import java.util.Enumeration; import java.util.Random; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriter.MaxFieldLength; import org.apache.lucene.index.Term; import org.apache.lucene.index.TermDocs; import org.apache.lucene.index.TermEnum; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.util.Version; /** * Implementation of vector store that creates term vectors by * iterating through all the terms in a Lucene index. Uses a sparse * representation for the basic document vectors, which saves * considerable space for collections with many individual documents. * * @author Dominic Widdows, Trevor Cohen. */ public class TermVectorsFromLucene implements VectorStore { private Hashtable<String, ObjectVector> termVectors; private IndexReader indexReader; private int seedLength; private String[] fieldsToIndex; private LuceneUtils lUtils; private int nonAlphabet; private int minFreq; private VectorStore basicDocVectors; // Basic accessor methods. /** * @return The object's basicDocVectors. */ public VectorStore getBasicDocVectors(){ return this.basicDocVectors; } /** * @return The object's indexReader. */ public IndexReader getIndexReader(){ return this.indexReader; } /** * @return The object's list of Lucene fields to index. */ public String[] getFieldsToIndex(){ return this.fieldsToIndex; } // Implementation of basic VectorStore methods. public float[] getVector(Object term) { return termVectors.get(term).getVector(); } public Enumeration getAllVectors() { return termVectors.elements(); } public int getNumVectors() { return termVectors.size(); } /** * @param indexDir Directory containing Lucene index. * @param seedLength Number of +1 or -1 entries in basic * vectors. Should be even to give same number of each. * @param minFreq The minimum term frequency for a term to be indexed. * @param basicDocVectors The store of basic document vectors. Null * is an acceptable value, in which case the constructor will build * this table. If non-null, the identifiers must correspond to the Lucene doc numbers. * @param fieldsToIndex These fields will be indexed. If null, all fields will be indexed. */ public TermVectorsFromLucene(String indexDir, int seedLength, int minFreq, int nonAlphabet, VectorStore basicDocVectors, String[] fieldsToIndex) throws IOException, RuntimeException { this.minFreq = minFreq; this.nonAlphabet = nonAlphabet; this.fieldsToIndex = fieldsToIndex; this.seedLength = seedLength; LuceneUtils.CompressIndex(indexDir); // Create LuceneUtils Class to filter terms. lUtils = new LuceneUtils(indexDir); indexReader = IndexReader.open(FSDirectory.open(new File(indexDir))); // Check that basicDocVectors is the right size. if (basicDocVectors != null) { this.basicDocVectors = basicDocVectors; System.out.println("Reusing basic doc vectors; number of documents: " + basicDocVectors.getNumVectors()); if (basicDocVectors.getNumVectors() != indexReader.numDocs()) { throw new RuntimeException("Wrong number of basicDocVectors " + "passed into constructor ..."); } } else { // Create basic doc vectors in vector store. // Derived term vectors will be linear combinations of these. System.err.println("Populating basic sparse doc vector store, number of vectors: " + indexReader.numDocs()); VectorStoreSparseRAM randomBasicDocVectors = new VectorStoreSparseRAM(); randomBasicDocVectors.CreateRandomVectors(indexReader.numDocs(), this.seedLength); this.basicDocVectors = randomBasicDocVectors; } createTermVectors(); } // Training method for term vectors. private void createTermVectors() throws IOException { termVectors = new Hashtable<String, ObjectVector>(); // Iterate through an enumeration of terms and create termVector table. System.err.println("Creating term vectors ..."); TermEnum terms = this.indexReader.terms(); int tc = 0; while(terms.next()){ tc++; } System.err.println("There are " + tc + " terms (and " + indexReader.numDocs() + " docs)"); tc = 0; terms = indexReader.terms(); while (terms.next()) { // Output progress counter. if (( tc % 10000 == 0 ) || ( tc < 10000 && tc % 1000 == 0 )) { System.err.print(tc + " ... "); } tc++; Term term = terms.term(); // Skip terms that don't pass the filter. if (!lUtils.termFilter(terms.term(), fieldsToIndex)) { continue; } // Initialize new termVector. float[] termVector = new float[Flags.dimension]; for (int i = 0; i < Flags.dimension; ++i) { termVector[i] = 0; } TermDocs tDocs = indexReader.termDocs(term); while (tDocs.next()) { String docID = Integer.toString(tDocs.doc()); int freq = tDocs.freq(); if (this.basicDocVectors.getClass().equals(VectorStoreSparseRAM.class)) //random docvectors { termVector = VectorUtils.addVectors(termVector, ((VectorStoreSparseRAM) this.basicDocVectors).getSparseVector(docID), freq); } else //pretrained docvectors { termVector = VectorUtils.addVectors(termVector, this.basicDocVectors.getVector(docID),freq); } } termVector = VectorUtils.getNormalizedVector(termVector); termVectors.put(term.text(), new ObjectVector(term.text(), termVector)); } System.err.println("\nCreated " + termVectors.size() + " term vectors ..."); } /** * This constructor generates an elemental vector for each * term. These elemental (random index) vectors will be used to * construct document vectors, a procedure we have called term-based * reflective random indexing. * * @param indexDir the directory of the Lucene Index * @param seedLength Number of +1 or -1 entries in basic * vectors. Should be even to give same number of each. * @param nonAlphabet the number of nonalphabet characters permitted * @param minFreq The minimum term frequency for a term to be indexed. * @param fieldsToIndex the fields to be indexed (most commonly "contents") */ public TermVectorsFromLucene(String indexDir, int seedLength, int minFreq, int nonAlphabet, String[] fieldsToIndex) throws IOException, RuntimeException { this.minFreq = minFreq; this.nonAlphabet = nonAlphabet; this.fieldsToIndex = fieldsToIndex; this.seedLength = seedLength; LuceneUtils.CompressIndex(indexDir); // Create LuceneUtils Class to filter terms. lUtils = new LuceneUtils(indexDir); indexReader = IndexReader.open(FSDirectory.open(new File(indexDir))); Random random = new Random(); this.termVectors = new Hashtable<String,ObjectVector>(); // For each term in the index if (Flags.initialtermvectors.equals("random")) { System.err.println("Creating random term vectors"); TermEnum terms = indexReader.terms(); int tc = 0; while(terms.next()){ Term term = terms.term(); // Skip terms that don't pass the filter. if (!lUtils.termFilter(terms.term(), fieldsToIndex)) { continue; } tc++; short[] indexVector = VectorUtils.generateRandomVector(seedLength, random); // Place each term vector in the vector store. this.termVectors.put(term.text(), new ObjectVector(term.text(), VectorUtils.sparseVectorToFloatVector( indexVector, Flags.dimension))); } } else { System.err.println("Using semantic term vectors from file " + Flags.initialtermvectors); VectorStore inputReader = new VectorStoreReaderLucene(Flags.initialtermvectors); Enumeration<ObjectVector> termEnumeration = inputReader.getAllVectors(); int count = 0; while (termEnumeration.hasMoreElements()) { ObjectVector next = termEnumeration.nextElement(); String term = next.getObject().toString(); this.termVectors.put(term, next); count++; } System.err.println("Read in "+count+" vectors"); } } }
package inte; import java.io.File; public class Ls { public static void main(String... args) { File[] files = new File("C:/Inte/").listFiles(); showFiles(files); } public static void showFiles(File[] files) { for (File file : files) { // if (file.isDirectory()) { // System.out.println("Directory: " + file.getName()); // showFiles(file.listFiles()); // Calls same method again. // } else { System.out.println("File: " + file.getName()); } } }
package cz.jcu.prf.uai.javamugs.logic; import sun.reflect.generics.reflectiveObjects.NotImplementedException; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.stream.Stream; public class Parser { final private static int B_SIZE_LIMIT = 5*1024*1024; /** * Opens track file and parses into PressChart. * Expected file format is [milliseconds from song beginning]:[number denoting its color] * without braces, one entry per line. * @param fileName Path to the track file to be parsed. * @param timeOffset Defines the offset of chords draw time and press time. * Positive offset means draw comes before press (recommended). * @return Parsed PressChart, never null. * @throws IOException: failed opening file, unexpected format */ public PressChart parseFile(String fileName, double timeOffset) throws IOException { throw new NotImplementedException(); } /** * * @param fileName * @return * @throws IOException: file is not found, file cannot be opened, * unexpected extension (.prc), file is too large (max 5MB) */ private Stream<String> attemptOpenFile(String fileName) throws IOException { if (!fileName.endsWith(".prc")) throw new IOException("Unexpected extension"); Path path = Paths.get(fileName); try{ if (Files.notExists(path) ) throw new IOException("File not found."); if (Files.size(path) > B_SIZE_LIMIT) throw new IOException("File is too large"); } catch (SecurityException e){ throw new IOException("Access to file denied."); } throw new NotImplementedException(); } }
package pl.polidea.navigator; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import pl.polidea.navigator.factories.FragmentFactoryBase; import pl.polidea.navigator.factories.FragmentFactoryInterface; import pl.polidea.navigator.factories.NavigationMenuFactoryBase; import pl.polidea.navigator.factories.NavigationMenuFactoryInterface; import pl.polidea.navigator.menu.AbstractNavigationMenu; import pl.polidea.navigator.retrievers.AssetMenuRetriever; import pl.polidea.navigator.retrievers.MenuRetrieverInterface; import pl.polidea.navigator.ui.BreadcrumbFragment; import android.app.Application; import android.util.DisplayMetrics; import com.apphance.android.Log; /** * Application that should be extended by any menu navigation application. */ public class MenuNavigatorBaseApplication extends Application { private static final String TAG = MenuNavigatorBaseApplication.class.getSimpleName(); private MenuRetrieverInterface firstTimeMenuRetriever; private AbstractNavigationMenu navigationMenu; private NavigationMenuFactoryInterface navigationMenuFactory; private FragmentFactoryInterface fragmentFactory; private MenuRetrieverInterface timedRunMenuRetriever; private ScheduledExecutorService executor; private Properties localConfig; private String flurryKey; @Override public void onCreate() { readLocalConfig(); setupFlurryKey(); createBaseFactories(); super.onCreate(); } private void setupFlurryKey() { flurryKey = localConfig.getProperty("flurry_key"); } public Properties getLocalConfig() { return localConfig; } protected void readLocalConfig() { final int configResId = getResources().getIdentifier("local_config", "raw", getPackageName()); if (configResId > 0) { Log.d(TAG, "Reading mPay configuration from raw resources using res id = " + configResId); try { localConfig = new Properties(); final InputStream is = getResources().openRawResource(configResId); try { localConfig.load(is); } finally { is.close(); } Log.d(TAG, "Properties read: " + localConfig); } catch (final IOException e) { Log.d(TAG, "Exception while reading configuration." + e, e); } } else { Log.d(TAG, "Skipping loading configuration - the local_config file is missing"); } } protected void createBaseFactories() { firstTimeMenuRetriever = createFirstTimeMenuRetriever(); timedRunMenuRetriever = createTimedRunMenuRetriever(); navigationMenuFactory = createNavigationMenuFactory(); fragmentFactory = createFragmentFactory(); } public final AbstractNavigationMenu getNavigationMenu() { return navigationMenu; } public final FragmentFactoryInterface getFragmentFactory() { return fragmentFactory; } public final NavigationMenuFactoryInterface getJsonReaderFactory() { return navigationMenuFactory; } public final MenuRetrieverInterface getFirstTimeMenuRetriever() { return firstTimeMenuRetriever; } public MenuRetrieverInterface getTimedMenuRetriever() { return timedRunMenuRetriever; } public final NavigationMenuFactoryInterface getNavigationMenuFactory() { return navigationMenuFactory; } protected MenuRetrieverInterface createFirstTimeMenuRetriever() { return new AssetMenuRetriever(this, "testmenu", "menu"); } protected MenuRetrieverInterface createTimedRunMenuRetriever() { return null; } protected FragmentFactoryBase createFragmentFactory() { return new FragmentFactoryBase(); } protected NavigationMenuFactoryInterface createNavigationMenuFactory() { return new NavigationMenuFactoryBase(); } public BreadcrumbFragment createBreadcrumbFragment() { return new BreadcrumbFragment(); } public BitmapReader getBitmapReader(final DisplayMetrics displayMetrics) { return new BitmapReader(this, getFirstTimeMenuRetriever(), displayMetrics, R.drawable.warning); } public final void setNavigationMenu(final AbstractNavigationMenu navigationMenu) { this.navigationMenu = navigationMenu; } protected void startTimerRetrieverThread(final long initialDelay, final long delay, final TimeUnit timeUnit) { final MenuRetrieverInterface timedRetriever = getTimedMenuRetriever(); if (timedRetriever == null) { Log.d(TAG, "Skipping timer startup because there is no timed retriever."); return; } executor = Executors.newScheduledThreadPool(1); executor.scheduleWithFixedDelay(new Runnable() { @Override public void run() { try { Log.d(TAG, "Scheduled run started for menu retrieval."); try { timedRetriever.copyMenu(); } catch (final IOException e) { Log.w(TAG, "Error while retrieving menu from remote: ", e); } Log.d(TAG, "Scheduled run finished for menu retrieval."); } catch (final Throwable t) { // NOPMD - it is needed here to // show any errors that might // occur. Log.w(TAG, "Error when retrieving new menu: ", t); } } }, initialDelay, delay, TimeUnit.SECONDS); Log.d(TAG, "Scheduled menu retrieval to run after few seconds, every hour,"); } public final String getFlurryKey() { return flurryKey; } }
package edu.ucdenver.ccp.common.file; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.io.filefilter.FileFilterUtils; import org.apache.commons.io.filefilter.IOFileFilter; import edu.ucdenver.ccp.common.collections.CollectionsUtil; import edu.ucdenver.ccp.common.io.StreamUtil; import edu.ucdenver.ccp.common.string.StringConstants; import edu.ucdenver.ccp.common.string.StringUtil; /** * Utility class for working with files and directories * * @author Center for Computational Pharmacology; ccp-support@ucdenver.edu * */ public class FileUtil { /** * Private constructor; do not instantiate this utility class */ /* @formatter:off */ private FileUtil() {/* do not instantiate */ } /* @formatter:on */ /** * Returns a temporary directory based on the File.createTempFile() method * @param directoryName * @return * @throws IOException if an error occurs while creating the temporary directory */ public static File createTemporaryDirectory(String directoryName) throws IOException { File tempFile = File.createTempFile("tmp","tmp"); File directory = new File(tempFile.getParentFile(), directoryName); FileUtil.mkdir(directory); return directory; } /** * Simple utility method that checks whether the input directory exists (and is a directory). * Returns an error message if the directory does not exist or is not a directory. Returns null * if the directory exists as expected. * * @param directory * @return */ public static String isDirectoryValid(File directory) { String errorMessage = null; if (!directory.exists()) { errorMessage = String.format("Directory does not exist: %s", directory.getAbsolutePath()); } else if (!directory.isDirectory()) { errorMessage = String.format("Input directory is not a directory: %s", directory.getAbsolutePath()); } return errorMessage; } /** * Checks to see if the directory exists, and if it is truly a directory. Throws a * FileNotFoundException if the input is not a true/existing directory. * * @param directory * @throws FileNotFoundException */ public static void validateDirectory(File directory) throws FileNotFoundException { String message = FileUtil.isDirectoryValid(directory); if (message != null) { throw new FileNotFoundException(message); } } /** * Simple utility method that checks whether the input file exists (and is a file). Returns an * error message if the file does not exist or is not a file (i.e. it's a directory instead). * Returns null if the directory exists as expected. * * @param directory * @return */ public static String isFileValid(File file) { String errorMessage = null; if (!file.exists()) { errorMessage = String.format("File does not exist: %s", file.getAbsolutePath()); } else if (!file.isFile()) { errorMessage = String.format("Input file is not a file: %s", file.getAbsolutePath()); } return errorMessage; } /** * Checks to see if the file exists, and if it is truly a file. Throws a FileNotFoundException * if the input is not a true/existing file. * * @param file * @throws FileNotFoundException */ public static void validateFile(File file) throws FileNotFoundException { String message = FileUtil.isFileValid(file); if (message != null) { throw new FileNotFoundException(message); } } public static void mkdir(File directory) throws IllegalStateException { if (!directory.exists()) { boolean succeeded = directory.mkdirs(); if (!succeeded) { throw new IllegalStateException(String.format("Error while creating directory: %s", directory .getAbsolutePath())); } } } /** * Recursively deletes the contents of a directory, and the directory itself * * @param directory * @return */ public static boolean deleteDirectory(File directory) { boolean success = true; if (directory.exists()) { File[] files = directory.listFiles(); for (File f : files) { if (f.isDirectory()) { deleteDirectory(f); } else { success = success && f.delete(); } } } return success && directory.delete(); } /** * Deletes the specified file * * @param file * @throws RuntimeException * if the file.delete() operation fails */ public static void deleteFile(File file) { if (file.exists()) if (!file.delete()) throw new RuntimeException(String.format("Error while deleting file: %s", file.getAbsolutePath())); } /** * Deletes files from a given directory, does not touch directories. * * @param directory * @return */ public static boolean deleteFilesFromDirectory(File directory) { if (directory.exists()) { for (File f : directory.listFiles()) { if (f.isFile()) { if (!f.delete()) { return false; } } } return true; } return false; } /** * Deletes a directory (including any contents) and recreates it so that it is empty * * @param directory * @return */ public static boolean cleanDirectory(File directory) { deleteDirectory(directory); return directory.mkdirs(); } /** * Deletes the input file and replaces it with a new empty file of the same name * * @param file * the file to clean * @throws IOException * if an error occurs during the cleaning process */ public static void cleanFile(File file) throws IOException { deleteFile(file); if (!file.createNewFile()) throw new IOException("File could not be re-created during clean: " + file.getAbsolutePath()); } /** * Copies the contents of the InputStream to the specified File * * @param is * @param file * @throws IOException */ public static void copy(InputStream is, File file) throws IOException { BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(file)); copy(is, outStream); } /** * Copies a file to the specified output stream * * @param file * @param os * @throws IOException */ public static void copy(File file, OutputStream os) throws IOException { FileInputStream fis = new FileInputStream(file); copy(fis, os); fis.close(); } /** * Copies the contents of one file to another * * @param fromFile * @param toFile * @throws IOException */ public static void copy(File fromFile, File toFileOrDirectory) throws IOException { validateFile(fromFile); FileInputStream fis = new FileInputStream(fromFile); File toFile = toFileOrDirectory; if (toFileOrDirectory.isDirectory()) { toFile = FileUtil.appendPathElementsToDirectory(toFileOrDirectory, fromFile.getName()); } FileOutputStream fos = new FileOutputStream(toFile); copy(fis, fos); fis.close(); fos.close(); validateFile(toFile); } /** * Copies the contents of the specified file to a <code>String</code> using the specified * character encoding * * @param fromFile * @param fromFileEncoding * @return * @throws IOException */ public static String copyToString(File fromFile, CharacterEncoding fromFileEncoding) throws IOException { validateFile(fromFile); return StreamUtil.toString(new InputStreamReader(new FileInputStream(fromFile), fromFileEncoding.getDecoder())); } /** * Copies the specified InputStream to the specified OutputStream * * @param is * @param os * @throws IOException */ public static void copy(InputStream is, OutputStream os) throws IOException { try { IOUtils.copyLarge(is, os); } finally { IOUtils.closeQuietly(os); } } /** * Creates a file name filter that accepts files based on the fileSuffix input parameter * * @return */ public static FilenameFilter createFilenameSuffixFilter(final String... fileSuffixes) { FilenameFilter filter = new FilenameFilter() { @Override public boolean accept(@SuppressWarnings("unused") File dir, String name) { for (String fileSuffix : fileSuffixes) { if (name.endsWith(fileSuffix)) { return true; } } return false; } }; return filter; } public static byte[] toByteArray(File file) throws IOException { FileInputStream fis = new FileInputStream(file); byte[] bytes = IOUtils.toByteArray(fis); fis.close(); return bytes; } /** * Returns a reference to a File that is specified by the input file name, and located in the * input directory. The file is not created, only the reference. * * @param directory * @param fileName * @return */ public static File appendPathElementsToDirectory(File directory, String... pathElements) { StringBuffer sb = new StringBuffer(directory.getPath()); for (String pathElement : pathElements) { sb.append(File.separator + pathElement); } return new File(sb.toString()); } /** * Returns an Iterator<File> over the files in the input directory. Only visible (i.e. not * hidden) files and directories will be processed. * * @param fileOrDirectory * @param recurse * @param fileSuffixes * @return * @throws IOException */ public static Iterator<File> getFileIterator(File fileOrDirectory, boolean recurse, String... fileSuffixes) throws IOException { if (FileUtil.isFileValid(fileOrDirectory) == null) { return createSingleFileIterator(fileOrDirectory, fileSuffixes); } else if (FileUtil.isDirectoryValid(fileOrDirectory) == null) { return FileUtils.iterateFiles(fileOrDirectory, createFileFilter(removeLeadingPeriods(fileSuffixes)), createDirectoryFilter(recurse)); } else throw new IOException(String.format("Input is not a valid file or directory: %s", fileOrDirectory .getAbsolutePath())); } /** * Returns a List<File> over the files in the input directory. Only visible (i.e. not hidden) * files and directories will be processed. The list is sorted using the * java.util.Collections.sort() method. * * @param fileOrDirectory * @param recurse * @param fileSuffixes * @return * @throws IOException */ public static List<File> getFileListing(File fileOrDirectory, boolean recurse, String... fileSuffixes) throws IOException { List<File> list = CollectionsUtil.createList(getFileIterator(fileOrDirectory, recurse, fileSuffixes)); Collections.sort(list); return list; } /** * Returns an IOFileFilter that accepts only file with the input suffixes. Files must also be * visible. * * @param suffixes * @return */ private static IOFileFilter createFileFilter(String... suffixes) { IOFileFilter fileFilter = FileFilterUtils.and(FileFilterUtils.fileFileFilter(), createVisibleFileFilter()); if (suffixes != null && suffixes.length > 0) { IOFileFilter suffixFilter = FileFilterUtils.suffixFileFilter(suffixes[0]); for (int i = 1; i < suffixes.length; i++) { suffixFilter = FileFilterUtils.or(suffixFilter, FileFilterUtils.suffixFileFilter(suffixes[i])); } fileFilter = FileFilterUtils.and(fileFilter, suffixFilter); } return fileFilter; } /** * Creates a file filter that ignores hidden files * * @return */ private static IOFileFilter createVisibleFileFilter() { return FileFilterUtils.notFileFilter(FileFilterUtils.prefixFileFilter(".")); } /** * Returns an IOFileFilter set up to either accept directories (if recurse == true) or to only * accept files (if recurse == false). Directories must be visible. * * @param recurse * @return */ private static IOFileFilter createDirectoryFilter(boolean recurse) { if (recurse) return FileFilterUtils.and(FileFilterUtils.directoryFileFilter(), createVisibleFileFilter()); return FileFilterUtils.and(FileFilterUtils.fileFileFilter(), createVisibleFileFilter()); } /** * Returns a FileFilter that accepts directories only * * @return */ public static FileFilter DIRECTORY_FILTER() { return new FileFilter() { @Override public boolean accept(File file) { return file.isDirectory(); } }; } /** * Returns the set of directories in the specified directory * * @param directory * @return * @throws FileNotFoundException */ public static Set<File> getDirectories(File directory) throws FileNotFoundException { validateDirectory(directory); File[] directories = directory.listFiles(DIRECTORY_FILTER()); return new HashSet<File>(Arrays.asList(directories)); } /** * Returns a set containing the directory names in the input directory * * @param directory * @return * @throws FileNotFoundException */ public static Set<String> getDirectoryNames(File directory) throws FileNotFoundException { Set<File> directories = getDirectories(directory); Set<String> directoryNames = new HashSet<String>(); for (File dir : directories) directoryNames.add(dir.getName()); return directoryNames; } /** * * leading periods need to be removed or else the FileUtils.iteratorFiles method does not work * as expected * * @param fileSuffixes * @return */ private static String[] removeLeadingPeriods(String[] fileSuffixes) { if (fileSuffixes != null) { for (int i = 0; i < fileSuffixes.length; i++) { if (fileSuffixes[i].startsWith(".")) { fileSuffixes[i] = fileSuffixes[i].substring(1); } } } return fileSuffixes; } /** * Creates an iterator over a single File object. File must be visible and must match one of the * input file suffixes if specified. * * @param file * @param fileSuffixes * @return */ private static Iterator<File> createSingleFileIterator(File file, String... fileSuffixes) { File inputFile = file; if (file.getName().startsWith(".")) inputFile = null; if (inputFile != null && fileSuffixes != null) if (!FileUtil.createFilenameSuffixFilter(fileSuffixes).accept(inputFile.getParentFile(), inputFile.getName())) inputFile = null; final File singleFile = inputFile; return new Iterator<File>() { private File nextFile = singleFile; @Override public boolean hasNext() { return nextFile != null; } @Override public File next() { if (!hasNext()) { throw new NoSuchElementException(); } File fileToReturn = nextFile; nextFile = null; return fileToReturn; } @Override public void remove() { throw new UnsupportedOperationException("The remove() method is not supported for this iterator."); } }; } /** * Returns an Iterator<File> over the files in the input directory * * @param fileOrDirectory * @param recurse * @return * @throws IOException */ public static Iterator<File> getFileIterator(File fileOrDirectory, boolean recurse) throws IOException { return getFileIterator(fileOrDirectory, recurse, (String[]) null); } /** * Returns a File object with a relative path to the input directory * * @param file * @param directory * @return */ public static File getFileRelativeToDirectory(File file, File directory) { String directoryStr = directory.getAbsolutePath(); String fileStr = file.getAbsolutePath(); if (!fileStr.startsWith(directoryStr)) throw new IllegalArgumentException(String.format( "Cannot determine relative file. Input file is not inside input directory. File=%s Directory=%s", fileStr, directoryStr)); String relativeFileStr = fileStr.substring(directoryStr.length()); return new File(relativeFileStr); } /** * @param file * @return the terminal file suffix for the specified file */ public static String getFileSuffix(File file) { String fileName = file.getName(); return getFileSuffix(fileName); } /** * Returns the terminal file suffix for the input file name * * @param fileName * the name of the file to process * @return the last file suffix that is part of the input file name */ private static String getFileSuffix(String fileName) { int lastIndexOfPeriod = fileName.lastIndexOf("."); if (lastIndexOfPeriod == -1) return ""; return fileName.substring(lastIndexOfPeriod); } /** * Returns a reference to the input file with all file suffixes removed * * @param file * the file to process * @return a reference to the input file with all file suffixes removed */ public static File removeFileSuffixes(File file) { File suffixlessFile = new File(file.getAbsolutePath()); String fileSuffix = null; while (!(fileSuffix = getFileSuffix(suffixlessFile)).isEmpty()) suffixlessFile = new File(StringUtil.removeSuffix(suffixlessFile.getAbsolutePath(), fileSuffix)); return suffixlessFile; } /** * Appends the specified file suffix to the end of the file name referenced by the input File * object * * @param file * the file to add the suffix to * @param suffix * the suffix to add * @return a reference to a file that is the input file appended with the input suffix */ public static File appendFileSuffix(File file, String suffix) { File path = file.getParentFile(); String fileName = file.getName(); if (suffix.startsWith(StringConstants.PERIOD)) suffix = suffix.substring(1); return new File(path, String.format("%s.%s", fileName, suffix)); } /** * Returns the number of lines in the input file * * @param file * the number of lines in this file will be returned * @param encoding * the character encoding used in the file * @return the number of lines in the input file * @throws IOException */ public static long getLineCount(File file, CharacterEncoding encoding) throws IOException { long lineCount = 0; BufferedReader reader = null; try { reader = FileReaderUtil.initBufferedReader(file, encoding); /* * The 'line' variable is unnecessary here, however if (reader.readLine() == null) is * used, a FindBugs warning is generated. */ @SuppressWarnings("unused") String line; while ((line = reader.readLine()) != null) lineCount++; return lineCount; } finally { if (reader != null) reader.close(); } } }
package de.dakror.arise.game.building; import java.awt.Graphics2D; import de.dakror.arise.game.Game; import de.dakror.arise.game.world.City; import de.dakror.gamesetup.util.Helper; /** * @author Dakror */ public class Center extends Building { public Center(int x, int y, int level) { super(x, y, 6, 6, level); typeId = 1; name = level > 3 ? "Stadtzentrum" : "Dorfzentrum"; init(); } @Override public void drawStage1(Graphics2D g) { Helper.setRenderingHints(g, false); Helper.drawImage2(Game.getImage("world/TileB.png"), x, y, width, height, City.levels[level][0], City.levels[level][1], City.levels[level][2], City.levels[level][3], g); Helper.setRenderingHints(g, true); } @Override public void update(int tick) { super.update(tick); name = level > 3 ? "Stadtzentrum" : "Dorfzentrum"; } }
package com.forgeessentials.api.snooper; import com.google.gson.*; import cpw.mods.fml.common.FMLCommonHandler; import net.minecraft.nbt.JsonToNBT; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTException; import net.minecraft.server.MinecraftServer; import net.minecraftforge.common.config.Configuration; import java.lang.reflect.Type; /** * If you want your own query response, extend this file and override * getResponceString(DatagramPacket packet) * * @author Dries007 */ public abstract class Response { protected final MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance(); protected static final Gson GSON = (new GsonBuilder()) .registerTypeHierarchyAdapter(NBTBase.class, new NBTBaseAdapter()) .setPrettyPrinting() .create(); public int id; public boolean allowed = true; public abstract JsonElement getResponce(JsonObject jsonElement) throws JsonParseException; public abstract String getName(); public abstract void readConfig(String category, Configuration config); public abstract void writeConfig(String category, Configuration config); private static class NBTBaseAdapter implements JsonDeserializer<NBTBase>, JsonSerializer<NBTBase> { @Override public JsonElement serialize(NBTBase src, Type typeOfSrc, JsonSerializationContext context) { return (new JsonParser()).parse(src.toString()); } @Override public NBTBase deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)throws JsonParseException { try { return parseAsJson(GSON.toJson(json)); } catch (NBTException e) { e.printStackTrace(); return null; } } private NBTBase parseAsJson(String string) throws NBTException { return JsonToNBT.func_150315_a(string) ; } } }
package com.uwetrottmann.shopr.algorithm; import com.uwetrottmann.shopr.algorithm.model.Item; import java.util.ArrayList; import java.util.List; public class BoundedGreedySelection { public static final double ALPHA = 0.5; /** * Chooses <code>bound*limit</code> items most similar to current query. * Returns <code>limit</code> items most similar to query and most * dissimilar to already selected items out of those. */ public static List<Item> boundedGreedySelection(Query query, List<Item> caseBase, int limit, int bound) { Utils.sortBySimilarityToQuery(query, caseBase); // TODO: get first b*k items List<Item> recommendations = new ArrayList<Item>(); // add recommendations for (int i = 0; i < limit; i++) { sortByQuality(caseBase, recommendations, query); // get top item, remove it from remaining cases recommendations.add(caseBase.remove(0)); } return recommendations; } /** * Calculates the quality for each item, sorts the case base with highest * quality first. */ private static void sortByQuality(List<Item> caseBase, List<Item> recommendations, Query query) { // TODO Sort by quality for (Item item : caseBase) { double quality = ALPHA * item.querySimilarity() + (1 - ALPHA) * relativeDiversity(item, recommendations); } } /** * Calculates the relative diversity of an item to the current list of * recommendations. */ private static double relativeDiversity(Item item, List<Item> recommendations) { if (recommendations.size() == 0) { // default to 1 for R={} return 1; } double similarity = 0; for (Item recommendation : recommendations) { similarity += 1 - Similarity.similarity(item.attributes(), recommendation.attributes()); } similarity /= recommendations.size(); return similarity; } }
package de.prob2.ui.plugin; import java.io.File; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.ResourceBundle; import java.util.stream.Collectors; import javax.annotation.Nonnull; import com.github.zafarkhaja.semver.Version; import com.google.inject.Inject; import com.google.inject.Singleton; import de.prob.Main; import de.prob2.ui.config.FileChooserManager; import de.prob2.ui.config.FileChooserManager.Kind; import de.prob2.ui.internal.StageManager; import de.prob2.ui.internal.StopActions; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.stage.DirectoryChooser; import javafx.stage.FileChooser; import javafx.stage.Modality; import javafx.stage.Stage; import org.apache.commons.lang.StringUtils; import org.pf4j.DefaultPluginManager; import org.pf4j.PluginDependency; import org.pf4j.PluginDescriptor; import org.pf4j.PluginException; import org.pf4j.PluginFactory; import org.pf4j.PluginState; import org.pf4j.PluginWrapper; import org.pf4j.RuntimeMode; import org.pf4j.util.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The {@link ProBPluginManager} is a wrapper for the {@link ProBJarPluginManager} which is an * implementation of the PF4J {@link org.pf4j.DefaultPluginManager}. * * {@link ProBPluginManager} has methods to start the plugin manager, to reload the plugins and * to add plugins using a {@link FileChooser}. * * @author Christoph Heinzen * @since 10.08.2017 */ @Singleton public class ProBPluginManager { private static final Logger LOGGER = LoggerFactory.getLogger(ProBPluginManager.class); private static final String VERSION = "0.1.0"; private static final File PLUGIN_DIRECTORY = new File(Main.getProBDirectory() + File.separator + "prob2ui" + File.separator + "plugins"); private final ProBPluginHelper proBPluginHelper; private final StageManager stageManager; private final ResourceBundle bundle; private final FileChooserManager fileChooserManager; private List<String> inactivePluginIds; private File pluginDirectory; private ProBJarPluginManager pluginManager; /** * Should only be used by the Guice-Injector. * Do not call this constructor. * * @param proBPluginHelper singleton instance of {@link ProBPluginHelper} used in the prob2-ui application * @param stageManager singleton instance of {@link StageManager} used in the prob2-ui application * @param bundle {@link ResourceBundle} used in the prob2-ui application */ @Inject public ProBPluginManager(ProBPluginHelper proBPluginHelper, StageManager stageManager, ResourceBundle bundle, final FileChooserManager fileChooserManager, final StopActions stopActions) { this.proBPluginHelper = proBPluginHelper; this.stageManager = stageManager; this.bundle = bundle; this.pluginManager = new ProBJarPluginManager(); createPluginDirectory(); this.fileChooserManager = fileChooserManager; // Do not convert this to a method reference! Otherwise it won't work correctly if the plugin manager changes. stopActions.add(() -> this.getPluginManager().stopPlugins()); } /** * Getter for the current {@link ProBJarPluginManager}, that the application is using. * * @return Return the current {@link ProBJarPluginManager} */ public ProBJarPluginManager getPluginManager() { return pluginManager; } /* * methods to add functionality */ /** * Shows a {@link FileChooser} to select a plugin. * If the user selects a plugin, the selected file will be copied into to the plugins-directory. * After that the plugin gets loaded and started if necessary. * If an error occurs, an {@link Alert} with an error message will be shown. * */ public void addPlugin() { //let the user select a plugin-file Stage stage = stageManager.getCurrent(); final File selectedPlugin = showFileChooser(stage); if (selectedPlugin != null && createPluginDirectory()) { String pluginFileName = selectedPlugin.getName(); File plugin = new File(getPluginDirectory() + File.separator + pluginFileName); try { if (copyPluginFile(selectedPlugin, plugin)) { String pluginId = pluginManager.loadPlugin(plugin.toPath()); if (checkLoadedPlugin(pluginId, pluginFileName) && getInactivePluginIds() != null && !getInactivePluginIds().contains(pluginId)) { pluginManager.startPlugin(pluginId); } } } catch (Exception e) { LOGGER.warn("Tried to copy and load/start the plugin {}.\nThis exception was thrown: ", pluginFileName, e); showWarningAlert("plugin.alerts.couldNotLoadPlugin.content", pluginFileName); //if an error occurred, delete the plugin file PluginWrapper wrapper = pluginManager.getPlugin(plugin.toPath()); if (wrapper != null) { pluginManager.deletePlugin(wrapper.getPluginId()); } try { Files.deleteIfExists(plugin.toPath()); } catch (IOException ex) { LOGGER.warn("Could not delete file {}.", pluginFileName); } } } } /** * This method loads all plugins in the plugins directory and * starts the plugin if it is not marked as inactive in the {@code inactive.txt} file. */ public void start() { pluginManager.loadPlugins(); List<String> inactivePluginIds = getInactivePluginIds(); if (inactivePluginIds != null) { for (PluginWrapper plugin : pluginManager.getPlugins()) { String pluginId = plugin.getPluginId(); if (!inactivePluginIds.contains(pluginId)) { pluginManager.startPlugin(pluginId); } } } else { showWarningAlert("plugin.alerts.couldNotLocateInactive.content", getPluginDirectory()); } } /** * This method unloads all loaded plugins and after that calls the * {@code start} method of the {@link ProBPluginManager}. */ public void reloadPlugins() { List<PluginWrapper> loadedPlugins = pluginManager.getPlugins(); for (PluginWrapper plugin : loadedPlugins) { pluginManager.unloadPlugin(plugin.getPluginId()); } start(); } /** * Changes the directory where PF4J searches for plugins. * Because PF4J does not allow it to change the directory, we have * to create a new instance of the {@link ProBJarPluginManager}. * * @return Returns the plugins in the new directory. */ List<PluginWrapper> changePluginDirectory() { DirectoryChooser chooser = new DirectoryChooser(); chooser.setTitle(bundle.getString("plugin.pluginMenu.directoryChooser.changePath.title")); chooser.setInitialDirectory(getPluginDirectory()); File newPath = chooser.showDialog(stageManager.getCurrent()); if (newPath != null) { //unload all plugins List<PluginWrapper> loadedPlugins = pluginManager.getPlugins(); for (PluginWrapper plugin : loadedPlugins) { pluginManager.unloadPlugin(plugin.getPluginId()); } //set new path pluginDirectory = newPath; //initialize the PluginManager using the new path pluginManager = new ProBJarPluginManager(); //load an start the plugins start(); return pluginManager.getPlugins(); } return null; } /** * Getter for the singleton instance of the {@link ProBPluginHelper} of * the prob2-ui application. * * @return singleton instance of the {@link ProBPluginHelper} */ public ProBPluginHelper getProBPluginHelper() { return proBPluginHelper; } /** * Saves the ids of every inactive plugin in the {@code inactive.txt} file. * A plugin is inactive if its state is not {@code PluginState.STARTED}. */ void writeInactivePlugins() { try { if (createPluginDirectory()) { File inactivePlugins = getInactivePluginsFile(); if (!inactivePlugins.exists() && !inactivePlugins.createNewFile()) { LOGGER.warn("Could not create file for inactive plugins!"); return; } inactivePluginIds = pluginManager.getPlugins().stream() .filter(pluginWrapper -> pluginWrapper.getPluginState() != PluginState.STARTED) .map(PluginWrapper::getPluginId) .collect(Collectors.toList()); FileUtils.writeLines(inactivePluginIds, inactivePlugins); } } catch (IOException e) { LOGGER.warn("An error occurred while writing the inactive plugins:", e); } } /* * private methods used to add a new plugin */ private boolean copyPluginFile(File source, File destination) { if (destination.exists()) { //if there is already a file with the name, try to find the corresponding plugin PluginWrapper wrapper = pluginManager.getPlugin(destination.toPath()); if (wrapper != null) { //if there is a corresponding plugin, ask the user if he wants to overwrite it List<ButtonType> buttons = new ArrayList<>(); buttons.add(ButtonType.YES); buttons.add(ButtonType.NO); Alert alert = stageManager.makeAlert(Alert.AlertType.CONFIRMATION, buttons, "", "plugin.alerts.confirmOverwriteExistingFile.content", destination.getName(), ((ProBPlugin) wrapper.getPlugin()).getName(), wrapper.getDescriptor().getVersion()); alert.initOwner(stageManager.getCurrent()); Optional<ButtonType> result = alert.showAndWait(); if (result.isPresent() && result.get() == ButtonType.YES) { //if he wants to overwrite, delete the plugin pluginManager.deletePlugin(wrapper.getPluginId()); } else { //if he doesn't want to overwrite it, do nothing return false; } } else { //if there is no corresponding plugin, delete the file try { Files.deleteIfExists(destination.toPath()); } catch (IOException ex) { LOGGER.warn("Could not delete file {}.", destination.getName()); showWarningAlert("plugin.alerts.couldNotDeleteJar.content", destination.getName()); return false; } } } try { //copy the selected file into the plugins directory Files.copy(source.toPath(), destination.toPath()); return true; } catch (IOException e) { showWarningAlert("plugin.alerts.couldNotCopyToPluginDirectory.content", destination.getName()); } return false; } private boolean checkLoadedPlugin(String loadedPluginId, String pluginFileName) throws PluginException { if (loadedPluginId == null) { // error while loading the plugin throw new PluginException("Could not load the plugin '{}'.", pluginFileName); } else { PluginWrapper pluginWrapper = pluginManager.getPlugin(loadedPluginId); if (pluginWrapper.getPlugin() instanceof InvalidPlugin) { InvalidPlugin invPlug = (InvalidPlugin) pluginWrapper.getPlugin(); Alert alert; if (invPlug.getException() != null) { alert = stageManager.makeExceptionAlert(invPlug.getException(), invPlug.getMessageBundleKey(), invPlug.getPluginClassName()); } else { alert = stageManager.makeAlert(Alert.AlertType.WARNING, "", invPlug.getMessageBundleKey(), invPlug.getPluginClassName()); } alert.initOwner(stageManager.getCurrent()); alert.initModality(Modality.APPLICATION_MODAL); alert.show(); } //because we don't use the enabled/disabled.txt of PF4J, the only reason for a //plugin to be disabled is, when it has the wrong version if (pluginWrapper.getPluginState() == PluginState.DISABLED) { showWarningAlert("plugin.alerts.wrongUIversion.content", pluginWrapper.getPluginPath().getFileName(), pluginWrapper.getDescriptor().getRequires(), pluginManager.getSystemVersion()); pluginManager.deletePlugin(loadedPluginId); return false; } } return true; } private File showFileChooser(@Nonnull final Stage stage) { final FileChooser fileChooser = new FileChooser(); fileChooser.setTitle(bundle.getString("plugin.fileChooser.addPlugin.title")); String proB2PluginFileExtension = "*.jar"; fileChooser.getExtensionFilters() .addAll(new FileChooser.ExtensionFilter(String.format(bundle.getString("common.fileChooser.fileTypes.proB2Plugin"), proB2PluginFileExtension), proB2PluginFileExtension)); return fileChooserManager.showOpenDialog(fileChooser, Kind.PLUGINS, stage); } /* * methods to handle the inactive plugins */ private void readInactivePlugins() { try { File inactivePlugins = getInactivePluginsFile(); if (inactivePlugins.exists()) { //if we already have a incative plugins file, read it inactivePluginIds = FileUtils.readLines(inactivePlugins.toPath(), true); } else { //if not, try to create an empty file if (!createPluginDirectory() || !inactivePlugins.createNewFile() ) { LOGGER.warn("Could not create file for inactive plugins!"); } inactivePluginIds = null; } } catch (IOException e) { LOGGER.warn("An error occurred while reading the inactive plugins:", e); } } private List<String> getInactivePluginIds() { if (inactivePluginIds == null) { readInactivePlugins(); } return inactivePluginIds; } private File getInactivePluginsFile() { return new File(getPluginDirectory() + File.separator + "inactive.txt"); } /* * methods to handle the plugin directory */ private boolean createPluginDirectory() { File directory = getPluginDirectory(); if (!directory.exists() && !directory.mkdirs()) { LOGGER.warn("Couldn't create the directory for plugins!\n{}", directory.getAbsolutePath()); return false; } return true; } public File getPluginDirectory() { if (pluginDirectory != null) { return pluginDirectory; } return PLUGIN_DIRECTORY; } /** * Do not call this method. */ public void setPluginDirectory(String path) { if (path != null) { this.pluginDirectory = new File(path); //initialize with the new PluginDirectory pluginManager = new ProBJarPluginManager(); } } /* * GUI helper methods */ private void showWarningAlert(String bundleKey, Object... stringParams) { Alert alert = stageManager.makeAlert(Alert.AlertType.WARNING, "", bundleKey, stringParams); alert.initOwner(stageManager.getCurrent()); alert.show(); } /** * Slightly changed version of the PF4J-{@link org.pf4j.DefaultPluginManager} * * {@inheritDoc} * * Overwrites the {@code createPluginFactory} method to use {@link ProBPlugin} as plugin clazz, * the {@code createPluginsRoot} method to set the plugins directory and the {@code getRuntimeMode} * to avoid the development mode of PF4J. * * @author Christoph Heinzen * @since 23.08.2017 * @see org.pf4j.DefaultPluginManager * @see org.pf4j.AbstractPluginManager */ public class ProBJarPluginManager extends DefaultPluginManager { private ProBJarPluginManager(){ setSystemVersion(Version.valueOf(VERSION).toString()); setExactVersionAllowed(true); } @Override protected Path createPluginsRoot() { if (pluginDirectory != null) { if (createPluginDirectory()) { return pluginDirectory.toPath(); } LOGGER.warn("Couldn't create plugin directory {}. Using the default directory {}.", pluginDirectory, PLUGIN_DIRECTORY); } return PLUGIN_DIRECTORY.toPath(); } @Override //changed to use the ProBPlugin clazz protected PluginFactory createPluginFactory() { return pluginWrapper -> { String pluginClassName = pluginWrapper.getDescriptor().getPluginClass(); LOGGER.debug("Create instance for plugin '{}'", pluginClassName); Class<?> pluginClass; try { pluginClass = pluginWrapper.getPluginClassLoader().loadClass(pluginClassName); } catch (ClassNotFoundException e) { LOGGER.error(e.getMessage(), e); return new InvalidPlugin(pluginWrapper, "plugin.invalidPlugin.message.couldNotFindPluginClass", pluginClassName, e); } // once we have the clazz, we can do some checks on it to ensure // that it is a valid implementation of a plugin. int modifiers = pluginClass.getModifiers(); if (Modifier.isAbstract(modifiers) || Modifier.isInterface(modifiers) || (!ProBPlugin.class.isAssignableFrom(pluginClass))) { LOGGER.error("The plugin clazz '{}' is not a valid ProBPlugin", pluginClassName); return new InvalidPlugin(pluginWrapper, "plugin.invalidPlugin.message.notAValidPluginClass", pluginClassName); } // create the ProBPlugin instance try { Constructor<?> constructor = pluginClass.getConstructor(PluginWrapper.class, ProBPluginManager.class, ProBPluginHelper.class); return (ProBPlugin) constructor.newInstance(pluginWrapper, ProBPluginManager.this, proBPluginHelper); } catch (Exception e) { LOGGER.error(e.getMessage(), e); return new InvalidPlugin(pluginWrapper, "plugin.invalidPlugin.message.couldNotCreateInstance", pluginClassName, e); } }; } @Override public RuntimeMode getRuntimeMode() { return RuntimeMode.DEPLOYMENT; } @Override //also checked required version protected void validatePluginDescriptor(PluginDescriptor descriptor) throws PluginException { //TODO: show what is wrong in an alert super.validatePluginDescriptor(descriptor); if (StringUtils.isEmpty(descriptor.getRequires()) || descriptor.getRequires().equals("*")) { throw new PluginException("Plugin-Requires has to be specified!"); } if (!descriptor.getDependencies().isEmpty()) { StringBuilder builder = new StringBuilder("Plugin-Dependencies are not supported but the plugin has the following dependencies:"); for (PluginDependency dependency : descriptor.getDependencies()) { builder.append(System.getProperty("line.separator")); builder.append(dependency.getPluginId()); } throw new PluginException(builder.toString()); } } private PluginWrapper getPlugin(Path pluginPath) { for (PluginWrapper pluginWrapper : getPlugins()) { if (pluginWrapper.getPluginPath().equals(pluginPath)) { return pluginWrapper; } } return null; } } }
package com.frameworkium.tests.internal; import com.frameworkium.capture.ScreenshotCapture; import com.frameworkium.config.DriverSetup; import com.frameworkium.config.DriverType; import com.frameworkium.config.WebDriverWrapper; import com.frameworkium.listeners.*; import com.frameworkium.reporting.AllureProperties; import com.saucelabs.common.SauceOnDemandAuthentication; import com.saucelabs.common.SauceOnDemandSessionIdProvider; import com.saucelabs.testng.SauceOnDemandAuthenticationProvider; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.remote.SessionId; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Listeners; import ru.yandex.qatools.allure.Allure; import ru.yandex.qatools.allure.annotations.Issue; import ru.yandex.qatools.allure.annotations.TestCaseId; import ru.yandex.qatools.allure.events.StepFinishedEvent; import ru.yandex.qatools.allure.events.StepStartedEvent; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; @Listeners({CaptureListener.class, ScreenshotListener.class, MethodInterceptor.class, SauceLabsListener.class, TestListener.class, ResultLoggerListener.class}) public abstract class BaseTest implements SauceOnDemandSessionIdProvider, SauceOnDemandAuthenticationProvider { private static ThreadLocal<Boolean> requiresReset; private static ThreadLocal<ScreenshotCapture> capture; private static ThreadLocal<DriverType> driverType; private static List<DriverType> activeDriverTypes = new ArrayList<>(); private static Logger logger = LogManager.getLogger(BaseTest.class); public static String userAgent; /** * Method which runs first upon running a test, it will do the following: * - Retrieve the desired driver type and initialise the driver * - Initialise whether the browser needs resetting * - Initialise the screenshot capture * - Configure the browser based on paramaters (maximise window, session resets, user agent) */ @BeforeSuite(alwaysRun = true) public static void instantiateDriverObject() { driverType = new ThreadLocal<DriverType>() { @Override protected DriverType initialValue() { DriverType driverType = new DriverSetup() .returnDesiredDriverType(); driverType.instantiate(); activeDriverTypes.add(driverType); return driverType; } }; requiresReset = new ThreadLocal<Boolean>() { @Override protected Boolean initialValue() { return Boolean.FALSE; } }; capture = new ThreadLocal<ScreenshotCapture>() { @Override protected ScreenshotCapture initialValue() { return null; } }; } /** * The methods which configure the browser once a test runs * - Maximises browser based on the driver type * - Initialises screenshot capture if needed * - Clears the session if another test ran prior * - Sets the user agent of the browser * * @param testMethod - The test method name of the test */ @BeforeMethod(alwaysRun = true) public static void configureBrowserBeforeTest(Method testMethod) { configureDriverBasedOnParams(); initialiseNewScreenshotCapture(testMethod); } /** * Initialise the screenshot capture and link to issue/test case id * * @param testMethod - Test method passed from the test script */ private static void initialiseNewScreenshotCapture(Method testMethod) { if (ScreenshotCapture.isRequired()) { String testID = "n/a"; try { testID = testMethod.getName(); } catch (NullPointerException e) { logger.debug("No test method defined."); } try { testID = testMethod.getAnnotation(Issue.class).value(); } catch (NullPointerException e) { logger.debug("No Issue defined."); } try { testID = testMethod.getAnnotation(TestCaseId.class).value(); } catch (NullPointerException e) { logger.debug("No Test Case ID defined."); } capture.set(new ScreenshotCapture(testID, driverType.get().getDriver())); } } /** * Ran as part of the initialiseDriverObject, configures parts of the driver */ private static void configureDriverBasedOnParams() { requiresReset.set(driverType.get().resetBrowser(requiresReset.get())); driverType.get().maximiseBrowserWindow(); setUserAgent(); } /** * Returns the webdriver object for that given thread * * @return - WebDriver object */ public static WebDriverWrapper getDriver() { return driverType.get().getDriver(); } /** * Sets the user agent of the browser for the test run */ private static void setUserAgent() { userAgent = getUserAgent(); } /** * Loops through all active driver types and tears down the driver object */ @AfterSuite(alwaysRun = true) public static void closeDriverObject() { try { for (DriverType driverType : activeDriverTypes) { driverType.tearDownDriver(); } } catch (Exception e) { logger.warn("Session quit unexpectedly.", e); } } /** * Creates the allure properties for the report, after the test run */ @AfterSuite(alwaysRun = true) public static void createAllureProperties() { AllureProperties.create(); } /** @return the Job id for the current thread */ @Override public String getSessionId() { WebDriverWrapper driver = getDriver(); SessionId sessionId = driver.getWrappedRemoteWebDriver().getSessionId(); return (sessionId == null) ? null : sessionId.toString(); } /** * Retrieves the user agent from the browser * @return - String of the user agent */ private static String getUserAgent() { String ua; JavascriptExecutor js = getDriver(); try { ua = (String) js.executeScript("return navigator.userAgent;"); } catch (Exception e) { ua = "Unable to fetch UserAgent"; } logger.debug("User agent is: '" + ua + "'"); return ua; } /** * @return the {@link SauceOnDemandAuthentication} instance containing the Sauce username/access key */ @Override public SauceOnDemandAuthentication getAuthentication() { return new SauceOnDemandAuthentication(); } /** * @return - Screenshot capture object for the current test */ public static ScreenshotCapture getCapture() { return capture.get(); } public void startStep(String stepName){ Allure.LIFECYCLE.fire(new StepStartedEvent(stepName)); } public void finishStep(){ Allure.LIFECYCLE.fire(new StepFinishedEvent()); } }
package edu.gslis.lucene.main; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.Options; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.apache.lucene.analysis.util.CharArraySet; import org.apache.lucene.analysis.util.StopwordAnalyzerBase; import org.apache.lucene.document.Document; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.queryparser.classic.MultiFieldQueryParser; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.similarities.DefaultSimilarity; import org.apache.lucene.search.similarities.Similarity; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.Version; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; import edu.gslis.lucene.indexer.Indexer; import edu.gslis.lucene.main.config.QueryConfig; import edu.gslis.lucene.main.config.QueryFile; import edu.gslis.lucene.main.config.RunQueryConfig; public class LuceneRunQuery { ClassLoader loader = ClassLoader.getSystemClassLoader(); RunQueryConfig config; public LuceneRunQuery(RunQueryConfig config) { this.config = config; } public void run() throws Exception { String indexPath = config.getIndex(); StopwordAnalyzerBase analyzer; String stopwordsPath = config.getStopwords(); String analyzerClass = config.getAnalyzer(); String docnoField = config.getDocno(); if (StringUtils.isEmpty(docnoField)) docnoField = "docno"; String similarityClass = config.getSimilarity(); Map<String, String> indexMetadata = readIndexMetadata(indexPath); if (StringUtils.isEmpty(analyzerClass) && indexMetadata.get("analyzer") != null) analyzerClass = indexMetadata.get("analyzer"); if (StringUtils.isEmpty(similarityClass) && indexMetadata.get("similarity") != null) similarityClass = indexMetadata.get("similarity"); if (!StringUtils.isEmpty(stopwordsPath)) { @SuppressWarnings("rawtypes") Class analyzerCls = loader.loadClass(analyzerClass); @SuppressWarnings({ "rawtypes", "unchecked" }) java.lang.reflect.Constructor analyzerConst = analyzerCls.getConstructor(Version.class, Reader.class); analyzer = (StopwordAnalyzerBase)analyzerConst.newInstance(Indexer.VERSION, new FileReader(stopwordsPath)); } else { @SuppressWarnings("rawtypes") Class analyzerCls = loader.loadClass(analyzerClass); @SuppressWarnings({ "rawtypes", "unchecked" }) java.lang.reflect.Constructor analyzerConst = analyzerCls.getConstructor(Version.class, CharArraySet.class); analyzer = (StopwordAnalyzerBase)analyzerConst.newInstance(Indexer.VERSION, new CharArraySet(Indexer.VERSION, 0, true)); } Similarity similarity = new DefaultSimilarity(); if (!StringUtils.isEmpty(similarityClass)) similarity = (Similarity)loader.loadClass(similarityClass).newInstance(); IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(indexPath))); IndexSearcher searcher = new IndexSearcher(reader); searcher.setSimilarity(similarity); String field = config.getField(); if (StringUtils.isEmpty(field)) field = "text"; String[] fields = field.split(","); Set<QueryConfig> queries = config.getQueries(); if (queries == null) queries = new HashSet<QueryConfig>(); QueryFile queryFile = config.getQueryFile(); if (queryFile != null) { String path = queryFile.getPath(); String format = queryFile.getFormat(); if (format.startsWith("fedweb")) queries = readDelimitedFile(new File(path), format); else if (format.equals("indri")) { queries = readIndriQueries(new File(path)); } } for (QueryConfig query: queries) { QueryParser parser = new MultiFieldQueryParser(Indexer.VERSION, fields, analyzer); Query q = parser.parse(query.getText()); TopDocs topDocs = searcher.search(q, 1000); ScoreDoc[] docs = topDocs.scoreDocs; for (int i=0; i<docs.length; i++) { int docid = docs[i].doc; double score = docs[i].score; Document doc = searcher.doc(docid); String docno = doc.getField(docnoField).stringValue(); long doclen = doc.getField(Indexer.FIELD_DOC_LEN).numericValue().longValue(); System.out.println(query.getNumber() + " " + docno + " " + score + " " + doclen); } } } public static void main(String[] args) throws Exception { RunQueryConfig config = new RunQueryConfig(); if (args.length == 0) { System.err.println("you must specify a configuration file."); System.exit(-1); } else if (args.length == 1) { File yamlFile = new File(args[0]); if(!yamlFile.exists()) { System.err.println("Configuration file not found."); System.exit(-1); } Yaml yaml = new Yaml(new Constructor(RunQueryConfig.class)); config = (RunQueryConfig)yaml.load(new FileInputStream(yamlFile)); } else { Options options = createOptions(); CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse( options, args); String analyzer = cmd.getOptionValue("analyzer", Indexer.DEFAULT_ANALYZER); String docno = cmd.getOptionValue("docno", Indexer.FIELD_DOCNO); String field = cmd.getOptionValue("field", Indexer.FIELD_TEXT); String querynum = cmd.getOptionValue("querynum", "1"); String similarity = cmd.getOptionValue("similarity", Indexer.DEFAULT_SIMILARITY); String query = cmd.getOptionValue("query"); String queryfile = cmd.getOptionValue("queryfile"); String format = cmd.getOptionValue("format"); String index = cmd.getOptionValue("index"); String stopwords = cmd.getOptionValue("stopwords"); Set<QueryConfig> queries = new HashSet<QueryConfig>(); if (!StringUtils.isEmpty(query)) { QueryConfig querycfg = new QueryConfig(); querycfg.setNumber(querynum); querycfg.setText(query.replaceAll("'", "\"")); queries.add(querycfg); } else if (!StringUtils.isEmpty(queryfile)) { if (format.startsWith("fedweb")) queries = readDelimitedFile(new File(queryfile), format); else if (format.equals("indri")) { queries = readIndriQueries(new File(queryfile)); } } config.setAnalyzer(analyzer); config.setField(field); config.setIndex(index); config.setQueries(queries); config.setDocno(docno); config.setSimilarity(similarity); config.setStopwords(stopwords); } LuceneRunQuery runner = new LuceneRunQuery(config); runner.run(); } public Map<String, String> readIndexMetadata(String indexPath) { Map<String, String> map = new HashMap<String, String>(); try { File metadata = new File(indexPath + File.separator + "index.metadata"); List<String> lines = FileUtils.readLines(metadata); for (String line: lines) { String[] fields = line.split("="); map.put(fields[0], fields[1]); } } catch (IOException e) { // Can't find the index.metadata file, use overrides } return map; } public static Set<QueryConfig> readDelimitedFile(File file, String format) throws Exception { Set<QueryConfig> queries = new HashSet<QueryConfig>(); List<String> rows = FileUtils.readLines(file); for (String row: rows) { if (format.equals("fedweb14")) { String[] fields = row.split("\t"); QueryConfig q = new QueryConfig(); q.setNumber(fields[0]); q.setText(fields[1]); queries.add(q); } else if (format.equals("fedweb13")) { String[] fields = row.split(":"); QueryConfig q = new QueryConfig(); q.setNumber(fields[0]); q.setText(fields[1]); queries.add(q); } } return queries; } public static Set<QueryConfig> readIndriQueries(File file) throws Exception { Set<QueryConfig> queries = new HashSet<QueryConfig>(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); org.w3c.dom.Document xml = builder.parse(new FileInputStream(file)); NodeList queryNodes = xml.getElementsByTagName("query"); for (int i=0; i<queryNodes.getLength(); i++) { Element queryElem = (Element) queryNodes.item(i); QueryConfig query = new QueryConfig(); String number = queryElem.getElementsByTagName("number").item(0).getFirstChild().getNodeValue(); String text = queryElem.getElementsByTagName("text").item(0).getFirstChild().getNodeValue(); text = text.replaceAll("\\\n", ""); query.setNumber(number); query.setText(text); queries.add(query); } return queries; } public static Options createOptions() { Options options = new Options(); options.addOption("analyzer", true, "Analyzer class"); options.addOption("index", true, "Path to index"); options.addOption("field", true, "Field to search"); options.addOption("docno", true, "Docno field"); options.addOption("querynum", true, "Query identifier"); options.addOption("query", true, "Query string"); options.addOption("queryfile", true, "Query file"); options.addOption("format", true, "Query file format"); options.addOption("similarity", true, "Similarity class"); options.addOption("stopwords", true, "Stopwords list"); return options; } }
package com.fundynamic.d2tm.game.entities; import com.fundynamic.d2tm.game.behaviors.Updateable; import com.fundynamic.d2tm.math.MapCoordinate; import com.fundynamic.d2tm.math.Vector2D; import org.newdawn.slick.Color; import java.util.HashMap; import java.util.Map; public class Player implements Updateable { private final String name; private final Faction faction; private Map<MapCoordinate, Boolean> shrouded; private EntitiesSet entitiesSet; // short-hand to player owned entities private EntitiesSet powerProducingEntities; // an easy way to query all power producing entities private EntitiesSet powerConsumingEntities; // an easy way to query all power consuming entities private boolean hasRadar; private float credits; private int animatedCredits; private int totalPowerProduced = 0; private int totalPowerConsumption = 0; public Player(String name, Faction faction) { this(name, faction, 2000); } public Player(String name, Faction faction, int startingCredits) { this.name = name; this.faction = faction; this.shrouded = new HashMap<>(); this.entitiesSet = new EntitiesSet(); this.powerProducingEntities = entitiesSet; this.powerConsumingEntities = entitiesSet; this.credits = startingCredits; this.animatedCredits = startingCredits; } public Faction getFaction() { return faction; } public Color getFactionColor() { switch (faction) { case RED: return Color.red; case BLUE: return Color.blue; case GREEN: return Color.green; default: throw new IllegalStateException("Unknown faction: " + faction); } } public boolean isShrouded(Vector2D position) { Boolean value = shrouded.get(position); return value != null ? value : true; } /** * Removes shroud for {@link MapCoordinate}. * * @param position */ public void revealShroudFor(MapCoordinate position) { shrouded.put(position, false); } public void addEntity(Entity entity) { entitiesSet.add(entity); if (entity.getEntityData().producesPower()) { powerProducingEntities.add(entity); } if (entity.getEntityData().consumesPower()) { powerConsumingEntities.add(entity); } hasRadar = hasRadarEntity(); calculatePowerProducedAndConsumed(); } public boolean removeEntity(Entity entity) { if (powerProducingEntities.contains(entity)) powerProducingEntities.remove(entity); if (powerConsumingEntities.contains(entity)) powerConsumingEntities.remove(entity); calculatePowerProducedAndConsumed(); boolean result = entitiesSet.remove(entity); hasRadar = hasRadarEntity(); return result; } public boolean hasRadarEntity() { return entitiesSet.stream().anyMatch(e -> "RADAR".equals(e.getEntityData().name)); } public int aliveEntities() { return entitiesSet.filter(Predicate.isNotDestroyed()).size(); } @Override public String toString() { return "Player{" + "name='" + name + '\'' + ", faction=" + faction + '}'; } public boolean isCPU() { return "CPU".equalsIgnoreCase(name); } /** * Make this {@link MapCoordinate} shrouded. * * @param mapCoordinate */ public void shroud(MapCoordinate mapCoordinate) { shrouded.put(mapCoordinate, true); } public void addCredits(float credits) { this.credits += credits; } public void setCredits(int credits) { this.credits = credits; this.animatedCredits = credits; } public boolean canBuy(int cost) { return cost <= credits; } public boolean spend(int amount) { if (canBuy(amount)) { credits -= amount; return true; } return false; } public int getCredits() { return (int)credits; } public int getAnimatedCredits() { return animatedCredits; } @Override public void update(float deltaInSeconds) { animatedCredits = (int) credits; } public int getTotalPowerProduced() { return totalPowerProduced; } public int getTotalPowerConsumption() { return totalPowerConsumption; } public boolean isLowPower() { return getPowerBalance() < 0; } private void calculatePowerProducedAndConsumed() { totalPowerProduced = powerProducingEntities.stream().filter(e->!e.isDestroyed()).mapToInt(e -> e.getPowerProduction()).sum(); totalPowerConsumption = powerConsumingEntities.stream().filter(e->!e.isDestroyed()).mapToInt(e -> e.getPowerConsumption()).sum(); } public void entityTookDamage(Entity entity) { if (entity.getEntityData().producesPower() || entity.getEntityData().consumesPower()) { calculatePowerProducedAndConsumed(); } } public int getPowerBalance() { return totalPowerProduced - totalPowerConsumption; } public boolean isHasRadar() { return hasRadar; } }
package hudson.plugins.analysis.util; import org.apache.xerces.parsers.SAXParser; /** * Registers the correct SAX driver if the environment variable is set. * * @Deprecated The usage of this class is discouraged, see JENKINS-27548 */ @Deprecated public class SaxSetup { /** Property of SAX parser factory. */ public static final String SAX_DRIVER_PROPERTY = "org.xml.sax.driver"; private final String oldProperty; /** * Creates a new instance of {@link SaxSetup}. * <p/> * Registers a valid SAX driver. */ public SaxSetup() { oldProperty = System.getProperty(SAX_DRIVER_PROPERTY); if (oldProperty != null) { System.setProperty(SAX_DRIVER_PROPERTY, SAXParser.class.getName()); } } /** * Removes the registered SAX driver. */ public void cleanup() { if (oldProperty != null) { System.setProperty(SAX_DRIVER_PROPERTY, oldProperty); } else { System.clearProperty(SAX_DRIVER_PROPERTY); } } }
package com.gameminers.visage.slave; import java.awt.Graphics2D; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.URL; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayDeque; import java.util.Deque; import java.util.Map; import java.util.UUID; import java.util.logging.Level; import java.util.zip.InflaterInputStream; import javax.imageio.ImageIO; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import org.spacehq.mc.auth.GameProfile; import org.spacehq.mc.auth.ProfileTexture; import org.spacehq.mc.auth.ProfileTextureType; import org.spacehq.mc.auth.properties.Property; import org.spacehq.mc.auth.util.Base64; import com.gameminers.visage.Visage; import com.gameminers.visage.RenderMode; import com.gameminers.visage.slave.render.Renderer; import com.gameminers.visage.util.Images; import com.gameminers.visage.util.UUIDs; import com.google.gson.JsonObject; import com.rabbitmq.client.AMQP.BasicProperties; import com.rabbitmq.client.QueueingConsumer.Delivery; public class RenderThread extends Thread { private static int nextId = 1; private VisageSlave parent; private Renderer[] renderers; private boolean run = true; private Deque<Delivery> toProcess = new ArrayDeque<>(); private ByteArrayOutputStream png = new ByteArrayOutputStream(); public RenderThread(VisageSlave parent) { super("Render thread #"+(nextId++)); this.parent = parent; RenderMode[] modes = RenderMode.values(); renderers = new Renderer[modes.length]; for (int i = 0; i < modes.length; i++) { renderers[i] = modes[i].newRenderer(); } } @Override public void run() { try { Visage.log.info("Waiting for jobs"); try { while (run) { if (!toProcess.isEmpty()) { Delivery delivery = toProcess.pop(); try { processDelivery(delivery); } catch (Exception e) { Visage.log.log(Level.SEVERE, "An unexpected error occurred while rendering", e); BasicProperties props = delivery.getProperties(); BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId()).build(); ByteArrayOutputStream ex = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(ex); oos.writeObject(e); oos.flush(); parent.channel.basicPublish("", props.getReplyTo(), replyProps, buildResponse(1, ex.toByteArray())); parent.channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); } } else { synchronized (toProcess) { toProcess.wait(); } } } for (Renderer r : renderers) { if (r != null) { r.destroy(); } } } catch (Exception e) { Visage.log.log(Level.SEVERE, "A fatal error has occurred in the render thread run loop.", e); } } catch (Exception e) { Visage.log.log(Level.SEVERE, "A fatal error has occurred while setting up a render thread.", e); } } public void process(Delivery delivery) throws IOException { toProcess.addLast(delivery); synchronized (toProcess) { toProcess.notify(); } } private void processDelivery(Delivery delivery) throws Exception { BasicProperties props = delivery.getProperties(); BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId()).build(); DataInputStream data = new DataInputStream(new InflaterInputStream(new ByteArrayInputStream(delivery.getBody()))); RenderMode mode = RenderMode.values()[data.readUnsignedByte()]; int width = data.readUnsignedShort(); int height = data.readUnsignedShort(); int supersampling = data.readUnsignedByte(); GameProfile profile = readGameProfile(data); Visage.log.finer("Rendering a "+width+"x"+height+" "+mode.name().toLowerCase()+" ("+supersampling+"x supersampling) for "+(profile == null ? "null" : profile.getName())); byte[] pngBys = draw(mode, width, height, supersampling, profile); Visage.log.finest("Got png bytes"); parent.channel.basicPublish("", props.getReplyTo(), replyProps, buildResponse(0, pngBys)); Visage.log.finest("Published response"); parent.channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); Visage.log.finest("Ack'd message"); } private byte[] buildResponse(int type, byte[] payload) throws IOException { Visage.log.finest("Building response of type "+type); ByteArrayOutputStream result = new ByteArrayOutputStream(); new DataOutputStream(result).writeUTF(parent.name); result.write(type); result.write(payload); byte[] resp = result.toByteArray(); Visage.log.finest("Built - "+resp.length+" bytes long"); return resp; } public byte[] draw(RenderMode mode, int width, int height, int supersampling, GameProfile profile) throws Exception { png.reset(); Visage.log.finest("Reset png"); Map<ProfileTextureType, ProfileTexture> tex = parent.session.getTextures(profile, false); boolean slim = isSlim(profile); BufferedImage skin; //BufferedImage cape; BufferedImage out; if (tex.containsKey(ProfileTextureType.SKIN)) { skin = ImageIO.read(new URL(tex.get(ProfileTextureType.SKIN).getUrl())); } else { skin = slim ? parent.alex : parent.steve; } if (skin.getHeight() == 32) { Visage.log.finer("Skin is legacy; painting onto new-style canvas"); BufferedImage canvas = new BufferedImage(64, 64, BufferedImage.TYPE_INT_ARGB); Graphics2D g = canvas.createGraphics(); g.drawImage(skin, 0, 0, null); g.drawImage(flipLimb(skin.getSubimage(0, 16, 16, 16)), 16, 48, null); g.drawImage(flipLimb(skin.getSubimage(40, 16, 16, 16)), 32, 48, null); g.dispose(); skin = canvas; } Visage.log.finest("Got skin"); Visage.log.finest(mode.name()); switch (mode) { case FACE: width /= supersampling; height /= supersampling; out = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); int border = width/24; Image face = skin.getSubimage(8, 8, 8, 8).getScaledInstance(width-(border*2), height-(border*2), Image.SCALE_FAST); Image helm = skin.getSubimage(40, 8, 8, 8).getScaledInstance(width, height, Image.SCALE_FAST); Graphics2D g2d = out.createGraphics(); g2d.drawImage(face, border, border, null); g2d.drawImage(helm, 0, 0, null); g2d.dispose(); break; case SKIN: out = skin; break; default: { Renderer renderer = renderers[mode.ordinal()]; if (!renderer.isInitialized()) { Visage.log.finest("Initialized renderer"); renderer.init(supersampling); } try { Visage.log.finest("Uploading"); renderer.setSkin(skin); Visage.log.finest("Rendering"); renderer.render(width, height); Visage.log.finest("Rendered - reading pixels"); GL11.glReadBuffer(GL11.GL_FRONT); ByteBuffer buf = BufferUtils.createByteBuffer(width * height * 4); GL11.glReadPixels(0, 0, width, height, GL12.GL_BGRA, GL11.GL_UNSIGNED_BYTE, buf); BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); int[] pixels = new int[width*height]; buf.asIntBuffer().get(pixels); img.setRGB(0, 0, width, height, pixels, 0, width); Visage.log.finest("Read pixels"); out = Images.toBuffered(img.getScaledInstance(width/supersampling, height/supersampling, Image.SCALE_AREA_AVERAGING)); Visage.log.finest("Rescaled image"); } finally { renderer.finish(); Visage.log.finest("Finished renderer"); } break; } } ImageIO.write(out, "PNG", png); Visage.log.finest("Wrote png"); return png.toByteArray(); } private BufferedImage flipLimb(BufferedImage in) { BufferedImage out = new BufferedImage(in.getWidth(), in.getHeight(), in.getType()); BufferedImage front = flipHorziontally(in.getSubimage(4, 4, 4, 12)); BufferedImage back = flipHorziontally(in.getSubimage(12, 4, 4, 12)); BufferedImage top = flipHorziontally(in.getSubimage(4, 0, 4, 4)); BufferedImage bottom = flipHorziontally(in.getSubimage(8, 0, 4, 4)); BufferedImage left = in.getSubimage(8, 4, 4, 12); BufferedImage right = in.getSubimage(0, 4, 4, 12); Graphics2D g = out.createGraphics(); g.drawImage(front, 4, 4, null); g.drawImage(back, 12, 4, null); g.drawImage(top, 4, 0, null); g.drawImage(bottom, 8, 0, null); g.drawImage(left, 0, 4, null); // left goes to right g.drawImage(right, 8, 4, null); // right goes to left g.dispose(); return out; } private BufferedImage flipHorziontally(BufferedImage in) { BufferedImage out = new BufferedImage(in.getWidth(), in.getHeight(), in.getType()); Graphics2D g = out.createGraphics(); g.drawImage(in, 0, 0, in.getWidth(), in.getHeight(), in.getWidth(), 0, 0, in.getHeight(), null); g.dispose(); return out; } private boolean isSlim(GameProfile profile) throws IOException { if (profile.getProperties().containsKey("textures")) { String texJson = new String(Base64.decode(profile.getProperties().get("textures").getValue().getBytes(StandardCharsets.UTF_8))); JsonObject obj = parent.gson.fromJson(texJson, JsonObject.class); JsonObject tex = obj.getAsJsonObject("textures"); if (tex.has("SKIN")) { JsonObject skin = tex.getAsJsonObject("SKIN"); if (skin.has("metadata")) { if ("slim".equals(skin.getAsJsonObject("metadata").get("model").getAsString())) return true; } return false; } } return UUIDs.isAlex(profile.getId()); } private GameProfile readGameProfile(DataInputStream data) throws IOException { boolean present = data.readBoolean(); if (!present) return new GameProfile(new UUID(0, 0), "<unknown>"); UUID uuid = new UUID(data.readLong(), data.readLong()); String name = data.readUTF(); GameProfile profile = new GameProfile(uuid, name); int len = data.readUnsignedShort(); for (int i = 0; i < len; i++) { boolean signed = data.readBoolean(); Property prop; if (signed) { prop = new Property(data.readUTF(), data.readUTF(), data.readUTF()); } else { prop = new Property(data.readUTF(), data.readUTF()); } profile.getProperties().put(data.readUTF(), prop); } return profile; } public void finish() { run = false; interrupt(); } }
package hdm.pk070.jscheme.setup; import hdm.pk070.jscheme.error.SchemeError; import hdm.pk070.jscheme.obj.builtin.function.base.SchemeBuiltinEq; import hdm.pk070.jscheme.obj.builtin.function.list.SchemeBuiltinCons; import hdm.pk070.jscheme.obj.builtin.function.list.SchemeBuiltinGetCar; import hdm.pk070.jscheme.obj.builtin.function.list.SchemeBuiltinGetCdr; import hdm.pk070.jscheme.obj.builtin.function.list.SchemeBuiltinIsCons; import hdm.pk070.jscheme.obj.builtin.function.math.*; import hdm.pk070.jscheme.obj.builtin.simple.SchemeSymbol; import hdm.pk070.jscheme.obj.builtin.syntax.SchemeBuiltinDefine; import hdm.pk070.jscheme.obj.builtin.syntax.SchemeBuiltinIf; import hdm.pk070.jscheme.obj.builtin.syntax.SchemeBuiltinLambda; import hdm.pk070.jscheme.table.environment.GlobalEnvironment; import hdm.pk070.jscheme.table.environment.entry.EnvironmentEntry; import hdm.pk070.jscheme.table.symbolTable.SchemeSymbolTable; /** * @author patrick.kleindienst */ public final class JSchemeSetup { public static void init() throws SchemeError { printWelcomeScreen(); GlobalEnvironment.getInstance().add(EnvironmentEntry.create(SchemeSymbolTable.getInstance().add(new SchemeSymbol ("+")), SchemeBuiltinPlus.create())); GlobalEnvironment.getInstance().add(EnvironmentEntry.create(SchemeSymbolTable.getInstance().add(new SchemeSymbol ("-")), SchemeBuiltinMinus.create())); GlobalEnvironment.getInstance().add(EnvironmentEntry.create(SchemeSymbolTable.getInstance().add(new SchemeSymbol ("*")), SchemeBuiltinTimes.create())); GlobalEnvironment.getInstance().add(EnvironmentEntry.create(SchemeSymbolTable.getInstance().add(new SchemeSymbol ("/")), SchemeBuiltinDivide.create())); GlobalEnvironment.getInstance().add(EnvironmentEntry.create(SchemeSymbolTable.getInstance().add(new SchemeSymbol ("abs")), SchemeBuiltinAbsolute.create())); GlobalEnvironment.getInstance().add(EnvironmentEntry.create(SchemeSymbolTable.getInstance().add(new SchemeSymbol ("cons")), SchemeBuiltinCons.create())); GlobalEnvironment.getInstance().add(EnvironmentEntry.create(SchemeSymbolTable.getInstance().add(new SchemeSymbol ("car")), SchemeBuiltinGetCar.create())); GlobalEnvironment.getInstance().add(EnvironmentEntry.create(SchemeSymbolTable.getInstance().add(new SchemeSymbol ("cdr")), SchemeBuiltinGetCdr.create())); GlobalEnvironment.getInstance().add(EnvironmentEntry.create(SchemeSymbolTable.getInstance().add(new SchemeSymbol ("cons?")), SchemeBuiltinIsCons.create())); GlobalEnvironment.getInstance().add(EnvironmentEntry.create(SchemeSymbolTable.getInstance().add(new SchemeSymbol("eq?")), SchemeBuiltinEq.create())); registerBuiltinSyntax(); } private static void registerBuiltinSyntax() throws SchemeError { GlobalEnvironment.getInstance().add(EnvironmentEntry.create(SchemeSymbolTable.getInstance().add(new SchemeSymbol("define")), SchemeBuiltinDefine.create())); GlobalEnvironment.getInstance().add(EnvironmentEntry.create(SchemeSymbolTable.getInstance().add(new SchemeSymbol("if")), SchemeBuiltinIf.create())); GlobalEnvironment.getInstance().add(EnvironmentEntry.create(SchemeSymbolTable.getInstance().add(new SchemeSymbol("lambda")), SchemeBuiltinLambda.create())); } private static void printWelcomeScreen() { System.out.println(); System.out.println(" *****************************************"); System.out.println(" System.out.println(" System.out.println(" System.out.println(" System.out.println(" System.out.println(" *****************************************"); System.out.println(); } }
package com.gengo.client.payloads; import org.json.JSONException; import org.json.JSONObject; import com.gengo.client.GengoClient; import com.gengo.client.enums.Tier; import com.gengo.client.exceptions.GengoException; /** * A translation job payload */ public class TranslationJob extends Payload { /** Maximum comment length in bytes. */ public static final int MAX_COMMENT_LENGTH = 1024; public static final String FLAG_TRUE = GengoClient.MYGENGO_TRUE; /* Required fields */ private String slug; private String textToTranslate; private String sourceLanguageCode; private String targetLanguageCode; private Tier tier; /* Optional fields */ private boolean forceNewTranslation; private String comment; private boolean usePreferredTranslators; private String callbackUrl; private boolean autoApprove; private String customData; private String position; private String glossaryId; private String maxChar; /** * Create a translation job. * @param slug short string to summarize this job * @param textToTranslate text to be translated * @param sourceLanguageCode source language code * @param targetLanguageCode target language code * @param tier translation tier */ public TranslationJob(String slug, String textToTranslate, String sourceLanguageCode, String targetLanguageCode, Tier tier) { this.slug = slug; this.textToTranslate = textToTranslate; this.sourceLanguageCode = sourceLanguageCode; this.targetLanguageCode = targetLanguageCode; this.tier = tier; } /* Getters and setters */ public String getSlug() { return slug; } public void setSlug(String slug) { this.slug = slug; } public String getTextToTranslate() { return textToTranslate; } public void setTextToTranslate(String textToTranslate) { this.textToTranslate = textToTranslate; } public String getSourceLanguageCode() { return sourceLanguageCode; } public void setSourceLanguageCode(String sourceLanguageCode) { this.sourceLanguageCode = sourceLanguageCode; } public String getTargetLanguageCode() { return targetLanguageCode; } public void setTargetLanguageCode(String targetLanguageCode) { this.targetLanguageCode = targetLanguageCode; } public Tier getTier() { return tier; } public void setTier(Tier tier) { this.tier = tier; } public boolean isForceNewTranslation() { return forceNewTranslation; } public void setForceNewTranslation(boolean forceNewTranslation) { this.forceNewTranslation = forceNewTranslation; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public boolean isUsePreferredTranslators() { return usePreferredTranslators; } public void setUsePreferredTranslators(boolean usePreferredTranslators) { this.usePreferredTranslators = usePreferredTranslators; } public String getCallbackUrl() { return callbackUrl; } public void setCallbackUrl(String callbackUrl) { this.callbackUrl = callbackUrl; } public boolean isAutoApprove() { return autoApprove; } public void setAutoApprove(boolean autoApprove) { this.autoApprove = autoApprove; } public String getCustomData() { return customData; } public void setCustomData(String data) throws GengoException { if (data.length() > MAX_COMMENT_LENGTH) { throw new GengoException("Maximum custom data is " + MAX_COMMENT_LENGTH + " bytes"); } customData = new String(data); } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public String getGlossaryId() { return glossaryId; } public void setGlossaryId(String glossaryId) { this.glossaryId = glossaryId; } public String getMaxChar() { return maxChar; } public void setMaxChar(String maxChar) { this.maxChar = maxChar; } /** Utility method */ private boolean isNullOrEmpty(String str) { return (null == str || str.length() == 0); } /** * Create a JSONObject representing this job * @return the JSONObject created * @throws GengoException */ public JSONObject toJSONObject() throws GengoException { if (isNullOrEmpty(textToTranslate)) throw new GengoException("Invalid translation job - textToTranslate is required."); if (isNullOrEmpty(this.sourceLanguageCode)) throw new GengoException("Invalid translation job - sourceLanguageCode is required."); if (isNullOrEmpty(this.targetLanguageCode)) throw new GengoException("Invalid translation job - targetLanguageCode is required."); JSONObject job = new JSONObject(); try { job.put("body_src", this.textToTranslate); job.put("lc_src", this.sourceLanguageCode); job.put("lc_tgt", this.targetLanguageCode); job.put("tier", this.tier.toString().toLowerCase()); job.put("slug", this.slug); if (this.forceNewTranslation) { job.put("force", FLAG_TRUE); } if (!isNullOrEmpty(comment)) { job.put("comment", this.comment); } if (this.usePreferredTranslators) { job.put("use_preferred", FLAG_TRUE); } if (!isNullOrEmpty(this.callbackUrl)) { job.put("callback_url", this.callbackUrl); } if (this.autoApprove) { job.put("auto_approve", FLAG_TRUE); } if (null != this.customData && this.customData.length() > 0) { job.put("custom_data", this.customData); } if (!isNullOrEmpty(this.position)) { job.put("position", this.position); } if (!isNullOrEmpty(this.glossaryId)) { job.put("glossary_id", this.glossaryId); } if (!isNullOrEmpty(this.maxChar)) { job.put("max_char", this.maxChar); } } catch (JSONException e) { throw new GengoException("Could not create JSONObject for TranslationJob", e); } return job; } }
package io.brdc.fusekicouchdb; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.jena.ontology.DatatypeProperty; import org.apache.jena.ontology.Individual; import org.apache.jena.ontology.OntModel; import org.apache.jena.ontology.OntModelSpec; import org.apache.jena.query.DatasetAccessor; import org.apache.jena.query.DatasetAccessorFactory; 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.riot.Lang; import org.apache.jena.riot.RDFDataMgr; import org.apache.jena.riot.RDFFormat; import org.apache.jena.riot.system.StreamRDF; import org.apache.jena.riot.system.StreamRDFLib; import org.apache.jena.sparql.util.Context; import org.apache.jena.util.iterator.ExtendedIterator; import org.ektorp.CouchDbConnector; import org.ektorp.CouchDbInstance; import org.ektorp.DbAccessException; import org.ektorp.StreamingViewResult; import org.ektorp.ViewQuery; import org.ektorp.ViewResult.Row; import org.ektorp.http.HttpClient; import org.ektorp.http.HttpResponse; import org.ektorp.http.StdHttpClient; import org.ektorp.impl.StdCouchDbConnector; import org.ektorp.impl.StdCouchDbInstance; public class TransferHelpers { public static final String CORE_PREFIX = "http://onto.bdrc.io/ontologies/bdrc/"; public static final String DESCRIPTION_PREFIX = "http://onto.bdrc.io/ontology/description public static final String ROOT_PREFIX = "http://purl.bdrc.io/ontology/root/"; public static final String COMMON_PREFIX = "http://purl.bdrc.io/ontology/common public static final String CORPORATION_PREFIX = "http://purl.bdrc.io/ontology/corporation public static final String LINEAGE_PREFIX = "http://purl.bdrc.io/ontology/lineage public static final String OFFICE_PREFIX = "http://purl.bdrc.io/ontology/office public static final String PRODUCT_PREFIX = "http://purl.bdrc.io/ontology/product public static final String OUTLINE_PREFIX = "http://purl.bdrc.io/ontology/outline public static final String PERSON_PREFIX = "http://purl.bdrc.io/ontology/person public static final String PLACE_PREFIX = "http://purl.bdrc.io/ontology/place public static final String TOPIC_PREFIX = "http://purl.bdrc.io/ontology/topic public static final String VOLUMES_PREFIX = "http://purl.bdrc.io/ontology/volumes public static final String WORK_PREFIX = "http://purl.bdrc.io/ontology/work public static final String OWL_PREFIX = "http://www.w3.org/2002/07/owl public static final String RDF_PREFIX = "http://www.w3.org/1999/02/22-rdf-syntax-ns public static final String RDFS_PREFIX = "http://www.w3.org/2000/01/rdf-schema public static final String XSD_PREFIX = "http://www.w3.org/2001/XMLSchema public static Map<String,String> jsonLdContext = new LinkedHashMap<String, String>(); static { jsonLdContext.put("@vocab", ROOT_PREFIX); jsonLdContext.put("com", COMMON_PREFIX); jsonLdContext.put("crp", CORPORATION_PREFIX); jsonLdContext.put("prd", PRODUCT_PREFIX); jsonLdContext.put("owl", OWL_PREFIX); jsonLdContext.put("plc", PLACE_PREFIX); jsonLdContext.put("xsd", XSD_PREFIX); jsonLdContext.put("rdfs", RDFS_PREFIX); jsonLdContext.put("ofc", OFFICE_PREFIX); jsonLdContext.put("out", OUTLINE_PREFIX); jsonLdContext.put("lin", LINEAGE_PREFIX); jsonLdContext.put("top", TOPIC_PREFIX); jsonLdContext.put("wor", WORK_PREFIX); jsonLdContext.put("per", PERSON_PREFIX); jsonLdContext.put("vol", VOLUMES_PREFIX); jsonLdContext.put("desc", DESCRIPTION_PREFIX); } public static String FusekiUrl = "http://localhost:13180/fuseki/bdrcrw/data"; public static String CouchDBUrl = "http://localhost:13598"; public static CouchDbConnector db = connectCouchDB(); public static DatasetAccessor fu = connectFuseki(); public static void init(String fusekiHost, String fusekiPort, String couchdbHost, String couchdbPort) { FusekiUrl = "http://" + fusekiHost + ":" + fusekiPort + "/fuseki/bdrcrw/data"; CouchDBUrl = "http://" + couchdbHost + ":" + couchdbPort + "/fuseki/bdrcrw/data"; } public static CouchDbConnector connectCouchDB() { HttpClient httpClient; CouchDbInstance dbInstance; CouchDbConnector res = null; try { httpClient = new StdHttpClient.Builder() .url(CouchDBUrl) .build(); dbInstance = new StdCouchDbInstance(httpClient); res = new StdCouchDbConnector("test", dbInstance); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return res; } private static boolean safeHasNext(Iterator<Row> rowIterator) { try { return rowIterator.hasNext(); } catch (DbAccessException e) { System.err.println("Failed to move to next row while detecting table"); return false; } } public static List<String> getAllIds() { List<String> res = new ArrayList<String>(); final StreamingViewResult streamingView = db.queryForStreamingView(new ViewQuery().allDocs()); try { final Iterator<Row> rowIterator = streamingView.iterator(); while (safeHasNext(rowIterator)) { Row row = rowIterator.next(); String Id = row.getId(); if (!Id.startsWith("_")) res.add(Id); } } catch (Exception e) { e.printStackTrace(); } finally { streamingView.close(); } return res; } public static void transferCompleteDB () { List<String> Ids = getAllIds(); System.out.println("Transferring " + Ids.size() + " docs to Fuseki"); // Ids.parallelStream().forEach( (id) -> transferOneDoc(id) ); String id ="start"; int i = 0; for (i = 0; i < Ids.size();) { id = Ids.get(i); transferOneDoc(id); if (++i % 100 == 0) { if (i % 1000 == 0) { System.out.println(id + ":" + i + ", "); } else { System.out.print(id + ":" + i + ", "); } } } System.out.println("\nLast doc transferred: " + id); System.out.println("Transferred " + i + " docs to Fuseki"); } public static DatasetAccessor connectFuseki() { return DatasetAccessorFactory.createHTTP(FusekiUrl); } public static void transferOneDoc(String docId) { try { Model m = ModelFactory.createDefaultModel(); addDocIdInModel(docId, m); //printModel(m); transferModel(m); } catch (Exception ex) { System.err.println("Processing: " + docId + " throws " + ex.toString()); } } private static void transferModel(Model m) { fu.add(m); } public static void addDocIdInModel(String docId, Model m) { String uri = "/test/_design/jsonld/_show/jsonld/" + docId; HttpResponse r = db.getConnection().get(uri); InputStream stuff = r.getContent(); // feeding the inputstream directly to jena for json-ld parsing // instead of ektorp json parsing StreamRDF dest = StreamRDFLib.graph(m.getGraph()) ; Context ctx = new Context(); RDFDataMgr.parse(dest, stuff, "", Lang.JSONLD, ctx); try { stuff.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // for debugging purposes only public static void printModel(Model m) { RDFDataMgr.write(System.out, m, RDFFormat.TURTLE_PRETTY); } // change Range Datatypes from rdf:PlainLitteral to rdf:langString // Warning: only works for public static void rdf10tordf11(OntModel o) { Resource RDFPL = o.getResource("http://www.w3.org/1999/02/22-rdf-syntax-ns#PlainLiteral"); Resource RDFLS = o.getResource("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"); ExtendedIterator<DatatypeProperty> it = o.listDatatypeProperties(); while(it.hasNext()) { DatatypeProperty p = it.next(); Resource r = p.getRange(); if (r != null && r.equals(RDFPL)) { p.setRange(RDFLS); } } } public static void removeIndividuals(OntModel o) { ExtendedIterator<Individual> it = o.listIndividuals(); while(it.hasNext()) { Individual i = it.next(); if (i.getLocalName().equals("UNKNOWN")) continue; i.remove(); } } public static OntModel getOntologyModel(String onto) { OntModel ontoModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM, null); try { InputStream inputStream; if (onto != null) { inputStream = new FileInputStream(onto); } else { ClassLoader classLoader = TransferHelpers.class.getClassLoader(); inputStream = classLoader.getResourceAsStream("owl-file/bdrc.owl"); } ontoModel.read(inputStream, "", "RDF/XML"); inputStream.close(); } catch (Exception e) { System.err.println(e.getMessage()); } // then we fix it by removing the individuals and converting rdf10 to rdf11 removeIndividuals(ontoModel); rdf10tordf11(ontoModel); return ontoModel; } public static void transferOntology() { OntModel m = getOntologyModel("src/main/resources/bdrc.owl"); transferModel(m); } public static void transferOntology(String path) { OntModel m = getOntologyModel(path); transferModel(m); } }
package hrv.calc.parameter; import hrv.RRData; import hrv.calc.Histogram; public class BaevskyCalculator implements HRVDataProcessor { @Override public HRVParameter process(RRData rrinterval) { Histogram hist = new Histogram(rrinterval.getValueAxis()); return new HRVParameter(HRVParameterEnum.BAEVSKY, hist.getAmplitudeMode() / (2 * hist.getMode() * hist.getRange()), "non"); } @Override public boolean validData(RRData data) { return data.getValueAxis().length > 0; } }
package ch.uzh.csg.samplepaymentproject; import java.security.InvalidAlgorithmParameterException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.SecureRandom; import java.security.Security; import java.util.UUID; import org.spongycastle.jce.ECNamedCurveTable; import org.spongycastle.jce.provider.BouncyCastleProvider; import org.spongycastle.jce.spec.ECParameterSpec; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.nfc.NfcAdapter; import android.os.Build; import android.os.Bundle; import android.provider.Settings; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import ch.uzh.csg.mbps.customserialization.Currency; import ch.uzh.csg.mbps.customserialization.DecoderFactory; import ch.uzh.csg.mbps.customserialization.PKIAlgorithm; import ch.uzh.csg.mbps.customserialization.PaymentRequest; import ch.uzh.csg.mbps.customserialization.PaymentResponse; import ch.uzh.csg.mbps.customserialization.ServerPaymentRequest; import ch.uzh.csg.mbps.customserialization.ServerPaymentResponse; import ch.uzh.csg.mbps.customserialization.ServerResponseStatus; import ch.uzh.csg.mbps.customserialization.exceptions.UnknownPKIAlgorithmException; import ch.uzh.csg.nfclib.NfcLibException; import ch.uzh.csg.nfclib.Utils; import ch.uzh.csg.paymentlib.IServerResponseListener; import ch.uzh.csg.paymentlib.IUserPromptPaymentRequest; import ch.uzh.csg.paymentlib.PaymentEvent; import ch.uzh.csg.paymentlib.PaymentEventInterface; import ch.uzh.csg.paymentlib.PaymentRequestHandler; import ch.uzh.csg.paymentlib.PaymentRequestInitializer; import ch.uzh.csg.paymentlib.PaymentRequestInitializer.PaymentType; import ch.uzh.csg.paymentlib.container.PaymentInfos; import ch.uzh.csg.paymentlib.container.ServerInfos; import ch.uzh.csg.paymentlib.container.UserInfos; import ch.uzh.csg.paymentlib.exceptions.IllegalArgumentException; import ch.uzh.csg.paymentlib.persistency.IPersistencyHandler; import ch.uzh.csg.paymentlib.persistency.PersistedPaymentRequest; //TODO: javadoc /** * * @author Jeton Memeti * */ public class MainActivity extends Activity { protected static final String PREF_UNIQUE_ID = "pref_unique_id"; private static String uniqueID; private static final String TAG = "##NFC## MainActivity"; @Override protected void onCreate(Bundle savedInstanceState) { Log.i(TAG, "start"); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); try { final KeyPair keyPairServer = generateKeyPair(42); final ServerInfos serverInfos = new ServerInfos(keyPairServer.getPublic()); final PaymentEventInterface eventHandler = new PaymentEventInterface() { @Override public void handleMessage(PaymentEvent event, Object object) { Log.i(TAG, "evt1:" + event + " obj:" + object); } @Override public void handleMessage(PaymentEvent event, Object object, IServerResponseListener caller) { Log.i(TAG, "evt2:" + event + " obj:" + object); if (event == PaymentEvent.FORWARD_TO_SERVER) { try { ServerPaymentRequest decode = DecoderFactory.decode(ServerPaymentRequest.class, (byte[]) object); PaymentRequest paymentRequestPayer = decode.getPaymentRequestPayer(); PaymentResponse pr = new PaymentResponse(PKIAlgorithm.DEFAULT, 1, ServerResponseStatus.SUCCESS, null, paymentRequestPayer.getUsernamePayer(), paymentRequestPayer.getUsernamePayee(), paymentRequestPayer.getCurrency(), paymentRequestPayer.getAmount(), paymentRequestPayer.getTimestamp()); pr.sign(keyPairServer.getPrivate()); ServerPaymentResponse spr = new ServerPaymentResponse(pr); caller.onServerResponse(spr); } catch (Exception e) { e.printStackTrace(); } } } }; String userName = id(getApplicationContext()); final KeyPair keyPair = generateKeyPair(); final UserInfos userInfos = new UserInfos(userName, keyPair.getPrivate(), PKIAlgorithm.DEFAULT, 1); final PaymentInfos paymentInfos = new PaymentInfos(Currency.BTC, 5); Button sendButton = (Button) findViewById(R.id.button1); sendButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { NfcAdapter nfcAdapter = createAdapter(MainActivity.this); if (nfcAdapter == null) { Log.e(TAG, "no nfc adapter"); return; } try { Log.i(TAG, "init payment"); PaymentRequestInitializer init = new PaymentRequestInitializer(MainActivity.this, eventHandler, userInfos, paymentInfos, serverInfos, PaymentType.REQUEST_PAYMENT); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NfcLibException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); final IUserPromptPaymentRequest userPrompt = new IUserPromptPaymentRequest() { @Override public boolean isPaymentAccepted() { Log.i(TAG, "payment accepted"); return true; } @Override public boolean getPaymentRequestAnswer(String username, Currency currency, long amount) { Log.i(TAG, "user " + username + " wants " + amount); return true; } }; final IPersistencyHandler persistencyHandler = new IPersistencyHandler() { @Override public PersistedPaymentRequest getPersistedPaymentRequest(String username, Currency currency, long amount) { Log.i(TAG, "getPersistedPaymentRequest"); return null; } @Override public void delete(PersistedPaymentRequest paymentRequest) { Log.i(TAG, "delete"); } @Override public void add(PersistedPaymentRequest paymentRequest) { Log.i(TAG, "add"); } }; PaymentRequestHandler handler = new PaymentRequestHandler(this, eventHandler, userInfos, serverInfos, userPrompt, persistencyHandler); Log.i(TAG, "payment handler initilazied"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * Create an NFC adapter, if NFC is enabled, return the adapter, otherwise * null and open up NFC settings. * * @param context * @return */ private NfcAdapter createAdapter(Context context) { NfcAdapter nfcAdapter = android.nfc.NfcAdapter.getDefaultAdapter(getApplicationContext()); if (!nfcAdapter.isEnabled()) { AlertDialog.Builder alertbox = new AlertDialog.Builder(context); alertbox.setTitle("Info"); alertbox.setMessage("Enable NFC"); alertbox.setPositiveButton("Turn On", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { Intent intent = new Intent(Settings.ACTION_NFC_SETTINGS); startActivity(intent); } else { Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS); startActivity(intent); } } }); alertbox.setNegativeButton("Close", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); alertbox.show(); return null; } return nfcAdapter; } public synchronized static String id(Context context) { if (uniqueID == null) { SharedPreferences sharedPrefs = context.getSharedPreferences(PREF_UNIQUE_ID, Context.MODE_PRIVATE); uniqueID = sharedPrefs.getString(PREF_UNIQUE_ID, null); if (uniqueID == null) { uniqueID = UUID.randomUUID().toString(); Editor editor = sharedPrefs.edit(); editor.putString(PREF_UNIQUE_ID, uniqueID); editor.commit(); } } return uniqueID; } private static final String SECURITY_PROVIDER = "SC"; static { Security.addProvider(new BouncyCastleProvider()); } public static KeyPair generateKeyPair() throws UnknownPKIAlgorithmException, NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException { return generateKeyPair(PKIAlgorithm.DEFAULT, 0); } /** * Generates a KeyPair with the default {@link PKIAlgorithm}. * * @throws UnknownPKIAlgorithmException * @throws NoSuchAlgorithmException * @throws NoSuchProviderException * @throws InvalidAlgorithmParameterException */ public static KeyPair generateKeyPair(long seed) throws UnknownPKIAlgorithmException, NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException { return generateKeyPair(PKIAlgorithm.DEFAULT, seed); } /** * Generates a KeyPair with the provided {@link PKIAlgorithm}. * * @param algorithm * the {@link PKIAlgorithm} to be used to generate the KeyPair * @throws UnknownPKIAlgorithmException * @throws NoSuchAlgorithmException * @throws NoSuchProviderException * @throws InvalidAlgorithmParameterException */ public static KeyPair generateKeyPair(PKIAlgorithm algorithm, long seed) throws UnknownPKIAlgorithmException, NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException { if (algorithm.getCode() != PKIAlgorithm.DEFAULT.getCode()) throw new UnknownPKIAlgorithmException(); ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec(algorithm.getKeyPairSpecification()); KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm.getKeyPairAlgorithm(), SECURITY_PROVIDER); if(seed != 0) { keyGen.initialize(ecSpec, new SecureRandom()); } else { keyGen.initialize(ecSpec, new SecureRandom(Utils.longToByteArray(seed))); } return keyGen.generateKeyPair(); } }
package com.groupon.seleniumgridextras.config; import com.google.common.base.Throwables; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.internal.LinkedTreeMap; import com.groupon.seleniumgridextras.config.capabilities.Capability; import com.groupon.seleniumgridextras.utilities.json.JsonParserWrapper; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; public class GridNode { private LinkedList<Capability> capabilities; private GridNodeConfiguration configuration; private String loadedFromFile; private static Logger logger = Logger.getLogger(GridNode.class); public GridNode() { capabilities = new LinkedList<Capability>(); configuration = new GridNodeConfiguration(); } private GridNode(LinkedList<Capability> caps, GridNodeConfiguration config) { capabilities = caps; configuration = config; } public static GridNode loadFromFile(String filename) { String configString = readConfigFile(filename); JsonObject topLevelJson = new JsonParser().parse(configString).getAsJsonObject(); String configFromFile = topLevelJson.getAsJsonObject("configuration").toString(); GridNodeConfiguration nodeConfiguration = new Gson().fromJson(configFromFile, GridNodeConfiguration.class); LinkedList<Capability> filteredCapabilities = new LinkedList<Capability>(); for (JsonElement cap : topLevelJson.getAsJsonArray("capabilities")) { Map capHash = JsonParserWrapper.toHashMap(cap.toString()); if (capHash.containsKey("browserName")) { filteredCapabilities.add(Capability.getCapabilityFor((String) capHash.get("browserName"), capHash)); } } GridNode node = new GridNode(filteredCapabilities, nodeConfiguration); node.setLoadedFromFile(filename); return node; } public String getLoadedFromFile() { return this.loadedFromFile; } public void setLoadedFromFile(String file) { this.loadedFromFile = file; } public LinkedList<Capability> getCapabilities() { return capabilities; } public GridNodeConfiguration getConfiguration() { return configuration; } public boolean isAppiumNode() { return getLoadedFromFile().startsWith("appium"); } public void writeToFile(String filename) { try { File f = new File(filename); String config = this.toPrettyJsonString(); FileUtils.writeStringToFile(f, config); } catch (Exception e) { logger.fatal("Could not write node config for '" + filename + "' with following error"); logger.fatal(e.toString()); System.exit(1); } } private String toPrettyJsonString() { return JsonParserWrapper.prettyPrintString(this); } protected static String readConfigFile(String filePath) { String returnString = ""; try { BufferedReader reader = new BufferedReader(new FileReader(filePath)); String line = null; while ((line = reader.readLine()) != null) { returnString = returnString + line; } } catch (FileNotFoundException error) { String e = String.format( "Error loading config from %s, %s, Will have to exit. \n%s", filePath, error.getMessage(), Throwables.getStackTraceAsString(error)); System.out.println(e); logger.error(e); System.exit(1); } catch (IOException error) { String e = String.format( "Error loading config from %s, %s, Will have to exit. \n%s", filePath, error.getMessage(), Throwables.getStackTraceAsString(error)); System.out.println(e); logger.error(e); System.exit(1); } return returnString; } //<Grumble Grumble>, google parsing Gson, Grumble protected static Map doubleToIntConverter(Map input) { for (Object key : input.keySet()) { if (input.get(key) instanceof Double) { input.put(key, ((Double) input.get(key)).intValue()); } } return input; } public static Map linkedTreeMapToHashMap(LinkedTreeMap input) { Map output = new HashMap(); output.putAll(input); return output; } //</Grubmle> public class GridNodeConfiguration { private String proxy = "com.groupon.seleniumgridextras.grid.proxies.SetupTeardownProxy"; private int maxSession = 3; private int port; private boolean register = true; private int unregisterIfStillDownAfter = 10000; private int hubPort; private String hubHost; private String host; private String url; private Integer registerCycle; // private int browserTimeout = 120; // private int timeout = 120; private int nodeStatusCheckTimeout = 10000; private String appiumStartCommand; //Only test the node status 1 time, since the limit checker is //Since DefaultRemoteProxy.java does this check failedPollingTries >= downPollingLimit private int downPollingLimit = 0; public int getMaxSession() { return this.maxSession; } public void setMaxSession(int maxSession) { this.maxSession = maxSession; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public int getHubPort() { return hubPort; } public void setHubPort(int hubPort) { this.hubPort = hubPort; } public String getHubHost() { return hubHost; } public void setHubHost(String hubHost) { this.hubHost = hubHost; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public int getRegisterCycle() { return registerCycle.intValue(); } public void setRegisterCycle(int registerCycle) { this.registerCycle = new Integer(registerCycle); } public String getAppiumStartCommand() { return appiumStartCommand; } public void setAppiumStartCommand(String appiumStartCommand) { this.appiumStartCommand = appiumStartCommand; } } }
package com.github.gregwhitaker.rschannel; import io.netty.bootstrap.Bootstrap; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; import io.reactivesocket.ConnectionSetupPayload; import io.reactivesocket.DefaultReactiveSocket; import io.reactivesocket.Frame; import io.reactivesocket.Payload; import io.reactivesocket.ReactiveSocket; import io.reactivesocket.RequestHandler; import io.reactivesocket.netty.tcp.client.ClientTcpDuplexConnection; import io.reactivesocket.netty.tcp.server.ReactiveSocketServerHandler; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import rx.RxReactiveStreams; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.util.Random; import java.util.Timer; import java.util.TimerTask; public class Server { private static final Logger LOG = LoggerFactory.getLogger(Server.class); private static final Random RANDOM = new Random(System.currentTimeMillis()); final String name; public Server(String name) { this.name = name; } public void start(InetSocketAddress local, InetSocketAddress remote) { Thread thread = new Thread(() -> { Server server = new Server(name); try { server.startServer(local, remote); } catch (Exception e) { throw new RuntimeException(e); } }); thread.setDaemon(true); thread.start(); } private void startServer(InetSocketAddress local, InetSocketAddress remote) throws Exception { new RequestHandler.Builder().withRequestChannel() ServerBootstrap localServer = new ServerBootstrap(); localServer.group(new NioEventLoopGroup(1), new NioEventLoopGroup(4)) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(ReactiveSocketServerHandler.create((setupPayload, reactiveSocket) -> { return new RequestHandler.Builder().withRequestChannel(payloadPublisher -> { return new Publisher<Payload>() { @Override public void subscribe(Subscriber<? super Payload> s) { s.onNext(new Payload() { @Override public ByteBuffer getData() { return ByteBuffer.wrap(String.format("[%s] - YO", name).getBytes()); } @Override public ByteBuffer getMetadata() { return Frame.NULL_BYTEBUFFER; } }); } }; }).build(); })); } }); localServer.bind(local).sync(); Publisher<ClientTcpDuplexConnection> publisher = ClientTcpDuplexConnection .create(remote, new NioEventLoopGroup(1)); ClientTcpDuplexConnection duplexConnection = RxReactiveStreams.toObservable(publisher).toBlocking().last(); ReactiveSocket reactiveSocket = DefaultReactiveSocket.fromClientConnection(duplexConnection, ConnectionSetupPayload.create("UTF-8", "UTF-8"), t -> t.printStackTrace()); reactiveSocket.startAndWait(); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { reactiveSocket.requestChannel(s -> { s.onNext(new Payload() { @Override public ByteBuffer getData() { return ByteBuffer.wrap(String.format("[%s] - YO", name).getBytes()); } @Override public ByteBuffer getMetadata() { return Frame.NULL_BYTEBUFFER; } }); }); } }, RANDOM.nextInt((3000 - 1) + 1) + 1, 1000); } }
package info.fingo.urlopia.report; import info.fingo.urlopia.history.HistoryLogService; import info.fingo.urlopia.holidays.HolidayService; import info.fingo.urlopia.holidays.WorkingDaysCalculator; import info.fingo.urlopia.request.Request; import info.fingo.urlopia.request.RequestService; import info.fingo.urlopia.request.RequestType; import info.fingo.urlopia.user.User; import info.fingo.urlopia.user.UserService; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.web.servlet.view.document.AbstractXlsxView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.time.LocalDate; import java.util.List; import java.util.Map; /** * Builds .xlsx report file from employee data. */ @Component public class ReportView extends AbstractXlsxView { private final static String[] romanNumerals = {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI", "XII"}; private final static String[] labelStrings = {"ogółem", "czas normatywny", "godziny nadliczbowe 50%", "godziny nadliczbowe 100%", "praca nocna", "niedziele i święta", "dodatkowe dni wolne", "postojowe", "urlop wypoczynkowy", "urlop okolicznościowy", "urlop - opieka nad dzieckiem", "choroba do 33 dni", "choroba pow. 33 dni", "opieka nad chorym", "opieka nad dzieckiem", "nieob. inne płatne", "nieob. inne niepłatne", "nieob. nieusprawiedliwione", "dyżury" }; private final UserService userService; private final RequestService requestService; private final HolidayService holidayService; private final HistoryLogService historyLogService; @Value("${report.company.name}") private String companyName; @Value("${report.company.address}") private String companyAddress; @Autowired public ReportView(UserService userService, RequestService requestService, HolidayService holidayService, HistoryLogService historyLogService, WorkingDaysCalculator workingDaysCalculator) { this.userService = userService; this.requestService = requestService; this.holidayService = holidayService; this.historyLogService = historyLogService; } @SuppressWarnings("unchecked") @Override protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception { Long userId = (Long) model.get("userId"); int year = (int) model.get("currentYear"); User user = userService.get(userId); List<Request> requests = requestService.get(userId, year); float worktime = user.getWorkTime(); // build doc XSSFSheet sheet = (XSSFSheet) workbook.createSheet("Ewidencja czasu pracy"); sheet.setDefaultColumnWidth(3); // default font & style for most cells XSSFCellStyle defaultStyle = (XSSFCellStyle) workbook.createCellStyle(); defaultStyle.setBorderTop(CellStyle.BORDER_THIN); defaultStyle.setBorderRight(CellStyle.BORDER_THIN); defaultStyle.setBorderBottom(CellStyle.BORDER_THIN); defaultStyle.setBorderLeft(CellStyle.BORDER_THIN); XSSFFont defaultFont = (XSSFFont) workbook.createFont(); defaultFont.setFontHeight(9); defaultFont.setFontName("Arial CE"); defaultStyle.setFont(defaultFont); XSSFCellStyle defaultCenterStyle = (XSSFCellStyle) workbook.createCellStyle(); defaultCenterStyle.setBorderTop(CellStyle.BORDER_THIN); defaultCenterStyle.setBorderRight(CellStyle.BORDER_THIN); defaultCenterStyle.setBorderBottom(CellStyle.BORDER_THIN); defaultCenterStyle.setBorderLeft(CellStyle.BORDER_THIN); defaultCenterStyle.setAlignment(CellStyle.ALIGN_CENTER); defaultCenterStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER); XSSFFont defaultCenterFont = (XSSFFont) workbook.createFont(); defaultCenterFont.setFontHeight(9); defaultCenterFont.setFontName("Arial CE"); defaultCenterStyle.setFont(defaultCenterFont); // labels on top sheet.createRow(1).createCell(1).setCellValue(companyName); sheet.createRow(2).createCell(1).setCellValue(companyAddress); sheet.createRow(4).createCell(1).setCellValue("ROCZNA KARTA EWIDENCJI OBECNOŚCI W PRACY"); // big box with full name and year XSSFRow labelsRow = sheet.createRow(6); labelsRow.setHeightInPoints(120); sheet.addMergedRegion(new CellRangeAddress(5, 6, 0, 31)); XSSFCellStyle fullNameYearStyle = (XSSFCellStyle) workbook.createCellStyle(); fullNameYearStyle.setBorderTop(CellStyle.BORDER_THIN); fullNameYearStyle.setBorderRight(CellStyle.BORDER_THIN); fullNameYearStyle.setBorderBottom(CellStyle.BORDER_THIN); fullNameYearStyle.setBorderLeft(CellStyle.BORDER_THIN); fullNameYearStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER); fullNameYearStyle.setAlignment(CellStyle.ALIGN_CENTER); XSSFFont fullNameYearCellFont = (XSSFFont) workbook.createFont(); fullNameYearCellFont.setFontName("Arial CE"); fullNameYearCellFont.setFontHeight(12); fullNameYearStyle.setFont(fullNameYearCellFont); XSSFRow workTimeRow = sheet.createRow(5); XSSFCell fullNameYearCell = workTimeRow.createCell(0); fullNameYearCell.setCellStyle(fullNameYearStyle); String fullNameYearCellValue = "nazwisko i imię: " + user.getFirstName() + " " + user.getLastName() + " rok: " + LocalDate.now().getYear(); fullNameYearCell.setCellValue(fullNameYearCellValue); // labels XSSFCellStyle labelCellStyle = (XSSFCellStyle) workbook.createCellStyle(); labelCellStyle.setBorderTop(CellStyle.BORDER_THIN); labelCellStyle.setBorderRight(CellStyle.BORDER_THIN); labelCellStyle.setBorderBottom(CellStyle.BORDER_THIN); labelCellStyle.setBorderLeft(CellStyle.BORDER_THIN); labelCellStyle.setRotation((short) 90); XSSFFont labelCellStyleFont = (XSSFFont) workbook.createFont(); labelCellStyleFont.setFontName("Arial CE"); labelCellStyleFont.setFontHeight(9); labelCellStyle.setFont(labelCellStyleFont); sheet.addMergedRegion(new CellRangeAddress(5, 6, 32, 32)); XSSFCell nominalCell = workTimeRow.createCell(32); nominalCell.setCellStyle(labelCellStyle); nominalCell.setCellValue("czas pracy nominalny"); sheet.addMergedRegion(new CellRangeAddress(5, 5, 33, 40)); XSSFCell timeWorkedCell = workTimeRow.createCell(33); timeWorkedCell.setCellStyle(defaultStyle); timeWorkedCell.setCellValue("czas przepracowany"); sheet.addMergedRegion(new CellRangeAddress(5, 5, 41, 51)); XSSFCell timeNotWorkedCell = workTimeRow.createCell(41); timeNotWorkedCell.setCellStyle(defaultStyle); timeNotWorkedCell.setCellValue("czas nieprzepracowany"); for (int i = 0; i < labelStrings.length; ++i) { XSSFCell labelCell = labelsRow.createCell(33 + i); labelCell.setCellStyle(labelCellStyle); labelCell.setCellValue(labelStrings[i]); } // day and month labels XSSFRow daysInMonthRow = sheet.createRow(7); XSSFCell mcCell = daysInMonthRow.createCell(0); mcCell.setCellStyle(defaultStyle); mcCell.setCellValue("M-C"); for (int i = 1; i <= 31; ++i) { XSSFCell dayInMonthCell = daysInMonthRow.createCell(i); dayInMonthCell.setCellStyle(defaultStyle); dayInMonthCell.setCellValue(i); } // ...then rest of the row with blanks for (int j = 32; j < 52; ++j) { XSSFCell dayInMonthCell = daysInMonthRow.createCell(j); dayInMonthCell.setCellStyle(defaultCenterStyle); } // for every month row till today int previousMonth = LocalDate.now().getMonthValue() - 1; for (int i = 0; i < previousMonth; ++i) { XSSFRow monthRow = sheet.createRow(8 + i); XSSFCell monthNumberCell = monthRow.createCell(0); monthNumberCell.setCellStyle(defaultStyle); monthNumberCell.setCellValue(romanNumerals[i]); // start filling day in month cells int monthLength = LocalDate.of(year, i + 1, 1).lengthOfMonth(); for (int j = 1; j <= monthLength; ++j) { XSSFCell dayCell = monthRow.createCell(j); dayCell.setCellStyle(defaultCenterStyle); LocalDate currentDay = LocalDate.of(year, i + 1, j); if (!holidayService.isWorkingDay(currentDay)) { dayCell.setCellValue("-"); } else { dayCell.setCellValue(worktime); } } // fill in rest of the days till 31th for (int j = monthLength + 1; j <= 31; ++j) { XSSFCell dayCell = monthRow.createCell(j); dayCell.setCellStyle(defaultCenterStyle); dayCell.setCellValue("-"); } // ...then rest of the row with blanks for (int j = 32; j < 52; ++j) { XSSFCell dayCell = monthRow.createCell(j); dayCell.setCellStyle(defaultCenterStyle); } } // fill in rest of the months for (int i = previousMonth; i < 12; ++i) { XSSFRow monthRow = sheet.createRow(8 + i); XSSFCell monthNumberCell = monthRow.createCell(0); monthNumberCell.setCellStyle(defaultStyle); monthNumberCell.setCellValue(romanNumerals[i]); // blank cells for (int j = 1; j < 52; ++j) { XSSFCell dayCell = monthRow.createCell(j); dayCell.setCellStyle(defaultCenterStyle); } } // for every user holidays request if (requests != null) { for (Request r : requests) { boolean isAccepted = r.getStatus() == Request.Status.ACCEPTED; if (isAccepted) { for (LocalDate k = r.getStartDate(); !k.isAfter(r.getEndDate()); k = k.plusDays(1)) { if (k.getMonthValue() <= previousMonth && holidayService.isWorkingDay(k)) { XSSFCell cell = sheet.getRow(7 + k.getMonthValue()).getCell(k.getDayOfMonth()); if (r.getType() == RequestType.NORMAL) { cell.setCellValue("uw"); } else if (r.getType() == RequestType.OCCASIONAL) { cell.setCellValue("uo"); } } } } } } XSSFRow summaryRow = sheet.createRow(20); summaryRow.setHeightInPoints(50); // entitled days/hours pool sheet.addMergedRegion(new CellRangeAddress(20, 20, 0, 5)); XSSFCell entitledTimeCell = summaryRow.createCell(0); entitledTimeCell.setCellStyle(defaultCenterStyle); String entitledTimeString = (Math.abs(8f - worktime) < 0.1) ? "urlop wypocz.\nprzysług. dni" : "urlop wypocz.\nprzysług. godz."; entitledTimeCell.setCellValue(entitledTimeString); sheet.addMergedRegion(new CellRangeAddress(20, 20, 6, 7)); XSSFCell entitledTimeValueCell = summaryRow.createCell(6); entitledTimeValueCell.setCellStyle(defaultCenterStyle); // used days/hours pool sheet.addMergedRegion(new CellRangeAddress(20, 20, 8, 13)); XSSFCell usedTimeCell = summaryRow.createCell(8); usedTimeCell.setCellStyle(defaultCenterStyle); String usedTimeString = (Math.abs(8f - worktime) < 0.1) ? "wykorzystano dni" : "wykorzystano godz."; usedTimeCell.setCellValue(usedTimeString); sheet.addMergedRegion(new CellRangeAddress(20, 20, 14, 15)); XSSFCell usedTimeValueCell = summaryRow.createCell(14); usedTimeValueCell.setCellStyle(defaultCenterStyle); // days/hours left sheet.addMergedRegion(new CellRangeAddress(20, 20, 16, 21)); XSSFCell leftTimeCell = summaryRow.createCell(16); leftTimeCell.setCellStyle(defaultCenterStyle); String leftTimeString = (Math.abs(8f - worktime) < 0.1) ? "pozostało dni" : "pozostało godz."; leftTimeCell.setCellValue(leftTimeString); sheet.addMergedRegion(new CellRangeAddress(20, 20, 22, 23)); XSSFCell leftTimeValueCell = summaryRow.createCell(22); leftTimeValueCell.setCellStyle(defaultCenterStyle); double leftTimeValueNumber = historyLogService.countRemainingHours(user.getId()); leftTimeValueNumber = (Math.abs(8f - worktime) < 0.1) ? leftTimeValueNumber / 8 : leftTimeValueNumber; leftTimeValueCell.setCellValue(leftTimeValueNumber); // total label sheet.addMergedRegion(new CellRangeAddress(20, 20, 24, 31)); XSSFCell totalCell = summaryRow.createCell(24); totalCell.setCellStyle(defaultCenterStyle); totalCell.setCellValue("ogółem"); // fill in rest of this row for (int i = 0; i < 20; ++i) { XSSFCell sumCell = summaryRow.createCell(32 + i); sumCell.setCellStyle(defaultCenterStyle); } // calculate work time sum of a month for (int i = 0; i < previousMonth; ++i) { float sum = 0; XSSFRow sumRow = sheet.getRow(8 + i); for (int j = 1; j <= 31; ++j) { XSSFCell valueCell = sumRow.getCell(j); double cellValue; try { cellValue = valueCell.getNumericCellValue(); sum += cellValue; } catch (Exception e) { } } XSSFCell sumCell = sumRow.getCell(32); sumCell.setCellValue(sum); } // calculate used holidays time for (int i = 0; i < previousMonth; ++i) { float time = (Math.abs(8f - worktime) < 0.1) ? user.getWorkTime() / 8 : user.getWorkTime(); float uwSum = 0; float uoSum = 0; XSSFRow sumRow = sheet.getRow(8 + i); for (int j = 1; j <= 31; ++j) { XSSFCell valueCell = sumRow.getCell(j); String cellValue; try { cellValue = valueCell.getStringCellValue(); if ("uw".equals(cellValue)) { uwSum += time; } else if ("uo".equals(cellValue)) { uoSum += time; } } catch (Exception e) { } } XSSFCell uwCell = sumRow.getCell(41); uwCell.setCellValue(uwSum); XSSFCell uoCell = sumRow.getCell(42); uoCell.setCellValue(uoSum); } // total used holidays time XSSFRow totalUsedRow = sheet.getRow(20); float totalUsedUwSum = 0; float totalUsedUoSum = 0; for (int i = 0; i < previousMonth; ++i) { XSSFRow sumRow = sheet.getRow(8 + i); XSSFCell valueCell = sumRow.getCell(41); double cellValue; try { cellValue = valueCell.getNumericCellValue(); totalUsedUwSum += cellValue; } catch (Exception e) { } valueCell = sumRow.getCell(42); try { cellValue = valueCell.getNumericCellValue(); totalUsedUoSum += cellValue; } catch (Exception e) { } } XSSFCell totalUsedUwCell = totalUsedRow.getCell(41); totalUsedUwCell.setCellValue(totalUsedUwSum); XSSFCell totalUsedUoCell = totalUsedRow.getCell(42); totalUsedUoCell.setCellValue(totalUsedUoSum); } }
package com.google.sps.data; import com.google.sps.data.Book; import java.io.File; import java.util.ArrayList; import java.util.Scanner; import javax.servlet.ServletException; /** * Class that takes in a CSV FileName as the constructor parameter * and populates a list of Books with title, genre, and reviews. */ public class BookReader { String path; public BookReader(String path) { this.path = path; } public ArrayList<Book> makeBookList() throws ServletException{ ArrayList<Book> listOfBooks = new ArrayList<Book>(); try (Scanner scanner = new Scanner(new File(path)).useDelimiter("\\Z")) { String content = scanner.next().replaceAll("[\\r\\n]+", ""); String[] lines = content.split("NEXTBOOK"); // lines[i] represents one row of the file String current_title = ""; Book.Builder current_builder = Book.builder().title("null"); for (int i = 1; i < lines.length; i++) { String[] cells = lines[i].split(","); String title = cells[0]; String genre = cells[8]; String review = cells[13]; if (current_title.equals(title)) { // add review: current_builder.addReview(review); } else { // close old book: if (i != 1) { Book book = current_builder.build(); listOfBooks.add(book); } // start building new book current_builder = Book.builder().title(title).genre(genre).addReview(review); current_title = title; } } Book book = current_builder.build(); listOfBooks.add(book); } catch (Exception ex) { throw new ServletException("Error reading CSV file", ex); } return listOfBooks; } }
package com.github.lock.free.queue; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; /** * Daneel Yaitskov */ public class LockFreeQueue<T> { // never empty private final AtomicLong length = new AtomicLong(1L); private final Node stub = new Node(null); private final AtomicReference<Node<T>> head = new AtomicReference<Node<T>>(stub); private final AtomicReference<Node<T>> tail = new AtomicReference<Node<T>>(stub); public void add(T x) { addNode(new Node<T>(x)); length.incrementAndGet(); } public T takeOrNull() { while (true) { long l = length.get(); if (l == 1) { return null; } if (length.compareAndSet(l, l - 1)) { break; } } while (true) { Node<T> r = head.get(); if (r == null) { throw new IllegalStateException("null head"); } if (r.next.get() == null) { length.incrementAndGet(); return null; } if (head.compareAndSet(r, r.next.get())) { if (r == stub) { stub.next.set(null); addNode(stub); } else { return r.ref; } } } } private void addNode(Node<T> n) { Node<T> t; while (true) { t = tail.get(); if (tail.compareAndSet(t, n)) { break; } } if (t.next.compareAndSet(null, n)) { return; } throw new IllegalStateException("bad tail next"); } }
package io.scif.formats.dicom; import java.util.Hashtable; /** * Data dictionary of DICOM types. * <p> * There are literally thousands of fields defined by the DICOM specifications, * so this list may be incomplete. * </p> * * @author Andrea Ballaminut * @author Curtis Rueden * @author Melissa Linkert * @author Mark Hiner */ public class DICOMDictionary { private Hashtable<Integer, String[]> table = new Hashtable<>(4000); public DICOMDictionary() { addAttributes(); } /** Checks whether the given code is in the dictionary. */ public boolean has(final int code) { return table.containsKey(code); } /** Gets the name for the given code. */ public String name(final int code) { return has(code) ? table.get(code)[0] : null; } /** Gets the VR for the given code. */ public String vr(final int code) { return has(code) ? table.get(code)[1] : null; } // -- Helper methods -- private void addAttributes() { addAttributeGroup0002(); addAttributeGroup0008(); addAttributeGroup0010(); addAttributeGroup0012(); addAttributeGroup0014(); addAttributeGroup0018(); addAttributeGroup0020(); addAttributeGroup0022(); addAttributeGroup0024(); addAttributeGroup0028(); addAttributeGroup0032(); addAttributeGroup0038(); addAttributeGroup003A(); addAttributeGroup0042(); addAttributeGroup0044(); addAttributeGroup0046(); addAttributeGroup0048(); addAttributeGroup0050(); addAttributeGroup0052(); addAttributeGroup0054(); addAttributeGroup0060(); addAttributeGroup0062(); addAttributeGroup0064(); addAttributeGroup0066(); addAttributeGroup0068(); addAttributeGroup0070(); addAttributeGroup0072(); addAttributeGroup0074(); addAttributeGroup0076(); addAttributeGroup0078(); addAttributeGroup0080(); addAttributeGroup0088(); addAttributeGroup0100(); addAttributeGroup0400(); addAttributeGroup2000(); addAttributeGroup2010(); addAttributeGroup2020(); addAttributeGroup2030(); addAttributeGroup2040(); addAttributeGroup2050(); addAttributeGroup2100(); addAttributeGroup2110(); addAttributeGroup2120(); addAttributeGroup2130(); addAttributeGroup2200(); addAttributeGroup3002(); addAttributeGroup3004(); addAttributeGroup3006(); addAttributeGroup3008(); addAttributeGroup300A(); addAttributeGroup300C(); addAttributeGroup300E(); addAttributeGroup4000(); addAttributeGroup4008(); addAttributeGroup4010(); addAttributeGroup4FFE(); addAttributeGroup5200(); addAttributeGroup5400(); addAttributeGroup5600(); addAttributeGroup7FE0(); addAttributeGroupFFFA(); } /** * Adds attributes of group 0x0002. */ private void addAttributeGroup0002() { add(0x00020000, "File Meta Information Group Length", "UL"); add(0x00020001, "File Meta Information Version", "OB"); add(0x00020002, "Media Storage SOP Class UID", "UI"); add(0x00020003, "Media Storage SOP Instance UID", "UI"); add(0x00020010, "Transfer Syntax UID", "UI"); add(0x00020012, "Implementation Class UID", "UI"); add(0x00020013, "Implementation Version Name", "SH"); add(0x00020016, "Source Application Entity Title", "AE"); add(0x00020017, "Sending Application Entity Title", "AE"); add(0x00020018, "Receiving Application Entity Title", "AE"); add(0x00020100, "Private Information Creator UID", "UI"); add(0x00020102, "Private Information", "OB"); } /** * Adds attributes of group 0x0008. */ private void addAttributeGroup0008() { add(0x00080001, "Length to End", "UL"); // Retired add(0x00080005, "Specific Character Set", "CS"); add(0x00080006, "Language Code Sequence", "SQ"); add(0x00080008, "Image Type", "CS"); add(0x00080010, "Recognition Code", "SH"); // Retired add(0x00080012, "Instance Creation Date", "DA"); add(0x00080013, "Instance Creation Time", "TM"); add(0x00080014, "Instance Creator UID", "UI"); add(0x00080015, "Instance Coercion DateTime", "DT"); add(0x00080016, "SOP Class UID", "UI"); add(0x00080018, "SOP Instance UID", "UI"); add(0x0008001A, "Related General SOP Class UID", "UI"); add(0x0008001B, "Original Specialized SOP ClassUID", "UI"); add(0x00080020, "Study Date", "DA"); add(0x00080021, "Series Date", "DA"); add(0x00080022, "Acquisition Date", "DA"); add(0x00080023, "Content Date", "DA"); add(0x00080024, "Overlay Date", "DA"); // Retired add(0x00080025, "Curve Date", "DA"); // Retired add(0x0008002A, "Acquisition DateTime", "DT"); add(0x00080030, "Study Time", "TM"); add(0x00080031, "Series Time", "TM"); add(0x00080032, "Acquisition Time", "TM"); add(0x00080033, "Content Time", "TM"); add(0x00080034, "Overlay Time", "TM"); // Retired add(0x00080035, "Curve Time", "TM"); // Retired add(0x00080040, "Data Set Type", "US"); // Retired add(0x00080041, "Data Set Subtype", "LO"); // Retired add(0x00080042, "Nuclear Medicine Series Type", "CS"); // Retired add(0x00080050, "Accession Number", "SH"); add(0x00080051, "Issuer of Accession NumberSequence", "SQ"); add(0x00080052, "Query/Retrieve Level", "CS"); add(0x00080053, "Query/Retrieve View", "CS"); add(0x00080054, "Retrieve AE Title", "AE"); add(0x00080056, "Instance Availability", "CS"); add(0x00080058, "Failed SOP Instance UID List", "UI"); add(0x00080060, "Modality", "CS"); add(0x00080061, "Modalities in Study", "CS"); add(0x00080062, "SOP Classes in Study", "UI"); add(0x00080064, "Conversion Type", "CS"); add(0x00080068, "Presentation Intent Type", "CS"); add(0x00080070, "Manufacturer", "LO"); add(0x00080080, "Institution Name", "LO"); add(0x00080081, "Institution Address", "ST"); add(0x00080082, "Institution Code Sequence", "SQ"); add(0x00080090, "Referring Physician's Name", "PN"); add(0x00080092, "Referring Physician's Address", "ST"); add(0x00080094, "Referring Physician's TelephoneNumbers", "SH"); add(0x00080096, "Referring Physician IdentificationSequence", "SQ"); add(0x0008009C, "Consulting Physician's Name", "PN"); add(0x0008009D, "Consulting Physician IdentificationSequence", "SQ"); add(0x00080100, "Code Value", "SH"); add(0x00080101, "Extended Code Value", "LO"); // DICOS add(0x00080102, "Coding Scheme Designator", "SH"); add(0x00080103, "Coding Scheme Version", "SH"); add(0x00080104, "Code Meaning", "LO"); add(0x00080105, "Mapping Resource", "CS"); add(0x00080106, "Context Group Version", "DT"); add(0x00080107, "Context Group Local Version", "DT"); add(0x00080108, "Extended Code Meaning", "LT"); // DICOS add(0x0008010B, "Context Group Extension Flag", "CS"); add(0x0008010C, "Coding Scheme UID", "UI"); add(0x0008010D, "Context Group Extension CreatorUID", "UI"); add(0x0008010F, "Context Identifier", "CS"); add(0x00080110, "Coding Scheme IdentificationSequence", "SQ"); add(0x00080112, "Coding Scheme Registry", "LO"); add(0x00080114, "Coding Scheme External ID", "ST"); add(0x00080115, "Coding Scheme Name", "ST"); add(0x00080116, "Coding Scheme ResponsibleOrganization", "ST"); add(0x00080117, "Context UID", "UI"); add(0x00080118, "Mapping Resource UID", "UI"); add(0x00080119, "Long Code Value", "UC"); add(0x00080120, "URN Code Value", "UR"); add(0x00080121, "Equivalent Code Sequence", "SQ"); add(0x00080201, "Timezone Offset From UTC", "SH"); add(0x00080300, "Private Data ElementCharacteristics Sequence", "SQ"); add(0x00080301, "Private Group Reference", "US"); add(0x00080302, "Private Creator Reference", "LO"); add(0x00080303, "Block Identifying Information Status", "CS"); add(0x00080304, "Nonidentifying Private Elements", "US"); add(0x00080306, "Identifying Private Elements", "US"); add(0x00080305, "Deidentification Action Sequence", "SQ"); add(0x00080307, "Deidentification Action", "CS"); add(0x00081000, "Network ID", "AE"); // Retired add(0x00081010, "Station Name", "SH"); add(0x00081030, "Study Description", "LO"); add(0x00081032, "Procedure Code Sequence", "SQ"); add(0x0008103E, "Series Description", "LO"); add(0x0008103F, "Series Description Code Sequence", "SQ"); add(0x00081040, "Institutional Department Name", "LO"); add(0x00081048, "Physician(s) of Record", "PN"); add(0x00081049, "Physician(s) of RecordIdentification Sequence", "SQ"); add(0x00081050, "Performing Physician's Name", "PN"); add(0x00081052, "Performing Physician IdentificationSequence", "SQ"); add(0x00081060, "Name of Physician(s) ReadingStudy", "PN"); add(0x00081062, "Physician(s) Reading StudyIdentification Sequence", "SQ"); add(0x00081070, "Operators' Name", "PN"); add(0x00081072, "Operator Identification Sequence", "SQ"); add(0x00081080, "Admitting Diagnoses Description", "LO"); add(0x00081084, "Admitting Diagnoses CodeSequence", "SQ"); add(0x00081090, "Manufacturer's Model Name", "LO"); add(0x00081100, "Referenced Results Sequence", "SQ"); // Retired add(0x00081110, "Referenced Study Sequence", "SQ"); add(0x00081111, "Referenced Performed ProcedureStep Sequence", "SQ"); add(0x00081115, "Referenced Series Sequence", "SQ"); add(0x00081120, "Referenced Patient Sequence", "SQ"); add(0x00081125, "Referenced Visit Sequence", "SQ"); add(0x00081130, "Referenced Overlay Sequence", "SQ"); // Retired add(0x00081134, "Referenced Stereometric InstanceSequence", "SQ"); add(0x0008113A, "Referenced Waveform Sequence", "SQ"); add(0x00081140, "Referenced Image Sequence", "SQ"); add(0x00081145, "Referenced Curve Sequence", "SQ"); // Retired add(0x0008114A, "Referenced Instance Sequence", "SQ"); add(0x0008114B, "Referenced Real World ValueMapping Instance Sequence", "SQ"); add(0x00081150, "Referenced SOP Class UID", "UI"); add(0x00081155, "Referenced SOP Instance UID", "UI"); add(0x0008115A, "SOP Classes Supported", "UI"); add(0x00081160, "Referenced Frame Number", "IS"); add(0x00081161, "Simple Frame List", "UL"); add(0x00081162, "Calculated Frame List", "UL"); add(0x00081163, "Time Range", "FD"); add(0x00081164, "Frame Extraction Sequence", "SQ"); add(0x00081167, "Multi-frame Source SOP InstanceUID", "UI"); add(0x00081190, "Retrieve URL", "UR"); add(0x00081195, "Transaction UID", "UI"); add(0x00081196, "Warning Reason", "US"); add(0x00081197, "Failure Reason", "US"); add(0x00081198, "Failed SOP Sequence", "SQ"); add(0x00081199, "Referenced SOP Sequence", "SQ"); add(0x00081200, "Studies Containing OtherReferenced Instances Sequence", "SQ"); add(0x00081250, "Related Series Sequence", "SQ"); add(0x00082110, "Lossy Image Compression(Retired)", "CS"); // Retired add(0x00082111, "Derivation Description", "ST"); add(0x00082112, "Source Image Sequence", "SQ"); add(0x00082120, "Stage Name", "SH"); add(0x00082122, "Stage Number", "IS"); add(0x00082124, "Number of Stages", "IS"); add(0x00082127, "View Name", "SH"); add(0x00082128, "View Number", "IS"); add(0x00082129, "Number of Event Timers", "IS"); add(0x0008212A, "Number of Views in Stage", "IS"); add(0x00082130, "Event Elapsed Time(s)", "DS"); add(0x00082132, "Event Timer Name(s)", "LO"); add(0x00082133, "Event Timer Sequence", "SQ"); add(0x00082134, "Event Time Offset", "FD"); add(0x00082135, "Event Code Sequence", "SQ"); add(0x00082142, "Start Trim", "IS"); add(0x00082143, "Stop Trim", "IS"); add(0x00082144, "Recommended Display FrameRate", "IS"); add(0x00082200, "Transducer Position", "CS"); // Retired add(0x00082204, "Transducer Orientation", "CS"); // Retired add(0x00082208, "Anatomic Structure", "CS"); // Retired add(0x00082218, "Anatomic Region Sequence", "SQ"); add(0x00082220, "Anatomic Region ModifierSequence", "SQ"); add(0x00082228, "Primary Anatomic StructureSequence", "SQ"); add(0x00082229, "Anatomic Structure, Space orRegion Sequence", "SQ"); add(0x00082230, "Primary Anatomic StructureModifier Sequence", "SQ"); add(0x00082240, "Transducer Position Sequence", "SQ"); // Retired add(0x00082242, "Transducer Position ModifierSequence", "SQ"); // Retired add(0x00082244, "Transducer Orientation Sequence", "SQ"); // Retired add(0x00082246, "Transducer Orientation ModifierSequence", "SQ"); // Retired add(0x00082251, "Anatomic Structure Space OrRegion Code Sequence (Trial)", "SQ"); // Retired add(0x00082253, "Anatomic Portal Of Entrance CodeSequence (Trial)", "SQ"); // Retired add(0x00082255, "Anatomic Approach Direction CodeSequence (Trial)", "SQ"); // Retired add(0x00082256, "Anatomic Perspective Description(Trial)", "ST"); // Retired add(0x00082257, "Anatomic Perspective CodeSequence (Trial)", "SQ"); // Retired add(0x00082258, "Anatomic Location Of ExaminingInstrument Description (Trial)", "ST"); // Retired add(0x00082259, "Anatomic Location Of ExaminingInstrument Code Sequence (Trial)", "SQ"); // Retired add(0x0008225A, "Anatomic Structure Space OrRegion Modifier Code Sequence(Trial)", "SQ"); // Retired add(0x0008225C, "On Axis Background AnatomicStructure Code Sequence (Trial)", "SQ"); // Retired add(0x00083001, "Alternate RepresentationSequence", "SQ"); add(0x00083010, "Irradiation Event UID", "UI"); add(0x00083011, "Source Irradiation Event Sequence", "SQ"); add(0x00083012, "RadiopharmaceuticalAdministration Event UID", "UI"); add(0x00084000, "Identifying Comments", "LT"); // Retired add(0x00089007, "Frame Type", "CS"); add(0x00089092, "Referenced Image EvidenceSequence", "SQ"); add(0x00089121, "Referenced Raw Data Sequence", "SQ"); add(0x00089123, "Creator-Version UID", "UI"); add(0x00089124, "Derivation Image Sequence", "SQ"); add(0x00089154, "Source Image Evidence Sequence", "SQ"); add(0x00089205, "Pixel Presentation", "CS"); add(0x00089206, "Volumetric Properties", "CS"); add(0x00089207, "Volume Based CalculationTechnique", "CS"); add(0x00089208, "Complex Image Component", "CS"); add(0x00089209, "Acquisition Contrast", "CS"); add(0x00089215, "Derivation Code Sequence", "SQ"); add(0x00089237, "Referenced Presentation StateSequence", "SQ"); add(0x00089410, "Referenced Other Plane Sequence", "SQ"); add(0x00089458, "Frame Display Sequence", "SQ"); add(0x00089459, "Recommended Display FrameRate in Float", "FL"); add(0x00089460, "Skip Frame Range Flag", "CS"); } /** * Adds attributes of group 0x0010. */ private void addAttributeGroup0010() { add(0x00100010, "Patient's Name", "PN"); add(0x00100020, "Patient ID", "LO"); add(0x00100021, "Issuer of Patient ID", "LO"); add(0x00100022, "Type of Patient ID", "CS"); add(0x00100024, "Issuer of Patient ID QualifiersSequence", "SQ"); add(0x00100030, "Patient's Birth Date", "DA"); add(0x00100032, "Patient's Birth Time", "TM"); add(0x00100040, "Patient's Sex", "CS"); add(0x00100050, "Patient's Insurance Plan CodeSequence", "SQ"); add(0x00100101, "Patient's Primary Language CodeSequence", "SQ"); add(0x00100102, "Patient's Primary LanguageModifier Code Sequence", "SQ"); add(0x00100200, "Quality Control Subject", "CS"); add(0x00100201, "Quality Control Subject Type CodeSequence", "SQ"); add(0x00101000, "Other Patient IDs", "LO"); add(0x00101001, "Other Patient Names", "PN"); add(0x00101002, "Other Patient IDs Sequence", "SQ"); add(0x00101005, "Patient's Birth Name", "PN"); add(0x00101010, "Patient's Age", "AS"); add(0x00101020, "Patient's Size", "DS"); add(0x00101021, "Patient's Size Code Sequence", "SQ"); add(0x00101030, "Patient's Weight", "DS"); add(0x00101040, "Patient's Address", "LO"); add(0x00101050, "Insurance Plan Identification", "LO"); // Retired add(0x00101060, "Patient's Mother's Birth Name", "PN"); add(0x00101080, "Military Rank", "LO"); add(0x00101081, "Branch of Service", "LO"); add(0x00101090, "Medical Record Locator", "LO"); add(0x00101100, "Referenced Patient PhotoSequence", "SQ"); add(0x00102000, "Medical Alerts", "LO"); add(0x00102110, "Allergies", "LO"); add(0x00102150, "Country of Residence", "LO"); add(0x00102152, "Region of Residence", "LO"); add(0x00102154, "Patient's Telephone Numbers", "SH"); add(0x00102155, "Patient's Telecom Information", "LT"); add(0x00102160, "Ethnic Group", "SH"); add(0x00102180, "Occupation", "SH"); add(0x001021A0, "Smoking Status", "CS"); add(0x001021B0, "Additional Patient History", "LT"); add(0x001021C0, "Pregnancy Status", "US"); add(0x001021D0, "Last Menstrual Date", "DA"); add(0x001021F0, "Patient's Religious Preference", "LO"); add(0x00102201, "Patient Species Description", "LO"); add(0x00102202, "Patient Species Code Sequence", "SQ"); add(0x00102203, "Patient's Sex Neutered", "CS"); add(0x00102210, "Anatomical Orientation Type", "CS"); add(0x00102292, "Patient Breed Description", "LO"); add(0x00102293, "Patient Breed Code Sequence", "SQ"); add(0x00102294, "Breed Registration Sequence", "SQ"); add(0x00102295, "Breed Registration Number", "LO"); add(0x00102296, "Breed Registry Code Sequence", "SQ"); add(0x00102297, "Responsible Person", "PN"); add(0x00102298, "Responsible Person Role", "CS"); add(0x00102299, "Responsible Organization", "LO"); add(0x00104000, "Patient Comments", "LT"); add(0x00109431, "Examined Body Thickness", "FL"); } /** * Adds attributes of group 0x0012. */ private void addAttributeGroup0012() { add(0x00120010, "Clinical Trial Sponsor Name", "LO"); add(0x00120020, "Clinical Trial Protocol ID", "LO"); add(0x00120021, "Clinical Trial Protocol Name", "LO"); add(0x00120030, "Clinical Trial Site ID", "LO"); add(0x00120031, "Clinical Trial Site Name", "LO"); add(0x00120040, "Clinical Trial Subject ID", "LO"); add(0x00120042, "Clinical Trial Subject Reading ID", "LO"); add(0x00120050, "Clinical Trial Time Point ID", "LO"); add(0x00120051, "Clinical Trial Time Point Description", "ST"); add(0x00120060, "Clinical Trial Coordinating CenterName", "LO"); add(0x00120062, "Patient Identity Removed", "CS"); add(0x00120063, "De-identification Method", "LO"); add(0x00120064, "De-identification Method CodeSequence", "SQ"); add(0x00120071, "Clinical Trial Series ID", "LO"); add(0x00120072, "Clinical Trial Series Description", "LO"); add(0x00120081, "Clinical Trial Protocol EthicsCommittee Name", "LO"); add(0x00120082, "Clinical Trial Protocol EthicsCommittee Approval Number", "LO"); add(0x00120083, "Consent for Clinical Trial UseSequence", "SQ"); add(0x00120084, "Distribution Type", "CS"); add(0x00120085, "Consent for Distribution Flag", "CS"); } /** * Adds attributes of group 0x0014. */ private void addAttributeGroup0014() { add(0x00140023, "CAD File Format", "ST"); // Retired add(0x00140024, "Component Reference System", "ST"); // Retired add(0x00140025, "Component ManufacturingProcedure", "ST"); // DICONDE add(0x00140028, "Component Manufacturer", "ST"); // DICONDE add(0x00140030, "Material Thickness", "DS"); // DICONDE add(0x00140032, "Material Pipe Diameter", "DS"); // DICONDE add(0x00140034, "Material Isolation Diameter", "DS"); // DICONDE add(0x00140042, "Material Grade", "ST"); // DICONDE add(0x00140044, "Material Properties Description", "ST"); // DICONDE add(0x00140045, "Material Properties File Format(Retired)", "ST"); // Retired add(0x00140046, "Material Notes", "LT"); // DICONDE add(0x00140050, "Component Shape", "CS"); // DICONDE add(0x00140052, "Curvature Type", "CS"); // DICONDE add(0x00140054, "Outer Diameter", "DS"); // DICONDE add(0x00140056, "Inner Diameter", "DS"); // DICONDE add(0x00141010, "Actual Environmental Conditions", "ST"); // DICONDE add(0x00141020, "Expiry Date", "DA"); // DICONDE add(0x00141040, "Environmental Conditions", "ST"); // DICONDE add(0x00142002, "Evaluator Sequence", "SQ"); // DICONDE add(0x00142004, "Evaluator Number", "IS"); // DICONDE add(0x00142006, "Evaluator Name", "PN"); // DICONDE add(0x00142008, "Evaluation Attempt", "IS"); // DICONDE add(0x00142012, "Indication Sequence", "SQ"); // DICONDE add(0x00142014, "Indication Number", "IS"); // DICONDE add(0x00142016, "Indication Label", "SH"); // DICONDE add(0x00142018, "Indication Description", "ST"); // DICONDE add(0x0014201A, "Indication Type", "CS"); // DICONDE add(0x0014201C, "Indication Disposition", "CS"); // DICONDE add(0x0014201E, "Indication ROI Sequence", "SQ"); // DICONDE add(0x00142030, "Indication Physical PropertySequence", "SQ"); // DICONDE add(0x00142032, "Property Label", "SH"); // DICONDE add(0x00142202, "Coordinate System Number ofAxes", "IS"); // DICONDE add(0x00142204, "Coordinate System Axes Sequence", "SQ"); // DICONDE add(0x00142206, "Coordinate System AxisDescription", "ST"); // DICONDE add(0x00142208, "Coordinate System Data SetMapping", "CS"); // DICONDE add(0x0014220A, "Coordinate System Axis Number", "IS"); // DICONDE add(0x0014220C, "Coordinate System Axis Type", "CS"); // DICONDE add(0x0014220E, "Coordinate System Axis Units", "CS"); // DICONDE add(0x00142210, "Coordinate System Axis Values", "OB"); // DICONDE add(0x00142220, "Coordinate System TransformSequence", "SQ"); // DICONDE add(0x00142222, "Transform Description", "ST"); // DICONDE add(0x00142224, "Transform Number of Axes", "IS"); // DICONDE add(0x00142226, "Transform Order of Axes", "IS"); // DICONDE add(0x00142228, "Transformed Axis Units", "CS"); // DICONDE add(0x0014222A, "Coordinate System TransformRotation and Scale Matrix", "DS"); // DICONDE add(0x0014222C, "Coordinate System TransformTranslation Matrix", "DS"); // DICONDE add(0x00143011, "Internal Detector Frame Time", "DS"); // DICONDE add(0x00143012, "Number of Frames Integrated", "DS"); // DICONDE add(0x00143020, "Detector Temperature Sequence", "SQ"); // DICONDE add(0x00143022, "Sensor Name", "ST"); // DICONDE add(0x00143024, "Horizontal Offset of Sensor", "DS"); // DICONDE add(0x00143026, "Vertical Offset of Sensor", "DS"); // DICONDE add(0x00143028, "Sensor Temperature", "DS"); // DICONDE add(0x00143040, "Dark Current Sequence", "SQ"); // DICONDE // add(0x00143050, "Dark Current Counts", "OB or OW"); //DICONDE add(0x00143060, "Gain Correction ReferenceSequence", "SQ"); // DICONDE // add(0x00143070, "Air Counts", "OB or OW"); //DICONDE add(0x00143071, "KV Used in Gain Calibration", "DS"); // DICONDE add(0x00143072, "MA Used in Gain Calibration", "DS"); // DICONDE add(0x00143073, "Number of Frames Used forIntegration", "DS"); // DICONDE add(0x00143074, "Filter Material Used in GainCalibration", "LO"); // DICONDE add(0x00143075, "Filter Thickness Used in GainCalibration", "DS"); // DICONDE add(0x00143076, "Date of Gain Calibration", "DA"); // DICONDE add(0x00143077, "Time of Gain Calibration", "TM"); // DICONDE add(0x00143080, "Bad Pixel Image", "OB"); // DICONDE add(0x00143099, "Calibration Notes", "LT"); // DICONDE add(0x00144002, "Pulser Equipment Sequence", "SQ"); // DICONDE add(0x00144004, "Pulser Type", "CS"); // DICONDE add(0x00144006, "Pulser Notes", "LT"); // DICONDE add(0x00144008, "Receiver Equipment Sequence", "SQ"); // DICONDE add(0x0014400A, "Amplifier Type", "CS"); // DICONDE add(0x0014400C, "Receiver Notes", "LT"); // DICONDE add(0x0014400E, "Pre-Amplifier Equipment Sequence", "SQ"); // DICONDE add(0x0014400F, "Pre-Amplifier Notes", "LT"); // DICONDE add(0x00144010, "Transmit Transducer Sequence", "SQ"); // DICONDE add(0x00144011, "Receive Transducer Sequence", "SQ"); // DICONDE add(0x00144012, "Number of Elements", "US"); // DICONDE add(0x00144013, "Element Shape", "CS"); // DICONDE add(0x00144014, "Element Dimension A", "DS"); // DICONDE add(0x00144015, "Element Dimension B", "DS"); // DICONDE add(0x00144016, "Element Pitch A", "DS"); // DICONDE add(0x00144017, "Measured Beam Dimension A", "DS"); // DICONDE add(0x00144018, "Measured Beam Dimension B", "DS"); // DICONDE add(0x00144019, "Location of Measured BeamDiameter", "DS"); // DICONDE add(0x0014401A, "Nominal Frequency", "DS"); // DICONDE add(0x0014401B, "Measured Center Frequency", "DS"); // DICONDE add(0x0014401C, "Measured Bandwidth", "DS"); // DICONDE add(0x0014401D, "Element Pitch B", "DS"); // DICONDE add(0x00144020, "Pulser Settings Sequence", "SQ"); // DICONDE add(0x00144022, "Pulse Width", "DS"); // DICONDE add(0x00144024, "Excitation Frequency", "DS"); // DICONDE add(0x00144026, "Modulation Type", "CS"); // DICONDE add(0x00144028, "Damping", "DS"); // DICONDE add(0x00144030, "Receiver Settings Sequence", "SQ"); // DICONDE add(0x00144031, "Acquired Soundpath Length", "DS"); // DICONDE add(0x00144032, "Acquisition Compression Type", "CS"); // DICONDE add(0x00144033, "Acquisition Sample Size", "IS"); // DICONDE add(0x00144034, "Rectifier Smoothing", "DS"); // DICONDE add(0x00144035, "DAC Sequence", "SQ"); // DICONDE add(0x00144036, "DAC Type", "CS"); // DICONDE add(0x00144038, "DAC Gain Points", "DS"); // DICONDE add(0x0014403A, "DAC Time Points", "DS"); // DICONDE add(0x0014403C, "DAC Amplitude", "DS"); // DICONDE add(0x00144040, "Pre-Amplifier Settings Sequence", "SQ"); // DICONDE add(0x00144050, "Transmit Transducer SettingsSequence", "SQ"); // DICONDE add(0x00144051, "Receive Transducer SettingsSequence", "SQ"); // DICONDE add(0x00144052, "Incident Angle", "DS"); // DICONDE add(0x00144054, "Coupling Technique", "ST"); // DICONDE add(0x00144056, "Coupling Medium", "ST"); // DICONDE add(0x00144057, "Coupling Velocity", "DS"); // DICONDE add(0x00144058, "Probe Center Location X", "DS"); // DICONDE add(0x00144059, "Probe Center Location Z", "DS"); // DICONDE add(0x0014405A, "Sound Path Length", "DS"); // DICONDE add(0x0014405C, "Delay Law Identifier", "ST"); // DICONDE add(0x00144060, "Gate Settings Sequence", "SQ"); // DICONDE add(0x00144062, "Gate Threshold", "DS"); // DICONDE add(0x00144064, "Velocity of Sound", "DS"); // DICONDE add(0x00144070, "Calibration Settings Sequence", "SQ"); // DICONDE add(0x00144072, "Calibration Procedure", "ST"); // DICONDE add(0x00144074, "Procedure Version", "SH"); // DICONDE add(0x00144076, "Procedure Creation Date", "DA"); // DICONDE add(0x00144078, "Procedure Expiration Date", "DA"); // DICONDE add(0x0014407A, "Procedure Last Modified Date", "DA"); // DICONDE add(0x0014407C, "Calibration Time", "TM"); // DICONDE add(0x0014407E, "Calibration Date", "DA"); // DICONDE add(0x00144080, "Probe Drive Equipment Sequence", "SQ"); // DICONDE add(0x00144081, "Drive Type", "CS"); // DICONDE add(0x00144082, "Probe Drive Notes", "LT"); // DICONDE add(0x00144083, "Drive Probe Sequence", "SQ"); // DICONDE add(0x00144084, "Probe Inductance", "DS"); // DICONDE add(0x00144085, "Probe Resistance", "DS"); // DICONDE add(0x00144086, "Receive Probe Sequence", "SQ"); // DICONDE add(0x00144087, "Probe Drive Settings Sequence", "SQ"); // DICONDE add(0x00144088, "Bridge Resistors", "DS"); // DICONDE add(0x00144089, "Probe Orientation Angle", "DS"); // DICONDE add(0x0014408B, "User Selected Gain Y", "DS"); // DICONDE add(0x0014408C, "User Selected Phase", "DS"); // DICONDE add(0x0014408D, "User Selected Offset X", "DS"); // DICONDE add(0x0014408E, "User Selected Offset Y", "DS"); // DICONDE add(0x00144091, "Channel Settings Sequence", "SQ"); // DICONDE add(0x00144092, "Channel Threshold", "DS"); // DICONDE add(0x0014409A, "Scanner Settings Sequence", "SQ"); // DICONDE add(0x0014409B, "Scan Procedure", "ST"); // DICONDE add(0x0014409C, "Translation Rate X", "DS"); // DICONDE add(0x0014409D, "Translation Rate Y", "DS"); // DICONDE add(0x0014409F, "Channel Overlap", "DS"); // DICONDE add(0x001440A0, "Image Quality Indicator Type", "LO"); // DICONDE add(0x001440A1, "Image Quality Indicator Material", "LO"); // DICONDE add(0x001440A2, "Image Quality Indicator Size", "LO"); // DICONDE add(0x00145002, "LINAC Energy", "IS"); // DICONDE add(0x00145004, "LINAC Output", "IS"); // DICONDE add(0x00145100, "Active Aperture", "US"); // DICONDE add(0x00145101, "Total Aperture", "DS"); // DICONDE add(0x00145102, "Aperture Elevation", "DS"); // DICONDE add(0x00145103, "Main Lobe Angle", "DS"); // DICONDE add(0x00145104, "Main Roof Angle", "DS"); // DICONDE add(0x00145105, "Connector Type", "CS"); // DICONDE add(0x00145106, "Wedge Model Number", "SH"); // DICONDE add(0x00145107, "Wedge Angle Float", "DS"); // DICONDE add(0x00145108, "Wedge Roof Angle", "DS"); // DICONDE add(0x00145109, "Wedge Element 1 Position", "CS"); // DICONDE add(0x0014510A, "Wedge Material Velocity", "DS"); // DICONDE add(0x0014510B, "Wedge Material", "SH"); // DICONDE add(0x0014510C, "Wedge Offset Z", "DS"); // DICONDE add(0x0014510D, "Wedge Origin Offset X", "DS"); // DICONDE add(0x0014510E, "Wedge Time Delay", "DS"); // DICONDE add(0x0014510F, "Wedge Name", "SH"); // DICONDE add(0x00145110, "Wedge Manufacturer Name", "SH"); // DICONDE add(0x00145111, "Wedge Description", "LO"); // DICONDE add(0x00145112, "Nominal Beam Angle", "DS"); // DICONDE add(0x00145113, "Wedge Offset X", "DS"); // DICONDE add(0x00145114, "Wedge Offset Y", "DS"); // DICONDE add(0x00145115, "Wedge Total Length", "DS"); // DICONDE add(0x00145116, "Wedge In Contact Length", "DS"); // DICONDE add(0x00145117, "Wedge Front Gap", "DS"); // DICONDE add(0x00145118, "Wedge Total Height", "DS"); // DICONDE add(0x00145119, "Wedge Front Height", "DS"); // DICONDE add(0x0014511A, "Wedge Rear Height", "DS"); // DICONDE add(0x0014511B, "Wedge Total Width", "DS"); // DICONDE add(0x0014511C, "Wedge In Contact Width", "DS"); // DICONDE add(0x0014511D, "Wedge Chamfer Height", "DS"); // DICONDE add(0x0014511E, "Wedge Curve", "CS"); // DICONDE add(0x0014511F, "Radius Along the Wedge", "DS"); // DICONDE } /** * Adds attributes of group 0x0018. */ private void addAttributeGroup0018() { add(0x00180010, "Contrast/Bolus Agent", "LO"); add(0x00180012, "Contrast/Bolus Agent Sequence", "SQ"); add(0x00180013, "Contrast/Bolus T1 Relaxivity", "FL"); add(0x00180014, "Contrast/Bolus AdministrationRoute Sequence", "SQ"); add(0x00180015, "Body Part Examined", "CS"); add(0x00180020, "Scanning Sequence", "CS"); add(0x00180021, "Sequence Variant", "CS"); add(0x00180022, "Scan Options", "CS"); add(0x00180023, "MR Acquisition Type", "CS"); add(0x00180024, "Sequence Name", "SH"); add(0x00180025, "Angio Flag", "CS"); add(0x00180026, "Intervention Drug InformationSequence", "SQ"); add(0x00180027, "Intervention Drug Stop Time", "TM"); add(0x00180028, "Intervention Drug Dose", "DS"); add(0x00180029, "Intervention Drug Code Sequence", "SQ"); add(0x0018002A, "Additional Drug Sequence", "SQ"); add(0x00180030, "Radionuclide", "LO"); // Retired add(0x00180031, "Radiopharmaceutical", "LO"); add(0x00180032, "Energy Window Centerline", "DS"); // Retired add(0x00180033, "Energy Window Total Width", "DS"); // Retired add(0x00180034, "Intervention Drug Name", "LO"); add(0x00180035, "Intervention Drug Start Time", "TM"); add(0x00180036, "Intervention Sequence", "SQ"); add(0x00180037, "Therapy Type", "CS"); // Retired add(0x00180038, "Intervention Status", "CS"); add(0x00180039, "Therapy Description", "CS"); // Retired add(0x0018003A, "Intervention Description", "ST"); add(0x00180040, "Cine Rate", "IS"); add(0x00180042, "Initial Cine Run State", "CS"); add(0x00180050, "Slice Thickness", "DS"); add(0x00180060, "KVP", "DS"); add(0x00180070, "Counts Accumulated", "IS"); add(0x00180071, "Acquisition Termination Condition", "CS"); add(0x00180072, "Effective Duration", "DS"); add(0x00180073, "Acquisition Start Condition", "CS"); add(0x00180074, "Acquisition Start Condition Data", "IS"); add(0x00180075, "Acquisition Termination ConditionData", "IS"); add(0x00180080, "Repetition Time", "DS"); add(0x00180081, "Echo Time", "DS"); add(0x00180082, "Inversion Time", "DS"); add(0x00180083, "Number of Averages", "DS"); add(0x00180084, "Imaging Frequency", "DS"); add(0x00180085, "Imaged Nucleus", "SH"); add(0x00180086, "Echo Number(s)", "IS"); add(0x00180087, "Magnetic Field Strength", "DS"); add(0x00180088, "Spacing Between Slices", "DS"); add(0x00180089, "Number of Phase Encoding Steps", "IS"); add(0x00180090, "Data Collection Diameter", "DS"); add(0x00180091, "Echo Train Length", "IS"); add(0x00180093, "Percent Sampling", "DS"); add(0x00180094, "Percent Phase Field of View", "DS"); add(0x00180095, "Pixel Bandwidth", "DS"); add(0x00181000, "Device Serial Number", "LO"); add(0x00181002, "Device UID", "UI"); add(0x00181003, "Device ID", "LO"); add(0x00181004, "Plate ID", "LO"); add(0x00181005, "Generator ID", "LO"); add(0x00181006, "Grid ID", "LO"); add(0x00181007, "Cassette ID", "LO"); add(0x00181008, "Gantry ID", "LO"); add(0x00181010, "Secondary Capture Device ID", "LO"); add(0x00181011, "Hardcopy Creation Device ID", "LO"); // Retired add(0x00181012, "Date of Secondary Capture", "DA"); add(0x00181014, "Time of Secondary Capture", "TM"); add(0x00181016, "Secondary Capture DeviceManufacturer", "LO"); add(0x00181017, "Hardcopy Device Manufacturer", "LO"); // Retired add(0x00181018, "Secondary Capture DeviceManufacturer's Model Name", "LO"); add(0x00181019, "Secondary Capture DeviceSoftware Versions", "LO"); add(0x0018101A, "Hardcopy Device Software Version", "LO"); // Retired add(0x0018101B, "Hardcopy Device Manufacturer'sModel Name", "LO"); // Retired add(0x00181020, "Software Version(s)", "LO"); add(0x00181022, "Video Image Format Acquired", "SH"); add(0x00181023, "Digital Image Format Acquired", "LO"); add(0x00181030, "Protocol Name", "LO"); add(0x00181040, "Contrast/Bolus Route", "LO"); add(0x00181041, "Contrast/Bolus Volume", "DS"); add(0x00181042, "Contrast/Bolus Start Time", "TM"); add(0x00181043, "Contrast/Bolus Stop Time", "TM"); add(0x00181044, "Contrast/Bolus Total Dose", "DS"); add(0x00181045, "Syringe Counts", "IS"); add(0x00181046, "Contrast Flow Rate", "DS"); add(0x00181047, "Contrast Flow Duration", "DS"); add(0x00181048, "Contrast/Bolus Ingredient", "CS"); add(0x00181049, "Contrast/Bolus IngredientConcentration", "DS"); add(0x00181050, "Spatial Resolution", "DS"); add(0x00181060, "Trigger Time", "DS"); // add(0x00181061, "Trigger Source or Type", "LO"); add(0x00181062, "Nominal Interval", "IS"); add(0x00181063, "Frame Time", "DS"); add(0x00181064, "Cardiac Framing Type", "LO"); add(0x00181065, "Frame Time Vector", "DS"); add(0x00181066, "Frame Delay", "DS"); add(0x00181067, "Image Trigger Delay", "DS"); add(0x00181068, "Multiplex Group Time Offset", "DS"); add(0x00181069, "Trigger Time Offset", "DS"); add(0x0018106A, "Synchronization Trigger", "CS"); add(0x0018106C, "Synchronization Channel", "US"); add(0x0018106E, "Trigger Sample Position", "UL"); add(0x00181070, "Radiopharmaceutical Route", "LO"); add(0x00181071, "Radiopharmaceutical Volume", "DS"); add(0x00181072, "Radiopharmaceutical Start Time", "TM"); add(0x00181073, "Radiopharmaceutical Stop Time", "TM"); add(0x00181074, "Radionuclide Total Dose", "DS"); add(0x00181075, "Radionuclide Half Life", "DS"); add(0x00181076, "Radionuclide Positron Fraction", "DS"); add(0x00181077, "Radiopharmaceutical SpecificActivity", "DS"); add(0x00181078, "Radiopharmaceutical StartDateTime", "DT"); add(0x00181079, "Radiopharmaceutical StopDateTime", "DT"); add(0x00181080, "Beat Rejection Flag", "CS"); add(0x00181081, "Low R-R Value", "IS"); add(0x00181082, "High R-R Value", "IS"); add(0x00181083, "Intervals Acquired", "IS"); add(0x00181084, "Intervals Rejected", "IS"); add(0x00181085, "PVC Rejection", "LO"); add(0x00181086, "Skip Beats", "IS"); add(0x00181088, "Heart Rate", "IS"); add(0x00181090, "Cardiac Number of Images", "IS"); add(0x00181094, "Trigger Window", "IS"); add(0x00181100, "Reconstruction Diameter", "DS"); add(0x00181110, "Distance Source to Detector", "DS"); add(0x00181111, "Distance Source to Patient", "DS"); add(0x00181114, "Estimated RadiographicMagnification Factor", "DS"); add(0x00181120, "Gantry/Detector Tilt", "DS"); add(0x00181121, "Gantry/Detector Slew", "DS"); add(0x00181130, "Table Height", "DS"); add(0x00181131, "Table Traverse", "DS"); add(0x00181134, "Table Motion", "CS"); add(0x00181135, "Table Vertical Increment", "DS"); add(0x00181136, "Table Lateral Increment", "DS"); add(0x00181137, "Table Longitudinal Increment", "DS"); add(0x00181138, "Table Angle", "DS"); add(0x0018113A, "Table Type", "CS"); add(0x00181140, "Rotation Direction", "CS"); add(0x00181141, "Angular Position", "DS"); // Retired add(0x00181142, "Radial Position", "DS"); add(0x00181143, "Scan Arc", "DS"); add(0x00181144, "Angular Step", "DS"); add(0x00181145, "Center of Rotation Offset", "DS"); add(0x00181146, "Rotation Offset", "DS"); // Retired add(0x00181147, "Field of View Shape", "CS"); add(0x00181149, "Field of View Dimension(s)", "IS"); add(0x00181150, "Exposure Time", "IS"); add(0x00181151, "X-Ray Tube Current", "IS"); add(0x00181152, "Exposure", "IS"); add(0x00181153, "Exposure in uAs", "IS"); add(0x00181154, "Average Pulse Width", "DS"); add(0x00181155, "Radiation Setting", "CS"); add(0x00181156, "Rectification Type", "CS"); add(0x0018115A, "Radiation Mode", "CS"); add(0x0018115E, "Image and Fluoroscopy Area DoseProduct", "DS"); add(0x00181160, "Filter Type", "SH"); add(0x00181161, "Type of Filters", "LO"); add(0x00181162, "Intensifier Size", "DS"); add(0x00181164, "Imager Pixel Spacing", "DS"); add(0x00181166, "Grid", "CS"); add(0x00181170, "Generator Power", "IS"); add(0x00181180, "Collimator/grid Name", "SH"); add(0x00181181, "Collimator Type", "CS"); add(0x00181182, "Focal Distance", "IS"); add(0x00181183, "X Focus Center", "DS"); add(0x00181184, "Y Focus Center", "DS"); add(0x00181190, "Focal Spot(s)", "DS"); add(0x00181191, "Anode Target Material", "CS"); add(0x001811A0, "Body Part Thickness", "DS"); add(0x001811A2, "Compression Force", "DS"); add(0x001811A4, "Paddle Description", "LO"); add(0x00181200, "Date of Last Calibration", "DA"); add(0x00181201, "Time of Last Calibration", "TM"); add(0x00181202, "DateTime of Last Calibration", "DT"); add(0x00181210, "Convolution Kernel", "SH"); add(0x00181240, "Upper/Lower Pixel Values", "IS"); // Retired add(0x00181242, "Actual Frame Duration", "IS"); add(0x00181243, "Count Rate", "IS"); add(0x00181244, "Preferred Playback Sequencing", "US"); add(0x00181250, "Receive Coil Name", "SH"); add(0x00181251, "Transmit Coil Name", "SH"); add(0x00181260, "Plate Type", "SH"); add(0x00181261, "Phosphor Type", "LO"); add(0x00181300, "Scan Velocity", "DS"); add(0x00181301, "Whole Body Technique", "CS"); add(0x00181302, "Scan Length", "IS"); add(0x00181310, "Acquisition Matrix", "US"); add(0x00181312, "In-plane Phase Encoding Direction", "CS"); add(0x00181314, "Flip Angle", "DS"); add(0x00181315, "Variable Flip Angle Flag", "CS"); add(0x00181316, "SAR", "DS"); add(0x00181318, "dB/dt", "DS"); add(0x00181400, "Acquisition Device ProcessingDescription", "LO"); add(0x00181401, "Acquisition Device ProcessingCode", "LO"); add(0x00181402, "Cassette Orientation", "CS"); add(0x00181403, "Cassette Size", "CS"); add(0x00181404, "Exposures on Plate", "US"); add(0x00181405, "Relative X-Ray Exposure", "IS"); add(0x00181411, "Exposure Index", "DS"); add(0x00181412, "Target Exposure Index", "DS"); add(0x00181413, "Deviation Index", "DS"); add(0x00181450, "Column Angulation", "DS"); add(0x00181460, "Tomo Layer Height", "DS"); add(0x00181470, "Tomo Angle", "DS"); add(0x00181480, "Tomo Time", "DS"); add(0x00181490, "Tomo Type", "CS"); add(0x00181491, "Tomo Class", "CS"); add(0x00181495, "Number of Tomosynthesis SourceImages", "IS"); add(0x00181500, "Positioner Motion", "CS"); add(0x00181508, "Positioner Type", "CS"); add(0x00181510, "Positioner Primary Angle", "DS"); add(0x00181511, "Positioner Secondary Angle", "DS"); add(0x00181520, "Positioner Primary Angle Increment", "DS"); add(0x00181521, "Positioner Secondary AngleIncrement", "DS"); add(0x00181530, "Detector Primary Angle", "DS"); add(0x00181531, "Detector Secondary Angle", "DS"); add(0x00181600, "Shutter Shape", "CS"); add(0x00181602, "Shutter Left Vertical Edge", "IS"); add(0x00181604, "Shutter Right Vertical Edge", "IS"); add(0x00181606, "Shutter Upper Horizontal Edge", "IS"); add(0x00181608, "Shutter Lower Horizontal Edge", "IS"); add(0x00181610, "Center of Circular Shutter", "IS"); add(0x00181612, "Radius of Circular Shutter", "IS"); add(0x00181620, "Vertices of the Polygonal Shutter", "IS"); add(0x00181622, "Shutter Presentation Value", "US"); add(0x00181623, "Shutter Overlay Group", "US"); add(0x00181624, "Shutter Presentation Color CIELabValue", "US"); add(0x00181700, "Collimator Shape", "CS"); add(0x00181702, "Collimator Left Vertical Edge", "IS"); add(0x00181704, "Collimator Right Vertical Edge", "IS"); add(0x00181706, "Collimator Upper Horizontal Edge", "IS"); add(0x00181708, "Collimator Lower Horizontal Edge", "IS"); add(0x00181710, "Center of Circular Collimator", "IS"); add(0x00181712, "Radius of Circular Collimator", "IS"); add(0x00181720, "Vertices of the PolygonalCollimator", "IS"); add(0x00181800, "Acquisition Time Synchronized", "CS"); add(0x00181801, "Time Source", "SH"); add(0x00181802, "Time Distribution Protocol", "CS"); add(0x00181803, "NTP Source Address", "LO"); add(0x00182001, "Page Number Vector", "IS"); add(0x00182002, "Frame Label Vector", "SH"); add(0x00182003, "Frame Primary Angle Vector", "DS"); add(0x00182004, "Frame Secondary Angle Vector", "DS"); add(0x00182005, "Slice Location Vector", "DS"); add(0x00182006, "Display Window Label Vector", "SH"); add(0x00182010, "Nominal Scanned Pixel Spacing", "DS"); add(0x00182020, "Digitizing Device TransportDirection", "CS"); add(0x00182030, "Rotation of Scanned Film", "DS"); add(0x00182041, "Biopsy Target Sequence", "SQ"); add(0x00182042, "Target UID", "UI"); add(0x00182043, "Localizing Cursor Position", "FL"); add(0x00182044, "Calculated Target Position", "FL"); add(0x00182045, "Target Label", "SH"); add(0x00182046, "Displayed Z Value", "FL"); add(0x00183100, "IVUS Acquisition", "CS"); add(0x00183101, "IVUS Pullback Rate", "DS"); add(0x00183102, "IVUS Gated Rate", "DS"); add(0x00183103, "IVUS Pullback Start Frame Number", "IS"); add(0x00183104, "IVUS Pullback Stop Frame Number", "IS"); add(0x00183105, "Lesion Number", "IS"); add(0x00184000, "Acquisition Comments", "LT"); // Retired add(0x00185000, "Output Power", "SH"); add(0x00185010, "Transducer Data", "LO"); add(0x00185012, "Focus Depth", "DS"); add(0x00185020, "Processing Function", "LO"); add(0x00185021, "Postprocessing Function", "LO"); // Retired add(0x00185022, "Mechanical Index", "DS"); add(0x00185024, "Bone Thermal Index", "DS"); add(0x00185026, "Cranial Thermal Index", "DS"); add(0x00185027, "Soft Tissue Thermal Index", "DS"); add(0x00185028, "Soft Tissue-focus Thermal Index", "DS"); add(0x00185029, "Soft Tissue-surface Thermal Index", "DS"); add(0x00185030, "Dynamic Range", "DS"); // Retired add(0x00185040, "Total Gain", "DS"); // Retired add(0x00185050, "Depth of Scan Field", "IS"); add(0x00185100, "Patient Position", "CS"); add(0x00185101, "View Position", "CS"); add(0x00185104, "Projection Eponymous Name CodeSequence", "SQ"); add(0x00185210, "Image Transformation Matrix", "DS"); // Retired add(0x00185212, "Image Translation Vector", "DS"); // Retired add(0x00186000, "Sensitivity", "DS"); add(0x00186011, "Sequence of Ultrasound Regions", "SQ"); add(0x00186012, "Region Spatial Format", "US"); add(0x00186014, "Region Data Type", "US"); add(0x00186016, "Region Flags", "UL"); add(0x00186018, "Region Location Min X0", "UL"); add(0x0018601A, "Region Location Min Y0", "UL"); add(0x0018601C, "Region Location Max X1", "UL"); add(0x0018601E, "Region Location Max Y1", "UL"); add(0x00186020, "Reference Pixel X0", "SL"); add(0x00186022, "Reference Pixel Y0", "SL"); add(0x00186024, "Physical Units X Direction", "US"); add(0x00186026, "Physical Units Y Direction", "US"); add(0x00186028, "Reference Pixel Physical Value X", "FD"); add(0x0018602A, "Reference Pixel Physical Value Y", "FD"); add(0x0018602C, "Physical Delta X", "FD"); add(0x0018602E, "Physical Delta Y", "FD"); add(0x00186030, "Transducer Frequency", "UL"); add(0x00186031, "Transducer Type", "CS"); add(0x00186032, "Pulse Repetition Frequency", "UL"); add(0x00186034, "Doppler Correction Angle", "FD"); add(0x00186036, "Steering Angle", "FD"); add(0x00186038, "Doppler Sample Volume X Position(Retired)", "UL"); // Retired add(0x00186039, "Doppler Sample Volume X Position", "SL"); add(0x0018603A, "Doppler Sample Volume Y Position(Retired)", "UL"); // Retired add(0x0018603B, "Doppler Sample Volume Y Position", "SL"); add(0x0018603C, "TM-Line Position X0 (Retired)", "UL"); // Retired add(0x0018603D, "TM-Line Position X0", "SL"); add(0x0018603E, "TM-Line Position Y0 (Retired)", "UL"); // Retired add(0x0018603F, "TM-Line Position Y0", "SL"); add(0x00186040, "TM-Line Position X1 (Retired)", "UL"); // Retired add(0x00186041, "TM-Line Position X1", "SL"); add(0x00186042, "TM-Line Position Y1 (Retired)", "UL"); // Retired add(0x00186043, "TM-Line Position Y1", "SL"); add(0x00186044, "Pixel Component Organization", "US"); add(0x00186046, "Pixel Component Mask", "UL"); add(0x00186048, "Pixel Component Range Start", "UL"); add(0x0018604A, "Pixel Component Range Stop", "UL"); add(0x0018604C, "Pixel Component Physical Units", "US"); add(0x0018604E, "Pixel Component Data Type", "US"); add(0x00186050, "Number of Table Break Points", "UL"); add(0x00186052, "Table of X Break Points", "UL"); add(0x00186054, "Table of Y Break Points", "FD"); add(0x00186056, "Number of Table Entries", "UL"); add(0x00186058, "Table of Pixel Values", "UL"); add(0x0018605A, "Table of Parameter Values", "FL"); add(0x00186060, "R Wave Time Vector", "FL"); add(0x00187000, "Detector Conditions Nominal Flag", "CS"); add(0x00187001, "Detector Temperature", "DS"); add(0x00187004, "Detector Type", "CS"); add(0x00187005, "Detector Configuration", "CS"); add(0x00187006, "Detector Description", "LT"); add(0x00187008, "Detector Mode", "LT"); add(0x0018700A, "Detector ID", "SH"); add(0x0018700C, "Date of Last Detector Calibration", "DA"); add(0x0018700E, "Time of Last Detector Calibration", "TM"); add(0x00187010, "Exposures on Detector Since LastCalibration", "IS"); add(0x00187011, "Exposures on Detector SinceManufactured", "IS"); add(0x00187012, "Detector Time Since Last Exposure", "DS"); add(0x00187014, "Detector Active Time", "DS"); add(0x00187016, "Detector Activation Offset FromExposure", "DS"); add(0x0018701A, "Detector Binning", "DS"); add(0x00187020, "Detector Element Physical Size", "DS"); add(0x00187022, "Detector Element Spacing", "DS"); add(0x00187024, "Detector Active Shape", "CS"); add(0x00187026, "Detector Active Dimension(s)", "DS"); add(0x00187028, "Detector Active Origin", "DS"); add(0x0018702A, "Detector Manufacturer Name DetectorManufacturerName LO 1 (0018,702B) Detector Manufacturer's ModelName", "LO"); add(0x00187030, "Field of View Origin", "DS"); add(0x00187032, "Field of View Rotation", "DS"); add(0x00187034, "Field of View Horizontal Flip", "CS"); add(0x00187036, "Pixel Data Area Origin Relative ToFOV", "FL"); add(0x00187038, "Pixel Data Area Rotation AngleRelative To FOV", "FL"); add(0x00187040, "Grid Absorbing Material", "LT"); add(0x00187041, "Grid Spacing Material", "LT"); add(0x00187042, "Grid Thickness", "DS"); add(0x00187044, "Grid Pitch", "DS"); add(0x00187046, "Grid Aspect Ratio", "IS"); add(0x00187048, "Grid Period", "DS"); add(0x0018704C, "Grid Focal Distance", "DS"); add(0x00187050, "Filter Material", "CS"); add(0x00187052, "Filter Thickness Minimum", "DS"); add(0x00187054, "Filter Thickness Maximum", "DS"); add(0x00187056, "Filter Beam Path Length Minimum", "FL"); add(0x00187058, "Filter Beam Path Length Maximum", "FL"); add(0x00187060, "Exposure Control Mode", "CS"); add(0x00187062, "Exposure Control Mode Description", "LT"); add(0x00187064, "Exposure Status", "CS"); add(0x00187065, "Phototimer Setting", "DS"); add(0x00188150, "Exposure Time in uS", "DS"); add(0x00188151, "X-Ray Tube Current in uA", "DS"); add(0x00189004, "Content Qualification", "CS"); add(0x00189005, "Pulse Sequence Name", "SH"); add(0x00189006, "MR Imaging Modifier Sequence", "SQ"); add(0x00189008, "Echo Pulse Sequence", "CS"); add(0x00189009, "Inversion Recovery", "CS"); add(0x00189010, "Flow Compensation", "CS"); add(0x00189011, "Multiple Spin Echo", "CS"); add(0x00189012, "Multi-planar Excitation", "CS"); add(0x00189014, "Phase Contrast", "CS"); add(0x00189015, "Time of Flight Contrast", "CS"); add(0x00189016, "Spoiling", "CS"); add(0x00189017, "Steady State Pulse Sequence", "CS"); add(0x00189018, "Echo Planar Pulse Sequence", "CS"); add(0x00189019, "Tag Angle First Axis", "FD"); add(0x00189020, "Magnetization Transfer", "CS"); add(0x00189021, "T2 Preparation", "CS"); add(0x00189022, "Blood Signal Nulling", "CS"); add(0x00189024, "Saturation Recovery", "CS"); add(0x00189025, "Spectrally Selected Suppression", "CS"); add(0x00189026, "Spectrally Selected Excitation", "CS"); add(0x00189027, "Spatial Pre-saturation", "CS"); add(0x00189028, "Tagging", "CS"); add(0x00189029, "Oversampling Phase", "CS"); add(0x00189030, "Tag Spacing First Dimension", "FD"); add(0x00189032, "Geometry of k-Space Traversal", "CS"); add(0x00189033, "Segmented k-Space Traversal", "CS"); add(0x00189034, "Rectilinear Phase EncodeReordering", "CS"); add(0x00189035, "Tag Thickness", "FD"); add(0x00189036, "Partial Fourier Direction", "CS"); add(0x00189037, "Cardiac Synchronization Technique", "CS"); add(0x00189041, "Receive Coil Manufacturer Name", "LO"); add(0x00189042, "MR Receive Coil Sequence", "SQ"); add(0x00189043, "Receive Coil Type", "CS"); add(0x00189044, "Quadrature Receive Coil", "CS"); add(0x00189045, "Multi-Coil Definition Sequence", "SQ"); add(0x00189046, "Multi-Coil Configuration", "LO"); add(0x00189047, "Multi-Coil Element Name", "SH"); add(0x00189048, "Multi-Coil Element Used", "CS"); add(0x00189049, "MR Transmit Coil Sequence", "SQ"); add(0x00189050, "Transmit Coil Manufacturer Name", "LO"); add(0x00189051, "Transmit Coil Type", "CS"); add(0x00189052, "Spectral Width", "FD"); add(0x00189053, "Chemical Shift Reference", "FD"); add(0x00189054, "Volume Localization Technique", "CS"); add(0x00189058, "MR Acquisition FrequencyEncoding Steps", "US"); add(0x00189059, "De-coupling", "CS"); add(0x00189060, "De-coupled Nucleus", "CS"); add(0x00189061, "De-coupling Frequency", "FD"); add(0x00189062, "De-coupling Method", "CS"); add(0x00189063, "De-coupling Chemical ShiftReference", "FD"); add(0x00189064, "k-space Filtering", "CS"); add(0x00189065, "Time Domain Filtering", "CS"); add(0x00189066, "Number of Zero Fills", "US"); add(0x00189067, "Baseline Correction", "CS"); add(0x00189069, "Parallel Reduction Factor In-plane", "FD"); add(0x00189070, "Cardiac R-R Interval Specified", "FD"); add(0x00189073, "Acquisition Duration", "FD"); add(0x00189074, "Frame Acquisition DateTime", "DT"); add(0x00189075, "Diffusion Directionality", "CS"); add(0x00189076, "Diffusion Gradient DirectionSequence", "SQ"); add(0x00189077, "Parallel Acquisition", "CS"); add(0x00189078, "Parallel Acquisition Technique", "CS"); add(0x00189079, "Inversion Times", "FD"); add(0x00189080, "Metabolite Map Description", "ST"); add(0x00189081, "Partial Fourier", "CS"); add(0x00189082, "Effective Echo Time", "FD"); add(0x00189083, "Metabolite Map Code Sequence", "SQ"); add(0x00189084, "Chemical Shift Sequence", "SQ"); add(0x00189085, "Cardiac Signal Source", "CS"); add(0x00189087, "Diffusion b-value", "FD"); add(0x00189089, "Diffusion Gradient Orientation", "FD"); add(0x00189090, "Velocity Encoding Direction", "FD"); add(0x00189091, "Velocity Encoding Minimum Value", "FD"); add(0x00189092, "Velocity Encoding AcquisitionSequence", "SQ"); add(0x00189093, "Number of k-Space Trajectories", "US"); add(0x00189094, "Coverage of k-Space", "CS"); add(0x00189095, "Spectroscopy Acquisition PhaseRows", "UL"); add(0x00189096, "Parallel Reduction Factor In-plane(Retired)", "FD"); // Retired add(0x00189098, "Transmitter Frequency", "FD"); add(0x00189100, "Resonant Nucleus", "CS"); add(0x00189101, "Frequency Correction", "CS"); add(0x00189103, "MR Spectroscopy FOV/GeometrySequence", "SQ"); add(0x00189104, "Slab Thickness", "FD"); add(0x00189105, "Slab Orientation", "FD"); add(0x00189106, "Mid Slab Position", "FD"); add(0x00189107, "MR Spatial Saturation Sequence", "SQ"); add(0x00189112, "MR Timing and RelatedParameters Sequence", "SQ"); add(0x00189114, "MR Echo Sequence", "SQ"); add(0x00189115, "MR Modifier Sequence", "SQ"); add(0x00189117, "MR Diffusion Sequence", "SQ"); add(0x00189118, "Cardiac Synchronization Sequence", "SQ"); add(0x00189119, "MR Averages Sequence", "SQ"); add(0x00189125, "MR FOV/Geometry Sequence", "SQ"); add(0x00189126, "Volume Localization Sequence", "SQ"); add(0x00189127, "Spectroscopy Acquisition DataColumns", "UL"); add(0x00189147, "Diffusion Anisotropy Type", "CS"); add(0x00189151, "Frame Reference DateTime", "DT"); add(0x00189152, "MR Metabolite Map Sequence", "SQ"); add(0x00189155, "Parallel Reduction Factorout-of-plane", "FD"); add(0x00189159, "Spectroscopy AcquisitionOut-of-plane Phase Steps", "UL"); add(0x00189166, "Bulk Motion Status", "CS"); // Retired add(0x00189168, "Parallel Reduction Factor SecondIn-plane", "FD"); add(0x00189169, "Cardiac Beat Rejection Technique", "CS"); add(0x00189170, "Respiratory Motion CompensationTechnique", "CS"); add(0x00189171, "Respiratory Signal Source", "CS"); add(0x00189172, "Bulk Motion CompensationTechnique", "CS"); add(0x00189173, "Bulk Motion Signal Source", "CS"); add(0x00189174, "Applicable Safety Standard Agency", "CS"); add(0x00189175, "Applicable Safety StandardDescription", "LO"); add(0x00189176, "Operating Mode Sequence", "SQ"); add(0x00189177, "Operating Mode Type", "CS"); add(0x00189178, "Operating Mode", "CS"); add(0x00189179, "Specific Absorption Rate Definition", "CS"); add(0x00189180, "Gradient Output Type", "CS"); add(0x00189181, "Specific Absorption Rate Value", "FD"); add(0x00189182, "Gradient Output", "FD"); add(0x00189183, "Flow Compensation Direction", "CS"); add(0x00189184, "Tagging Delay", "FD"); add(0x00189185, "Respiratory Motion CompensationTechnique Description", "ST"); add(0x00189186, "Respiratory Signal Source ID", "SH"); add(0x00189195, "Chemical Shift Minimum IntegrationLimit in Hz", "FD"); // Retired add(0x00189196, "Chemical Shift MaximumIntegration Limit in Hz", "FD"); // Retired add(0x00189197, "MR Velocity Encoding Sequence", "SQ"); add(0x00189198, "First Order Phase Correction", "CS"); add(0x00189199, "Water Referenced PhaseCorrection", "CS"); add(0x00189200, "MR Spectroscopy Acquisition Type", "CS"); add(0x00189214, "Respiratory Cycle Position", "CS"); add(0x00189217, "Velocity Encoding Maximum Value", "FD"); add(0x00189218, "Tag Spacing Second Dimension", "FD"); add(0x00189219, "Tag Angle Second Axis", "SS"); add(0x00189220, "Frame Acquisition Duration", "FD"); add(0x00189226, "MR Image Frame Type Sequence", "SQ"); add(0x00189227, "MR Spectroscopy Frame TypeSequence", "SQ"); add(0x00189231, "MR Acquisition Phase EncodingSteps in-plane", "US"); add(0x00189232, "MR Acquisition Phase EncodingSteps out-of-plane", "US"); add(0x00189234, "Spectroscopy Acquisition PhaseColumns", "UL"); add(0x00189236, "Cardiac Cycle Position", "CS"); add(0x00189239, "Specific Absorption Rate Sequence", "SQ"); add(0x00189240, "RF Echo Train Length", "US"); add(0x00189241, "Gradient Echo Train Length", "US"); add(0x00189250, "Arterial Spin Labeling Contrast", "CS"); add(0x00189251, "MR Arterial Spin LabelingSequence", "SQ"); add(0x00189252, "ASL Technique Description", "LO"); add(0x00189253, "ASL Slab Number", "US"); add(0x00189254, "ASL Slab Thickness", "FD"); add(0x00189255, "ASL Slab Orientation", "FD"); add(0x00189256, "ASL Mid Slab Position", "FD"); add(0x00189257, "ASL Context", "CS"); add(0x00189258, "ASL Pulse Train Duration", "UL"); add(0x00189259, "ASL Crusher Flag", "CS"); add(0x0018925A, "ASL Crusher Flow Limit", "FD"); add(0x0018925B, "ASL Crusher Description", "LO"); add(0x0018925C, "ASL Bolus Cut-off Flag", "CS"); add(0x0018925D, "ASL Bolus Cut-off TimingSequence", "SQ"); add(0x0018925E, "ASL Bolus Cut-off Technique", "LO"); add(0x0018925F, "ASL Bolus Cut-off Delay Time", "UL"); add(0x00189260, "ASL Slab Sequence", "SQ"); add(0x00189295, "Chemical Shift Minimum IntegrationLimit in ppm", "FD"); add(0x00189296, "Chemical Shift MaximumIntegration Limit in ppm", "FD"); add(0x00189297, "Water Reference Acquisition", "CS"); add(0x00189298, "Echo Peak Position", "IS"); add(0x00189301, "CT Acquisition Type Sequence", "SQ"); add(0x00189302, "Acquisition Type", "CS"); add(0x00189303, "Tube Angle", "FD"); add(0x00189304, "CT Acquisition Details Sequence", "SQ"); add(0x00189305, "Revolution Time", "FD"); add(0x00189306, "Single Collimation Width", "FD"); add(0x00189307, "Total Collimation Width", "FD"); add(0x00189308, "CT Table Dynamics Sequence", "SQ"); add(0x00189309, "Table Speed", "FD"); add(0x00189310, "Table Feed per Rotation", "FD"); add(0x00189311, "Spiral Pitch Factor", "FD"); add(0x00189312, "CT Geometry Sequence", "SQ"); add(0x00189313, "Data Collection Center (Patient)", "FD"); add(0x00189314, "CT Reconstruction Sequence", "SQ"); add(0x00189315, "Reconstruction Algorithm", "CS"); add(0x00189316, "Convolution Kernel Group", "CS"); add(0x00189317, "Reconstruction Field of View", "FD"); add(0x00189318, "Reconstruction Target Center(Patient)", "FD"); add(0x00189319, "Reconstruction Angle", "FD"); add(0x00189320, "Image Filter", "SH"); add(0x00189321, "CT Exposure Sequence", "SQ"); add(0x00189322, "Reconstruction Pixel Spacing", "FD"); add(0x00189323, "Exposure Modulation Type", "CS"); add(0x00189324, "Estimated Dose Saving", "FD"); add(0x00189325, "CT X-Ray Details Sequence", "SQ"); add(0x00189326, "CT Position Sequence", "SQ"); add(0x00189327, "Table Position", "FD"); add(0x00189328, "Exposure Time in ms", "FD"); add(0x00189329, "CT Image Frame Type Sequence", "SQ"); add(0x00189330, "X-Ray Tube Current in mA", "FD"); add(0x00189332, "Exposure in mAs", "FD"); add(0x00189333, "Constant Volume Flag", "CS"); add(0x00189334, "Fluoroscopy Flag", "CS"); add(0x00189335, "Distance Source to Data CollectionCenter", "FD"); add(0x00189337, "Contrast/Bolus Agent Number", "US"); add(0x00189338, "Contrast/Bolus Ingredient CodeSequence", "SQ"); add(0x00189340, "Contrast Administration ProfileSequence", "SQ"); add(0x00189341, "Contrast/Bolus Usage Sequence", "SQ"); add(0x00189342, "Contrast/Bolus Agent Administered", "CS"); add(0x00189343, "Contrast/Bolus Agent Detected", "CS"); add(0x00189344, "Contrast/Bolus Agent Phase", "CS"); add(0x00189345, "CTDIvol", "FD"); add(0x00189346, "CTDI Phantom Type CodeSequence", "SQ"); add(0x00189351, "Calcium Scoring Mass FactorPatient", "FL"); add(0x00189352, "Calcium Scoring Mass FactorDevice", "FL"); add(0x00189353, "Energy Weighting Factor", "FL"); add(0x00189360, "CT Additional X-Ray SourceSequence", "SQ"); add(0x00189401, "Projection Pixel CalibrationSequence", "SQ"); add(0x00189402, "Distance Source to Isocenter", "FL"); add(0x00189403, "Distance Object to Table Top", "FL"); add(0x00189404, "Object Pixel Spacing in Center ofBeam", "FL"); add(0x00189405, "Positioner Position Sequence", "SQ"); add(0x00189406, "Table Position Sequence", "SQ"); add(0x00189407, "Collimator Shape Sequence", "SQ"); add(0x00189410, "Planes in Acquisition", "CS"); add(0x00189412, "XA/XRF Frame CharacteristicsSequence", "SQ"); add(0x00189417, "Frame Acquisition Sequence", "SQ"); add(0x00189420, "X-Ray Receptor Type", "CS"); add(0x00189423, "Acquisition Protocol Name", "LO"); add(0x00189424, "Acquisition Protocol Description", "LT"); add(0x00189425, "Contrast/Bolus Ingredient Opaque", "CS"); add(0x00189426, "Distance Receptor Plane toDetector Housing", "FL"); add(0x00189427, "Intensifier Active Shape", "CS"); add(0x00189428, "Intensifier Active Dimension(s)", "FL"); add(0x00189429, "Physical Detector Size", "FL"); add(0x00189430, "Position of Isocenter Projection", "FL"); add(0x00189432, "Field of View Sequence", "SQ"); add(0x00189433, "Field of View Description", "LO"); add(0x00189434, "Exposure Control Sensing RegionsSequence", "SQ"); add(0x00189435, "Exposure Control Sensing RegionShape", "CS"); add(0x00189436, "Exposure Control Sensing RegionLeft Vertical Edge", "SS"); add(0x00189437, "Exposure Control Sensing RegionRight Vertical Edge", "SS"); add(0x00189438, "Exposure Control Sensing RegionUpper Horizontal Edge", "SS"); add(0x00189439, "Exposure Control Sensing RegionLower Horizontal Edge", "SS"); add(0x00189440, "Center of Circular ExposureControl Sensing Region", "SS"); add(0x00189441, "Radius of Circular ExposureControl Sensing Region", "US"); add(0x00189442, "Vertices of the Polygonal ExposureControl Sensing Region", "SS"); add(0x00189445, "Column Angulation (Patient)", "FL"); add(0x00189449, "Beam Angle", "FL"); add(0x00189451, "Frame Detector ParametersSequence", "SQ"); add(0x00189452, "Calculated Anatomy Thickness", "FL"); add(0x00189455, "Calibration Sequence", "SQ"); add(0x00189456, "Object Thickness Sequence", "SQ"); add(0x00189457, "Plane Identification", "CS"); add(0x00189461, "Field of View Dimension(s) in Float", "FL"); add(0x00189462, "Isocenter Reference SystemSequence", "SQ"); add(0x00189463, "Positioner Isocenter Primary Angle", "FL"); add(0x00189464, "Positioner Isocenter SecondaryAngle", "FL"); add(0x00189465, "Positioner Isocenter DetectorRotation Angle", "FL"); add(0x00189466, "Table X Position to Isocenter", "FL"); add(0x00189467, "Table Y Position to Isocenter", "FL"); add(0x00189468, "Table Z Position to Isocenter", "FL"); add(0x00189469, "Table Horizontal Rotation Angle", "FL"); add(0x00189470, "Table Head Tilt Angle", "FL"); add(0x00189471, "Table Cradle Tilt Angle", "FL"); add(0x00189472, "Frame Display Shutter Sequence", "SQ"); add(0x00189473, "Acquired Image Area Dose Product", "FL"); add(0x00189474, "C-arm Positioner TabletopRelationship", "CS"); add(0x00189476, "X-Ray Geometry Sequence", "SQ"); add(0x00189477, "Irradiation Event IdentificationSequence", "SQ"); add(0x00189504, "X-Ray 3D Frame Type Sequence", "SQ"); add(0x00189506, "Contributing Sources Sequence", "SQ"); add(0x00189507, "X-Ray 3D Acquisition Sequence", "SQ"); add(0x00189508, "Primary Positioner Scan Arc", "FL"); add(0x00189509, "Secondary Positioner Scan Arc", "FL"); add(0x00189510, "Primary Positioner Scan StartAngle", "FL"); add(0x00189511, "Secondary Positioner Scan StartAngle", "FL"); add(0x00189514, "Primary Positioner Increment", "FL"); add(0x00189515, "Secondary Positioner Increment", "FL"); add(0x00189516, "Start Acquisition DateTime", "DT"); add(0x00189517, "End Acquisition DateTime", "DT"); add(0x00189518, "Primary Positioner Increment Sign", "SS"); add(0x00189519, "Secondary Positioner IncrementSign", "SS"); add(0x00189524, "Application Name", "LO"); add(0x00189525, "Application Version", "LO"); add(0x00189526, "Application Manufacturer", "LO"); add(0x00189527, "Algorithm Type", "CS"); add(0x00189528, "Algorithm Description", "LO"); add(0x00189530, "X-Ray 3D ReconstructionSequence", "SQ"); add(0x00189531, "Reconstruction Description", "LO"); add(0x00189538, "Per Projection AcquisitionSequence", "SQ"); add(0x00189541, "Detector Position Sequence", "SQ"); add(0x00189542, "X-Ray Acquisition Dose Sequence", "SQ"); add(0x00189543, "X-Ray Source Isocenter PrimaryAngle", "FD"); add(0x00189544, "X-Ray Source Isocenter SecondaryAngle", "FD"); add(0x00189545, "Breast Support Isocenter PrimaryAngle", "FD"); add(0x00189546, "Breast Support IsocenterSecondary Angle", "FD"); add(0x00189547, "Breast Support X Position toIsocenter", "FD"); add(0x00189548, "Breast Support Y Position toIsocenter", "FD"); add(0x00189549, "Breast Support Z Position toIsocenter", "FD"); add(0x00189550, "Detector Isocenter Primary Angle", "FD"); add(0x00189551, "Detector Isocenter SecondaryAngle", "FD"); add(0x00189552, "Detector X Position to Isocenter", "FD"); add(0x00189553, "Detector Y Position to Isocenter", "FD"); add(0x00189554, "Detector Z Position to Isocenter", "FD"); add(0x00189555, "X-Ray Grid Sequence", "SQ"); add(0x00189556, "X-Ray Filter Sequence", "SQ"); add(0x00189557, "Detector Active Area TLHCPosition", "FD"); add(0x00189558, "Detector Active Area Orientation", "FD"); add(0x00189559, "Positioner Primary Angle Direction", "CS"); add(0x00189601, "Diffusion b-matrix Sequence", "SQ"); add(0x00189602, "Diffusion b-value XX", "FD"); add(0x00189603, "Diffusion b-value XY", "FD"); add(0x00189604, "Diffusion b-value XZ", "FD"); add(0x00189605, "Diffusion b-value YY", "FD"); add(0x00189606, "Diffusion b-value YZ", "FD"); add(0x00189607, "Diffusion b-value ZZ", "FD"); add(0x00189701, "Decay Correction DateTime", "DT"); add(0x00189715, "Start Density Threshold", "FD"); add(0x00189716, "Start Relative Density DifferenceThreshold", "FD"); add(0x00189717, "Start Cardiac Trigger CountThreshold", "FD"); add(0x00189718, "Start Respiratory Trigger CountThreshold", "FD"); add(0x00189719, "Termination Counts Threshold", "FD"); add(0x00189720, "Termination Density Threshold", "FD"); add(0x00189721, "Termination Relative DensityThreshold", "FD"); add(0x00189722, "Termination Time Threshold", "FD"); add(0x00189723, "Termination Cardiac Trigger CountThreshold", "FD"); add(0x00189724, "Termination Respiratory TriggerCount Threshold", "FD"); add(0x00189725, "Detector Geometry", "CS"); add(0x00189726, "Transverse Detector Separation", "FD"); add(0x00189727, "Axial Detector Dimension", "FD"); add(0x00189729, "Radiopharmaceutical AgentNumber", "US"); add(0x00189732, "PET Frame Acquisition Sequence", "SQ"); add(0x00189733, "PET Detector Motion DetailsSequence", "SQ"); add(0x00189734, "PET Table Dynamics Sequence", "SQ"); add(0x00189735, "PET Position Sequence", "SQ"); add(0x00189736, "PET Frame Correction FactorsSequence", "SQ"); add(0x00189737, "Radiopharmaceutical UsageSequence", "SQ"); add(0x00189738, "Attenuation Correction Source", "CS"); add(0x00189739, "Number of Iterations", "US"); add(0x00189740, "Number of Subsets", "US"); add(0x00189749, "PET Reconstruction Sequence", "SQ"); add(0x00189751, "PET Frame Type Sequence", "SQ"); add(0x00189755, "Time of Flight Information Used", "CS"); add(0x00189756, "Reconstruction Type", "CS"); add(0x00189758, "Decay Corrected", "CS"); add(0x00189759, "Attenuation Corrected", "CS"); add(0x00189760, "Scatter Corrected", "CS"); add(0x00189761, "Dead Time Corrected", "CS"); add(0x00189762, "Gantry Motion Corrected", "CS"); add(0x00189763, "Patient Motion Corrected", "CS"); add(0x00189764, "Count Loss NormalizationCorrected", "CS"); add(0x00189765, "Randoms Corrected", "CS"); add(0x00189766, "Non-uniform Radial SamplingCorrected", "CS"); add(0x00189767, "Sensitivity Calibrated", "CS"); add(0x00189768, "Detector Normalization Correction", "CS"); add(0x00189769, "Iterative Reconstruction Method", "CS"); add(0x00189770, "Attenuation Correction TemporalRelationship", "CS"); add(0x00189771, "Patient Physiological StateSequence", "SQ"); add(0x00189772, "Patient Physiological State CodeSequence", "SQ"); add(0x00189801, "Depth(s) of Focus", "FD"); add(0x00189803, "Excluded Intervals Sequence", "SQ"); add(0x00189804, "Exclusion Start DateTime", "DT"); add(0x00189805, "Exclusion Duration", "FD"); add(0x00189806, "US Image Description Sequence", "SQ"); add(0x00189807, "Image Data Type Sequence", "SQ"); add(0x00189808, "Data Type", "CS"); add(0x00189809, "Transducer Scan Pattern CodeSequence", "SQ"); add(0x0018980B, "Aliased Data Type", "CS"); add(0x0018980C, "Position Measuring Device Used", "CS"); add(0x0018980D, "Transducer Geometry CodeSequence", "SQ"); add(0x0018980E, "Transducer Beam Steering CodeSequence", "SQ"); add(0x0018980F, "Transducer Application CodeSequence", "SQ"); // add(0x00189810, "Zero Velocity Pixel Value", "US or SS"); add(0x0018A001, "Contributing Equipment Sequence", "SQ"); add(0x0018A002, "Contribution DateTime", "DT"); add(0x0018A003, "Contribution Description", "ST"); } /** * Adds attributes of group 0x0020. */ private void addAttributeGroup0020() { add(0x0020000D, "Study Instance UID", "UI"); add(0x0020000E, "Series Instance UID", "UI"); add(0x00200010, "Study ID", "SH"); add(0x00200011, "Series Number", "IS"); add(0x00200012, "Acquisition Number", "IS"); add(0x00200013, "Instance Number", "IS"); add(0x00200014, "Isotope Number", "IS"); // Retired add(0x00200015, "Phase Number", "IS"); // Retired add(0x00200016, "Interval Number", "IS"); // Retired add(0x00200017, "Time Slot Number", "IS"); // Retired add(0x00200018, "Angle Number", "IS"); // Retired add(0x00200019, "Item Number", "IS"); add(0x00200020, "Patient Orientation", "CS"); add(0x00200022, "Overlay Number", "IS"); // Retired add(0x00200024, "Curve Number", "IS"); // Retired add(0x00200026, "LUT Number", "IS"); // Retired add(0x00200030, "Image Position", "DS"); // Retired add(0x00200032, "Image Position (Patient)", "DS"); add(0x00200035, "Image Orientation", "DS"); // Retired add(0x00200037, "Image Orientation (Patient)", "DS"); add(0x00200050, "Location", "DS"); // Retired add(0x00200052, "Frame of Reference UID", "UI"); add(0x00200060, "Laterality", "CS"); add(0x00200062, "Image Laterality", "CS"); add(0x00200070, "Image Geometry Type", "LO"); // Retired add(0x00200080, "Masking Image", "CS"); // Retired add(0x002000AA, "Report Number", "IS"); // Retired add(0x00200100, "Temporal Position Identifier", "IS"); add(0x00200105, "Number of Temporal Positions", "IS"); add(0x00200110, "Temporal Resolution", "DS"); add(0x00200200, "Synchronization Frame ofReference UID", "UI"); add(0x00200242, "SOP Instance UID ofConcatenation Source", "UI"); add(0x00201000, "Series in Study", "IS"); // Retired add(0x00201001, "Acquisitions in Series", "IS"); // Retired add(0x00201002, "Images in Acquisition", "IS"); add(0x00201003, "Images in Series", "IS"); // Retired add(0x00201004, "Acquisitions in Study", "IS"); // Retired add(0x00201005, "Images in Study", "IS"); // Retired add(0x00201020, "Reference", "LO"); // Retired add(0x00201040, "Position Reference Indicator", "LO"); add(0x00201041, "Slice Location", "DS"); add(0x00201070, "Other Study Numbers", "IS"); // Retired add(0x00201200, "Number of Patient Related Studies", "IS"); add(0x00201202, "Number of Patient Related Series", "IS"); add(0x00201204, "Number of Patient RelatedInstances", "IS"); add(0x00201206, "Number of Study Related Series", "IS"); add(0x00201208, "Number of Study Related Instances", "IS"); add(0x00201209, "Number of Series RelatedInstances", "IS"); add(0x00203401, "Modifying Device ID", "CS"); // Retired add(0x00203402, "Modified Image ID", "CS"); // Retired add(0x00203403, "Modified Image Date", "DA"); // Retired add(0x00203404, "Modifying Device Manufacturer", "LO"); // Retired add(0x00203405, "Modified Image Time", "TM"); // Retired add(0x00203406, "Modified Image Description", "LO"); // Retired add(0x00204000, "Image Comments", "LT"); add(0x00205000, "Original Image Identification", "AT"); // Retired add(0x00205002, "Original Image IdentificationNomenclature", "LO"); // Retired add(0x00209056, "Stack ID", "SH"); add(0x00209057, "In-Stack Position Number", "UL"); add(0x00209071, "Frame Anatomy Sequence", "SQ"); add(0x00209072, "Frame Laterality", "CS"); add(0x00209111, "Frame Content Sequence", "SQ"); add(0x00209113, "Plane Position Sequence", "SQ"); add(0x00209116, "Plane Orientation Sequence", "SQ"); add(0x00209128, "Temporal Position Index", "UL"); add(0x00209153, "Nominal Cardiac Trigger DelayTime", "FD"); add(0x00209154, "Nominal Cardiac Trigger Time PriorTo R-Peak", "FL"); add(0x00209155, "Actual Cardiac Trigger Time PriorTo R-Peak", "FL"); add(0x00209156, "Frame Acquisition Number", "US"); add(0x00209157, "Dimension Index Values", "UL"); add(0x00209158, "Frame Comments", "LT"); add(0x00209161, "Concatenation UID", "UI"); add(0x00209162, "In-concatenation Number", "US"); add(0x00209163, "In-concatenation Total Number", "US"); add(0x00209164, "Dimension Organization UID", "UI"); add(0x00209165, "Dimension Index Pointer", "AT"); add(0x00209167, "Functional Group Pointer", "AT"); add(0x00209170, "Unassigned Shared ConvertedAttributes Sequence", "SQ"); add(0x00209171, "Unassigned Per-Frame ConvertedAttributes Sequence", "SQ"); add(0x00209172, "Conversion Source AttributesSequence", "SQ"); add(0x00209213, "Dimension Index Private Creator", "LO"); add(0x00209221, "Dimension Organization Sequence", "SQ"); add(0x00209222, "Dimension Index Sequence", "SQ"); add(0x00209228, "Concatenation Frame OffsetNumber", "UL"); add(0x00209238, "Functional Group Private Creator", "LO"); add(0x00209241, "Nominal Percentage of CardiacPhase", "FL"); add(0x00209245, "Nominal Percentage of RespiratoryPhase", "FL"); add(0x00209246, "Starting Respiratory Amplitude", "FL"); add(0x00209247, "Starting Respiratory Phase", "CS"); add(0x00209248, "Ending Respiratory Amplitude", "FL"); add(0x00209249, "Ending Respiratory Phase", "CS"); add(0x00209250, "Respiratory Trigger Type", "CS"); add(0x00209251, "R-R Interval Time Nominal", "FD"); add(0x00209252, "Actual Cardiac Trigger Delay Time", "FD"); add(0x00209253, "Respiratory SynchronizationSequence", "SQ"); add(0x00209254, "Respiratory Interval Time", "FD"); add(0x00209255, "Nominal Respiratory Trigger DelayTime", "FD"); add(0x00209256, "Respiratory Trigger DelayThreshold", "FD"); add(0x00209257, "Actual Respiratory Trigger DelayTime", "FD"); add(0x00209301, "Image Position (Volume)", "FD"); add(0x00209302, "Image Orientation (Volume)", "FD"); add(0x00209307, "Ultrasound Acquisition Geometry", "CS"); add(0x00209308, "Apex Position", "FD"); add(0x00209309, "Volume to Transducer MappingMatrix", "FD"); add(0x0020930A, "Volume to Table Mapping Matrix", "FD"); add(0x0020930B, "Volume to Transducer Relationship", "CS"); add(0x0020930C, "Patient Frame of Reference Source", "CS"); add(0x0020930D, "Temporal Position Time Offset", "FD"); add(0x0020930E, "Plane Position (Volume) Sequence", "SQ"); add(0x0020930F, "Plane Orientation (Volume) Sequence", "SQ"); add(0x00209310, "Temporal Position Sequence", "SQ"); add(0x00209311, "Dimension Organization Type", "CS"); add(0x00209312, "Volume Frame of Reference UID", "UI"); add(0x00209313, "Table Frame of Reference UID", "UI"); add(0x00209421, "Dimension Description Label", "LO"); add(0x00209450, "Patient Orientation in FrameSequence", "SQ"); add(0x00209453, "Frame Label", "LO"); add(0x00209518, "Acquisition Index", "US"); add(0x00209529, "Contributing SOP InstancesReference Sequence", "SQ"); add(0x00209536, "Reconstruction Index", "US"); } /** * Adds attributes of group 0x0022. */ private void addAttributeGroup0022() { add(0x00220001, "Light Path Filter Pass-ThroughWavelength", "US"); add(0x00220002, "Light Path Filter Pass Band", "US"); add(0x00220003, "Image Path Filter Pass-ThroughWavelength", "US"); add(0x00220004, "Image Path Filter Pass Band", "US"); add(0x00220005, "Patient Eye MovementCommanded", "CS"); add(0x00220006, "Patient Eye Movement CommandCode Sequence", "SQ"); add(0x00220007, "Spherical Lens Power", "FL"); add(0x00220008, "Cylinder Lens Power", "FL"); add(0x00220009, "Cylinder Axis", "FL"); add(0x0022000A, "Emmetropic Magnification", "FL"); add(0x0022000B, "Intra Ocular Pressure", "FL"); add(0x0022000C, "Horizontal Field of View", "FL"); add(0x0022000D, "Pupil Dilated", "CS"); add(0x0022000E, "Degree of Dilation", "FL"); add(0x00220010, "Stereo Baseline Angle", "FL"); add(0x00220011, "Stereo Baseline Displacement", "FL"); add(0x00220012, "Stereo Horizontal Pixel Offset", "FL"); add(0x00220013, "Stereo Vertical Pixel Offset", "FL"); add(0x00220014, "Stereo Rotation", "FL"); add(0x00220015, "Acquisition Device Type CodeSequence", "SQ"); add(0x00220016, "Illumination Type Code Sequence", "SQ"); add(0x00220017, "Light Path Filter Type Stack CodeSequence", "SQ"); add(0x00220018, "Image Path Filter Type Stack CodeSequence", "SQ"); add(0x00220019, "Lenses Code Sequence", "SQ"); add(0x0022001A, "Channel Description CodeSequence", "SQ"); add(0x0022001B, "Refractive State Sequence", "SQ"); add(0x0022001C, "Mydriatic Agent Code Sequence", "SQ"); add(0x0022001D, "Relative Image Position CodeSequence", "SQ"); add(0x0022001E, "Camera Angle of View", "FL"); add(0x00220020, "Stereo Pairs Sequence", "SQ"); add(0x00220021, "Left Image Sequence", "SQ"); add(0x00220022, "Right Image Sequence", "SQ"); add(0x00220028, "Stereo Pairs Present", "CS"); add(0x00220030, "Axial Length of the Eye", "FL"); add(0x00220031, "Ophthalmic Frame LocationSequence", "SQ"); add(0x00220032, "Reference Coordinates", "FL"); add(0x00220035, "Depth Spatial Resolution", "FL"); add(0x00220036, "Maximum Depth Distortion", "FL"); add(0x00220037, "Along-scan Spatial Resolution", "FL"); add(0x00220038, "Maximum Along-scan Distortion", "FL"); add(0x00220039, "Ophthalmic Image Orientation", "CS"); add(0x00220041, "Depth of Transverse Image", "FL"); add(0x00220042, "Mydriatic Agent ConcentrationUnits Sequence", "SQ"); add(0x00220048, "Across-scan Spatial Resolution", "FL"); add(0x00220049, "Maximum Across-scan Distortion", "FL"); add(0x0022004E, "Mydriatic Agent Concentration", "DS"); add(0x00220055, "Illumination Wave Length", "FL"); add(0x00220056, "Illumination Power", "FL"); add(0x00220057, "Illumination Bandwidth", "FL"); add(0x00220058, "Mydriatic Agent Sequence", "SQ"); add(0x00221007, "Ophthalmic Axial MeasurementsRight Eye Sequence", "SQ"); add(0x00221008, "Ophthalmic Axial MeasurementsLeft Eye Sequence", "SQ"); add(0x00221009, "Ophthalmic Axial MeasurementsDevice Type", "CS"); add(0x00221010, "Ophthalmic Axial LengthMeasurements Type", "CS"); add(0x00221012, "Ophthalmic Axial Length Sequence", "SQ"); add(0x00221019, "Ophthalmic Axial Length", "FL"); add(0x00221024, "Lens Status Code Sequence", "SQ"); add(0x00221025, "Vitreous Status Code Sequence", "SQ"); add(0x00221028, "IOL Formula Code Sequence", "SQ"); add(0x00221029, "IOL Formula Detail", "LO"); add(0x00221033, "Keratometer Index", "FL"); add(0x00221035, "Source of Ophthalmic Axial LengthCode Sequence", "SQ"); add(0x00221037, "Target Refraction", "FL"); add(0x00221039, "Refractive Procedure Occurred", "CS"); add(0x00221040, "Refractive Surgery Type CodeSequence", "SQ"); add(0x00221044, "Ophthalmic Ultrasound MethodCode Sequence", "SQ"); add(0x00221050, "Ophthalmic Axial LengthMeasurements Sequence", "SQ"); add(0x00221053, "IOL Power", "FL"); add(0x00221054, "Predicted Refractive Error", "FL"); add(0x00221059, "Ophthalmic Axial Length Velocity", "FL"); add(0x00221065, "Lens Status Description", "LO"); add(0x00221066, "Vitreous Status Description", "LO"); add(0x00221090, "IOL Power Sequence", "SQ"); add(0x00221092, "Lens Constant Sequence", "SQ"); add(0x00221093, "IOL Manufacturer", "LO"); add(0x00221094, "Lens Constant Description", "LO"); // Retired add(0x00221095, "Implant Name", "LO"); add(0x00221096, "Keratometry Measurement TypeCode Sequence", "SQ"); add(0x00221097, "Implant Part Number", "LO"); add(0x00221100, "Referenced Ophthalmic AxialMeasurements Sequence", "SQ"); add(0x00221101, "Ophthalmic Axial LengthMeasurements Segment NameCode Sequence", "SQ"); add(0x00221103, "Refractive Error Before RefractiveSurgery Code Sequence", "SQ"); add(0x00221121, "IOL Power For Exact Emmetropia", "FL"); add(0x00221122, "IOL Power For Exact TargetRefraction", "FL"); add(0x00221125, "Anterior Chamber Depth DefinitionCode Sequence", "SQ"); add(0x00221127, "Lens Thickness Sequence", "SQ"); add(0x00221128, "Anterior Chamber Depth Sequence", "SQ"); add(0x00221130, "Lens Thickness", "FL"); add(0x00221131, "Anterior Chamber Depth", "FL"); add(0x00221132, "Source of Lens Thickness DataCode Sequence", "SQ"); add(0x00221133, "Source of Anterior Chamber DepthData Code Sequence", "SQ"); add(0x00221134, "Source of RefractiveMeasurements Sequence", "SQ"); add(0x00221135, "Source of RefractiveMeasurements Code Sequence", "SQ"); add(0x00221140, "Ophthalmic Axial LengthMeasurement Modified", "CS"); add(0x00221150, "Ophthalmic Axial Length DataSource Code Sequence", "SQ"); add(0x00221153, "Ophthalmic Axial LengthAcquisition Method CodeSequence", "SQ"); // Retired add(0x00221155, "Signal to Noise Ratio", "FL"); add(0x00221159, "Ophthalmic Axial Length DataSource Description", "LO"); add(0x00221210, "Ophthalmic Axial LengthMeasurements Total LengthSequence", "SQ"); add(0x00221211, "Ophthalmic Axial LengthMeasurements Segmental LengthSequence", "SQ"); add(0x00221212, "Ophthalmic Axial LengthMeasurements Length SummationSequence", "SQ"); add(0x00221220, "Ultrasound Ophthalmic AxialLength Measurements Sequence", "SQ"); add(0x00221225, "Optical Ophthalmic Axial LengthMeasurements Sequence", "SQ"); add(0x00221230, "Ultrasound Selected OphthalmicAxial Length Sequence", "SQ"); add(0x00221250, "Ophthalmic Axial Length SelectionMethod Code Sequence", "SQ"); add(0x00221255, "Optical Selected Ophthalmic AxialLength Sequence", "SQ"); add(0x00221257, "Selected Segmental OphthalmicAxial Length Sequence", "SQ"); add(0x00221260, "Selected Total Ophthalmic AxialLength Sequence", "SQ"); add(0x00221262, "Ophthalmic Axial Length QualityMetric Sequence", "SQ"); add(0x00221265, "Ophthalmic Axial Length QualityMetric Type Code Sequence", "SQ"); // Retired add(0x00221273, "Ophthalmic Axial Length QualityMetric Type Description", "LO"); // Retired add(0x00221300, "Intraocular Lens Calculations RightEye Sequence", "SQ"); add(0x00221310, "Intraocular Lens Calculations LeftEye Sequence", "SQ"); add(0x00221330, "Referenced Ophthalmic AxialLength Measurement QC ImageSequence", "SQ"); add(0x00221415, "Ophthalmic Mapping Device Type", "CS"); add(0x00221420, "Acquisition Method CodeSequence", "SQ"); add(0x00221423, "Acquisition Method AlgorithmSequence", "SQ"); add(0x00221436, "Ophthalmic Thickness Map TypeCode Sequence", "SQ"); add(0x00221443, "Ophthalmic Thickness MappingNormals Sequence", "SQ"); add(0x00221445, "Retinal Thickness Definition CodeSequence", "SQ"); add(0x00221450, "Pixel Value Mapping to CodedConcept Sequence", "SQ"); // add(0x00221452, "Mapped Pixel Value", "US or SS"); add(0x00221454, "Pixel Value Mapping Explanation", "LO"); add(0x00221458, "Ophthalmic Thickness Map QualityThreshold Sequence", "SQ"); add(0x00221460, "Ophthalmic Thickness MapThreshold Quality Rating", "FL"); add(0x00221463, "Anatomic Structure ReferencePoint", "FL"); add(0x00221465, "Registration to Localizer Sequence", "SQ"); add(0x00221466, "Registered Localizer Units", "CS"); add(0x00221467, "Registered Localizer Top Left HandCorner", "FL"); add(0x00221468, "Registered Localizer Bottom RightHand Corner", "FL"); add(0x00221470, "Ophthalmic Thickness Map QualityRating Sequence", "SQ"); add(0x00221472, "Relevant OPT Attributes Sequence", "SQ"); add(0x00221512, "Transformation Method CodeSequence", "SQ"); add(0x00221513, "Transformation AlgorithmSequence", "SQ"); add(0x00221515, "Ophthalmic Axial Length Method", "CS"); add(0x00221517, "Ophthalmic FOV", "FL"); add(0x00221518, "Two Dimensional to ThreeDimensional Map Sequence", "SQ"); add(0x00221525, "Wide Field OphthalmicPhotography Quality RatingSequence", "SQ"); add(0x00221526, "Wide Field OphthalmicPhotography Quality ThresholdSequence", "SQ"); add(0x00221527, "Wide Field OphthalmicPhotography Threshold QualityRating", "FL"); add(0x00221528, "X Coordinates Center Pixel ViewAngle", "FL"); add(0x00221529, "Y Coordinates Center Pixel ViewAngle", "FL"); add(0x00221530, "Number of Map Points", "UL"); add(0x00221531, "Two Dimensional to ThreeDimensional Map Data", "OF"); } /** * Adds attributes of group 0x0024. */ private void addAttributeGroup0024() { add(0x00240010, "Visual Field Horizontal Extent", "FL"); add(0x00240011, "Visual Field Vertical Extent", "FL"); add(0x00240012, "Visual Field Shape", "CS"); add(0x00240016, "Screening Test Mode CodeSequence", "SQ"); add(0x00240018, "Maximum Stimulus Luminance", "FL"); add(0x00240020, "Background Luminance", "FL"); add(0x00240021, "Stimulus Color Code Sequence", "SQ"); add(0x00240024, "Background Illumination ColorCode Sequence", "SQ"); add(0x00240025, "Stimulus Area", "FL"); add(0x00240028, "Stimulus Presentation Time", "FL"); add(0x00240032, "Fixation Sequence", "SQ"); add(0x00240033, "Fixation Monitoring CodeSequence", "SQ"); add(0x00240034, "Visual Field Catch Trial Sequence", "SQ"); add(0x00240035, "Fixation Checked Quantity", "US"); add(0x00240036, "Patient Not Properly FixatedQuantity", "US"); add(0x00240037, "Presented Visual Stimuli Data Flag", "CS"); add(0x00240038, "Number of Visual Stimuli", "US"); add(0x00240039, "Excessive Fixation Losses DataFlag", "CS"); add(0x00240040, "Excessive Fixation Losses", "CS"); add(0x00240042, "Stimuli Retesting Quantity", "US"); add(0x00240044, "Comments on Patient'sPerformance of Visual Field", "LT"); add(0x00240045, "False Negatives Estimate Flag", "CS"); add(0x00240046, "False Negatives Estimate", "FL"); add(0x00240048, "Negative Catch Trials Quantity", "US"); add(0x00240050, "False Negatives Quantity", "US"); add(0x00240051, "Excessive False Negatives DataFlag", "CS"); add(0x00240052, "Excessive False Negatives", "CS"); add(0x00240053, "False Positives Estimate Flag", "CS"); add(0x00240054, "False Positives Estimate", "FL"); add(0x00240055, "Catch Trials Data Flag", "CS"); add(0x00240056, "Positive Catch Trials Quantity", "US"); add(0x00240057, "Test Point Normals Data Flag", "CS"); add(0x00240058, "Test Point Normals Sequence", "SQ"); add(0x00240059, "Global Deviation ProbabilityNormals Flag", "CS"); add(0x00240060, "False Positives Quantity", "US"); add(0x00240061, "Excessive False Positives DataFlag", "CS"); add(0x00240062, "Excessive False Positives", "CS"); add(0x00240063, "Visual Field Test Normals Flag", "CS"); add(0x00240064, "Results Normals Sequence", "SQ"); add(0x00240065, "Age Corrected Sensitivity DeviationAlgorithm Sequence", "SQ"); add(0x00240066, "Global Deviation From Normal", "FL"); add(0x00240067, "Generalized Defect SensitivityDeviation Algorithm Sequence", "SQ"); add(0x00240068, "Localized Deviation From Normal", "FL"); add(0x00240069, "Patient Reliability Indicator", "LO"); add(0x00240070, "Visual Field Mean Sensitivity", "FL"); add(0x00240071, "Global Deviation Probability", "FL"); add(0x00240072, "Local Deviation Probability NormalsFlag", "CS"); add(0x00240073, "Localized Deviation Probability", "FL"); add(0x00240074, "Short Term Fluctuation Calculated", "CS"); add(0x00240075, "Short Term Fluctuation", "FL"); add(0x00240076, "Short Term Fluctuation ProbabilityCalculated", "CS"); add(0x00240077, "Short Term Fluctuation Probability", "FL"); add(0x00240078, "Corrected Localized DeviationFrom Normal Calculated", "CS"); add(0x00240079, "Corrected Localized DeviationFrom Normal", "FL"); add(0x00240080, "Corrected Localized DeviationFrom Normal Probability Calculated", "CS"); add(0x00240081, "Corrected Localized DeviationFrom Normal Probability", "FL"); add(0x00240083, "Global Deviation ProbabilitySequence", "SQ"); add(0x00240085, "Localized Deviation ProbabilitySequence", "SQ"); add(0x00240086, "Foveal Sensitivity Measured", "CS"); add(0x00240087, "Foveal Sensitivity", "FL"); add(0x00240088, "Visual Field Test Duration", "FL"); add(0x00240089, "Visual Field Test Point Sequence", "SQ"); add(0x00240090, "Visual Field Test PointX-Coordinate", "FL"); add(0x00240091, "Visual Field Test PointY-Coordinate", "FL"); add(0x00240092, "Age Corrected Sensitivity DeviationValue", "FL"); add(0x00240093, "Stimulus Results", "CS"); add(0x00240094, "Sensitivity Value", "FL"); add(0x00240095, "Retest Stimulus Seen", "CS"); add(0x00240096, "Retest Sensitivity Value", "FL"); add(0x00240097, "Visual Field Test Point NormalsSequence", "SQ"); add(0x00240098, "Quantified Defect", "FL"); add(0x00240100, "Age Corrected Sensitivity DeviationProbability Value", "FL"); add(0x00240102, "Generalized Defect CorrectedSensitivity Deviation Flag", "CS"); add(0x00240103, "Generalized Defect CorrectedSensitivity Deviation Value", "FL"); add(0x00240104, "Generalized Defect CorrectedSensitivity Deviation ProbabilityValue", "FL"); add(0x00240105, "Minimum Sensitivity Value", "FL"); add(0x00240106, "Blind Spot Localized", "CS"); add(0x00240107, "Blind Spot X-Coordinate", "FL"); add(0x00240108, "Blind Spot Y-Coordinate", "FL"); add(0x00240110, "Visual Acuity MeasurementSequence", "SQ"); add(0x00240112, "Refractive Parameters Used onPatient Sequence", "SQ"); add(0x00240113, "Measurement Laterality", "CS"); add(0x00240114, "Ophthalmic Patient ClinicalInformation Left Eye Sequence", "SQ"); add(0x00240115, "Ophthalmic Patient ClinicalInformation Right Eye Sequence", "SQ"); add(0x00240117, "Foveal Point Normative Data Flag", "CS"); add(0x00240118, "Foveal Point Probability Value", "FL"); add(0x00240120, "Screening Baseline Measured", "CS"); add(0x00240122, "Screening Baseline MeasuredSequence", "SQ"); add(0x00240124, "Screening Baseline Type", "CS"); add(0x00240126, "Screening Baseline Value", "FL"); add(0x00240202, "Algorithm Source", "LO"); add(0x00240306, "Data Set Name", "LO"); add(0x00240307, "Data Set Version", "LO"); add(0x00240308, "Data Set Source", "LO"); add(0x00240309, "Data Set Description", "LO"); add(0x00240317, "Visual Field Test Reliability GlobalIndex Sequence", "SQ"); add(0x00240320, "Visual Field Global Results IndexSequence", "SQ"); add(0x00240325, "Data Observation Sequence", "SQ"); add(0x00240338, "Index Normals Flag", "CS"); add(0x00240341, "Index Probability", "FL"); add(0x00240344, "Index Probability Sequence", "SQ"); } /** * Adds attributes of group 0x0028. */ private void addAttributeGroup0028() { add(0x00280002, "Samples per Pixel", "US"); add(0x00280003, "Samples per Pixel Used", "US"); add(0x00280004, "Photometric Interpretation", "CS"); add(0x00280005, "Image Dimensions", "US"); // Retired add(0x00280006, "Planar Configuration", "US"); add(0x00280008, "Number of Frames", "IS"); add(0x00280009, "Frame Increment Pointer", "AT"); add(0x0028000A, "Frame Dimension Pointer", "AT"); add(0x00280010, "Rows", "US"); add(0x00280011, "Columns", "US"); add(0x00280012, "Planes", "US"); // Retired add(0x00280014, "Ultrasound Color Data Present", "US"); add(0x00280030, "Pixel Spacing", "DS"); add(0x00280031, "Zoom Factor", "DS"); add(0x00280032, "Zoom Center", "DS"); add(0x00280034, "Pixel Aspect Ratio", "IS"); add(0x00280040, "Image Format", "CS"); // Retired add(0x00280050, "Manipulated Image", "LO"); // Retired add(0x00280051, "Corrected Image", "CS"); add(0x0028005F, "Compression Recognition Code", "LO"); // Retired add(0x00280060, "Compression Code", "CS"); // Retired add(0x00280061, "Compression Originator", "SH"); // Retired add(0x00280062, "Compression Label", "LO"); // Retired add(0x00280063, "Compression Description", "SH"); // Retired add(0x00280065, "Compression Sequence", "CS"); // Retired add(0x00280066, "Compression Step Pointers", "AT"); // Retired add(0x00280068, "Repeat Interval", "US"); // Retired add(0x00280069, "Bits Grouped", "US"); // Retired add(0x00280070, "Perimeter Table", "US"); // Retired // add(0x00280071, "Perimeter Value", "US or SS"); //Retired add(0x00280080, "Predictor Rows", "US"); // Retired add(0x00280081, "Predictor Columns", "US"); // Retired add(0x00280082, "Predictor Constants", "US"); // Retired add(0x00280090, "Blocked Pixels", "CS"); // Retired add(0x00280091, "Block Rows", "US"); // Retired add(0x00280092, "Block Columns", "US"); // Retired add(0x00280093, "Row Overlap", "US"); // Retired add(0x00280094, "Column Overlap", "US"); // Retired add(0x00280100, "Bits Allocated", "US"); add(0x00280101, "Bits Stored", "US"); add(0x00280102, "High Bit", "US"); add(0x00280103, "Pixel Representation", "US"); // add(0x00280104, "Smallest Valid Pixel Value", "US or SS"); //Retired // add(0x00280105, "Largest Valid Pixel Value", "US or SS"); //Retired // add(0x00280106, "Smallest Image Pixel Value", "US or SS"); // add(0x00280107, "Largest Image Pixel Value", "US or SS"); // add(0x00280108, "Smallest Pixel Value in Series", "US or SS"); // add(0x00280109, "Largest Pixel Value in Series", "US or SS"); // add(0x00280110, "Smallest Image Pixel Value inPlane", "US or SS1"); // //Retired // add(0x00280111, "Largest Image Pixel Value in Plane", "US or SS"); // //Retired // add(0x00280120, "Pixel Padding Value", "US or SS"); // add(0x00280121, "Pixel Padding Range Limit", "US or SS"); add(0x00280122, "Float Pixel Padding Value", "FL"); add(0x00280123, "Double Float Pixel Padding Value", "FD"); add(0x00280124, "Float Pixel Padding Range Limit", "FL"); add(0x00280125, "Double Float Pixel Padding RangeLimit", "FD"); add(0x00280200, "Image Location", "US"); // Retired add(0x00280300, "Quality Control Image", "CS"); add(0x00280301, "Burned In Annotation", "CS"); add(0x00280302, "Recognizable Visual Features", "CS"); add(0x00280303, "Longitudinal Temporal InformationModified", "CS"); add(0x00280304, "Referenced Color Palette InstanceUID", "UI"); add(0x00280400, "Transform Label", "LO"); // Retired add(0x00280401, "Transform Version Number", "LO"); // Retired add(0x00280402, "Number of Transform Steps", "US"); // Retired add(0x00280403, "Sequence of Compressed Data", "LO"); // Retired add(0x00280404, "Details of Coefficients", "AT"); // Retired add(0x00280700, "DCT Label", "LO"); // Retired add(0x00280701, "Data Block Description", "CS"); // Retired add(0x00280702, "Data Block", "AT"); // Retired add(0x00280710, "Normalization Factor Format", "US"); // Retired add(0x00280720, "Zonal Map Number Format", "US"); // Retired add(0x00280721, "Zonal Map Location", "AT"); // Retired add(0x00280722, "Zonal Map Format", "US"); // Retired add(0x00280730, "Adaptive Map Format", "US"); // Retired add(0x00280740, "Code Number Format", "US"); // Retired add(0x00280A02, "Pixel Spacing Calibration Type", "CS"); add(0x00280A04, "Pixel Spacing CalibrationDescription", "LO"); add(0x00281040, "Pixel Intensity Relationship", "CS"); add(0x00281041, "Pixel Intensity Relationship Sign", "SS"); add(0x00281050, "Window Center", "DS"); add(0x00281051, "Window Width", "DS"); add(0x00281052, "Rescale Intercept", "DS"); add(0x00281053, "Rescale Slope", "DS"); add(0x00281054, "Rescale Type", "LO"); add(0x00281055, "Window Center & WidthExplanation", "LO"); add(0x00281056, "VOI LUT Function", "CS"); add(0x00281080, "Gray Scale", "CS"); // Retired add(0x00281090, "Recommended Viewing Mode", "CS"); // add(0x00281100, "Gray Lookup Table Descriptor", "US or SS"); //Retired // add(0x00281101, "Red Palette Color Lookup TableDescriptor", "US or SS"); // add(0x00281102, "Green Palette Color Lookup TableDescriptor", "US or SS"); // add(0x00281103, "Blue Palette Color Lookup TableDescriptor", "US or SS"); add(0x00281104, "Alpha Palette Color Lookup TableDescriptor", "US"); // add(0x00281111, "Large Red Palette Color LookupTable Descriptor", "US or SS"); //Retired // add(0x00281112, "Large Green Palette Color LookupTable Descriptor", "US or SS"); //Retired // add(0x00281113, "Large Blue Palette Color LookupTable Descriptor", "US or SS"); //Retired add(0x00281199, "Palette Color Lookup Table UID", "UI"); // add(0x00281200, "Gray Lookup Table Data", "US or SS or OW"); //Retired add(0x00281201, "Red Palette Color Lookup TableData", "OW"); add(0x00281202, "Green Palette Color Lookup TableData", "OW"); add(0x00281203, "Blue Palette Color Lookup TableData", "OW"); add(0x00281204, "Alpha Palette Color Lookup TableData", "OW"); add(0x00281211, "Large Red Palette Color LookupTable Data", "OW"); // Retired add(0x00281212, "Large Green Palette Color LookupTable Data", "OW"); // Retired add(0x00281213, "Large Blue Palette Color LookupTable Data", "OW"); // Retired add(0x00281214, "Large Palette Color Lookup TableUID", "UI"); // Retired add(0x00281221, "Segmented Red Palette ColorLookup Table Data", "OW"); add(0x00281222, "Segmented Green Palette ColorLookup Table Data", "OW"); add(0x00281223, "Segmented Blue Palette ColorLookup Table Data", "OW"); add(0x00281300, "Breast Implant Present", "CS"); add(0x00281350, "Partial View", "CS"); add(0x00281351, "Partial View Description", "ST"); add(0x00281352, "Partial View Code Sequence", "SQ"); add(0x0028135A, "Spatial Locations Preserved", "CS"); add(0x00281401, "Data Frame Assignment Sequence", "SQ"); add(0x00281402, "Data Path Assignment", "CS"); add(0x00281403, "Bits Mapped to Color Lookup Table", "US"); add(0x00281404, "Blending LUT 1 Sequence", "SQ"); add(0x00281405, "Blending LUT 1 Transfer Function", "CS"); add(0x00281406, "Blending Weight Constant", "FD"); add(0x00281407, "Blending Lookup Table Descriptor", "US"); add(0x00281408, "Blending Lookup Table Data", "OW"); add(0x0028140B, "Enhanced Palette Color LookupTable Sequence", "SQ"); add(0x0028140C, "Blending LUT 2 Sequence", "SQ"); add(0x0028140D, "Blending LUT 2 Transfer Function BlendingLUT2TransferFunction CS 1 (0028,140E) Data Path ID", "CS"); add(0x0028140F, "RGB LUT Transfer Function", "CS"); add(0x00281410, "Alpha LUT Transfer Function", "CS"); add(0x00282000, "ICC Profile", "OB"); add(0x00282110, "Lossy Image Compression", "CS"); add(0x00282112, "Lossy Image Compression Ratio", "DS"); add(0x00282114, "Lossy Image Compression Method", "CS"); add(0x00283000, "Modality LUT Sequence", "SQ"); // add(0x00283002, "LUT Descriptor", "US or SS"); add(0x00283003, "LUT Explanation", "LO"); add(0x00283004, "Modality LUT Type", "LO"); // add(0x00283006, "LUT Data", "US or OW"); add(0x00283010, "VOI LUT Sequence", "SQ"); add(0x00283110, "Softcopy VOI LUT Sequence", "SQ"); add(0x00284000, "Image Presentation Comments", "LT"); // Retired add(0x00285000, "Bi-Plane Acquisition Sequence", "SQ"); // Retired add(0x00286010, "Representative Frame Number", "US"); add(0x00286020, "Frame Numbers of Interest (FOI)", "US"); add(0x00286022, "Frame of Interest Description", "LO"); add(0x00286023, "Frame of Interest Type", "CS"); add(0x00286030, "Mask Pointer(s)", "US"); // Retired add(0x00286040, "R Wave Pointer", "US"); add(0x00286100, "Mask Subtraction Sequence", "SQ"); add(0x00286101, "Mask Operation", "CS"); add(0x00286102, "Applicable Frame Range", "US"); add(0x00286110, "Mask Frame Numbers", "US"); add(0x00286112, "Contrast Frame Averaging", "US"); add(0x00286114, "Mask Sub-pixel Shift", "FL"); add(0x00286120, "TID Offset", "SS"); add(0x00286190, "Mask Operation Explanation", "ST"); add(0x00287000, "Equipment Administrator Sequence", "SQ"); add(0x00287001, "Number of Display Subsystems", "US"); add(0x00287002, "Current Configuration ID", "US"); add(0x00287003, "Display Subsystem ID", "US"); add(0x00287004, "Display Subsystem Name", "SH"); add(0x00287005, "Display Subsystem Description", "LO"); add(0x00287006, "System Status", "CS"); add(0x00287007, "System Status Comment", "LO"); add(0x00287008, "Target Luminance CharacteristicsSequence", "SQ"); add(0x00287009, "Luminance Characteristics ID", "US"); add(0x0028700A, "Display Subsystem ConfigurationSequence", "SQ"); add(0x0028700B, "Configuration ID", "US"); add(0x0028700C, "Configuration Name", "SH"); add(0x0028700D, "Configuration Description", "LO"); add(0x0028700E, "Referenced Target LuminanceCharacteristics ID", "US"); add(0x0028700F, "QA Results Sequence", "SQ"); add(0x00287010, "Display Subsystem QA ResultsSequence", "SQ"); add(0x00287011, "Configuration QA ResultsSequence", "SQ"); add(0x00287012, "Measurement EquipmentSequence", "SQ"); add(0x00287013, "Measurement Functions", "CS"); add(0x00287014, "Measurement Equipment Type", "CS"); add(0x00287015, "Visual Evaluation Result Sequence", "SQ"); add(0x00287016, "Display Calibration ResultSequence", "SQ"); add(0x00287017, "DDL Value", "US"); add(0x00287018, "CIExy White Point", "FL"); add(0x00287019, "Display Function Type", "CS"); add(0x0028701A, "Gamma Value", "FL"); add(0x0028701B, "Number of Luminance Points", "US"); add(0x0028701C, "Luminance Response Sequence", "SQ"); add(0x0028701D, "Target Minimum Luminance", "FL"); add(0x0028701E, "Target Maximum Luminance", "FL"); add(0x0028701F, "Luminance Value", "FL"); add(0x00287020, "Luminance Response Description", "LO"); add(0x00287021, "White Point Flag", "CS"); add(0x00287022, "Display Device Type CodeSequence", "SQ"); add(0x00287023, "Display Subsystem Sequence", "SQ"); add(0x00287024, "Luminance Result Sequence", "SQ"); add(0x00287025, "Ambient Light Value Source", "CS"); add(0x00287026, "Measured Characteristics", "CS"); add(0x00287027, "Luminance Uniformity ResultSequence", "SQ"); add(0x00287028, "Visual Evaluation Test Sequence", "SQ"); add(0x00287029, "Test Result", "CS"); add(0x0028702A, "Test Result Comment", "LO"); add(0x0028702B, "Test Image Validation", "CS"); add(0x0028702C, "Test Pattern Code Sequence", "SQ"); add(0x0028702D, "Measurement Pattern CodeSequence", "SQ"); add(0x0028702E, "Visual Evaluation Method CodeSequence", "SQ"); add(0x00287FE0, "Pixel Data Provider URL", "UR"); add(0x00289001, "Data Point Rows", "UL"); add(0x00289002, "Data Point Columns", "UL"); add(0x00289003, "Signal Domain Columns", "CS"); add(0x00289099, "Largest Monochrome Pixel Value", "US"); // Retired add(0x00289108, "Data Representation", "CS"); add(0x00289110, "Pixel Measures Sequence", "SQ"); add(0x00289132, "Frame VOI LUT Sequence", "SQ"); add(0x00289145, "Pixel Value TransformationSequence", "SQ"); add(0x00289235, "Signal Domain Rows", "CS"); add(0x00289411, "Display Filter Percentage", "FL"); add(0x00289415, "Frame Pixel Shift Sequence", "SQ"); add(0x00289416, "Subtraction Item ID", "US"); add(0x00289422, "Pixel Intensity Relationship LUTSequence", "SQ"); add(0x00289443, "Frame Pixel Data PropertiesSequence", "SQ"); add(0x00289444, "Geometrical Properties", "CS"); add(0x00289445, "Geometric Maximum Distortion", "FL"); add(0x00289446, "Image Processing Applied", "CS"); add(0x00289454, "Mask Selection Mode", "CS"); add(0x00289474, "LUT Function", "CS"); add(0x00289478, "Mask Visibility Percentage", "FL"); add(0x00289501, "Pixel Shift Sequence", "SQ"); add(0x00289502, "Region Pixel Shift Sequence", "SQ"); add(0x00289503, "Vertices of the Region", "SS"); add(0x00289505, "Multi-frame Presentation Sequence", "SQ"); add(0x00289506, "Pixel Shift Frame Range", "US"); add(0x00289507, "LUT Frame Range", "US"); add(0x00289520, "Image to Equipment MappingMatrix", "DS"); add(0x00289537, "Equipment Coordinate SystemIdentification", "CS"); } /** * Adds attributes of group 0x0032. */ private void addAttributeGroup0032() { add(0x0032000A, "Study Status ID", "CS"); // Retired add(0x0032000C, "Study Priority ID", "CS"); // Retired add(0x00320012, "Study ID Issuer", "LO"); // Retired add(0x00320032, "Study Verified Date", "DA"); // Retired add(0x00320033, "Study Verified Time", "TM"); // Retired add(0x00320034, "Study Read Date", "DA"); // Retired add(0x00320035, "Study Read Time", "TM"); // Retired add(0x00321000, "Scheduled Study Start Date", "DA"); // Retired add(0x00321001, "Scheduled Study Start Time", "TM"); // Retired add(0x00321010, "Scheduled Study Stop Date", "DA"); // Retired add(0x00321011, "Scheduled Study Stop Time", "TM"); // Retired add(0x00321020, "Scheduled Study Location", "LO"); // Retired add(0x00321021, "Scheduled Study Location AE Title", "AE"); // Retired add(0x00321030, "Reason for Study", "LO"); // Retired add(0x00321031, "Requesting Physician IdentificationSequence", "SQ"); add(0x00321032, "Requesting Physician", "PN"); add(0x00321033, "Requesting Service", "LO"); add(0x00321034, "Requesting Service CodeSequence", "SQ"); add(0x00321040, "Study Arrival Date", "DA"); // Retired add(0x00321041, "Study Arrival Time", "TM"); // Retired add(0x00321050, "Study Completion Date", "DA"); // Retired add(0x00321051, "Study Completion Time", "TM"); // Retired add(0x00321055, "Study Component Status ID", "CS"); // Retired add(0x00321060, "Requested Procedure Description", "LO"); add(0x00321064, "Requested Procedure CodeSequence", "SQ"); add(0x00321070, "Requested Contrast Agent", "LO"); add(0x00324000, "Study Comments", "LT"); // Retired } /** * Adds attributes of group 0x0038. */ private void addAttributeGroup0038() { add(0x00380004, "Referenced Patient Alias Sequence", "SQ"); add(0x00380008, "Visit Status ID", "CS"); add(0x00380010, "Admission ID", "LO"); add(0x00380011, "Issuer of Admission ID", "LO"); // Retired add(0x00380014, "Issuer of Admission ID Sequence", "SQ"); add(0x00380016, "Route of Admissions", "LO"); add(0x0038001A, "Scheduled Admission Date", "DA"); // Retired add(0x0038001B, "Scheduled Admission Time", "TM"); // Retired add(0x0038001C, "Scheduled Discharge Date", "DA"); // Retired add(0x0038001D, "Scheduled Discharge Time", "TM"); // Retired add(0x0038001E, "Scheduled Patient InstitutionResidence", "LO"); // Retired add(0x00380020, "Admitting Date", "DA"); add(0x00380021, "Admitting Time", "TM"); add(0x00380030, "Discharge Date", "DA"); // Retired add(0x00380032, "Discharge Time", "TM"); // Retired add(0x00380040, "Discharge Diagnosis Description", "LO"); // Retired add(0x00380044, "Discharge Diagnosis CodeSequence", "SQ"); // Retired add(0x00380050, "Special Needs", "LO"); add(0x00380060, "Service Episode ID", "LO"); add(0x00380061, "Issuer of Service Episode ID", "LO"); // Retired add(0x00380062, "Service Episode Description", "LO"); add(0x00380064, "Issuer of Service Episode IDSequence", "SQ"); add(0x00380100, "Pertinent Documents Sequence", "SQ"); add(0x00380101, "Pertinent Resources Sequence", "SQ"); add(0x00380102, "Resource Description", "LO"); add(0x00380300, "Current Patient Location", "LO"); add(0x00380400, "Patient's Institution Residence", "LO"); add(0x00380500, "Patient State", "LO"); add(0x00380502, "Patient Clinical Trial ParticipationSequence", "SQ"); add(0x00384000, "Visit Comments", "LT"); } /** * Adds attributes of group 0x003A. */ private void addAttributeGroup003A() { add(0x00400001, "Scheduled Station AE Title", "AE"); add(0x00400002, "Scheduled Procedure Step StartDate", "DA"); add(0x00400003, "Scheduled Procedure Step StartTime", "TM"); add(0x00400004, "Scheduled Procedure Step EndDate", "DA"); add(0x00400005, "Scheduled Procedure Step EndTime", "TM"); add(0x00400006, "Scheduled Performing Physician'sName", "PN"); add(0x00400007, "Scheduled Procedure StepDescription", "LO"); add(0x00400008, "Scheduled Protocol CodeSequence", "SQ"); add(0x00400009, "Scheduled Procedure Step ID", "SH"); add(0x0040000A, "Stage Code Sequence", "SQ"); add(0x0040000B, "Scheduled Performing PhysicianIdentification Sequence", "SQ"); add(0x00400010, "Scheduled Station Name", "SH"); add(0x00400011, "Scheduled Procedure StepLocation", "SH"); add(0x00400012, "Pre-Medication", "LO"); add(0x00400020, "Scheduled Procedure Step Status", "CS"); add(0x00400026, "Order Placer Identifier Sequence", "SQ"); add(0x00400027, "Order Filler Identifier Sequence", "SQ"); add(0x00400031, "Local Namespace Entity ID", "UT"); add(0x00400032, "Universal Entity ID", "UT"); add(0x00400033, "Universal Entity ID Type", "CS"); add(0x00400035, "Identifier Type Code", "CS"); add(0x00400036, "Assigning Facility Sequence", "SQ"); add(0x00400039, "Assigning Jurisdiction CodeSequence", "SQ"); // add(0x0040003A, "Assigning Agency or DepartmentCode Sequence", "SQ"); add(0x00400100, "Scheduled Procedure StepSequence", "SQ"); add(0x00400220, "Referenced Non-Image CompositeSOP Instance Sequence", "SQ"); add(0x00400241, "Performed Station AE Title", "AE"); add(0x00400242, "Performed Station Name", "SH"); add(0x00400243, "Performed Location", "SH"); add(0x00400244, "Performed Procedure Step StartDate", "DA"); add(0x00400245, "Performed Procedure Step StartTime", "TM"); add(0x00400250, "Performed Procedure Step EndDate", "DA"); add(0x00400251, "Performed Procedure Step EndTime", "TM"); add(0x00400252, "Performed Procedure Step Status", "CS"); add(0x00400253, "Performed Procedure Step ID", "SH"); add(0x00400254, "Performed Procedure StepDescription", "LO"); add(0x00400255, "Performed Procedure TypeDescription", "LO"); add(0x00400260, "Performed Protocol CodeSequence", "SQ"); add(0x00400261, "Performed Protocol Type", "CS"); add(0x00400270, "Scheduled Step AttributesSequence", "SQ"); add(0x00400275, "Request Attributes Sequence", "SQ"); add(0x00400280, "Comments on the PerformedProcedure Step", "ST"); add(0x00400281, "Performed Procedure StepDiscontinuation Reason CodeSequence", "SQ"); add(0x00400293, "Quantity Sequence", "SQ"); add(0x00400294, "Quantity", "DS"); add(0x00400295, "Measuring Units Sequence", "SQ"); add(0x00400296, "Billing Item Sequence", "SQ"); add(0x00400300, "Total Time of Fluoroscopy", "US"); add(0x00400301, "Total Number of Exposures", "US"); add(0x00400302, "Entrance Dose", "US"); add(0x00400303, "Exposed Area", "US"); add(0x00400306, "Distance Source to Entrance", "DS"); add(0x00400307, "Distance Source to Support", "DS"); // Retired add(0x0040030E, "Exposure Dose Sequence", "SQ"); add(0x00400310, "Comments on Radiation Dose", "ST"); add(0x00400312, "X-Ray Output", "DS"); add(0x00400314, "Half Value Layer", "DS"); add(0x00400316, "Organ Dose", "DS"); add(0x00400318, "Organ Exposed", "CS"); add(0x00400320, "Billing Procedure Step Sequence", "SQ"); add(0x00400321, "Film Consumption Sequence", "SQ"); add(0x00400324, "Billing Supplies and DevicesSequence", "SQ"); add(0x00400330, "Referenced Procedure StepSequence", "SQ"); // Retired add(0x00400340, "Performed Series Sequence", "SQ"); add(0x00400400, "Comments on the ScheduledProcedure Step", "LT"); add(0x00400440, "Protocol Context Sequence", "SQ"); add(0x00400441, "Content Item Modifier Sequence", "SQ"); add(0x00400500, "Scheduled Specimen Sequence", "SQ"); add(0x0040050A, "Specimen Accession Number", "LO"); // Retired add(0x00400512, "Container Identifier", "LO"); add(0x00400513, "Issuer of the Container IdentifierSequence", "SQ"); add(0x00400515, "Alternate Container IdentifierSequence", "SQ"); add(0x00400518, "Container Type Code Sequence", "SQ"); add(0x0040051A, "Container Description", "LO"); add(0x00400520, "Container Component Sequence", "SQ"); add(0x00400550, "Specimen Sequence", "SQ"); // Retired add(0x00400551, "Specimen Identifier", "LO"); add(0x00400552, "Specimen Description Sequence(Trial)", "SQ"); // Retired add(0x00400553, "Specimen Description (Trial)", "ST"); // Retired add(0x00400554, "Specimen UID", "UI"); add(0x00400555, "Acquisition Context Sequence", "SQ"); add(0x00400556, "Acquisition Context Description", "ST"); add(0x0040059A, "Specimen Type Code Sequence", "SQ"); add(0x00400560, "Specimen Description Sequence", "SQ"); add(0x00400562, "Issuer of the Specimen IdentifierSequence", "SQ"); add(0x00400600, "Specimen Short Description", "LO"); add(0x00400602, "Specimen Detailed Description", "UT"); add(0x00400610, "Specimen Preparation Sequence", "SQ"); add(0x00400612, "Specimen Preparation StepContent Item Sequence", "SQ"); add(0x00400620, "Specimen Localization ContentItem Sequence", "SQ"); add(0x004006FA, "Slide Identifier", "LO"); // Retired add(0x0040071A, "Image Center Point CoordinatesSequence", "SQ"); add(0x0040072A, "X Offset in Slide CoordinateSystem", "DS"); add(0x0040073A, "Y Offset in Slide CoordinateSystem", "DS"); add(0x0040074A, "Z Offset in Slide CoordinateSystem", "DS"); add(0x004008D8, "Pixel Spacing Sequence", "SQ"); // Retired add(0x004008DA, "Coordinate System Axis CodeSequence", "SQ"); // Retired add(0x004008EA, "Measurement Units CodeSequence", "SQ"); add(0x004009F8, "Vital Stain Code Sequence (Trial)", "SQ"); // Retired add(0x00401001, "Requested Procedure ID", "SH"); add(0x00401002, "Reason for the RequestedProcedure", "LO"); add(0x00401003, "Requested Procedure Priority", "SH"); add(0x00401004, "Patient Transport Arrangements", "LO"); add(0x00401005, "Requested Procedure Location", "LO"); add(0x00401006, "Placer Order Number / Procedure", "SH"); // Retired add(0x00401007, "Filler Order Number / Procedure", "SH"); // Retired add(0x00401008, "Confidentiality Code", "LO"); add(0x00401009, "Reporting Priority", "SH"); add(0x0040100A, "Reason for Requested ProcedureCode Sequence", "SQ"); add(0x00401010, "Names of Intended Recipients ofResults", "PN"); add(0x00401011, "Intended Recipients of ResultsIdentification Sequence", "SQ"); add(0x00401012, "Reason For Performed ProcedureCode Sequence", "SQ"); add(0x00401060, "Requested Procedure Description(Trial)", "LO"); // Retired add(0x00401101, "Person Identification CodeSequence", "SQ"); add(0x00401102, "Person's Address", "ST"); add(0x00401103, "Person's Telephone Numbers", "LO"); add(0x00401104, "Person's Telecom Information", "LT"); add(0x00401400, "Requested Procedure Comments", "LT"); add(0x00402001, "Reason for the Imaging ServiceRequest", "LO"); // Retired add(0x00402004, "Issue Date of Imaging ServiceRequest", "DA"); add(0x00402005, "Issue Time of Imaging ServiceRequest", "TM"); add(0x00402006, "Placer Order Number / ImagingService Request (Retired)", "SH"); // Retired add(0x00402007, "Filler Order Number / ImagingService Request (Retired)", "SH"); // Retired add(0x00402008, "Order Entered By", "PN"); add(0x00402009, "Order Enterer's Location", "SH"); add(0x00402010, "Order Callback Phone Number", "SH"); add(0x00402011, "Order Callback TelecomInformation", "LT"); add(0x00402016, "Placer Order Number / ImagingService Request", "LO"); add(0x00402017, "Filler Order Number / ImagingService Request", "LO"); add(0x00402400, "Imaging Service RequestComments", "LT"); add(0x00403001, "Confidentiality Constraint onPatient Data Description", "LO"); add(0x00404001, "General Purpose ScheduledProcedure Step Status", "CS"); // Retired add(0x00404002, "General Purpose PerformedProcedure Step Status", "CS"); // Retired add(0x00404003, "General Purpose ScheduledProcedure Step Priority", "CS"); // Retired add(0x00404004, "Scheduled Processing ApplicationsCode Sequence", "SQ"); // Retired add(0x00404005, "Scheduled Procedure Step StartDateTime", "DT"); add(0x00404006, "Multiple Copies Flag", "CS"); // Retired add(0x00404007, "Performed Processing ApplicationsCode Sequence", "SQ"); add(0x00404009, "Human Performer Code Sequence", "SQ"); add(0x00404010, "Scheduled Procedure StepModification DateTime", "DT"); add(0x00404011, "Expected Completion DateTime", "DT"); add(0x00404015, "Resulting General PurposePerformed Procedure StepsSequence", "SQ"); // Retired add(0x00404016, "Referenced General PurposeScheduled Procedure StepSequence", "SQ"); // Retired add(0x00404018, "Scheduled Workitem CodeSequence", "SQ"); add(0x00404019, "Performed Workitem CodeSequence", "SQ"); add(0x00404020, "Input Availability Flag", "CS"); add(0x00404021, "Input Information Sequence", "SQ"); add(0x00404022, "Relevant Information Sequence", "SQ"); // Retired add(0x00404023, "Referenced General PurposeScheduled Procedure StepTransaction UID", "UI"); // Retired add(0x00404025, "Scheduled Station Name CodeSequence", "SQ"); add(0x00404026, "Scheduled Station Class CodeSequence", "SQ"); add(0x00404027, "Scheduled Station GeographicLocation Code Sequence", "SQ"); add(0x00404028, "Performed Station Name CodeSequence", "SQ"); add(0x00404029, "Performed Station Class CodeSequence", "SQ"); add(0x00404030, "Performed Station GeographicLocation Code Sequence", "SQ"); add(0x00404031, "Requested Subsequent WorkitemCode Sequence", "SQ"); // Retired add(0x00404032, "Non-DICOM Output CodeSequence", "SQ"); // Retired add(0x00404033, "Output Information Sequence", "SQ"); add(0x00404034, "Scheduled Human PerformersSequence", "SQ"); add(0x00404035, "Actual Human PerformersSequence", "SQ"); add(0x00404036, "Human Performer's Organization", "LO"); add(0x00404037, "Human Performer's Name", "PN"); add(0x00404040, "Raw Data Handling", "CS"); add(0x00404041, "Input Readiness State", "CS"); add(0x00404050, "Performed Procedure Step StartDateTime", "DT"); add(0x00404051, "Performed Procedure Step EndDateTime", "DT"); add(0x00404052, "Procedure Step CancellationDateTime", "DT"); add(0x00408302, "Entrance Dose in mGy", "DS"); add(0x00409092, "Parametric Map Frame TypeSequence", "SQ"); add(0x00409094, "Referenced Image Real WorldValue Mapping Sequence", "SQ"); add(0x00409096, "Real World Value MappingSequence", "SQ"); add(0x00409098, "Pixel Value Mapping CodeSequence", "SQ"); add(0x00409210, "LUT Label", "SH"); // add(0x00409211, "Real World Value Last ValueMapped", "US or SS"); add(0x00409212, "Real World Value LUT Data", "FD"); // add(0x00409216, "Real World Value First ValueMapped", "US or SS"); add(0x00409220, "Quantity Definition Sequence", "SQ"); add(0x00409224, "Real World Value Intercept", "FD"); add(0x00409225, "Real World Value Slope", "FD"); add(0x0040A007, "Findings Flag (Trial)", "CS"); // Retired add(0x0040A010, "Relationship Type", "CS"); add(0x0040A020, "Findings Sequence (Trial)", "SQ"); // Retired add(0x0040A021, "Findings Group UID (Trial)", "UI"); // Retired add(0x0040A022, "Referenced Findings Group UID(Trial)", "UI"); // Retired add(0x0040A023, "Findings Group Recording Date(Trial)", "DA"); // Retired add(0x0040A024, "Findings Group Recording Time(Trial)", "TM"); // Retired add(0x0040A026, "Findings Source Category CodeSequence (Trial)", "SQ"); // Retired add(0x0040A027, "Verifying Organization", "LO"); add(0x0040A028, "Documenting OrganizationIdentifier Code Sequence (Trial)", "SQ"); // Retired add(0x0040A030, "Verification DateTime", "DT"); add(0x0040A032, "Observation DateTime", "DT"); add(0x0040A040, "Value Type", "CS"); add(0x0040A043, "Concept Name Code Sequence", "SQ"); add(0x0040A047, "Measurement Precision Description(Trial)", "LO"); // Retired add(0x0040A050, "Continuity Of Content", "CS"); // add(0x0040A057, "Urgency or Priority Alerts (Trial)", "CS"); //Retired add(0x0040A060, "Sequencing Indicator (Trial)", "LO"); // Retired add(0x0040A066, "Document Identifier CodeSequence (Trial)", "SQ"); // Retired add(0x0040A067, "Document Author (Trial)", "PN"); // Retired add(0x0040A068, "Document Author Identifier CodeSequence (Trial)", "SQ"); // Retired add(0x0040A070, "Identifier Code Sequence (Trial)", "SQ"); // Retired add(0x0040A073, "Verifying Observer Sequence", "SQ"); add(0x0040A074, "Object Binary Identifier (Trial)", "OB"); // Retired add(0x0040A075, "Verifying Observer Name", "PN"); add(0x0040A076, "Documenting Observer IdentifierCode Sequence (Trial)", "SQ"); // Retired add(0x0040A078, "Author Observer Sequence", "SQ"); add(0x0040A07A, "Participant Sequence", "SQ"); add(0x0040A07C, "Custodial Organization Sequence", "SQ"); add(0x0040A080, "Participation Type", "CS"); add(0x0040A082, "Participation DateTime", "DT"); add(0x0040A084, "Observer Type", "CS"); add(0x0040A085, "Procedure Identifier CodeSequence (Trial)", "SQ"); // Retired add(0x0040A088, "Verifying Observer IdentificationCode Sequence", "SQ"); add(0x0040A089, "Object Directory Binary Identifier(Trial)", "OB"); // Retired add(0x0040A090, "Equivalent CDA DocumentSequence", "SQ"); // Retired add(0x0040A0B0, "Referenced Waveform Channels", "US"); // add(0x0040A110, "Date of Document or VerbalTransaction (Trial)", "DA"); // //Retired add(0x0040A112, "Time of Document Creation orVerbal Transaction (Trial)", "TM"); // Retired add(0x0040A120, "DateTime", "DT"); add(0x0040A121, "Date", "DA"); add(0x0040A122, "Time", "TM"); add(0x0040A123, "Person Name", "PN"); add(0x0040A124, "UID", "UI"); add(0x0040A125, "Report Status ID (Trial)", "CS"); // Retired add(0x0040A130, "Temporal Range Type", "CS"); add(0x0040A132, "Referenced Sample Positions", "UL"); add(0x0040A136, "Referenced Frame Numbers", "US"); add(0x0040A138, "Referenced Time Offsets", "DS"); add(0x0040A13A, "Referenced DateTime", "DT"); add(0x0040A160, "Text Value", "UT"); add(0x0040A161, "Floating Point Value", "FD"); add(0x0040A162, "Rational Numerator Value", "SL"); add(0x0040A163, "Rational Denominator Value", "UL"); add(0x0040A167, "Observation Category CodeSequence (Trial)", "SQ"); // Retired add(0x0040A168, "Concept Code Sequence", "SQ"); add(0x0040A16A, "Bibliographic Citation (Trial)", "ST"); // Retired add(0x0040A170, "Purpose of Reference CodeSequence", "SQ"); add(0x0040A171, "Observation UID", "UI"); add(0x0040A172, "Referenced Observation UID (Trial)", "UI"); // Retired add(0x0040A173, "Referenced Observation Class(Trial)", "CS"); // Retired add(0x0040A174, "Referenced Object ObservationClass (Trial)", "CS"); // Retired add(0x0040A180, "Annotation Group Number", "US"); add(0x0040A192, "Observation Date (Trial)", "DA"); // Retired add(0x0040A193, "Observation Time (Trial)", "TM"); // Retired add(0x0040A194, "Measurement Automation (Trial)", "CS"); // Retired add(0x0040A195, "Modifier Code Sequence", "SQ"); add(0x0040A224, "Identification Description (Trial)", "ST"); // Retired add(0x0040A290, "Coordinates Set Geometric Type(Trial)", "CS"); // Retired add(0x0040A296, "Algorithm Code Sequence (Trial)", "SQ"); // Retired add(0x0040A297, "Algorithm Description (Trial)", "ST"); // Retired add(0x0040A29A, "Pixel Coordinates Set (Trial)", "SL"); // Retired add(0x0040A300, "Measured Value Sequence", "SQ"); add(0x0040A301, "Numeric Value Qualifier CodeSequence", "SQ"); add(0x0040A307, "Current Observer (Trial)", "PN"); // Retired add(0x0040A30A, "Numeric Value", "DS"); add(0x0040A313, "Referenced Accession Sequence(Trial)", "SQ"); // Retired add(0x0040A33A, "Report Status Comment (Trial)", "ST"); // Retired add(0x0040A340, "Procedure Context Sequence(Trial)", "SQ"); // Retired add(0x0040A352, "Verbal Source (Trial)", "PN"); // Retired add(0x0040A353, "Address (Trial)", "ST"); // Retired add(0x0040A354, "Telephone Number (Trial)", "LO"); // Retired add(0x0040A358, "Verbal Source Identifier CodeSequence (Trial)", "SQ"); // Retired add(0x0040A360, "Predecessor Documents Sequence", "SQ"); add(0x0040A370, "Referenced Request Sequence", "SQ"); add(0x0040A372, "Performed Procedure CodeSequence", "SQ"); add(0x0040A375, "Current Requested ProcedureEvidence Sequence", "SQ"); add(0x0040A380, "Report Detail Sequence (Trial)", "SQ"); // Retired add(0x0040A385, "Pertinent Other EvidenceSequence", "SQ"); add(0x0040A390, "HL7 Structured DocumentReference Sequence", "SQ"); add(0x0040A402, "Observation Subject UID (Trial)", "UI"); // Retired add(0x0040A403, "Observation Subject Class (Trial)", "CS"); // Retired add(0x0040A404, "Observation Subject Type CodeSequence (Trial)", "SQ"); // Retired add(0x0040A491, "Completion Flag", "CS"); add(0x0040A492, "Completion Flag Description", "LO"); add(0x0040A493, "Verification Flag", "CS"); add(0x0040A494, "Archive Requested", "CS"); add(0x0040A496, "Preliminary Flag", "CS"); add(0x0040A504, "Content Template Sequence", "SQ"); add(0x0040A525, "Identical Documents Sequence", "SQ"); add(0x0040A600, "Observation Subject Context Flag(Trial)", "CS"); // Retired add(0x0040A601, "Observer Context Flag (Trial)", "CS"); // Retired add(0x0040A603, "Procedure Context Flag (Trial)", "CS"); // Retired add(0x0040A730, "Content Sequence", "SQ"); add(0x0040A731, "Relationship Sequence (Trial)", "SQ"); // Retired add(0x0040A732, "Relationship Type Code Sequence(Trial)", "SQ"); // Retired add(0x0040A744, "Language Code Sequence (Trial)", "SQ"); // Retired add(0x0040A992, "Uniform Resource Locator (Trial)", "ST"); // Retired add(0x0040B020, "Waveform Annotation Sequence", "SQ"); add(0x0040DB00, "Template Identifier", "CS"); add(0x0040DB06, "Template Version", "DT"); // Retired add(0x0040DB07, "Template Local Version", "DT"); // Retired add(0x0040DB0B, "Template Extension Flag", "CS"); // Retired add(0x0040DB0C, "Template Extension OrganizationUID", "UI"); // Retired add(0x0040DB0D, "Template Extension Creator UID", "UI"); // Retired add(0x0040DB73, "Referenced Content Item Identifier", "UL"); add(0x0040E001, "HL7 Instance Identifier", "ST"); add(0x0040E004, "HL7 Document Effective Time", "DT"); add(0x0040E006, "HL7 Document Type CodeSequence", "SQ"); add(0x0040E008, "Document Class Code Sequence", "SQ"); add(0x0040E010, "Retrieve URI", "UR"); add(0x0040E011, "Retrieve Location UID", "UI"); add(0x0040E020, "Type of Instances", "CS"); add(0x0040E021, "DICOM Retrieval Sequence", "SQ"); add(0x0040E022, "DICOM Media Retrieval Sequence", "SQ"); add(0x0040E023, "WADO Retrieval Sequence", "SQ"); add(0x0040E024, "XDS Retrieval Sequence", "SQ"); add(0x0040E025, "WADO-RS Retrieval Sequence", "SQ"); add(0x0040E030, "Repository Unique ID", "UI"); add(0x0040E031, "Home Community ID", "UI"); } /** * Adds attributes of group 0x0042. */ private void addAttributeGroup0042() { add(0x00420010, "Document Title", "ST"); add(0x00420011, "Encapsulated Document", "OB"); add(0x00420012, "MIME Type of EncapsulatedDocument", "LO"); add(0x00420013, "Source Instance Sequence", "SQ"); add(0x00420014, "List of MIME Types", "LO"); } /** * Adds attributes of group 0x0044. */ private void addAttributeGroup0044() { add(0x00440001, "Product Package Identifier", "ST"); add(0x00440002, "Substance Administration Approval", "CS"); add(0x00440003, "Approval Status FurtherDescription", "LT"); add(0x00440004, "Approval Status DateTime", "DT"); add(0x00440007, "Product Type Code Sequence", "SQ"); add(0x00440008, "Product Name", "LO"); add(0x00440009, "Product Description", "LT"); add(0x0044000A, "Product Lot Identifier", "LO"); add(0x0044000B, "Product Expiration DateTime", "DT"); add(0x00440010, "Substance AdministrationDateTime", "DT"); add(0x00440011, "Substance Administration Notes", "LO"); add(0x00440012, "Substance Administration DeviceID", "LO"); add(0x00440013, "Product Parameter Sequence", "SQ"); add(0x00440019, "Substance AdministrationParameter Sequence", "SQ"); } /** * Adds attributes of group 0x0046. */ private void addAttributeGroup0046() { add(0x00460012, "Lens Description", "LO"); add(0x00460014, "Right Lens Sequence", "SQ"); add(0x00460015, "Left Lens Sequence", "SQ"); add(0x00460016, "Unspecified Laterality LensSequence", "SQ"); add(0x00460018, "Cylinder Sequence", "SQ"); add(0x00460028, "Prism Sequence", "SQ"); add(0x00460030, "Horizontal Prism Power", "FD"); add(0x00460032, "Horizontal Prism Base", "CS"); add(0x00460034, "Vertical Prism Power", "FD"); add(0x00460036, "Vertical Prism Base", "CS"); add(0x00460038, "Lens Segment Type", "CS"); add(0x00460040, "Optical Transmittance", "FD"); add(0x00460042, "Channel Width", "FD"); add(0x00460044, "Pupil Size", "FD"); add(0x00460046, "Corneal Size", "FD"); add(0x00460050, "Autorefraction Right Eye Sequence", "SQ"); add(0x00460052, "Autorefraction Left Eye Sequence", "SQ"); add(0x00460060, "Distance Pupillary Distance", "FD"); add(0x00460062, "Near Pupillary Distance", "FD"); add(0x00460063, "Intermediate Pupillary Distance", "FD"); add(0x00460064, "Other Pupillary Distance", "FD"); add(0x00460070, "Keratometry Right Eye Sequence", "SQ"); add(0x00460071, "Keratometry Left Eye Sequence", "SQ"); add(0x00460074, "Steep Keratometric Axis Sequence", "SQ"); add(0x00460075, "Radius of Curvature", "FD"); add(0x00460076, "Keratometric Power", "FD"); add(0x00460077, "Keratometric Axis", "FD"); add(0x00460080, "Flat Keratometric Axis Sequence", "SQ"); add(0x00460092, "Background Color", "CS"); add(0x00460094, "Optotype", "CS"); add(0x00460095, "Optotype Presentation", "CS"); add(0x00460097, "Subjective Refraction Right EyeSequence", "SQ"); add(0x00460098, "Subjective Refraction Left EyeSequence", "SQ"); add(0x00460100, "Add Near Sequence", "SQ"); add(0x00460101, "Add Intermediate Sequence", "SQ"); add(0x00460102, "Add Other Sequence", "SQ"); add(0x00460104, "Add Power", "FD"); add(0x00460106, "Viewing Distance", "FD"); add(0x00460121, "Visual Acuity Type Code Sequence", "SQ"); add(0x00460122, "Visual Acuity Right Eye Sequence", "SQ"); add(0x00460123, "Visual Acuity Left Eye Sequence", "SQ"); add(0x00460124, "Visual Acuity Both Eyes OpenSequence", "SQ"); add(0x00460125, "Viewing Distance Type", "CS"); add(0x00460135, "Visual Acuity Modifiers", "SS"); add(0x00460137, "Decimal Visual Acuity", "FD"); add(0x00460139, "Optotype Detailed Definition", "LO"); add(0x00460145, "Referenced RefractiveMeasurements Sequence", "SQ"); add(0x00460146, "Sphere Power", "FD"); add(0x00460147, "Cylinder Power", "FD"); add(0x00460201, "Corneal Topography Surface", "CS"); add(0x00460202, "Corneal Vertex Location", "FL"); add(0x00460203, "Pupil Centroid X-Coordinate", "FL"); add(0x00460204, "Pupil Centroid Y-Coordinate", "FL"); add(0x00460205, "Equivalent Pupil Radius", "FL"); add(0x00460207, "Corneal Topography Map TypeCode Sequence", "SQ"); add(0x00460208, "Vertices of the Outline of Pupil", "IS"); add(0x00460210, "Corneal Topography MappingNormals Sequence", "SQ"); add(0x00460211, "Maximum Corneal CurvatureSequence", "SQ"); add(0x00460212, "Maximum Corneal Curvature", "FL"); add(0x00460213, "Maximum Corneal CurvatureLocation", "FL"); add(0x00460215, "Minimum Keratometric Sequence", "SQ"); add(0x00460218, "Simulated Keratometric CylinderSequence", "SQ"); add(0x00460220, "Average Corneal Power", "FL"); add(0x00460224, "Corneal I-S Value", "FL"); add(0x00460227, "Analyzed Area", "FL"); add(0x00460230, "Surface Regularity Index", "FL"); add(0x00460232, "Surface Asymmetry Index", "FL"); add(0x00460234, "Corneal Eccentricity Index", "FL"); add(0x00460236, "Keratoconus Prediction Index", "FL"); add(0x00460238, "Decimal Potential Visual Acuity", "FL"); add(0x00460242, "Corneal Topography Map QualityEvaluation", "CS"); add(0x00460244, "Source Image Corneal ProcessedData Sequence", "SQ"); add(0x00460247, "Corneal Point Location", "FL"); add(0x00460248, "Corneal Point Estimated", "CS"); add(0x00460249, "Axial Power", "FL"); add(0x00460250, "Tangential Power", "FL"); add(0x00460251, "Refractive Power", "FL"); add(0x00460252, "Relative Elevation", "FL"); add(0x00460253, "Corneal Wavefront", "FL"); } /** * Adds attributes of group 0x0048. */ private void addAttributeGroup0048() { add(0x00480001, "Imaged Volume Width", "FL"); add(0x00480002, "Imaged Volume Height", "FL"); add(0x00480003, "Imaged Volume Depth", "FL"); add(0x00480006, "Total Pixel Matrix Columns", "UL"); add(0x00480007, "Total Pixel Matrix Rows", "UL"); add(0x00480008, "Total Pixel Matrix Origin Sequence", "SQ"); add(0x00480010, "Specimen Label in Image", "CS"); add(0x00480011, "Focus Method", "CS"); add(0x00480012, "Extended Depth of Field", "CS"); add(0x00480013, "Number of Focal Planes", "US"); add(0x00480014, "Distance Between Focal Planes", "FL"); add(0x00480015, "Recommended Absent PixelCIELab Value", "US"); add(0x00480100, "Illuminator Type Code Sequence", "SQ"); add(0x00480102, "Image Orientation (Slide)", "DS"); add(0x00480105, "Optical Path Sequence", "SQ"); add(0x00480106, "Optical Path Identifier", "SH"); add(0x00480107, "Optical Path Description", "ST"); add(0x00480108, "Illumination Color Code Sequence", "SQ"); add(0x00480110, "Specimen Reference Sequence", "SQ"); add(0x00480111, "Condenser Lens Power", "DS"); add(0x00480112, "Objective Lens Power", "DS"); add(0x00480113, "Objective Lens Numerical Aperture", "DS"); add(0x00480120, "Palette Color Lookup TableSequence", "SQ"); add(0x00480200, "Referenced Image NavigationSequence", "SQ"); add(0x00480201, "Top Left Hand Corner of LocalizerArea", "US"); add(0x00480202, "Bottom Right Hand Corner ofLocalizer Area", "US"); add(0x00480207, "Optical Path IdentificationSequence", "SQ"); add(0x0048021A, "Plane Position (Slide) Sequence", "SQ"); add(0x0048021E, "Column Position In Total ImagePixel Matrix", "SL"); add(0x0048021F, "Row Position In Total Image PixelMatrix", "SL"); add(0x00480301, "Pixel Origin Interpretation", "CS"); add(0x00480001, "Imaged Volume Width", "FL"); add(0x00480002, "Imaged Volume Height", "FL"); add(0x00480003, "Imaged Volume Depth", "FL"); add(0x00480006, "Total Pixel Matrix Columns", "UL"); add(0x00480007, "Total Pixel Matrix Rows", "UL"); add(0x00480008, "Total Pixel Matrix Origin Sequence", "SQ"); add(0x00480010, "Specimen Label in Image", "CS"); add(0x00480011, "Focus Method", "CS"); add(0x00480012, "Extended Depth of Field", "CS"); add(0x00480013, "Number of Focal Planes", "US"); add(0x00480014, "Distance Between Focal Planes", "FL"); add(0x00480015, "Recommended Absent PixelCIELab Value", "US"); add(0x00480100, "Illuminator Type Code Sequence", "SQ"); add(0x00480102, "Image Orientation (Slide)", "DS"); add(0x00480105, "Optical Path Sequence", "SQ"); add(0x00480106, "Optical Path Identifier", "SH"); add(0x00480107, "Optical Path Description", "ST"); add(0x00480108, "Illumination Color Code Sequence", "SQ"); add(0x00480110, "Specimen Reference Sequence", "SQ"); add(0x00480111, "Condenser Lens Power", "DS"); add(0x00480112, "Objective Lens Power", "DS"); add(0x00480113, "Objective Lens Numerical Aperture", "DS"); add(0x00480120, "Palette Color Lookup TableSequence", "SQ"); add(0x00480200, "Referenced Image NavigationSequence", "SQ"); add(0x00480201, "Top Left Hand Corner of LocalizerArea", "US"); add(0x00480202, "Bottom Right Hand Corner ofLocalizer Area", "US"); add(0x00480207, "Optical Path IdentificationSequence", "SQ"); add(0x0048021A, "Plane Position (Slide) Sequence", "SQ"); add(0x0048021E, "Column Position In Total ImagePixel Matrix", "SL"); add(0x0048021F, "Row Position In Total Image PixelMatrix", "SL"); add(0x00480301, "Pixel Origin Interpretation", "CS"); } /** * Adds attributes of group 0x0050. */ private void addAttributeGroup0050() { add(0x00500004, "Calibration Image", "CS"); add(0x00500010, "Device Sequence", "SQ"); add(0x00500012, "Container Component Type CodeSequence", "SQ"); add(0x00500013, "Container Component Thickness", "FD"); add(0x00500014, "Device Length", "DS"); add(0x00500015, "Container Component Width", "FD"); add(0x00500016, "Device Diameter", "DS"); add(0x00500017, "Device Diameter Units", "CS"); add(0x00500018, "Device Volume", "DS"); add(0x00500019, "Inter-Marker Distance", "DS"); add(0x0050001A, "Container Component Material", "CS"); add(0x0050001B, "Container Component ID", "LO"); add(0x0050001C, "Container Component Length", "FD"); add(0x0050001D, "Container Component Diameter", "FD"); add(0x0050001E, "Container Component Description", "LO"); add(0x00500020, "Device Description", "LO"); } /** * Adds attributes of group 0x0052. */ private void addAttributeGroup0052() { add(0x00520001, "Contrast/Bolus Ingredient Percentby Volume", "FL"); add(0x00520002, "OCT Focal Distance", "FD"); add(0x00520003, "Beam Spot Size", "FD"); add(0x00520004, "Effective Refractive Index", "FD"); add(0x00520006, "OCT Acquisition Domain", "CS"); add(0x00520007, "OCT Optical Center Wavelength", "FD"); add(0x00520008, "Axial Resolution", "FD"); add(0x00520009, "Ranging Depth", "FD"); add(0x00520011, "A-line Rate", "FD"); add(0x00520012, "A-lines Per Frame", "US"); add(0x00520013, "Catheter Rotational Rate", "FD"); add(0x00520014, "A-line Pixel Spacing", "FD"); add(0x00520016, "Mode of Percutaneous AccessSequence", "SQ"); add(0x00520025, "Intravascular OCT Frame TypeSequence", "SQ"); add(0x00520026, "OCT Z Offset Applied", "CS"); add(0x00520027, "Intravascular Frame ContentSequence", "SQ"); add(0x00520028, "Intravascular Longitudinal Distance", "FD"); add(0x00520029, "Intravascular OCT Frame ContentSequence", "SQ"); add(0x00520030, "OCT Z Offset Correction", "SS"); add(0x00520031, "Catheter Direction of Rotation", "CS"); add(0x00520033, "Seam Line Location", "FD"); add(0x00520034, "First A-line Location", "FD"); add(0x00520036, "Seam Line Index", "US"); add(0x00520038, "Number of Padded A-lines", "US"); add(0x00520039, "Interpolation Type", "CS"); add(0x0052003A, "Refractive Index Applied", "CS"); } /** * Adds attributes of group 0x0054. */ private void addAttributeGroup0054() { add(0x00540010, "Energy Window Vector", "US"); add(0x00540011, "Number of Energy Windows", "US"); add(0x00540012, "Energy Window InformationSequence", "SQ"); add(0x00540013, "Energy Window Range Sequence", "SQ"); add(0x00540014, "Energy Window Lower Limit", "DS"); add(0x00540015, "Energy Window Upper Limit", "DS"); add(0x00540016, "Radiopharmaceutical InformationSequence", "SQ"); add(0x00540017, "Residual Syringe Counts", "IS"); add(0x00540018, "Energy Window Name", "SH"); add(0x00540020, "Detector Vector", "US"); add(0x00540021, "Number of Detectors", "US"); add(0x00540022, "Detector Information Sequence", "SQ"); add(0x00540030, "Phase Vector", "US"); add(0x00540031, "Number of Phases", "US"); add(0x00540032, "Phase Information Sequence", "SQ"); add(0x00540033, "Number of Frames in Phase", "US"); add(0x00540036, "Phase Delay", "IS"); add(0x00540038, "Pause Between Frames", "IS"); add(0x00540039, "Phase Description", "CS"); add(0x00540050, "Rotation Vector", "US"); add(0x00540051, "Number of Rotations", "US"); add(0x00540052, "Rotation Information Sequence", "SQ"); add(0x00540053, "Number of Frames in Rotation", "US"); add(0x00540060, "R-R Interval Vector", "US"); add(0x00540061, "Number of R-R Intervals", "US"); add(0x00540062, "Gated Information Sequence", "SQ"); add(0x00540063, "Data Information Sequence", "SQ"); add(0x00540070, "Time Slot Vector", "US"); add(0x00540071, "Number of Time Slots", "US"); add(0x00540072, "Time Slot Information Sequence", "SQ"); add(0x00540073, "Time Slot Time", "DS"); add(0x00540080, "Slice Vector", "US"); add(0x00540081, "Number of Slices", "US"); add(0x00540090, "Angular View Vector", "US"); add(0x00540100, "Time Slice Vector", "US"); add(0x00540101, "Number of Time Slices", "US"); add(0x00540200, "Start Angle", "DS"); add(0x00540202, "Type of Detector Motion", "CS"); add(0x00540210, "Trigger Vector", "IS"); add(0x00540211, "Number of Triggers in Phase", "US"); add(0x00540220, "View Code Sequence", "SQ"); add(0x00540222, "View Modifier Code Sequence", "SQ"); add(0x00540300, "Radionuclide Code Sequence", "SQ"); add(0x00540302, "Administration Route CodeSequence", "SQ"); add(0x00540304, "Radiopharmaceutical CodeSequence", "SQ"); add(0x00540306, "Calibration Data Sequence", "SQ"); add(0x00540308, "Energy Window Number", "US"); add(0x00540400, "Image ID", "SH"); add(0x00540410, "Patient Orientation Code Sequence", "SQ"); add(0x00540412, "Patient Orientation Modifier CodeSequence", "SQ"); add(0x00540414, "Patient Gantry Relationship CodeSequence", "SQ"); add(0x00540500, "Slice Progression Direction", "CS"); add(0x00540501, "Scan Progression Direction", "CS"); add(0x00541000, "Series Type", "CS"); add(0x00541001, "Units", "CS"); add(0x00541002, "Counts Source", "CS"); add(0x00541004, "Reprojection Method", "CS"); add(0x00541006, "SUV Type", "CS"); add(0x00541100, "Randoms Correction Method", "CS"); add(0x00541101, "Attenuation Correction Method", "LO"); add(0x00541102, "Decay Correction", "CS"); add(0x00541103, "Reconstruction Method", "LO"); add(0x00541104, "Detector Lines of Response Used", "LO"); add(0x00541105, "Scatter Correction Method", "LO"); add(0x00541200, "Axial Acceptance", "DS"); add(0x00541201, "Axial Mash", "IS"); add(0x00541202, "Transverse Mash", "IS"); add(0x00541203, "Detector Element Size", "DS"); add(0x00541210, "Coincidence Window Width", "DS"); add(0x00541220, "Secondary Counts Type", "CS"); add(0x00541300, "Frame Reference Time", "DS"); add(0x00541310, "Primary (Prompts) CountsAccumulated", "IS"); add(0x00541311, "Secondary Counts Accumulated", "IS"); add(0x00541320, "Slice Sensitivity Factor", "DS"); add(0x00541321, "Decay Factor", "DS"); add(0x00541322, "Dose Calibration Factor", "DS"); add(0x00541323, "Scatter Fraction Factor", "DS"); add(0x00541324, "Dead Time Factor", "DS"); add(0x00541330, "Image Index", "US"); add(0x00541400, "Counts Included", "CS"); // Retired add(0x00541401, "Dead Time Correction Flag", "CS"); // Retired } /** * Adds attributes of group 0x0060. */ private void addAttributeGroup0060() { add(0x00603000, "Histogram Sequence", "SQ"); add(0x00603002, "Histogram Number of Bins", "US"); // add(0x00603004, "Histogram First Bin Value", "US or SS"); // add(0x00603006, "Histogram Last Bin Value", "US or SS"); add(0x00603008, "Histogram Bin Width", "US"); add(0x00603010, "Histogram Explanation", "LO"); add(0x00603020, "Histogram Data", "UL"); } /** * Adds attributes of group 0x0062. */ private void addAttributeGroup0062() { add(0x00620001, "Segmentation Type", "CS"); add(0x00620002, "Segment Sequence", "SQ"); add(0x00620003, "Segmented Property CategoryCode Sequence", "SQ"); add(0x00620004, "Segment Number", "US"); add(0x00620005, "Segment Label", "LO"); add(0x00620006, "Segment Description", "ST"); add(0x00620008, "Segment Algorithm Type", "CS"); add(0x00620009, "Segment Algorithm Name", "LO"); add(0x0062000A, "Segment Identification Sequence", "SQ"); add(0x0062000B, "Referenced Segment Number", "US"); add(0x0062000C, "Recommended Display GrayscaleValue", "US"); add(0x0062000D, "Recommended Display CIELabValue", "US"); add(0x0062000E, "Maximum Fractional Value", "US"); add(0x0062000F, "Segmented Property Type CodeSequence", "SQ"); add(0x00620010, "Segmentation Fractional Type", "CS"); add(0x00620011, "Segmented Property Type ModifierCode Sequence", "SQ"); add(0x00620012, "Used Segments Sequence", "SQ"); } /** * Adds attributes of group 0x0064. */ private void addAttributeGroup0064() { add(0x00640002, "Deformable Registration Sequence", "SQ"); add(0x00640003, "Source Frame of Reference UID", "UI"); add(0x00640005, "Deformable Registration GridSequence", "SQ"); add(0x00640007, "Grid Dimensions", "UL"); add(0x00640008, "Grid Resolution", "FD"); add(0x00640009, "Vector Grid Data", "OF"); add(0x0064000F, "Pre Deformation MatrixRegistration Sequence", "SQ"); add(0x00640010, "Post Deformation MatrixRegistration Sequence", "SQ"); } /** * Adds attributes of group 0x0066. */ private void addAttributeGroup0066() { add(0x00660001, "Number of Surfaces", "UL"); add(0x00660002, "Surface Sequence", "SQ"); add(0x00660003, "Surface Number", "UL"); add(0x00660004, "Surface Comments", "LT"); add(0x00660009, "Surface Processing", "CS"); add(0x0066000A, "Surface Processing Ratio", "FL"); add(0x0066000B, "Surface Processing Description", "LO"); add(0x0066000C, "Recommended PresentationOpacity", "FL"); add(0x0066000D, "Recommended Presentation Type", "CS"); add(0x0066000E, "Finite Volume", "CS"); add(0x00660010, "Manifold", "CS"); add(0x00660011, "Surface Points Sequence", "SQ"); add(0x00660012, "Surface Points Normals Sequence", "SQ"); add(0x00660013, "Surface Mesh Primitives Sequence", "SQ"); add(0x00660015, "Number of Surface Points", "UL"); add(0x00660016, "Point Coordinates Data", "OF"); add(0x00660017, "Point Position Accuracy", "FL"); add(0x00660018, "Mean Point Distance", "FL"); add(0x00660019, "Maximum Point Distance", "FL"); add(0x0066001A, "Points Bounding Box Coordinates", "FL"); add(0x0066001B, "Axis of Rotation", "FL"); add(0x0066001C, "Center of Rotation", "FL"); add(0x0066001E, "Number of Vectors", "UL"); add(0x0066001F, "Vector Dimensionality", "US"); add(0x00660020, "Vector Accuracy", "FL"); add(0x00660021, "Vector Coordinate Data", "OF"); add(0x00660023, "Triangle Point Index List", "OW"); add(0x00660024, "Edge Point Index List", "OW"); add(0x00660025, "Vertex Point Index List", "OW"); add(0x00660026, "Triangle Strip Sequence", "SQ"); add(0x00660027, "Triangle Fan Sequence", "SQ"); add(0x00660028, "Line Sequence", "SQ"); add(0x00660029, "Primitive Point Index List", "OW"); add(0x0066002A, "Surface Count", "UL"); add(0x0066002B, "Referenced Surface Sequence", "SQ"); add(0x0066002C, "Referenced Surface Number", "UL"); add(0x0066002D, "Segment Surface GenerationAlgorithm Identification Sequence", "SQ"); add(0x0066002E, "Segment Surface Source InstanceSequence", "SQ"); add(0x0066002F, "Algorithm Family Code Sequence", "SQ"); add(0x00660030, "Algorithm Name Code Sequence", "SQ"); add(0x00660031, "Algorithm Version", "LO"); add(0x00660032, "Algorithm Parameters", "LT"); add(0x00660034, "Facet Sequence", "SQ"); add(0x00660035, "Surface Processing AlgorithmIdentification Sequence", "SQ"); add(0x00660036, "Algorithm Name", "LO"); add(0x00660037, "Recommended Point Radius", "FL"); add(0x00660038, "Recommended Line Thickness", "FL"); add(0x00660040, "Long Primitive Point Index List", "UL"); add(0x00660041, "Long Triangle Point Index List", "UL"); add(0x00660042, "Long Edge Point Index List", "UL"); add(0x00660043, "Long Vertex Point Index List", "UL"); } /** * Adds attributes of group 0x0068. */ private void addAttributeGroup0068() { add(0x00686210, "Implant Size", "LO"); add(0x00686221, "Implant Template Version", "LO"); add(0x00686222, "Replaced Implant TemplateSequence", "SQ"); add(0x00686223, "Implant Type", "CS"); add(0x00686224, "Derivation Implant TemplateSequence", "SQ"); add(0x00686225, "Original Implant TemplateSequence", "SQ"); add(0x00686226, "Effective DateTime", "DT"); add(0x00686230, "Implant Target Anatomy Sequence", "SQ"); add(0x00686260, "Information From ManufacturerSequence", "SQ"); add(0x00686265, "Notification From ManufacturerSequence", "SQ"); add(0x00686270, "Information Issue DateTime", "DT"); add(0x00686280, "Information Summary", "ST"); add(0x006862A0, "Implant Regulatory DisapprovalCode Sequence", "SQ"); add(0x006862A5, "Overall Template Spatial Tolerance", "FD"); add(0x006862C0, "HPGL Document Sequence", "SQ"); add(0x006862D0, "HPGL Document ID", "US"); add(0x006862D5, "HPGL Document Label", "LO"); add(0x006862E0, "View Orientation Code Sequence", "SQ"); add(0x006862F0, "View Orientation Modifier", "FD"); add(0x006862F2, "HPGL Document Scaling", "FD"); add(0x00686300, "HPGL Document", "OB"); add(0x00686310, "HPGL Contour Pen Number", "US"); add(0x00686320, "HPGL Pen Sequence", "SQ"); add(0x00686330, "HPGL Pen Number", "US"); add(0x00686340, "HPGL Pen Label", "LO"); add(0x00686345, "HPGL Pen Description", "ST"); add(0x00686346, "Recommended Rotation Point", "FD"); add(0x00686347, "Bounding Rectangle", "FD"); add(0x00686350, "Implant Template 3D ModelSurface Number", "US"); add(0x00686360, "Surface Model DescriptionSequence", "SQ"); add(0x00686380, "Surface Model Label", "LO"); add(0x00686390, "Surface Model Scaling Factor", "FD"); add(0x006863A0, "Materials Code Sequence", "SQ"); add(0x006863A4, "Coating Materials Code Sequence", "SQ"); add(0x006863A8, "Implant Type Code Sequence", "SQ"); add(0x006863AC, "Fixation Method Code Sequence", "SQ"); add(0x006863B0, "Mating Feature Sets Sequence", "SQ"); add(0x006863C0, "Mating Feature Set ID", "US"); add(0x006863D0, "Mating Feature Set Label", "LO"); add(0x006863E0, "Mating Feature Sequence", "SQ"); add(0x006863F0, "Mating Feature ID", "US"); add(0x00686400, "Mating Feature Degree of FreedomSequence", "SQ"); add(0x00686410, "Degree of Freedom ID", "US"); add(0x00686420, "Degree of Freedom Type", "CS"); add(0x00686430, "2D Mating Feature CoordinatesSequence", "SQ"); add(0x00686440, "Referenced HPGL Document ID", "US"); add(0x00686450, "2D Mating Point", "FD"); add(0x00686460, "2D Mating Axes", "FD"); add(0x00686470, "2D Degree of Freedom Sequence", "SQ"); add(0x00686490, "3D Degree of Freedom Axis", "FD"); add(0x006864A0, "Range of Freedom", "FD"); add(0x006864C0, "3D Mating Point", "FD"); add(0x006864D0, "3D Mating Axes", "FD"); add(0x006864F0, "2D Degree of Freedom Axis", "FD"); add(0x00686500, "Planning Landmark PointSequence", "SQ"); add(0x00686510, "Planning Landmark Line Sequence", "SQ"); add(0x00686520, "Planning Landmark PlaneSequence", "SQ"); add(0x00686530, "Planning Landmark ID", "US"); add(0x00686540, "Planning Landmark Description", "LO"); add(0x00686545, "Planning Landmark IdentificationCode Sequence", "SQ"); add(0x00686550, "2D Point Coordinates Sequence", "SQ"); add(0x00686560, "2D Point Coordinates", "FD"); add(0x00686590, "3D Point Coordinates", "FD"); add(0x006865A0, "2D Line Coordinates Sequence", "SQ"); add(0x006865B0, "2D Line Coordinates", "FD"); add(0x006865D0, "3D Line Coordinates", "FD"); add(0x006865E0, "2D Plane Coordinates Sequence", "SQ"); add(0x006865F0, "2D Plane Intersection", "FD"); add(0x00686610, "3D Plane Origin", "FD"); add(0x00686620, "3D Plane Normal", "FD"); } /** * Adds attributes of group 0x0070. */ private void addAttributeGroup0070() { add(0x00700001, "Graphic Annotation Sequence", "SQ"); add(0x00700002, "Graphic Layer", "CS"); add(0x00700003, "Bounding Box Annotation Units", "CS"); add(0x00700004, "Anchor Point Annotation Units", "CS"); add(0x00700005, "Graphic Annotation Units", "CS"); add(0x00700006, "Unformatted Text Value", "ST"); add(0x00700008, "Text Object Sequence", "SQ"); add(0x00700009, "Graphic Object Sequence", "SQ"); add(0x00700010, "Bounding Box Top Left HandCorner", "FL"); add(0x00700011, "Bounding Box Bottom Right HandCorner", "FL"); add(0x00700012, "Bounding Box Text HorizontalJustification", "CS"); add(0x00700014, "Anchor Point", "FL"); add(0x00700015, "Anchor Point Visibility", "CS"); add(0x00700020, "Graphic Dimensions", "US"); add(0x00700021, "Number of Graphic Points", "US"); add(0x00700022, "Graphic Data", "FL"); add(0x00700023, "Graphic Type", "CS"); add(0x00700024, "Graphic Filled", "CS"); add(0x00700040, "Image Rotation (Retired)", "IS"); // Retired add(0x00700041, "Image Horizontal Flip", "CS"); add(0x00700042, "Image Rotation", "US"); add(0x00700050, "Displayed Area Top Left HandCorner (Trial)", "US"); // Retired add(0x00700051, "Displayed Area Bottom Right HandCorner (Trial)", "US"); // Retired add(0x00700052, "Displayed Area Top Left HandCorner", "SL"); add(0x00700053, "Displayed Area Bottom Right HandCorner", "SL"); add(0x0070005A, "Displayed Area SelectionSequence", "SQ"); add(0x00700060, "Graphic Layer Sequence", "SQ"); add(0x00700062, "Graphic Layer Order", "IS"); add(0x00700066, "Graphic Layer RecommendedDisplay Grayscale Value", "US"); add(0x00700067, "Graphic Layer RecommendedDisplay RGB Value", "US"); // Retired add(0x00700068, "Graphic Layer Description", "LO"); add(0x00700080, "Content Label", "CS"); add(0x00700081, "Content Description", "LO"); add(0x00700082, "Presentation Creation Date", "DA"); add(0x00700083, "Presentation Creation Time", "TM"); add(0x00700084, "Content Creator's Name", "PN"); add(0x00700086, "Content Creator's IdentificationCode Sequence", "SQ"); add(0x00700087, "Alternate Content DescriptionSequence", "SQ"); add(0x00700100, "Presentation Size Mode", "CS"); add(0x00700101, "Presentation Pixel Spacing", "DS"); add(0x00700102, "Presentation Pixel Aspect Ratio", "IS"); add(0x00700103, "Presentation Pixel MagnificationRatio", "FL"); add(0x00700207, "Graphic Group Label", "LO"); add(0x00700208, "Graphic Group Description", "ST"); add(0x00700209, "Compound Graphic Sequence", "SQ"); add(0x00700226, "Compound Graphic Instance ID", "UL"); add(0x00700227, "Font Name", "LO"); add(0x00700228, "Font Name Type", "CS"); add(0x00700229, "CSS Font Name", "LO"); add(0x00700230, "Rotation Angle", "FD"); add(0x00700231, "Text Style Sequence", "SQ"); add(0x00700232, "Line Style Sequence", "SQ"); add(0x00700233, "Fill Style Sequence", "SQ"); add(0x00700234, "Graphic Group Sequence", "SQ"); add(0x00700241, "Text Color CIELab Value", "US"); add(0x00700242, "Horizontal Alignment", "CS"); add(0x00700243, "Vertical Alignment", "CS"); add(0x00700244, "Shadow Style", "CS"); add(0x00700245, "Shadow Offset X", "FL"); add(0x00700246, "Shadow Offset Y", "FL"); add(0x00700247, "Shadow Color CIELab Value", "US"); add(0x00700248, "Underlined", "CS"); add(0x00700249, "Bold", "CS"); add(0x00700250, "Italic", "CS"); add(0x00700251, "Pattern On Color CIELab Value", "US"); add(0x00700252, "Pattern Off Color CIELab Value", "US"); add(0x00700253, "Line Thickness", "FL"); add(0x00700254, "Line Dashing Style", "CS"); add(0x00700255, "Line Pattern", "UL"); add(0x00700256, "Fill Pattern", "OB"); add(0x00700257, "Fill Mode", "CS"); add(0x00700258, "Shadow Opacity", "FL"); add(0x00700261, "Gap Length", "FL"); add(0x00700262, "Diameter of Visibility", "FL"); add(0x00700273, "Rotation Point", "FL"); add(0x00700274, "Tick Alignment", "CS"); add(0x00700278, "Show Tick Label", "CS"); add(0x00700279, "Tick Label Alignment", "CS"); add(0x00700282, "Compound Graphic Units", "CS"); add(0x00700284, "Pattern On Opacity", "FL"); add(0x00700285, "Pattern Off Opacity", "FL"); add(0x00700287, "Major Ticks Sequence", "SQ"); add(0x00700288, "Tick Position", "FL"); add(0x00700289, "Tick Label", "SH"); add(0x00700294, "Compound Graphic Type", "CS"); add(0x00700295, "Graphic Group ID", "UL"); add(0x00700306, "Shape Type", "CS"); add(0x00700308, "Registration Sequence", "SQ"); add(0x00700309, "Matrix Registration Sequence", "SQ"); add(0x0070030A, "Matrix Sequence", "SQ"); add(0x0070030C, "Frame of ReferenceTransformation Matrix Type", "CS"); add(0x0070030D, "Registration Type Code Sequence", "SQ"); add(0x0070030F, "Fiducial Description", "ST"); add(0x00700310, "Fiducial Identifier", "SH"); add(0x00700311, "Fiducial Identifier Code Sequence", "SQ"); add(0x00700312, "Contour Uncertainty Radius", "FD"); add(0x00700314, "Used Fiducials Sequence", "SQ"); add(0x00700318, "Graphic Coordinates DataSequence", "SQ"); add(0x0070031A, "Fiducial UID", "UI"); add(0x0070031C, "Fiducial Set Sequence", "SQ"); add(0x0070031E, "Fiducial Sequence", "SQ"); add(0x00700401, "Graphic Layer RecommendedDisplay CIELab Value", "US"); add(0x00700402, "Blending Sequence", "SQ"); add(0x00700403, "Relative Opacity", "FL"); add(0x00700404, "Referenced Spatial RegistrationSequence", "SQ"); add(0x00700405, "Blending Position", "CS"); } /** * Adds attributes of group 0x0072. */ private void addAttributeGroup0072() { add(0x00720002, "Hanging Protocol Name", "SH"); add(0x00720004, "Hanging Protocol Description", "LO"); add(0x00720006, "Hanging Protocol Level", "CS"); add(0x00720008, "Hanging Protocol Creator", "LO"); add(0x0072000A, "Hanging Protocol CreationDateTime", "DT"); add(0x0072000C, "Hanging Protocol DefinitionSequence", "SQ"); add(0x0072000E, "Hanging Protocol UserIdentification Code Sequence", "SQ"); add(0x00720010, "Hanging Protocol User GroupName", "LO"); add(0x00720012, "Source Hanging ProtocolSequence", "SQ"); add(0x00720014, "Number of Priors Referenced", "US"); add(0x00720020, "Image Sets Sequence", "SQ"); add(0x00720022, "Image Set Selector Sequence", "SQ"); add(0x00720024, "Image Set Selector Usage Flag", "CS"); add(0x00720026, "Selector Attribute", "AT"); add(0x00720028, "Selector Value Number", "US"); add(0x00720030, "Time Based Image Sets Sequence", "SQ"); add(0x00720032, "Image Set Number", "US"); add(0x00720034, "Image Set Selector Category", "CS"); add(0x00720038, "Relative Time", "US"); add(0x0072003A, "Relative Time Units", "CS"); add(0x0072003C, "Abstract Prior Value", "SS"); add(0x0072003E, "Abstract Prior Code Sequence", "SQ"); add(0x00720040, "Image Set Label", "LO"); add(0x00720050, "Selector Attribute VR", "CS"); add(0x00720052, "Selector Sequence Pointer", "AT"); add(0x00720054, "Selector Sequence Pointer PrivateCreator", "LO"); add(0x00720056, "Selector Attribute Private Creator", "LO"); add(0x00720060, "Selector AT Value", "AT"); add(0x00720062, "Selector CS Value", "CS"); add(0x00720064, "Selector IS Value", "IS"); add(0x00720066, "Selector LO Value", "LO"); add(0x00720068, "Selector LT Value", "LT"); add(0x0072006A, "Selector PN Value", "PN"); add(0x0072006C, "Selector SH Value", "SH"); add(0x0072006E, "Selector ST Value", "ST"); add(0x00720070, "Selector UT Value", "UT"); add(0x00720072, "Selector DS Value", "DS"); add(0x00720074, "Selector FD Value", "FD"); add(0x00720076, "Selector FL Value", "FL"); add(0x00720078, "Selector UL Value", "UL"); add(0x0072007A, "Selector US Value", "US"); add(0x0072007C, "Selector SL Value", "SL"); add(0x0072007E, "Selector SS Value", "SS"); add(0x0072007F, "Selector UI Value", "UI"); add(0x00720080, "Selector Code Sequence Value", "SQ"); add(0x00720100, "Number of Screens", "US"); add(0x00720102, "Nominal Screen DefinitionSequence", "SQ"); add(0x00720104, "Number of Vertical Pixels", "US"); add(0x00720106, "Number of Horizontal Pixels", "US"); add(0x00720108, "Display Environment SpatialPosition", "FD"); add(0x0072010A, "Screen Minimum Grayscale BitDepth", "US"); add(0x0072010C, "Screen Minimum Color Bit Depth", "US"); add(0x0072010E, "Application Maximum Repaint Time", "US"); add(0x00720200, "Display Sets Sequence", "SQ"); add(0x00720202, "Display Set Number", "US"); add(0x00720203, "Display Set Label", "LO"); add(0x00720204, "Display Set Presentation Group", "US"); add(0x00720206, "Display Set Presentation GroupDescription", "LO"); add(0x00720208, "Partial Data Display Handling", "CS"); add(0x00720210, "Synchronized Scrolling Sequence", "SQ"); add(0x00720212, "Display Set Scrolling Group", "US"); add(0x00720214, "Navigation Indicator Sequence", "SQ"); add(0x00720216, "Navigation Display Set", "US"); add(0x00720218, "Reference Display Sets", "US"); add(0x00720300, "Image Boxes Sequence", "SQ"); add(0x00720302, "Image Box Number", "US"); add(0x00720304, "Image Box Layout Type", "CS"); add(0x00720306, "Image Box Tile HorizontalDimension", "US"); add(0x00720308, "Image Box Tile Vertical Dimension", "US"); add(0x00720310, "Image Box Scroll Direction", "CS"); add(0x00720312, "Image Box Small Scroll Type", "CS"); add(0x00720314, "Image Box Small Scroll Amount", "US"); add(0x00720316, "Image Box Large Scroll Type", "CS"); add(0x00720318, "Image Box Large Scroll Amount", "US"); add(0x00720320, "Image Box Overlap Priority", "US"); add(0x00720330, "Cine Relative to Real-Time", "FD"); add(0x00720400, "Filter Operations Sequence", "SQ"); add(0x00720402, "Filter-by Category", "CS"); add(0x00720404, "Filter-by Attribute Presence", "CS"); add(0x00720406, "Filter-by Operator", "CS"); add(0x00720420, "Structured Display BackgroundCIELab Value", "US"); add(0x00720421, "Empty Image Box CIELab Value", "US"); add(0x00720422, "Structured Display Image BoxSequence", "SQ"); add(0x00720424, "Structured Display Text BoxSequence", "SQ"); add(0x00720427, "Referenced First Frame Sequence", "SQ"); add(0x00720430, "Image Box SynchronizationSequence", "SQ"); add(0x00720432, "Synchronized Image Box List", "US"); add(0x00720434, "Type of Synchronization", "CS"); add(0x00720500, "Blending Operation Type", "CS"); add(0x00720510, "Reformatting Operation Type", "CS"); add(0x00720512, "Reformatting Thickness", "FD"); add(0x00720514, "Reformatting Interval", "FD"); add(0x00720516, "Reformatting Operation Initial ViewDirection", "CS"); add(0x00720520, "3D Rendering Type", "CS"); add(0x00720600, "Sorting Operations Sequence", "SQ"); add(0x00720602, "Sort-by Category", "CS"); add(0x00720604, "Sorting Direction", "CS"); add(0x00720700, "Display Set Patient Orientation", "CS"); add(0x00720702, "VOI Type", "CS"); add(0x00720704, "Pseudo-Color Type", "CS"); add(0x00720705, "Pseudo-Color Palette InstanceReference Sequence", "SQ"); add(0x00720706, "Show Grayscale Inverted", "CS"); add(0x00720710, "Show Image True Size Flag", "CS"); add(0x00720712, "Show Graphic Annotation Flag", "CS"); add(0x00720714, "Show Patient Demographics Flag", "CS"); add(0x00720716, "Show Acquisition Techniques Flag", "CS"); add(0x00720717, "Display Set Horizontal Justification", "CS"); add(0x00720718, "Display Set Vertical Justification", "CS"); } /** * Adds attributes of group 0x0074. */ private void addAttributeGroup0074() { add(0x00740120, "Continuation Start Meterset", "FD"); add(0x00740121, "Continuation End Meterset", "FD"); add(0x00741000, "Procedure Step State", "CS"); add(0x00741002, "Procedure Step ProgressInformation Sequence", "SQ"); add(0x00741004, "Procedure Step Progress", "DS"); add(0x00741006, "Procedure Step ProgressDescription", "ST"); add(0x00741008, "Procedure Step CommunicationsURI Sequence", "SQ"); add(0x0074100A, "Contact URI", "UR"); add(0x0074100C, "Contact Display Name", "LO"); add(0x0074100E, "Procedure Step DiscontinuationReason Code Sequence", "SQ"); add(0x00741020, "Beam Task Sequence", "SQ"); add(0x00741022, "Beam Task Type", "CS"); add(0x00741024, "Beam Order Index (Trial)", "IS"); // Retired add(0x00741025, "Autosequence Flag", "CS"); add(0x00741026, "Table Top Vertical AdjustedPosition", "FD"); add(0x00741027, "Table Top Longitudinal AdjustedPosition", "FD"); add(0x00741028, "Table Top Lateral AdjustedPosition", "FD"); add(0x0074102A, "Patient Support Adjusted Angle", "FD"); add(0x0074102B, "Table Top Eccentric AdjustedAngle", "FD"); add(0x0074102C, "Table Top Pitch Adjusted Angle", "FD"); add(0x0074102D, "Table Top Roll Adjusted Angle", "FD"); add(0x00741030, "Delivery Verification ImageSequence", "SQ"); add(0x00741032, "Verification Image Timing", "CS"); add(0x00741034, "Double Exposure Flag", "CS"); add(0x00741036, "Double Exposure Ordering", "CS"); add(0x00741038, "Double Exposure Meterset (Trial)", "DS"); // Retired add(0x0074103A, "Double Exposure Field Delta (Trial)", "DS"); // Retired add(0x00741040, "Related Reference RT ImageSequence", "SQ"); add(0x00741042, "General Machine VerificationSequence", "SQ"); add(0x00741044, "Conventional Machine VerificationSequence", "SQ"); add(0x00741046, "Ion Machine Verification Sequence", "SQ"); add(0x00741048, "Failed Attributes Sequence", "SQ"); add(0x0074104A, "Overridden Attributes Sequence", "SQ"); add(0x0074104C, "Conventional Control PointVerification Sequence", "SQ"); add(0x0074104E, "Ion Control Point VerificationSequence", "SQ"); add(0x00741050, "Attribute Occurrence Sequence", "SQ"); add(0x00741052, "Attribute Occurrence Pointer", "AT"); add(0x00741054, "Attribute Item Selector", "UL"); add(0x00741056, "Attribute Occurrence PrivateCreator", "LO"); add(0x00741057, "Selector Sequence Pointer Items", "IS"); add(0x00741200, "Scheduled Procedure Step Priority", "CS"); add(0x00741202, "Worklist Label", "LO"); add(0x00741204, "Procedure Step Label", "LO"); add(0x00741210, "Scheduled Processing ParametersSequence", "SQ"); add(0x00741212, "Performed Processing ParametersSequence", "SQ"); add(0x00741216, "Unified Procedure Step PerformedProcedure Sequence", "SQ"); add(0x00741220, "Related Procedure Step Sequence", "SQ"); // Retired add(0x00741222, "Procedure Step Relationship Type", "LO"); // Retired add(0x00741224, "Replaced Procedure StepSequence", "SQ"); add(0x00741230, "Deletion Lock", "LO"); add(0x00741234, "Receiving AE", "AE"); add(0x00741236, "Requesting AE", "AE"); add(0x00741238, "Reason for Cancellation", "LT"); add(0x00741242, "SCP Status", "CS"); add(0x00741244, "Subscription List Status", "CS"); add(0x00741246, "Unified Procedure Step List Status", "CS"); add(0x00741324, "Beam Order Index", "UL"); add(0x00741338, "Double Exposure Meterset", "FD"); add(0x0074133A, "Double Exposure Field Delta", "FD"); } /** * Adds attributes of group 0x0076. */ private void addAttributeGroup0076() { add(0x00760001, "Implant Assembly Template Name", "LO"); add(0x00760003, "Implant Assembly Template Issuer", "LO"); add(0x00760006, "Implant Assembly TemplateVersion", "LO"); add(0x00760008, "Replaced Implant AssemblyTemplate Sequence", "SQ"); add(0x0076000A, "Implant Assembly Template Type", "CS"); add(0x0076000C, "Original Implant AssemblyTemplate Sequence", "SQ"); add(0x0076000E, "Derivation Implant AssemblyTemplate Sequence", "SQ"); add(0x00760010, "Implant Assembly Template TargetAnatomy Sequence", "SQ"); add(0x00760020, "Procedure Type Code Sequence", "SQ"); add(0x00760030, "Surgical Technique", "LO"); add(0x00760032, "Component Types Sequence", "SQ"); add(0x00760034, "Component Type Code Sequence", "CS"); add(0x00760036, "Exclusive Component Type", "CS"); add(0x00760038, "Mandatory Component Type", "CS"); add(0x00760040, "Component Sequence", "SQ"); add(0x00760055, "Component ID", "US"); add(0x00760060, "Component Assembly Sequence", "SQ"); add(0x00760070, "Component 1 Referenced ID", "US"); add(0x00760080, "Component 1 Referenced MatingFeature Set ID", "US"); add(0x00760090, "Component 1 Referenced MatingFeature ID", "US"); add(0x007600A0, "Component 2 Referenced ID", "US"); add(0x007600B0, "Component 2 Referenced MatingFeature Set ID", "US"); add(0x007600C0, "Component 2 Referenced MatingFeature ID", "US"); } /** * Adds attributes of group 0x0078. */ private void addAttributeGroup0078() { add(0x00780001, "Implant Template Group Name", "LO"); add(0x00780010, "Implant Template GroupDescription", "ST"); add(0x00780020, "Implant Template Group Issuer", "LO"); add(0x00780024, "Implant Template Group Version", "LO"); add(0x00780026, "Replaced Implant Template GroupSequence", "SQ"); add(0x00780028, "Implant Template Group TargetAnatomy Sequence", "SQ"); add(0x0078002A, "Implant Template Group MembersSequence", "SQ"); add(0x0078002E, "Implant Template Group MemberID", "US"); add(0x00780050, "3D Implant Template GroupMember Matching Point", "FD"); add(0x00780060, "3D Implant Template GroupMember Matching Axes", "FD"); add(0x00780070, "Implant Template Group MemberMatching 2D CoordinatesSequence", "SQ"); add(0x00780090, "2D Implant Template GroupMember Matching Point", "FD"); add(0x007800A0, "2D Implant Template GroupMember Matching Axes", "FD"); add(0x007800B0, "Implant Template Group VariationDimension Sequence", "SQ"); add(0x007800B2, "Implant Template Group VariationDimension Name", "LO"); add(0x007800B4, "Implant Template Group VariationDimension Rank Sequence", "SQ"); add(0x007800B6, "Referenced Implant TemplateGroup Member ID", "US"); add(0x007800B8, "Implant Template Group VariationDimension Rank", "US"); } /** * Adds attributes of group 0x0080. */ private void addAttributeGroup0080() { add(0x00800001, "Surface Scan Acquisition TypeCode Sequence", "SQ"); add(0x00800002, "Surface Scan Mode CodeSequence", "SQ"); add(0x00800003, "Registration Method CodeSequence", "SQ"); add(0x00800004, "Shot Duration Time", "FD"); add(0x00800005, "Shot Offset Time", "FD"); add(0x00800006, "Surface Point Presentation ValueData", "US"); add(0x00800007, "Surface Point Color CIELab ValueData", "US"); add(0x00800008, "UV Mapping Sequence", "SQ"); add(0x00800009, "Texture Label", "SH"); add(0x00800010, "U Value Data", "OF"); add(0x00800011, "V Value Data", "OF"); add(0x00800012, "Referenced Texture Sequence", "SQ"); add(0x00800013, "Referenced Surface DataSequence", "SQ"); } /** * Adds attributes of group 0x0088. */ private void addAttributeGroup0088() { add(0x00880130, "Storage Media File-set ID", "SH"); add(0x00880140, "Storage Media File-set UID", "UI"); add(0x00880200, "Icon Image Sequence", "SQ"); add(0x00880904, "Topic Title", "LO"); // Retired add(0x00880906, "Topic Subject", "ST"); // Retired add(0x00880910, "Topic Author", "LO"); // Retired add(0x00880912, "Topic Keywords", "LO"); // Retired } /** * Adds attributes of group 0x0100. */ private void addAttributeGroup0100() { add(0x01000410, "SOP Instance Status", "CS"); add(0x01000420, "SOP Authorization DateTime", "DT"); add(0x01000424, "SOP Authorization Comment", "LT"); add(0x01000426, "Authorization EquipmentCertification Number", "LO"); } /** * Adds attributes of group 0x0400. */ private void addAttributeGroup0400() { add(0x04000005, "MAC ID Number", "US"); add(0x04000010, "MAC Calculation Transfer SyntaxUID", "UI"); add(0x04000015, "MAC Algorithm", "CS"); add(0x04000020, "Data Elements Signed", "AT"); add(0x04000100, "Digital Signature UID", "UI"); add(0x04000105, "Digital Signature DateTime", "DT"); add(0x04000110, "Certificate Type", "CS"); add(0x04000115, "Certificate of Signer", "OB"); add(0x04000120, "Signature", "OB"); add(0x04000305, "Certified Timestamp Type", "CS"); add(0x04000310, "Certified Timestamp", "OB"); add(0x04000401, "Digital Signature Purpose CodeSequence", "SQ"); add(0x04000402, "Referenced Digital SignatureSequence", "SQ"); add(0x04000403, "Referenced SOP Instance MACSequence", "SQ"); add(0x04000404, "MAC", "OB"); add(0x04000500, "Encrypted Attributes Sequence", "SQ"); add(0x04000510, "Encrypted Content Transfer SyntaxUID", "UI"); add(0x04000520, "Encrypted Content", "OB"); add(0x04000550, "Modified Attributes Sequence", "SQ"); add(0x04000561, "Original Attributes Sequence", "SQ"); add(0x04000562, "Attribute Modification DateTime", "DT"); add(0x04000563, "Modifying System", "LO"); add(0x04000564, "Source of Previous Values", "LO"); add(0x04000565, "Reason for the AttributeModification", "CS"); } /** * Adds attributes of group 0x2000. */ private void addAttributeGroup2000() { add(0x20000010, "Number of Copies", "IS"); add(0x2000001E, "Printer Configuration Sequence", "SQ"); add(0x20000020, "Print Priority", "CS"); add(0x20000030, "Medium Type", "CS"); add(0x20000040, "Film Destination", "CS"); add(0x20000050, "Film Session Label", "LO"); add(0x20000060, "Memory Allocation", "IS"); add(0x20000061, "Maximum Memory Allocation", "IS"); add(0x20000062, "Color Image Printing Flag", "CS"); // Retired add(0x20000063, "Collation Flag", "CS"); // Retired add(0x20000065, "Annotation Flag", "CS"); // Retired add(0x20000067, "Image Overlay Flag", "CS"); // Retired add(0x20000069, "Presentation LUT Flag", "CS"); // Retired add(0x2000006A, "Image Box Presentation LUT Flag", "CS"); // Retired add(0x200000A0, "Memory Bit Depth", "US"); add(0x200000A1, "Printing Bit Depth", "US"); add(0x200000A2, "Media Installed Sequence", "SQ"); add(0x200000A4, "Other Media Available Sequence", "SQ"); add(0x200000A8, "Supported Image Display FormatsSequence", "SQ"); add(0x20000500, "Referenced Film Box Sequence", "SQ"); add(0x20000510, "Referenced Stored Print Sequence", "SQ"); // Retired } /** * Adds attributes of group 0x2010. */ private void addAttributeGroup2010() { add(0x20100010, "Image Display Format", "ST"); add(0x20100030, "Annotation Display Format ID", "CS"); add(0x20100040, "Film Orientation", "CS"); add(0x20100050, "Film Size ID", "CS"); add(0x20100052, "Printer Resolution ID", "CS"); add(0x20100054, "Default Printer Resolution ID", "CS"); add(0x20100060, "Magnification Type", "CS"); add(0x20100080, "Smoothing Type", "CS"); add(0x201000A6, "Default Magnification Type", "CS"); add(0x201000A7, "Other Magnification TypesAvailable", "CS"); add(0x201000A8, "Default Smoothing Type", "CS"); add(0x201000A9, "Other Smoothing Types Available", "CS"); add(0x20100100, "Border Density", "CS"); add(0x20100110, "Empty Image Density", "CS"); add(0x20100120, "Min Density", "US"); add(0x20100130, "Max Density", "US"); add(0x20100140, "Trim", "CS"); add(0x20100150, "Configuration Information", "ST"); add(0x20100152, "Configuration InformationDescription", "LT"); add(0x20100154, "Maximum Collated Films", "IS"); add(0x2010015E, "Illumination", "US"); add(0x20100160, "Reflected Ambient Light", "US"); add(0x20100376, "Printer Pixel Spacing", "DS"); add(0x20100500, "Referenced Film SessionSequence", "SQ"); add(0x20100510, "Referenced Image Box Sequence", "SQ"); add(0x20100520, "Referenced Basic Annotation BoxSequence", "SQ"); } /** * Adds attributes of group 0x2020. */ private void addAttributeGroup2020() { add(0x20200010, "Image Box Position", "US"); add(0x20200020, "Polarity", "CS"); add(0x20200030, "Requested Image Size", "DS"); add(0x20200040, "Requested Decimate/CropBehavior", "CS"); add(0x20200050, "Requested Resolution ID", "CS"); add(0x202000A0, "Requested Image Size Flag", "CS"); add(0x202000A2, "Decimate/Crop Result", "CS"); add(0x20200110, "Basic Grayscale Image Sequence", "SQ"); add(0x20200111, "Basic Color Image Sequence", "SQ"); add(0x20200130, "Referenced Image Overlay BoxSequence", "SQ"); // Retired add(0x20200140, "Referenced VOI LUT BoxSequence", "SQ"); // Retired1 } /** * Adds attributes of group 0x2030. */ private void addAttributeGroup2030() { add(0x20300010, "Annotation Position", "US"); add(0x20300020, "Text String", "LO"); } /** * Adds attributes of group 0x2040. */ private void addAttributeGroup2040() { add(0x20400010, "Referenced Overlay PlaneSequence", "SQ"); // Retired add(0x20400011, "Referenced Overlay Plane Groups", "US"); // Retired add(0x20400020, "Overlay Pixel Data Sequence", "SQ"); // Retired add(0x20400060, "Overlay Magnification Type", "CS"); // Retired add(0x20400070, "Overlay Smoothing Type", "CS"); // Retired // add(0x20400072, "Overlay or Image Magnification", "CS"); //Retired add(0x20400074, "Magnify to Number of Columns", "US"); // Retired add(0x20400080, "Overlay Foreground Density", "CS"); // Retired add(0x20400082, "Overlay Background Density", "CS"); // Retired add(0x20400090, "Overlay Mode", "CS"); // Retired add(0x20400100, "Threshold Density", "CS"); // Retired add(0x20400500, "Referenced Image Box Sequence(Retired)", "SQ"); // Retired } /** * Adds attributes of group 0x2050. */ private void addAttributeGroup2050() { add(0x20500010, "Presentation LUT Sequence", "SQ"); add(0x20500020, "Presentation LUT Shape", "CS"); add(0x20500500, "Referenced Presentation LUTSequence", "SQ"); } /** * Adds attributes of group 0x2100. */ private void addAttributeGroup2100() { add(0x21000010, "Print Job ID", "SH"); // Retired add(0x21000020, "Execution Status", "CS"); add(0x21000030, "Execution Status Info", "CS"); add(0x21000040, "Creation Date", "DA"); add(0x21000050, "Creation Time", "TM"); add(0x21000070, "Originator", "AE"); add(0x21000140, "Destination AE", "AE"); // Retired add(0x21000160, "Owner ID", "SH"); add(0x21000170, "Number of Films", "IS"); add(0x21000500, "Referenced Print Job Sequence(Pull Stored Print)", "SQ"); // Retired } /** * Adds attributes of group 0x2110. */ private void addAttributeGroup2110() { add(0x21100010, "Printer Status", "CS"); add(0x21100020, "Printer Status Info", "CS"); add(0x21100030, "Printer Name", "LO"); add(0x21100099, "Print Queue ID", "SH"); // Retired } /** * Adds attributes of group 0x2120. */ private void addAttributeGroup2120() { add(0x21200010, "Queue Status", "CS"); // Retired add(0x21200050, "Print Job Description Sequence", "SQ"); // Retired add(0x21200070, "Referenced Print Job Sequence", "SQ"); // Retired } /** * Adds attributes of group 0x2130. */ private void addAttributeGroup2130() { add(0x21300010, "Print Management CapabilitiesSequence", "SQ"); // Retired add(0x21300015, "Printer Characteristics Sequence", "SQ"); // Retired add(0x21300030, "Film Box Content Sequence", "SQ"); // Retired add(0x21300040, "Image Box Content Sequence", "SQ"); // Retired add(0x21300050, "Annotation Content Sequence", "SQ"); // Retired add(0x21300060, "Image Overlay Box ContentSequence", "SQ"); // Retired add(0x21300080, "Presentation LUT ContentSequence", "SQ"); // Retired add(0x213000A0, "Proposed Study Sequence", "SQ"); // Retired add(0x213000C0, "Original Image Sequence", "SQ"); // Retired } /** * Adds attributes of group 0x2200. */ private void addAttributeGroup2200() { add(0x22000001, "Label Using Information ExtractedFrom Instances", "CS"); add(0x22000002, "Label Text", "UT"); add(0x22000003, "Label Style Selection", "CS"); add(0x22000004, "Media Disposition", "LT"); add(0x22000005, "Barcode Value", "LT"); add(0x22000006, "Barcode Symbology", "CS"); add(0x22000007, "Allow Media Splitting", "CS"); add(0x22000008, "Include Non-DICOM Objects", "CS"); add(0x22000009, "Include Display Application", "CS"); add(0x2200000A, "Preserve Composite InstancesAfter Media Creation", "CS"); add(0x2200000B, "Total Number of Pieces of MediaCreated", "US"); add(0x2200000C, "Requested Media ApplicationProfile", "LO"); add(0x2200000D, "Referenced Storage MediaSequence", "SQ"); add(0x2200000E, "Failure Attributes FailureAttributes AT 1-n(2200,000F) Allow Lossy Compression", "CS"); add(0x22000020, "Request Priority", "CS"); } /** * Adds attributes of group 0x3002. */ private void addAttributeGroup3002() { add(0x30020002, "RT Image Label", "SH"); add(0x30020003, "RT Image Name", "LO"); add(0x30020004, "RT Image Description", "ST"); add(0x3002000A, "Reported Values Origin", "CS"); add(0x3002000C, "RT Image Plane", "CS"); add(0x3002000D, "X-Ray Image Receptor Translation", "DS"); add(0x3002000E, "X-Ray Image Receptor Angle", "DS"); add(0x30020010, "RT Image Orientation", "DS"); add(0x30020011, "Image Plane Pixel Spacing", "DS"); add(0x30020012, "RT Image Position", "DS"); add(0x30020020, "Radiation Machine Name", "SH"); add(0x30020022, "Radiation Machine SAD", "DS"); add(0x30020024, "Radiation Machine SSD", "DS"); add(0x30020026, "RT Image SID", "DS"); add(0x30020028, "Source to Reference ObjectDistance", "DS"); add(0x30020029, "Fraction Number", "IS"); add(0x30020030, "Exposure Sequence", "SQ"); add(0x30020032, "Meterset Exposure", "DS"); add(0x30020034, "Diaphragm Position", "DS"); add(0x30020040, "Fluence Map Sequence", "SQ"); add(0x30020041, "Fluence Data Source", "CS"); add(0x30020042, "Fluence Data Scale", "DS"); add(0x30020050, "Primary Fluence Mode Sequence", "SQ"); add(0x30020051, "Fluence Mode", "CS"); add(0x30020052, "Fluence Mode ID", "SH"); } /** * Adds attributes of group 0x3004. */ private void addAttributeGroup3004() { add(0x30040001, "DVH Type", "CS"); add(0x30040002, "Dose Units", "CS"); add(0x30040004, "Dose Type", "CS"); add(0x30040005, "Spatial Transform of Dose", "CS"); add(0x30040006, "Dose Comment", "LO"); add(0x30040008, "Normalization Point", "DS"); add(0x3004000A, "Dose Summation Type", "CS"); add(0x3004000C, "Grid Frame Offset Vector", "DS"); add(0x3004000E, "Dose Grid Scaling", "DS"); add(0x30040010, "RT Dose ROI Sequence", "SQ"); add(0x30040012, "Dose Value", "DS"); add(0x30040014, "Tissue Heterogeneity Correction", "CS"); add(0x30040040, "DVH Normalization Point", "DS"); add(0x30040042, "DVH Normalization Dose Value", "DS"); add(0x30040050, "DVH Sequence", "SQ"); add(0x30040052, "DVH Dose Scaling", "DS"); add(0x30040054, "DVH Volume Units", "CS"); add(0x30040056, "DVH Number of Bins", "IS"); add(0x30040058, "DVH Data", "DS"); add(0x30040060, "DVH Referenced ROI Sequence", "SQ"); add(0x30040062, "DVH ROI Contribution Type", "CS"); add(0x30040070, "DVH Minimum Dose", "DS"); add(0x30040072, "DVH Maximum Dose", "DS"); add(0x30040074, "DVH Mean Dose", "DS"); } /** * Adds attributes of group 0x3006. */ private void addAttributeGroup3006() { add(0x30060002, "Structure Set Label", "SH"); add(0x30060004, "Structure Set Name", "LO"); add(0x30060006, "Structure Set Description", "ST"); add(0x30060008, "Structure Set Date", "DA"); add(0x30060009, "Structure Set Time", "TM"); add(0x30060010, "Referenced Frame of ReferenceSequence", "SQ"); add(0x30060012, "RT Referenced Study Sequence", "SQ"); add(0x30060014, "RT Referenced Series Sequence", "SQ"); add(0x30060016, "Contour Image Sequence", "SQ"); add(0x30060018, "Predecessor Structure SetSequence", "SQ"); add(0x30060020, "Structure Set ROI Sequence", "SQ"); add(0x30060022, "ROI Number", "IS"); add(0x30060024, "Referenced Frame of ReferenceUID", "UI"); add(0x30060026, "ROI Name", "LO"); add(0x30060028, "ROI Description", "ST"); add(0x3006002A, "ROI Display Color", "IS"); add(0x3006002C, "ROI Volume", "DS"); add(0x30060030, "RT Related ROI Sequence", "SQ"); add(0x30060033, "RT ROI Relationship", "CS"); add(0x30060036, "ROI Generation Algorithm", "CS"); add(0x30060038, "ROI Generation Description", "LO"); add(0x30060039, "ROI Contour Sequence", "SQ"); add(0x30060040, "Contour Sequence", "SQ"); add(0x30060042, "Contour Geometric Type", "CS"); add(0x30060044, "Contour Slab Thickness", "DS"); add(0x30060045, "Contour Offset Vector", "DS"); add(0x30060046, "Number of Contour Points", "IS"); add(0x30060048, "Contour Number", "IS"); add(0x30060049, "Attached Contours", "IS"); add(0x30060050, "Contour Data", "DS"); add(0x30060080, "RT ROI Observations Sequence", "SQ"); add(0x30060082, "Observation Number", "IS"); add(0x30060084, "Referenced ROI Number", "IS"); add(0x30060085, "ROI Observation Label", "SH"); add(0x30060086, "RT ROI Identification CodeSequence", "SQ"); add(0x30060088, "ROI Observation Description", "ST"); add(0x300600A0, "Related RT ROI ObservationsSequence", "SQ"); add(0x300600A4, "RT ROI Interpreted Type", "CS"); add(0x300600A6, "ROI Interpreter", "PN"); add(0x300600B0, "ROI Physical Properties Sequence", "SQ"); add(0x300600B2, "ROI Physical Property", "CS"); add(0x300600B4, "ROI Physical Property Value", "DS"); add(0x300600B6, "ROI Elemental CompositionSequence", "SQ"); add(0x300600B7, "ROI Elemental Composition AtomicNumber", "US"); add(0x300600B8, "ROI Elemental Composition AtomicMass Fraction", "FL"); add(0x300600B9, "Additional RT ROI IdentificationCode Sequence", "SQ"); add(0x300600C0, "Frame of Reference RelationshipSequence", "SQ"); // Retired add(0x300600C2, "Related Frame of Reference UID", "UI"); // Retired add(0x300600C4, "Frame of ReferenceTransformation Type", "CS"); // Retired add(0x300600C6, "Frame of ReferenceTransformation Matrix", "DS"); add(0x300600C8, "Frame of ReferenceTransformation Comment", "LO"); } /** * Adds attributes of group 0x3008. */ private void addAttributeGroup3008() { add(0x30080010, "Measured Dose ReferenceSequence", "SQ"); add(0x30080012, "Measured Dose Description", "ST"); add(0x30080014, "Measured Dose Type", "CS"); add(0x30080016, "Measured Dose Value", "DS"); add(0x30080020, "Treatment Session BeamSequence", "SQ"); add(0x30080021, "Treatment Session Ion BeamSequence", "SQ"); add(0x30080022, "Current Fraction Number", "IS"); add(0x30080024, "Treatment Control Point Date", "DA"); add(0x30080025, "Treatment Control Point Time", "TM"); add(0x3008002A, "Treatment Termination Status", "CS"); add(0x3008002B, "Treatment Termination Code", "SH"); add(0x3008002C, "Treatment Verification Status", "CS"); add(0x30080030, "Referenced Treatment RecordSequence", "SQ"); add(0x30080032, "Specified Primary Meterset", "DS"); add(0x30080033, "Specified Secondary Meterset", "DS"); add(0x30080036, "Delivered Primary Meterset", "DS"); add(0x30080037, "Delivered Secondary Meterset", "DS"); add(0x3008003A, "Specified Treatment Time", "DS"); add(0x3008003B, "Delivered Treatment Time", "DS"); add(0x30080040, "Control Point Delivery Sequence", "SQ"); add(0x30080041, "Ion Control Point DeliverySequence", "SQ"); add(0x30080042, "Specified Meterset", "DS"); add(0x30080044, "Delivered Meterset", "DS"); add(0x30080045, "Meterset Rate Set", "FL"); add(0x30080046, "Meterset Rate Delivered", "FL"); add(0x30080047, "Scan Spot Metersets Delivered", "FL"); add(0x30080048, "Dose Rate Delivered", "DS"); add(0x30080050, "Treatment Summary CalculatedDose Reference Sequence", "SQ"); add(0x30080052, "Cumulative Dose to DoseReference", "DS"); add(0x30080054, "First Treatment Date", "DA"); add(0x30080056, "Most Recent Treatment Date", "DA"); add(0x3008005A, "Number of Fractions Delivered", "IS"); add(0x30080060, "Override Sequence", "SQ"); add(0x30080061, "Parameter Sequence Pointer", "AT"); add(0x30080062, "Override Parameter Pointer", "AT"); add(0x30080063, "Parameter Item Index", "IS"); add(0x30080064, "Measured Dose Reference Number", "IS"); add(0x30080065, "Parameter Pointer", "AT"); add(0x30080066, "Override Reason", "ST"); add(0x30080068, "Corrected Parameter Sequence", "SQ"); add(0x3008006A, "Correction Value", "FL"); add(0x30080070, "Calculated Dose ReferenceSequence", "SQ"); add(0x30080072, "Calculated Dose ReferenceNumber", "IS"); add(0x30080074, "Calculated Dose ReferenceDescription", "ST"); add(0x30080076, "Calculated Dose Reference DoseValue", "DS"); add(0x30080078, "Start Meterset", "DS"); add(0x3008007A, "End Meterset", "DS"); add(0x30080080, "Referenced Measured DoseReference Sequence", "SQ"); add(0x30080082, "Referenced Measured DoseReference Number", "IS"); add(0x30080090, "Referenced Calculated DoseReference Sequence", "SQ"); add(0x30080092, "Referenced Calculated DoseReference Number", "IS"); add(0x300800A0, "Beam Limiting Device Leaf PairsSequence", "SQ"); add(0x300800B0, "Recorded Wedge Sequence", "SQ"); add(0x300800C0, "Recorded Compensator Sequence", "SQ"); add(0x300800D0, "Recorded Block Sequence", "SQ"); add(0x300800E0, "Treatment Summary MeasuredDose Reference Sequence", "SQ"); add(0x300800F0, "Recorded Snout Sequence", "SQ"); add(0x300800F2, "Recorded Range Shifter Sequence", "SQ"); add(0x300800F4, "Recorded Lateral SpreadingDevice Sequence", "SQ"); add(0x300800F6, "Recorded Range ModulatorSequence", "SQ"); add(0x30080100, "Recorded Source Sequence", "SQ"); add(0x30080105, "Source Serial Number", "LO"); add(0x30080110, "Treatment Session ApplicationSetup Sequence", "SQ"); add(0x30080116, "Application Setup Check", "CS"); add(0x30080120, "Recorded Brachy AccessoryDevice Sequence", "SQ"); add(0x30080122, "Referenced Brachy AccessoryDevice Number", "IS"); add(0x30080130, "Recorded Channel Sequence", "SQ"); add(0x30080132, "Specified Channel Total Time", "DS"); add(0x30080134, "Delivered Channel Total Time", "DS"); add(0x30080136, "Specified Number of Pulses", "IS"); add(0x30080138, "Delivered Number of Pulses", "IS"); add(0x3008013A, "Specified Pulse Repetition Interval", "DS"); add(0x3008013C, "Delivered Pulse Repetition Interval", "DS"); add(0x30080140, "Recorded Source ApplicatorSequence", "SQ"); add(0x30080142, "Referenced Source ApplicatorNumber", "IS"); add(0x30080150, "Recorded Channel ShieldSequence", "SQ"); add(0x30080152, "Referenced Channel ShieldNumber", "IS"); add(0x30080160, "Brachy Control Point DeliveredSequence", "SQ"); add(0x30080162, "Safe Position Exit Date", "DA"); add(0x30080164, "Safe Position Exit Time", "TM"); add(0x30080166, "Safe Position Return Date", "DA"); add(0x30080168, "Safe Position Return Time", "TM"); add(0x30080171, "Pulse Specific Brachy Control PointDelivered Sequence", "SQ"); add(0x30080172, "Pulse Number", "US"); add(0x30080173, "Brachy Pulse Control PointDelivered Sequence", "SQ"); add(0x30080200, "Current Treatment Status", "CS"); add(0x30080202, "Treatment Status Comment", "ST"); add(0x30080220, "Fraction Group SummarySequence", "SQ"); add(0x30080223, "Referenced Fraction Number", "IS"); add(0x30080224, "Fraction Group Type", "CS"); add(0x30080230, "Beam Stopper Position", "CS"); add(0x30080240, "Fraction Status SummarySequence", "SQ"); add(0x30080250, "Treatment Date", "DA"); add(0x30080251, "Treatment Time", "TM"); } /** * Adds attributes of group 0x300A. */ private void addAttributeGroup300A() { add(0x300A0002, "RT Plan Label", "SH"); add(0x300A0003, "RT Plan Name", "LO"); add(0x300A0004, "RT Plan Description", "ST"); add(0x300A0006, "RT Plan Date", "DA"); add(0x300A0007, "RT Plan Time", "TM"); add(0x300A0009, "Treatment Protocols", "LO"); add(0x300A000A, "Plan Intent", "CS"); add(0x300A000B, "Treatment Sites", "LO"); add(0x300A000C, "RT Plan Geometry", "CS"); add(0x300A000E, "Prescription Description", "ST"); add(0x300A0010, "Dose Reference Sequence", "SQ"); add(0x300A0012, "Dose Reference Number", "IS"); add(0x300A0013, "Dose Reference UID", "UI"); add(0x300A0014, "Dose Reference Structure Type", "CS"); add(0x300A0015, "Nominal Beam Energy Unit", "CS"); add(0x300A0016, "Dose Reference Description", "LO"); add(0x300A0018, "Dose Reference Point Coordinates", "DS"); add(0x300A001A, "Nominal Prior Dose", "DS"); add(0x300A0020, "Dose Reference Type", "CS"); add(0x300A0021, "Constraint Weight", "DS"); add(0x300A0022, "Delivery Warning Dose", "DS"); add(0x300A0023, "Delivery Maximum Dose", "DS"); add(0x300A0025, "Target Minimum Dose", "DS"); add(0x300A0026, "Target Prescription Dose", "DS"); add(0x300A0027, "Target Maximum Dose", "DS"); add(0x300A0028, "Target Underdose Volume Fraction", "DS"); add(0x300A002A, "Organ at Risk Full-volume Dose", "DS"); add(0x300A002B, "Organ at Risk Limit Dose", "DS"); add(0x300A002C, "Organ at Risk Maximum Dose", "DS"); add(0x300A002D, "Organ at Risk Overdose VolumeFraction", "DS"); add(0x300A0040, "Tolerance Table Sequence", "SQ"); add(0x300A0042, "Tolerance Table Number", "IS"); add(0x300A0043, "Tolerance Table Label", "SH"); add(0x300A0044, "Gantry Angle Tolerance", "DS"); add(0x300A0046, "Beam Limiting Device AngleTolerance", "DS"); add(0x300A0048, "Beam Limiting Device ToleranceSequence", "SQ"); add(0x300A004A, "Beam Limiting Device PositionTolerance", "DS"); add(0x300A004B, "Snout Position Tolerance", "FL"); add(0x300A004C, "Patient Support Angle Tolerance", "DS"); add(0x300A004E, "Table Top Eccentric AngleTolerance", "DS"); add(0x300A004F, "Table Top Pitch Angle Tolerance", "FL"); add(0x300A0050, "Table Top Roll Angle Tolerance", "FL"); add(0x300A0051, "Table Top Vertical PositionTolerance", "DS"); add(0x300A0052, "Table Top Longitudinal PositionTolerance", "DS"); add(0x300A0053, "Table Top Lateral PositionTolerance", "DS"); add(0x300A0055, "RT Plan Relationship", "CS"); add(0x300A0070, "Fraction Group Sequence", "SQ"); add(0x300A0071, "Fraction Group Number", "IS"); add(0x300A0072, "Fraction Group Description", "LO"); add(0x300A0078, "Number of Fractions Planned", "IS"); add(0x300A0079, "Number of Fraction Pattern DigitsPer Day", "IS"); add(0x300A007A, "Repeat Fraction Cycle Length", "IS"); add(0x300A007B, "Fraction Pattern", "LT"); add(0x300A0080, "Number of Beams", "IS"); add(0x300A0082, "Beam Dose Specification Point", "DS"); add(0x300A0084, "Beam Dose", "DS"); add(0x300A0086, "Beam Meterset", "DS"); add(0x300A0088, "Beam Dose Point Depth", "FL"); // Retired add(0x300A0089, "Beam Dose Point Equivalent Depth", "FL"); // Retired add(0x300A008A, "Beam Dose Point SSD", "FL"); // Retired add(0x300A008B, "Beam Dose Meaning", "CS"); add(0x300A008C, "Beam Dose Verification ControlPoint Sequence", "SQ"); add(0x300A008D, "Average Beam Dose Point Depth", "FL"); add(0x300A008E, "Average Beam Dose PointEquivalent Depth", "FL"); add(0x300A008F, "Average Beam Dose Point SSD", "FL"); add(0x300A00A0, "Number of Brachy ApplicationSetups", "IS"); add(0x300A00A2, "Brachy Application Setup DoseSpecification Point", "DS"); add(0x300A00A4, "Brachy Application Setup Dose", "DS"); add(0x300A00B0, "Beam Sequence", "SQ"); add(0x300A00B2, "Treatment Machine Name", "SH"); add(0x300A00B3, "Primary Dosimeter Unit", "CS"); add(0x300A00B4, "Source-Axis Distance", "DS"); add(0x300A00B6, "Beam Limiting Device Sequence", "SQ"); add(0x300A00B8, "RT Beam Limiting Device Type", "CS"); add(0x300A00BA, "Source to Beam Limiting DeviceDistance", "DS"); add(0x300A00BB, "Isocenter to Beam Limiting DeviceDistance", "FL"); add(0x300A00BC, "Number of Leaf/Jaw Pairs", "IS"); add(0x300A00BE, "Leaf Position Boundaries", "DS"); add(0x300A00C0, "Beam Number", "IS"); add(0x300A00C2, "Beam Name", "LO"); add(0x300A00C3, "Beam Description", "ST"); add(0x300A00C4, "Beam Type", "CS"); add(0x300A00C5, "Beam Delivery Duration Limit", "FD"); add(0x300A00C6, "Radiation Type", "CS"); add(0x300A00C7, "High-Dose Technique Type", "CS"); add(0x300A00C8, "Reference Image Number", "IS"); add(0x300A00CA, "Planned Verification ImageSequence", "SQ"); add(0x300A00CC, "Imaging Device-SpecificAcquisition Parameters", "LO"); add(0x300A00CE, "Treatment Delivery Type", "CS"); add(0x300A00D0, "Number of Wedges", "IS"); add(0x300A00D1, "Wedge Sequence", "SQ"); add(0x300A00D2, "Wedge Number", "IS"); add(0x300A00D3, "Wedge Type", "CS"); add(0x300A00D4, "Wedge ID", "SH"); add(0x300A00D5, "Wedge Angle", "IS"); add(0x300A00D6, "Wedge Factor", "DS"); add(0x300A00D7, "Total Wedge TrayWater-Equivalent Thickness", "FL"); add(0x300A00D8, "Wedge Orientation", "DS"); add(0x300A00D9, "Isocenter to Wedge Tray Distance", "FL"); add(0x300A00DA, "Source to Wedge Tray Distance", "DS"); add(0x300A00DB, "Wedge Thin Edge Position", "FL"); add(0x300A00DC, "Bolus ID", "SH"); add(0x300A00DD, "Bolus Description", "ST"); add(0x300A00DE, "Effective Wedge Angle", "DS"); add(0x300A00E0, "Number of Compensators", "IS"); add(0x300A00E1, "Material ID", "SH"); add(0x300A00E2, "Total Compensator Tray Factor", "DS"); add(0x300A00E3, "Compensator Sequence", "SQ"); add(0x300A00E4, "Compensator Number", "IS"); add(0x300A00E5, "Compensator ID", "SH"); add(0x300A00E6, "Source to Compensator TrayDistance", "DS"); add(0x300A00E7, "Compensator Rows", "IS"); add(0x300A00E8, "Compensator Columns", "IS"); add(0x300A00E9, "Compensator Pixel Spacing", "DS"); add(0x300A00EA, "Compensator Position", "DS"); add(0x300A00EB, "Compensator Transmission Data", "DS"); add(0x300A00EC, "Compensator Thickness Data", "DS"); add(0x300A00ED, "Number of Boli", "IS"); add(0x300A00EE, "Compensator Type", "CS"); add(0x300A00EF, "Compensator Tray ID", "SH"); add(0x300A00F0, "Number of Blocks", "IS"); add(0x300A00F2, "Total Block Tray Factor", "DS"); add(0x300A00F3, "Total Block Tray Water-EquivalentThickness", "FL"); add(0x300A00F4, "Block Sequence", "SQ"); add(0x300A00F5, "Block Tray ID", "SH"); add(0x300A00F6, "Source to Block Tray Distance", "DS"); add(0x300A00F7, "Isocenter to Block Tray Distance", "FL"); add(0x300A00F8, "Block Type", "CS"); add(0x300A00F9, "Accessory Code", "LO"); add(0x300A00FA, "Block Divergence", "CS"); add(0x300A00FB, "Block Mounting Position", "CS"); add(0x300A00FC, "Block Number", "IS"); add(0x300A00FE, "Block Name", "LO"); add(0x300A0100, "Block Thickness", "DS"); add(0x300A0102, "Block Transmission", "DS"); add(0x300A0104, "Block Number of Points", "IS"); add(0x300A0106, "Block Data", "DS"); add(0x300A0107, "Applicator Sequence", "SQ"); add(0x300A0108, "Applicator ID", "SH"); add(0x300A0109, "Applicator Type", "CS"); add(0x300A010A, "Applicator Description", "LO"); add(0x300A010C, "Cumulative Dose ReferenceCoefficient", "DS"); add(0x300A010E, "Final Cumulative Meterset Weight", "DS"); add(0x300A0110, "Number of Control Points", "IS"); add(0x300A0111, "Control Point Sequence", "SQ"); add(0x300A0112, "Control Point Index", "IS"); add(0x300A0114, "Nominal Beam Energy", "DS"); add(0x300A0115, "Dose Rate Set", "DS"); add(0x300A0116, "Wedge Position Sequence", "SQ"); add(0x300A0118, "Wedge Position", "CS"); add(0x300A011A, "Beam Limiting Device PositionSequence", "SQ"); add(0x300A011C, "Leaf/Jaw Positions", "DS"); add(0x300A011E, "Gantry Angle", "DS"); add(0x300A011F, "Gantry Rotation Direction", "CS"); add(0x300A0120, "Beam Limiting Device Angle", "DS"); add(0x300A0121, "Beam Limiting Device RotationDirection", "CS"); add(0x300A0122, "Patient Support Angle", "DS"); add(0x300A0123, "Patient Support Rotation Direction", "CS"); add(0x300A0124, "Table Top Eccentric Axis Distance", "DS"); add(0x300A0125, "Table Top Eccentric Angle", "DS"); add(0x300A0126, "Table Top Eccentric RotationDirection", "CS"); add(0x300A0128, "Table Top Vertical Position", "DS"); add(0x300A0129, "Table Top Longitudinal Position", "DS"); add(0x300A012A, "Table Top Lateral Position", "DS"); add(0x300A012C, "Isocenter Position", "DS"); add(0x300A012E, "Surface Entry Point", "DS"); add(0x300A0130, "Source to Surface Distance", "DS"); add(0x300A0131, "Average Beam Dose Point Sourceto External Contour SurfaceDistance", "FL"); add(0x300A0132, "Source to External ContourDistance", "FL"); add(0x300A0133, "External Contour Entry Point", "FL"); add(0x300A0134, "Cumulative Meterset Weight", "DS"); add(0x300A0140, "Table Top Pitch Angle", "FL"); add(0x300A0142, "Table Top Pitch Rotation Direction", "CS"); add(0x300A0144, "Table Top Roll Angle", "FL"); add(0x300A0146, "Table Top Roll Rotation Direction", "CS"); add(0x300A0148, "Head Fixation Angle", "FL"); add(0x300A014A, "Gantry Pitch Angle", "FL"); add(0x300A014C, "Gantry Pitch Rotation Direction", "CS"); add(0x300A014E, "Gantry Pitch Angle Tolerance", "FL"); add(0x300A0180, "Patient Setup Sequence", "SQ"); add(0x300A0182, "Patient Setup Number", "IS"); add(0x300A0183, "Patient Setup Label", "LO"); add(0x300A0184, "Patient Additional Position", "LO"); add(0x300A0190, "Fixation Device Sequence", "SQ"); add(0x300A0192, "Fixation Device Type", "CS"); add(0x300A0194, "Fixation Device Label", "SH"); add(0x300A0196, "Fixation Device Description", "ST"); add(0x300A0198, "Fixation Device Position", "SH"); add(0x300A0199, "Fixation Device Pitch Angle", "FL"); add(0x300A019A, "Fixation Device Roll Angle", "FL"); add(0x300A01A0, "Shielding Device Sequence", "SQ"); add(0x300A01A2, "Shielding Device Type", "CS"); add(0x300A01A4, "Shielding Device Label", "SH"); add(0x300A01A6, "Shielding Device Description", "ST"); add(0x300A01A8, "Shielding Device Position", "SH"); add(0x300A01B0, "Setup Technique", "CS"); add(0x300A01B2, "Setup Technique Description", "ST"); add(0x300A01B4, "Setup Device Sequence", "SQ"); add(0x300A01B6, "Setup Device Type", "CS"); add(0x300A01B8, "Setup Device Label", "SH"); add(0x300A01BA, "Setup Device Description", "ST"); add(0x300A01BC, "Setup Device Parameter", "DS"); add(0x300A01D0, "Setup Reference Description", "ST"); add(0x300A01D2, "Table Top Vertical SetupDisplacement", "DS"); add(0x300A01D4, "Table Top Longitudinal SetupDisplacement", "DS"); add(0x300A01D6, "Table Top Lateral SetupDisplacement", "DS"); add(0x300A0200, "Brachy Treatment Technique", "CS"); add(0x300A0202, "Brachy Treatment Type", "CS"); add(0x300A0206, "Treatment Machine Sequence", "SQ"); add(0x300A0210, "Source Sequence", "SQ"); add(0x300A0212, "Source Number", "IS"); add(0x300A0214, "Source Type", "CS"); add(0x300A0216, "Source Manufacturer", "LO"); add(0x300A0218, "Active Source Diameter", "DS"); add(0x300A021A, "Active Source Length", "DS"); add(0x300A021B, "Source Model ID", "SH"); add(0x300A021C, "Source Description", "LO"); add(0x300A0222, "Source Encapsulation NominalThickness", "DS"); add(0x300A0224, "Source Encapsulation NominalTransmission", "DS"); add(0x300A0226, "Source Isotope Name", "LO"); add(0x300A0228, "Source Isotope Half Life", "DS"); add(0x300A0229, "Source Strength Units", "CS"); add(0x300A022A, "Reference Air Kerma Rate", "DS"); add(0x300A022B, "Source Strength", "DS"); add(0x300A022C, "Source Strength Reference Date", "DA"); add(0x300A022E, "Source Strength Reference Time", "TM"); add(0x300A0230, "Application Setup Sequence", "SQ"); add(0x300A0232, "Application Setup Type", "CS"); add(0x300A0234, "Application Setup Number", "IS"); add(0x300A0236, "Application Setup Name", "LO"); add(0x300A0238, "Application Setup Manufacturer", "LO"); add(0x300A0240, "Template Number", "IS"); add(0x300A0242, "Template Type", "SH"); add(0x300A0244, "Template Name", "LO"); add(0x300A0250, "Total Reference Air Kerma", "DS"); add(0x300A0260, "Brachy Accessory DeviceSequence", "SQ"); add(0x300A0262, "Brachy Accessory Device Number", "IS"); add(0x300A0263, "Brachy Accessory Device ID", "SH"); add(0x300A0264, "Brachy Accessory Device Type", "CS"); add(0x300A0266, "Brachy Accessory Device Name", "LO"); add(0x300A026A, "Brachy Accessory Device NominalThickness", "DS"); add(0x300A026C, "Brachy Accessory Device NominalTransmission", "DS"); add(0x300A0280, "Channel Sequence", "SQ"); add(0x300A0282, "Channel Number", "IS"); add(0x300A0284, "Channel Length", "DS"); add(0x300A0286, "Channel Total Time", "DS"); add(0x300A0288, "Source Movement Type", "CS"); add(0x300A028A, "Number of Pulses", "IS"); add(0x300A028C, "Pulse Repetition Interval", "DS"); add(0x300A0290, "Source Applicator Number", "IS"); add(0x300A0291, "Source Applicator ID", "SH"); add(0x300A0292, "Source Applicator Type", "CS"); add(0x300A0294, "Source Applicator Name", "LO"); add(0x300A0296, "Source Applicator Length", "DS"); add(0x300A0298, "Source Applicator Manufacturer", "LO"); add(0x300A029C, "Source Applicator Wall NominalThickness", "DS"); add(0x300A029E, "Source Applicator Wall NominalTransmission", "DS"); add(0x300A02A0, "Source Applicator Step Size", "DS"); add(0x300A02A2, "Transfer Tube Number", "IS"); add(0x300A02A4, "Transfer Tube Length", "DS"); add(0x300A02B0, "Channel Shield Sequence", "SQ"); add(0x300A02B2, "Channel Shield Number", "IS"); add(0x300A02B3, "Channel Shield ID", "SH"); add(0x300A02B4, "Channel Shield Name", "LO"); add(0x300A02B8, "Channel Shield Nominal Thickness", "DS"); add(0x300A02BA, "Channel Shield NominalTransmission", "DS"); add(0x300A02C8, "Final Cumulative Time Weight", "DS"); add(0x300A02D0, "Brachy Control Point Sequence", "SQ"); add(0x300A02D2, "Control Point Relative Position", "DS"); add(0x300A02D4, "Control Point 3D Position", "DS"); add(0x300A02D6, "Cumulative Time Weight", "DS"); add(0x300A02E0, "Compensator Divergence", "CS"); add(0x300A02E1, "Compensator Mounting Position", "CS"); add(0x300A02E2, "Source to Compensator Distance", "DS"); add(0x300A02E3, "Total Compensator TrayWater-Equivalent Thickness", "FL"); add(0x300A02E4, "Isocenter to Compensator TrayDistance", "FL"); add(0x300A02E5, "Compensator Column Offset", "FL"); add(0x300A02E6, "Isocenter to CompensatorDistances", "FL"); add(0x300A02E7, "Compensator Relative StoppingPower Ratio", "FL"); add(0x300A02E8, "Compensator Milling Tool Diameter", "FL"); add(0x300A02EA, "Ion Range Compensator Sequence", "SQ"); add(0x300A02EB, "Compensator Description", "LT"); add(0x300A0302, "Radiation Mass Number", "IS"); add(0x300A0304, "Radiation Atomic Number", "IS"); add(0x300A0306, "Radiation Charge State", "SS"); add(0x300A0308, "Scan Mode", "CS"); add(0x300A030A, "Virtual Source-Axis Distances", "FL"); add(0x300A030C, "Snout Sequence", "SQ"); add(0x300A030D, "Snout Position", "FL"); add(0x300A030F, "Snout ID", "SH"); add(0x300A0312, "Number of Range Shifters", "IS"); add(0x300A0314, "Range Shifter Sequence", "SQ"); add(0x300A0316, "Range Shifter Number", "IS"); add(0x300A0318, "Range Shifter ID", "SH"); add(0x300A0320, "Range Shifter Type", "CS"); add(0x300A0322, "Range Shifter Description", "LO"); add(0x300A0330, "Number of Lateral SpreadingDevices", "IS"); add(0x300A0332, "Lateral Spreading DeviceSequence", "SQ"); add(0x300A0334, "Lateral Spreading Device Number", "IS"); add(0x300A0336, "Lateral Spreading Device ID", "SH"); add(0x300A0338, "Lateral Spreading Device Type", "CS"); add(0x300A033A, "Lateral Spreading DeviceDescription", "LO"); add(0x300A033C, "Lateral Spreading Device WaterEquivalent Thickness", "FL"); add(0x300A0340, "Number of Range Modulators", "IS"); add(0x300A0342, "Range Modulator Sequence", "SQ"); add(0x300A0344, "Range Modulator Number", "IS"); add(0x300A0346, "Range Modulator ID", "SH"); add(0x300A0348, "Range Modulator Type", "CS"); add(0x300A034A, "Range Modulator Description", "LO"); add(0x300A034C, "Beam Current Modulation ID", "SH"); add(0x300A0350, "Patient Support Type", "CS"); add(0x300A0352, "Patient Support ID", "SH"); add(0x300A0354, "Patient Support Accessory Code", "LO"); add(0x300A0356, "Fixation Light Azimuthal Angle", "FL"); add(0x300A0358, "Fixation Light Polar Angle", "FL"); add(0x300A035A, "Meterset Rate", "FL"); add(0x300A0360, "Range Shifter Settings Sequence", "SQ"); add(0x300A0362, "Range Shifter Setting", "LO"); add(0x300A0364, "Isocenter to Range Shifter Distance", "FL"); add(0x300A0366, "Range Shifter Water EquivalentThickness", "FL"); add(0x300A0370, "Lateral Spreading Device SettingsSequence", "SQ"); add(0x300A0372, "Lateral Spreading Device Setting", "LO"); add(0x300A0374, "Isocenter to Lateral SpreadingDevice Distance", "FL"); add(0x300A0380, "Range Modulator SettingsSequence", "SQ"); add(0x300A0382, "Range Modulator Gating StartValue", "FL"); add(0x300A0384, "Range Modulator Gating StopValue", "FL"); add(0x300A0386, "Range Modulator Gating StartWater Equivalent Thickness", "FL"); add(0x300A0388, "Range Modulator Gating StopWater Equivalent Thickness", "FL"); add(0x300A038A, "Isocenter to Range ModulatorDistance", "FL"); add(0x300A0390, "Scan Spot Tune ID", "SH"); add(0x300A0392, "Number of Scan Spot Positions", "IS"); add(0x300A0394, "Scan Spot Position Map", "FL"); add(0x300A0396, "Scan Spot Meterset Weights", "FL"); add(0x300A0398, "Scanning Spot Size", "FL"); add(0x300A039A, "Number of Paintings", "IS"); add(0x300A03A0, "Ion Tolerance Table Sequence", "SQ"); add(0x300A03A2, "Ion Beam Sequence", "SQ"); add(0x300A03A4, "Ion Beam Limiting DeviceSequence", "SQ"); add(0x300A03A6, "Ion Block Sequence", "SQ"); add(0x300A03A8, "Ion Control Point Sequence", "SQ"); add(0x300A03AA, "Ion Wedge Sequence", "SQ"); add(0x300A03AC, "Ion Wedge Position Sequence", "SQ"); add(0x300A0401, "Referenced Setup ImageSequence", "SQ"); add(0x300A0402, "Setup Image Comment", "ST"); add(0x300A0410, "Motion Synchronization Sequence", "SQ"); add(0x300A0412, "Control Point Orientation", "FL"); add(0x300A0420, "General Accessory Sequence", "SQ"); add(0x300A0421, "General Accessory ID", "SH"); add(0x300A0422, "General Accessory Description", "ST"); add(0x300A0423, "General Accessory Type", "CS"); add(0x300A0424, "General Accessory Number", "IS"); add(0x300A0425, "Source to General AccessoryDistance", "FL"); add(0x300A0431, "Applicator Geometry Sequence", "SQ"); add(0x300A0432, "Applicator Aperture Shape", "CS"); add(0x300A0433, "Applicator Opening", "FL"); add(0x300A0434, "Applicator Opening X", "FL"); add(0x300A0435, "Applicator Opening Y", "FL"); add(0x300A0436, "Source to Applicator MountingPosition Distance", "FL"); add(0x300A0440, "Number of Block Slab Items", "IS"); add(0x300A0441, "Block Slab Sequence", "SQ"); add(0x300A0442, "Block Slab Thickness", "DS"); add(0x300A0443, "Block Slab Number", "US"); add(0x300A0450, "Device Motion Control Sequence", "SQ"); add(0x300A0451, "Device Motion Execution Mode", "CS"); add(0x300A0452, "Device Motion Observation Mode", "CS"); add(0x300A0453, "Device Motion Parameter CodeSequence", "SQ"); } /** * Adds attributes of group 0x300C. */ private void addAttributeGroup300C() { add(0x300C0002, "Referenced RT Plan Sequence", "SQ"); add(0x300C0004, "Referenced Beam Sequence", "SQ"); add(0x300C0006, "Referenced Beam Number", "IS"); add(0x300C0007, "Referenced Reference ImageNumber", "IS"); add(0x300C0008, "Start Cumulative Meterset Weight", "DS"); add(0x300C0009, "End Cumulative Meterset Weight", "DS"); add(0x300C000A, "Referenced Brachy ApplicationSetup Sequence", "SQ"); add(0x300C000C, "Referenced Brachy ApplicationSetup Number", "IS"); add(0x300C000E, "Referenced Source Number", "IS"); add(0x300C0020, "Referenced Fraction GroupSequence", "SQ"); add(0x300C0022, "Referenced Fraction GroupNumber", "IS"); add(0x300C0040, "Referenced Verification ImageSequence", "SQ"); add(0x300C0042, "Referenced Reference ImageSequence", "SQ"); add(0x300C0050, "Referenced Dose ReferenceSequence", "SQ"); add(0x300C0051, "Referenced Dose ReferenceNumber", "IS"); add(0x300C0055, "Brachy Referenced DoseReference Sequence", "SQ"); add(0x300C0060, "Referenced Structure SetSequence", "SQ"); add(0x300C006A, "Referenced Patient Setup Number", "IS"); add(0x300C0080, "Referenced Dose Sequence", "SQ"); add(0x300C00A0, "Referenced Tolerance TableNumber", "IS"); add(0x300C00B0, "Referenced Bolus Sequence", "SQ"); add(0x300C00C0, "Referenced Wedge Number", "IS"); add(0x300C00D0, "Referenced Compensator Number", "IS"); add(0x300C00E0, "Referenced Block Number", "IS"); add(0x300C00F0, "Referenced Control Point Index", "IS"); add(0x300C00F2, "Referenced Control PointSequence", "SQ"); add(0x300C00F4, "Referenced Start Control PointIndex", "IS"); add(0x300C00F6, "Referenced Stop Control PointIndex", "IS"); add(0x300C0100, "Referenced Range Shifter Number", "IS"); add(0x300C0102, "Referenced Lateral SpreadingDevice Number", "IS"); add(0x300C0104, "Referenced Range ModulatorNumber", "IS"); add(0x300C0111, "Omitted Beam Task Sequence", "SQ"); add(0x300C0112, "Reason for Omission", "CS"); add(0x300C0113, "Reason for Omission Description", "LO"); } /** * Adds attributes of group 0x300E. */ private void addAttributeGroup300E() { add(0x300E0002, "Approval Status", "CS"); add(0x300E0004, "Review Date", "DA"); add(0x300E0005, "Review Time", "TM"); add(0x300E0008, "Reviewer Name", "PN"); } /** * Adds attributes of group 0x4000. */ private void addAttributeGroup4000() { add(0x40000010, "Arbitrary", "LT"); // Retired add(0x40004000, "Text Comments", "LT"); // Retired } /** * Adds attributes of group 0x4008. */ private void addAttributeGroup4008() { add(0x40080040, "Results ID", "SH"); // Retired add(0x40080042, "Results ID Issuer", "LO"); // Retired add(0x40080050, "Referenced InterpretationSequence", "SQ"); // Retired add(0x400800FF, "Report Production Status (Trial)", "CS"); // Retired add(0x40080100, "Interpretation Recorded Date", "DA"); // Retired add(0x40080101, "Interpretation Recorded Time", "TM"); // Retired add(0x40080102, "Interpretation Recorder", "PN"); // Retired add(0x40080103, "Reference to Recorded Sound", "LO"); // Retired add(0x40080108, "Interpretation Transcription Date", "DA"); // Retired add(0x40080109, "Interpretation Transcription Time", "TM"); // Retired add(0x4008010A, "Interpretation Transcriber", "PN"); // Retired add(0x4008010B, "Interpretation Text", "ST"); // Retired add(0x4008010C, "Interpretation Author", "PN"); // Retired add(0x40080111, "Interpretation Approver Sequence", "SQ"); // Retired add(0x40080112, "Interpretation Approval Date", "DA"); // Retired add(0x40080113, "Interpretation Approval Time", "TM"); // Retired add(0x40080114, "Physician Approving Interpretation", "PN"); // Retired add(0x40080115, "Interpretation DiagnosisDescription", "LT"); // Retired add(0x40080117, "Interpretation Diagnosis CodeSequence", "SQ"); // Retired add(0x40080118, "Results Distribution List Sequence", "SQ"); // Retired add(0x40080119, "Distribution Name", "PN"); // Retired add(0x4008011A, "Distribution Address", "LO"); // Retired add(0x40080200, "Interpretation ID", "SH"); // Retired add(0x40080202, "Interpretation ID Issuer", "LO"); // Retired add(0x40080210, "Interpretation Type ID", "CS"); // Retired add(0x40080212, "Interpretation Status ID", "CS"); // Retired add(0x40080300, "Impressions", "ST"); // Retired add(0x40084000, "Results Comments", "ST"); // Retired } /** * Adds attributes of group 0x4010. */ private void addAttributeGroup4010() { add(0x40100001, "Low Energy Detectors", "CS"); // DICOS add(0x40100002, "High Energy Detectors", "CS"); // DICOS add(0x40100004, "Detector Geometry Sequence", "SQ"); // DICOS add(0x40101001, "Threat ROI Voxel Sequence", "SQ"); // DICOS add(0x40101004, "Threat ROI Base", "FL"); // DICOS add(0x40101005, "Threat ROI Extents", "FL"); // DICOS add(0x40101006, "Threat ROI Bitmap", "OB"); // DICOS add(0x40101007, "Route Segment ID", "SH"); // DICOS add(0x40101008, "Gantry Type", "CS"); // DICOS add(0x40101009, "OOI Owner Type", "CS"); // DICOS add(0x4010100A, "Route Segment Sequence", "SQ"); // DICOS add(0x40101010, "Potential Threat Object ID", "US"); // DICOS add(0x40101011, "Threat Sequence", "SQ"); // DICOS add(0x40101012, "Threat Category", "CS"); // DICOS add(0x40101013, "Threat Category Description", "LT"); // DICOS add(0x40101014, "ATD Ability Assessment", "CS"); // DICOS add(0x40101015, "ATD Assessment Flag", "CS"); // DICOS add(0x40101016, "ATD Assessment Probability", "FL"); // DICOS add(0x40101017, "Mass", "FL"); // DICOS add(0x40101018, "Density", "FL"); // DICOS add(0x40101019, "Z Effective", "FL"); // DICOS add(0x4010101A, "Boarding Pass ID", "SH"); // DICOS add(0x4010101B, "Center of Mass", "FL"); // DICOS add(0x4010101C, "Center of PTO", "FL"); // DICOS add(0x4010101D, "Bounding Polygon", "FL"); // DICOS add(0x4010101E, "Route Segment Start Location ID", "SH"); // DICOS add(0x4010101F, "Route Segment End Location ID", "SH"); // DICOS add(0x40101020, "Route Segment Location ID Type", "CS"); // DICOS add(0x40101021, "Abort Reason", "CS"); // DICOS add(0x40101023, "Volume of PTO", "FL"); // DICOS add(0x40101024, "Abort Flag", "CS"); // DICOS add(0x40101025, "Route Segment Start Time", "DT"); // DICOS add(0x40101026, "Route Segment End Time", "DT"); // DICOS add(0x40101027, "TDR Type", "CS"); // DICOS add(0x40101028, "International Route Segment", "CS"); // DICOS add(0x40101029, "Threat Detection Algorithm andVersion", "LO"); // DICOS add(0x4010102A, "Assigned Location", "SH"); // DICOS add(0x4010102B, "Alarm Decision Time", "DT"); // DICOS add(0x40101031, "Alarm Decision", "CS"); // DICOS add(0x40101033, "Number of Total Objects", "US"); // DICOS add(0x40101034, "Number of Alarm Objects", "US"); // DICOS add(0x40101037, "PTO Representation Sequence", "SQ"); // DICOS add(0x40101038, "ATD Assessment Sequence", "SQ"); // DICOS1 add(0x40101039, "TIP Type", "CS"); // DICOS add(0x4010103A, "DICOS Version", "CS"); // DICOS add(0x40101041, "OOI Owner Creation Time", "DT"); // DICOS add(0x40101042, "OOI Type", "CS"); // DICOS add(0x40101043, "OOI Size", "FL"); // DICOS add(0x40101044, "Acquisition Status", "CS"); // DICOS add(0x40101045, "Basis Materials Code Sequence", "SQ"); // DICOS add(0x40101046, "Phantom Type", "CS"); // DICOS add(0x40101047, "OOI Owner Sequence", "SQ"); // DICOS add(0x40101048, "Scan Type", "CS"); // DICOS add(0x40101051, "Itinerary ID", "LO"); // DICOS add(0x40101052, "Itinerary ID Type", "SH"); // DICOS add(0x40101053, "Itinerary ID Assigning Authority", "LO"); // DICOS add(0x40101054, "Route ID", "SH"); // DICOS add(0x40101055, "Route ID Assigning Authority", "SH"); // DICOS add(0x40101056, "Inbound Arrival Type", "CS"); // DICOS add(0x40101058, "Carrier ID", "SH"); // DICOS add(0x40101059, "Carrier ID Assigning Authority", "CS"); // DICOS add(0x40101060, "Source Orientation", "FL"); // DICOS add(0x40101061, "Source Position", "FL"); // DICOS add(0x40101062, "Belt Height", "FL"); // DICOS add(0x40101064, "Algorithm Routing Code Sequence", "SQ"); // DICOS add(0x40101067, "Transport Classification", "CS"); // DICOS add(0x40101068, "OOI Type Descriptor", "LT"); // DICOS add(0x40101069, "Total Processing Time", "FL"); // DICOS add(0x4010106C, "Detector Calibration Data", "OB"); // DICOS add(0x4010106D, "Additional Screening Performed", "CS"); // DICOS add(0x4010106E, "Additional Inspection SelectionCriteria", "CS"); // DICOS add(0x4010106F, "Additional Inspection MethodSequence", "SQ"); // DICOS add(0x40101070, "AIT Device Type", "CS"); // DICOS add(0x40101071, "QR Measurements Sequence", "SQ"); // DICOS add(0x40101072, "Target Material Sequence", "SQ"); // DICOS add(0x40101073, "SNR Threshold", "FD"); // DICOS add(0x40101075, "Image Scale Representation", "DS"); // DICOS add(0x40101076, "Referenced PTO Sequence", "SQ"); // DICOS add(0x40101077, "Referenced TDR InstanceSequence", "SQ"); // DICOS add(0x40101078, "PTO Location Description", "ST"); // DICOS add(0x40101079, "Anomaly Locator IndicatorSequence", "SQ"); // DICOS add(0x4010107A, "Anomaly Locator Indicator", "FL"); // DICOS add(0x4010107B, "PTO Region Sequence", "SQ"); // DICOS add(0x4010107C, "Inspection Selection Criteria", "CS"); // DICOS add(0x4010107D, "Secondary Inspection MethodSequence", "SQ"); // DICOS add(0x4010107E, "PRCS to RCS Orientation", "DS"); // DICOS } /** * Adds attributes of group 0x4FFE. */ private void addAttributeGroup4FFE() { add(0x4FFE0001, "MAC Parameters Sequence", "SQ"); } /** * Adds attributes of group 0x5200. */ private void addAttributeGroup5200() { add(0x52009229, "Shared Functional GroupsSequence", "SQ"); add(0x52009230, "Per-frame Functional GroupsSequence", "SQ"); } /** * Adds attributes of group 0x5400. */ private void addAttributeGroup5400() { add(0x54000100, "Waveform Sequence", "SQ"); // add(0x54000110, "Channel Minimum Value", "OB or OW"); // add(0x54000112, "Channel Maximum Value", "OB or OW"); add(0x54001004, "Waveform Bits Allocated", "US"); add(0x54001006, "Waveform Sample Interpretation", "CS"); // add(0x5400100A, "Waveform Padding Value", "OB or OW"); // add(0x54001010, "Waveform Data", "OB or OW"); } /** * Adds attributes of group 0x5600. */ private void addAttributeGroup5600() { add(0x56000010, "First Order Phase Correction Angle", "OF"); add(0x56000020, "Spectroscopy Data", "OF"); } /** * Adds attributes of group 0x7FE0. */ private void addAttributeGroup7FE0() { add(0x7FE00008, "Float Pixel Data", "OF"); add(0x7FE00009, "Double Float Pixel Data", "OD"); // add(0x7FE00010, "Pixel Data", "OB or OW"); add(0x7FE00020, "Coefficients SDVN", "OW"); // Retired add(0x7FE00030, "Coefficients SDHN", "OW"); // Retired add(0x7FE00040, "Coefficients SDDN", "OW"); // Retired } /** * Adds attributes of group 0xFFFA. */ private void addAttributeGroupFFFA() { add(0xFFFAFFFA, "Digital Signatures Sequence", "SQ"); } private void add(final int code, final String name, final String vr) { table.put(code, new String[] {name, vr}); } }
package io.badgeup.sponge; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.Unirest; import io.badgeup.sponge.event.BadgeUpEvent; import io.badgeup.sponge.service.AchievementPersistenceService; import io.badgeup.sponge.service.AwardPersistenceService; import org.json.JSONObject; import org.spongepowered.api.Sponge; import org.spongepowered.api.entity.living.player.Player; import java.util.ArrayList; import java.util.List; import java.util.Optional; public class PostEventsRunnable implements Runnable { private BadgeUpSponge plugin; public PostEventsRunnable(BadgeUpSponge plugin) { this.plugin = plugin; } @Override public void run() { Config config = BadgeUpSponge.getConfig(); // build the base API URL String baseURL = ""; if (!config.getBadgeUpConfig().getBaseAPIURL().isEmpty()) { // override other config settings with this base URL baseURL = config.getBadgeUpConfig().getBaseAPIURL(); } else { // region provided baseURL = "https://api." + config.getBadgeUpConfig().getRegion() + ".badgeup.io/v1/apps/"; } String appId = Util.parseAppIdFromAPIKey(config.getBadgeUpConfig().getAPIKey()).get(); this.plugin.getLogger().info("Started BadgeUp event consumer"); try { while (true) { final BadgeUpEvent event = BadgeUpSponge.getEventQueue().take(); event.setDiscardable(true); try { HttpResponse<JsonNode> response = Unirest.post(baseURL + appId + "/events").body(event.build()) .asJson(); if (response.getStatus() == 413) { System.out.println("Event too large: " + event.build().getString("key")); continue; } final JSONObject body = response.getBody().getObject(); List<JSONObject> completedAchievements = new ArrayList<>(); body.getJSONArray("progress").forEach(progressObj -> { JSONObject record = (JSONObject) progressObj; if (record.getBoolean("isComplete") && record.getBoolean("isNew")) { completedAchievements.add(record); } }); for (JSONObject record : completedAchievements) { final String earnedAchievementId = record.getString("earnedAchievementId"); final JSONObject earnedAchievementRecord = Unirest .get(baseURL + appId + "/earnedachievements/" + earnedAchievementId).asJson().getBody() .getObject(); final String achievementId = earnedAchievementRecord.getString("achievementId"); final JSONObject achievement = Unirest.get(baseURL + appId + "/achievements/" + achievementId) .asJson().getBody().getObject(); final Optional<Player> subjectOpt = Sponge.getServer().getPlayer(event.getSubject()); AwardPersistenceService awardPS = Sponge.getServiceManager() .provide(AwardPersistenceService.class).get(); List<String> awardIds = new ArrayList<>(); achievement.getJSONArray("awards") .forEach(awardId -> awardIds.add((String) awardId)); for (String awardId : awardIds) { final JSONObject award = Unirest.get(baseURL + appId + "/awards/" + awardId).asJson() .getBody().getObject(); awardPS.addPendingAward(event.getSubject(), award); boolean autoRedeem = Util.safeGetBoolean(award.getJSONObject("data"), "autoRedeem").orElse(false); if (subjectOpt.isPresent() && autoRedeem) { // Check if the award is auto-redeemable and // send the redeem command if it is Sponge.getCommandManager().process(subjectOpt.get(), "redeem " + awardId); } } if (!subjectOpt.isPresent()) { // Store the achievement to be presented later AchievementPersistenceService achPS = Sponge.getServiceManager() .provide(AchievementPersistenceService.class).get(); achPS.addUnpresentedAchievement(event.getSubject(), achievement); } else { // Present the achievement to the player BadgeUpSponge.presentAchievement(subjectOpt.get(), achievement); } } } catch (Exception e) { e.printStackTrace(); System.out.println(e.getMessage()); this.plugin.getLogger().error("Could not connect to BadgeUp API!"); continue; } } } catch (Exception e) { System.err.println(e); e.printStackTrace(); } } }
package com.github.niwaniwa.we.core; import java.io.File; import java.util.Map; import java.util.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitRunnable; import com.github.niwaniwa.we.core.command.WhiteEggCoreCommandHandler; import com.github.niwaniwa.we.core.command.abs.core.WhiteEggCoreBaseCommandExecutor; import com.github.niwaniwa.we.core.config.WhiteEggCoreConfig; import com.github.niwaniwa.we.core.database.DataBase; import com.github.niwaniwa.we.core.init.Initialization; import com.github.niwaniwa.we.core.player.WhitePlayerFactory; import com.github.niwaniwa.we.core.player.commad.WhiteCommandSender; import com.github.niwaniwa.we.core.player.commad.WhiteConsoleSender; import com.github.niwaniwa.we.core.player.rank.Rank; import com.github.niwaniwa.we.core.script.JavaScript; import com.github.niwaniwa.we.core.util.Versioning; import com.github.niwaniwa.we.core.util.message.LanguageType; import com.github.niwaniwa.we.core.util.message.MessageManager; /** * * @author niwaniwa * @version 2.0.0 */ public class WhiteEggCore extends JavaPlugin { private static WhiteEggCore instance; private static MessageManager msg; private static LanguageType type = LanguageType.en_US;; private static WhiteEggCoreConfig config; private static DataBase database; public static final String logPrefix = "[WhiteEggCore]"; public static final String msgPrefix = "§7[§bWhiteEggCore§7]§r"; public static Logger logger; public static Versioning version; public static boolean isLock = false; private PluginManager pm = Bukkit.getPluginManager(); private JavaScript script; @Override public void onLoad() { logger = this.getLogger(); logger.info("Checking version...."); version = Versioning.getInstance(); } @Override public void onEnable(){ this.versionCheck(); if (!version.isSupport()) { return; } long time = System.nanoTime(); this.init(); long finish = (System.nanoTime() - time); logger.info(String.format("Done : %.3f s", new Object[] { Double.valueOf(finish / 1.0E9D) })); } @Override public void onDisable(){ if (!version.isSupport()) { return; } logger.info("Saving players (WhiteEgg)"); WhitePlayerFactory.saveAll(); Rank.saveAll(); config.save(); } /** * instance * @return */ public static WhiteEggCore getInstance(){ return instance; } /** * * @return */ public static MessageManager getMessageManager(){ return msg; } /** * * @return */ public static LanguageType getType() { return type; } /** * * @return */ public static WhiteEggCoreConfig getConf(){ return config; } private void init(){ instance = this; this.saveDefaultConfig(); config = new WhiteEggCoreConfig(); config.load(); Initialization init = Initialization.getInstance(this); msg = init.getMessageManager(); init.start(false); database = init.getDatabase(); isLock = config.isLock(); this.script = init.getScript(); runTask(); } /** * command */ @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { WhiteCommandSender whiteCommandSender; if(sender instanceof Player){ whiteCommandSender = WhitePlayerFactory.getInstance((Player) sender); } else { whiteCommandSender = new WhiteConsoleSender(true); } return WhiteEggCoreCommandHandler.onCommand(whiteCommandSender, command, label, args); } private void runTask(){ final int run = config.getConfig().getInt("setting.player.save.autoSave.time", 3600 * 20); new BukkitRunnable() { @Override public void run() { if(!config.getConfig().getBoolean("setting.player.save.autoSave.enable", false)){ this.cancel(); return; } WhitePlayerFactory.saveAll(); } }.runTaskTimerAsynchronously(instance, run, run); } private void versionCheck(){ if(version.getJavaVersion() <= 1.7){ logger.warning("Unsupported Java Version >_< : " + version.getJavaVersion()); logger.warning("Please use 1.8"); pm.disablePlugin(instance); return; } if(!version.getCraftBukkitVersion().equalsIgnoreCase("v1_8_R3")){ logger.warning("Unsupported CraftBukkit Version >_< : " + version); logger.warning("Please use v1_8_R3"); pm.disablePlugin(instance); return; } return; } /** * JarFile */ @Override public File getFile() { return super.getFile(); } /** * * @return Map */ public Map<String, WhiteEggCoreBaseCommandExecutor> getCommands(){ return WhiteEggCoreCommandHandler.getCommans(); } public JavaScript getScript() { return script; } public static DataBase getDataBase() { return database; } public void setScript(JavaScript s){ this.script = s; } }
package com.degueLobo.app; import java.sql.*; /** * Hello world! * */ public class App { public static void main( String[] args ) { System.out.println( "Hello World!" ); Connection conn = null; Statement stm = null; try { conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/avis", "appuser", "7LB7qBZh6Zjmqz7c"); stm = conn.createStatement(); String sql = "SELECT * FROM marca"; ResultSet a = stm.executeQuery(sql); while(a.next()) { int id = a.getInt("id"); String marca = a.getString("nombre_marca"); System.out.println("ID: " + id + "; Marca: " + marca); } conn.close(); System.out.printf("TOdo pioli"); } catch (SQLException e) { e.printStackTrace(); } } }
package com.winterwell.web.app; import java.lang.reflect.Field; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.atomic.AtomicLong; import com.winterwell.data.AThing; import com.winterwell.data.KStatus; import com.winterwell.data.PersonLite; import com.winterwell.es.ESKeyword; import com.winterwell.es.ESPath; import com.winterwell.es.ESType; import com.winterwell.es.IESRouter; import com.winterwell.es.client.DeleteRequestBuilder; import com.winterwell.es.client.ESConfig; import com.winterwell.es.client.ESHttpClient; import com.winterwell.es.client.GetRequestBuilder; import com.winterwell.es.client.GetResponse; import com.winterwell.es.client.IESResponse; import com.winterwell.es.client.KRefresh; import com.winterwell.es.client.ReindexRequest; import com.winterwell.es.client.SearchRequestBuilder; import com.winterwell.es.client.SearchResponse; import com.winterwell.es.client.UpdateRequestBuilder; import com.winterwell.es.client.admin.CreateIndexRequest; import com.winterwell.es.client.admin.PutMappingRequestBuilder; import com.winterwell.es.client.query.ESQueryBuilder; import com.winterwell.es.client.query.ESQueryBuilders; import com.winterwell.es.fail.ESException; import com.winterwell.gson.Gson; import com.winterwell.nlp.query.SearchQuery; import com.winterwell.utils.AString; import com.winterwell.utils.Dep; import com.winterwell.utils.ReflectionUtils; import com.winterwell.utils.Utils; import com.winterwell.utils.containers.Containers; import com.winterwell.utils.io.ConfigFactory; import com.winterwell.utils.log.Log; import com.winterwell.utils.time.Time; import com.winterwell.utils.web.WebUtils; import com.winterwell.web.WebEx; import com.winterwell.web.ajax.JThing; import com.winterwell.web.data.XId; import com.winterwell.web.fields.EnumField; import com.winterwell.web.fields.JsonField; /** * Stuff used across the projects, mostly ES / CRUD stuff. * @author daniel * */ public class AppUtils { public static SearchResponse search(ESPath path, SearchQuery q) { ESHttpClient esjc = Dep.get(ESHttpClient.class); SearchRequestBuilder s = new SearchRequestBuilder(esjc); s.setPath(path); com.winterwell.es.client.query.BoolQueryBuilder f = makeESFilterFromSearchQuery(q, null, null); s.setQuery(f); SearchResponse sr = s.get(); return sr; } public static final JsonField ITEM = new JsonField("item"); public static final EnumField<KStatus> STATUS = new EnumField<>(KStatus.class, "status"); private static final List<String> LOCAL_MACHINES = Arrays.asList( "stross", "aardvark" ); private static final List<String> TEST_MACHINES = Arrays.asList( "hugh", "mail.soda.sh" ); @Deprecated private static final List<String> PROD_MACHINES = Arrays.asList( "heppner" ); KServerType serverType = AppUtils.getServerType(null); /** * Use ConfigFactory to get a config from standard places. * This is for loading configs during initialisation. * It also calls Dep.set() * @param config * @param args * @return */ public static <X> X getConfig(String appName, Class<X> config, String[] args) { ConfigFactory cf = ConfigFactory.get(); X c = cf.getConfig(config); // set them for manifest ManifestServlet.addConfig(c); assert config != null; return c; } /** * Convenience for {@link #get(ESPath, Class)} using Dep.get(IESRouter) * @param id * @param klass * @return */ public static <X> X get(String id, Class<X> klass) { ESPath path = Dep.get(IESRouter.class).getPath(klass, id, KStatus.PUBLISHED); return get(path, klass); } /** * Will try path.indices in order if multiple * @param path * @return */ public static <X> X get(ESPath path, Class<X> klass) { return get(path, klass, null); } /** * * @param path * @param klass * @param version * @return object or null for 404 */ public static <X> X get(ESPath path, Class<X> klass, AtomicLong version) { ESHttpClient client = new ESHttpClient(Dep.get(ESConfig.class)); GetRequestBuilder s = new GetRequestBuilder(client); // Minor TODO both indices in one call s.setIndices(path.indices[0]).setType(path.type).setId(path.id); if (version==null) s.setSourceOnly(true); // s.setDebug(true); GetResponse sr = s.get(); if (sr.isSuccess()) { if (klass!=null) { Gson gson = Dep.get(Gson.class); String json = sr.getSourceAsString(); X item = gson.fromJson(json, klass); // version? if (version!=null) { Long v = sr.getVersion(); version.set(v); } return item; } Map<String, Object> json = sr.getSourceAsMap(); //SourceAsString(); return (X) json; } Exception error = sr.getError(); if (error!=null) { if (error instanceof WebEx.E404) { // was version=draft? if (path.indices.length > 1) { ESPath path2 = new ESPath(Arrays.copyOfRange(path.indices, 1, path.indices.length), path.type, path.id); return get(path2, klass); } // 404 return null; } throw Utils.runtime(error); } return null; } public static JThing doUnPublish(JThing thing, ESPath draftPath, ESPath pubPath, KStatus newStatus) { Log.d("unpublish", draftPath+" "+pubPath+" "+newStatus); // prefer being given the thing to avoid ES race conditions if (thing==null) { Map<String, Object> draftMap = get(pubPath, null); thing = new JThing().setMap(draftMap); } assert thing != null : draftPath; // remove modified flag if (thing.map().containsKey("modified")) { thing.put("modified", false); } // set status thing = setStatus(thing, newStatus); // update draft // TODO just an update script to set status ESHttpClient client = new ESHttpClient(Dep.get(ESConfig.class)); UpdateRequestBuilder up = client.prepareUpdate(draftPath); up.setDoc(thing.map()); up.setDocAsUpsert(true); // NB: this doesn't return the merged item :( IESResponse resp = up.get().check(); // delete the published version if ( ! draftPath.equals(pubPath)) { Log.d("unpublish", "deleting published version "+pubPath); DeleteRequestBuilder del = client.prepareDelete(pubPath.index(), pubPath.type, pubPath.id); IESResponse ok = del.get().check(); } return thing; } public static JThing doPublish(JThing draft, ESPath draftPath, ESPath publishPath) { return doPublish(draft, draftPath, publishPath, KRefresh.FALSE, false); } public static JThing doPublish(AThing item, KRefresh refresh, boolean deleteDraft) { IESRouter esr = Dep.get(IESRouter.class); Class type = item.getClass(); String id = item.getId(); ESPath draftPath = esr.getPath(type, id, KStatus.DRAFT); ESPath publishPath = esr.getPath(type, id, KStatus.PUBLISHED); JThing draft = new JThing(item); return doPublish(draft, draftPath, publishPath, refresh, deleteDraft); } /** * * @param draft * @param draftPath * @param publishPath * @param forceRefresh true - use refresh=true to make the index update now * @param deleteDraft Normally we leave the draft, for future editing. But if the object is not editable once published - delete the draft. * @return */ public static JThing doPublish(JThing draft, ESPath draftPath, ESPath publishPath, KRefresh refresh, boolean deleteDraft) { Log.d("doPublish", "to "+publishPath+"... deleteDraft "+deleteDraft); // prefer being given the draft to avoid ES race conditions if (draft==null) { Map<String, Object> draftMap = get(draftPath, null); draft = new JThing().setMap(draftMap); } assert draft != null : draftPath; // remove modified flag if (draft.map().containsKey("modified")) { draft.put("modified", false); } // set status draft = setStatus(draft, KStatus.PUBLISHED); // publish ESHttpClient client = new ESHttpClient(Dep.get(ESConfig.class)); UpdateRequestBuilder up = client.prepareUpdate(publishPath); up.setDoc(draft.map()); up.setRefresh(refresh); up.setDocAsUpsert(true); // NB: this doesn't return the merged item :( IESResponse resp = up.get().check(); // Also update draft? Log.d("doPublish", publishPath+" deleteDraft: "+deleteDraft); if ( ! draftPath.equals(publishPath)) { if (deleteDraft) { doDelete(draftPath); } else { Log.d("doPublish", "also update draft "+draftPath); UpdateRequestBuilder upd = client.prepareUpdate(draftPath); upd.setDoc(draft.map()); upd.setDocAsUpsert(true); upd.setRefresh(refresh); IESResponse respd = upd.get().check(); } } return draft; } public static void doDelete(ESPath path) { try { Log.d("delete", path+" possible-state:"+WebRequest.getCurrent()); ESHttpClient client = new ESHttpClient(Dep.get(ESConfig.class)); DeleteRequestBuilder del = client.prepareDelete(path.index(), path.type, path.id); IESResponse ok = del.get().check(); } catch(WebEx.E404 ex) { // oh well Log.d("delete", path+" 404 - already deleted?"); } } public static JThing doSaveEdit(ESPath path, JThing item, WebRequest state) { assert path.index().toLowerCase().contains("draft") : path; // TODO check security with YouAgain! // update status TODO factor out the status logic Object s = item.map().get("status"); if (Utils.streq(s, KStatus.PUBLISHED)) { AppUtils.setStatus(item, KStatus.MODIFIED); } else { AppUtils.setStatus(item, KStatus.DRAFT); } // talk to ES return doSaveEdit2(path, item, state); } /** * skips the status bit in {@link #doSaveEdit(ESPath, JThing, WebRequest)} * @param path * @param item * @param stateCanBeNull * @return */ @SuppressWarnings("unused") public static JThing doSaveEdit2(ESPath path, JThing item, WebRequest stateCanBeNull) { return doSaveEdit2(path, item, stateCanBeNull, false); } public static JThing doSaveEdit2(ESPath path, JThing item, WebRequest stateCanBeNull, boolean instant) { assert path.id != null : "need an id in path to save "+item; ESHttpClient client = new ESHttpClient(Dep.get(ESConfig.class)); // save update // JThing item2 = Utils.copy(item); // String json = item2.string(); // Object start = SimpleJson.get(item2.map(), "projects", 0, "start"); // Object startraw = SimpleJson.get(item2.map(), "projects", 0, "start_raw"); // prep object via IInit? (IInit is checked within JThing) // e.g. set the suggest field for NGO Object jobj = item.java(); // item2 = Utils.copy(item); // String json2 = item2.string(); // Object start2 = SimpleJson.get(item2.map(), "projects", 0, "start"); // Object startraw2 = SimpleJson.get(item2.map(), "projects", 0, "start_raw"); // sanity check id matches path String id = (String) item.map().get("@id"); //mod.getId(); if (id==null) { Object _id = item.map().get("id"); if (_id instanceof String) id= (String) _id; if (_id.getClass().isArray()) id= (String) Containers.asList(_id).get(0); } assert id != null && ! id.equals("new") : "use action=new "+stateCanBeNull; assert id.equals(path.id) : path+" vs "+id; // item2 = Utils.copy(item); // String json3 = item2.string(); // Object start3 = SimpleJson.get(item2.map(), "projects", 0, "start"); // Object startraw3 = SimpleJson.get(item2.map(), "projects", 0, "start_raw"); // save to ES UpdateRequestBuilder up = client.prepareUpdate(path); // This should merge against what's in the DB Map map = item.map(); up.setDoc(map); up.setDocAsUpsert(true); // force an instant refresh? if (instant) up.setRefresh("true"); // TODO delete stuff?? fields or items from a list // up.setScript(script) // NB: this doesn't return the merged item :( IESResponse resp = up.get().check(); // Map<String, Object> item2 = resp.getParsedJson(); return item; } /** * local / test / production */ public static KServerType getServerType(WebRequest state) { if (state != null && false) { KServerType st = KServerType.PRODUCTION; String url = state.getRequestUrl(); if (url.contains("//local")) st = KServerType.LOCAL; if (url.contains("//test")) st = KServerType.TEST; Log.d("AppUtils", "Using WebRequest serverType "+st+" from url "+url); return st; } // cache the answer if (_serverType==null) { _serverType = getServerType2(); Log.d("AppUtils", "Using serverType "+_serverType); } return _serverType; } private static KServerType _serverType; private static String _hostname; /** * Determined in this order: * * 1. Is there a config rule "serverType=dev|production" in Statics.properties? * (i.e. loaded from a server.properties file) * 2. Is the hostname in the hardcoded PRODUCTION_ and DEV_MACHINES lists? * * @return */ private static KServerType getServerType2() { // explicit config if (Dep.has(Properties.class)) { String st = Dep.get(Properties.class).getProperty("serverType"); if (st!=null) { Log.d("init", "Using explicit serverType "+st); return KServerType.valueOf(st); } else { Log.d("init", "No explicit serverType in config"); } } else { Log.d("init", "No Properties for explicit serverType"); } // explicitly listed String hostname = getFullHostname(); Log.d("init", "serverType for host "+hostname+" ...?"); if (LOCAL_MACHINES.contains(hostname)) { Log.i("init", "Treating "+hostname+" as serverType = "+KServerType.LOCAL); return KServerType.LOCAL; } if (TEST_MACHINES.contains(hostname)) { Log.i("init", "Treating "+hostname+" as serverType = "+KServerType.TEST); return KServerType.TEST; } if (PROD_MACHINES.contains(hostname)) { Log.i("init", "Treating "+hostname+" as serverType = "+KServerType.PRODUCTION); return KServerType.PRODUCTION; } Log.i("init", "Fallback: Treating "+hostname+" as serverType = "+KServerType.PRODUCTION); return KServerType.PRODUCTION; } public static String getFullHostname() { if (_hostname==null) _hostname = WebUtils.fullHostname(); return _hostname; } public static void addDebugInfo(WebRequest request) { request.getResponse().addHeader("X-Server", AppUtils.getFullHostname()); } /** * Make indices. * Does not set mapping. * @param main * @param dbclasses */ public static void initESIndices(KStatus[] main, Class... dbclasses) { IESRouter esRouter = Dep.get(IESRouter.class); ESHttpClient es = Dep.get(ESHttpClient.class); ESException err = null; for(KStatus s : main) { for(Class klass : dbclasses) { ESPath path = esRouter.getPath(null, klass, null, s); String index = path.index(); if (es.admin().indices().indexExists(index)) { continue; } try { // make with an alias to allow for later switching if we change the schema String baseIndex = index+"_"+es.getConfig().getIndexAliasVersion(); CreateIndexRequest pi = es.admin().indices().prepareCreate(baseIndex); pi.setFailIfAliasExists(true); pi.setAlias(index); IESResponse r = pi.get().check(); } catch(ESException ex) { Log.e("ES.init", ex.toString()); err = ex; } } } if (err!=null) throw err; } /** * Create mappings. Some common fields are set: "name", "id", "@type" * @param statuses * @param dbclasses * @param mappingFromClass Setup more fields. Can be null */ public static void initESMappings(KStatus[] statuses, Class[] dbclasses, Map<Class,Map> mappingFromClass) { IESRouter esRouter = Dep.get(IESRouter.class); ESHttpClient es = Dep.get(ESHttpClient.class); ESException err = null; for(KStatus status : statuses) { for(Class k : dbclasses) { ESPath path = esRouter.getPath(null, k, null, status); try { // Normal setup String index = path.index(); initESMappings2_putMapping(mappingFromClass, es, k, path, index); } catch(ESException ex) { // map the base index (so we can do a reindex with the right mapping) String index = path.index() +"_"+Dep.get(ESConfig.class).getIndexAliasVersion() ; // make if not exists if ( ! es.admin().indices().indexExists(index)) { CreateIndexRequest pi = es.admin().indices().prepareCreate(index); // pi.setFailIfAliasExists(true); // pi.setAlias(path.index()); // no alias - the old version is still in place IESResponse r = pi.get().check(); } // setup the right mapping initESMappings2_putMapping(mappingFromClass, es, k, path, index); // attempt a simple reindex ReindexRequest rr = new ReindexRequest(es, path.index(), index); rr.execute(); // could be slow, so don't wait // and shout fail! // -- but run through all the mappings first, so a sys-admin can update them all in one run. // After this, the sysadmin should (probably) remove the link old-base -> alias, // and put in a new-base -> alias link err = ex; Log.e("init", ex.toString()); } } } if (err != null) throw err; } private static void initESMappings2_putMapping(Map<Class, Map> mappingFromClass, ESHttpClient es, Class k, ESPath path, String index) { PutMappingRequestBuilder pm = es.admin().indices().preparePutMapping( index, path.type); ESType dtype = new ESType(); // passed in Map mapping = mappingFromClass==null? null : mappingFromClass.get(k); if (mapping != null) { // merge in // NB: done here, so that it doesn't accidentally trash the settings below // -- because probably both maps define "properties" // Future: It'd be nice to have a deep merge, and give the passed in mapping precendent. dtype.putAll(mapping); } // some common props dtype.property("name", new ESType().text() // enable keyword based sorting .field("raw", "keyword")); // ID, either thing.org or sane version dtype.property("@id", ESType.keyword); dtype.property("id", ESType.keyword); // type dtype.property("@type", ESType.keyword); // reflection based initESMappings3_putMapping_byAnnotation(k, dtype); // Call ES... pm.setMapping(dtype); IESResponse r2 = pm.get(); r2.check(); } private static void initESMappings3_putMapping_byAnnotation(Class k, ESType dtype) { List<Field> fields = ReflectionUtils.getAllFields(k); for (Field field : fields) { String fname = field.getName(); if (dtype.containsKey(fname) || dtype.containsKey(fname.toLowerCase())) { continue; } Class<?> type = field.getType(); // annotation? ESKeyword esk = field.getAnnotation(ESKeyword.class); if (esk!=null) { dtype.property(fname, ESType.keyword); continue; } // enum = keyword if (type.isEnum()) { dtype.property(fname, ESType.keyword); continue; } // IDs if (type.equals(XId.class) || ReflectionUtils.isa(type, AString.class)) { dtype.property(fname, ESType.keyword); continue; } // ??anything else ES is liable to guess wrong?? // TODO recurse if (type != Object.class && ! type.isPrimitive() && ! type.isArray() && ! ReflectionUtils.isa(type, Collection.class) && ! ReflectionUtils.isa(type, Map.class)) { ESType ftype = new ESType(); assert ftype.isEmpty(); initESMappings3_putMapping_byAnnotation(type, ftype); if ( ! ftype.isEmpty()) { dtype.property(fname, ftype); } } } } /** * * @param from * @param info Optional {name, img, description, url} * @return */ public static PersonLite getCreatePersonLite(XId from, Map info) { assert from != null : info; // it is strongly recommended that the router treat PersonLite == Person IESRouter router = Dep.get(IESRouter.class); ESPath path = router.getPath(PersonLite.class, from.toString(), KStatus.PUBLISHED); PersonLite peep = get(path, PersonLite.class); if (peep!=null) { // not saving any edits here?! if (info != null) peep.setInfo(info); return peep; } // draft? path = router.getPath(PersonLite.class, from.toString(), KStatus.DRAFT); peep = get(path, PersonLite.class); if (peep!=null) { // not saving any edits here?! if (info != null) peep.setInfo(info); return peep; } // make it peep = new PersonLite(from); if (info != null) peep.setInfo(info); // store it NB: the only data is the id, so there's no issue with race conditions AppUtils.doSaveEdit(path, new JThing().setJava(peep), null); return peep; } /** * NB: not in {@link ESQueryBuilders} 'cos that cant see the SearchQuery class * * @param sq never null * @param start * @param end * @return */ public static com.winterwell.es.client.query.BoolQueryBuilder makeESFilterFromSearchQuery(SearchQuery sq, Time start, Time end) { assert sq != null; com.winterwell.es.client.query.BoolQueryBuilder filter = ESQueryBuilders.boolQuery(); if (start != null || end != null) { if (start !=null && end !=null && ! end.isAfter(start)) { if (end.equals(start)) { throw new WebEx.E400("Empty date range - start = end = "+start+" Search: "+sq); } throw new WebEx.E400("Bad date range: start: "+start+" end: "+end+" Search: "+sq); } ESQueryBuilder timeFilter = ESQueryBuilders.dateRangeQuery("time", start, end); filter = filter.must(timeFilter); } // filters TODO a true recursive SearchQuery -> ES query mapping // TODO this is just a crude 1-level thing List ptree = sq.getParseTree(); try { com.winterwell.es.client.query.BoolQueryBuilder q = parseTreeToQuery(ptree); if ( ! q.isEmpty()) { filter = filter.must(q); } } catch (Throwable e) { // Put full query info on an assertion failure throw new WebEx.E40X(400, "bad query "+sq, e); } return filter; } private static com.winterwell.es.client.query.BoolQueryBuilder parseTreeToQuery(Object rawClause) { if ( ! (rawClause instanceof List) && ! (rawClause instanceof Map)) { throw new IllegalArgumentException("clause is not list or map: " + rawClause); } com.winterwell.es.client.query.BoolQueryBuilder filter = ESQueryBuilders.boolQuery(); // Map means propname=value constraint. if (rawClause instanceof Map) { Map<String, Object> clause = (Map<String, Object>) rawClause; // We expect only one pair per clause, but no reason not to tolerate multiples. for (String prop : clause.keySet()) { String val = (String) clause.get(prop); if (ESQueryBuilders.UNSET.equals(val)) { ESQueryBuilder setFilter = ESQueryBuilders.existsQuery(prop); return filter.mustNot(setFilter); } else { // normal key=value case ESQueryBuilder kvFilter = ESQueryBuilders.termQuery(prop, val); return filter.must(kvFilter); } } } List clause = (List) rawClause; assert (! clause.isEmpty()) : "empty clause"; // Only one element? if (clause.size() < 2) { Object entry = clause.get(0); // empty query string yields degenerate parse tree with just ["and"] if (entry instanceof String && SearchQuery.KEYWORD_AND.equalsIgnoreCase((String) entry)) { return filter; } // Well, try and parse it. return parseTreeToQuery(entry); } // 2+ elements, first is a String - is it a Boolean operator? Object maybeOperator = clause.get(0); if (maybeOperator instanceof String) { // Is it an explicit NOT clause, ie (NOT, x=y)? if (SearchQuery.KEYWORD_NOT.equals((String) maybeOperator)) { assert (clause.size() == 2) : "Explicit NOT clause with >1 operand??: " + clause; return filter.mustNot(parseTreeToQuery(clause.get(1))); } if (SearchQuery.KEYWORD_AND.equals((String) maybeOperator)) { for (Object term : clause.subList(1, clause.size())) { com.winterwell.es.client.query.BoolQueryBuilder andTerm = parseTreeToQuery(term); filter = filter.must(andTerm); } return filter; } if (SearchQuery.KEYWORD_OR.equals((String) maybeOperator)) { for (Object term : clause.subList(1, clause.size())) { filter = filter.should(parseTreeToQuery(term)); } return filter; } } // Fall-through clause: 2+ elements, first isn't a Boolean operator // Assume it's an implicit AND of all elements in list. for (Object term : clause) { filter = filter.must(parseTreeToQuery((List) term)); } return filter; } @Deprecated public static <X> X getConfig(String appName, X config, String[] args) { return (X) getConfig(appName, config.getClass(), args); } public static <T> JThing<T> setStatus(JThing<T> thing, KStatus newStatus) { Utils.check4null(thing, newStatus); thing.put("status", newStatus); return thing; } public static KStatus getStatus(JThing thing) { Object s = thing.map().get("status"); if (s==null) { return null; // odd } if (s instanceof KStatus) return (KStatus) s; return KStatus.valueOf((String) s); } public static StringBuilder getServerUrl(KServerType mtype, String domain) { assert ! domain.startsWith("http") && ! domain.endsWith("/") : domain; // SoGive uses "app.sogive.org", "test.sogive.org", "local.sogive.org" for Historical Reasons if ("app.sogive.org".equals(domain) && mtype != KServerType.PRODUCTION) { domain = ".sogive.org"; } StringBuilder url = new StringBuilder(); url.append(mtype==KServerType.LOCAL? "http" : "https"); url.append("://"); url.append(mtype==KServerType.PRODUCTION? "" : mtype.toString().toLowerCase()); url.append(domain); return url; } /** * Std implementation of IESRouter * @param dataspaceIgnored * @param type * @param id * @param status * @return */ public static ESPath getPath(CharSequence dataspaceIgnored, Class type, String id, Object status) { String stype = type==null? null : type.getSimpleName().toLowerCase(); // HACK NGO -> charity if ("ngo".equals(stype)) stype = "charity"; // HACK map personlite and person to the same DB if (type==PersonLite.class) stype = "person"; String index = stype; KStatus ks = (KStatus) status; if (ks==null) ks = KStatus.PUBLISHED; switch(ks) { case PUBLISHED: break; case DRAFT: case PENDING: case REQUEST_PUBLISH: case MODIFIED: index += ".draft"; break; case TRASH: index += ".trash"; break; default: throw new IllegalArgumentException(type+" "+status); } return new ESPath(index, stype, id); } }