answer
stringlengths
17
10.2M
package nl.mpi.arbil.MetadataFile; import java.io.File; import java.net.URI; public interface MetadataUtils { public boolean addCorpusLink(URI nodeURI, URI linkURI[]); public boolean removeCorpusLink(URI nodeURI, URI linkURI[]); public boolean moveMetadataFile(URI sourceURI, File destinationFile, boolean updateLinks); public boolean copyMetadataFile(URI sourceURI, File destinationFile, URI[] linksNotToUpdate, boolean updateLinks); public URI[] getCorpusLinks(URI nodeURI); }
package org.apache.xerces.msg; import java.util.ListResourceBundle; /** * This file contains error and warning messages to be localized * The messages are arranged in key and value tuples in a ListResourceBundle. * * @version */ public class ExceptionMessages extends ListResourceBundle { /** The list resource bundle contents. */ public static final Object CONTENTS[][] = { // org.apache.xerces.msg.ExceptionMessageLocalizer { "FMT001", "Message Formatting Error." }, // org.apache.html { "HTM001", "State error: startDocument fired twice on one builder." }, { "HTM002", "State error: document never started or missing document element." }, { "HTM003", "State error: document ended before end of document element." }, { "HTM004", "Argument ''tagName'' is null." }, { "HTM005", "State error: Document.getDocumentElement returns null." }, { "HTM006", "State error: startElement called after end of document element." }, { "HTM007", "State error: endElement called with no current node." }, { "HTM008", "State error: mismatch in closing tag name {0}" }, { "HTM009", "State error: character data found outside of root element." }, { "HTM010", "State error: character data found outside of root element." }, { "HTM011", "Argument ''topLevel'' is null." }, { "HTM012", "Argument ''index'' is negative." }, { "HTM013", "Argument ''name'' is null." }, { "HTM014", "Argument ''title'' is null." }, { "HTM015", "Tag ''{0}'' associated with an Element class that failed to construct." }, { "HTM016", "Argument ''caption'' is not an element of type <CAPTION>." }, { "HTM017", "Argument ''tHead'' is not an element of type <THEAD>." }, { "HTM018", "Argument ''tFoot'' is not an element of type <TFOOT>." }, { "HTM019", "OpenXML Error: Could not find class {0} implementing HTML element {1}" }, // org.apache.xml.serialize { "SER001", "Argument ''output'' is null." }, { "SER002", "No writer supplied for serializer" }, { "SER003", "The resource [{0}] could not be found." }, { "SER004", "The resource [{0}] could not load: {1}" }, { "SER005", "The method ''{0}'' is not supported by this factory" }, // org.apache.xerces.dom { "DOM001", "Modification not allowed" }, { "DOM002", "Illegal character" }, { "DOM003", "Namespace error" }, { "DOM004", "Index out of bounds" }, { "DOM005", "Wrong document" }, { "DOM006", "Hierarchy request error" }, { "DOM007", "Not supported" }, { "DOM008", "Not found" }, { "DOM009", "Attribute already in use" }, { "DOM010", "Unspecified event type" }, { "DOM011", "Invalid state" }, { "DOM012", "Invalid node type" }, { "DOM013", "Bad boundary points" }, // org.apache.xerces.framework { "FWK001", "{0}] scannerState: {1}" }, { "FWK002", "{0}] popElementType: fElementDepth { "FWK003", "TrailingMiscDispatcher.endOfInput moreToFollow" }, { "FWK004", "cannot happen: {0}" }, { "FWK005", "parse may not be called while parsing." }, { "FWK006", "setLocale may not be called while parsing." }, { "FWK007", "Unknown error domain \"{0}\"." }, { "FWK008", "Element stack underflow." }, // org.apache.xerces.parsers { "PAR001", "Fatal error constructing DOMParser." }, { "PAR002", "Class, \"{0}\", is not of type org.w3c.dom.Document." }, { "PAR003", "Class, \"{0}\", not found." }, { "PAR004", "Cannot setFeature({0}): parse is in progress." }, { "PAR005", "Property, \"{0}\" is read-only." }, { "PAR006", "Property value must be of type java.lang.String." }, { "PAR007", "Current element node cannot be queried when node expansion is deferred." }, { "PAR008", "Fatal error getting document factory." }, { "PAR009", "Fatal error reading expansion mode." }, { "PAR010", "Can''t copy node type, {0} ({1})." }, { "PAR011", "Feature {0} not supported during parse." }, { "PAR012", "For propertyId \"{0}\", the value \""+ "{1}\" cannot be cast to {2}." }, { "PAR013", "Property \"{0}\" is read only." }, { "PAR014", "Cannot getProperty(\"{0}\". No DOM tree exists." }, { "PAR015", "startEntityReference(): ENTITYTYPE_UNPARSED" }, { "PAR016", "endEntityReference(): ENTITYTYPE_UNPARSED" }, { "PAR017", "cannot happen: {0}" }, { "PAR018", "{0} state for feature \"{1}\" is not supported." }, { "PAR019", "Property, \"{0}\", is not supported." }, // org.apache.xerces.readers { "RDR001", "untested" }, { "RDR002", "cannot happen" }, //org.apache.xerces.utils { "UTL001", "untested" }, { "UTL002", "cannot happen" }, //org.apache.xerces.validators { "VAL001", "Element stack underflow" }, { "VAL002", "getValidatorForAttType ({0})" }, { "VAL003", "cannot happen" } }; /** Returns the list resource bundle contents. */ public Object[][] getContents() { return CONTENTS; } }
package org.biojava.bio.seq.io; import java.util.*; import java.io.*; import org.biojava.utils.*; import org.biojava.bio.*; import org.biojava.bio.symbol.*; /** * Simple implementation of SymbolTokenization which uses the `name' * field of the symbols. This class works with any non-cross-product * FiniteAlphabet, and doesn't need any extra data to be provided. * * @author Thomas Down * @since 1.2 */ public class NameTokenization extends WordTokenization { private transient Map nameToSymbol = null; private boolean caseSensitive; public NameTokenization(FiniteAlphabet fab, boolean caseSensitive) { super(fab); fab.addChangeListener(ChangeListener.ALWAYS_VETO, ChangeType.UNKNOWN); this.caseSensitive = caseSensitive; } /** * Construct a new NameTokenization, defaulting to case-insensitive. */ public NameTokenization(FiniteAlphabet fab) { this(fab, false); } protected void finalize() throws Throwable { super.finalize(); getAlphabet().removeChangeListener(ChangeListener.ALWAYS_VETO, ChangeType.UNKNOWN); } protected Map getNameToSymbol() { if (nameToSymbol == null) { nameToSymbol = new HashMap(); for (Iterator i = ((FiniteAlphabet) getAlphabet()).iterator(); i.hasNext(); ) { Symbol sym = (Symbol) i.next(); if (caseSensitive) { nameToSymbol.put(sym.getName(), sym); } else { nameToSymbol.put(sym.getName().toLowerCase(), sym); } } nameToSymbol.put("gap", getAlphabet().getGapSymbol()); } return nameToSymbol; } public Symbol parseToken(String token) throws IllegalSymbolException { Symbol sym; if (caseSensitive) { sym = (Symbol) getNameToSymbol().get(token); } else { sym = (Symbol) getNameToSymbol().get(token.toLowerCase()); } if (sym == null) { char c = token.charAt(0); if (c == '[') { if (token.charAt(token.length() - 1) != ']') { throw new IllegalSymbolException("Mismatched parentheses: " + token); } else { Symbol[] syms = parseString(token.substring(1, token.length() - 1)); Set ambigSet = new HashSet(); for (int i = 0; i < syms.length; ++i) { ambigSet.add(syms[i]); } return getAlphabet().getAmbiguity(ambigSet); } } else { throw new IllegalSymbolException("Token `" + token + "' does not appear as a named symbol in alphabet `" + getAlphabet().getName() + "'"); } } return sym; } public String tokenizeSymbol(Symbol s) throws IllegalSymbolException { getAlphabet().validate(s); return s.getName(); } }
package org.biojava.spice.Panel; import org.biojava.spice.SPICEFrame ; import org.biojava.spice.GUI.SelectionLockMenuListener; import org.biojava.spice.GUI.SelectionLockPopupListener; import org.biojava.spice.Feature.* ; import org.biojava.spice.Panel.SeqPanel ; import org.biojava.bio.structure.Chain ; import org.biojava.bio.structure.Group ; import java.awt.Color ; import java.awt.Graphics ; import java.awt.image.BufferedImage ; import java.awt.Font ; import java.awt.Dimension ; import java.awt.event.ActionListener; import java.awt.event.MouseListener ; import java.awt.event.MouseMotionListener ; import java.awt.event.MouseEvent ; import java.awt.Graphics2D ; import java.awt.* ; import java.net.URL; import java.util.List ; import java.util.ArrayList ; import java.util.Date ; import java.util.logging.Logger; //import java.uti.logging.* ; import javax.swing.JMenuItem; import javax.swing.JPanel ; import javax.swing.JPopupMenu; import java.net.MalformedURLException; //import ToolTip.* ; /** * A class the provides a graphical reqpresentation of the Features of a protein sequences. Requires an arraylist of features. @author Andreas Prlic */ public class SeqFeaturePanel extends JPanel implements SeqPanel, MouseListener, MouseMotionListener { public static final int DEFAULT_X_START = 60 ; public static final int DEFAULT_X_RIGHT_BORDER = 20 ; public static final int DEFAULT_Y_START = 30 ; public static final int DEFAULT_Y_STEP = 10 ; public static final int DEFAULT_Y_HEIGHT = 4 ; public static final int DEFAULT_Y_BOTTOM = 16 ; // the line where to draw the structure public static final int DEFAULT_STRUCTURE_Y = 20 ; public static final int TIMEDELAY = 300 ; public static final Color SELECTION_COLOR = Color.lightGray; public static final Color STRUCTURE_COLOR = Color.red; public static final Color STRUCTURE_BACKGROUND_COLOR = new Color(0.5f, 0.1f, 0.5f, 0.5f); // use this font for the text public static final Font plainFont = new Font("SansSerif", Font.PLAIN, 10); static Cursor handCursor = new Cursor(Cursor.HAND_CURSOR); static Cursor defaultCursor = new Cursor(Cursor.DEFAULT_CURSOR); JPopupMenu popupMenu ; int selectStart ; int selectEnd ; int mouseDragStart ; // the master application SPICEFrame spice ; Color seqColorOld ; Color strucColorOld ; Chain chain ; int current_chainnumber; //int chainlength ; //int seqPosOld, strucPosOld ; float scale ; List drawLines ; ArrayList knownLinks; //mouse events Date lastHighlight ; // highliting boolean dragging; //Logger logger ; static Logger logger = Logger.getLogger("org.biojava.spice"); public SeqFeaturePanel(SPICEFrame spicefr ) { super(); //logger = Logger.getLogger("org.biojava.spice"); setDoubleBuffered(true) ; // TODO Auto-generated constructor stub Dimension dstruc=this.getSize(); //imbuf = this.createImage(dstruc.width, dstruc.height); //imbuf = null ; //imbufDim = dstruc; //Graphics gstruc=imbuf.getGraphics(); //gstruc.drawImage(imbuf, 0, 0, this); spice = spicefr; //features = new ArrayList(); drawLines = new ArrayList(); knownLinks = new ArrayList(); chain = null ; lastHighlight = new Date(); current_chainnumber = -1 ; setOpaque(true); selectStart = -1 ; selectEnd = 1 ; mouseDragStart = -1 ; dragging = false; popupMenu = new JPopupMenu(); SelectionLockMenuListener ml = new SelectionLockMenuListener(spice,null); JMenuItem menuItem = new JMenuItem("lock selection"); menuItem.addActionListener(ml); popupMenu.add(menuItem); //menuItem = new JMenuItem("delete"); //menuItem.addActionListener(ml); //tablePopup.add(menuItem); MouseListener popupListener = new SelectionLockPopupListener(popupMenu,spice); this.addMouseListener(popupListener); } public void lockSelection(){ spice.setSelectionLocked(true); } public void unlockSelection(){ spice.setSelectionLocked(false); } public void paintComponent( Graphics g) { //logger.entering(this.getClass().getName(),"paintComponent"); super.paintComponent(g); //logger.finest("DasCanv - paintComponent"); if ( chain == null ) return ; Dimension dstruc=this.getSize(); BufferedImage imbuf = (BufferedImage)this.createImage(dstruc.width,dstruc.height); Graphics2D g2D = (Graphics2D)g ; // Set current alpha Composite oldComposite = g2D.getComposite(); g2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,1.0f)); g2D.setFont(plainFont); int chainlength = chain.getLength() ; // scale should span the whole length ... scale(dstruc); //logger.finest("scale:" +scale+ " width: "+dstruc.width + " chainlength: "+chainlength ); // draw scale drawScale(g2D,chainlength); // draw sequence int seqx = drawSequence(g2D, chainlength); // minimum size of one aminoacid int aminosize = getAminoSize(); // draw region covered with structure drawStructureRegion(g2D,aminosize); // draw features drawFeatures(g2D,aminosize); // highlite selection drawSelection(g2D, aminosize, seqx); // copy new image to visible one g2D.setComposite(oldComposite); // g.drawImage(imbuf,0,0,this.getBackground(),this); //logger.exiting(this.getClass().getName(),"paintComponent"); } /** returns the size of one amino acid in the display; in pixel */ public int getAminoSize(){ return Math.round(1 * scale) ; } public void scale(Dimension dstruc){ int chainlength =chain.getLength() ; scale = (dstruc.width ) / (float)(DEFAULT_X_START + chainlength + DEFAULT_X_RIGHT_BORDER ) ; } /** draw structrure covered region as feature */ private void drawStructureRegion(Graphics2D g2D, int aminosize){ // data is coming from chain; g2D.drawString("Structure",1,DEFAULT_STRUCTURE_Y+DEFAULT_Y_HEIGHT); int start = -1; int end = -1; for ( int i=0 ; i< chain.getLength() ; i++ ) { Group g = chain.getGroup(i); if ( g.size() > 0 ){ if ( start == -1){ start = i; } end = i; } else { if ( start > -1) { drawStruc(g2D,start,end,aminosize); start = -1 ; } } } // finish if ( start > -1) drawStruc(g2D,start,end,aminosize); } private void drawStruc(Graphics2D g2D, int start, int end, int aminosize){ //System.out.println("Structure " + start + " " + end); int y = DEFAULT_STRUCTURE_Y ; int xstart = java.lang.Math.round(start * scale) + DEFAULT_X_START; int endx = java.lang.Math.round(end * scale)-xstart + DEFAULT_X_START +aminosize; int width = aminosize ; int height = DEFAULT_Y_HEIGHT ; // draw the red structure line g2D.setColor(STRUCTURE_COLOR); g2D.fillRect(xstart,y,endx,height); // highlite the background Composite origComposite = g2D.getComposite(); g2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,0.8f)); g2D.setColor(STRUCTURE_BACKGROUND_COLOR); Dimension dstruc=this.getSize(); Rectangle strucregion = new Rectangle(xstart , 0, endx, dstruc.height); g2D.fill(strucregion); g2D.setComposite(origComposite); } /** draw a line representing a sequence * returns the scaled length of the sequence */ public int drawSequence(Graphics2D g2D, float chainlength){ g2D.setColor(Color.white); int seqx = java.lang.Math.round(chainlength * scale) ; g2D.drawString("Sequence",1,10+DEFAULT_Y_HEIGHT); g2D.fillRect(0+DEFAULT_X_START, 10, seqx, 6); return seqx ; } /** draw the Scale */ public void drawScale(Graphics2D g2D, int chainlength){ g2D.setColor(Color.GRAY); for (int i =0 ; i< chainlength ; i++){ if ( (i%100) == 0 ) { int xpos = Math.round(i*scale)+DEFAULT_X_START ; g2D.fillRect(xpos, 0, 1, 8); }else if ( (i%50) == 0 ) { int xpos = Math.round(i*scale)+DEFAULT_X_START ; g2D.fillRect(xpos, 0, 1, 6); } else if ( (i%10) == 0 ) { int xpos = Math.round(i*scale)+DEFAULT_X_START ; g2D.fillRect(xpos, 0, 1, 4); } } } /** draw the selected region */ public void drawSelection(Graphics2D g2D, int aminosize, int seqx){ if ( selectStart > -1 ) { Dimension dstruc=this.getSize(); g2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,0.8f)); g2D.setColor(SELECTION_COLOR); seqx = java.lang.Math.round(selectStart*scale)+DEFAULT_X_START ; int selectEndX = java.lang.Math.round(selectEnd * scale)-seqx + DEFAULT_X_START +aminosize; if ( selectEndX < aminosize) selectEndX = aminosize ; if ( selectEndX < 1 ) selectEndX = 1 ; Rectangle selection = new Rectangle(seqx , 0, selectEndX, dstruc.height); g2D.fill(selection); } } /** draw the features */ public void drawFeatures(Graphics g2D, int aminosize){ int y = DEFAULT_Y_START ; drawFeatures(g2D,aminosize,y); } /** draw the features starting at position y * returns the y coordinate of the last feature ; * */ public int drawFeatures(Graphics g2D, int aminosize, int y){ //logger.finest("number features: "+features.size()); //System.out.println("seqFeatCanvas aminosize "+ aminosize); boolean secstruc = false ; for (int i = 0 ; i< drawLines.size();i++) { //logger.finest(i%entColors.length); //g2D.setColor(entColors[i%entColors.length]); y = y + DEFAULT_Y_STEP ; List features = (List) drawLines.get(i) ; for ( int f =0 ; f< features.size();f++) { Feature feature = (Feature) features.get(f); // line separator if ( feature.getMethod().equals("_SPICE_LINESEPARATOR")) { //logger.finest("_SPICE_LINESEPARATOR"); String ds = feature.getSource(); g2D.setColor(Color.white); g2D.drawString(ds,DEFAULT_X_START,y+DEFAULT_Y_HEIGHT); continue ; } List segments = feature.getSegments() ; // draw text if ( segments.size() < 1) { //logger.finest(feature.getMethod()); continue ; } Segment seg0 = (Segment) segments.get(0) ; Color col = seg0.getColor(); g2D.setColor(col); g2D.drawString(feature.getName(), 1,y+DEFAULT_Y_HEIGHT); for (int s=0; s<segments.size();s++){ Segment segment=(Segment) segments.get(s); int start = segment.getStart()-1 ; int end = segment.getEnd() -1 ; col = segment.getColor(); g2D.setColor(col); int xstart = java.lang.Math.round(start * scale) + DEFAULT_X_START; int width = java.lang.Math.round(end * scale) - xstart + DEFAULT_X_START+aminosize ; int height = DEFAULT_Y_HEIGHT ; //logger.finest(feature+ " " + end +" " + width); //logger.finest("color"+entColors[i%entColors.length]); //logger.finest("new feature ("+i+"): x1:"+ xstart+" y1:"+y+" width:"+width+" height:"+height); String type = feature.getType() ; if ( type.equals("DISULFID")){ g2D.fillRect(xstart,y,aminosize,height); g2D.fillRect(xstart,y+(height/2),width,1); g2D.fillRect(xstart+width-aminosize,y,aminosize,height); } else { g2D.fillRect(xstart,y,width,height); } } } } return y ; } public void setFeatures( List feats) { //logger.entering(this.getClass().getName(), "setFeatures", new Object[]{" features size: " +feats.size()}); //logger.finest("DasCanv setFeatures"); //features = feats ; // check if features are overlapping, if yes, add to a new line drawLines = new ArrayList(); List currentLine = new ArrayList(); Feature oldFeature = new FeatureImpl(); boolean start = true ; String featureSource = "" ; clearOldLinkMenus(); for (int i=0; i< feats.size(); i++) { Feature feat = (Feature)feats.get(i); // add link to popupmenu String link = feat.getLink(); if ( link != null) { registerLinkMenu(link,feat.getName() ); } String ds =feat.getSource(); // check if new feature source if ( ! featureSource.equals(ds) ) { //logger.finest("new DAS source " + ds ); if ( ! start) { drawLines.add(currentLine); } Feature tmpfeat = new FeatureImpl(); tmpfeat.setSource(ds); tmpfeat.setMethod("_SPICE_LINESEPARATOR"); currentLine = new ArrayList(); currentLine.add(tmpfeat); drawLines.add(currentLine); currentLine = new ArrayList(); } featureSource = ds ; // check for type //logger.finest(feat.toString()); if (oldFeature.getType().equals(feat.getType())){ // see if they are overlapping if ( overlap(oldFeature,feat)) { //logger.finest("OVERLAP found!" + oldFeature+ " "+ feat); drawLines.add(currentLine); currentLine = new ArrayList(); currentLine.add(feat); oldFeature = feat ; } else { // not overlapping, they fit into the same line //logger.finest("same line" + oldFeature+ " "+ feat); currentLine.add(feat); oldFeature = feat ; } } else { // a new feature type has been found // always put into a new line if ( ! start ) { drawLines.add(currentLine); currentLine = new ArrayList(); } start = false; currentLine.add(feat); oldFeature = feat ; } } drawLines.add(currentLine); int height = getImageHeight(); Dimension dstruc=this.getSize(); int width = dstruc.width ; this.setPreferredSize(new Dimension(width,height)) ; this.setMaximumSize(new Dimension(width,height)); this.repaint(); } private void registerLinkMenu(String link, String txt){ // add link to the menu //ActionListener ml = new LinkMenuListener(spice,link); if ( knownLinks.contains(link)) return; //System.out.println("adding menu:" + link); URL u ; try { u = new URL(link); } catch ( MalformedURLException e){ return; } ActionListener ml = new SelectionLockMenuListener(spice,u); JMenuItem menuItem = new JMenuItem("open in browser "+ txt); menuItem.addActionListener(ml); popupMenu.add(menuItem); knownLinks.add(link); } private void clearOldLinkMenus(){ int nr = popupMenu.getComponentCount(); for ( int i = nr-1; i > 0; i popupMenu.remove(i); } knownLinks = new ArrayList(); } /** return height of image. dpends on number of features! */ private int getImageHeight(){ int h = DEFAULT_Y_START + drawLines.size() * DEFAULT_Y_STEP + DEFAULT_Y_BOTTOM; //logger.finest("setting height " + h); return h ; } // an overlap occurs if any of the segments overlap ... private boolean overlap (Feature a, Feature b) { List segmentsa = a.getSegments() ; List segmentsb = b.getSegments(); for ( int i =0; i< segmentsa.size();i++) { Segment sa = (Segment)segmentsa.get(i) ; int starta = sa.getStart(); int enda = sa.getEnd(); for (int j = 0; j<segmentsb.size();j++){ Segment sb = (Segment)segmentsb.get(j) ; // compare boundaries: int startb = sb.getStart(); int endb = sb.getEnd(); // overlap! if (( starta <= endb ) && ( enda >= startb)) return true ; if (( startb <= enda ) && ( endb >= starta)) return true ; } } return false ; } public void setChain(Chain c,int chainnumber) { chain = c; current_chainnumber = chainnumber ; //this.paintComponent(this.getGraphics()); this.repaint(); } /** select a single segment */ private void selectSegment (Segment segment) { //logger.finest("select Segment"); /* // clicked on a segment! Color col = segment.getColor(); //seqColorOld = col ; //spice.setOldColor(col) ; int start = segment.getStart() ; int end = segment.getEnd() ; String type = segment.getType() ; if ( type.equals("DISULFID")){ logger.finest("selectSegment DISULFID " + (start+1) + " " + (end+1)); //String cmd = spice.getSelectStr(current_chainnumber,start+1); //cmd += spice.getSelectStr(current_chainnumber,end+1); String pdb1 = spice.getSelectStrSingle(current_chainnumber,start+1); String pdb2 = spice.getSelectStrSingle(current_chainnumber,end+1); String cmd = "select "+pdb1 +", " + pdb2 + "; spacefill on; cpk on;" ; spice.executeCmd(cmd); } else { spice.select(current_chainnumber,start+1,end+1); } */ } /** highlite a single segment */ private void highliteSegment (Segment segment) { //logger.finest("highlite Segment"); //logger.finest("segment"); // clicked on a segment! String col = segment.getTxtColor(); //seqColorOld = col ; //spice.setOldColor(col) ; int start = segment.getStart(); int end = segment.getEnd() ; start = start -1 ; end = end -1 ; String type = segment.getParent().getType() ; //logger.finest(start+" " + end+" "+type); //logger.finest(segment); if ( type.equals("DISULFID")){ spice.highlite(current_chainnumber,start); spice.highlite(current_chainnumber,end); String pdb1 = spice.getSelectStrSingle(current_chainnumber,start); String pdb2 = spice.getSelectStrSingle(current_chainnumber,end); String cmd = "select "+pdb1 +", " + pdb2 + "; spacefill on; colour cpk;" ; spice.executeCmd(cmd); } else if (type.equals("METAL") ){ spice.highlite(current_chainnumber,start+1,end+1 ,"cpk"); } else if ( type.equals("MSD_SITE") || type.equals("snp") ) { spice.highlite(current_chainnumber,start+1,end+1 ,"wireframe"); } else if ( (end - start) == 0 ) { // feature of size 1 spice.highlite(current_chainnumber,start+1,start+1 ,"cpk"); } else { spice.colour(current_chainnumber,start+1 ,end+1 ,col); } } /** highlite all segments of a feature */ private String highliteFeature(Feature feature){ //logger.finest("highlite feature " + feature); //Feature feature = (Feature) features.get(featurenr) ; //logger.finest("highlite feature " + feature); List segments = feature.getSegments() ; String cmd = "" ; for ( int i =0; i< segments.size() ; i++ ) { Segment segment = (Segment) segments.get(i); //highliteSegment(segment); int start = segment.getStart(); int end = segment.getEnd(); //logger.finest("highilte feature " +featurenr+" " + start + " " +end ); if ( feature.getType().equals("DISULFID")){ cmd += spice.getSelectStr(current_chainnumber,start-1); cmd += "colour cpk; spacefill on;"; cmd += spice.getSelectStr(current_chainnumber,end-1); cmd += "colour cpk; spacefill on;"; } else { cmd += spice.getSelectStr(current_chainnumber,start,end); String col = segment.getTxtColor(); cmd += "color "+ col +";"; } //if ( start == end ) { //cmd += " spacefill on;"; } if ( ( feature.getType().equals("METAL")) || ( feature.getType().equals("SITE")) || ( feature.getType().equals("ACT_SITE")) ){ cmd += " spacefill on; " ; } else if ( feature.getType().equals("MSD_SITE")|| feature.getType().equals("snp") ) { cmd += " wireframe on; " ; } //logger.finest("cmd: "+cmd); return cmd ; } /** select single position select a position */ public void select(int seqpos){ // should be done at spice level //if ( spice.isSelectionLocked() ) return; highlite(seqpos); } /** select range */ public void select(int start, int end) { //if ( spice.isSelectionLocked() ) return; highlite(start,end); } /** same as select here. draw a line at current seqence position * only if chain_number is currently being displayed */ public void highlite( int seqpos){ if ( chain == null ) return ; //if (selectionLocked) return; if ( seqpos > chain.getLength()) return ; selectStart = seqpos ; selectEnd = 1 ; this.repaint(); } /** highlite a region */ public void highlite( int start , int end){ if ( chain == null ) return ; //if (selectionLocked) return ; if ( (start > chain.getLength()) || (end > chain.getLength()) ) return ; selectStart = start ; selectEnd = end ; this.repaint(); } /* check if the mouse is over a feature and if it is * return the feature number * @author andreas * * To change the template for this generated type comment go to * Window - Preferences - Java - Code Generation - Code and Comments */ private int getLineNr(MouseEvent e){ int mouseY = e.getY(); float top = mouseY - DEFAULT_Y_START +1 ; // java.lang.Math.round((y-DEFAULT_Y_START)/ (DEFAULT_Y_STEP + DEFAULT_Y_HEIGHT-1)); float interval = DEFAULT_Y_STEP ; int linenr = java.lang.Math.round(top/interval) -1 ; //logger.finest("top "+top+" interval "+ interval + " top/interval =" + (top/interval) ); if ( linenr >= drawLines.size()){ // can happen at bottom part // simply skip it ... return -1; } return linenr ; } private Feature getFeatureAt(int seqpos, int lineNr){ //logger.finest("getFeatureAt " + seqpos + " " + lineNr); Segment s = getSegmentUnder(seqpos,lineNr); if (s == null ) return null; return s.getParent(); } /** check if mouse is over a segment and if it is, return the segment */ private Segment getSegmentUnder( int seqpos,int lineNr){ //logger.entering(this.getClass().getName(),"getSegmentUnder", new Object[]{new Integer(seqpos),new Integer(lineNr)}); if ( ( lineNr < 0) || ( lineNr >= drawLines.size() ) ){ return null ; } List features = (List) drawLines.get(lineNr); for ( int i =0; i<features.size();i++ ){ Feature feature = (Feature) features.get(i) ; List segments = feature.getSegments() ; for ( int j =0; j< segments.size() ; j++ ) { Segment segment = (Segment) segments.get(j); int start = segment.getStart() -1 ; int end = segment.getEnd() -1 ; if ( (start <= seqpos) && (end >= seqpos) ) { //logger.exiting(this.getClass().getName(),"getSegmentUnder", new Object[]{segment}); return segment ; } } } //logger.exiting(this.getClass().getName(),"getSegmentUnder", new Object[]{null}); return null ; } /** create a tooltip string */ private String getToolString(int seqpos, Segment segment){ //logger.finest("getToolString"); // current position is seqpos String toolstr = spice.getToolString(current_chainnumber,seqpos); //logger.finest("getToolString"); Feature parent = segment.getParent() ; String method = parent.getMethod() ; String type = parent.getType() ; String note = parent.getNote() ; int start = segment.getStart() -1 ; int end = segment.getEnd() -1 ; toolstr += " " + type + " start " + start + " end " + end + " Note:" + note; //logger.finest(toolstr); //new ToolTip(toolstr, this); //this.repaint(); return toolstr ; } /** test if the click was on the name of the feature */ private boolean nameClicked(MouseEvent e) { int x = e.getX(); if (x <= DEFAULT_X_START) { return true ; } return false ; } /** get the sequence position of the current mouse event */ private int getSeqPos(MouseEvent e) { int x = e.getX(); int y = e.getY(); int seqpos = java.lang.Math.round((x-DEFAULT_X_START)/scale) ; return seqpos ; } public void mouseMoved(MouseEvent e) { int b = e.getButton(); //logger.finest("mouseMoved button " +b); // do not change selection if we display the popup window if ( popupMenu.isVisible()) return; if (b != 0 ) if ( b != MouseEvent.BUTTON1 ) return; //, int x, int y int seqpos = getSeqPos(e); int linenr = getLineNr(e); //int featurenr = get_featurenr(y); if ( linenr < 0 ) return ; if ( seqpos < 0 ) return ; // and the feature display //Feature feature = getFeatureAt(seqpos,linenr); Segment segment = getSegmentUnder(seqpos,linenr); if ( segment != null) { String toolstr = getToolString(seqpos,segment); //gfeat.drawString(toolstr,5,13); spice.showStatus(toolstr) ; // display ToolTip this.setToolTipText(toolstr); /* Feature feat = segment.getParent(); String link = feat.getLink(); //logger.finest(segment); if (link != null ) { // check if this feature has a link, if yes, // change mouse cursor System.out.println("setting cursor to hand cursor"); addLinkMenu(link); setCursor(handCursor); } else { System.out.println("setting cursor to default cursor"); setCursor(defaultCursor); removeLinkMenu(); } */ } else { this.setToolTipText(null); setCursor(defaultCursor); spice.showSeqPos(current_chainnumber,seqpos); } if ( spice.isSelectionLocked()) return; spice.select(current_chainnumber,seqpos); return ; } public void mouseClicked(MouseEvent e) { // removed functionality, because of different behaviour of //implementations between OSX and Linux !!!!!! ARGH!! return ; } public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) { int b = e.getButton(); logger.finest("mousePressed "+b); if ( b == MouseEvent.BUTTON1 ) mouseDragStart = getSeqPos(e); } public void mouseReleased(MouseEvent e) { int b = e.getButton(); logger.finest("mouseReleased "+b); if ( b != MouseEvent.BUTTON1) { return; } if ( popupMenu.isVisible()) return; int seqpos = getSeqPos(e); int lineNr = getLineNr(e); //logger.finest("mouseReleased at " + seqpos + " line " + lineNr); if ( seqpos > chain.getLength()) return ; if ( b == MouseEvent.BUTTON1 ) mouseDragStart = -1 ; if ( dragging ) { // we are stopping to drag... dragging = false; return; } if ( b == MouseEvent.BUTTON1 && ( ! spice.isSelectionLocked())) { //System.out.println("checking more"); if ( lineNr < 0 ) return ; if ( seqpos < 0 ) { // check if the name was clicked if (nameClicked(e)){ //System.out.println("nameclicked"); // highlight all features in the line //Feature feature = getFeatureAt(seqpos,lineNr); List features = (List) drawLines.get(lineNr); String cmd = ""; for ( int i=0; i<features.size(); i++) { Feature feature = (Feature) features.get(i); cmd += highliteFeature(feature); } //logger.finest(cmd); spice.executeCmd(cmd); return ; } } else { //System.out.print("getSegmentUnder"); Segment segment = getSegmentUnder(seqpos,lineNr); //logger.finest(segment.toString()); if (segment != null ) { highliteSegment(segment); //String drstr = "x "+ seqpos + " y " + lineNr ; String toolstr = getToolString(seqpos,segment); //spice.showStatus(drstr + " " + toolstr) ; this.setToolTipText(toolstr); } else { if ( ! spice.isSelectionLocked()) spice.highlite(current_chainnumber,seqpos); this.setToolTipText(null); } } } } public void mouseDragged(MouseEvent e) { dragging = true; if ( mouseDragStart < 0 ) return ; if (spice.isSelectionLocked()) return; int b = e.getButton(); logger.finest("dragging mouse "+b); // ARGH my linux java 142_05 does not show Button 1 when being dragged! //if ( b != MouseEvent.BUTTON1 ) // return; // only do with left mouse click int seqpos = getSeqPos(e); int selEnd = seqpos; int start = mouseDragStart ; int end = selEnd ; if ( selEnd < mouseDragStart ) { start = selEnd ; end = mouseDragStart ; } spice.highlite(current_chainnumber,start,end); } }
package org.nschmidt.ldparteditor.data; import java.math.BigDecimal; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.TreeMap; import java.util.TreeSet; import org.lwjgl.util.vector.Matrix4f; import org.lwjgl.util.vector.Vector4f; import org.nschmidt.csg.CSG; import org.nschmidt.csg.CSGCircle; import org.nschmidt.csg.CSGCone; import org.nschmidt.csg.CSGCube; import org.nschmidt.csg.CSGCylinder; import org.nschmidt.csg.CSGQuad; import org.nschmidt.csg.CSGSphere; import org.nschmidt.csg.Plane; import org.nschmidt.ldparteditor.composites.Composite3D; import org.nschmidt.ldparteditor.enums.MyLanguage; import org.nschmidt.ldparteditor.helpers.math.MathHelper; import org.nschmidt.ldparteditor.helpers.math.Vector3d; import org.nschmidt.ldparteditor.helpers.math.Vector3dd; import org.nschmidt.ldparteditor.i18n.I18n; import org.nschmidt.ldparteditor.logger.NLogger; import org.nschmidt.ldparteditor.text.DatParser; /** * @author nils * */ public final class GDataCSG extends GData { final byte type; private final static HashMap<String, CSG> linkedCSG = new HashMap<String, CSG>(); private static boolean deleteAndRecompile = true; private final static HashSet<GDataCSG> registeredData = new HashSet<GDataCSG>(); private final static HashSet<GDataCSG> parsedData = new HashSet<GDataCSG>(); private static int quality = 16; private int global_quality = 16; private double global_epsilon = 1e-6; private final String ref1; private final String ref2; private final String ref3; private CSG compiledCSG = null; private final GColour colour; final Matrix4f matrix; public static void forceRecompile() { registeredData.add(null); Plane.EPSILON = 1e-3; } public static void fullReset() { quality = 16; registeredData.clear(); linkedCSG.clear(); parsedData.clear(); Plane.EPSILON = 1e-3; } public static void resetCSG() { quality = 16; HashSet<GDataCSG> ref = new HashSet<GDataCSG>(registeredData); ref.removeAll(parsedData); deleteAndRecompile = !ref.isEmpty(); if (deleteAndRecompile) { registeredData.clear(); registeredData.add(null); linkedCSG.clear(); } parsedData.clear(); } public byte getCSGtype() { return type; } // CASE 1 0 !LPE [CSG TAG] [ID] [COLOUR] [MATRIX] 17 // CASE 2 0 !LPE [CSG TAG] [ID] [ID2] [ID3] 6 // CASE 3 0 !LPE [CSG TAG] [ID] 4 public GDataCSG(byte type, String csgLine, GData1 parent) { registeredData.add(this); String[] data_segments = csgLine.trim().split("\\s+"); //$NON-NLS-1$ this.type = type; this.text = csgLine; switch (type) { case CSG.COMPILE: if (data_segments.length == 4) { ref1 = data_segments[3] + "#>" + parent.shortName; //$NON-NLS-1$ } else { ref1 = null; } ref2 = null; ref3 = null; colour = null; matrix = null; break; case CSG.QUAD: case CSG.CIRCLE: case CSG.ELLIPSOID: case CSG.CUBOID: case CSG.CYLINDER: case CSG.CONE: if (data_segments.length == 17) { ref1 = data_segments[3] + "#>" + parent.shortName; //$NON-NLS-1$ GColour c = DatParser.validateColour(data_segments[4], .5f, .5f, .5f, 1f); if (c != null) { colour = c.clone(); } else { colour = null; } matrix = MathHelper.matrixFromStrings(data_segments[5], data_segments[6], data_segments[7], data_segments[8], data_segments[11], data_segments[14], data_segments[9], data_segments[12], data_segments[15], data_segments[10], data_segments[13], data_segments[16]); } else { colour = null; matrix = null; ref1 = null; } ref2 = null; ref3 = null; break; case CSG.DIFFERENCE: case CSG.INTERSECTION: case CSG.UNION: if (data_segments.length == 6) { ref1 = data_segments[3] + "#>" + parent.shortName; //$NON-NLS-1$ ref2 = data_segments[4] + "#>" + parent.shortName; //$NON-NLS-1$ ref3 = data_segments[5] + "#>" + parent.shortName; //$NON-NLS-1$ } else { ref1 = null; ref2 = null; ref3 = null; } colour = null; matrix = null; break; case CSG.QUALITY: if (data_segments.length == 4) { try { int q = Integer.parseInt(data_segments[3]); if (q > 0 && q < 49) { global_quality = q; } else { throw new Exception(); } } catch (Exception e) { } ref1 = data_segments[3] + "#>" + parent.shortName; //$NON-NLS-1$ } else { ref1 = null; } ref2 = null; ref3 = null; colour = null; matrix = null; break; case CSG.EPSILON: if (data_segments.length == 4) { try { double q = Double.parseDouble(data_segments[3]); if (q > 0d) { global_epsilon = q; } else { throw new Exception(); } } catch (Exception e) { } ref1 = data_segments[3] + "#>" + parent.shortName; //$NON-NLS-1$ } else { ref1 = null; } ref2 = null; ref3 = null; colour = null; matrix = null; break; default: ref1 = null; ref2 = null; ref3 = null; colour = null; matrix = null; break; } } private void drawAndParse(Composite3D c3d) { parsedData.add(this); if (deleteAndRecompile) { registeredData.remove(null); try { compiledCSG = null; registeredData.add(this); if (ref1 != null) { switch (type) { case CSG.QUAD: case CSG.CIRCLE: case CSG.ELLIPSOID: case CSG.CUBOID: case CSG.CYLINDER: case CSG.CONE: if (matrix != null) { switch (type) { case CSG.QUAD: CSGQuad quad = new CSGQuad(); CSG csgQuad = quad.toCSG(colour).transformed(matrix); linkedCSG.put(ref1, csgQuad); break; case CSG.CIRCLE: CSGCircle circle = new CSGCircle(quality); CSG csgCircle = circle.toCSG(colour).transformed(matrix); linkedCSG.put(ref1, csgCircle); break; case CSG.ELLIPSOID: CSGSphere sphere = new CSGSphere(quality, quality / 2); CSG csgSphere = sphere.toCSG(colour).transformed(matrix); linkedCSG.put(ref1, csgSphere); break; case CSG.CUBOID: CSGCube cube = new CSGCube(); CSG csgCube = cube.toCSG(colour).transformed(matrix); linkedCSG.put(ref1, csgCube); break; case CSG.CYLINDER: CSGCylinder cylinder = new CSGCylinder(quality); CSG csgCylinder = cylinder.toCSG(colour).transformed(matrix); linkedCSG.put(ref1, csgCylinder); break; case CSG.CONE: CSGCone cone = new CSGCone(quality); CSG csgCone = cone.toCSG(colour).transformed(matrix); linkedCSG.put(ref1, csgCone); break; default: break; } } break; case CSG.COMPILE: if (linkedCSG.containsKey(ref1)) { compiledCSG = linkedCSG.get(ref1); compiledCSG.compile(); } else { compiledCSG = null; } break; case CSG.DIFFERENCE: if (linkedCSG.containsKey(ref1) && linkedCSG.containsKey(ref2)) { linkedCSG.put(ref3, linkedCSG.get(ref1).difference(linkedCSG.get(ref2))); } break; case CSG.INTERSECTION: if (linkedCSG.containsKey(ref1) && linkedCSG.containsKey(ref2)) { linkedCSG.put(ref3, linkedCSG.get(ref1).intersect(linkedCSG.get(ref2))); } break; case CSG.UNION: if (linkedCSG.containsKey(ref1) && linkedCSG.containsKey(ref2)) { linkedCSG.put(ref3, linkedCSG.get(ref1).union(linkedCSG.get(ref2))); } break; case CSG.QUALITY: quality = global_quality; break; case CSG.EPSILON: Plane.EPSILON = global_epsilon; break; default: break; } } } catch (StackOverflowError e) { registeredData.clear(); linkedCSG.clear(); parsedData.clear(); deleteAndRecompile = false; registeredData.add(null); Plane.EPSILON = Plane.EPSILON * 10d; } catch (Exception e) { } } if (compiledCSG != null) { if (c3d.getRenderMode() != 5) { compiledCSG.draw(c3d); } else { compiledCSG.draw_textured(c3d); } } } @Override public void draw(Composite3D c3d) { drawAndParse(c3d); } @Override public void drawRandomColours(Composite3D c3d) { drawAndParse(c3d); } @Override public void drawBFC(Composite3D c3d) { drawAndParse(c3d); } @Override public void drawBFCuncertified(Composite3D c3d) { drawAndParse(c3d); } @Override public void drawBFC_backOnly(Composite3D c3d) { drawAndParse(c3d); } @Override public void drawBFC_Colour(Composite3D c3d) { drawAndParse(c3d); } @Override public void drawBFC_Textured(Composite3D c3d) { drawAndParse(c3d); } @Override public void drawWhileAddCondlines(Composite3D c3d) { drawAndParse(c3d); } @Override public int type() { return 8; } @Override String getNiceString() { return text; } @Override public String inlinedString(byte bfc, GColour colour) { switch (type) { case CSG.COMPILE: if (compiledCSG != null) { StringBuilder sb = new StringBuilder(); Object[] messageArguments = {getNiceString()}; MessageFormat formatter = new MessageFormat(""); //$NON-NLS-1$ formatter.setLocale(MyLanguage.LOCALE); formatter.applyPattern(I18n.DATFILE_Inlined); sb.append(formatter.format(messageArguments) + "<br>"); //$NON-NLS-1$ // FIXME Needs T-Junction Elimination! HashMap<Integer, ArrayList<GData3>> surfaces = new HashMap<Integer, ArrayList<GData3>>(); TreeSet<Vector3dd> verts = new TreeSet<Vector3dd>(); HashMap<GData3, Integer[]> result = compiledCSG.getResult(); HashMap<Integer, ArrayList<Vector3dd[]>> edges = new HashMap<Integer, ArrayList<Vector3dd[]>>(); // 1. Create surfaces, vertices and edges NLogger.debug(getClass(), "1. Create surfaces, vertices and edges"); //$NON-NLS-1$ for (GData3 g3 : result.keySet()) { Integer key = result.get(g3)[0]; if (!surfaces.containsKey(key)) { surfaces.put(key, new ArrayList<GData3>()); edges.put(key, new ArrayList<Vector3dd[]>()); } ArrayList<GData3> elements = surfaces.get(key); ArrayList<Vector3dd[]> edges2 = edges.get(key); elements.add(g3); Vector3dd a = new Vector3dd(new Vector3d(g3.X1, g3.Y1, g3.Z1)); Vector3dd b = new Vector3dd(new Vector3d(g3.X2, g3.Y2, g3.Z2)); Vector3dd c = new Vector3dd(new Vector3d(g3.X3, g3.Y3, g3.Z3)); verts.add(a); verts.add(b); verts.add(c); edges2.add(new Vector3dd[]{a, b}); edges2.add(new Vector3dd[]{b, c}); edges2.add(new Vector3dd[]{c, a}); } // 1.5 Unify near vertices (Threshold 0.001) // 2. Detect outer edges NLogger.debug(getClass(), "2. Detect outer edges"); //$NON-NLS-1$ { TreeSet<Integer> keys = new TreeSet<Integer>(); for (GData3 g3 : result.keySet()) { Integer key = result.get(g3)[0]; keys.add(key); } for (Integer key : keys) { ArrayList<Vector3dd[]> outerEdges = new ArrayList<Vector3dd[]>(); ArrayList<Vector3dd[]> edges2 = edges.get(key); for (Vector3dd[] e1 : edges2) { boolean isOuter = true; for (Vector3dd[] e2 : edges2) { if (e1 != e2) { if ( e1[0].equals(e2[0]) && e1[1].equals(e2[1]) || e1[1].equals(e2[0]) && e1[0].equals(e2[1])) { isOuter = false; break; } } } if (isOuter) { outerEdges.add(new Vector3dd[]{e1[0], e1[1]}); } } edges2.clear(); edges2.addAll(outerEdges); } // 3. Remove collinear points NLogger.debug(getClass(), "3. Remove collinear points"); //$NON-NLS-1$ { final BigDecimal fourMinusEpsilon = new BigDecimal("3.9"); //$NON-NLS-1$ for (Integer key : keys) { boolean foundCollinearity = true; while (foundCollinearity) { foundCollinearity = false; ArrayList<Vector3dd[]> edges2 = edges.get(key); Vector3dd[] match = new Vector3dd[2]; for (Vector3dd[] e1 : edges2) { if (foundCollinearity) { break; } for (Vector3dd[] e2 : edges2) { if (e1 != e2) { int[] index = new int[]{0,0,0,0}; if (e1[0].equals(e2[0])) { index[0] = 0; index[1] = 1; index[2] = 0; index[3] = 1; } else if (e1[1].equals(e2[1])) { index[0] = 1; index[1] = 0; index[2] = 1; index[3] = 0; } else if (e1[1].equals(e2[0])) { index[0] = 1; index[1] = 0; index[2] = 0; index[3] = 1; } else if (e1[0].equals(e2[1])) { index[0] = 0; index[1] = 1; index[2] = 1; index[3] = 0; } // Check "angle" Vector3d v1 = Vector3d.sub(e1[index[1]], e1[index[0]]); if (v1.length().compareTo(BigDecimal.ZERO) == 0) { continue; } Vector3d v2 = Vector3d.sub(e2[index[1]], e2[index[0]]); if (v2.length().compareTo(BigDecimal.ZERO) == 0) { continue; } v1.normalise(v1); v2.normalise(v2); BigDecimal d = Vector3d.distSquare(v1, v2); if (d.compareTo(fourMinusEpsilon) > 0) { NLogger.debug(getClass(), "3. Found collinear points"); //$NON-NLS-1$ foundCollinearity = true; match[0] = e1[index[0]]; match[1] = e1[index[1]]; break; } } } } if (foundCollinearity) { for (Iterator<Vector3dd[]> it = edges2.iterator(); it.hasNext();) { Vector3dd[] v = it.next(); if (v[0].equals(match[0]) && v[1].equals(match[1])) { it.remove(); } else if (v[0].equals(match[1]) && v[1].equals(match[0])) { it.remove(); } else if (v[0].equals(match[0])) { v[0] = match[1]; } else if (v[1].equals(match[0])) { v[1] = match[1]; } } } } } } // 4. Re-Triangulate NLogger.debug(getClass(), "4. Re-Triangulate"); //$NON-NLS-1$ { for (Integer key : keys) { ArrayList<Vector3dd[]> edges2 = edges.get(key); for (Vector3dd[] e1 : edges2) { } } } } for (GData3 g3 : result.keySet()) { StringBuilder lineBuilder3 = new StringBuilder(); lineBuilder3.append(3); lineBuilder3.append(" "); //$NON-NLS-1$ if (g3.colourNumber == -1) { lineBuilder3.append("0x2"); //$NON-NLS-1$ lineBuilder3.append(MathHelper.toHex((int) (255f * g3.r)).toUpperCase()); lineBuilder3.append(MathHelper.toHex((int) (255f * g3.g)).toUpperCase()); lineBuilder3.append(MathHelper.toHex((int) (255f * g3.b)).toUpperCase()); } else { lineBuilder3.append(g3.colourNumber); } Vector4f g3_v1 = new Vector4f(g3.x1, g3.y1, g3.z1, 1f); Vector4f g3_v2 = new Vector4f(g3.x2, g3.y2, g3.z2, 1f); Vector4f g3_v3 = new Vector4f(g3.x3, g3.y3, g3.z3, 1f); lineBuilder3.append(" "); //$NON-NLS-1$ lineBuilder3.append(floatToString(g3_v1.x / 1000f)); lineBuilder3.append(" "); //$NON-NLS-1$ lineBuilder3.append(floatToString(g3_v1.y / 1000f)); lineBuilder3.append(" "); //$NON-NLS-1$ lineBuilder3.append(floatToString(g3_v1.z / 1000f)); lineBuilder3.append(" "); //$NON-NLS-1$ lineBuilder3.append(floatToString(g3_v2.x / 1000f)); lineBuilder3.append(" "); //$NON-NLS-1$ lineBuilder3.append(floatToString(g3_v2.y / 1000f)); lineBuilder3.append(" "); //$NON-NLS-1$ lineBuilder3.append(floatToString(g3_v2.z / 1000f)); lineBuilder3.append(" "); //$NON-NLS-1$ lineBuilder3.append(floatToString(g3_v3.x / 1000f)); lineBuilder3.append(" "); //$NON-NLS-1$ lineBuilder3.append(floatToString(g3_v3.y / 1000f)); lineBuilder3.append(" "); //$NON-NLS-1$ lineBuilder3.append(floatToString(g3_v3.z / 1000f)); sb.append(lineBuilder3.toString() + "<br>"); //$NON-NLS-1$ } return sb.toString(); } else { return getNiceString(); } default: return getNiceString(); } } private String floatToString(float flt) { String result; if (flt == (int) flt) { result = String.format("%d", (int) flt); //$NON-NLS-1$ } else { result = String.format("%s", flt); //$NON-NLS-1$ if (result.equals("0.0"))result = "0"; //$NON-NLS-1$ //$NON-NLS-2$ } if (result.startsWith("-0."))return "-" + result.substring(2); //$NON-NLS-1$ //$NON-NLS-2$ if (result.startsWith("0."))return result.substring(1); //$NON-NLS-1$ return result; } @Override public String transformAndColourReplace(String colour2, Matrix matrix) { boolean notChoosen = true; String t = null; switch (type) { case CSG.QUAD: if (notChoosen) { t = " CSG_QUAD "; //$NON-NLS-1$ notChoosen = false; } case CSG.CIRCLE: if (notChoosen) { t = " CSG_CIRCLE "; //$NON-NLS-1$ notChoosen = false; } case CSG.ELLIPSOID: if (notChoosen) { t = " CSG_ELLIPSOID "; //$NON-NLS-1$ notChoosen = false; } case CSG.CUBOID: if (notChoosen) { t = " CSG_CUBOID "; //$NON-NLS-1$ notChoosen = false; } case CSG.CYLINDER: if (notChoosen) { t = " CSG_CYLINDER "; //$NON-NLS-1$ notChoosen = false; } case CSG.CONE: if (notChoosen) { t = " CSG_CONE "; //$NON-NLS-1$ notChoosen = false; } StringBuilder colourBuilder = new StringBuilder(); if (colour == null) { colourBuilder.append(16); } else if (colour.getColourNumber() == -1) { colourBuilder.append("0x2"); //$NON-NLS-1$ colourBuilder.append(MathHelper.toHex((int) (255f * colour.getR())).toUpperCase()); colourBuilder.append(MathHelper.toHex((int) (255f * colour.getG())).toUpperCase()); colourBuilder.append(MathHelper.toHex((int) (255f * colour.getB())).toUpperCase()); } else { colourBuilder.append(colour.getColourNumber()); } Matrix4f newMatrix = new Matrix4f(this.matrix); Matrix4f newMatrix2 = new Matrix4f(matrix.getMatrix4f()); Matrix4f.transpose(newMatrix, newMatrix); newMatrix.m30 = newMatrix.m03; newMatrix.m31 = newMatrix.m13; newMatrix.m32 = newMatrix.m23; newMatrix.m03 = 0f; newMatrix.m13 = 0f; newMatrix.m23 = 0f; Matrix4f.mul(newMatrix2, newMatrix, newMatrix); String col = colourBuilder.toString(); if (col.equals(colour2)) col = "16"; //$NON-NLS-1$ String tag = ref1.substring(0, ref1.lastIndexOf("#>")); //$NON-NLS-1$ return "0 !LPE" + t + tag + " " + col + " " + MathHelper.matrixToString(newMatrix); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ default: return text; } } @Override public void getBFCorientationMap(HashMap<GData, Byte> map) {} @Override public void getBFCorientationMapNOCERTIFY(HashMap<GData, Byte> map) {} @Override public void getBFCorientationMapNOCLIP(HashMap<GData, Byte> map) {} @Override public void getVertexNormalMap(TreeMap<Vertex, float[]> vertexLinkedToNormalCACHE, HashMap<GData, float[]> dataLinkedToNormalCACHE, VertexManager vm) {} @Override public void getVertexNormalMapNOCERTIFY(TreeMap<Vertex, float[]> vertexLinkedToNormalCACHE, HashMap<GData, float[]> dataLinkedToNormalCACHE, VertexManager vm) {} @Override public void getVertexNormalMapNOCLIP(TreeMap<Vertex, float[]> vertexLinkedToNormalCACHE, HashMap<GData, float[]> dataLinkedToNormalCACHE, VertexManager vm) {} }
package org.opencms.workplace.commons; import org.opencms.file.CmsObject; import org.opencms.file.CmsProperty; import org.opencms.file.CmsPropertyDefinition; import org.opencms.file.CmsResource; import org.opencms.file.CmsResourceFilter; import org.opencms.file.types.CmsResourceTypePlain; import org.opencms.file.types.I_CmsResourceType; import org.opencms.jsp.CmsJspActionElement; import org.opencms.loader.CmsLoaderException; import org.opencms.main.CmsException; import org.opencms.main.OpenCms; import org.opencms.security.CmsPermissionSet; import org.opencms.security.CmsRole; import org.opencms.util.CmsStringUtil; import org.opencms.workplace.CmsWorkplaceSettings; import org.opencms.workplace.explorer.CmsExplorerTypeSettings; import org.opencms.workplace.explorer.CmsNewResource; import org.opencms.workplace.list.A_CmsListResourceTypeDialog; import org.opencms.workplace.list.CmsListItem; import org.opencms.workplace.list.CmsListOrderEnum; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.JspException; import javax.servlet.jsp.PageContext; /** * The change resource type dialog handles the change of a resource type of a single VFS file.<p> * * The following files use this class: * <ul> * <li>/commons/chtype.jsp * </ul> * <p> * * @author Andreas Zahner * @author Peter Bonrad * * @version $Revision: 1.26 $ * * @since 6.0.0 */ public class CmsChtype extends A_CmsListResourceTypeDialog { /** Dialog action: show advanced list (for workplace VFS managers). */ public static final int ACTION_ADVANCED = 555; /** The dialog type.<p> */ public static final String DIALOG_TYPE = "chtype"; /** Session attribute to store advanced mode. */ public static final String SESSION_ATTR_ADVANCED = "ocms_chtype_adv"; /** Flag indicating if dialog is in advanced mode. */ private boolean m_advancedMode; /** The available resource types as String, if set. */ private String m_availableResTypes; /** Flag indicating if resource types to select are limited. */ private boolean m_limitedRestypes; /** * Public constructor with JSP action element.<p> * * @param jsp an initialized JSP action element */ public CmsChtype(CmsJspActionElement jsp) { super( jsp, A_CmsListResourceTypeDialog.LIST_ID, Messages.get().container(Messages.GUI_CHTYPE_PLEASE_SELECT_0), A_CmsListResourceTypeDialog.LIST_COLUMN_NAME, CmsListOrderEnum.ORDER_ASCENDING, null); } /** * Public constructor with JSP variables.<p> * * @param context the JSP page context * @param req the JSP request * @param res the JSP response */ public CmsChtype(PageContext context, HttpServletRequest req, HttpServletResponse res) { this(new CmsJspActionElement(context, req, res)); } /** * Uploads the specified file and replaces the VFS file.<p> * * @throws JspException if inclusion of error dialog fails */ public void actionChtype() throws JspException { try { int newType = CmsResourceTypePlain.getStaticTypeId(); try { // get new resource type id from request newType = Integer.parseInt(getParamSelectedType()); } catch (NumberFormatException nf) { throw new CmsException(Messages.get().container(Messages.ERR_GET_RESTYPE_1, getParamSelectedType())); } // check the resource lock state checkLock(getParamResource()); // change the resource type getCms().chtype(getParamResource(), newType); // close the dialog window actionCloseDialog(); } catch (Throwable e) { // error changing resource type, show error dialog includeErrorpage(this, e); } } /** * @see org.opencms.workplace.list.A_CmsListDialog#actionDialog() */ public void actionDialog() throws JspException, ServletException, IOException { if (getAction() == ACTION_OK) { actionChtype(); return; } else if (getAction() == ACTION_ADVANCED) { refreshList(); return; } super.actionDialog(); } /** * Builds a default button row with a continue and cancel button.<p> * * Override this to have special buttons for your dialog.<p> * * @return the button row */ public String dialogButtons() { return dialogButtonsOkAdvancedCancel( " onclick=\"submitChtype(form);\"", " onclick=\"submitAdvanced(form);\"", null); } /** * Builds a button row with an optional "ok", "advanced" and a "cancel" button.<p> * * @param okAttrs optional attributes for the ok button * @param advancedAttrs optional attributes for the advanced button * @param cancelAttrs optional attributes for the cancel button * @return the button row */ public String dialogButtonsOkAdvancedCancel(String okAttrs, String advancedAttrs, String cancelAttrs) { if (!m_advancedMode && m_limitedRestypes && OpenCms.getRoleManager().hasRole(getCms(), CmsRole.VFS_MANAGER)) { return dialogButtons(new int[] {BUTTON_OK, BUTTON_ADVANCED, BUTTON_CANCEL}, new String[] { okAttrs, advancedAttrs, cancelAttrs}); } else { return dialogButtonsOkCancel(okAttrs, cancelAttrs); } } /** * @see org.opencms.workplace.list.A_CmsListResourceTypeDialog#getParamSelectedType() */ public String getParamSelectedType() { String item = super.getParamSelectedType(); if (CmsStringUtil.isEmptyOrWhitespaceOnly(item)) { // determine resource type id of resource to change try { CmsResource res = getCms().readResource(getParamResource(), CmsResourceFilter.ALL); return Integer.toString(res.getTypeId()); } catch (CmsException e) { // do nothing } } return item; } /** * Returns the html code to add directly before the list inside the form element.<p> * * @return the html code to add directly before the list inside the form element */ protected String customHtmlBeforeList() { StringBuffer result = new StringBuffer(256); result.append(dialogBlockStart(null)); result.append(key(Messages.GUI_LABEL_TITLE_0)); result.append(": "); result.append(getJsp().property("Title", getParamResource(), "")); result.append("<br>"); result.append(key(Messages.GUI_LABEL_STATE_0)); result.append(": "); try { result.append(getState()); } catch (CmsException e) { // not so important ... just go on } result.append("<br>"); result.append(key(Messages.GUI_LABEL_PERMALINK_0)); result.append(": "); result.append(OpenCms.getLinkManager().getPermalink(getCms(), getParamResource())); result.append(dialogBlockEnd()); result.append(dialogSpacer()); return result.toString(); } /** * @see org.opencms.workplace.list.A_CmsListDialog#customHtmlStart() */ protected String customHtmlStart() { StringBuffer result = new StringBuffer(256); result.append(super.customHtmlStart()); result.append("<script type='text/javascript'>\n"); result.append("function submitAdvanced(theForm) {\n"); result.append("\ttheForm.action.value = \"" + CmsNewResource.DIALOG_ADVANCED + "\";\n"); result.append("\ttheForm.submit();\n"); result.append("}\n\n"); result.append("function submitChtype(theForm) {\n"); result.append("\ttheForm.action.value = \"" + DIALOG_OK + "\";\n"); result.append("\ttheForm.submit();\n"); result.append("}\n\n"); result.append("</script>"); return result.toString(); } /** * @see org.opencms.workplace.list.A_CmsListDialog#getListItems() */ protected List getListItems() throws CmsException { List ret = new ArrayList(); // fill the list with available resource types if they are limited List availableResTypes = new ArrayList(); if (!m_advancedMode && m_limitedRestypes) { if (m_availableResTypes.indexOf(CmsNewResource.DELIM_PROPERTYVALUES) > -1) { availableResTypes = CmsStringUtil.splitAsList( m_availableResTypes, CmsNewResource.DELIM_PROPERTYVALUES, true); } else { availableResTypes = CmsStringUtil.splitAsList( m_availableResTypes, CmsProperty.VALUE_LIST_DELIMITER, true); } } // get current Cms object CmsObject cms = getCms(); // determine resource type id of resource to change CmsResource res = cms.readResource(getParamResource(), CmsResourceFilter.ALL); // get all available explorer type settings List resTypes = OpenCms.getWorkplaceManager().getExplorerTypeSettings(); boolean isFolder = res.isFolder(); // loop through all visible resource types for (int i = 0; i < resTypes.size(); i++) { boolean changeable = false; // get explorer type settings for current resource type CmsExplorerTypeSettings settings = (CmsExplorerTypeSettings)resTypes.get(i); // only if settings is a real resourcetype boolean isResourceType; I_CmsResourceType type = new CmsResourceTypePlain(); try { type = OpenCms.getResourceManager().getResourceType(settings.getName()); isResourceType = true; } catch (CmsLoaderException e) { isResourceType = false; } if (isResourceType) { // first check if types are limited if (!m_advancedMode && m_limitedRestypes && availableResTypes.indexOf(type.getTypeName()) == -1) { // this resource type is not in the list of available types, skip it continue; } int resTypeId = OpenCms.getResourceManager().getResourceType(settings.getName()).getTypeId(); // determine if this resTypeId is changeable by currentResTypeId // changeable is true if current resource is a folder and this resource type also if (isFolder && OpenCms.getResourceManager().getResourceType(resTypeId).isFolder()) { changeable = true; } else if (!isFolder && !OpenCms.getResourceManager().getResourceType(resTypeId).isFolder()) { // changeable is true if current resource is NOT a folder and this resource type also NOT changeable = true; } if (changeable) { // determine if this resource type is editable for the current user CmsPermissionSet permissions = settings.getAccess().getPermissions(cms, res); if (!permissions.requiresWritePermission() || !permissions.requiresControlPermission()) { continue; } // add found setting to list CmsListItem item = getList().newItem(Integer.toString(resTypeId)); item.set(LIST_COLUMN_NAME, key(settings.getKey())); item.set(LIST_COLUMN_ICON, "<img src=\"" + getSkinUri() + "filetypes/" + settings.getIcon() + "\" style=\"width: 16px; height: 16px;\" />"); ret.add(item); } } } return ret; } /** * @see org.opencms.workplace.CmsWorkplace#initWorkplaceRequestValues(org.opencms.workplace.CmsWorkplaceSettings, javax.servlet.http.HttpServletRequest) */ protected void initWorkplaceRequestValues(CmsWorkplaceSettings settings, HttpServletRequest request) { // first call of dialog setAction(ACTION_DEFAULT); super.initWorkplaceRequestValues(settings, request); if (!checkResourcePermissions(CmsPermissionSet.ACCESS_WRITE, false)) { setParamAction(DIALOG_CANCEL); } // set the dialog type setParamDialogtype(DIALOG_TYPE); // set the action for the JSP switch if (DIALOG_OK.equals(getParamAction())) { // ok button pressed, change file type setAction(ACTION_OK); getJsp().getRequest().getSession(true).removeAttribute(SESSION_ATTR_ADVANCED); } else if (DIALOG_LOCKS_CONFIRMED.equals(getParamAction())) { setAction(ACTION_LOCKS_CONFIRMED); } else if (DIALOG_CANCEL.equals(getParamAction())) { // cancel button pressed setAction(ACTION_CANCEL); getJsp().getRequest().getSession(true).removeAttribute(SESSION_ATTR_ADVANCED); } else { // build title for change file type dialog setParamTitle(key(Messages.GUI_CHTYPE_1, new Object[] {CmsResource.getName(getParamResource())})); } // get session attribute storing if we are in advanced mode String sessionAttr = (String)request.getSession(true).getAttribute(SESSION_ATTR_ADVANCED); if (CmsNewResource.DIALOG_ADVANCED.equals(getParamAction()) || sessionAttr != null) { // advanced mode to display all possible resource types if (sessionAttr == null) { // set attribute that we are in advanced mode request.getSession(true).setAttribute(SESSION_ATTR_ADVANCED, "true"); setAction(ACTION_ADVANCED); } m_advancedMode = true; } else { // check for presence of property limiting the new resource types to create String newResTypesProperty = ""; try { newResTypesProperty = getCms().readPropertyObject( getParamResource(), CmsPropertyDefinition.PROPERTY_RESTYPES_AVAILABLE, true).getValue(); } catch (CmsException e) { // ignore this exception, this is a minor issue } if (CmsStringUtil.isNotEmpty(newResTypesProperty) && !newResTypesProperty.equals(CmsNewResource.VALUE_DEFAULT)) { m_limitedRestypes = true; m_availableResTypes = newResTypesProperty; } } } }
package org.phenoscape.util; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.jdom.Document; import org.jdom.Element; import org.jdom.input.DOMBuilder; import org.obo.datamodel.Namespace; import org.obo.datamodel.OBOClass; import org.obo.datamodel.OBOProperty; import org.obo.datamodel.OBOSession; import org.obo.datamodel.impl.DanglingClassImpl; import org.obo.datamodel.impl.OBOClassImpl; import org.obo.datamodel.impl.OBORestrictionImpl; import org.xml.sax.SAXException; public class ProvisionalTermUtil { private static final String SERVICE = "http://rest.bioontology.org/bioportal/provisional"; private static final String APIKEY = "37697970-f916-40fe-bfeb-46aadbd07dba"; public static List<OBOClass> getProvisionalTerms(OBOSession session) throws IllegalStateException, SAXException, IOException, ParserConfigurationException { final List<NameValuePair> values = new ArrayList<NameValuePair>(); values.add(new BasicNameValuePair("apikey", APIKEY)); values.add(new BasicNameValuePair("submittedby", "39814")); values.add(new BasicNameValuePair("pagesize", "9999")); final String paramString = URLEncodedUtils.format(values, "utf-8"); final HttpGet get = new HttpGet(SERVICE + "?" + paramString); final DefaultHttpClient client = new DefaultHttpClient(); final HttpResponse response = new DefaultHttpClient().execute(get); client.getConnectionManager().shutdown(); final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); final DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); final Document xmlDoc = new DOMBuilder().build(docBuilder.parse(response.getEntity().getContent())); @SuppressWarnings("unchecked") final List<Element> termElements = xmlDoc.getRootElement().getChild("data").getChild("page").getChild("contents").getChild("classBeanResultList").getChildren("classBean"); final List<OBOClass> terms = new ArrayList<OBOClass>(); for (Element element : termElements) { terms.add(createClassForProvisionalTerm(element, session)); } return terms; } public static OBOClass createClassForProvisionalTerm(Element element, OBOSession session) { final String termID = element.getChild("id").getValue(); final String label = element.getChild("label").getValue(); final String definition = element.getChild("definitions").getValue(); final String parentURI = findParentURI(element); final OBOClass newTerm = new OBOClassImpl(termID); newTerm.setName(label); newTerm.setDefinition(definition); final String permanentID = findPermanentID(element); if (permanentID != null) { newTerm.setObsolete(true); final String replacedByID = toOBOID(permanentID); final OBOClass replacedBy = findClassOrCreateDangler(replacedByID, session); newTerm.addReplacedBy(replacedBy); } if ((!newTerm.isObsolete()) && (parentURI != null)) { final String parentOBOID = toOBOID(parentURI); final OBOClass parent = findClassOrCreateDangler(parentOBOID, session); newTerm.addParent(new OBORestrictionImpl(newTerm, parent, (OBOProperty)(session.getObject("OBO_REL:is_a")))); } newTerm.setNamespace(new Namespace("bioportal_provisional")); return newTerm; } public static String toURI(String oboID) { return "http://purl.obolibrary.org/obo/" + oboID.replaceAll(":", "_"); } public static String toOBOID(String uri) { if (uri.contains("http://purl.obolibrary.org/obo/")) { final String id = uri.split("http://purl.obolibrary.org/obo/")[1]; final int underscore = id.lastIndexOf("_"); return id.substring(0, underscore) + ":" + id.substring(underscore + 1, id.length()); } else { return uri; } } private static OBOClass findClassOrCreateDangler(String oboID, OBOSession session) { final OBOClass term; if (session.getObject(oboID) != null) { term = (OBOClass)(session.getObject(oboID)); } else { term = new DanglingClassImpl(oboID); session.addObject(term); } return term; } private static String findPermanentID(Element element) { for (Object item : element.getChild("relations").getChildren("entry")) { final Element entry = (Element)item; final String entryKey = entry.getChild("string").getValue(); if (entryKey.equals("provisionalPermanentId")) { if (entry.getChild("null") != null) { return null; } else { return ((Element)(entry.getChildren("string").get(1))).getValue(); } } } return null; } private static String findParentURI(Element term) { for (Object item : term.getChild("relations").getChildren("entry")) { final Element entry = (Element)item; final String entryKey = entry.getChild("string").getValue(); if (entryKey.equals("provisionalSubclassOf")) { final Element uriElement = entry.getChild("org.openrdf.model.URI"); if (uriElement != null) { return uriElement.getChild("uriString").getValue(); } else { return null; } } } return null; } }
package org.robockets.stronghold.robot; import com.kauailabs.nav6.frc.IMUAdvanced; import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.SerialPort; import edu.wpi.first.wpilibj.Victor; /** * The RobotMap is a mapping from the ports sensors and actuators are wired into * to a variable name. This provides flexibility changing wiring, makes checking * the wiring easier and significantly reduces the number of magic numbers * floating around. */ public class RobotMap { private static SerialPort navXSerialPort = new SerialPort(57600, SerialPort.Port.kMXP); private static byte updateRateHz = 50; public static IMUAdvanced navX = new IMUAdvanced(navXSerialPort, updateRateHz); public static RobotDrive robotDrive = new RobotDrive(1, 2, 3, 4); public static Victor intakeMotor = new Victor(5); //TEMP public static Encoder intakeEncoder = new Encoder(9, 10); public static Victor jeffRoller1 = new Victor(6); // TEMP public static Victor jeffRoller2 = new Victor(7); // TEMP public static Victor shootingWheelMotor = new Victor(8); public static Victor turnTableMotor = new Victor(9); // TEMP public static Encoder turnTableEncoder = new Encoder(5, 6); public static Victor hoodMotor = new Victor(10); // TEMP public static Encoder hoodEncoder = new Encoder(7, 8); public RobotMap () { navX.zeroYaw(); } }
package org.shaman.terrain.sketch; import Jama.Matrix; import com.jme3.collision.CollisionResult; import com.jme3.collision.CollisionResults; import com.jme3.input.KeyInput; import com.jme3.input.MouseInput; import com.jme3.input.controls.*; import com.jme3.light.DirectionalLight; import com.jme3.material.Material; import com.jme3.material.RenderState; import com.jme3.math.*; import com.jme3.renderer.Camera; import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.renderer.queue.RenderQueue; import com.jme3.scene.*; import com.jme3.scene.control.AbstractControl; import com.jme3.scene.shape.Cylinder; import com.jme3.scene.shape.Quad; import com.jme3.scene.shape.Sphere; import com.jme3.shadow.DirectionalLightShadowRenderer; import com.jme3.texture.FrameBuffer; import com.jme3.texture.Image; import com.jme3.util.BufferUtils; import de.lessvoid.nifty.Nifty; import java.awt.Graphics; import java.awt.Transparency; import java.awt.color.ColorSpace; import java.awt.image.*; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.shaman.terrain.AbstractTerrainStep; import org.shaman.terrain.TerrainHeighmapCreator; import org.shaman.terrain.Heightmap; import org.shaman.terrain.erosion.WaterErosionSimulation; /** * * @author Sebastian Weiss */ public class SketchTerrain extends AbstractTerrainStep implements ActionListener, AnalogListener { private static final Logger LOG = Logger.getLogger(SketchTerrain.class.getName()); private static final Class<? extends AbstractTerrainStep> NEXT_STEP = WaterErosionSimulation.class; private static final float PLANE_QUAD_SIZE = 200 * TerrainHeighmapCreator.TERRAIN_SCALE; private static final float INITIAL_PLANE_DISTANCE = 150f * TerrainHeighmapCreator.TERRAIN_SCALE; private static final float PLANE_MOVE_SPEED = 0.002f * TerrainHeighmapCreator.TERRAIN_SCALE; private static final float CURVE_SIZE = 0.5f * TerrainHeighmapCreator.TERRAIN_SCALE; private static final int CURVE_RESOLUTION = 8; private static final int CURVE_SAMPLES = 128; private static final boolean DEBUG_DIFFUSION_SOLVER = false; private static final boolean SAVE_TEXTURES = true; private static final int DIFFUSION_SOLVER_ITERATIONS = 100; private Heightmap map; private Heightmap originalMap; private Spatial waterPlane; private float planeDistance = INITIAL_PLANE_DISTANCE; private Spatial sketchPlane; private SketchTerrainScreenController screenController; private Node curveNode; private final ArrayList<ControlCurve> featureCurves; private final ArrayList<Node> featureCurveNodes; private final ArrayList<ControlCurveMesh> featureCurveMesh; private boolean addNewCurves = true; private int selectedCurveIndex; private int selectedPointIndex; private ControlCurve newCurve; private Node newCurveNode; private ControlCurveMesh newCurveMesh; private long lastTime; private final CurvePreset[] presets; private int selectedPreset; private DiffusionSolver solver; private Matrix solverMatrix; private int step; private long lastUpdateTime; public SketchTerrain() { this.featureCurves = new ArrayList<>(); this.featureCurveNodes = new ArrayList<>(); this.featureCurveMesh = new ArrayList<>(); this.presets = DefaultCurvePresets.DEFAULT_PRESETS; } @Override protected void enable() { this.map = (Heightmap) properties.get(AbstractTerrainStep.KEY_HEIGHTMAP); if (this.map == null) { throw new IllegalStateException("SketchTerrain requires a heightmap"); } this.originalMap = this.map.clone(); selectedPreset = 0; init(); } @Override protected void disable() { app.getInputManager().removeListener(this); } private void init() { //init nodes guiNode.detachAllChildren(); sceneNode.detachAllChildren(); curveNode = new Node("curves"); sceneNode.attachChild(curveNode); //initial terrain app.setTerrain(originalMap); //init water plane initWaterPlane(); //init sketch plane initSketchPlane(); //init actions // app.getInputManager().addMapping("SolveDiffusion", new KeyTrigger(KeyInput.KEY_RETURN)); app.getInputManager().addMapping("MouseClicked", new MouseButtonTrigger(MouseInput.BUTTON_LEFT)); app.getInputManager().addListener(this, "SolveDiffusion", "MouseClicked"); //init light for shadow DirectionalLight light = new DirectionalLight(new Vector3f(0, -1, 0)); light.setColor(ColorRGBA.White); sceneNode.addLight(light); DirectionalLightShadowRenderer shadowRenderer = new DirectionalLightShadowRenderer(app.getAssetManager(), 512, 1); shadowRenderer.setLight(light); app.getHeightmapSpatial().setShadowMode(RenderQueue.ShadowMode.Receive); app.getViewPort().addProcessor(shadowRenderer); //TODO: add pseudo water at height 0 initNifty(); } private void initNifty() { Nifty nifty = app.getNifty(); screenController = new SketchTerrainScreenController(this); nifty.registerScreenController(screenController); nifty.addXml("org/shaman/terrain/sketch/SketchTerrainScreen.xml"); nifty.gotoScreen("SketchTerrain"); sendAvailablePresets(); // nifty.setDebugOptionPanelColors(true); } private void initWaterPlane() { float size = map.getSize() * TerrainHeighmapCreator.TERRAIN_SCALE; Quad quad = new Quad(size, size); Material mat = new Material(app.getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md"); mat.setColor("Color", new ColorRGBA(0, 0, 0.5f, 0.5f)); mat.setTransparent(true); mat.getAdditionalRenderState().setAlphaTest(true); mat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Alpha); mat.getAdditionalRenderState().setFaceCullMode(RenderState.FaceCullMode.Off); mat.getAdditionalRenderState().setDepthWrite(false); Geometry geom = new Geometry("water", quad); geom.setMaterial(mat); geom.setQueueBucket(RenderQueue.Bucket.Transparent); geom.rotate(FastMath.HALF_PI, 0, 0); geom.move(-size/2, 0, -size/2); waterPlane = geom; sceneNode.attachChild(geom); } private void initSketchPlane() { Quad quad = new Quad(PLANE_QUAD_SIZE*2, PLANE_QUAD_SIZE*2); Material mat = new Material(app.getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md"); mat.setColor("Color", new ColorRGBA(0.5f, 0, 0, 0.5f)); mat.setTransparent(true); mat.getAdditionalRenderState().setAlphaTest(true); mat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Alpha); Geometry geom = new Geometry("SketchPlaneQuad", quad); geom.setMaterial(mat); geom.setQueueBucket(RenderQueue.Bucket.Translucent); geom.setLocalTranslation(-PLANE_QUAD_SIZE, -PLANE_QUAD_SIZE, 0); sketchPlane = new Node("SketchPlane"); ((Node) sketchPlane).attachChild(geom); sceneNode.attachChild(sketchPlane); sketchPlane.addControl(new AbstractControl() { @Override protected void controlUpdate(float tpf) { //place the plane at the given distance from the camera Vector3f pos = app.getCamera().getLocation().clone(); pos.addLocal(app.getCamera().getDirection().mult(planeDistance)); sketchPlane.setLocalTranslation(pos); //face the camera Quaternion q = sketchPlane.getLocalRotation(); q.lookAt(app.getCamera().getDirection().negate(), Vector3f.UNIT_Y); sketchPlane.setLocalRotation(q); } @Override protected void controlRender(RenderManager rm, ViewPort vp) {} }); app.getInputManager().addMapping("SketchPlaneDist-", new MouseAxisTrigger(MouseInput.AXIS_WHEEL, true)); app.getInputManager().addMapping("SketchPlaneDist+", new MouseAxisTrigger(MouseInput.AXIS_WHEEL, false)); app.getInputManager().addListener(this, "SketchPlaneDist-", "SketchPlaneDist+"); } private void addFeatureCurve(ControlCurve curve) { int index = featureCurveNodes.size(); Node node = new Node("feature"+index); featureCurves.add(curve); addControlPointsToNode(curve.getPoints(), node, index); ControlCurveMesh mesh = new ControlCurveMesh(curve, "Curve"+index, app); node.attachChild(mesh.getTubeGeometry()); node.attachChild(mesh.getSlopeGeometry()); node.setShadowMode(RenderQueue.ShadowMode.CastAndReceive); mesh.getSlopeGeometry().setShadowMode(RenderQueue.ShadowMode.Off); featureCurveNodes.add(node); featureCurveMesh.add(mesh); curveNode.attachChild(node); } private void addControlPointsToNode(ControlPoint[] points, Node node, int index) { Material sphereMat = new Material(app.getAssetManager(), "Common/MatDefs/Light/Lighting.j3md"); sphereMat.setBoolean("UseMaterialColors", true); sphereMat.setColor("Diffuse", ColorRGBA.Gray); sphereMat.setColor("Ambient", ColorRGBA.White); for (int i=0; i<points.length; ++i) { Sphere s = new Sphere(CURVE_RESOLUTION, CURVE_RESOLUTION, CURVE_SIZE*3f); Geometry g = new Geometry(index<0 ? "dummy" : ("ControlPoint"+index+":"+i), s); g.setMaterial(sphereMat); g.setLocalTranslation(app.mapHeightmapToWorld(points[i].x, points[i].y, points[i].height)); node.attachChild(g); } } private void startSolving() { LOG.info("Solve diffusion"); //create solver solver = new DiffusionSolver(map.getSize(), featureCurves.toArray(new ControlCurve[featureCurves.size()])); solverMatrix = new Matrix(map.getSize(), map.getSize()); //Save if (DEBUG_DIFFUSION_SOLVER) { solver.saveFloatMatrix(solverMatrix, "diffusion/Iter0.png",1); } step = 1; screenController.startSolving(); lastUpdateTime = System.currentTimeMillis(); app.setCameraEnabled(false); } private void runSolving() { long maxTime = 50; int minIterations = 5; //run iterations long time = System.currentTimeMillis() + maxTime; for (int i=0; (System.currentTimeMillis()<time) || (i<minIterations); ++i) { solverMatrix = solver.oneIteration(solverMatrix, step); step++; } screenController.setSolvingIteration(step); //update terrain occasionally time = System.currentTimeMillis(); if (time > lastUpdateTime + 500) { lastUpdateTime = time; for (int x=0; x<map.getSize(); ++x) { for (int y=0; y<map.getSize(); ++y) { map.setHeightAt(x, y, (float) solverMatrix.get(x, y) + originalMap.getHeightAt(x, y)); } } app.setTerrain(map); } } private void solvingFinished() { LOG.info("solved"); //fill heighmap for (int x=0; x<map.getSize(); ++x) { for (int y=0; y<map.getSize(); ++y) { map.setHeightAt(x, y, (float) solverMatrix.get(x, y) + originalMap.getHeightAt(x, y)); } } app.setTerrain(map); LOG.info("terrain updated"); solver = null; screenController.stopSolving(); app.setCameraEnabled(true); } @Override public void update(float tpf) { if (solver != null) { runSolving(); } } @Override public void onAction(String name, boolean isPressed, float tpf) { if ("SolveDiffusion".equals(name) && isPressed) { startSolving(); } else if ("MouseClicked".equals(name) && isPressed) { Vector3f dir = app.getCamera().getWorldCoordinates(app.getInputManager().getCursorPosition(), 1); dir.subtractLocal(app.getCamera().getLocation()); dir.normalizeLocal(); Ray ray = new Ray(app.getCamera().getLocation(), dir); if (addNewCurves) { addNewPoint(ray); } else { pickCurve(ray); } } } @Override public void onAnalog(String name, float value, float tpf) { switch (name) { case "SketchPlaneDist-": planeDistance *= 1+PLANE_MOVE_SPEED; break; case "SketchPlaneDist+": planeDistance /= 1+PLANE_MOVE_SPEED; break; } } //Edit private void addNewPoint(Ray ray) { long time = System.currentTimeMillis(); if (time < lastTime+500) { //finish current curve if (newCurve==null) { return; } newCurveMesh = null; curveNode.detachChild(newCurveNode); newCurveNode = null; if (newCurve.getPoints().length>=2) { addFeatureCurve(newCurve); } newCurve = null; LOG.info("new feature added"); screenController.setMessage(""); return; } lastTime = time; //create new point CollisionResults results = new CollisionResults(); sketchPlane.collideWith(ray, results); if (results.size()==0) { return; } Vector3f point = results.getClosestCollision().getContactPoint(); point = app.mapWorldToHeightmap(point); ControlPoint p = createNewControlPoint(point.x, point.y, point.z); //add to curve if (newCurve==null) { LOG.info("start a new feature"); newCurve = new ControlCurve(new ControlPoint[]{p}); newCurveNode = new Node(); addControlPointsToNode(newCurve.getPoints(), newCurveNode, -1); newCurveMesh = new ControlCurveMesh(newCurve, "dummy", app); newCurveNode.attachChild(newCurveMesh.getSlopeGeometry()); newCurveNode.attachChild(newCurveMesh.getTubeGeometry()); curveNode.attachChild(newCurveNode); screenController.setMessage("ADDING A NEW FEATURE"); } else { newCurve.setPoints(ArrayUtils.add(newCurve.getPoints(), p)); newCurveNode.detachAllChildren(); addControlPointsToNode(newCurve.getPoints(), newCurveNode, -1); newCurveMesh.updateMesh(); newCurveNode.attachChild(newCurveMesh.getSlopeGeometry()); newCurveNode.attachChild(newCurveMesh.getTubeGeometry()); } newCurveNode.setShadowMode(RenderQueue.ShadowMode.CastAndReceive); newCurveMesh.getSlopeGeometry().setShadowMode(RenderQueue.ShadowMode.Off); } private ControlPoint createNewControlPoint(float x, float y, float h) { ControlPoint[] points = newCurve==null ? new ControlPoint[0] : newCurve.getPoints(); return presets[selectedPreset].createControlPoint(x, y, h, points, map); } private void pickCurve(Ray ray) { CollisionResults results = new CollisionResults(); curveNode.collideWith(ray, results); if (results.size()==0) { selectedCurveIndex = -1; selectedPointIndex = -1; selectCurve(-1, null); } else { CollisionResult result = results.getClosestCollision(); Geometry geom = result.getGeometry(); if (geom.getName().startsWith("Curve")) { int index = Integer.parseInt(geom.getName().substring("Curve".length())); selectedCurveIndex = index; selectedPointIndex = -1; selectCurve(index, null); } else if (geom.getName().startsWith("ControlPoint")) { String n = geom.getName().substring("ControlPoint".length()); String[] parts = n.split(":"); selectedCurveIndex = Integer.parseInt(parts[0]); selectedPointIndex = Integer.parseInt(parts[1]); selectCurve(selectedCurveIndex, featureCurves.get(selectedCurveIndex).getPoints()[selectedPointIndex]); } else { selectedCurveIndex = -1; selectedPointIndex = -1; selectCurve(-1, null); } } } //GUI-Interface public void guiAddCurves() { addNewCurves = true; } public void guiEditCurves() { addNewCurves = false; if (newCurve != null) { newCurveMesh = null; curveNode.detachChild(newCurveNode); newCurveNode = null; newCurve = null; screenController.setMessage(""); } } public void guiShowCurves(boolean show) { curveNode.setCullHint(show ? Spatial.CullHint.Inherit : Spatial.CullHint.Always); } private void selectCurve(int curveIndex, ControlPoint point) { screenController.selectCurve(curveIndex, point); } public void guiDeleteCurve() { if (selectedCurveIndex==-1) { return; } Node n = featureCurveNodes.get(selectedCurveIndex); featureCurveNodes.set(selectedCurveIndex, null); featureCurves.set(selectedCurveIndex, null); curveNode.detachChild(n); selectCurve(-1, null); selectedCurveIndex = -1; } public void guiDeleteControlPoint() { if (selectedCurveIndex==-1 || selectedPointIndex==-1) { return; } ControlCurve c = featureCurves.get(selectedCurveIndex); if (c.getPoints().length<=2) { LOG.warning("Cannot delete control point, at least 2 points are required"); return; } featureCurves.remove(selectedCurveIndex); Node n = featureCurveNodes.remove(selectedCurveIndex); curveNode.detachChild(n); c = new ControlCurve(ArrayUtils.remove(c.getPoints(), selectedPointIndex)); addFeatureCurve(c); } public void guiControlPointChanged() { if (selectedCurveIndex==-1 || selectedPointIndex==-1) { return; } System.out.println("control point changed: "+featureCurves.get(selectedCurveIndex).getPoints()[selectedPointIndex]); ControlCurveMesh mesh = featureCurveMesh.get(selectedCurveIndex); mesh.updateMesh(); } private void sendAvailablePresets() { String[] names = new String[presets.length]; for (int i=0; i<presets.length; ++i) { names[i] = presets[i].getName(); } screenController.setAvailablePresets(names); } public void guiPresetChanged(int index) { selectedPreset = index; } public void guiSolve() { startSolving(); } public void guiStopSolve() { solvingFinished(); } public void guiNextStep() { Map<Object, Object> props = new HashMap<>(properties); props.put(KEY_HEIGHTMAP, map.clone()); //replace heightmap with new one nextStep(NEXT_STEP, props); } private class DiffusionSolver { //settings private final double BETA_SCALE = 0.9; private final double ALPHA_SCALE = 0.5; private final double GRADIENT_SCALE = 0.01; private final float SLOPE_ALPHA_FACTOR = 0f; private final boolean EVALUATE_SLOPE_RELATIVE_TO_ORIGINAL = true; //input private final int size; private final ControlCurve[] curves; //matrices private Matrix elevation; //target elevation private Matrix alpha, beta; //factors specifying the influence of the gradient, smootheness and elevation private Matrix gradX, gradY; //the normalized direction of the gradient at this point private Matrix gradH; //the target gradient / height difference from the reference point specified by gradX, gradY private DiffusionSolver(int size, ControlCurve[] curves) { this.size = size; this.curves = curves; rasterize(); } /** * Rasterizes the control curves in the matrices */ private void rasterize() { elevation = new Matrix(size, size); alpha = new Matrix(size, size); beta = new Matrix(size, size); gradX = new Matrix(size, size); gradY = new Matrix(size, size); gradH = new Matrix(size, size); //render meshes Material vertexColorMat = new Material(app.getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md"); vertexColorMat.setBoolean("VertexColor", true); vertexColorMat.getAdditionalRenderState().setFaceCullMode(RenderState.FaceCullMode.Off); vertexColorMat.getAdditionalRenderState().setBlendMode(RenderState.BlendMode.Alpha); vertexColorMat.getAdditionalRenderState().setDepthTest(true); vertexColorMat.getAdditionalRenderState().setDepthWrite(true); Node elevationNode = new Node(); Node gradientNode = new Node(); for (ControlCurve curve : curves) { if (curve==null) continue; //sample curve int samples = 32; ControlPoint[] points = new ControlPoint[samples+1]; for (int i=0; i<=samples; ++i) { points[i] = curve.interpolate(i / (float) samples); } Geometry lineGeom = new Geometry("line", createLineMesh(points)); lineGeom.setMaterial(vertexColorMat); lineGeom.setQueueBucket(RenderQueue.Bucket.Gui); Geometry plateauGeom = new Geometry("plateau", createPlateauMesh(points)); plateauGeom.setMaterial(vertexColorMat); plateauGeom.setQueueBucket(RenderQueue.Bucket.Gui); elevationNode.attachChild(lineGeom); elevationNode.attachChild(plateauGeom); Geometry slopeGeom = new Geometry("slope", createSlopeMesh(points)); slopeGeom.setMaterial(vertexColorMat); slopeGeom.setQueueBucket(RenderQueue.Bucket.Gui); gradientNode.attachChild(slopeGeom); } elevationNode.setCullHint(Spatial.CullHint.Never); gradientNode.setCullHint(Spatial.CullHint.Never); for (Spatial s : elevationNode.getChildren()) { fillMatrix(elevation, s, true); } fillSlopeMatrix(gradientNode); vertexColorMat.setBoolean("VertexColor", false); vertexColorMat.setColor("Color", ColorRGBA.White); fillMatrix(beta, elevationNode, false); //copy existing heightmap data for (int x=0; x<map.getSize(); ++x) { for (int y=0; y<map.getSize(); ++y) { elevation.set(x, y, elevation.get(x, y) - originalMap.getHeightAt(x, y)); } } alpha.timesEquals(ALPHA_SCALE); beta.timesEquals(BETA_SCALE); gradH.timesEquals(GRADIENT_SCALE); //save for debugging if (DEBUG_DIFFUSION_SOLVER || SAVE_TEXTURES) { saveFloatMatrix(elevation, "diffusion/Elevation.png", 0.5); saveMatrix(beta, "diffusion/Beta.png"); saveMatrix(alpha, "diffusion/Alpha.png"); saveFloatMatrix(gradX, "diffusion/GradX.png",1); saveFloatMatrix(gradY, "diffusion/GradY.png",1); saveFloatMatrix(gradH, "diffusion/GradH.png",50); } LOG.info("curves rasterized"); } public Matrix oneIteration(Matrix last, int iteration) { Matrix mat = new Matrix(size, size); //add elevation constraint mat.plusEquals(elevation.arrayTimes(beta)); //add laplace constraint Matrix laplace = new Matrix(size, size); for (int x=0; x<size; ++x) { for (int y=0; y<size; ++y) { double v = 0; v += last.get(Math.max(0, x-1), y); v += last.get(Math.min(size-1, x+1), y); v += last.get(x, Math.max(0, y-1)); v += last.get(x, Math.min(size-1, y+1)); v /= 4.0; v *= 1 - alpha.get(x, y) - beta.get(x, y); laplace.set(x, y, v); } } mat.plusEquals(laplace); //add gradient constraint Matrix gradient = new Matrix(size, size); for (int x=0; x<size; ++x) { for (int y=0; y<size; ++y) { double v = 0; //v = gradH.get(x, y); double gx = gradX.get(x, y); double gy = gradY.get(x, y); if (gx==0 && gy==0) { v = 0; //no gradient } else { double h1, h2; if (EVALUATE_SLOPE_RELATIVE_TO_ORIGINAL) { h1 = last.get(clamp(x-(int) Math.signum(gx)), y) + originalMap.getHeightAt(clamp(x-(int) Math.signum(gx)), y) - originalMap.getHeightAt(x, y); h2 = last.get(x, clamp(y-(int) Math.signum(gy))) + originalMap.getHeightAt(x, clamp(y-(int) Math.signum(gy))) - originalMap.getHeightAt(x, y); } else { h1 = last.get(clamp(x-(int) Math.signum(gx)), y); h2 = last.get(x, clamp(y-(int) Math.signum(gy))); } v += gx*gx*h1; v += gy*gy*h2; } gradient.set(x, y, v); } } Matrix oldGradient; if (DEBUG_DIFFUSION_SOLVER) { oldGradient = gradient.copy(); //Test } if (DEBUG_DIFFUSION_SOLVER) { saveFloatMatrix(gradient, "diffusion/Gradient"+iteration+".png",1); } Matrix gradChange = gradH.plus(gradient); gradChange.arrayTimesEquals(alpha); if (DEBUG_DIFFUSION_SOLVER) { saveFloatMatrix(gradChange, "diffusion/GradChange"+iteration+".png",1); } mat.plusEquals(gradChange); //Test if (DEBUG_DIFFUSION_SOLVER) { Matrix newGradient = new Matrix(size, size); for (int x=0; x<size; ++x) { for (int y=0; y<size; ++y) { double v = 0; v += gradX.get(x, y)*gradX.get(x, y) *mat.get(clamp(x-(int) Math.signum(gradX.get(x, y))), y); v += gradY.get(x, y)*gradY.get(x, y) *mat.get(x, clamp(y-(int) Math.signum(gradY.get(x, y)))); v -= mat.get(x, y); newGradient.set(x, y, -v); } } Matrix diff = oldGradient.minus(newGradient); saveFloatMatrix(diff, "diffusion/Diff"+iteration+".png",1); } return mat; } private int clamp(int i) { return Math.max(0, Math.min(size-1, i)); } private Mesh createLineMesh(ControlPoint[] points) { Vector3f[] pos = new Vector3f[points.length]; ColorRGBA[] col = new ColorRGBA[points.length]; for (int i=0; i<points.length; ++i) { pos[i] = new Vector3f(points[i].x, points[i].y, 1-points[i].height); float height = points[i].hasElevation ? points[i].height : 0; col[i] = new ColorRGBA(height, height, height, 1); } Mesh mesh = new Mesh(); mesh.setBuffer(VertexBuffer.Type.Position, 3, BufferUtils.createFloatBuffer(pos)); mesh.setBuffer(VertexBuffer.Type.Color, 4, BufferUtils.createFloatBuffer(col)); mesh.setMode(Mesh.Mode.LineStrip); mesh.setLineWidth(1); return mesh; } private Mesh createPlateauMesh(ControlPoint[] points) { Vector3f[] pos = new Vector3f[points.length*3]; ColorRGBA[] col = new ColorRGBA[points.length*3]; for (int i=0; i<points.length; ++i) { pos[3*i] = new Vector3f(points[i].x, points[i].y, points[i].height*100-100); float dx,dy; if (i==0) { dx = points[i+1].x - points[i].x; dy = points[i+1].y - points[i].y; } else if (i==points.length-1) { dx = points[i].x - points[i-1].x; dy = points[i].y - points[i-1].y; } else { dx = (points[i+1].x - points[i-1].x) / 2f; dy = (points[i+1].y - points[i-1].y) / 2f; } float sum = (float) Math.sqrt(dx*dx + dy*dy); dx /= sum; dy /= sum; pos[3*i + 1] = pos[3*i].add(points[i].plateau * -dy, points[i].plateau * dx, points[i].height*100-100); pos[3*i + 2] = pos[3*i].add(points[i].plateau * dy, points[i].plateau * -dx, points[i].height*100-100); float height = points[i].hasElevation ? points[i].height : 0; col[3*i] = new ColorRGBA(height, height, height, 1); col[3*i+1] = col[3*i]; col[3*i+2] = col[3*i]; } int[] index = new int[(points.length-1) * 12]; for (int i=0; i<points.length-1; ++i) { index[12*i] = 3*i; index[12*i + 1] = 3*i + 3; index[12*i + 2] = 3*i + 1; index[12*i + 3] = 3*i + 3; index[12*i + 4] = 3*i + 4; index[12*i + 5] = 3*i + 1; index[12*i + 6] = 3*i; index[12*i + 7] = 3*i + 2; index[12*i + 8] = 3*i + 3; index[12*i + 9] = 3*i + 3; index[12*i + 10] = 3*i + 2; index[12*i + 11] = 3*i + 5; } Mesh m = new Mesh(); m.setBuffer(VertexBuffer.Type.Position, 3, BufferUtils.createFloatBuffer(pos)); m.setBuffer(VertexBuffer.Type.Color, 4, BufferUtils.createFloatBuffer(col)); m.setBuffer(VertexBuffer.Type.Index, 1, index); m.setMode(Mesh.Mode.Triangles); return m; } private Mesh createSlopeMesh(ControlPoint[] points) { Vector3f[] pos = new Vector3f[points.length*4]; ColorRGBA[] col = new ColorRGBA[points.length*4]; for (int i=0; i<points.length; ++i) { Vector3f p = new Vector3f(points[i].x, points[i].y, 1-points[i].height); float dx,dy; if (i==0) { dx = points[i+1].x - points[i].x; dy = points[i+1].y - points[i].y; } else if (i==points.length-1) { dx = points[i].x - points[i-1].x; dy = points[i].y - points[i-1].y; } else { dx = (points[i+1].x - points[i-1].x) / 2f; dy = (points[i+1].y - points[i-1].y) / 2f; } float sum = (float) Math.sqrt(dx*dx + dy*dy); dx /= sum; dy /= sum; pos[4*i + 0] = p.add(points[i].plateau * -dy, points[i].plateau * dx, 0); pos[4*i + 1] = p.add( (points[i].plateau + FastMath.cos(points[i].angle1)*points[i].extend1) * -dy, (points[i].plateau + FastMath.cos(points[i].angle1)*points[i].extend1) * dx, 0); pos[4*i + 2] = p.add(points[i].plateau * dy, points[i].plateau * -dx, 0); pos[4*i + 3] = p.add( (points[i].plateau + FastMath.cos(points[i].angle2)*points[i].extend2) * dy, (points[i].plateau + FastMath.cos(points[i].angle2)*points[i].extend2) * -dx, 0); ColorRGBA c1, c2, c3, c4; c1 = new ColorRGBA(-dy/2 + 0.5f, dx/2 + 0.5f, -FastMath.sin(points[i].angle1) + 0.5f, 1); c2 = new ColorRGBA(c1.r, c1.g, c1.b, 0); c3 = new ColorRGBA(dy/2 + 0.5f, -dx/2 + 0.5f, -FastMath.sin(points[i].angle2) + 0.5f, 1); c4 = new ColorRGBA(c3.r, c3.g, c3.b, 0); col[4*i + 0] = c1; col[4*i + 1] = c2; col[4*i + 2] = c3; col[4*i + 3] = c4; } int[] index = new int[(points.length-1) * 12]; for (int i=0; i<points.length-1; ++i) { index[12*i] = 4*i; index[12*i + 1] = 4*i + 4; index[12*i + 2] = 4*i + 1; index[12*i + 3] = 4*i + 4; index[12*i + 4] = 4*i + 5; index[12*i + 5] = 4*i + 1; index[12*i + 6] = 4*i + 2; index[12*i + 7] = 4*i + 3; index[12*i + 8] = 4*i + 6; index[12*i + 9] = 4*i + 6; index[12*i + 10] = 4*i + 3; index[12*i + 11] = 4*i + 7; } Mesh m = new Mesh(); m.setBuffer(VertexBuffer.Type.Position, 3, BufferUtils.createFloatBuffer(pos)); m.setBuffer(VertexBuffer.Type.Color, 4, BufferUtils.createFloatBuffer(col)); m.setBuffer(VertexBuffer.Type.Index, 1, index); m.setMode(Mesh.Mode.Triangles); return m; } @Deprecated private Mesh createSlopeAlphaMesh(ControlPoint[] points) { Vector3f[] pos = new Vector3f[points.length*6]; ColorRGBA[] col = new ColorRGBA[points.length*6]; for (int i=0; i<points.length; ++i) { Vector3f p = new Vector3f(points[i].x, points[i].y, 1-points[i].height); float dx,dy; if (i==0) { dx = points[i+1].x - points[i].x; dy = points[i+1].y - points[i].y; } else if (i==points.length-1) { dx = points[i].x - points[i-1].x; dy = points[i].y - points[i-1].y; } else { dx = (points[i+1].x - points[i-1].x) / 2f; dy = (points[i+1].y - points[i-1].y) / 2f; } float sum = (float) Math.sqrt(dx*dx + dy*dy); dx /= sum; dy /= sum; float factor = SLOPE_ALPHA_FACTOR; pos[6*i + 0] = p.add(points[i].plateau * -dy, points[i].plateau * dx, 0); pos[6*i + 1] = p.add( (points[i].plateau + FastMath.cos(points[i].angle1)*points[i].extend1*factor) * -dy, (points[i].plateau + FastMath.cos(points[i].angle1)*points[i].extend1*factor) * dx, 0); pos[6*i + 2] = p.add( (points[i].plateau + FastMath.cos(points[i].angle1)*points[i].extend1) * -dy, (points[i].plateau + FastMath.cos(points[i].angle1)*points[i].extend1) * dx, 0); pos[6*i + 3] = p.add(points[i].plateau * dy, points[i].plateau * -dx, 0); pos[6*i + 4] = p.add( (points[i].plateau + FastMath.cos(points[i].angle2)*points[i].extend2*factor) * dy, (points[i].plateau + FastMath.cos(points[i].angle2)*points[i].extend2*factor) * -dx, 0); pos[6*i + 5] = p.add( (points[i].plateau + FastMath.cos(points[i].angle2)*points[i].extend2) * dy, (points[i].plateau + FastMath.cos(points[i].angle2)*points[i].extend2) * -dx, 0); ColorRGBA c1 = new ColorRGBA(0, 0, 0, 1); ColorRGBA c2 = new ColorRGBA(1, 1, 1, 1); col[6*i + 0] = c1; col[6*i + 1] = c2; col[6*i + 2] = c1; col[6*i + 3] = c1; col[6*i + 4] = c2; col[6*i + 5] = c1; } int[] index = new int[(points.length-1) * 24]; for (int i=0; i<points.length-1; ++i) { index[24*i + 0] = 6*i; index[24*i + 1] = 6*i + 6; index[24*i + 2] = 6*i + 1; index[24*i + 3] = 6*i + 6; index[24*i + 4] = 6*i + 7; index[24*i + 5] = 6*i + 1; index[24*i + 6] = 6*i + 1; index[24*i + 7] = 6*i + 7; index[24*i + 8] = 6*i + 2; index[24*i + 9] = 6*i + 7; index[24*i + 10] = 6*i + 8; index[24*i + 11] = 6*i + 2; index[24*i + 12] = 6*i + 3; index[24*i + 13] = 6*i + 9; index[24*i + 14] = 6*i + 4; index[24*i + 15] = 6*i + 9; index[24*i + 16] = 6*i + 10; index[24*i + 17] = 6*i + 4; index[24*i + 18] = 6*i + 4; index[24*i + 19] = 6*i + 10; index[24*i + 20] = 6*i + 5; index[24*i + 21] = 6*i + 10; index[24*i + 22] = 6*i + 11; index[24*i + 23] = 6*i + 5; } Mesh m = new Mesh(); m.setBuffer(VertexBuffer.Type.Position, 3, BufferUtils.createFloatBuffer(pos)); m.setBuffer(VertexBuffer.Type.Color, 4, BufferUtils.createFloatBuffer(col)); m.setBuffer(VertexBuffer.Type.Index, 1, index); m.setMode(Mesh.Mode.Triangles); return m; } /** * Renders the given scene in a top-down manner in the given matrix * @param matrix * @param scene */ private void fillMatrix(Matrix matrix, Spatial scene, boolean max) { //init Camera cam = new Camera(size, size); cam.setParallelProjection(true); ViewPort view = new ViewPort("Off", cam); view.setClearFlags(true, true, true); FrameBuffer buffer = new FrameBuffer(size, size, 1); buffer.setDepthBuffer(Image.Format.Depth); buffer.setColorBuffer(Image.Format.RGBA32F); view.setOutputFrameBuffer(buffer); view.attachScene(scene); //render scene.updateGeometricState(); view.setEnabled(true); app.getRenderManager().renderViewPort(view, 0); //retrive data ByteBuffer data = BufferUtils.createByteBuffer(size*size*4*4); app.getRenderer().readFrameBufferWithFormat(buffer, data, Image.Format.RGBA32F); data.rewind(); for (int y=0; y<size; ++y) { for (int x=0; x<size; ++x) { // byte d = data.get(); // matrix.set(x, y, (d & 0xff) / 255.0); // data.get(); data.get(); data.get(); double v = data.getFloat(); double old = matrix.get(x, y); if (max) { v = Math.max(v, old); } else { v += old; } matrix.set(x, y, v); data.getFloat(); data.getFloat(); data.getFloat(); } } } /** * Renders the given scene in a top-down manner in the given matrix * @param matrix * @param scene */ private void fillSlopeMatrix(Spatial scene) { //init Camera cam = new Camera(size, size); cam.setParallelProjection(true); ViewPort view = new ViewPort("Off", cam); view.setClearFlags(true, true, true); view.setBackgroundColor(new ColorRGBA(0.5f, 0.5f, 0.5f, 0f)); FrameBuffer buffer = new FrameBuffer(size, size, 1); buffer.setDepthBuffer(Image.Format.Depth); buffer.setColorBuffer(Image.Format.RGBA32F); view.setOutputFrameBuffer(buffer); view.attachScene(scene); //render scene.updateGeometricState(); view.setEnabled(true); app.getRenderManager().renderViewPort(view, 0); //retrive data ByteBuffer data = BufferUtils.createByteBuffer(size*size*4*4); app.getRenderer().readFrameBufferWithFormat(buffer, data, Image.Format.RGBA32F); data.rewind(); for (int y=0; y<size; ++y) { for (int x=0; x<size; ++x) { // double gx = (((data.get() & 0xff) / 256.0) - 0.5) * 2; // double gy = (((data.get() & 0xff) / 256.0) - 0.5) * 2; double gx = (data.getFloat() - 0.5) * 2; double gy = (data.getFloat() - 0.5) * 2; double s = Math.sqrt(gx*gx + gy*gy); if (s==0) { gx=0; gy=0; s=1; } gradX.set(x, y, (gx / s) + gradX.get(x, y)); gradY.set(x, y, (gy / s) + gradY.get(x, y)); // double v = (((data.get() & 0xff) / 255.0) - 0.5); double v = (data.getFloat() - 0.5); if (Math.abs(v)<0.002) { v=0; } gradH.set(x, y, v + gradH.get(x, y)); // data.get(); double a = data.getFloat(); alpha.set(x, y, a); } } } private void saveMatrix(Matrix matrix, String filename) { byte[] buffer = new byte[size*size]; int i=0; for (int x=0; x<size; ++x) { for (int y=0; y<size; ++y) { buffer[i] = (byte) (matrix.get(x, y) * 255); i++; } } ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY); int[] nBits = { 8 }; ColorModel cm = new ComponentColorModel(cs, nBits, false, true, Transparency.OPAQUE, DataBuffer.TYPE_BYTE); SampleModel sm = cm.createCompatibleSampleModel(size, size); DataBufferByte db = new DataBufferByte(buffer, size * size); WritableRaster raster = Raster.createWritableRaster(sm, db, null); BufferedImage result = new BufferedImage(cm, raster, false, null); try { ImageIO.write(result, "png", new File(filename)); } catch (IOException ex) { Logger.getLogger(SketchTerrain.class.getName()).log(Level.SEVERE, null, ex); } } private void saveFloatMatrix(Matrix matrix, String filename, double scale) { byte[] buffer = new byte[size*size]; int i=0; for (int x=0; x<size; ++x) { for (int y=0; y<size; ++y) { buffer[i] = (byte) ((matrix.get(x, y)*scale/2 + 0.5) * 255); i++; } } ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY); int[] nBits = { 8 }; ColorModel cm = new ComponentColorModel(cs, nBits, false, true, Transparency.OPAQUE, DataBuffer.TYPE_BYTE); SampleModel sm = cm.createCompatibleSampleModel(size, size); DataBufferByte db = new DataBufferByte(buffer, size * size); WritableRaster raster = Raster.createWritableRaster(sm, db, null); BufferedImage result = new BufferedImage(cm, raster, false, null); try { ImageIO.write(result, "png", new File(filename)); } catch (IOException ex) { Logger.getLogger(SketchTerrain.class.getName()).log(Level.SEVERE, null, ex); } } } }
package org.ssgwt.client.ui.datagrid; import java.util.List; import org.eclipse.jdt.internal.compiler.ast.DoStatement; import com.google.gwt.core.client.GWT; import com.google.gwt.layout.client.Layout.Layer; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.cellview.client.Column; import com.google.gwt.user.cellview.client.DataGrid; import com.google.gwt.user.cellview.client.Header; import com.google.gwt.user.cellview.client.SimplePager; import com.google.gwt.user.cellview.client.SimplePager.TextLocation; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.RequiresResize; import com.google.gwt.user.client.ui.Widget; /** * The SSDataGrid with a changeable action bar that dispatches events for * sorting, filtering, selection clicking of row and paging * * @author Johannes Gryffenberg * @param <T> * @since 29 June 2012 */ public class SSDataGrid<T> extends Composite implements RequiresResize { /** * UiBinder interface for the composite * * @author Johannes Gryffenberg * @since 29 June 2012 */ interface Binder extends UiBinder<Widget, SSDataGrid> { } /** * Whether the data grid supports selecting multiple rows */ private boolean multiSelect; /** * Whether the data grid supports click actions */ private boolean clickAction; /** * Instance of the UiBinder */ private static Binder uiBinder = GWT.create(Binder.class); /** * The DataGrid that will be displayed on the screen */ @UiField(provided = true) protected DataGrid<T> dataGrid; /** * The DataGrid that will be displayed on the screen */ @UiField protected FlowPanel actionBar; @UiField FlowPanel actionBarContainer; /** * The pager that will handle the paging of the DataGrid */ @UiField(provided = true) protected SimplePager pager; /** * Class Constructor * * @author Lodewyk Duminy * @since 29 June 2012 */ public SSDataGrid() { this((DataGrid.Resources)GWT.create(DataGrid.Resources.class), (SimplePager.Resources)GWT.create(SimplePager.Resources.class)); } /** * Class Constructor * * @author Lodewyk Duminy * @since 29 June 2012 */ public SSDataGrid(DataGrid.Resources dataGridResource, SimplePager.Resources pagerResource) { this.initWidget(uiBinder.createAndBindUi(this)); dataGrid = new DataGrid<T>(10, dataGridResource); pager = new SimplePager(TextLocation.CENTER, pagerResource, false, 0, true); pager.setDisplay(dataGrid); } /** * Setter to set the data that should be displayed on the DataGrid * * @param data - The data the should be displayed on the data grid * * @author Lodewyk Duminy * @since 29 June 2012 */ public void setData(List<T> data) { } /** * Getter to retrieve the data currently being displayed on the DataGrid * * @author Lodewyk Duminy * @since 29 June 2012 * * @return The data being displayed on the DataGrid */ public List<T> getData() { return null; } /** * Ensures that the datagrid has a scrollbar when the browser is too small * to display all the rows. * * @author Lodewyk Duminy * @since 29 June 2012 */ @Override public void onResize() { dataGrid.setHeight((this.getOffsetHeight() - 40) + "px"); } /** * Adds a column to the end of the table. * * @param col the column to be added */ public void addColumn(Column<T, ?> col) { dataGrid.addColumn(col); } /** * Adds a column to the end of the table with an associated header. * * @param col the column to be added * @param header the associated {@link Header} */ public void addColumn(Column<T, ?> col, Header<?> header) { dataGrid.addColumn(col, header); } /** * Adds a column to the end of the table with an associated header and footer. * * @param col the column to be added * @param header the associated {@link Header} * @param footer the associated footer (as a {@link Header} object) */ public void addColumn(Column<T, ?> col, Header<?> header, Header<?> footer) { dataGrid.addColumn(col, header, footer); } /** * Adds a column to the end of the table with an associated String header. * * @param col the column to be added * @param headerString the associated header text, as a String */ public void addColumn(Column<T, ?> col, String headerString) { dataGrid.addColumn(col, headerString); } /** * Adds a column to the end of the table with an associated {@link SafeHtml} * header. * * @param col the column to be added * @param headerHtml the associated header text, as safe HTML */ public void addColumn(Column<T, ?> col, SafeHtml headerHtml) { dataGrid.addColumn(col, headerHtml); } /** * Adds a column to the end of the table with an associated String header and * footer. * * @param col the column to be added * @param headerString the associated header text, as a String * @param footerString the associated footer text, as a String */ public void addColumn(Column<T, ?> col, String headerString, String footerString) { dataGrid.addColumn(col, headerString, footerString); } /** * Adds a column to the end of the table with an associated {@link SafeHtml} * header and footer. * * @param col the column to be added * @param headerHtml the associated header text, as safe HTML * @param footerHtml the associated footer text, as safe HTML */ public void addColumn(Column<T, ?> col, SafeHtml headerHtml, SafeHtml footerHtml) { dataGrid.addColumn(col, headerHtml, footerHtml); } /** * Sets the amount of rows that the data grid will have. This * does not specify how many rows will be displayed. * * @param count - The amount of rows that the data grid will have */ public final void setRowCount(int count) { dataGrid.setRowCount(count); } /** * Sets the amount of rows that the data grid will have. This * does not specify how many rows will be displayed. * * @param count - The amount of rows that the data grid will have * @param isExact - Whether or not the row measurement is exact */ public void setRowCount(int size, boolean isExact) { dataGrid.setRowCount(size, isExact); } /** * Hides the action bar by setting it invisible */ public void hideActionBar(){ actionBar.setVisible(false); } /** * Hides the header by setting it invisible */ public void hideHeader(){ //TODO: Add functionality for reusability } /** * Adds a widget to the action bar * * @param actionBarWidget - The widget that needs to be added to the action bar */ public void setActionBarWidget(Widget actionBarWidget){ this.actionBarContainer.add(actionBarWidget); } /** * Sets the size of the pager. * * @param pageSize - The size of the pager */ public void setPageSize(int pageSize) { pager.setPageSize(pageSize); } /** * * @return */ public boolean isMultiSelect(){ return this.multiSelect; } /** * Set whether or not the grid should support multiple row select * * @param multiSelect - Whether the data grid should support multiple row select */ public void setMultiSelect(boolean multiSelect){ this.multiSelect = multiSelect; if (!multiSelect){ dataGrid.removeStyleName("isMultiSelect"); } else { dataGrid.addStyleName("isMultiSelect"); } } /** * Gets the current click action state for the data grid * * @return Whether the data grid has click action support */ public boolean hasClickAction(){ return this.clickAction; } /** * Gets the current click action state for the data grid * * @param clickAction - If the data grid should support click actions */ public void setClickAction(boolean clickAction){ this.clickAction = clickAction; if (!clickAction){ dataGrid.removeStyleName("hasClickAction"); dataGrid.addStyleName("noClickAction"); } else { dataGrid.removeStyleName("noClickAction"); dataGrid.addStyleName("hasClickAction"); } } }
package com.facebook.flipper.core; import java.util.Arrays; import java.util.Iterator; import javax.annotation.Nullable; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class FlipperObject { final JSONObject mJson; public FlipperObject(JSONObject json) { mJson = (json != null ? json : new JSONObject()); } public FlipperObject(String json) { try { mJson = new JSONObject(json); } catch (JSONException e) { throw new RuntimeException(e); } } public FlipperDynamic getDynamic(String name) { return new FlipperDynamic(mJson.opt(name)); } public String getString(String name) { if (mJson.isNull(name)) { return null; } return mJson.optString(name); } public int getInt(String name) { return mJson.optInt(name); } public long getLong(String name) { return mJson.optLong(name); } public float getFloat(String name) { return (float) mJson.optDouble(name); } public double getDouble(String name) { return mJson.optDouble(name); } public boolean getBoolean(String name) { return mJson.optBoolean(name); } public FlipperObject getObject(String name) { final Object o = mJson.opt(name); return new FlipperObject((JSONObject) o); } public FlipperArray getArray(String name) { final Object o = mJson.opt(name); return new FlipperArray((JSONArray) o); } public Object get(String name) { final Object o = mJson.opt(name); if (o instanceof JSONObject) { return new FlipperObject((JSONObject) o); } else if (o instanceof JSONArray) { return new FlipperArray((JSONArray) o); } else { return o; } } public boolean contains(String name) { return mJson.has(name); } public Iterator<String> keys() { return mJson.keys(); } public String toJsonString() { return toString(); } @Override public String toString() { return mJson.toString(); } @Override public boolean equals(@Nullable Object o) { if (o == null) { return false; } else { return mJson.toString().equals(o.toString()); } } @Override public int hashCode() { return mJson.hashCode(); } public static class Builder { private final JSONObject mJson; public Builder() { mJson = new JSONObject(); } public Builder put(String name, Object obj) { if (obj == null) { return put(name, (String) null); } else if (obj instanceof Integer) { return put(name, (Integer) obj); } else if (obj instanceof Long) { return put(name, (Long) obj); } else if (obj instanceof Float) { return put(name, (Float) obj); } else if (obj instanceof Double) { return put(name, (Double) obj); } else if (obj instanceof String) { return put(name, (String) obj); } else if (obj instanceof Boolean) { return put(name, (Boolean) obj); } else if (obj instanceof Object[]) { return put(name, Arrays.deepToString((Object[]) obj)); } else if (obj instanceof FlipperObject) { return put(name, (FlipperObject) obj); } else if (obj instanceof FlipperObject.Builder) { return put(name, (FlipperObject.Builder) obj); } else if (obj instanceof FlipperArray) { return put(name, (FlipperArray) obj); } else if (obj instanceof FlipperArray.Builder) { return put(name, (FlipperArray.Builder) obj); } else if (obj instanceof FlipperValue) { return put(name, ((FlipperValue) obj).toFlipperObject()); } else { return put(name, obj.toString()); } } public Builder put(String name, String s) { try { mJson.put(name, s); } catch (JSONException e) { throw new RuntimeException(e); } return this; } public Builder put(String name, Integer i) { try { mJson.put(name, i); } catch (JSONException e) { throw new RuntimeException(e); } return this; } public Builder put(String name, Long l) { try { mJson.put(name, l); } catch (JSONException e) { throw new RuntimeException(e); } return this; } public Builder put(String name, Float f) { try { mJson.put(name, Float.isNaN(f) ? null : f); } catch (JSONException e) { throw new RuntimeException(e); } return this; } public Builder put(String name, Double d) { try { mJson.put(name, Double.isNaN(d) ? null : d); } catch (JSONException e) { throw new RuntimeException(e); } return this; } public Builder put(String name, Boolean b) { try { mJson.put(name, b); } catch (JSONException e) { throw new RuntimeException(e); } return this; } public Builder put(String name, FlipperValue v) { return put(name, v.toFlipperObject()); } public Builder put(String name, FlipperArray a) { try { mJson.put(name, a == null ? null : a.mJson); } catch (JSONException e) { throw new RuntimeException(e); } return this; } public Builder put(String name, FlipperArray.Builder b) { return put(name, b.build()); } public Builder put(String name, FlipperObject o) { try { mJson.put(name, o == null ? null : o.mJson); } catch (JSONException e) { throw new RuntimeException(e); } return this; } public Builder put(String name, FlipperObject.Builder b) { return put(name, b.build()); } public FlipperObject build() { return new FlipperObject(mJson); } } }
package anabalica.github.io.meowletters.utils; import android.content.SharedPreferences; import anabalica.github.io.meowletters.GameActivity; import anabalica.github.io.meowletters.letters.Cell; import anabalica.github.io.meowletters.letters.Letter; import anabalica.github.io.meowletters.letters.LetterGrid; import anabalica.github.io.meowletters.metrics.Level; import anabalica.github.io.meowletters.metrics.Score; /** * Helper class to store and load GameActivity instance for persistence. * Kind of serialization/deserialization in shared preferences. * * @author Ana Balica */ public class State { private SharedPreferences sharedPreferences; public static final String STATE_LEVEL = "anabalica.github.io.meowletters.state_level"; public static final String STATE_SCORE = "anabalica.github.io.meowletters.state_score"; public State(SharedPreferences sharedPreferences) { this.sharedPreferences = sharedPreferences; } public void save(GameActivity gameActivity) { SharedPreferences.Editor editor = sharedPreferences.edit(); // save metrics Level level = gameActivity.getLevel(); Score score = gameActivity.getScore(); editor.putInt(STATE_LEVEL, level.getLevel()); editor.putInt(STATE_SCORE, score.getPoints()); editor.apply(); } /** * Encode a Letter object as a single string to be stored in shared preferences as * "<row><column><letter char><1 if selected, 0 otherwise>". * * @param letter Letter object * @return String encoded letter */ private String encodeLetter(Letter letter) { StringBuilder letterStringBuilder = new StringBuilder(); Cell position = letter.getPosition(); letterStringBuilder.append(String.valueOf(position.getRow())); letterStringBuilder.append(String.valueOf(position.getColumn())); letterStringBuilder.append(letter.getLetter()); String isSelected = letter.isSelected() ? "1" : "0"; letterStringBuilder.append(isSelected); return letterStringBuilder.toString(); } /** * Decode a Letter object from a string * * @param letterString String containing encoded information about Letter object * @return Letter object */ private Letter decodeLetter(String letterString) { int row = Integer.parseInt(Character.toString(letterString.charAt(0))); int column = Integer.parseInt(Character.toString(letterString.charAt(1))); String letterChar = Character.toString(letterString.charAt(2)); boolean isSelected = Integer.parseInt(Character.toString(letterString.charAt(3))) == 1; return new Letter(letterChar, row, column, isSelected); } /** * Encode the game letter grid to a single string to be stored in shared preferences. * Only non empty cells are stored into the string. Letters are delimited using a semicolon. * * @param letterGrid LetterGrid object * @return String encoded letter grid */ private String encodeLetterGrid(LetterGrid letterGrid) { int rows = letterGrid.getROWS(); int columns = letterGrid.getCOLUMNS(); Letter[][] grid = letterGrid.getGrid(); StringBuilder gridStringBuilder= new StringBuilder(); for (int row = 0; row < rows; row++) { for (int column = 0; column < columns; column++) { if (grid[row][column] != null) { gridStringBuilder.append(encodeLetter(grid[row][column])); gridStringBuilder.append(";"); } } } if (gridStringBuilder.length() != 0) { int lastCharIndex = gridStringBuilder.length() - 1; gridStringBuilder.deleteCharAt(lastCharIndex); } return gridStringBuilder.toString(); } /** * Decode a LetterGrid object from a string * * @param letterGridString String containing encoded information about a LetterGrid object * @return LetterGrid object */ private LetterGrid decodeLetterGrid(String letterGridString) { Letter[][] grid = new Letter[GameActivity.gridRows][GameActivity.gridColumns]; if (letterGridString.length() > 0) { for (String letterString : letterGridString.split(";")) { Letter letter = decodeLetter(letterString); Cell position = letter.getPosition(); int row = position.getRow(); int column = position.getColumn(); grid[row][column] = letter; } } return new LetterGrid(grid); } }
package be.digitalia.fosdem.activities; import java.text.DateFormat; import java.util.Date; import java.util.Locale; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.Dialog; import android.app.SearchManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.Color; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import android.support.annotation.StringRes; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.content.LocalBroadcastManager; import android.support.v4.view.MenuItemCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.SearchView; import android.text.method.LinkMovementMethod; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import be.digitalia.fosdem.R; import be.digitalia.fosdem.api.FosdemApi; import be.digitalia.fosdem.db.DatabaseManager; import be.digitalia.fosdem.fragments.BookmarksListFragment; import be.digitalia.fosdem.fragments.LiveFragment; import be.digitalia.fosdem.fragments.MapFragment; import be.digitalia.fosdem.fragments.PersonsListFragment; import be.digitalia.fosdem.fragments.TracksFragment; /** * Main entry point of the application. Allows to switch between section fragments and update the database. * * @author Christophe Beyls */ public class MainActivity extends ActionBarActivity implements ListView.OnItemClickListener { private enum Section { TRACKS(TracksFragment.class, R.string.menu_tracks, R.drawable.ic_action_event, true), BOOKMARKS(BookmarksListFragment.class, R.string.menu_bookmarks, R.drawable.ic_action_important, false), LIVE(LiveFragment.class, R.string.menu_live, R.drawable.ic_action_play_over_video, false), SPEAKERS(PersonsListFragment.class, R.string.menu_speakers, R.drawable.ic_action_group, false), MAP(MapFragment.class, R.string.menu_map, R.drawable.ic_action_map, false); private final String fragmentClassName; private final int titleResId; private final int iconResId; private final boolean keep; private Section(Class<? extends Fragment> fragmentClass, @StringRes int titleResId, @DrawableRes int iconResId, boolean keep) { this.fragmentClassName = fragmentClass.getName(); this.titleResId = titleResId; this.iconResId = iconResId; this.keep = keep; } public String getFragmentClassName() { return fragmentClassName; } public int getTitleResId() { return titleResId; } public int getIconResId() { return iconResId; } public boolean shouldKeep() { return keep; } } private static final long DATABASE_VALIDITY_DURATION = 24L * 60L * 60L * 1000L; // 24h private static final long DOWNLOAD_REMINDER_SNOOZE_DURATION = 24L * 60L * 60L * 1000L; // 24h private static final String PREF_LAST_DOWNLOAD_REMINDER_TIME = "last_download_reminder_time"; private static final String STATE_CURRENT_SECTION = "current_section"; private static final DateFormat LAST_UPDATE_DATE_FORMAT = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.getDefault()); private Section currentSection; private DrawerLayout drawerLayout; private ActionBarDrawerToggle drawerToggle; private View mainMenu; private TextView lastUpdateTextView; private MainMenuAdapter menuAdapter; private MenuItem searchMenuItem; private final BroadcastReceiver scheduleDownloadProgressReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { setSupportProgressBarIndeterminate(false); setSupportProgress(intent.getIntExtra(FosdemApi.EXTRA_PROGRESS, 0) * 100); } }; private final BroadcastReceiver scheduleDownloadResultReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // Hide the progress bar with a fill and fade out animation setSupportProgressBarIndeterminate(false); setSupportProgress(10000); int result = intent.getIntExtra(FosdemApi.EXTRA_RESULT, FosdemApi.RESULT_ERROR); String message; switch (result) { case FosdemApi.RESULT_ERROR: message = getString(R.string.schedule_loading_error); break; case 0: message = getString(R.string.events_download_empty); break; default: message = getResources().getQuantityString(R.plurals.events_download_completed, result, result); } Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show(); } }; private final BroadcastReceiver scheduleRefreshedReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { updateLastUpdateTime(); } }; public static class DownloadScheduleReminderDialogFragment extends DialogFragment { @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { return new AlertDialog.Builder(getActivity()).setTitle(R.string.download_reminder_title).setMessage(R.string.download_reminder_message) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ((MainActivity) getActivity()).startDownloadSchedule(); } }).setNegativeButton(android.R.string.cancel, null).create(); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); supportRequestWindowFeature(Window.FEATURE_PROGRESS); setContentView(R.layout.main); // Setup drawer layout getSupportActionBar().setDisplayHomeAsUpEnabled(true); drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); drawerLayout.setDrawerShadow(getResources().getDrawable(R.drawable.drawer_shadow), Gravity.LEFT); drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.main_menu, R.string.close_menu) { @Override public void onDrawerOpened(View drawerView) { updateActionBar(); supportInvalidateOptionsMenu(); // Make keypad navigation easier mainMenu.requestFocus(); } @Override public void onDrawerClosed(View drawerView) { updateActionBar(); supportInvalidateOptionsMenu(); } }; drawerToggle.setDrawerIndicatorEnabled(true); drawerLayout.setDrawerListener(drawerToggle); // Disable drawerLayout focus to allow trackball navigation. // We handle the drawer closing on back press ourselves. drawerLayout.setFocusable(false); // Setup Main menu mainMenu = findViewById(R.id.main_menu); ListView menuListView = (ListView) findViewById(R.id.main_menu_list); LayoutInflater inflater = LayoutInflater.from(this); View menuHeaderView = inflater.inflate(R.layout.header_main_menu, null); menuListView.addHeaderView(menuHeaderView, null, false); LocalBroadcastManager.getInstance(this).registerReceiver(scheduleRefreshedReceiver, new IntentFilter(DatabaseManager.ACTION_SCHEDULE_REFRESHED)); menuAdapter = new MainMenuAdapter(inflater); menuListView.setAdapter(menuAdapter); menuListView.setOnItemClickListener(this); // Last update date, below the menu lastUpdateTextView = (TextView) findViewById(R.id.last_update); updateLastUpdateTime(); // Restore current section if (savedInstanceState == null) { currentSection = Section.TRACKS; String fragmentClassName = currentSection.getFragmentClassName(); Fragment f = Fragment.instantiate(this, fragmentClassName); getSupportFragmentManager().beginTransaction().add(R.id.content, f, fragmentClassName).commit(); } else { currentSection = Section.values()[savedInstanceState.getInt(STATE_CURRENT_SECTION)]; } // Ensure the current section is visible in the menu menuListView.setSelection(currentSection.ordinal()); updateActionBar(); } private void updateActionBar() { getSupportActionBar().setTitle(drawerLayout.isDrawerOpen(mainMenu) ? R.string.app_name : currentSection.getTitleResId()); } private void updateLastUpdateTime() { long lastUpdateTime = DatabaseManager.getInstance().getLastUpdateTime(); lastUpdateTextView.setText(getString(R.string.last_update, (lastUpdateTime == -1L) ? getString(R.string.never) : LAST_UPDATE_DATE_FORMAT.format(new Date(lastUpdateTime)))); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); if (drawerLayout.isDrawerOpen(mainMenu)) { updateActionBar(); } drawerToggle.syncState(); } @Override public void onBackPressed() { if (drawerLayout.isDrawerOpen(mainMenu)) { drawerLayout.closeDrawer(mainMenu); } else { super.onBackPressed(); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(STATE_CURRENT_SECTION, currentSection.ordinal()); } @Override protected void onStart() { super.onStart(); // Ensure the progress bar is hidden when starting setSupportProgressBarVisibility(false); // Monitor the schedule download LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this); lbm.registerReceiver(scheduleDownloadProgressReceiver, new IntentFilter(FosdemApi.ACTION_DOWNLOAD_SCHEDULE_PROGRESS)); lbm.registerReceiver(scheduleDownloadResultReceiver, new IntentFilter(FosdemApi.ACTION_DOWNLOAD_SCHEDULE_RESULT)); // Download reminder long now = System.currentTimeMillis(); long time = DatabaseManager.getInstance().getLastUpdateTime(); if ((time == -1L) || (time < (now - DATABASE_VALIDITY_DURATION))) { SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE); time = prefs.getLong(PREF_LAST_DOWNLOAD_REMINDER_TIME, -1L); if ((time == -1L) || (time < (now - DOWNLOAD_REMINDER_SNOOZE_DURATION))) { prefs.edit().putLong(PREF_LAST_DOWNLOAD_REMINDER_TIME, now).commit(); FragmentManager fm = getSupportFragmentManager(); if (fm.findFragmentByTag("download_reminder") == null) { new DownloadScheduleReminderDialogFragment().show(fm, "download_reminder"); } } } } @Override protected void onStop() { if ((searchMenuItem != null) && (MenuItemCompat.isActionViewExpanded(searchMenuItem))) { MenuItemCompat.collapseActionView(searchMenuItem); } LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this); lbm.unregisterReceiver(scheduleDownloadProgressReceiver); lbm.unregisterReceiver(scheduleDownloadResultReceiver); super.onStop(); } @Override protected void onDestroy() { super.onDestroy(); LocalBroadcastManager.getInstance(this).unregisterReceiver(scheduleRefreshedReceiver); } @SuppressLint("NewApi") @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); MenuItem searchMenuItem = menu.findItem(R.id.search); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { this.searchMenuItem = searchMenuItem; // Associate searchable configuration with the SearchView SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchMenuItem); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); } else { // Legacy search mode for Eclair MenuItemCompat.setActionView(searchMenuItem, null); MenuItemCompat.setShowAsAction(searchMenuItem, MenuItemCompat.SHOW_AS_ACTION_IF_ROOM); } return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { // Hide & disable primary (contextual) action items when the main menu is opened if (drawerLayout.isDrawerOpen(mainMenu)) { final int size = menu.size(); for (int i = 0; i < size; ++i) { MenuItem item = menu.getItem(i); if ((item.getOrder() & 0xFFFF0000) == 0) { item.setVisible(false).setEnabled(false); } } } return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Will close the drawer if the home button is pressed if (drawerToggle.onOptionsItemSelected(item)) { return true; } switch (item.getItemId()) { case R.id.search: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { return false; } else { // Legacy search mode for Eclair onSearchRequested(); return true; } case R.id.refresh: startDownloadSchedule(); return true; case R.id.settings: startActivity(new Intent(this, SettingsActivity.class)); overridePendingTransition(R.anim.slide_in_right, R.anim.partial_zoom_out); return true; case R.id.about: new AboutDialogFragment().show(getSupportFragmentManager(), "about"); return true; } return false; } @SuppressLint("NewApi") public void startDownloadSchedule() { // Start by displaying indeterminate progress, determinate will come later setSupportProgressBarIndeterminate(true); setSupportProgressBarVisibility(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { new DownloadScheduleAsyncTask(this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } else { new DownloadScheduleAsyncTask(this).execute(); } } private static class DownloadScheduleAsyncTask extends AsyncTask<Void, Void, Void> { private final Context appContext; public DownloadScheduleAsyncTask(Context context) { appContext = context.getApplicationContext(); } @Override protected Void doInBackground(Void... args) { FosdemApi.downloadSchedule(appContext); return null; } } // MAIN MENU private class MainMenuAdapter extends BaseAdapter { private Section[] sections = Section.values(); private LayoutInflater inflater; private int currentSectionBackgroundColor; public MainMenuAdapter(LayoutInflater inflater) { this.inflater = inflater; currentSectionBackgroundColor = getResources().getColor(R.color.translucent_grey); } @Override public int getCount() { return sections.length; } @Override public Section getItem(int position) { return sections[position]; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = inflater.inflate(R.layout.item_main_menu, parent, false); } Section section = getItem(position); TextView tv = (TextView) convertView.findViewById(R.id.section_text); tv.setText(section.getTitleResId()); tv.setCompoundDrawablesWithIntrinsicBounds(section.getIconResId(), 0, 0, 0); // Show highlighted background for current section tv.setBackgroundColor((section == currentSection) ? currentSectionBackgroundColor : Color.TRANSPARENT); return convertView; } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Decrease position by 1 since the listView has a header view. Section section = menuAdapter.getItem(position - 1); if (section != currentSection) { // Switch to new section FragmentManager fm = getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); Fragment f = fm.findFragmentById(R.id.content); if (f != null) { if (currentSection.shouldKeep()) { ft.detach(f); } else { ft.remove(f); } } String fragmentClassName = section.getFragmentClassName(); if (section.shouldKeep() && ((f = fm.findFragmentByTag(fragmentClassName)) != null)) { ft.attach(f); } else { f = Fragment.instantiate(this, fragmentClassName); ft.add(R.id.content, f, fragmentClassName); } ft.commit(); currentSection = section; menuAdapter.notifyDataSetChanged(); } drawerLayout.closeDrawer(mainMenu); } public static class AboutDialogFragment extends DialogFragment { @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Context context = getActivity(); String title; try { String versionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName; title = String.format("%1$s %2$s", getString(R.string.app_name), versionName); } catch (NameNotFoundException e) { title = getString(R.string.app_name); } return new AlertDialog.Builder(context).setTitle(title).setIcon(R.drawable.ic_launcher).setMessage(getResources().getText(R.string.about_text)) .setPositiveButton(android.R.string.ok, null).create(); } @Override public void onStart() { super.onStart(); // Make links clickable; must be called after the dialog is shown ((TextView) getDialog().findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance()); } } }
package peergos.shared.mutable; import peergos.server.crypto.*; import peergos.shared.*; import peergos.shared.cbor.*; import peergos.shared.crypto.*; import peergos.shared.crypto.hash.*; import peergos.shared.io.ipfs.cid.*; import peergos.shared.util.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.stream.*; public class BufferedPointers implements MutablePointers { public static class PointerUpdate { public final PublicKeyHash owner, writer; public final byte[] signedUpdate; public PointerUpdate(PublicKeyHash owner, PublicKeyHash writer, byte[] signedUpdate) { this.owner = owner; this.writer = writer; this.signedUpdate = signedUpdate; } } private final MutablePointers target; private final Map<PublicKeyHash, PointerUpdate> buffer = new HashMap<>(); private final List<PointerUpdate> order = new ArrayList<>(); private Supplier<CompletableFuture<Boolean>> watcher; public BufferedPointers(MutablePointers target) { this.target = target; } public void watchUpdates(Supplier<CompletableFuture<Boolean>> watcher) { this.watcher = watcher; } @Override public CompletableFuture<Optional<byte[]>> getPointer(PublicKeyHash owner, PublicKeyHash writer) { synchronized (buffer) { PointerUpdate buffered = buffer.get(writer); if (buffered != null) return CompletableFuture.completedFuture(Optional.of(buffered.signedUpdate)); } return target.getPointer(owner, writer); } @Override public CompletableFuture<Boolean> setPointer(PublicKeyHash owner, PublicKeyHash writer, byte[] writerSignedBtreeRootHash) { synchronized (buffer) { PointerUpdate update = new PointerUpdate(owner, writer, writerSignedBtreeRootHash); buffer.put(writer, update); order.add(update); } return watcher.get(); } /** * Merge updates to a single pointer into a single update */ public void condense(Map<PublicKeyHash, SigningPrivateKeyAndPublicHash> writers) { int start = 0; List<PointerUpdate> newOrder = new ArrayList<>(); int j=1; for (; j < order.size(); j++) { PointerUpdate first = order.get(start); // preserve order of inter writer commits if (! order.get(j).writer.equals(first.writer)) { if (j - start > 1) { MaybeMultihash original = parse(first.signedUpdate).original; MaybeMultihash updated = parse(order.get(j - 1).signedUpdate).updated; newOrder.add(new PointerUpdate(first.owner, first.writer, writers.get(first.writer).secret.signMessage(new HashCasPair(original, updated).serialize()))); } else newOrder.add(first); // nothing to condense start = j; } } if (j - start > 0) {// condense the last run PointerUpdate first = order.get(start); MaybeMultihash original = parse(first.signedUpdate).original; MaybeMultihash updated = parse(order.get(j - 1).signedUpdate).updated; newOrder.add(new PointerUpdate(first.owner, first.writer, writers.get(first.writer).secret.signMessage(new HashCasPair(original, updated).serialize()))); } order.clear(); order.addAll(newOrder); } private static HashCasPair parse(byte[] signedCas) { return HashCasPair.fromCbor(CborObject.fromByteArray(Arrays.copyOfRange(signedCas, TweetNaCl.SIGNATURE_SIZE_BYTES, signedCas.length))); } public List<Cid> getRoots() { return order.stream() .map(u -> parse(u.signedUpdate)) .map(p -> p.updated) .flatMap(m -> m.toOptional().stream()) .map(c -> (Cid)c) .collect(Collectors.toList()); } public CompletableFuture<List<Boolean>> commit() { return Futures.combineAllInOrder(order.stream() .map(u -> target.setPointer(u.owner, u.writer, u.signedUpdate)) .collect(Collectors.toList())); } public void clear() { buffer.clear(); order.clear(); } }
package com.xensource.xenapi; import java.net.URL; import java.util.Map; import java.util.TimeZone; import org.apache.xmlrpc.XmlRpcException; import org.apache.xmlrpc.client.XmlRpcClient; import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; import org.apache.xmlrpc.client.XmlRpcHttpClientConfig; import com.xensource.xenapi.Types.BadServerResponse; import com.xensource.xenapi.Types.XenAPIException; /** * Represents a connection to a XenServer. Creating a new instance of this class initialises a new XmlRpcClient that is * then used by all method calls: each method call in xenapi takes a Connection as a parameter, composes an XMLRPC * method call, and dispatches it on the Connection's client via the dispatch method. */ public class Connection { /** * The version of the bindings that this class belongs to. */ public static final String BINDINGS_VERSION = "@SDK_VERSION@"; private APIVersion apiVersion; /** * Default reply timeout for xml-rpc calls in seconds */ protected static final int DEFAULT_REPLY_TIMEOUT = 600; /** * Default connection timeout for xml-rpc calls in seconds */ protected static final int DEFAULT_CONNECTION_TIMEOUT = 5; /** * Reply timeout for xml-rpc calls. The default value is 10 minutes. * * @deprecated This field is not used any more. To set the reply timeout * for xml-rpc calls, please use the appropriate Connection constructor. */ @Deprecated protected int _replyWait = 600; /** * Connection timeout for xml-rpc calls. The default value is 5 seconds. * * @deprecated This field is not used any more. To set the connection timeout * for xml-rpc calls, please use the appropriate Connection constructor. */ @Deprecated protected int _connWait = 5; /** * Updated when Session.login_with_password() is called. */ public APIVersion getAPIVersion() { return apiVersion; } /** * The opaque reference to the session used by this connection */ private String sessionReference; /** * As seen by the xmlrpc library. From our point of view it's a server. */ private final XmlRpcClient client; /** * Creates a connection to a particular server using a given url. This object can then be passed * in to any other API calls. * * Note this constructor does NOT call Session.loginWithPassword; the programmer is responsible for calling it, * passing the Connection as a parameter. No attempt to connect to the server is made until login is called. * * When this constructor is used, a call to dispose() will do nothing. The programmer is responsible for manually * logging out the Session. * * This constructor uses the default values of the reply and connection timeouts for the xmlrpc calls * (600 seconds and 5 seconds respectively). * * @param url The URL of the server to connect to */ public Connection(URL url) { this.client = getClientFromURL(url, DEFAULT_REPLY_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT); } /** * Creates a connection to a particular server using a given url. This object can then be passed * in to any other API calls. * * Note this constructor does NOT call Session.loginWithPassword; the programmer is responsible for calling it, * passing the Connection as a parameter. No attempt to connect to the server is made until login is called. * * When this constructor is used, a call to dispose() will do nothing. The programmer is responsible for manually * logging out the Session. * * @param url The URL of the server to connect to * @param replyTimeout The reply timeout for xml-rpc calls in seconds * @param connTimeout The connection timeout for xml-rpc calls in seconds */ public Connection(URL url, int replyTimeout, int connTimeout) { this.client = getClientFromURL(url, replyTimeout, connTimeout); } /** * Creates a connection to a particular server using a given url. This object can then be passed * in to any other API calls. * * This constructor uses the default values of the reply and connection timeouts for the xmlrpc calls * (600 seconds and 5 seconds respectively). * * @param url The URL of the server to connect to * @param sessionReference A reference to a logged-in Session. Any method calls on this * Connection will use it. This constructor does not call Session.loginWithPassword, and dispose() on the resulting * Connection object does not call Session.logout. The programmer is responsible for ensuring the Session is logged * in and out correctly. */ public Connection(URL url, String sessionReference) { this.client = getClientFromURL(url, DEFAULT_REPLY_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT); this.sessionReference = sessionReference; } /** * Creates a connection to a particular server using a given url. This object can then be passed * in to any other API calls. * * @param url The URL of the server to connect to * @param sessionReference A reference to a logged-in Session. Any method calls on this Connection will use it. * This constructor does not call Session.loginWithPassword, and dispose() on the resulting * Connection object does not call Session.logout. The programmer is responsible for * ensuring the Session is logged in and out correctly. * @param replyTimeout The reply timeout for xml-rpc calls in seconds * @param connTimeout The connection timeout for xml-rpc calls in seconds */ public Connection(URL url, String sessionReference, int replyTimeout, int connTimeout) { this.client = getClientFromURL(url, replyTimeout, connTimeout); this.sessionReference = sessionReference; } private XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); public XmlRpcClientConfigImpl getConfig() { return config; } private XmlRpcClient getClientFromURL(URL url, int replyWait, int connWait) { config.setTimeZone(TimeZone.getTimeZone("UTC")); config.setServerURL(url); config.setReplyTimeout(replyWait * 1000); config.setConnectionTimeout(connWait * 1000); XmlRpcClient client = new XmlRpcClient(); client.setConfig(config); return client; } /* * Because the binding calls are constructing their own parameter lists, they need to be able to get to * the session reference directly. This is all rather ugly and needs redone * Changed to public to allow easier integration with HTTP-level streaming interface, * see CA-15447 */ public String getSessionReference() { return this.sessionReference; } /** * The (auto-generated parts of) the bindings dispatch XMLRPC calls on this Connection's client through this method. */ protected Map dispatch(String method_call, Object[] method_params) throws XmlRpcException, XenAPIException { Map response = (Map) client.execute(method_call, method_params); if (method_call.equals("session.login_with_password") && response.get("Status").equals("Success")) { Session session = Types.toSession(response.get("Value")); sessionReference = session.ref; setAPIVersion(session); } else if (method_call.equals("session.slave_local_login_with_password") && response.get("Status").equals("Success")) { sessionReference = Types.toSession(response.get("Value")).ref; apiVersion = APIVersion.latest(); } else if (method_call.equals("session.logout")) { // Work around a bug in XenServer 5.0 and below. // session.login_with_password should have rejected us with // HOST_IS_SLAVE, but instead we don't find out until later. // We don't want to leak the session, so we need to log out // this session from the master instead. if (response.get("Status").equals("Failure")) { Object[] error = (Object[]) response.get("ErrorDescription"); if (error.length == 2 && error[0].equals("HOST_IS_SLAVE")) { try { XmlRpcHttpClientConfig clientConfig = (XmlRpcHttpClientConfig)client.getClientConfig(); URL client_url = clientConfig.getServerURL(); URL masterUrl = new URL(client_url.getProtocol(), (String)error[1], client_url.getPort(), client_url.getFile()); Connection tmp_conn = new Connection(masterUrl, sessionReference, clientConfig.getReplyTimeout(), clientConfig.getConnectionTimeout()); Session.logout(tmp_conn); } catch (Exception ex) { // Ignore } } } this.sessionReference = null; } return Types.checkResponse(response); } private void setAPIVersion(Session session) throws XenAPIException, XmlRpcException { try { long major = session.getThisHost(this).getAPIVersionMajor(this); long minor = session.getThisHost(this).getAPIVersionMinor(this); apiVersion = APIVersion.fromMajorMinor(major, minor); } catch (BadServerResponse exn) { apiVersion = APIVersion.UNKNOWN; } } }
package com.couchbase.devxp.updownvote; import com.couchbase.lite.CouchbaseLiteException; import com.couchbase.lite.Database; import com.couchbase.lite.Document; import com.couchbase.lite.Query; import java.util.Date; public class Presentation { // HINT create a property in the presentations so you can find them among the objects public static final String TYPE = "presentation"; private Date createdAt; private int upVotes; private int downVotes; private String title; private Document sourceDocument; private Database database; // TODO Create fields for createdAt, upVotes, downVotes, title public static Query findAll(Database database) { // TODO create a view with a map function listing all the presentations in the database return null; } public static Presentation from(Document document) { // TODO create a presentation object from the document passed // HINT make sure to save of the document to enable updating later return null; } public Presentation(Database database) { // TODO initialzie the fields // TODO save of a reference to the database used } public void save() throws CouchbaseLiteException { // TODO save a document to the database // TODO update a document if it has been saved before // HINT this needs a reference to the original document for revision, key, etc. } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } public int getUpVotes() { return upVotes; } public void setUpVotes(int upVotes) { this.upVotes = upVotes; } public int getDownVotes() { return downVotes; } public void setDownVotes(int downVotes) { this.downVotes = downVotes; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Document getSourceDocument() { return sourceDocument; } public void setSourceDocument(Document sourceDocument) { this.sourceDocument = sourceDocument; } }
package com.example.cbess.firebasecrud; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.BuildConfig; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.database.ChildEventListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.remoteconfig.FirebaseRemoteConfig; import com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings; import java.util.ArrayList; public class MainActivity extends AppCompatActivity implements TaskAdapter.TaskAdapterListener { public static final String TAG = MainActivity.class.getSimpleName(); private ArrayList<TaskItem> tasks = new ArrayList<>(); private TaskAdapter adapter; // Tasks ref to firebase DB private DatabaseReference tasksRef; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); initConfig(); initDatabase(); // setup the recycler view final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(this)); adapter = new TaskAdapter(tasks, this); recyclerView.setAdapter(adapter); loadData(); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { addEmptyTask(); } }); } private void initConfig() { final FirebaseRemoteConfig config = FirebaseRemoteConfig.getInstance(); // update the config to ping multiple times, don't use liberally FirebaseRemoteConfigSettings settings = new FirebaseRemoteConfigSettings.Builder() .setDeveloperModeEnabled(BuildConfig.DEBUG) .build(); config.setConfigSettings(settings); // set the defaults config.setDefaults(R.xml.firebase); // if there is no entry on the server for the config keys, then the client-side defaults are used config.fetch(15).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()) { config.activateFetched(); } } }); } private void initDatabase() { FirebaseDatabase database = FirebaseDatabase.getInstance(); // synced data and writes will be persisted to disk across app // restarts and our app should work seamlessly in offline situations //database.setPersistenceEnabled(true); // create a leaf on root tasksRef = database.getReference("tasks"); } private void loadData() { tasks.clear(); // fetch from firebase as remote data changes tasksRef.addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String s) { TaskItem item = dataSnapshot.getValue(TaskItem.class); // make sure it is not already in the dataset if (!tasks.contains(item)) { addTask(item); } } @Override public void onChildChanged(DataSnapshot dataSnapshot, String s) { TaskItem remoteItem = dataSnapshot.getValue(TaskItem.class); // find the local item by uid int idx = tasks.indexOf(remoteItem); TaskItem localItem = tasks.get(idx); Log.d(TAG, String.format("Updating '%s' to '%s'", localItem.getName(), remoteItem.getName())); // update local from remote localItem.setName(remoteItem.getName()); adapter.notifyItemChanged(idx); } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { TaskItem remoteItem = dataSnapshot.getValue(TaskItem.class); int idx = tasks.indexOf(remoteItem); if (idx > -1) { tasks.remove(idx); adapter.notifyItemRemoved(idx); } } // region Unused Methods @Override public void onChildMoved(DataSnapshot dataSnapshot, String s) {} @Override public void onCancelled(DatabaseError databaseError) {} // endregion }); } @Override public void onDeleteButtonClick(TaskAdapter adapter, int position) { TaskItem item = tasks.get(position); tasksRef.child(item.getUid()).removeValue(); Toast.makeText(this, "Deleted: " + item, Toast.LENGTH_SHORT).show(); } @Override public void onDoneKeyClick(TaskAdapter adapter, int position) { final TaskItem item = tasks.get(position); String uid = item.getUid(); if (uid == null) { // get unique ID from firebase db uid = tasksRef.push().getKey(); item.setUid(uid); } // send data to firebase tasksRef.child(uid).setValue(item).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { Toast.makeText(MainActivity.this, "Saved: " + item, Toast.LENGTH_SHORT).show(); addEmptyTask(); } }); } private void addEmptyTask() { String newTaskDefault = getString(R.string.config_task_name); String hint = FirebaseRemoteConfig.getInstance().getString(newTaskDefault); adapter.setEditTextHint(hint); addTask(new TaskItem()); } private void addTask(TaskItem taskItem) { // try to find an existing new task, then remove it int idx = 0; for (TaskItem item : tasks) { if (item.getUid() == null) { tasks.remove(idx); break; } ++idx; } tasks.add(taskItem); adapter.notifyDataSetChanged(); } }
package com.example.fatih.ocrtest; import android.app.ProgressDialog; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONObject; import java.io.File; import java.util.List; public class ImageConfirmation extends AppCompatActivity{ String path; ProgressDialog pDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.image_confirmation); ImageView image = (ImageView) findViewById(R.id.show_image); Button confirmation = (Button) findViewById(R.id.confirmation_button); Bundle extras = getIntent().getExtras(); if (extras != null) { path = extras.getString("path"); setImage(path,image); } confirmation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(checkNetwork(getApplicationContext())){ LongOperation op = new LongOperation(); op.execute(path); } else{ Context context = getApplicationContext(); CharSequence text = "Check Your Internet Connection"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); } } }); } void setImage(String path, ImageView image){ File imgFile = new File(path); if(imgFile.exists()){ Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath()); image.setImageBitmap(myBitmap); } } boolean checkNetwork(Context ctx){ ConnectivityManager conMgr = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo i = conMgr.getActiveNetworkInfo(); if (i == null) return false; if (!i.isConnected()) return false; if (!i.isAvailable()) return false; return true; } private class LongOperation extends AsyncTask<String, Void, String> { String parsedText=""; @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(ImageConfirmation.this); pDialog.setMessage("Processing Image"); pDialog.setCancelable(false); pDialog.show(); } @Override protected String doInBackground(String... params) { try{ Log.e("PATH", path); String charset = "UTF-8"; String apikey = "helloworld"; String requestURL = "https://ocr.space/api/Parse/Image"; MultiPartUtility multipart = new MultiPartUtility(requestURL, charset); multipart.addFormField("apikey", apikey); multipart.addFormField("param_name_3", "param_value"); multipart.addFilePart("file", new File(path)); List<String> response = multipart.finish(); // response from server. String res=""; JSONObject jObj; for (int i=0;i<response.size();i++){ Log.e("SONUC:::",response.get(i)); res += response.get(i); } jObj = new JSONObject(res); JSONArray aJsonArray = jObj.getJSONArray("ParsedResults"); for (int i =0; i<aJsonArray.length(); i++){ JSONObject c = aJsonArray.getJSONObject(i); parsedText = c.getString("ParsedText"); } Log.i("PARSED TEXT",parsedText); }catch (Exception e){ Log.e("ERROR ON BUILDING URL",e.toString()); } return parsedText; } @Override protected void onPostExecute(String result) { Log.e(" if (pDialog.isShowing()) pDialog.dismiss(); final TextView resultView = (TextView) findViewById(R.id.result); resultView.setText(parsedText); } @Override protected void onProgressUpdate(Void... values) { } } }
package fitnesse.testsystems.slim.tables; import static fitnesse.slim.converters.VoidConverter.VOID_TAG; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static util.ListUtility.list; import java.util.List; import java.util.Map; import org.junit.Test; import fitnesse.slim.instructions.CallAndAssignInstruction; import fitnesse.slim.instructions.CallInstruction; import fitnesse.slim.instructions.Instruction; import fitnesse.slim.instructions.MakeInstruction; import fitnesse.testsystems.slim.SlimCommandRunningClient; public class DecisionTableTest extends SlimTableTestSupport<DecisionTable> { private final String simpleDecisionTable = "|DT:fixture|argument|\n" + "|var|func?|\n" + "|3|5|\n" + "|7|9|\n"; private final String decisionTableWithSameFunctionMultipleTimes= "|DT:fixture|argument|\n" + "|func?|func?|\n" + "|3|5|\n" + "|7|9|\n"; private DecisionTable decisionTable; private void makeDecisionTableAndBuildInstructions(String tableText) throws Exception { decisionTable = makeSlimTableAndBuildInstructions(tableText); } @Test(expected=SyntaxError.class) public void aDecisionTableWithOnlyTwoRowsIsBad() throws Exception { makeDecisionTableWithTwoRows(); } private void assertTableIsBad(DecisionTable decisionTable) { assertTrue(firstCellOfTable(decisionTable).contains("Bad table")); } private String firstCellOfTable(DecisionTable decisionTable) { return decisionTable.getTable().getCellContents(0, 0); } private void makeDecisionTableWithTwoRows() throws Exception { makeDecisionTableAndBuildInstructions("|x|\n|y|\n"); } @Test(expected=SyntaxError.class) public void wrongNumberOfColumns() throws Exception { makeDecisionTableAndBuildInstructions( "|DT:fixture|argument|\n" + "|var|var2|\n" + "|3|\n" + "|7|9|\n" ); assertTableIsBad(decisionTable); } @Test public void decisionTableCanBeConstructorOnly() throws Exception { makeDecisionTableAndBuildInstructions("|fixture|argument|\n"); List<Instruction> expectedInstructions = list( new MakeInstruction("decisionTable_id_0", "decisionTable_id", "fixture", new Object[]{"argument"}), new CallInstruction("decisionTable_id_1", "decisionTable_id", "table", new Object[]{list()}) ); assertEquals(expectedInstructions, instructions); Map<String, Object> pseudoResults = SlimCommandRunningClient.resultToMap( list( list("decisionTable_id_0", "OK"), list("decisionTable_id_1", "OK") ) ); SlimAssertion.evaluateExpectations(assertions, pseudoResults); String colorizedTable = decisionTable.getTable().toString(); String expectedColorizedTable = "[[pass(fixture), argument]]"; assertEquals(expectedColorizedTable, colorizedTable); } @Test public void canBuildInstructionsForSimpleDecisionTable() throws Exception { makeDecisionTableAndBuildInstructions(simpleDecisionTable); int n = 0; List<Instruction> expectedInstructions = list( new MakeInstruction(id(n++), "decisionTable_id", "fixture", new Object[]{"argument"}), new CallInstruction(id(n++), "decisionTable_id", "table", new Object[]{list(list("var", "func?"), list("3", "5"), list("7", "9"))}), new CallInstruction(id(n++), "decisionTable_id", "beginTable"), new CallInstruction(id(n++), "decisionTable_id", "reset"), new CallInstruction(id(n++), "decisionTable_id", "setVar", new Object[]{"3"}), new CallInstruction(id(n++), "decisionTable_id", "execute"), new CallInstruction(id(n++), "decisionTable_id", "func"), new CallInstruction(id(n++), "decisionTable_id", "reset"), new CallInstruction(id(n++), "decisionTable_id", "setVar", new Object[]{"7"}), new CallInstruction(id(n++), "decisionTable_id", "execute"), new CallInstruction(id(n++), "decisionTable_id", "func"), new CallInstruction(id(n++), "decisionTable_id", "endTable") ); assertEquals(expectedInstructions, instructions); } @Test public void canBuildInstructionsForMultipleCallsToSameSetter() throws Exception { String decisionTableWithSameSetterMultipleTimes = "|DT:fixture|argument|\n" + "|var|var|\n" + "|3|5|\n" + "|7|9|\n"; makeDecisionTableAndBuildInstructions(decisionTableWithSameSetterMultipleTimes); int n = 0; List<Instruction> expectedInstructions = list( new MakeInstruction(id(n++), "decisionTable_id", "fixture", new Object[]{"argument"}), new CallInstruction(id(n++), "decisionTable_id", "table", new Object[]{list(list("var", "var"), list("3", "5"), list("7", "9"))}), new CallInstruction(id(n++), "decisionTable_id", "beginTable"), new CallInstruction(id(n++), "decisionTable_id", "reset"), new CallInstruction(id(n++), "decisionTable_id", "setVar", new Object[]{"3"}), new CallInstruction(id(n++), "decisionTable_id", "setVar", new Object[]{"5"}), new CallInstruction(id(n++), "decisionTable_id", "execute"), new CallInstruction(id(n++), "decisionTable_id", "reset"), new CallInstruction(id(n++), "decisionTable_id", "setVar", new Object[]{"7"}), new CallInstruction(id(n++), "decisionTable_id", "setVar", new Object[]{"9"}), new CallInstruction(id(n++), "decisionTable_id", "execute"), new CallInstruction(id(n++), "decisionTable_id", "endTable") ); assertEquals(expectedInstructions, instructions); } @Test public void canBuildInstructionsForMultipleCallsToSameFunction() throws Exception { makeDecisionTableAndBuildInstructions(decisionTableWithSameFunctionMultipleTimes); int n = 0; List<Instruction> expectedInstructions = list( new MakeInstruction(id(n++), "decisionTable_id", "fixture", new Object[]{"argument"}), new CallInstruction(id(n++), "decisionTable_id", "table", new Object[]{list(list("func?", "func?"), list("3", "5"), list("7", "9"))}), new CallInstruction(id(n++), "decisionTable_id", "beginTable"), new CallInstruction(id(n++), "decisionTable_id", "reset"), new CallInstruction(id(n++), "decisionTable_id", "execute"), new CallInstruction(id(n++), "decisionTable_id", "func"), new CallInstruction(id(n++), "decisionTable_id", "func"), new CallInstruction(id(n++), "decisionTable_id", "reset"), new CallInstruction(id(n++), "decisionTable_id", "execute"), new CallInstruction(id(n++), "decisionTable_id", "func"), new CallInstruction(id(n++), "decisionTable_id", "func"), new CallInstruction(id(n++), "decisionTable_id", "endTable") ); assertEquals(expectedInstructions, instructions); } private String id(int n) { return "decisionTable_id_"+n; } @Test public void canUseBangToCallFunction() throws Exception { makeDecisionTableAndBuildInstructions( "|DT:fixture|argument|\n" + "|var|func!|\n" + "|3|5|\n" + "|7|9|\n"); int n=0; List<Instruction> expectedInstructions = list( new MakeInstruction(id(n++), "decisionTable_id", "fixture", new Object[]{"argument"}), new CallInstruction(id(n++), "decisionTable_id", "table", new Object[]{list(list("var", "func!"), list("3", "5"), list("7", "9"))}), new CallInstruction(id(n++), "decisionTable_id", "beginTable"), new CallInstruction(id(n++), "decisionTable_id", "reset"), new CallInstruction(id(n++), "decisionTable_id", "setVar", new Object[]{"3"}), new CallInstruction(id(n++), "decisionTable_id", "execute"), new CallInstruction(id(n++), "decisionTable_id", "func"), new CallInstruction(id(n++), "decisionTable_id", "reset"), new CallInstruction(id(n++), "decisionTable_id", "setVar", new Object[]{"7"}), new CallInstruction(id(n++), "decisionTable_id", "execute"), new CallInstruction(id(n++), "decisionTable_id", "func"), new CallInstruction(id(n++), "decisionTable_id", "endTable") ); assertEquals(expectedInstructions, instructions); } @SuppressWarnings("unchecked") @Test public void settersAreFirstFunctionsAreLastLeftToRight() throws Exception { makeDecisionTableAndBuildInstructions("|DT:fixture|\n" + "|a|fa?|b|fb?|c|fc?|d|e|f|fd?|fe?|ff?|\n" + "|a|a|b|b|c|c|d|e|f|d|e|f|\n"); int n = 0; List<Instruction> expectedInstructions = list( new MakeInstruction(id(n++), "decisionTable_id", "fixture"), new CallInstruction(id(n++),"decisionTable_id", "table", new Object[] {list( list("a", "fa?", "b", "fb?", "c", "fc?", "d", "e", "f", "fd?", "fe?", "ff?"), list("a", "a", "b", "b", "c", "c", "d", "e", "f", "d", "e", "f"))}), new CallInstruction(id(n++), "decisionTable_id", "beginTable"), new CallInstruction(id(n++), "decisionTable_id", "reset"), new CallInstruction(id(n++), "decisionTable_id", "setA", new Object[] {"a"}), new CallInstruction(id(n++), "decisionTable_id", "setB", new Object[] {"b"}), new CallInstruction(id(n++), "decisionTable_id", "setC", new Object[] {"c"}), new CallInstruction(id(n++), "decisionTable_id", "setD", new Object[] {"d"}), new CallInstruction(id(n++), "decisionTable_id", "setE", new Object[] {"e"}), new CallInstruction(id(n++), "decisionTable_id", "setF", new Object[] {"f"}), new CallInstruction(id(n++), "decisionTable_id", "execute"), new CallInstruction(id(n++), "decisionTable_id", "fa"), new CallInstruction(id(n++), "decisionTable_id", "fb"), new CallInstruction(id(n++), "decisionTable_id", "fc"), new CallInstruction(id(n++), "decisionTable_id", "fd"), new CallInstruction(id(n++), "decisionTable_id", "fe"), new CallInstruction(id(n++), "decisionTable_id", "ff"), new CallInstruction(id(n++), "decisionTable_id", "endTable") ); assertEquals(expectedInstructions, instructions); } @Test public void canBuildInstructionsForTableWithVariables() throws Exception { makeDecisionTableAndBuildInstructions( "|DT:fixture|\n" + "|var|func?|\n" + "|3|$V=|\n" + "|$V|9|\n" ); int n=0; List<Instruction> expectedInstructions = list( new MakeInstruction(id(n++), "decisionTable_id", "fixture"), new CallInstruction(id(n++), "decisionTable_id", "table", new Object[]{list(list("var", "func?"), list("3", "$V="), list("$V", "9"))}), new CallInstruction(id(n++), "decisionTable_id", "beginTable"), new CallInstruction(id(n++), "decisionTable_id", "reset"), new CallInstruction(id(n++), "decisionTable_id", "setVar", new Object[]{"3"}), new CallInstruction(id(n++), "decisionTable_id", "execute"), new CallAndAssignInstruction(id(n++), "V", "decisionTable_id", "func"), new CallInstruction(id(n++), "decisionTable_id", "reset"), new CallInstruction(id(n++), "decisionTable_id", "setVar", new Object[]{"$V"}), new CallInstruction(id(n++), "decisionTable_id", "execute"), new CallInstruction(id(n++), "decisionTable_id", "func"), new CallInstruction(id(n++), "decisionTable_id", "endTable") ); assertEquals(expectedInstructions.toString(), instructions.toString()); } @Test public void canEvaluateReturnValuesAndColorizeTable() throws Exception { makeDecisionTableAndBuildInstructions(simpleDecisionTable); int n=0; Map<String, Object> pseudoResults = SlimCommandRunningClient.resultToMap( list( list(id(n++), "OK"), list(id(n++), VOID_TAG), list(id(n++), VOID_TAG), // beginTable list(id(n++), VOID_TAG), //reset list(id(n++), VOID_TAG), //set list(id(n++), VOID_TAG), //execute list(id(n++), "5"), list(id(n++), VOID_TAG), list(id(n++), VOID_TAG), list(id(n++), VOID_TAG), list(id(n++), "5"), list(id(n++), VOID_TAG) //endTable ) ); SlimAssertion.evaluateExpectations(assertions, pseudoResults); String colorizedTable = decisionTable.getTable().toString(); String expectedColorizedTable = "[" + "[pass(DT:fixture), argument], " + "[var, func?], " + "[3, pass(5)], " + "[7, fail(a=5;e=9)]" + "]"; assertEquals(expectedColorizedTable, colorizedTable); } @Test public void translatesTestTablesIntoLiteralTables() throws Exception { makeDecisionTableAndBuildInstructions("!" + simpleDecisionTable); int n = 0; Map<String, Object> pseudoResults = SlimCommandRunningClient.resultToMap( list( list(id(n++), "OK"), list(id(n++), VOID_TAG), list(id(n++), VOID_TAG), //beginTable list(id(n++), VOID_TAG), //reset list(id(n++), VOID_TAG), //set list(id(n++), VOID_TAG), //execute list(id(n++), "5"), list(id(n++), VOID_TAG), list(id(n++), VOID_TAG), list(id(n++), VOID_TAG), list(id(n++), "5"), list(id(n++), VOID_TAG) //endTable ) ); SlimAssertion.evaluateExpectations(assertions, pseudoResults); String colorizedTable = decisionTable.getTable().toString(); String expectedColorizedTable = "[" + "[pass(DT:fixture), argument], " + "[var, func?], " + "[3, pass(5)], " + "[7, fail(a=5;e=9)]" + "]"; assertEquals(expectedColorizedTable, colorizedTable); } @Test public void commentColumn() throws Exception { // TODO: a lot of copy and paste from the previous test String decisionTableWithComment = "|DT:fixture|argument||\n" + "|var|func?|#comment|\n" + "|3|5|comment|\n" + "|7|9||\n"; makeDecisionTableAndBuildInstructions(decisionTableWithComment); int n = 0; Map<String, Object> pseudoResults = SlimCommandRunningClient.resultToMap( list( list(id(n++), "OK"), list(id(n++), VOID_TAG), list(id(n++), VOID_TAG), //beginTable list(id(n++), VOID_TAG), //reset list(id(n++), VOID_TAG), //set list(id(n++), VOID_TAG), //execute list(id(n++), "5"), list(id(n++), VOID_TAG), list(id(n++), VOID_TAG), list(id(n++), VOID_TAG), list(id(n++), "5"), list(id(n++), VOID_TAG) //endTable ) ); SlimAssertion.evaluateExpectations(assertions, pseudoResults); String colorizedTable = decisionTable.getTable().toString(); String expectedColorizedTable = "[" + "[pass(DT:fixture), argument, ], " + "[var, func?, #comment], " + "[3, pass(5), comment], " + "[7, fail(a=5;e=9), ]" + "]"; assertEquals(expectedColorizedTable, colorizedTable); } @Test public void canEvaluateReturnValuesAndColorizeTableForMultipleCallsToSameFunction() throws Exception { makeDecisionTableAndBuildInstructions(decisionTableWithSameFunctionMultipleTimes); int n=0; Map<String, Object> pseudoResults = SlimCommandRunningClient.resultToMap( list( list(id(n++), "OK"), list(id(n++), VOID_TAG), list(id(n++), VOID_TAG), // beginTable list(id(n++), VOID_TAG), //reset list(id(n++), VOID_TAG), //execute list(id(n++), "4"), list(id(n++), "5"), list(id(n++), VOID_TAG), list(id(n++), VOID_TAG), list(id(n++), "7"), list(id(n++), "5"), list(id(n++), VOID_TAG) //endTable ) ); SlimAssertion.evaluateExpectations(assertions, pseudoResults); String colorizedTable = decisionTable.getTable().toString(); String expectedColorizedTable = "[" + "[pass(DT:fixture), argument], " + "[func?, func?], " + "[fail(a=4;e=3), pass(5)], " + "[pass(7), fail(a=5;e=9)]" + "]"; assertEquals(expectedColorizedTable, colorizedTable); } @Test public void usesDisgracedClassNames() throws Exception { makeDecisionTableAndBuildInstructions( "|DT:slim test|\n" + "|x|\n" + "|y|\n" ); Instruction makeInstruction = new MakeInstruction("decisionTable_id_0", "decisionTable_id", "SlimTest"); assertEquals(makeInstruction, instructions.get(0)); } @Test public void usesDisgracedMethodNames() throws Exception { makeDecisionTableAndBuildInstructions( "|DT:fixture|\n" + "|my var|my func?|\n" + "|8|7|\n" ); CallInstruction setInstruction = new CallInstruction("decisionTable_id_4", "decisionTable_id", "setMyVar", new Object[]{"8"}); CallInstruction callInstruction = new CallInstruction("decisionTable_id_6", "decisionTable_id", "myFunc"); assertEquals(setInstruction, instructions.get(4)); assertEquals(callInstruction, instructions.get(6)); } }
package pt.webdetails.cda.utils; import java.util.ArrayList; import javax.swing.table.TableModel; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.pentaho.reporting.engine.classic.core.util.TypedTableModel; import pt.webdetails.cda.dataaccess.ColumnDefinition; import pt.webdetails.cda.dataaccess.DataAccess; public class TableModelUtils { private static final Log logger = LogFactory.getLog(TableModelUtils.class); private static TableModelUtils _instance; public TableModelUtils() { } public TableModel transformTableModel(final DataAccess dataAccess /*, QueryOptions queryOptions*/, final TableModel tableModel) { logger.warn("transformTableModel Not implemented yet"); return copyTableModel(dataAccess, tableModel); } public TableModel copyTableModel(final DataAccess dataAccess, final TableModel t) { final int count = t.getColumnCount(); ArrayList<ColumnDefinition> calculatedColumnsList = dataAccess.getCalculatedColumns(); if (calculatedColumnsList.size() > 0) { logger.warn("Todo: Implement " + calculatedColumnsList.size() + " Calculated Columns"); } final Class[] colTypes = new Class[count]; final String[] colNames = new String[count]; for (int i = 0; i < count; i++) { colTypes[i] = t.getColumnClass(i); final ColumnDefinition col = dataAccess.getColumnDefinition(i); colNames[i] = col != null ? col.getName() : t.getColumnName(i); } final int rowCount = t.getRowCount(); logger.debug(rowCount == 0 ? "No data found" : "Found " + rowCount + " rows"); final TypedTableModel typedTableModel = new TypedTableModel(colNames, colTypes, rowCount); for (int r = 0; r < rowCount; r++) { for (int c = 0; c < count; c++) { typedTableModel.setValueAt(t.getValueAt(r, c), r, c); } } return typedTableModel; } public static synchronized TableModelUtils getInstance() { if (_instance == null) { _instance = new TableModelUtils(); } return _instance; } }
package org.cytoscape.data.reader.kgml.test; import static org.junit.Assert.*; import org.cytoscape.data.reader.kgml.KGMLReader; import org.junit.After; import org.junit.Before; import org.junit.Test; public class KGMLReaderTest { private KGMLReader reader1; @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testRead() throws Exception { reader1 = new KGMLReader("testData/bsu00010.xml"); reader1.read(); final int[] nodeArray = reader1.getNodeIndicesArray(); assertNotNull(nodeArray); assertEquals(91, nodeArray.length); final int[] edgeArray = reader1.getEdgeIndicesArray(); assertNotNull(edgeArray); // expected:<115> but was:<139> // assertEquals(115, edgeArray.length); } }
package org.jvnet.hudson.test; import com.gargoylesoftware.htmlunit.AjaxController; import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException; import com.gargoylesoftware.htmlunit.Page; import com.gargoylesoftware.htmlunit.WebRequestSettings; import com.gargoylesoftware.htmlunit.html.HtmlForm; import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine; import com.gargoylesoftware.htmlunit.javascript.host.Stylesheet; import hudson.model.Descriptor; import hudson.model.FreeStyleProject; import hudson.model.Hudson; import hudson.model.Item; import hudson.model.UpdateCenter; import hudson.tasks.Mailer; import junit.framework.TestCase; import org.jvnet.hudson.test.HudsonHomeLoader.CopyExisting; import org.jvnet.hudson.test.recipes.Recipe; import org.jvnet.hudson.test.recipes.Recipe.Runner; import org.jvnet.hudson.test.rhino.JavaScriptDebugger; import org.mortbay.jetty.Server; import org.mortbay.jetty.bio.SocketConnector; import org.mortbay.jetty.security.HashUserRealm; import org.mortbay.jetty.security.UserRealm; import org.mortbay.jetty.webapp.Configuration; import org.mortbay.jetty.webapp.WebAppContext; import org.mortbay.jetty.webapp.WebXmlConfiguration; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextFactory; import org.w3c.css.sac.CSSException; import org.w3c.css.sac.CSSParseException; import org.w3c.css.sac.ErrorHandler; import org.xml.sax.SAXException; import javax.servlet.ServletContext; import java.io.File; import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.ref.WeakReference; import java.lang.reflect.Method; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.logging.Level; import java.util.logging.Logger; public abstract class HudsonTestCase extends TestCase { protected Hudson hudson; protected final TestEnvironment env = new TestEnvironment(); protected HudsonHomeLoader homeLoader = HudsonHomeLoader.NEW; /** * TCP/IP port that the server is listening on. */ protected int localPort; protected Server server; /** * Where in the {@link Server} is Hudson deploed? */ protected String contextPath = "/"; /** * {@link Runnable}s to be invoked at {@link #tearDown()}. */ protected List<LenientRunnable> tearDowns = new ArrayList<LenientRunnable>(); /** * Remember {@link WebClient}s that are created, to release them properly. */ private List<WeakReference<WebClient>> clients = new ArrayList<WeakReference<WebClient>>(); /** * JavaScript "debugger" that provides you information about the JavaScript call stack * and the current values of the local variables in those stack frame. * * <p> * Unlike Java debugger, which you as a human interfaces directly and interactively, * this JavaScript debugger is to be interfaced by your program (or through the * expression evaluation capability of your Java debugger.) */ protected JavaScriptDebugger jsDebugger = new JavaScriptDebugger(); protected HudsonTestCase(String name) { super(name); } protected HudsonTestCase() { } protected void setUp() throws Exception { env.pin(); recipe(); hudson = newHudson(); hudson.servletContext.setAttribute("app",hudson); hudson.servletContext.setAttribute("version","?"); // cause all the descriptors to reload. // ideally we'd like to reset them to properly emulate the behavior, but that's not possible. Mailer.DESCRIPTOR.setHudsonUrl(null); for( Descriptor d : Descriptor.ALL ) d.load(); } protected void tearDown() throws Exception { // cancel pending asynchronous operations, although this doesn't really seem to be working for (WeakReference<WebClient> client : clients) { WebClient c = client.get(); if(c==null) continue; // unload the page to cancel asynchronous operations c.getPage("about:blank"); } clients.clear(); server.stop(); for (LenientRunnable r : tearDowns) r.run(); hudson.cleanUp(); env.dispose(); } protected void runTest() throws Throwable { new JavaScriptEngine(null); // ensure that ContextFactory is initialized Context cx= ContextFactory.getGlobal().enterContext(); try { cx.setOptimizationLevel(-1); cx.setDebugger(jsDebugger,null); super.runTest(); } finally { Context.exit(); } } /** * Creates a new instance of {@link Hudson}. If the derived class wants to create it in a different way, * you can override it. */ protected Hudson newHudson() throws Exception { return new Hudson(homeLoader.allocate(), createWebServer()); } /** * Prepares a webapp hosting environment to get {@link ServletContext} implementation * that we need for testing. */ protected ServletContext createWebServer() throws Exception { server = new Server(); WebAppContext context = new WebAppContext(WarExploder.EXPLODE_DIR.getPath(), contextPath); context.setClassLoader(getClass().getClassLoader()); context.setConfigurations(new Configuration[]{new WebXmlConfiguration(),new NoListenerConfiguration()}); server.setHandler(context); SocketConnector connector = new SocketConnector(); server.addConnector(connector); server.addUserRealm(configureUserRealm()); server.start(); localPort = connector.getLocalPort(); return context.getServletContext(); } /** * Configures a security realm for a test. */ protected UserRealm configureUserRealm() { HashUserRealm realm = new HashUserRealm(); realm.setName("default"); // this is the magic realm name to make it effective on everywhere realm.put("alice","alice"); realm.put("bob","bob"); realm.put("charlie","charlie"); realm.addUserToRole("alice","female"); realm.addUserToRole("bob","male"); realm.addUserToRole("charlie","male"); return realm; } // Convenience methods protected FreeStyleProject createFreeStyleProject() throws IOException { return createFreeStyleProject("test"); } protected FreeStyleProject createFreeStyleProject(String name) throws IOException { return (FreeStyleProject)hudson.createProject(FreeStyleProject.DESCRIPTOR,name); } /** * Returns the last item in the list. */ protected <T> T last(List<T> items) { return items.get(items.size()-1); } // recipe methods. Control the test environments. /** * Called during the {@link #setUp()} to give a test case an opportunity to * control the test environment in which Hudson is run. * * <p> * From here, call a series of {@code withXXX} methods. */ protected void recipe() throws Exception { // look for recipe meta-annotation Method runMethod= getClass().getMethod(getName()); for( final Annotation a : runMethod.getAnnotations() ) { Recipe r = a.annotationType().getAnnotation(Recipe.class); if(r==null) continue; final Runner runner = r.value().newInstance(); tearDowns.add(new LenientRunnable() { public void run() throws Exception { runner.tearDown(HudsonTestCase.this,a); } }); runner.setup(this,a); } } public HudsonTestCase withNewHome() { return with(HudsonHomeLoader.NEW); } public HudsonTestCase withExistingHome(File source) { return with(new CopyExisting(source)); } public HudsonTestCase withPresetData(String name) { name = "/" + name + ".zip"; URL res = getClass().getResource(name); if(res==null) throw new IllegalArgumentException("No such data set found: "+name); return with(new CopyExisting(res)); } public HudsonTestCase with(HudsonHomeLoader homeLoader) { this.homeLoader = homeLoader; return this; } /** * Extends {@link com.gargoylesoftware.htmlunit.WebClient} and provide convenience methods * for accessing Hudson. */ public class WebClient extends com.gargoylesoftware.htmlunit.WebClient { public WebClient() { // setJavaScriptEnabled(false); setPageCreator(HudsonPageCreator.INSTANCE); clients.add(new WeakReference<WebClient>(this)); // make ajax calls synchronous for predictable behaviors that simplify debugging setAjaxController(new AjaxController() { public boolean processSynchron(HtmlPage page, WebRequestSettings settings, boolean async) { return true; } }); } /** * Logs in to Hudson. */ public WebClient login(String username, String password) throws Exception { HtmlPage page = goTo("login"); // page = (HtmlPage) page.getFirstAnchorByText("Login").click(); HtmlForm form = page.getFormByName("login"); form.getInputByName("j_username").setValueAttribute(username); form.getInputByName("j_password").setValueAttribute(password); form.submit(null); return this; } /** * Logs in to Hudson, by using the user name as the password. * * <p> * See {@link HudsonTestCase#configureUserRealm()} for how the container is set up with the user names * and passwords. All the test accounts have the same user name and password. */ public WebClient login(String username) throws Exception { login(username,username); return this; } public HtmlPage getPage(Item item) throws IOException, SAXException { return getPage(item,""); } public HtmlPage getPage(Item item, String relative) throws IOException, SAXException { return goTo(item.getUrl()+relative); } /** * @deprecated * This method expects a full URL. This method is marked as deprecated to warn you * that you probably should be using {@link #goTo(String)} method, which accepts * a relative path within the Hudson being tested. (IOW, if you really need to hit * a website on the internet, there's nothing wrong with using this method.) */ public Page getPage(String url) throws IOException, FailingHttpStatusCodeException { return super.getPage(url); } /** * Requests a page within Hudson. * * @param relative * Relative path within Hudson. Starts without '/'. * For example, "job/test/" to go to a job top page. */ public HtmlPage goTo(String relative) throws IOException, SAXException { return (HtmlPage)goTo(relative, "text/html"); } public Page goTo(String relative, String expectedContentType) throws IOException, SAXException { return super.getPage("http://localhost:"+localPort+contextPath+relative); } } static { // screen scraping relies on locale being fixed. Locale.setDefault(Locale.ENGLISH); // don't waste bandwidth talking to the update center UpdateCenter.neverUpdate = true; // we don't care CSS errors in YUI final ErrorHandler defaultHandler = Stylesheet.CSS_ERROR_HANDLER; Stylesheet.CSS_ERROR_HANDLER = new ErrorHandler() { public void warning(CSSParseException exception) throws CSSException { if(!ignore(exception)) defaultHandler.warning(exception); } public void error(CSSParseException exception) throws CSSException { if(!ignore(exception)) defaultHandler.error(exception); } public void fatalError(CSSParseException exception) throws CSSException { if(!ignore(exception)) defaultHandler.fatalError(exception); } private boolean ignore(CSSParseException e) { return e.getURI().contains("/yui/"); } }; // suppress INFO output from Spring, which is verbose Logger.getLogger("org.springframework").setLevel(Level.WARNING); } private static final Logger LOGGER = Logger.getLogger(HudsonTestCase.class.getName()); }
package com.ecyrd.jspwiki.plugin; import com.ecyrd.jspwiki.*; import junit.framework.*; import java.util.*; public class UndefinedPagesPluginTest extends TestCase { Properties props = new Properties(); TestEngine engine; WikiContext context; PluginManager manager; public UndefinedPagesPluginTest( String s ) { super( s ); } public void setUp() throws Exception { props.load( TestEngine.findTestProperties() ); engine = new TestEngine(props); engine.saveText( "TestPage", "Reference to [Foobar]." ); engine.saveText( "Foobar", "Reference to [Foobar 2], [Foobars]" ); context = new WikiContext( engine, new WikiPage(engine, "TestPage") ); manager = new PluginManager( engine, props ); } public void tearDown() { TestEngine.deleteTestPage( "TestPage" ); TestEngine.deleteTestPage( "Foobar" ); TestEngine.emptyWorkDir(); } private String wikitize( String s ) { return engine.textToHTML( context, s ); } /** * Tests that only correct undefined links are found. * We also check against plural forms here, which should not * be listed as non-existant. */ public void testSimpleUndefined() throws Exception { WikiContext context2 = new WikiContext( engine, new WikiPage(engine, "Foobar") ); String res = manager.execute( context2, "{INSERT com.ecyrd.jspwiki.plugin.UndefinedPagesPlugin"); String exp = "[Foobar 2]\\\\"; assertEquals( wikitize(exp), res ); } public static Test suite() { return new TestSuite( UndefinedPagesPluginTest.class ); } }
package com.github.nsnjson; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.node.*; import org.junit.*; import static com.github.nsnjson.format.Format.*; public class DriverTest extends AbstractFormatTest { @Test public void processTestNull() { shouldBeConsistencyWhenGivenNull(getNull(), getNullPresentation()); } @Test public void processTestNumberInt() { NumericNode value = getNumberInt(); shouldBeConsistencyWhenGivenNumber(value, getNumberIntPresentation(value)); } @Test public void testNumberLong() { NumericNode value = getNumberLong(); shouldBeConsistencyWhenGivenNumber(value, getNumberLongPresentation(value)); } @Test public void testNumberDouble() { NumericNode value = getNumberDouble(); shouldBeConsistencyWhenGivenNumber(value, getNumberDoublePresentation(value)); } @Test public void testEmptyString() { TextNode value = getEmptyString(); shouldBeConsistencyWhenGivenString(value, getStringPresentation(value)); } @Test public void testString() { TextNode value = getString(); shouldBeConsistencyWhenGivenString(value, getStringPresentation(value)); } @Test public void testBooleanTrue() { BooleanNode value = getBooleanTrue(); shouldBeConsistencyWhenGivenBoolean(value, getBooleanPresentation(value)); } @Test public void testBooleanFalse() { BooleanNode value = getBooleanFalse(); shouldBeConsistencyWhenGivenBoolean(value, getBooleanPresentation(value)); } @Test public void testEmptyArray() { shouldBeConsistencyWhenGivenArrayIsEmpty(getEmptyArray(), getEmptyArrayPresentation()); } @Test public void shouldBeConsistencyWhenGivenArray() { ObjectMapper objectMapper = new ObjectMapper(); JsonNode numberInt = getNumberInt(); JsonNode numberLong = getNumberLong(); JsonNode numberDouble = getNumberDouble(); JsonNode string = getString(); JsonNode booleanTrue = getBooleanTrue(); JsonNode booleanFalse = getBooleanFalse(); ArrayNode array = objectMapper.createArrayNode(); array.add(getNull()); array.add(numberInt); array.add(numberLong); array.add(numberDouble); array.add(string); array.add(booleanTrue); array.add(booleanFalse); ObjectNode presentationOfNull = objectMapper.createObjectNode(); presentationOfNull.put(FIELD_TYPE, TYPE_MARKER_NULL); ObjectNode presentationOfNumberInt = objectMapper.createObjectNode(); presentationOfNumberInt.put(FIELD_TYPE, TYPE_MARKER_NUMBER); presentationOfNumberInt.put(FIELD_VALUE, numberInt.asInt()); ObjectNode presentationOfNumberLong = objectMapper.createObjectNode(); presentationOfNumberLong.put(FIELD_TYPE, TYPE_MARKER_NUMBER); presentationOfNumberLong.put(FIELD_VALUE, numberLong.asLong()); ObjectNode presentationOfNumberDouble = objectMapper.createObjectNode(); presentationOfNumberDouble.put(FIELD_TYPE, TYPE_MARKER_NUMBER); presentationOfNumberDouble.put(FIELD_VALUE, numberDouble.asDouble()); ObjectNode presentationOfString = objectMapper.createObjectNode(); presentationOfString.put(FIELD_TYPE, TYPE_MARKER_STRING); presentationOfString.put(FIELD_VALUE, string.asText()); ObjectNode presentationOfBooleanTrue = objectMapper.createObjectNode(); presentationOfBooleanTrue.put(FIELD_TYPE, TYPE_MARKER_BOOLEAN); presentationOfBooleanTrue.put(FIELD_VALUE, BOOLEAN_TRUE); ObjectNode presentationOfBooleanFalse = objectMapper.createObjectNode(); presentationOfBooleanFalse.put(FIELD_TYPE, TYPE_MARKER_BOOLEAN); presentationOfBooleanFalse.put(FIELD_VALUE, BOOLEAN_FALSE); ArrayNode presentationOfArrayItems = objectMapper.createArrayNode(); presentationOfArrayItems.add(presentationOfNull); presentationOfArrayItems.add(presentationOfNumberInt); presentationOfArrayItems.add(presentationOfNumberLong); presentationOfArrayItems.add(presentationOfNumberDouble); presentationOfArrayItems.add(presentationOfString); presentationOfArrayItems.add(presentationOfBooleanTrue); presentationOfArrayItems.add(presentationOfBooleanFalse); ObjectNode presentation = objectMapper.createObjectNode(); presentation.put(FIELD_TYPE, TYPE_MARKER_ARRAY); presentation.set(FIELD_VALUE, presentationOfArrayItems); assertConsistency(array, presentation); } @Test public void testEmptyObject() { shouldBeConsistencyWhenGivenObjectIsEmpty(getEmptyObject(), getEmptyObjectPresentation()); } @Test public void shouldBeConsistencyWhenGivenObject() { ObjectMapper objectMapper = new ObjectMapper(); String nullField = "null_field"; String numberIntField = "int_field"; String numberLongField = "long_field"; String numberDoubleField = "double_field"; String stringField = "string_field"; String booleanTrueField = "true_field"; String booleanFalseField = "false_field"; JsonNode numberInt = getNumberInt(); JsonNode numberLong = getNumberLong(); JsonNode numberDouble = getNumberDouble(); JsonNode string = getString(); JsonNode booleanTrue = getBooleanTrue(); JsonNode booleanFalse = getBooleanFalse(); ObjectNode object = objectMapper.createObjectNode(); object.set(nullField, getNull()); object.set(numberIntField, numberInt); object.set(numberLongField, numberLong); object.set(numberDoubleField, numberDouble); object.set(stringField, string); object.set(booleanTrueField, booleanTrue); object.set(booleanFalseField, booleanFalse); ObjectNode presentationOfNullField = objectMapper.createObjectNode(); presentationOfNullField.put(FIELD_NAME, nullField); presentationOfNullField.put(FIELD_TYPE, TYPE_MARKER_NULL); ObjectNode presentationOfNumberIntField = objectMapper.createObjectNode(); presentationOfNumberIntField.put(FIELD_NAME, numberIntField); presentationOfNumberIntField.put(FIELD_TYPE, TYPE_MARKER_NUMBER); presentationOfNumberIntField.put(FIELD_VALUE, numberInt.asInt()); ObjectNode presentationOfNumberLongField = objectMapper.createObjectNode(); presentationOfNumberLongField.put(FIELD_NAME, numberLongField); presentationOfNumberLongField.put(FIELD_TYPE, TYPE_MARKER_NUMBER); presentationOfNumberLongField.put(FIELD_VALUE, numberLong.asLong()); ObjectNode presentationOfNumberDoubleField = objectMapper.createObjectNode(); presentationOfNumberDoubleField.put(FIELD_NAME, numberDoubleField); presentationOfNumberDoubleField.put(FIELD_TYPE, TYPE_MARKER_NUMBER); presentationOfNumberDoubleField.put(FIELD_VALUE, numberDouble.asDouble()); ObjectNode presentationOfStringField = objectMapper.createObjectNode(); presentationOfStringField.put(FIELD_NAME, stringField); presentationOfStringField.put(FIELD_TYPE, TYPE_MARKER_STRING); presentationOfStringField.put(FIELD_VALUE, string.asText()); ObjectNode presentationOfBooleanTrueField = objectMapper.createObjectNode(); presentationOfBooleanTrueField.put(FIELD_NAME, booleanTrueField); presentationOfBooleanTrueField.put(FIELD_TYPE, TYPE_MARKER_BOOLEAN); presentationOfBooleanTrueField.put(FIELD_VALUE, BOOLEAN_TRUE); ObjectNode presentationOfBooleanFalseField = objectMapper.createObjectNode(); presentationOfBooleanFalseField.put(FIELD_NAME, booleanFalseField); presentationOfBooleanFalseField.put(FIELD_TYPE, TYPE_MARKER_BOOLEAN); presentationOfBooleanFalseField.put(FIELD_VALUE, BOOLEAN_FALSE); ArrayNode presentationOfArrayItems = objectMapper.createArrayNode(); presentationOfArrayItems.add(presentationOfNullField); presentationOfArrayItems.add(presentationOfNumberIntField); presentationOfArrayItems.add(presentationOfNumberLongField); presentationOfArrayItems.add(presentationOfNumberDoubleField); presentationOfArrayItems.add(presentationOfStringField); presentationOfArrayItems.add(presentationOfBooleanTrueField); presentationOfArrayItems.add(presentationOfBooleanFalseField); ObjectNode presentation = objectMapper.createObjectNode(); presentation.put(FIELD_TYPE, TYPE_MARKER_OBJECT); presentation.set(FIELD_VALUE, presentationOfArrayItems); assertConsistency(object, presentation); } private void shouldBeConsistencyWhenGivenNull(NullNode value, ObjectNode presentation) { assertConsistency(value, presentation); } private void shouldBeConsistencyWhenGivenNumber(NumericNode value, ObjectNode presentation) { assertConsistency(value, presentation); } private void shouldBeConsistencyWhenGivenString(TextNode value, ObjectNode presentation) { assertConsistency(value, presentation); } private void shouldBeConsistencyWhenGivenBoolean(BooleanNode value, ObjectNode presentation) { assertConsistency(value, presentation); } private void shouldBeConsistencyWhenGivenArrayIsEmpty(ArrayNode array, ObjectNode presentation) { assertConsistency(array, presentation); } private void shouldBeConsistencyWhenGivenObjectIsEmpty(ObjectNode object, ObjectNode presentation) { assertConsistency(object, presentation); } private static void assertConsistency(JsonNode value, ObjectNode presentation) { Assert.assertEquals(value, Driver.decode(Driver.encode(value))); Assert.assertEquals(presentation, Driver.encode(Driver.decode(presentation))); } }
package innovimax.mixthem; import innovimax.mixthem.arguments.Mode; import innovimax.mixthem.arguments.ParamValue; import innovimax.mixthem.arguments.Rule; import innovimax.mixthem.arguments.RuleParam; import innovimax.mixthem.io.InputResource; import java.io.*; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.logging.Level; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.theories.*; import org.junit.runner.RunWith; public class GenericTest { @Test public final void testCharRules() throws MixException, FileNotFoundException, IOException, NumberFormatException { testRules(Mode.CHAR); } @Test public final void testBytesRules() throws MixException, FileNotFoundException, IOException, NumberFormatException { testRules(Mode.BYTE); } private final void testRules(final Mode mode) throws MixException, FileNotFoundException, IOException, NumberFormatException { MixThem.setLogging(Level.FINE); int testId = 1; List<String> failed = new ArrayList<String>(); boolean result = true; while (true) { MixThem.LOGGER.info("TEST [" + mode.getName().toUpperCase() + "] N° " + testId + "***********************************************************"); String prefix = "test" + String.format("%03d", testId) +"_"; URL url1 = getClass().getResource(prefix + "file1.txt"); URL url2 = getClass().getResource(prefix + "file2.txt"); if( url1 == null || url2 == null) break; MixThem.LOGGER.info("File 1 : " + url1); MixThem.LOGGER.info("File 2 : " + url2); for(Rule rule : Rule.values()) { if (rule.isImplemented() && rule.acceptMode(mode)) { String paramsFile = prefix + "params-" + rule.getExtension() + ".txt"; URL urlP = getClass().getResource(paramsFile); List<RuleRun> runs = RuleRuns.getRuns(rule, urlP); for (RuleRun run : runs) { String resultFile = prefix + "output-" + rule.getExtension(); if (run.hasSuffix()) { resultFile += "-" + run.getSuffix(); } resultFile += ".txt"; URL urlR = getClass().getResource(resultFile); if (urlR != null) { MixThem.LOGGER.info(" if (urlP != null) { MixThem.LOGGER.info("Params file : " + urlP); } MixThem.LOGGER.info("Result file : " + urlR); MixThem.LOGGER.info(" boolean res = check(new File(url1.getFile()), new File(url2.getFile()), new File(urlR.getFile()), mode, rule, run.getParams()); MixThem.LOGGER.info("Run " + (res ? "pass" : "FAIL") + " with params " + run.getParams().toString()); result &= res; if (!res) { failed.add(Integer.toString(testId)); } } } } } testId++; } MixThem.LOGGER.info("*********************************************************************"); MixThem.LOGGER.info("FAILED [" + mode.getName().toUpperCase() + "] TESTS : " + (failed.size() > 0 ? failed.toString() : "None")); MixThem.LOGGER.info("*********************************************************************"); Assert.assertTrue(result); } private final static boolean check(final File file1, final File file2, final File expected, final Mode mode, final Rule rule, final Map<RuleParam, ParamValue> params) throws MixException, FileNotFoundException, IOException { MixThem.LOGGER.info("Run and check result..."); InputResource input1 = InputResource.createFile(file1); InputResource input2 = InputResource.createFile(file2); List<InputResource> inputs = new ArrayList<InputResource>(); inputs.add(input1); inputs.add(input2); ByteArrayOutputStream baos_rule = new ByteArrayOutputStream(); MixThem mixThem = new MixThem(inputs, baos_rule); mixThem.process(mode, rule, params); MixThem.LOGGER.info("Run and print result..."); mixThem = new MixThem(inputs, System.out); mixThem.process(mode, rule, params); return checkFileEquals(expected, baos_rule.toByteArray()); } private static boolean checkFileEquals(final File fileExpected, final byte[] result) throws FileNotFoundException, IOException { FileInputStream fisExpected = new FileInputStream(fileExpected); int c; int offset = 0; while ((c = fisExpected.read()) != -1) { if (offset >= result.length) return false; int d = result[offset++]; if (c != d) return false; } if (offset > result.length) return false; return true; } }
package innovimax.mixthem; import innovimax.mixthem.arguments.Mode; import innovimax.mixthem.arguments.ParamValue; import innovimax.mixthem.arguments.Rule; import innovimax.mixthem.arguments.RuleParam; import innovimax.mixthem.io.InputResource; import java.io.*; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.logging.Level; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.theories.*; import org.junit.runner.RunWith; public class GenericTest { @Test public final void testCharRules() throws MixException, FileNotFoundException, IOException, NumberFormatException { testRules(Mode.CHAR); } @Test public final void testBytesRules() throws MixException, FileNotFoundException, IOException, NumberFormatException { testRules(Mode.BYTE); } private final void testRules(final Mode mode) throws MixException, FileNotFoundException, IOException, NumberFormatException { MixThem.setLogging(Level.FINE); int testId = 1; List<String> failed = new ArrayList<String>(); boolean result = true; while (true) { MixThem.LOGGER.info("TEST [" + mode.getName().toUpperCase() + "] N° " + testId + "***********************************************************"); final String prefix = "test" + String.format("%03d", testId) +"_"; final List<URL> urlF = new ArrayList<URL>(); int index = 1; while (true) { final URL url = getClass().getResource(prefix + "file" + index + ".txt"); if (url != null) { urlF.add(url); index++; } else { break; } } if( urlF.size() < 2) break; for (int i=0; i < urlF.size(); i++) { MixThem.LOGGER.info("File " + (i+1) + ": " + urlF.get(i)); } for(Rule rule : Rule.values()) { if (rule.isImplemented() && rule.acceptMode(mode)) { String paramsFile = prefix + "params-" + rule.getExtension() + ".txt"; URL urlP = getClass().getResource(paramsFile); List<RuleRun> runs = RuleRuns.getRuns(rule, urlP); for (RuleRun run : runs) { String resultFile = prefix + "output-" + rule.getExtension(); if (run.hasSuffix()) { resultFile += "-" + run.getSuffix(); } resultFile += ".txt"; URL urlR = getClass().getResource(resultFile); if (urlR != null) { MixThem.LOGGER.info(" if (urlP != null) { MixThem.LOGGER.info("Params file : " + urlP); } MixThem.LOGGER.info("Result file : " + urlR); MixThem.LOGGER.info(" boolean res = check(urlF, urlR, mode, rule, run.getParams()); MixThem.LOGGER.info("Run " + (res ? "pass" : "FAIL") + " with params " + run.getParams().toString()); result &= res; if (!res) { failed.add(Integer.toString(testId)); } } } } } testId++; } MixThem.LOGGER.info("*********************************************************************"); MixThem.LOGGER.info("FAILED [" + mode.getName().toUpperCase() + "] TESTS : " + (failed.size() > 0 ? failed.toString() : "None")); MixThem.LOGGER.info("*********************************************************************"); Assert.assertTrue(result); } private final static boolean check(final List<URL> filesURL, final URL resultURL, final Mode mode, final Rule rule, final Map<RuleParam, ParamValue> params) throws MixException, FileNotFoundException, IOException { MixThem.LOGGER.info("Run and check result..."); final List<InputResource> inputs = new ArrayList<InputResource>(); for (URL url : filesURL) { inputs.add(InputResource.createFile(new File(url.getFile()))); } final ByteArrayOutputStream baos_rule = new ByteArrayOutputStream(); MixThem mixThem = new MixThem(inputs, baos_rule); mixThem.process(mode, rule, params); MixThem.LOGGER.info("Run and print result..."); mixThem = new MixThem(inputs, System.out); mixThem.process(mode, rule, params); final File result = new File(resultURL.getFile()); return checkFileEquals(result, baos_rule.toByteArray()); } private static boolean checkFileEquals(final File fileExpected, final byte[] result) throws FileNotFoundException, IOException { FileInputStream fisExpected = new FileInputStream(fileExpected); int c; int offset = 0; while ((c = fisExpected.read()) != -1) { if (offset >= result.length) return false; int d = result[offset++]; if (c != d) return false; } if (offset > result.length) return false; return true; } }
package net.dean.jraw.test; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import net.dean.jraw.ApiException; import net.dean.jraw.JrawUtils; import net.dean.jraw.RedditClient; import net.dean.jraw.Version; import net.dean.jraw.http.AuthenticationMethod; import net.dean.jraw.http.Credentials; import net.dean.jraw.http.NetworkException; import net.dean.jraw.managers.AccountManager; import net.dean.jraw.managers.ModerationManager; import net.dean.jraw.models.CommentNode; import net.dean.jraw.models.JsonModel; import net.dean.jraw.models.Listing; import net.dean.jraw.models.Subreddit; import net.dean.jraw.models.meta.JsonProperty; import net.dean.jraw.paginators.Paginators; import org.testng.Assert; import org.testng.SkipException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Date; import java.util.List; /** * This class is the base class of all JRAW test classes. It provides dynamic User-Agents based on the name of the class * and several utility methods. */ public abstract class RedditTest { protected static final RedditClient reddit = new RedditClient( "JRAW v" + Version.get().formatted() + " test suite runner by /u/thatJavaNerd"); private static Credentials credentials; private static ObjectMapper objectMapper = new ObjectMapper(); protected final AccountManager account; protected final ModerationManager moderation; protected RedditTest() { reddit.setLoggingEnabled(true); Credentials creds = getCredentials(); if (!reddit.isLoggedIn()) { try { reddit.authenticate(reddit.getOAuthHelper().easyAuth(creds)); } catch (NetworkException | ApiException e) { handle(e); } } this.account = new AccountManager(reddit); this.moderation = new ModerationManager(reddit); } protected String getUserAgent(Class<?> clazz) { return clazz.getSimpleName() + " for JRAW v" + Version.get().formatted(); } public long epochMillis() { return new Date().getTime(); } protected void handle(Throwable t) { if (t instanceof NetworkException) { NetworkException e = (NetworkException) t; if (e.getCode() >= 500 && e.getCode() < 600) { throw new SkipException("Received " + e.getCode() + ", skipping"); } } t.printStackTrace(); Assert.fail(t.getMessage() == null ? t.getClass().getName() : t.getMessage(), t); } protected final boolean isRateLimit(ApiException e) { return e.getReason().equals("QUOTA_FILLED") || e.getReason().equals("RATELIMIT"); } protected void handlePostingQuota(ApiException e) { if (!isRateLimit(e)) { Assert.fail(e.getMessage()); } String msg = null; // toUpperCase just in case (no pun intended) String method = getCallingMethod(); switch (e.getReason().toUpperCase()) { case "QUOTA_FILLED": msg = String.format("Skipping %s(), link posting quota has been filled for this user", method); break; case "RATELIMIT": msg = String.format("Skipping %s(), reached ratelimit (%s)", method, e.getExplanation()); break; } if (msg != null) { JrawUtils.logger().error(msg); throw new SkipException(msg); } else { Assert.fail(e.getMessage()); } } protected String getCallingMethod() { StackTraceElement[] elements = Thread.currentThread().getStackTrace(); // [0] = Thread.currentThread().getStackTrace() // [1] = this method // [2] = caller of this method // [3] = Caller of the caller of this method return elements[3].getMethodName(); } protected final <T extends JsonModel> void validateModels(Iterable<T> iterable) { for (T model : iterable) { validateModel(model); } } /** * Validates all of the CommentNode's children's Comments */ protected final void validateModel(CommentNode root) { for (CommentNode node : root.walkTree()) { validateModel(node.getComment()); } } protected final <T extends JsonModel> void validateModel(T model) { Assert.assertNotNull(model); List<Method> jsonInteractionMethods = JsonModel.getJsonProperties(model.getClass()); try { for (Method method : jsonInteractionMethods) { JsonProperty jsonProperty = method.getAnnotation(JsonProperty.class); Object returnVal = null; try { returnVal = method.invoke(model); } catch (InvocationTargetException e) { // InvocationTargetException thrown when the method.invoke() returns null and @JsonInteraction "nullable" // property is false if (e.getCause().getClass().equals(NullPointerException.class) && !jsonProperty.nullable()) { Assert.fail("Non-nullable JsonInteraction method returned null: " + model.getClass().getName() + "." + method.getName() + "()"); } else { // Other reason for InvocationTargetException Throwable cause = e.getCause(); cause.printStackTrace(); Assert.fail(cause.getClass().getName() + ": " + cause.getMessage()); } } if (returnVal != null && returnVal instanceof JsonModel) { validateModel((JsonModel) returnVal); } } } catch (IllegalAccessException e) { handle(e); } } /** * Gets a Credentials object that represents the properties found in credentials.json * (located at /src/test/resources). The Credential's AuthenticationMethod will always be * {@link AuthenticationMethod#SCRIPT} * * @return A Credentials object parsed form credentials.json */ protected final Credentials getCredentials() { if (credentials != null) { return credentials; } try { // If running locally, use credentials file // If running with Travis-CI, use env variables if (System.getenv("TRAVIS") != null && Boolean.parseBoolean(System.getenv("TRAVIS"))) { credentials = Credentials.script(System.getenv("USERNAME"), System.getenv("PASS"), System.getenv("CLIENT_ID"), System.getenv("CLIENT_SECRET")); return credentials; } else { InputStream in = RedditTest.class.getResourceAsStream("/credentials.json"); if (in == null) { throw new SetupRequiredException("credentials.json could not be found. See " + "https://github.com/thatJavaNerd/JRAW#contributing for more information."); } JsonNode data = objectMapper.readTree(in); credentials = Credentials.script(data.get("username").asText(), data.get("password").asText(), data.get("client_id").asText(), data.get("client_secret").asText()); return credentials; } } catch (Exception e) { handle(e); return null; } } /** * Gets a subreddit that the testing user moderates * @return A subreddit */ protected final Subreddit getModeratedSubreddit() { Listing<Subreddit> moderatorOf = Paginators.mySubreddits(reddit, "moderator").next(); if (moderatorOf.size() == 0) { throw new IllegalStateException("Must be a moderator of at least one subreddit"); } return moderatorOf.get(0); } }
package net.sf.gaboto.test; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.FileInputStream; import net.sf.gaboto.Gaboto; import net.sf.gaboto.GabotoFactory; import org.junit.Test; /** * @author timp * @since 23 Sep 2009 * */ public class TestGaboto { /** * Test method for {@link net.sf.gaboto.Gaboto#read(java.io.InputStream)}. */ @Test public void testReadInputStream() throws Exception { Gaboto g = GabotoFactory.getEmptyInMemoryGaboto(); assertEquals(0, g.getJenaModelViewOnNamedGraphSet().size()); File graphs = new File(Utils.rooted("src/test/data/test1"), Gaboto.GRAPH_FILE_NAME); FileInputStream graphsFileInputStream; graphsFileInputStream = new FileInputStream(graphs); g.read(graphsFileInputStream); g.persistToDisk(Utils.rooted("src/test/data/test1")); assertEquals(21,g.getJenaModelViewOnNamedGraphSet().size()); } @Test public void testPersistEmpty() throws Exception { Gaboto g = GabotoFactory.getEmptyInMemoryGaboto(); g.persistToDisk(Utils.rooted("src/test/data/empty")); } /** * Test method for {@link net.sf.gaboto.Gaboto#read(java.lang.String)}. */ @Test public void testReadString() throws Exception { Gaboto g = GabotoFactory.getGaboto(Utils.rooted("src/test/data/empty")); assertEquals(0, g.getJenaModelViewOnNamedGraphSet().size()); File graphs = new File(Utils.rooted("src/test/data/test1"), "graphs.rdf"); FileInputStream graphsFileInputStream; graphsFileInputStream = new FileInputStream(graphs); StringBuffer contents = new StringBuffer(); int c = 0; while ( c != -1){ c = graphsFileInputStream.read(); contents.append((char)c); } g.read(contents.toString()); g.persistToDisk(Utils.rooted("src/test/data/test1")); assertEquals(21,g.getJenaModelViewOnNamedGraphSet().size()); } /** * Test method for {@link net.sf.gaboto.Gaboto#read(java.io.InputStream, java.lang.String, java.io.InputStream, java.lang.String)}. */ @Test public void testReadInputStreamStringInputStreamString() throws Exception { Gaboto g = GabotoFactory.getEmptyInMemoryGaboto(); assertEquals(0,g.getJenaModelViewOnNamedGraphSet().size()); File graphs = new File(Utils.rooted("src/test/data/test1"), Gaboto.GRAPH_FILE_NAME); FileInputStream graphsFileInputStream; graphsFileInputStream = new FileInputStream(graphs); g.read(graphsFileInputStream); assertEquals(21,g.getJenaModelViewOnNamedGraphSet().size()); } }
package org.almibe.codearea.demo; import javafx.application.Application; import javafx.scene.Scene; import javafx.stage.Stage; import org.almibe.codearea.AceCodeArea; import org.almibe.codearea.CodeArea; public class Demo extends Application { @Override public void start(Stage primaryStage) throws Exception { CodeArea codeArea = new AceCodeArea(); Scene scene = new Scene(codeArea.getWidget()); primaryStage.setScene(scene); codeArea.init(); primaryStage.show(); } public static void main(String[] args) { Demo.launch(); } }
package org.dita.dost; import com.google.common.collect.ImmutableMap; import org.junit.Test; import java.nio.file.Paths; import static java.util.Collections.emptyMap; public class IntegrationTest extends AbstractIntegrationTest { @Test public void test03() throws Throwable { test("03", Transtype.XHTML, Paths.get("03.ditamap"), emptyMap()); } @Test public void test1_5_2_M4_BUG3052904() throws Throwable { test("1.5.2_M4_BUG3052904", Transtype.XHTML, Paths.get("keyref-test-01.ditamap"), emptyMap()); } @Test public void test1_5_2_M4_BUG3052913() throws Throwable { test("1.5.2_M4_BUG3052913", Transtype.XHTML, Paths.get("keyref-test-01.ditamap"), emptyMap()); } @Test public void test1_5_2_M4_BUG3056939() throws Throwable { test("1.5.2_M4_BUG3056939", Transtype.XHTML, Paths.get("test-conref-xref-keyref-bug.ditamap"), emptyMap()); } @Test public void test1_5_2_M5_BUG3059256() throws Throwable { test("1.5.2_M5_BUG3059256", Transtype.XHTML, Paths.get("test.ditamap"), emptyMap()); } @Test public void test1_5_3_M2_BUG3157890() throws Throwable { test("1.5.3_M2_BUG3157890", Transtype.XHTML, Paths.get("test.ditamap"), emptyMap()); } @Test public void test1_5_3_M2_BUG3164866() throws Throwable { test("1.5.3_M2_BUG3164866", Transtype.XHTML, Paths.get("testpng.ditamap"), ImmutableMap.<String, Object>builder() .put("onlytopic.in.map", "true") .build()); } @Test public void test1_5_3_M3_BUG3178361() throws Throwable { test("1.5.3_M3_BUG3178361", Transtype.XHTML, Paths.get("test.ditamap"), emptyMap()); } @Test public void test1_5_3_M3_BUG3191701() throws Throwable { test("1.5.3_M3_BUG3191701", Transtype.XHTML, Paths.get("test.ditamap"), emptyMap()); } @Test public void test1_5_3_M3_BUG3191704() throws Throwable { test("1.5.3_M3_BUG3191704", Transtype.XHTML, Paths.get("test.ditamap"), emptyMap()); } @Test public void test22_TC1() throws Throwable { test("22_TC1", Transtype.PREPROCESS, Paths.get("TC1.ditamap"), emptyMap(), 3, 0); } @Test public void test22_TC2() throws Throwable { test("22_TC2", Transtype.PREPROCESS, Paths.get("TC2.ditamap"), emptyMap(), 2, 0); } @Test public void test22_TC3() throws Throwable { test("22_TC3", Transtype.PREPROCESS, Paths.get("TC3.ditamap"), emptyMap(), 3, 0); } @Test public void test22_TC4() throws Throwable { test("22_TC4", Transtype.PREPROCESS, Paths.get("TC4.ditamap"), emptyMap()); } @Test public void test22_TC6() throws Throwable { test("22_TC6", Transtype.PREPROCESS, Paths.get("TC6.ditamap"), emptyMap(), 4, 0); } @Test public void test2374525() throws Throwable { test("2374525", Transtype.PREPROCESS, Paths.get("test.dita"), emptyMap()); } @Test public void test3178361() throws Throwable { test("3178361", Transtype.PREPROCESS, Paths.get("conref-push-test.ditamap"), ImmutableMap.<String, Object>builder() .put("dita.ext", ".dita") .build()); } @Test public void test3189883() throws Throwable { test("3189883", Transtype.PREPROCESS, Paths.get("main.ditamap"), ImmutableMap.<String, Object>builder() .put("validate", "false") .build(), 1, 0); } @Test public void test3191704() throws Throwable { test("3191704", Transtype.PREPROCESS, Paths.get("jandrew-test.ditamap"), ImmutableMap.<String, Object>builder() .put("dita.ext", ".dita") .build()); } @Test public void test3344142() throws Throwable { test("3344142", Transtype.PREPROCESS, Paths.get("push.ditamap"), ImmutableMap.<String, Object>builder() .put("dita.ext", ".dita") .build(), 2, 0); } @Test public void test3470331() throws Throwable { test("3470331", Transtype.PREPROCESS, Paths.get("bookmap.ditamap"), emptyMap()); } @Test public void testMetadataInheritance() throws Throwable { test("MetadataInheritance"); } @Test public void testSF1333481() throws Throwable { test("SF1333481", Transtype.PREPROCESS, Paths.get("main.ditamap"), emptyMap()); } @Test public void testBookmap1() throws Throwable { test("bookmap1", Transtype.XHTML, Paths.get("bookmap(2)_testdata1.ditamap"), emptyMap(), 0, 0); } @Test public void testBookmap2() throws Throwable { test("bookmap2", Transtype.XHTML, Paths.get("bookmap(2)_testdata2.ditamap"), emptyMap(), 0, 1); } @Test public void testBookmap3() throws Throwable { test("bookmap3", Transtype.XHTML, Paths.get("bookmap(2)_testdata3.ditamap"), emptyMap(), 0, 0); } @Test public void testBookmap4() throws Throwable { test("bookmap4", Transtype.XHTML, Paths.get("bookmap(2)_testdata4.ditamap"), emptyMap(), 0, 1); } @Test public void testBookmap5() throws Throwable { test("bookmap5", Transtype.XHTML, Paths.get("bookmap(2)_testdata5.ditamap"), emptyMap(), 0, 0); } @Test public void testBookmap6() throws Throwable { test("bookmap6", Transtype.XHTML, Paths.get("bookmap(2)_testdata6.ditamap"), emptyMap(), 0, 1); } @Test public void testBookmap7() throws Throwable { test("bookmap7", Transtype.XHTML, Paths.get("bookmap(2)_testdata7.ditamap"), emptyMap(), 0, 0); } @Test public void testcoderef_source() throws Throwable { test("coderef_source", Transtype.PREPROCESS, Paths.get("mp.ditamap"), ImmutableMap.<String, Object>builder() .put("transtype", "preprocess").put("dita.ext", ".dita").put("validate", "false") .build(), 1, 0); } @Test public void testconref() throws Throwable { test("conref", Transtype.PREPROCESS, Paths.get("lang-common1.dita"), ImmutableMap.<String, Object>builder() .put("validate", "false") .build(), 1, 0); } @Test public void testpushAfter_between_Specialization() throws Throwable { test("pushAfter_between_Specialization", Transtype.PREPROCESS, Paths.get("pushAfter.ditamap"), ImmutableMap.<String, Object>builder() // .put("validate", "false") .build(), 0, 0); } @Test public void testpushAfter_with_crossRef() throws Throwable { test("pushAfter_with_crossRef", Transtype.PREPROCESS, Paths.get("pushAfter.ditamap"), ImmutableMap.<String, Object>builder() // .put("validate", "false") .build(), 0, 0); } @Test public void testpushAfter_with_InvalidTarget() throws Throwable { test("pushAfter_with_InvalidTarget", Transtype.PREPROCESS, Paths.get("pushAfter.ditamap"), ImmutableMap.<String, Object>builder() // .put("validate", "false") .build(), 1, 0); } @Test public void testpushAfter_without_conref() throws Throwable { test("pushAfter_without_conref", Transtype.PREPROCESS, Paths.get("pushAfter.ditamap"), ImmutableMap.<String, Object>builder() // .put("validate", "false") .build(), 0, 0); } @Test public void testsimple_pushAfter() throws Throwable { test("simple_pushAfter", Transtype.PREPROCESS, Paths.get("pushAfter.ditamap"), ImmutableMap.<String, Object>builder() // .put("validate", "false") .build(), 0, 0); } @Test public void testpushBefore_between_Specialization() throws Throwable { test("pushBefore_between_Specialization", Transtype.PREPROCESS, Paths.get("pushBefore.ditamap"), ImmutableMap.<String, Object>builder() // .put("validate", "false") .build(), 0, 0); } @Test public void testpushBefore_with_crossRef() throws Throwable { test("pushBefore_with_crossRef", Transtype.PREPROCESS, Paths.get("pushBefore.ditamap"), ImmutableMap.<String, Object>builder() // .put("validate", "false") .build(), 1, 0); } @Test public void testpushBefore_with_InvalidTarget() throws Throwable { test("pushBefore_with_InvalidTarget", Transtype.PREPROCESS, Paths.get("pushBefore.ditamap"), ImmutableMap.<String, Object>builder() // .put("validate", "false") .build(), 1, 0); } @Test public void testpushBefore_without_conref() throws Throwable { test("pushBefore_without_conref", Transtype.PREPROCESS, Paths.get("pushBefore.ditamap"), ImmutableMap.<String, Object>builder() // .put("validate", "false") .build(), 0, 0); } @Test public void testsimple_pushBefore() throws Throwable { test("simple_pushBefore", Transtype.PREPROCESS, Paths.get("pushBefore.ditamap"), ImmutableMap.<String, Object>builder() // .put("validate", "false") .build(), 0, 0); } @Test public void testpushReplace_between_Specialization() throws Throwable { test("pushReplace_between_Specialization", Transtype.PREPROCESS, Paths.get("pushReplace.ditamap"), ImmutableMap.<String, Object>builder() // .put("validate", "false") .build(), 0, 0); } @Test public void testpushReplace_with_crossRef() throws Throwable { test("pushReplace_with_crossRef", Transtype.PREPROCESS, Paths.get("pushReplace.ditamap"), ImmutableMap.<String, Object>builder() // .put("validate", "false") .build(), 0, 0); } @Test public void testpushReplace_with_InvalidTarget() throws Throwable { test("pushReplace_with_InvalidTarget", Transtype.PREPROCESS, Paths.get("pushReplace.ditamap"), ImmutableMap.<String, Object>builder() // .put("validate", "false") .build(), 1, 4); } @Test public void testpushReplace_without_conref() throws Throwable { test("pushReplace_without_conref", Transtype.PREPROCESS, Paths.get("pushReplace.ditamap"), ImmutableMap.<String, Object>builder() // .put("validate", "false") .build(), 0, 0); } @Test public void testsimple_pushReplace() throws Throwable { test("simple_pushReplace", Transtype.PREPROCESS, Paths.get("pushReplace.ditamap"), ImmutableMap.<String, Object>builder() // .put("validate", "false") .build(), 0, 0); } @Test public void testconrefbreaksxref() throws Throwable { test("conrefbreaksxref", Transtype.PREPROCESS, Paths.get("conrefbreaksxref.dita"), emptyMap()); } @Test public void testcontrol_value_file() throws Throwable { test("control_value_file"); } @Test public void testexportanchors() throws Throwable { test("exportanchors", Transtype.PREPROCESS, Paths.get("test.ditamap"), ImmutableMap.<String, Object>builder() .put("transtype", "eclipsehelp") .build()); } @Test public void testimage_scale() throws Throwable { test("image-scale", Transtype.XHTML, Paths.get("test.dita"), emptyMap()); } @Test public void testindex_see() throws Throwable { test("index-see"); } @Test public void testkeyref() throws Throwable { test("keyref", Transtype.PREPROCESS, Paths.get("test.ditamap"), emptyMap()); } @Test public void testkeyref_All_tags() throws Throwable { test("keyref_All_tags", Transtype.XHTML, Paths.get("mp_author1.ditamap"), emptyMap(), 1, 0); } @Test public void testkeyref_Keyword_links() throws Throwable { test("keyref_Keyword_links", Transtype.XHTML, Paths.get("mp_author1.ditamap"), emptyMap()); } @Test public void testkeyref_Redirect_conref() throws Throwable { test("keyref_Redirect_conref"); } @Test public void testkeyref_Redirect_link_or_xref() throws Throwable { test("keyref_Redirect_link_or_xref"); } @Test public void testkeyref_Splitting_combining_targets() throws Throwable { test("keyref_Splitting_combining_targets"); } @Test public void testkeyref_Swap_out_variable_content() throws Throwable { test("keyref_Swap_out_variable_content", Transtype.XHTML, Paths.get("mp_author1.ditamap"), emptyMap()); } @Test public void testkeyref_modify() throws Throwable { test("keyref_modify", Transtype.XHTML, Paths.get("mp_author1.ditamap"), emptyMap(), 1, 0); } @Test public void testlang() throws Throwable { test("lang", Transtype.XHTML, Paths.get("lang.ditamap"), ImmutableMap.<String, Object>builder() .put("validate", "false") .build(), 1, 0); } @Test public void testmapref() throws Throwable { test("mapref", Transtype.PREPROCESS, Paths.get("test.ditamap"), ImmutableMap.<String, Object>builder() .put("generate-debug-attributes", "false") .build()); } @Test public void testsubjectschema_case() throws Throwable { test("subjectschema_case", Transtype.XHTML, Paths.get("simplemap.ditamap"), ImmutableMap.<String, Object>builder() .put("args.filter", Paths.get("filter.ditaval")) .put("clean.temp", "no") .build()); } @Test public void testuplevels1() throws Throwable { test("uplevels1", Transtype.XHTML, Paths.get("maps/above.ditamap"), ImmutableMap.<String, Object>builder() .put("generate.copy.outer", "1") .put("outer.control", "quiet") .build()); } @Test public void testuplevels3() throws Throwable { test("uplevels3", Transtype.XHTML, Paths.get("maps/above.ditamap"), ImmutableMap.<String, Object>builder() .put("generate.copy.outer", "3") .put("outer.control", "quiet") .build()); } }
package org.web3j.quorum; import org.junit.Test; import org.web3j.protocol.ResponseTester; import org.web3j.protocol.core.methods.response.EthSendTransaction; import org.web3j.protocol.core.methods.response.VoidResponse; import org.web3j.quorum.methods.response.*; import static junit.framework.TestCase.assertTrue; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.assertThat; public class ResponseTest extends ResponseTester { @Test public void testEthSendTransaction() { buildResponse("{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\"0x0d9e7e34fd4db216a3f66981a467d9d990954e6ed3128aff4ec51a50fa175663\"}"); EthSendTransaction transaction = deserialiseResponse(EthSendTransaction.class); assertThat(transaction.getTransactionHash(), is("0x0d9e7e34fd4db216a3f66981a467d9d990954e6ed3128aff4ec51a50fa175663")); } @Test public void testNodeInfo() { buildResponse("{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"blockMakerAccount\":\"0xca843569e3427144cead5e4d5999a3d0ccf92b8e\",\"blockmakestrategy\":{\"maxblocktime\":5,\"minblocktime\":2,\"status\":\"active\",\"type\":\"deadline\"},\"canCreateBlocks\":true,\"canVote\":false,\"voteAccount\":\"0x0fbdc686b912d7722dc86510934589e0aaf3b55a\"}}"); QuorumNodeInfo quorumNodeInfo = deserialiseResponse(QuorumNodeInfo.class); assertThat(quorumNodeInfo.getNodeInfo(), equalTo( new QuorumNodeInfo.NodeInfo("0xca843569e3427144cead5e4d5999a3d0ccf92b8e", "0x0fbdc686b912d7722dc86510934589e0aaf3b55a", true, false, new QuorumNodeInfo.BlockMakeStrategy(5, 2, "active", "deadline")))); } @Test public void testCanonicalHash() { buildResponse("{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\"0x8bb911238205c6d5e9841335c9c5aff3dfae4c0f6b0df28100737c2660a15f8d\"}"); CanonicalHash canonicalHash = deserialiseResponse(CanonicalHash.class); assertThat(canonicalHash.getCanonicalHash(), is("0x8bb911238205c6d5e9841335c9c5aff3dfae4c0f6b0df28100737c2660a15f8d")); } @Test public void testVote() { buildResponse("{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\"0x582f40b7915fb069809dc9f0b2c6f03b53d386344d43b4727f83183831822913\"}"); Vote vote = deserialiseResponse(Vote.class); assertThat(vote.getTransactionHash(), is("0x582f40b7915fb069809dc9f0b2c6f03b53d386344d43b4727f83183831822913")); } @Test public void testMakeBlock() { buildResponse("{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\"0x290ae9295e3a6e35e2d43a8bf9804dfe701c7cd4009619f771735bdebb66372f\"}"); MakeBlock makeBlock = deserialiseResponse(MakeBlock.class); assertThat(makeBlock.getBlockHash(), is("0x290ae9295e3a6e35e2d43a8bf9804dfe701c7cd4009619f771735bdebb66372f")); } @Test public void testVoidResponse() { buildResponse("{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":null}"); VoidResponse voidResponse = deserialiseResponse(VoidResponse.class); assertTrue(voidResponse.isValid()); } @Test public void testBlockMaker() { buildResponse("{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":true}"); BlockMaker blockMaker = deserialiseResponse(BlockMaker.class); assertTrue(blockMaker.isBlockMaker()); } @Test public void testVoter() { buildResponse("{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":true}"); Voter voter = deserialiseResponse(Voter.class); assertTrue(voter.isVoter()); } }
package ragnardb.plugin; import gw.lang.Gosu; import gw.lang.reflect.IPropertyInfo; import gw.lang.reflect.IType; import gw.lang.reflect.ITypeLoader; import gw.lang.reflect.TypeSystem; import gw.lang.reflect.java.IJavaType; import gw.lang.reflect.java.JavaTypes; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.Assert.*; public class SQLPluginTest { @BeforeClass public static void beforeClass() { Gosu.init(); ITypeLoader sqlPlugin = new SQLPlugin(TypeSystem.getGlobalModule()); // global vs. current? TypeSystem.pushTypeLoader(TypeSystem.getGlobalModule(), sqlPlugin); } @Test public void getTypeExplicitly() { IType result = TypeSystem.getByFullNameIfValid("ragnardb.foo.Users.Contacts"); assertNotNull(result); assertEquals("ragnardb.foo.Users.Contacts", result.getName()); } @Test public void getNonExistantType() { IType result = TypeSystem.getByFullNameIfValid("ragnardb.foo.Unknown.DoesNotExist"); assertNull(result); } @Test public void oneSourceWithMultipleTypes() { IType result = TypeSystem.getByFullNameIfValid("ragnardb.foo.Vehicles.Cars"); assertNotNull(result); assertEquals("ragnardb.foo.Vehicles.Cars", result.getName()); result = TypeSystem.getByFullNameIfValid("ragnardb.foo.Vehicles.Motorcycles"); assertNotNull(result); assertEquals("ragnardb.foo.Vehicles.Motorcycles", result.getName()); } @Test public void getColumnDefs() { ISQLType result = (ISQLType) TypeSystem.getByFullNameIfValid("ragnardb.foo.Users.Contacts"); assertNotNull(result); List<ColumnDefinition> colDefs = result.getColumnDefinitions(); assertNotNull(colDefs); Set<String> expectedColumnNames = Stream.of("UserId", "LastName", "FirstName", "Age").collect(Collectors.toSet()); Set<String> actualColumnNames = colDefs.stream().map(ColumnDefinition::getColumnName).collect(Collectors.toSet()); assertEquals(expectedColumnNames, actualColumnNames); } @Test public void getTypeInfo() { ISQLType result = (ISQLType) TypeSystem.getByFullNameIfValid("ragnardb.foo.Users.Contacts"); assertNotNull(result); assertEquals("ragnardb.foo.Users.Contacts", result.getName()); assertEquals("ragnardb.foo.Users", result.getNamespace()); assertEquals("Contacts", result.getRelativeName()); SQLTypeInfo ti = (SQLTypeInfo) result.getTypeInfo(); assertEquals("Contacts", ti.getName()); //make a set of expected Name/IJavaType pairs Set<String> expectedPropertyNames = Stream.of("UserId", "LastName", "FirstName", "Age").collect(Collectors.toSet()); Map<String, IJavaType> expectedPropertyNameAndType = new HashMap<>(expectedPropertyNames.size()); expectedPropertyNameAndType.put("UserId", JavaTypes.pINT()); expectedPropertyNameAndType.put("LastName", JavaTypes.STRING()); expectedPropertyNameAndType.put("FirstName", JavaTypes.STRING()); expectedPropertyNameAndType.put("Age", JavaTypes.pINT()); //number of properties is what we expect assertEquals(expectedPropertyNameAndType.size(), ti.getProperties().size()); //each property name has a match in the map, and the type is identical for(IPropertyInfo actualProp : ti.getProperties()) { IJavaType expectedType = expectedPropertyNameAndType.get(actualProp.getName()); assertNotNull("expectedType was null, meaning the actualProp's name was not found in the map", expectedType); assertSame(expectedType, actualProp.getFeatureType()); } } }
// modification, are permitted provided that the following conditions are met: // documentation and/or other materials provided with the distribution. // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. package jodd.db; import jodd.db.type.SqlType; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.converter.ConvertWith; import org.junit.jupiter.params.converter.SimpleArgumentConverter; import org.junit.jupiter.params.provider.CsvSource; import org.mockito.Mockito; import java.math.BigDecimal; import java.sql.*; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; class DbUtilTest { @Nested @DisplayName("tests for close(Statement statement)") class CloseStatement { @Test void close_with_null_statement() { DbUtil.close((Statement) null); } @Test void close_with_thrown_exception() throws SQLException { Statement mock = Mockito.mock(Statement.class); Mockito.doThrow(SQLException.class).when(mock).close(); DbUtil.close(mock); } @Test void close_without_exception() throws SQLException { Statement mock = Mockito.mock(Statement.class); DbUtil.close(mock); } } @Nested @DisplayName("tests for close(ResultSet resultSet)") class CloseResultSet { @Test void close_with_null_resultSet() { DbUtil.close((ResultSet) null); } @Test void close_with_thrown_exception() throws SQLException { ResultSet mock = Mockito.mock(ResultSet.class); Mockito.doThrow(SQLException.class).when(mock).close(); DbUtil.close(mock); // Mock verify Mockito.verify(mock, Mockito.times(1)).close(); } @Test void close_without_exception() throws SQLException { ResultSet mock = Mockito.mock(ResultSet.class); DbUtil.close(mock); // Mock verify Mockito.verify(mock, Mockito.times(1)).close(); } } @Nested @DisplayName("tests for getFirstLong(ResultSet resultSet)") class GetFirstLong { @Test void getFirstLong_with_empty_resultset() throws SQLException { final long expected = -1L; ResultSet mock = Mockito.mock(ResultSet.class); Mockito.when(mock.next()).thenReturn(Boolean.FALSE); final long actual = DbUtil.getFirstLong(mock); // asserts assertEquals(expected, actual); // Mock verify Mockito.verify(mock, Mockito.times(1)).next(); Mockito.verify(mock, Mockito.times(0)).getLong(0); } @Test void getFirstLong_with_filled_resultset() throws SQLException { final long expected = 23L; ResultSet mock = Mockito.mock(ResultSet.class); Mockito.when(mock.next()).thenReturn(Boolean.TRUE); Mockito.when(mock.getLong(1)).thenReturn(expected); final long actual = DbUtil.getFirstLong(mock); // asserts assertEquals(expected, actual); // Mock verify Mockito.verify(mock, Mockito.times(1)).next(); Mockito.verify(mock, Mockito.times(1)).getLong(1); } } @Nested @DisplayName("tests for getFirstInt(ResultSet resultSet)") class GetFirstInt { @Test void getFirstLong_with_empty_resultset() throws SQLException { final int expected = -1; ResultSet mock = Mockito.mock(ResultSet.class); Mockito.when(mock.next()).thenReturn(Boolean.FALSE); final long actual = DbUtil.getFirstInt(mock); // asserts assertEquals(expected, actual); // Mock verify Mockito.verify(mock, Mockito.times(1)).next(); Mockito.verify(mock, Mockito.times(0)).getLong(0); } @Test void getFirstLong_with_filled_resultset() throws SQLException { final int expected = 23; ResultSet mock = Mockito.mock(ResultSet.class); Mockito.when(mock.next()).thenReturn(Boolean.TRUE); Mockito.when(mock.getInt(1)).thenReturn(expected); final long actual = DbUtil.getFirstInt(mock); // asserts assertEquals(expected, actual); // Mock verify Mockito.verify(mock, Mockito.times(1)).next(); Mockito.verify(mock, Mockito.times(1)).getInt(1); } } @Nested @DisplayName("tests for setPreparedStatementObject(PreparedStatement preparedStatement, int index, Object value, int targetSqlType)") class SetPreparedStatementObject { private PreparedStatement mock = null; private final int index = 1; @BeforeEach void before() { mock = Mockito.mock(PreparedStatement.class); } @Test void value_is_null() throws SQLException { DbUtil.setPreparedStatementObject(mock, index, null, Types.INTEGER); Mockito.verify(mock, Mockito.times(1)).setNull(index, Types.NULL); } @ParameterizedTest @CsvSource(value = {"Jodd, 12", "Jodd, -1", "Jodd, 1"}) void call_setString(String value, int targetSqlType) throws SQLException { DbUtil.setPreparedStatementObject(mock, index, value, targetSqlType); Mockito.verify(mock, Mockito.times(1)).setString(index, value); } @ParameterizedTest @CsvSource(value = {"23, 4", "23, 5", "23, -6"}) void call_setInt(Integer value, int targetSqlType) throws SQLException { DbUtil.setPreparedStatementObject(mock, index, value, targetSqlType); Mockito.verify(mock, Mockito.times(1)).setInt(index, value); } @ParameterizedTest @CsvSource(value = {"77, -5"}) void call_setLong(Long value, int targetSqlType) throws SQLException { DbUtil.setPreparedStatementObject(mock, index, value, targetSqlType); Mockito.verify(mock, Mockito.times(1)).setLong(index, value); } @ParameterizedTest @CsvSource(value = {"true, 16", "false, -7"}) void call_setBoolean(Boolean value, int targetSqlType) throws SQLException { DbUtil.setPreparedStatementObject(mock, index, value, targetSqlType); Mockito.verify(mock, Mockito.times(1)).setBoolean(index, value); } @ParameterizedTest @CsvSource(value = {"1511517069757, 91"}) void call_setDate(@ConvertWith(ToSqlDateArgumentConverter.class) Date value, int targetSqlType) throws SQLException { DbUtil.setPreparedStatementObject(mock, index, value, targetSqlType); Mockito.verify(mock, Mockito.times(1)).setDate(index, value); } @ParameterizedTest @CsvSource(value = {"33.11, 2", "111.11, 3"}) void call_setBigDecimal(@ConvertWith(ToBigDecimalArgumentConverter.class) BigDecimal value, int targetSqlType) throws SQLException { DbUtil.setPreparedStatementObject(mock, index, value, targetSqlType); Mockito.verify(mock, Mockito.times(1)).setBigDecimal(index, value); } @ParameterizedTest @CsvSource(value = {"45.66, 8"}) void call_setDouble(Double value, int targetSqlType) throws SQLException { DbUtil.setPreparedStatementObject(mock, index, value, targetSqlType); Mockito.verify(mock, Mockito.times(1)).setDouble(index, value); } @ParameterizedTest @CsvSource(value = {"45.66, 7", "88.55, 6"}) void call_setFloat(Float value, int targetSqlType) throws SQLException { DbUtil.setPreparedStatementObject(mock, index, value, targetSqlType); Mockito.verify(mock, Mockito.times(1)).setFloat(index, value); } @ParameterizedTest @CsvSource(value = {"21:44:06, 92"}) void call_setTime(@ConvertWith(ToSqlTimeArgumentConverter.class) Time value, int targetSqlType) throws SQLException { DbUtil.setPreparedStatementObject(mock, index, value, targetSqlType); Mockito.verify(mock, Mockito.times(1)).setTime(index, value); } @ParameterizedTest @CsvSource(value = {"1511517069757, 93"}) void call_setTimestamp(@ConvertWith(ToSqlTimestampArgumentConverter.class) Timestamp value, int targetSqlType) throws SQLException { DbUtil.setPreparedStatementObject(mock, index, value, targetSqlType); Mockito.verify(mock, Mockito.times(1)).setTimestamp(index, value); } @ParameterizedTest @CsvSource(value = {"65, -2", "123,-3"}) void call_setBytes(@ConvertWith(ToByteArrayArgumentConverter.class) byte[] value, int targetSqlType) throws SQLException { DbUtil.setPreparedStatementObject(mock, index, value, targetSqlType); Mockito.verify(mock, Mockito.times(1)).setBytes(index, value); } @Test void call_setObject() throws SQLException { final Object value = new Object(); final int targetSqlType = Types.BLOB; // Blob not used before DbUtil.setPreparedStatementObject(mock, index, value, targetSqlType); Mockito.verify(mock, Mockito.times(1)).setObject(index, value, targetSqlType); } @Test void call_setObject_with_DB_SQLTYPE_NOT_AVAILABLE() throws SQLException { final Object value = new Object(); final int targetSqlType = SqlType.DB_SQLTYPE_NOT_AVAILABLE; DbUtil.setPreparedStatementObject(mock, index, value, targetSqlType); Mockito.verify(mock, Mockito.times(1)).setObject(index, value); } } // all converters are simple - no special handling is available - e.g. support different input data / types static class ToSqlDateArgumentConverter extends SimpleArgumentConverter { @Override protected Object convert(Object source, Class<?> targetType) { assertEquals(java.sql.Date.class, targetType, "Can only convert to " + Date.class.getCanonicalName()); Long value = null; try { value = Long.parseLong(source.toString()); } catch (Exception e) { fail("failure while converting " + source + " into an instance of " + targetType.getCanonicalName() ); } return new Date(value); } } static class ToBigDecimalArgumentConverter extends SimpleArgumentConverter { @Override protected Object convert(Object source, Class<?> targetType) { assertEquals(BigDecimal.class, targetType, "Can only convert to " + BigDecimal.class.getCanonicalName()); try { return BigDecimal.valueOf(Double.parseDouble(source.toString())); } catch (Exception e) { fail("failure while converting " + source + " into an instance of " + targetType.getCanonicalName()); } return null; } } static class ToSqlTimeArgumentConverter extends SimpleArgumentConverter { @Override protected Object convert(Object source, Class<?> targetType) { assertEquals(Time.class, targetType, "Can only convert to " + Time.class.getCanonicalName()); try { return Time.valueOf(source.toString()); } catch (Exception e) { fail("failure while converting " + source + " into an instance of " + targetType.getCanonicalName()); } return null; } } static class ToSqlTimestampArgumentConverter extends SimpleArgumentConverter { @Override protected Object convert(Object source, Class<?> targetType) { assertEquals(Timestamp.class, targetType, "Can only convert to " + Timestamp.class.getCanonicalName()); try { return new Timestamp(Long.parseLong(source.toString())); } catch (Exception e) { fail("failure while converting " + source + " into an instance of " + targetType.getCanonicalName()); } return null; } } static class ToByteArrayArgumentConverter extends SimpleArgumentConverter { @Override protected Object convert(Object source, Class<?> targetType) { assertEquals(byte[].class, targetType, "Can only convert to " + byte[].class.getCanonicalName()); try { return new byte[] {Byte.parseByte(source.toString())}; } catch (Exception e) { fail("failure while converting " + source + " into an instance of " + targetType.getCanonicalName()); } return null; } } }
package controllers; import dbflute.exbhv.WidgetBhv; import dbflute.exentity.Widget; import models.WidgetItem; import org.dbflute.cbean.result.ListResultBean; import org.springframework.transaction.annotation.Transactional; import play.Logger; import play.data.Form; import play.data.FormFactory; import play.mvc.Controller; import play.mvc.Result; import javax.inject.Inject; import javax.inject.Singleton; import static play.libs.Scala.toSeq; @Singleton public class WidgetController extends Controller { private static final Logger.ALogger logger = Logger.of(WidgetController.class); private final FormFactory formFactory; private final WidgetBhv widgetBhv; @Inject public WidgetController(FormFactory formFactory, WidgetBhv widgetBhv) { this.formFactory = formFactory; this.widgetBhv = widgetBhv; } public Result listWidgets() { final Form<WidgetItem> form = formFactory.form(WidgetItem.class); return ok(views.html.listWidgets.render(toSeq(selectWidgetList()), form)); } @Transactional public Result createWidget() { final Form<WidgetItem> form = formFactory.form(WidgetItem.class).bindFromRequest(); if (form.hasErrors()) { logger.error("errors = {}", form.allErrors()); return badRequest(views.html.listWidgets.render(toSeq(selectWidgetList()), form)); } WidgetItem item = form.get(); Widget entity = new Widget(); entity.setName(item.getName()); entity.setPrice(item.getPrice()); widgetBhv.insert(entity); flash("info", "Widget added!"); return redirect(routes.WidgetController.listWidgets()); } private ListResultBean<Widget> selectWidgetList() { return widgetBhv.selectList(cb -> { cb.query().addOrderBy_Id_Asc(); }); } }
package testsuite.manager; import org.xml.sax.SAXException; import testsuite.group.Group; import testsuite.result.AbstractResult; import testsuite.result.ResultsCollections; import testsuite.test.FunctionalTest; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; /** * @author Alexandre di Costanzo * */ public abstract class FunctionalTestManager extends AbstractManager { public FunctionalTestManager() { super("FunctionalTestManager with no name", "FunctionalTestManager with no description"); } /** * @param name * @param description */ public FunctionalTestManager(String name, String description) { super(name, description); } public FunctionalTestManager(File xmlDescriptor) throws IOException, SAXException { super(xmlDescriptor); this.loadAttributes(getProperties()); } /** * @see testsuite.manager.AbstractManager#execute() */ public void execute(boolean useAttributesFile) { if (logger.isInfoEnabled()) { logger.info("Starting ..."); } ResultsCollections results = getResults(); if (useAttributesFile) { try { if (logger.isDebugEnabled()) { logger.debug("Load attributes"); } loadAttributes(); } catch (IOException e1) { if (logger.isInfoEnabled()) { logger.info(e1); } } } results.add(AbstractResult.IMP_MSG, "Starting ..."); try { initManager(); } catch (Exception e) { logger.fatal("Can't init the manager", e); results.add(AbstractResult.ERROR, "Can't init the manager", e); return; } if (logger.isInfoEnabled()) { logger.info("Init Manager with success"); } results.add(AbstractResult.IMP_MSG, "Init Manager with success"); Iterator itGroup = iterator(); while (itGroup.hasNext()) { Group group = (Group) itGroup.next(); ResultsCollections resultsGroup = group.getResults(); try { group.initGroup(); } catch (Exception e) { logger.warn("Can't init group : " + group.getName(), e); resultsGroup.add(AbstractResult.ERROR, "Can't init group : " + group.getName(), e); continue; } int runs = 0; int errors = 0; for (int i = 0; i < getNbRuns(); i++) { Iterator itTest = group.iterator(); while (itTest.hasNext()) { FunctionalTest test = (FunctionalTest) itTest.next(); AbstractResult result = test.runTest(); if (result != null) { resultsGroup.add(result); if (test.isFailed()) { logger.warn("Test " + test.getName() + " [FAILED]"); errors++; } else { if (logger.isInfoEnabled()) { logger.info("Test " + test.getName() + " runs with [SUCCESS]"); } runs++; } } } } resultsGroup.add(AbstractResult.GLOBAL_RESULT, "Group : " + group.getName() + " Runs : " + runs + " Errors : " + errors); try { group.endGroup(); } catch (Exception e) { logger.warn("Can't ending group : " + group.getName(), e); resultsGroup.add(AbstractResult.ERROR, "Can't ending group : " + group.getName(), e); continue; } results.addAll(resultsGroup); } if (this.interLinkedGroups != null) { // runs interlinked test Iterator itInterGroup = this.interLinkedGroups.iterator(); while (itInterGroup.hasNext()) { Group group = (Group) itInterGroup.next(); ResultsCollections resultsGroup = group.getResults(); try { group.initGroup(); } catch (Exception e) { logger.warn("Can't init group : " + group.getName(), e); resultsGroup.add(AbstractResult.ERROR, "Can't init group : " + group.getName(), e); continue; } int runs = 0; int errors = 0; for (int i = 0; i < getNbRuns(); i++) { Iterator itTest = group.iterator(); while (itTest.hasNext()) { FunctionalTest test = (FunctionalTest) itTest.next(); AbstractResult result = test.runTestCascading(); resultsGroup.add(result); if (test.isFailed()) { logger.warn("Test " + test.getName() + " [FAILED]"); errors++; } else { if (logger.isInfoEnabled()) { logger.info("Test " + test.getName() + " runs with [SUCCESS]"); } runs++; } } } resultsGroup.add(AbstractResult.GLOBAL_RESULT, "Group : " + group.getName() + " Runs : " + runs + " Errors : " + errors); try { group.endGroup(); } catch (Exception e) { logger.warn("Can't ending group : " + group.getName(), e); resultsGroup.add(AbstractResult.ERROR, "Can't ending group : " + group.getName(), e); continue; } results.addAll(resultsGroup); this.add(group); } } // end Manager try { endManager(); } catch (Exception e) { logger.fatal("Can't ending the manager", e); results.add(AbstractResult.ERROR, "Can't ending the manager", e); return; } results.add(AbstractResult.IMP_MSG, "... Finish"); if (logger.isInfoEnabled()) { logger.info("... Finish"); } // Show Results this.showResult(); } private int runs = 0; private int errors = 0; private void execCascadingTests(ResultsCollections results, FunctionalTest test) { FunctionalTest[] tests = test.getTests(); int length = (tests != null) ? tests.length : 0; for (int i = 0; i < length; i++) execCascadingTests(results, tests[i]); results.add(test.runTestCascading()); if (test.isFailed()) { logger.warn("Test " + test.getName() + " [FAILED]"); errors++; } else { if (logger.isInfoEnabled()) { logger.info("Test " + test.getName() + " runs with [SUCCESS]"); } runs++; } } public void execute(Group group, FunctionalTest lastestTest, boolean useAttributesFile) { if (logger.isInfoEnabled()) { logger.info("Starting with interlinked Tests ..."); } ResultsCollections results = getResults(); if (useAttributesFile) { try { if (logger.isDebugEnabled()) { logger.debug("Load attributes"); } loadAttributes(); } catch (IOException e1) { if (logger.isInfoEnabled()) { logger.info(e1); } } } results.add(AbstractResult.IMP_MSG, "Starting with interlinked Tests ..."); try { initManager(); } catch (Exception e) { logger.fatal("Can't init the manager", e); results.add(AbstractResult.ERROR, "Can't init the manager", e); return; } if (logger.isInfoEnabled()) { logger.info("Init Manager with success"); } results.add(AbstractResult.IMP_MSG, "Init Manager with success"); ResultsCollections resultsGroup = group.getResults(); try { group.initGroup(); } catch (Exception e) { logger.warn("Can't init group : " + group.getName(), e); resultsGroup.add(AbstractResult.ERROR, "Can't init group : " + group.getName(), e); } for (int i = 0; i < getNbRuns(); i++) { execCascadingTests(resultsGroup, lastestTest); } resultsGroup.add(AbstractResult.GLOBAL_RESULT, "Group : " + group.getName() + " Runs : " + runs + " Errors : " + errors); try { group.endGroup(); } catch (Exception e) { logger.warn("Can't ending group : " + group.getName(), e); resultsGroup.add(AbstractResult.ERROR, "Can't ending group : " + group.getName(), e); } results.addAll(resultsGroup); try { endManager(); } catch (Exception e) { logger.fatal("Can't ending the manager", e); results.add(AbstractResult.ERROR, "Can't ending the manager", e); return; } results.add(AbstractResult.IMP_MSG, "... Finish"); if (logger.isInfoEnabled()) { logger.info("... Finish"); } } public void executeInterLinkedTest() { if (logger.isInfoEnabled()) { logger.info("Starting ..."); } ResultsCollections results = getResults(); results.add(AbstractResult.IMP_MSG, "Starting ..."); try { initManager(); } catch (Exception e) { logger.fatal("Can't init the manager", e); results.add(AbstractResult.ERROR, "Can't init the manager", e); return; } if (logger.isInfoEnabled()) { logger.info("Init Manager with success"); } results.add(AbstractResult.IMP_MSG, "Init Manager with success"); Iterator itGroup = this.interLinkedGroups.iterator(); while (itGroup.hasNext()) { Group group = (Group) itGroup.next(); ResultsCollections resultsGroup = group.getResults(); try { group.initGroup(); } catch (Exception e) { logger.warn("Can't init group : " + group.getName(), e); resultsGroup.add(AbstractResult.ERROR, "Can't init group : " + group.getName(), e); continue; } int runs = 0; int errors = 0; for (int i = 0; i < getNbRuns(); i++) { Iterator itTest = group.iterator(); while (itTest.hasNext()) { FunctionalTest test = (FunctionalTest) itTest.next(); AbstractResult result = test.runTestCascading(); resultsGroup.add(result); if (test.isFailed()) { logger.warn("Test " + test.getName() + " [FAILED]"); errors++; } else { if (logger.isInfoEnabled()) { logger.info("Test " + test.getName() + " runs with [SUCCESS]"); } runs++; } } } resultsGroup.add(AbstractResult.GLOBAL_RESULT, "Group : " + group.getName() + " Runs : " + runs + " Errors : " + errors); try { group.endGroup(); } catch (Exception e) { logger.warn("Can't ending group : " + group.getName(), e); resultsGroup.add(AbstractResult.ERROR, "Can't ending group : " + group.getName(), e); continue; } results.addAll(resultsGroup); } try { endManager(); } catch (Exception e) { logger.fatal("Can't ending the manager", e); results.add(AbstractResult.ERROR, "Can't ending the manager", e); return; } results.add(AbstractResult.IMP_MSG, "... Finish"); if (logger.isInfoEnabled()) { logger.info("... Finish"); } this.showResult(); } public void addInterLinkedGroup(Group group) { this.interLinkedGroups.add(group); } /** * @return */ public ArrayList getInterLinkedGroups() { return this.interLinkedGroups; } /** * @param list */ public void setInterLinkedGroups(ArrayList list) { this.interLinkedGroups = list; } /** * @see testsuite.manager.AbstractManager#execute() */ public void execute() { super.execute(); } }
package uk.co.eluinhost.commands; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.command.TabExecutor; import uk.co.eluinhost.commands.exceptions.*; import java.lang.reflect.Method; import java.util.*; public class CommandHandler implements TabExecutor { private final CommandMap m_commandMap = new CommandMap(); /** * Stores a list of class */ private final Map<String,Object> m_instances = new HashMap<String,Object>(); private static final String COMMAND_NOT_FOUND = ChatColor.RED + "Couldn't find the command requested"; private static final class CommandHandlerHolder { private static final CommandHandler COMMAND_HANDLER = new CommandHandler(); } /** * @return instance of the bukkit command handler */ public static final CommandHandler getInstance(){ return CommandHandlerHolder.COMMAND_HANDLER; } /** * Create the bukkit command handler */ private CommandHandler() {} /** * Register the commands within the class * @param clazz the class to check * @throws uk.co.eluinhost.commands.exceptions.CommandCreateException if there is an error creating the instance for calling the commands * @throws CommandIDConflictException when an ID is already taken * @throws CommandParentNotFoundException when a parent ID doesn't point to anything valid */ public void registerCommands(Class clazz) throws CommandCreateException, CommandIDConflictException, CommandParentNotFoundException, InvalidMethodParametersException { Object instance = getClassInstance(clazz.getName()); if(instance == null){ //noinspection OverlyBroadCatchBlock try { instance = clazz.getConstructor().newInstance(); m_instances.put(clazz.getName(),instance); } catch (Exception ex) { ex.printStackTrace(); throw new CommandCreateException(); } } Map<String, List<String>> parentsToChildren = new HashMap<String, List<String>>(); Map<String,ICommandProxy> allCommands = new HashMap<String, ICommandProxy>(); Method[] methods = clazz.getDeclaredMethods(); for(Method method : methods){ Command methodAnnotation = method.getAnnotation(Command.class); if(methodAnnotation != null){ //check if ID already exists if(m_commandMap.getCommandByIdentifier(methodAnnotation.identifier())!=null){ throw new CommandIDConflictException(); } //check if the method has 1 parameter of type CommandRequest Class[] parameterTypes = method.getParameterTypes(); if(parameterTypes.length != 1 || !parameterTypes[0].equals(CommandRequest.class)){ throw new InvalidMethodParametersException(); } //Make the new command proxy object ICommandProxy commandProxy = new CommandProxy( method, instance, methodAnnotation.trigger(), methodAnnotation.identifier(), methodAnnotation.minArgs(), methodAnnotation.maxArgs() ); //get the list for the parent name List<String> children = parentsToChildren.get(methodAnnotation.parentID()); if(children == null){ children = new ArrayList<String>(); parentsToChildren.put(methodAnnotation.parentID(), children); } //add the object to the list children.add(commandProxy.getIdentifier()); allCommands.put(commandProxy.getIdentifier(), commandProxy); } } //commands don't have any conflicting IDs here, now we need to check parent IDs are all valid for(String parentname : parentsToChildren.keySet()){ if(parentname.isEmpty()){ continue; } if(!allCommands.containsKey(parentname) && m_commandMap.getCommandByIdentifier(parentname) == null){ throw new CommandParentNotFoundException(); } } //for all the parent->children mappings generate the trees for the parent for (Map.Entry<String, List<String>> entry : parentsToChildren.entrySet()) { //the parent ID String parentID = entry.getKey(); //all the children we want to add to the parent List<String> children = entry.getValue(); //if we have the parent if (allCommands.containsKey(parentID)) { //get the parent and add all the children ICommandProxy parent = allCommands.get(entry.getKey()); for (String child : children) { parent.addChild(allCommands.get(child)); } } //else add the children to the existing map of commands else { for (String child : children) { try { m_commandMap.addCommand(allCommands.get(child), entry.getKey()); Bukkit.getLogger().info("Added command "+child+" with trigger "+allCommands.get(child).getTrigger()+" to map"); } catch (CommandNotFoundException e) { e.printStackTrace(); //this should never happen if logic is correct Bukkit.getLogger().severe("Error adding command to map, parent ID "+parentID+" not valid."); } } } } } /** * Gets the instance stored for the class name * @param className the class name to check for * @return the class if exists or null otherwise */ public Object getClassInstance(String className) { return m_instances.get(className); } /** * Converts arguements with the " char to use 1 index * @param args the arguements to parse * @return array of converted strings */ private static List<String> convertArgs(String[] args){ List<String> finalArgs = new ArrayList<String>(); for(int i = 0; i < args.length; i++){ String arg = args[i]; if(arg.charAt(0) == '"'){ StringBuilder build = new StringBuilder(); build.append(arg.substring(1)); for(i += 1;i<args.length;i++){ build.append(" "); String quotedArg = args[i]; if(quotedArg.charAt(quotedArg.length()-1) == '"'){ build.append(quotedArg.substring(0,quotedArg.length()-1)); break; }else{ build.append(quotedArg); } } finalArgs.add(build.toString()); }else{ finalArgs.add(arg); } } return finalArgs; } @Override public boolean onCommand(CommandSender sender, org.bukkit.command.Command command, String label, String[] args) { try { m_commandMap.callCommand(new CommandRequest(command.getName(),convertArgs(args),sender)); } catch (CommandNotFoundException ex) { ex.printStackTrace(); sender.sendMessage(ChatColor.RED + COMMAND_NOT_FOUND); } return true; } @Override public List<String> onTabComplete(CommandSender sender, org.bukkit.command.Command command, String label, String[] args) { //TODO ... or not return null; } }
package cn.aofeng.threadpool4j; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import static org.easymock.EasyMock.*; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; /** * {@link ThreadPoolImpl} * * @author <a href="mailto:aofengblog@163.com"></a> */ public class ThreadPoolTest { private ThreadPoolImpl _threadPool = new ThreadPoolImpl(); @Rule public ExpectedException _expectedEx = ExpectedException.none(); @Before public void setUp() throws Exception { _threadPool.init(); } @After public void tearDown() throws Exception { } @Test public void testInit() { assertEquals(2, _threadPool._multiThreadPool.size()); assertTrue(_threadPool._multiThreadPool.containsKey("default")); assertTrue(_threadPool._multiThreadPool.containsKey("other")); assertTrue(_threadPool._threadPoolConfig._threadStateSwitch); assertEquals(60, _threadPool._threadPoolConfig._threadStateInterval); } @Test public void testSubmitRunnable4TaskIsNull() { _expectedEx.expect(IllegalArgumentException.class); _expectedEx.expectMessage("task is null"); Runnable task = null; _threadPool.submit(task); } /** * <br/> * * <pre> * {@link Runnable} * </pre> * * * <pre> * defaultsubmit1 * </pre> */ @Test public void testSubmitRunnable() { callThreadPool("default"); } @Test public void testSubmitRunnableString4TaskIsNull() { _expectedEx.expect(IllegalArgumentException.class); _expectedEx.expectMessage("task is null"); Runnable task = null; _threadPool.submit(task, "default"); } @Test public void testSubmitRunnableString4ThreadpoolNameIsNull() { _expectedEx.expect(IllegalArgumentException.class); _expectedEx.expectMessage("thread pool name is empty"); Runnable task = createRunnable(); _threadPool.submit(task, null); } @Test public void testSubmitRunnableString4ThreadpoolNameNotExists() { _expectedEx.expect(IllegalArgumentException.class); _expectedEx.expectMessage("thread pool ThreadpoolNotExists not exists"); Runnable task = createRunnable(); _threadPool.submit(task, "ThreadpoolNotExists"); } /** * <br/> * * <pre> * {@link Runnable}"other" * </pre> * * * <pre> * othersubmit1 * </pre> */ @Test public void testSubmitRunnableString() { callThreadPool("other"); } /** * <br/> * * <pre> * {@link Runnable}"default" * </pre> * * * <pre> * run1 * </pre> */ @Test public void testSubmitRunnableString4RunTask() throws InterruptedException { Runnable mock = createMock(Runnable.class); mock.run(); expectLastCall().once(); // run1 replay(mock); _threadPool.submit(mock, "default"); Thread.sleep(1000); verify(mock); } private void callThreadPool(String threadpoolName) { ExecutorService mock = createMock(ExecutorService.class); mock.submit(anyObject(Runnable.class)); expectLastCall().andReturn(null).once(); // submit1 replay(mock); _threadPool._multiThreadPool.put(threadpoolName, mock); _threadPool.submit(createRunnable(), threadpoolName); verify(mock); } private Runnable createRunnable() { return new Runnable() { @Override public void run() { // nothing } }; } @Test public void testSubmitCallable4TaskIsNull() { _expectedEx.expect(IllegalArgumentException.class); _expectedEx.expectMessage("task is null"); Callable<?> task = null; _threadPool.submit(task); } @Test public void testSubmitCallableString4TaskIsNull() { _expectedEx.expect(IllegalArgumentException.class); _expectedEx.expectMessage("task is null"); Callable<?> task = null; _threadPool.submit(task, "default"); } @Test public void testSubmitCallableString4ThreadpoolNameIsNull() { _expectedEx.expect(IllegalArgumentException.class); _expectedEx.expectMessage("thread pool name is empty"); Callable<?> task = createCallable(); _threadPool.submit(task, null); } @Test public void testSubmitCallableString4ThreadpoolNameNotExists() { _expectedEx.expect(IllegalArgumentException.class); _expectedEx.expectMessage("thread pool ThreadpoolNotExists not exists"); Callable<?> task = createCallable(); _threadPool.submit(task, "ThreadpoolNotExists"); } /** * <br/> * * <pre> * {@link Runnable}"default" * </pre> * * * <pre> * run1 * </pre> */ @SuppressWarnings("unchecked") @Test public void testSubmitCallableString4RunTask() throws Exception { Callable<List<String>> mock = createMock(Callable.class); List<String> returnMock = createMock(List.class); mock.call(); expectLastCall().andReturn(returnMock).once(); // call1 replay(mock); _threadPool.submit(mock, "default"); Thread.sleep(1000); verify(mock); } @Test public void testInvokeAll4TaskListIsNull() { _expectedEx.expect(IllegalArgumentException.class); _expectedEx.expectMessage("task list is null or empty"); Collection<Callable<Integer>> tasks = null; _threadPool.invokeAll(tasks, 1, TimeUnit.SECONDS); } @Test public void testInvokeAll4TaskListIsEmpty() { _expectedEx.expect(IllegalArgumentException.class); _expectedEx.expectMessage("task list is null or empty"); Collection<Callable<Integer>> tasks = new ArrayList<Callable<Integer>>(); _threadPool.invokeAll(tasks, 1, TimeUnit.SECONDS); } @Test public void testInvokeAll4TimeoutEqualsZero() { _expectedEx.expect(IllegalArgumentException.class); _expectedEx.expectMessage("timeout less than or equals zero"); Collection<Callable<Integer>> tasks = new ArrayList<Callable<Integer>>(); tasks.add(createCallable()); _threadPool.invokeAll(tasks, 0, TimeUnit.SECONDS); } @Test public void testInvokeAll4TimeoutLessThanZero() { _expectedEx.expect(IllegalArgumentException.class); _expectedEx.expectMessage("timeout less than or equals zero"); Collection<Callable<Integer>> tasks = new ArrayList<Callable<Integer>>(); tasks.add(createCallable()); _threadPool.invokeAll(tasks, -1, TimeUnit.SECONDS); } @Test public void testInvokeAll4ThreadpoolNameIsNull() { _expectedEx.expect(IllegalArgumentException.class); _expectedEx.expectMessage("thread pool name is empty"); Collection<Callable<Integer>> tasks = new ArrayList<Callable<Integer>>(); tasks.add(createCallable()); _threadPool.invokeAll(tasks, 2, TimeUnit.SECONDS, null); } @Test public void testInvokeAll4ThreadpoolNameIsEmpty() { _expectedEx.expect(IllegalArgumentException.class); _expectedEx.expectMessage("thread pool name is empty"); Collection<Callable<Integer>> tasks = new ArrayList<Callable<Integer>>(); tasks.add(createCallable()); _threadPool.invokeAll(tasks, 2, TimeUnit.SECONDS, " "); } @Test public void testInvokeAll4ThreadpoolNotExists() { _expectedEx.expect(IllegalArgumentException.class); _expectedEx.expectMessage("thread pool ThreadPoolNotExists not exists"); Collection<Callable<Integer>> tasks = new ArrayList<Callable<Integer>>(); tasks.add(createCallable()); _threadPool.invokeAll(tasks, 2, TimeUnit.SECONDS, "ThreadPoolNotExists"); } /** * "default" <br/> * * <pre> * 1 * 2 * 3 * </pre> * * * <pre> * * </pre> * @throws ExecutionException * @throws InterruptedException */ @Test public void testInvokeAll() throws InterruptedException, ExecutionException { Collection<Callable<Integer>> tasks = new ArrayList<Callable<Integer>>(); tasks.add(createCallable()); tasks.add(createCallable()); List<Future<Integer>> futures = _threadPool.invokeAll(tasks, 2, TimeUnit.SECONDS); int result = 0; for (Future<Integer> future : futures) { result += future.get(); } assertEquals(18, result); } /** * <br/> * * <pre> * "ThreadPoolNotExists" * </pre> * * * <pre> * false * </pre> */ @Test public void testIsExists4NotExists() { assertFalse(_threadPool.isExists("ThreadPoolNotExists")); } /** * <br/> * * <pre> * "default" * </pre> * * * <pre> * true * </pre> */ @Test public void testIsExists4Exists() { assertTrue(_threadPool.isExists("default")); } private Callable<Integer> createCallable() { return new Callable<Integer>() { @Override public Integer call() throws Exception { return 9; } }; } }
package ru.my; public class MyFirstProgram { public static void main(String[] args) { hello("me"); hello("me1"); hello("me"); double q = 5; System.out.println("Площадь квадрата со стороной " + q + " = " + area(q)); double a = 4; double b = 6; System.out.println("Площадь прямоугольника 1 со сторонами " + a + " и " + b + " = " + area(a,b)); System.out.println("Площадь прямоугольника 2 со сторонами " + a + " и " + b + " = " + area(a,b)); } public static void hello(String smb) { System.out.println("Hello, " + smb); } public static double area(double t) { return t * t; } public static double area(double a, double b) { return a*b; } }
package net.fortuna.ical4j.model; import net.fortuna.ical4j.model.property.Transp; /** * Unit tests for Property-specific functionality. * @author Ben Fortuna */ public class PropertyTest extends AbstractPropertyTest { /** * Test equality of properties. */ public void testEquals() { Property p = new Transp(); assertFalse("Properties are not equal", Transp.TRANSPARENT.equals(p)); assertFalse("Properties are not equal", p.equals(Transp.TRANSPARENT)); } }
package org.encog.app.quant; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.GregorianCalendar; import org.encog.app.quant.loader.yahoo.YahooDownload; import org.encog.util.csv.CSVFormat; import org.junit.Assert; import junit.framework.TestCase; public class TestYahooDownload extends TestCase { public void testYahooDownloadError() throws IOException { try { YahooDownload yahoo = new YahooDownload(); yahoo.setPercision(2); // load a non-sense ticker, should throw error yahoo.loadAllData("sdfhusdhfuish", new File("test.txt"), CSVFormat.ENGLISH, new GregorianCalendar(2000, 00, 01).getTime(), new GregorianCalendar(2000, 00, 10).getTime()); // bad! Assert.assertTrue(false); } catch (QuantError e) { // good! } } public void testYahooDownloadCSV() throws IOException { YahooDownload yahoo = new YahooDownload(); yahoo.setPercision(2); yahoo.loadAllData("yhoo", new File("test.txt"), CSVFormat.ENGLISH, new GregorianCalendar(2000, 00, 01).getTime(), new GregorianCalendar(2000, 00, 10).getTime()); BufferedReader tr = new BufferedReader(new FileReader("test.txt")); Assert.assertEquals( "date,time,open price,high price,low price,close price,volume,adjusted price", tr.readLine()); Assert.assertEquals( "20000110,0,432.5,451.25,420,436.06,61022400,109.01", tr.readLine()); Assert.assertEquals("20000107,0,366.75,408,363,407.25,48999600,101.81", tr.readLine()); Assert.assertEquals("20000106,0,406.25,413,361,368.19,71301200,92.05", tr.readLine()); Assert.assertEquals( "20000105,0,430.5,431.13,402,410.5,83194800,102.62", tr.readLine()); tr.close(); } }
package performance.nameByPrefix; import java.net.URL; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import us.kbase.common.service.ServerException; import us.kbase.common.service.UObject; import us.kbase.workspace.CloneWorkspaceParams; import us.kbase.workspace.CreateWorkspaceParams; import us.kbase.workspace.ObjectSaveData; import us.kbase.workspace.SaveObjectsParams; import us.kbase.workspace.WorkspaceClient; import us.kbase.workspace.WorkspaceIdentity; /** Set up objects to test speed of the name_by_prefix function. Assumes * Empty.AType-0.1 (which has no restrictions on the save object, e.g. 1 * optional field) exists in the target workspace. * @author gaprice@lbl.gov * */ public class NamebyPrefix { public static final String TYPE = "Empty.AType-0.1"; public static final String wsURL = "http://localhost:7058"; public static final String ORIGINAL_WORKSPACE_NAME = "getnamesbyprefix_original"; public static final int CLONE_COUNT = 9; public static String PASSWORD; public static void main(String[] args) throws Exception { PASSWORD = args[0]; try { loadOneMillion(); } catch (ServerException se) { System.out.println(se.getData()); throw se; } } private static String intToName(int in) { final char[] seq = new char[4]; final int start = (int) 'a'; final int abc = 26; for (int i = seq.length - 1; i >= 0; i seq[i] = (char)(start + in % abc); in = in / abc; } return new String(seq); } private static void loadOneMillion() throws Exception { WorkspaceClient cli = new WorkspaceClient(new URL(wsURL), "kbasetest", PASSWORD); cli.setIsInsecureHttpConnectionAllowed(true); cli.createWorkspace(new CreateWorkspaceParams().withGlobalread("r") .withWorkspace(ORIGINAL_WORKSPACE_NAME)); List<ObjectSaveData> o = new LinkedList<ObjectSaveData>(); for (int i = 0; i < 100000; i++) { o.add(new ObjectSaveData() .withData(new UObject(new HashMap<String, String>())) .withName(intToName(i)) .withType(TYPE)); } System.out.println("saving 100000 objects"); cli.saveObjects(new SaveObjectsParams() .withWorkspace(ORIGINAL_WORKSPACE_NAME) .withObjects(o)); for (int i = 1; i <= CLONE_COUNT; i++) { System.out.println(String.format( "Clone %s of %s.", i, CLONE_COUNT)); cli.cloneWorkspace(new CloneWorkspaceParams().withGlobalread("r") .withWsi(new WorkspaceIdentity() .withWorkspace(ORIGINAL_WORKSPACE_NAME)) .withWorkspace(ORIGINAL_WORKSPACE_NAME + (i + 1))); } System.out.println("Done"); } }
package org.orbeon.oxf.test; import org.apache.commons.lang.StringUtils; import org.dom4j.Document; import org.dom4j.Element; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.orbeon.oxf.common.Errors; import org.orbeon.oxf.common.OXFException; import org.orbeon.oxf.common.Version; import org.orbeon.oxf.pipeline.api.PipelineContext; import org.orbeon.oxf.processor.DOMSerializer; import org.orbeon.oxf.processor.Processor; import org.orbeon.oxf.processor.ProcessorUtils; import org.orbeon.oxf.processor.generator.URLGenerator; import org.orbeon.oxf.util.PipelineUtils; import org.orbeon.oxf.xml.Dom4j; import org.orbeon.oxf.xml.XPathUtils; import org.orbeon.oxf.xml.dom4j.Dom4jUtils; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import static org.junit.Assert.fail; @RunWith(Parameterized.class) public class ProcessorTest extends ResourceManagerTestBase { private static final String TEST_CONFIG = "oxf.test.config"; @Test public void runTest() throws Throwable { test(); } @Rule public TestName name= new TestName() { @Override public String getMethodName() { return getName(); } }; @Override public String toString() { return getName(); } @Parameterized.Parameters(name="{0}") public static Collection<Object[]> data() { String currentTestError = null; try { staticSetup(); final List<Object[]> parameters = new ArrayList<Object[]>(); final Document tests; { final URLGenerator urlGenerator = new URLGenerator(System.getProperty(TEST_CONFIG), true); final DOMSerializer domSerializer = new DOMSerializer(); PipelineUtils.connect(urlGenerator, "data", domSerializer, "data"); final PipelineContext pipelineContext = new PipelineContext(); domSerializer.start(pipelineContext); tests = domSerializer.getDocument(pipelineContext); } // If there are tests with a true "only" attribute but not a true "exclude" attribute, execute only those Iterator i = XPathUtils.selectIterator(tests, "(/tests/test | /tests/group/test)[ancestor-or-self::*/@only = 'true' and not(ancestor-or-self::*/@exclude = 'true')]"); // Otherwise, run all tests that are not excluded if (!i.hasNext()) i = XPathUtils.selectIterator(tests, "(/tests/test | /tests/group/test)[not(ancestor-or-self::*/@exclude = 'true')]"); for (; i.hasNext();) { final Element testNode = (Element) i.next(); final Element groupNode = testNode.getParent(); if ("true".equals(testNode.attributeValue("ignore")) || ("pe".equalsIgnoreCase(testNode.attributeValue("edition")) && ! Version.isPE()) || ("ce".equalsIgnoreCase(testNode.attributeValue("edition")) && Version.isPE())) continue; String description = testNode.attributeValue("description", ""); if (groupNode.getName().equals("group")) { String groupDescription = groupNode.attributeValue("description"); if (groupDescription != null) description = groupDescription + " - " + description; } currentTestError = "Error when executing test with description: '" + description + "'"; // Create processor and connect its inputs final Processor processor = ProcessorUtils.createProcessorWithInputs(testNode); processor.setId("Main Test Processor"); // Connect outputs final List<DOMSerializer> domSerializers = new ArrayList<DOMSerializer>(); final List<Document> expectedDocuments = new ArrayList<Document>(); for (Iterator j = XPathUtils.selectIterator(testNode, "output"); j.hasNext();) { final Element outputElement = (Element) j.next(); final String name = XPathUtils.selectStringValue(outputElement, "@name"); if (name == null || name.equals("")) throw new OXFException("Output name is mandatory"); final Document doc = ProcessorUtils.createDocumentFromEmbeddedOrHref(outputElement, XPathUtils.selectStringValue(outputElement, "@href")); expectedDocuments.add(doc); final DOMSerializer domSerializer = new DOMSerializer(); PipelineUtils.connect(processor, name, domSerializer, "data"); domSerializers.add(domSerializer); } final String requestURL = testNode.attributeValue("request", ""); parameters.add(new Object[] { description, processor, requestURL, domSerializers, expectedDocuments }); } return parameters; } catch (Throwable t) { System.err.println(currentTestError + Errors.format(t)); throw new OXFException(currentTestError); } } private String description; private Processor processor; private String requestURL; private List<DOMSerializer> domSerializers; private List<Document> expectedDocuments; public ProcessorTest(String description, Processor processor, String requestURL, List<DOMSerializer> domSerializers, List<Document> expectedDocuments) { this.description = description; this.requestURL = requestURL; this.processor = processor; this.domSerializers = domSerializers; this.expectedDocuments = expectedDocuments; } protected ProcessorTest(String name) { this.description = name; } public String getName() { return description; } /** * Run test and compare to expected result */ private void test() throws Throwable { TestRunner runner = new TestRunner(); runner.run(); // Check exception if (runner.getException() != null) { System.err.println(description); throw OXFException.getRootThrowable(runner.getException()); } // Check if got expected result if (! runner.isExpectedEqualsActual()) { System.err.println(description); System.err.println("\nExpected data:\n" + runner.getExpectedDataStringFormatted()); System.err.println("\nActual data:\n" + runner.getActualDataStringFormatted()); fail(); } } class TestRunner implements Runnable { private Throwable exception; private boolean expectedEqualsActual = true; private String expectedDataStringFormatted; private String actualDataStringFormatted; public void run() { try { // Create pipeline context final PipelineContext pipelineContext = StringUtils.isNotEmpty(requestURL) ? createPipelineContextWithExternalContext(requestURL) : createPipelineContextWithExternalContext(); processor.reset(pipelineContext); if (domSerializers.size() == 0) { // Processor with no output: just run it processor.start(pipelineContext); } else { // Get output and compare to expected result final Iterator<DOMSerializer> domSerializersIterator = domSerializers.iterator(); final Iterator<Document> expectedNodesIterator = expectedDocuments.iterator(); while (domSerializersIterator.hasNext()) { // Get expected final DOMSerializer domSerializer = domSerializersIterator.next(); final Document expectedData = expectedNodesIterator.next(); // Run serializer domSerializer.start(pipelineContext); // Get actual data final Document actualData = domSerializer.getDocument(pipelineContext); // NOTE: We could make the comparison more configurable, for example to not collapse white space final boolean outputPassed = Dom4j.compareDocumentsIgnoreNamespacesInScopeCollapse(expectedData, actualData); // Display if test not passed if (!outputPassed) { expectedEqualsActual = false; // Store pretty strings expectedDataStringFormatted = Dom4jUtils.domToPrettyString(expectedData); actualDataStringFormatted = Dom4jUtils.domToPrettyString(actualData); break; } } } } catch (Throwable e) { exception = e; } } public Throwable getException() { return exception; } public boolean isExpectedEqualsActual() { return expectedEqualsActual; } public String getExpectedDataStringFormatted() { return expectedDataStringFormatted; } public String getActualDataStringFormatted() { return actualDataStringFormatted; } } }
package com.firebase.samples.logindemo; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Intent; import android.content.IntentSender; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.facebook.Session; import com.facebook.SessionState; import com.facebook.widget.LoginButton; import com.firebase.client.AuthData; import com.firebase.client.Firebase; import com.firebase.client.FirebaseError; import com.google.android.gms.auth.GoogleAuthException; import com.google.android.gms.auth.GoogleAuthUtil; import com.google.android.gms.auth.UserRecoverableAuthException; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.Scopes; import com.google.android.gms.common.SignInButton; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.plus.Plus; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * This application demos the use of the Firebase Login feature. It currently supports logging in * with Google, Facebook, Twitter, Email/Password, and Anonymous providers. * <p/> * The methods in this class have been divided into sections based on providers (with a few * general methods). * <p/> * Facebook provides its own API via the {@link com.facebook.widget.LoginButton}. * Google provides its own API via the {@link com.google.android.gms.common.api.GoogleApiClient}. * Twitter requires us to use a Web View to authenticate, see * {@link com.firebase.samples.logindemo.TwitterOAuthActivity} * Email/Password is provided using {@link com.firebase.client.Firebase} * Anonymous is provided using {@link com.firebase.client.Firebase} */ public class MainActivity extends ActionBarActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { /* TextView that is used to display information about the logged in user */ private TextView mLoggedInStatusTextView; /* A dialog that is presented until the Firebase authentication finished. */ private ProgressDialog mAuthProgressDialog; /* A reference to the firebase */ private Firebase ref; /* Data from the authenticated user */ private AuthData authData; /* A tag that is used for logging statements */ private static final String TAG = "LoginDemo"; /* The login button for Facebook */ private LoginButton mFacebookLoginButton; /* Request code used to invoke sign in user interactions for Google+ */ public static final int RC_GOOGLE_LOGIN = 1; /* Client used to interact with Google APIs. */ private GoogleApiClient mGoogleApiClient; /* A flag indicating that a PendingIntent is in progress and prevents us from starting further intents. */ private boolean mGoogleIntentInProgress; /* Track whether the sign-in button has been clicked so that we know to resolve all issues preventing sign-in * without waiting. */ private boolean mGoogleLoginClicked; /* Store the connection result from onConnectionFailed callbacks so that we can resolve them when the user clicks * sign-in. */ private ConnectionResult mGoogleConnectionResult; /* The login button for Google */ private SignInButton mGoogleLoginButton; public static final int RC_TWITTER_LOGIN = 2; private Button mTwitterLoginButton; private Button mPasswordLoginButton; private Button mAnonymousLoginButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* Load the view and display it */ setContentView(R.layout.activity_main); /* Load the Facebook login button and set up the session callback */ mFacebookLoginButton = (LoginButton)findViewById(R.id.login_with_facebook); mFacebookLoginButton.setSessionStatusCallback(new Session.StatusCallback() { @Override public void call(Session session, SessionState state, Exception exception) { onFacebookSessionStateChange(session, state, exception); } }); /* Load the Google login button */ mGoogleLoginButton = (SignInButton)findViewById(R.id.login_with_google); mGoogleLoginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mGoogleLoginClicked = true; if (!mGoogleApiClient.isConnecting()) { if (mGoogleConnectionResult != null) { resolveSignInError(); } else if (mGoogleApiClient.isConnected()) { getGoogleOAuthTokenAndLogin(); } else { /* connect API now */ Log.d(TAG, "Trying to connect to Google API"); mGoogleApiClient.connect(); } } } }); /* Setup the Google API object to allow Google+ logins */ mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(Plus.API) .addScope(Plus.SCOPE_PLUS_LOGIN) .build(); mTwitterLoginButton = (Button)findViewById(R.id.login_with_twitter); mTwitterLoginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { loginWithTwitter(); } }); mPasswordLoginButton = (Button)findViewById(R.id.login_with_password); mPasswordLoginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { loginWithPassword(); } }); /* Load and setup the anonymous login button */ mAnonymousLoginButton = (Button)findViewById(R.id.login_anonymously); mAnonymousLoginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { loginAnonymously(); } }); mLoggedInStatusTextView = (TextView)findViewById(R.id.login_status); /* Create the SimpleLogin class that is used for all authentication with Firebase */ String firebaseUrl = getResources().getString(R.string.firebase_url); Firebase.setAndroidContext(getApplicationContext()); ref = new Firebase(firebaseUrl); /* Setup the progress dialog that is displayed later when authenticating with Firebase */ mAuthProgressDialog = new ProgressDialog(this); mAuthProgressDialog.setTitle("Loading"); mAuthProgressDialog.setMessage("Authenticating with Firebase..."); mAuthProgressDialog.setCancelable(false); mAuthProgressDialog.show(); /* Check if the user is authenticated with Firebase already. If this is the case we can set the authenticated * user and hide hide any login buttons */ ref.addAuthStateListener(new Firebase.AuthStateListener() { @Override public void onAuthStateChanged(AuthData authData) { mAuthProgressDialog.hide(); setAuthenticatedUser(authData); } }); } /** * This method fires when any startActivityForResult finishes. The requestCode maps to * the value passed into startActivityForResult. */ @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Map<String, String> options = new HashMap<String, String>(); if (requestCode == RC_GOOGLE_LOGIN) { /* This was a request by the Google API */ if (resultCode != RESULT_OK) { mGoogleLoginClicked = false; } mGoogleIntentInProgress = false; if (!mGoogleApiClient.isConnecting()) { mGoogleApiClient.connect(); } } else if (requestCode == RC_TWITTER_LOGIN) { options.put("oauth_token", data.getStringExtra("oauth_token")); options.put("oauth_token_secret", data.getStringExtra("oauth_token_secret")); options.put("user_id", data.getStringExtra("user_id")); authWithFirebase("twitter", options); } else { /* Otherwise, it's probably the request by the Facebook login button, keep track of the session */ Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data); } } @Override public boolean onCreateOptionsMenu(Menu menu) { /* If a user is currently authenticated, display a logout menu */ if (this.authData != null) { getMenuInflater().inflate(R.menu.main, menu); return true; } else { return false; } } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_logout) { logout(); return true; } return super.onOptionsItemSelected(item); } /** * Unauthenticate from Firebase and from providers where necessary. */ private void logout() { if (this.authData != null) { /* logout of Firebase */ ref.unauth(); /* Logout of any of the Frameworks. This step is optional, but ensures the user is not logged into * Facebook/Google+ after logging out of Firebase. */ if (this.authData.getProvider().equals("facebook")) { /* Logout from Facebook */ Session session = Session.getActiveSession(); if (session != null) { if (!session.isClosed()) { session.closeAndClearTokenInformation(); } } else { session = new Session(getApplicationContext()); Session.setActiveSession(session); session.closeAndClearTokenInformation(); } } else if (this.authData.getProvider().equals("google")) { /* Logout from Google+ */ if (mGoogleApiClient.isConnected()) { Plus.AccountApi.clearDefaultAccount(mGoogleApiClient); mGoogleApiClient.disconnect(); } } /* Update authenticated user and show login buttons */ setAuthenticatedUser(null); } } /** * This method will attempt to authenticate a user to firebase given an oauth_token (and other * necessary parameters depending on the provider) */ private void authWithFirebase(final String provider, Map<String, String> options) { if (options.containsKey("error")) { showErrorDialog(options.get("error")); } else { mAuthProgressDialog.show(); if (provider.equals("twitter")) { // if the provider is twitter, we pust pass in additional options, so use the options endpoint ref.authWithOAuthToken(provider, options, new AuthResultHandler(provider)); } else { // if the provider is not twitter, we just need to pass in the oauth_token ref.authWithOAuthToken(provider, options.get("oauth_token"), new AuthResultHandler(provider)); } } } /** * Once a user is logged in, take the authData provided from Firebase and "use" it. */ private void setAuthenticatedUser(AuthData authData) { if (authData != null) { /* Hide all the login buttons */ mFacebookLoginButton.setVisibility(View.GONE); mGoogleLoginButton.setVisibility(View.GONE); mTwitterLoginButton.setVisibility(View.GONE); mPasswordLoginButton.setVisibility(View.GONE); mAnonymousLoginButton.setVisibility(View.GONE); mLoggedInStatusTextView.setVisibility(View.VISIBLE); /* show a provider specific status text */ String name = null; if (authData.getProvider().equals("facebook") || authData.getProvider().equals("google") || authData.getProvider().equals("twitter")) { name = (String)authData.getProviderData().get("displayName"); } else if (authData.getProvider().equals("anonymous") || authData.getProvider().equals("password")) { name = authData.getUid(); } else { Log.e(TAG, "Invalid provider: " + authData.getProvider()); } if (name != null) { mLoggedInStatusTextView.setText("Logged in as " + name + " (" + authData.getProvider() + ")"); } } else { /* No authenticated user show all the login buttons */ mFacebookLoginButton.setVisibility(View.VISIBLE); mGoogleLoginButton.setVisibility(View.VISIBLE); mTwitterLoginButton.setVisibility(View.VISIBLE); mPasswordLoginButton.setVisibility(View.VISIBLE); mAnonymousLoginButton.setVisibility(View.VISIBLE); mLoggedInStatusTextView.setVisibility(View.GONE); } this.authData = authData; /* invalidate options menu to hide/show the logout button */ supportInvalidateOptionsMenu(); } /** * Show errors to users */ private void showErrorDialog(String message) { new AlertDialog.Builder(this) .setTitle("Error") .setMessage(message) .setPositiveButton(android.R.string.ok, null) .setIcon(android.R.drawable.ic_dialog_alert) .show(); } /** * Utility class for authentication results */ private class AuthResultHandler implements Firebase.AuthResultHandler { private final String provider; public AuthResultHandler(String provider) { this.provider = provider; } @Override public void onAuthenticated(AuthData authData) { mAuthProgressDialog.hide(); Log.i(TAG, provider + " auth successful"); setAuthenticatedUser(authData); } @Override public void onAuthenticationError(FirebaseError firebaseError) { mAuthProgressDialog.hide(); showErrorDialog(firebaseError.toString()); } } /* Handle any changes to the Facebook session */ private void onFacebookSessionStateChange(Session session, SessionState state, Exception exception) { if (state.isOpened()) { mAuthProgressDialog.show(); ref.authWithOAuthToken("facebook", session.getAccessToken(), new AuthResultHandler("facebook")); } else if (state.isClosed()) { /* Logged out of Facebook and currently authenticated with Firebase using Facebook, so do a logout */ if (this.authData != null && this.authData.getProvider().equals("facebook")) { ref.unauth(); setAuthenticatedUser(null); } } } /* A helper method to resolve the current ConnectionResult error. */ private void resolveSignInError() { if (mGoogleConnectionResult.hasResolution()) { try { mGoogleIntentInProgress = true; mGoogleConnectionResult.startResolutionForResult(this, RC_GOOGLE_LOGIN); } catch (IntentSender.SendIntentException e) { // The intent was canceled before it was sent. Return to the default // state and attempt to connect to get an updated ConnectionResult. mGoogleIntentInProgress = false; mGoogleApiClient.connect(); } } } private void getGoogleOAuthTokenAndLogin() { mAuthProgressDialog.show(); /* Get OAuth token in Background */ AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() { String errorMessage = null; @Override protected String doInBackground(Void... params) { String token = null; try { String scope = String.format("oauth2:%s", Scopes.PLUS_LOGIN); token = GoogleAuthUtil.getToken(MainActivity.this, Plus.AccountApi.getAccountName(mGoogleApiClient), scope); } catch (IOException transientEx) { /* Network or server error */ Log.e(TAG, "Error authenticating with Google: " + transientEx); errorMessage = "Network error: " + transientEx.getMessage(); } catch (UserRecoverableAuthException e) { Log.w(TAG, "Recoverable Google OAuth error: " + e.toString()); if (!mGoogleIntentInProgress) { mGoogleIntentInProgress = true; Intent recover = e.getIntent(); startActivityForResult(recover, RC_GOOGLE_LOGIN); } } catch (GoogleAuthException authEx) { /* The call is not ever expected to succeed assuming you have already verified that * Google Play services is installed. */ Log.e(TAG, "Error authenticating with Google: " + authEx.getMessage(), authEx); errorMessage = "Error authenticating with Google: " + authEx.getMessage(); } return token; } @Override protected void onPostExecute(String token) { mGoogleLoginClicked = false; if (token != null) { /* Successfully got OAuth token, now login with Google */ ref.authWithOAuthToken("google", token, new AuthResultHandler("google")); } else if (errorMessage != null) { mAuthProgressDialog.hide(); showErrorDialog(errorMessage); } } }; task.execute(); } @Override public void onConnected(final Bundle bundle) { /* Connected with Google API, use this to authenticate with Firebase */ getGoogleOAuthTokenAndLogin(); } @Override public void onConnectionFailed(ConnectionResult result) { if (!mGoogleIntentInProgress) { /* Store the ConnectionResult so that we can use it later when the user clicks on the Google+ login button */ mGoogleConnectionResult = result; if (mGoogleLoginClicked) { /* The user has already clicked login so we attempt to resolve all errors until the user is signed in, * or they cancel. */ resolveSignInError(); } else { Log.e(TAG, result.toString()); } } } @Override public void onConnectionSuspended(int i) { // ignore } private void loginWithTwitter() { startActivityForResult(new Intent(this, TwitterOAuthActivity.class), RC_TWITTER_LOGIN); } public void loginWithPassword() { mAuthProgressDialog.show(); ref.authWithPassword("test@firebaseuser.com", "test1234", new AuthResultHandler("password")); } private void loginAnonymously() { mAuthProgressDialog.show(); ref.authAnonymously(new AuthResultHandler("anonymous")); } }
package org.voltdb.dtxn; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Set; import junit.framework.TestCase; import org.voltdb.ClientResponseImpl; import org.voltdb.MockVoltDB; import org.voltdb.StoredProcedureInvocation; import org.voltdb.VoltDB; import org.voltdb.VoltTable; import org.voltdb.VoltTable.ColumnInfo; import org.voltdb.VoltType; import org.voltdb.fault.FaultDistributor; import org.voltdb.fault.NodeFailureFault; import org.voltcore.messaging.HostMessenger; import org.voltdb.messaging.InitiateResponseMessage; import org.voltdb.messaging.InitiateTaskMessage; import org.voltcore.network.WriteStream; import org.voltcore.utils.EstTime; public class TestDtxnInitiatorMailbox extends TestCase { static int INITIATOR_SITE_ID = 5; static int HOST_ID = 0; static int MESSAGE_SIZE = 13; MockVoltDB m_mockVolt = null; private final Map<Long, Integer> m_siteMap = new HashMap<Long, Integer>(); class MockWriteStream extends org.voltcore.network.MockWriteStream { boolean m_gotResponse; MockWriteStream() { m_gotResponse = false; } void reset() { m_gotResponse = false; } boolean gotResponse() { return m_gotResponse; } @Override public synchronized void enqueue(ByteBuffer buf) { m_gotResponse = true; notify(); } } private final HostMessenger m_mockMessenger = new HostMessenger() { }; class MockConnection extends org.voltcore.network.MockConnection { MockWriteStream m_writeStream; MockConnection(MockWriteStream writeStream) { m_writeStream = writeStream; } @Override public WriteStream writeStream() { return m_writeStream; } } class MockInitiator extends TransactionInitiator { int m_reduceSize; int m_reduceCount; MockInitiator() { m_reduceSize = 0; m_reduceCount = 0; } @Override public boolean createTransaction(long connectionId, String connectionHostname, boolean adminConnection, StoredProcedureInvocation invocation, boolean isReadOnly, boolean isSinglePartition, boolean isEveryPartition, int[] partitions, int numPartitions, Object clientData, int messageSize, long now) { return true; } @Override public boolean createTransaction(long connectionId, String connectionHostname, boolean adminConnection, long txnId, StoredProcedureInvocation invocation, boolean isReadOnly, boolean isSinglePartition, boolean isEverySite, int[] partitions, int numPartitions, Object clientData, int messageSize, long now) { return true; } @Override public long getMostRecentTxnId() { return 0; } @Override protected void increaseBackpressure(int messageSize) { } @Override protected void reduceBackpressure(int messageSize) { m_reduceCount++; m_reduceSize += messageSize; } @Override public long tick() { return 0; } @Override public void notifyExecutionSiteRejoin(ArrayList<Long> executorSiteIds) { // TODO Auto-generated method stub } @Override public Map<Long, long[]> getOutstandingTxnStats() { // TODO Auto-generated method stub return null; } @Override public void setSendHeartbeats(boolean val) { // TODO Auto-generated method stub } @Override public void sendHeartbeat(long txnId) { // TODO Auto-generated method stub } @Override public boolean isOnBackPressure() { // TODO Auto-generated method stub return false; } @Override public void removeConnectionStats(long connectionId) { // TODO Auto-generated method stub } } InFlightTxnState createTxnState(long txnId, int[] coordIds, boolean readOnly, boolean isSinglePart) { long now = EstTime.currentTimeMillis(); InFlightTxnState retval = new InFlightTxnState( txnId, coordIds[0], null, new long[]{}, readOnly, isSinglePart, new StoredProcedureInvocation(), m_testConnect, MESSAGE_SIZE, now, 0, "", false); if (coordIds.length > 1) { for (int i = 1; i < coordIds.length; i++) retval.addCoordinator(coordIds[i]); } return retval; } VoltTable[] createResultSet(String thing) { VoltTable[] retval = new VoltTable[1]; retval[0] = new VoltTable(new ColumnInfo("thing", VoltType.STRING)); retval[0].addRow(thing); return retval; } InitiateResponseMessage createInitiateResponse(long txnId, int coordId, boolean readOnly, boolean isSinglePart, boolean recovering, VoltTable[] results) { InitiateTaskMessage task = new InitiateTaskMessage(INITIATOR_SITE_ID, coordId, txnId, readOnly, isSinglePart, new StoredProcedureInvocation(), Long.MAX_VALUE); InitiateResponseMessage response = new InitiateResponseMessage(task); response.setResults(new ClientResponseImpl((byte) 0, results, ""), task); response.setRecovering(recovering); return response; } @Override public void setUp() { m_mockVolt = new MockVoltDB(); m_mockVolt.shouldIgnoreCrashes = true; m_mockVolt.addHost(HOST_ID); m_mockVolt.addPartition(0); m_mockVolt.addSite(1, HOST_ID, 0, true); m_mockVolt.addSite(0, HOST_ID, 0, true); m_mockVolt.addSite(2, HOST_ID, 0, false); m_siteMap.clear(); m_siteMap.put(0L, 0); m_siteMap.put(1L, 0); m_siteMap.put(2L, 0); m_mockVolt.setFaultDistributor(new FaultDistributor(m_mockVolt)); VoltDB.replaceVoltDBInstanceForTest(m_mockVolt); } @Override public void tearDown() throws Exception { m_mockVolt.shutdown(null); } public void testNonReplicatedBasicOps() { MockInitiator initiator = new MockInitiator(); ExecutorTxnIdSafetyState safetyState = new ExecutorTxnIdSafetyState(m_siteMap); DtxnInitiatorMailbox dim = new DtxnInitiatorMailbox(safetyState, m_mockMessenger); dim.setInitiator(initiator); dim.setHSId(INITIATOR_SITE_ID); m_testStream.reset(); // Single-partition read-only txn dim.addPendingTxn(createTxnState(0, new int[] {0}, true, true)); dim.deliver(createInitiateResponse(0, 0, true, true, false, createResultSet("dude"))); assertTrue(m_testStream.gotResponse()); assertEquals(1, initiator.m_reduceCount); assertEquals(MESSAGE_SIZE, initiator.m_reduceSize); m_testStream.reset(); // multi-partition read-only txn dim.addPendingTxn(createTxnState(1, new int[] {0}, true, false)); dim.deliver(createInitiateResponse(1, 0, true, false, false, createResultSet("dude"))); assertTrue(m_testStream.gotResponse()); assertEquals(2, initiator.m_reduceCount); assertEquals(MESSAGE_SIZE * 2, initiator.m_reduceSize); m_testStream.reset(); // Single-partition read-write txn dim.addPendingTxn(createTxnState(2, new int[] {0}, false, true)); dim.deliver(createInitiateResponse(2, 0, false, true, false, createResultSet("dude"))); assertTrue(m_testStream.gotResponse()); assertEquals(3, initiator.m_reduceCount); assertEquals(MESSAGE_SIZE * 3, initiator.m_reduceSize); m_testStream.reset(); // multi-partition read-write txn dim.addPendingTxn(createTxnState(3, new int[] {0}, false, false)); dim.deliver(createInitiateResponse(3, 0, false, false, false, createResultSet("dude"))); assertEquals(4, initiator.m_reduceCount); assertEquals(MESSAGE_SIZE * 4, initiator.m_reduceSize); assertTrue(m_testStream.gotResponse()); } // Multi-partition transactions don't differ in behavior at the initiator // so we'll only throw in the single-partition cases public void testReplicatedBasicOps() { MockInitiator initiator = new MockInitiator(); ExecutorTxnIdSafetyState safetyState = new ExecutorTxnIdSafetyState(m_siteMap); DtxnInitiatorMailbox dim = new DtxnInitiatorMailbox(safetyState, m_mockMessenger); dim.setInitiator(initiator); dim.setHSId(INITIATOR_SITE_ID); m_testStream.reset(); // Single-partition read-only txn dim.addPendingTxn(createTxnState(0, new int[] {0,1}, true, true)); dim.deliver(createInitiateResponse(0, 0, true, true, false, createResultSet("dude"))); assertTrue(m_testStream.gotResponse()); assertEquals(0, initiator.m_reduceCount); assertEquals(0, initiator.m_reduceSize); m_testStream.reset(); dim.deliver(createInitiateResponse(0, 1, true, true, false, createResultSet("dude"))); assertFalse(m_testStream.gotResponse()); assertEquals(1, initiator.m_reduceCount); assertEquals(MESSAGE_SIZE, initiator.m_reduceSize); m_testStream.reset(); // Single-partition read-write txn dim.addPendingTxn(createTxnState(2, new int[] {0,1}, false, true)); dim.deliver(createInitiateResponse(2, 0, false, true, false, createResultSet("dude"))); assertFalse(m_testStream.gotResponse()); assertEquals(1, initiator.m_reduceCount); assertEquals(MESSAGE_SIZE, initiator.m_reduceSize); dim.deliver(createInitiateResponse(2, 1, false, true, false, createResultSet("dude"))); assertTrue(m_testStream.gotResponse()); assertEquals(2, initiator.m_reduceCount); assertEquals(MESSAGE_SIZE * 2, initiator.m_reduceSize); } // Test responsing where some things are recovering // Again, only matters for single-partition work public void testRecoveringBasicOps() { MockInitiator initiator = new MockInitiator(); ExecutorTxnIdSafetyState safetyState = new ExecutorTxnIdSafetyState(m_siteMap); DtxnInitiatorMailbox dim = new DtxnInitiatorMailbox(safetyState, m_mockMessenger); dim.setInitiator(initiator); dim.setHSId(INITIATOR_SITE_ID); m_testStream.reset(); // Single-partition read-only txn dim.addPendingTxn(createTxnState(0, new int[] {0,1}, true, true)); // recovering message dim.deliver(createInitiateResponse(0, 0, true, true, true, createResultSet("fido"))); assertFalse(m_testStream.gotResponse()); assertEquals(0, initiator.m_reduceCount); assertEquals(0, initiator.m_reduceSize); m_testStream.reset(); // Single-partition read-only txn dim.addPendingTxn(createTxnState(0, new int[] {0,1}, true, true)); // recovering message dim.deliver(createInitiateResponse(0, 0, true, true, true, createResultSet("fido"))); // valid message gets sent out dim.deliver(createInitiateResponse(0, 1, true, true, false, createResultSet("dude"))); assertTrue(m_testStream.gotResponse()); assertEquals(1, initiator.m_reduceCount); assertEquals(MESSAGE_SIZE, initiator.m_reduceSize); m_testStream.reset(); // Single-partition read-only txn dim.addPendingTxn(createTxnState(0, new int[] {0,1}, true, true)); // valid message gets sent out dim.deliver(createInitiateResponse(0, 0, true, true, false, createResultSet("dude"))); // recovering message dim.deliver(createInitiateResponse(0, 1, true, true, true, createResultSet("fido"))); assertTrue(m_testStream.gotResponse()); assertEquals(2, initiator.m_reduceCount); assertEquals(MESSAGE_SIZE * 2, initiator.m_reduceSize); m_testStream.reset(); // Single-partition read-only txn dim.addPendingTxn(createTxnState(0, new int[] {0,1}, false, true)); // valid message gets sent out dim.deliver(createInitiateResponse(0, 0, false, true, false, createResultSet("dude"))); // recovering message dim.deliver(createInitiateResponse(0, 1, false, true, true, createResultSet("fido"))); assertTrue(m_testStream.gotResponse()); assertEquals(3, initiator.m_reduceCount); assertEquals(MESSAGE_SIZE * 3, initiator.m_reduceSize); m_testStream.reset(); // Single-partition read-only txn dim.addPendingTxn(createTxnState(0, new int[] {0,1}, false, true)); // recovering message dim.deliver(createInitiateResponse(0, 0, false, true, true, createResultSet("fido"))); // valid message gets sent out dim.deliver(createInitiateResponse(0, 1, false, true, false, createResultSet("dude"))); assertTrue(m_testStream.gotResponse()); assertEquals(4, initiator.m_reduceCount); assertEquals(MESSAGE_SIZE * 4, initiator.m_reduceSize); } public void testInconsistentResults() { MockInitiator initiator = new MockInitiator(); ExecutorTxnIdSafetyState safetyState = new ExecutorTxnIdSafetyState(m_siteMap); DtxnInitiatorMailbox dim = new DtxnInitiatorMailbox(safetyState, m_mockMessenger); dim.setInitiator(initiator); dim.setHSId(INITIATOR_SITE_ID); m_testStream.reset(); // Single-partition read-only txn dim.addPendingTxn(createTxnState(0, new int[] {0,1}, true, true)); dim.deliver(createInitiateResponse(0, 0, true, true, false, createResultSet("dude"))); assertTrue(m_testStream.gotResponse()); m_testStream.reset(); boolean caught = false; try { dim.deliver(createInitiateResponse(0, 1, true, true, false, createResultSet("sweet"))); } catch (RuntimeException e) { if (e.getMessage().contains("Mismatched")) { caught = true; } } assertTrue(caught); m_testStream.reset(); // Single-partition read-write txn dim.addPendingTxn(createTxnState(2, new int[] {0,1}, false, true)); dim.deliver(createInitiateResponse(2, 0, false, true, false, createResultSet("dude"))); assertFalse(m_testStream.gotResponse()); caught = false; try { dim.deliver(createInitiateResponse(2, 1, true, true, false, createResultSet("sweet"))); } catch (RuntimeException e) { if (e.getMessage().contains("Mismatched")) { caught = true; } } assertTrue(caught); } // Failure cases to test: // for read/write: // add two pending txns // -- receive one, fail the second site, verify that we get enqueue // -- fail the second site, receive one, verify that we get enqueue // -- fail both, verify ?? (exception/crash of some sort?) // -- receive both, fail one, verify ?? // replace two with three or for for tricksier cases? // have two or three different outstanding txn IDs // read-only harder since stuff lingers and there's no way to look at it public void testEarlyReadWriteFailure() { MockInitiator initiator = new MockInitiator(); ExecutorTxnIdSafetyState safetyState = new ExecutorTxnIdSafetyState(m_siteMap); DtxnInitiatorMailbox dim = new DtxnInitiatorMailbox(safetyState, m_mockMessenger); dim.setInitiator(initiator); dim.setHSId(INITIATOR_SITE_ID); m_testStream.reset(); // Single-partition read-write txn dim.addPendingTxn(createTxnState(0, new int[] {0,1}, false, true)); dim.removeSite(0); dim.deliver(createInitiateResponse(0, 1, true, true, false, createResultSet("dude"))); assertTrue(m_testStream.gotResponse()); assertEquals(1, initiator.m_reduceCount); assertEquals(MESSAGE_SIZE, initiator.m_reduceSize); } public void testMidReadWriteFailure() { MockInitiator initiator = new MockInitiator(); ExecutorTxnIdSafetyState safetyState = new ExecutorTxnIdSafetyState(m_siteMap); DtxnInitiatorMailbox dim = new DtxnInitiatorMailbox(safetyState, m_mockMessenger); dim.setInitiator(initiator); dim.setHSId(INITIATOR_SITE_ID); m_testStream.reset(); // Single-partition read-write txn dim.addPendingTxn(createTxnState(0, new int[] {0,1}, false, true)); dim.deliver(createInitiateResponse(0, 1, true, true, false, createResultSet("dude"))); dim.removeSite(0); assertTrue(m_testStream.gotResponse()); assertEquals(1, initiator.m_reduceCount); assertEquals(MESSAGE_SIZE, initiator.m_reduceSize); } public void testMultipleTxnIdMidFailure() { MockInitiator initiator = new MockInitiator(); ExecutorTxnIdSafetyState safetyState = new ExecutorTxnIdSafetyState(m_siteMap); DtxnInitiatorMailbox dim = new DtxnInitiatorMailbox(safetyState, m_mockMessenger); dim.setInitiator(initiator); dim.setHSId(INITIATOR_SITE_ID); m_testStream.reset(); // Single-partition read-write txn dim.addPendingTxn(createTxnState(0, new int[] {0,1}, false, true)); dim.addPendingTxn(createTxnState(1, new int[] {0,1}, false, true)); dim.deliver(createInitiateResponse(0, 1, true, true, false, createResultSet("dude"))); dim.deliver(createInitiateResponse(1, 1, true, true, false, createResultSet("sweet"))); dim.removeSite(0); assertTrue(m_testStream.gotResponse()); assertEquals(2, initiator.m_reduceCount); assertEquals(MESSAGE_SIZE * 2, initiator.m_reduceSize); } // public void testTotalFailure() // MockInitiator initiator = new MockInitiator(); // DtxnInitiatorQueue dut = new DtxnInitiatorQueue(SITE_ID); // dut.setInitiator(initiator); // m_testStream.reset(); // // Single-partition read-only txn // dut.addPendingTxn(createTxnState(0, 0, false, true)); // dut.addPendingTxn(createTxnState(0, 1, false, true)); // dut.removeSite(0); // dut.removeSite(1); public void testFaultNotification() throws Exception { MockInitiator initiator = new MockInitiator(); ExecutorTxnIdSafetyState safetyState = new ExecutorTxnIdSafetyState(m_siteMap); DtxnInitiatorMailbox dim = new DtxnInitiatorMailbox(safetyState, m_mockMessenger); dim.setInitiator(initiator); dim.setHSId(INITIATOR_SITE_ID); m_testStream.reset(); // Single-partition read-write txn dim.addPendingTxn(createTxnState(0, new int[] {0,1}, false, true)); dim.deliver(createInitiateResponse(0, 1, true, true, false, createResultSet("dude"))); synchronized (m_testStream) { throw new UnsupportedOperationException("Fault distributor isn't working yet"); // NodeFailureFault node_failure = new NodeFailureFault( // HOST_ID, // Arrays.asList(new Long[] { 2L }),// the non exec site in setUp() // "localhost"); // VoltDB.instance().getFaultDistributor().reportFault(node_failure); // m_testStream.wait(10000); } // Thread.sleep(100); // assertTrue(m_testStream.gotResponse()); // assertEquals(1, initiator.m_reduceCount); // assertEquals(MESSAGE_SIZE, initiator.m_reduceSize); } MockWriteStream m_testStream = new MockWriteStream(); MockConnection m_testConnect = new MockConnection(m_testStream); }
package com.hacktx.electron.activities; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.TextView; import com.google.android.gms.vision.CameraSource; import com.google.android.gms.vision.MultiProcessor; import com.google.android.gms.vision.barcode.Barcode; import com.google.android.gms.vision.barcode.BarcodeDetector; import com.hacktx.electron.R; import com.hacktx.electron.utils.PreferencesUtils; import com.hacktx.electron.vision.BarcodeTrackerFactory; import com.hacktx.electron.vision.CameraSourcePreview; import com.hacktx.electron.vision.GraphicOverlay; import com.hacktx.electron.vision.VisionCallback; import java.io.IOException; public class MainActivity extends AppCompatActivity { private CameraSourcePreview mPreview; private GraphicOverlay mGraphicOverlay; private CameraSource mCameraSource; private boolean scanning; @Override public void onCreate(Bundle state) { super.onCreate(state); checkIfShowWelcomeActivity(); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); if (toolbar != null) { setSupportActionBar(toolbar); getSupportActionBar().setTitle(R.string.app_name); } mPreview = (CameraSourcePreview) findViewById(R.id.preview); mGraphicOverlay = (GraphicOverlay) findViewById(R.id.overlay); BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(this).build(); BarcodeTrackerFactory barcodeFactory = new BarcodeTrackerFactory(mGraphicOverlay, new VisionCallback() { @Override public void onFound(final Barcode barcode) { runOnUiThread(new Runnable() { public void run() { if(scanning && barcode.format == Barcode.QR_CODE) { scanning = false; showConfirmationDialog(barcode.rawValue); } } }); } }); barcodeDetector.setProcessor(new MultiProcessor.Builder<>(barcodeFactory).build()); mCameraSource = new CameraSource.Builder(this, barcodeDetector) .setFacing(CameraSource.CAMERA_FACING_BACK) .setRequestedPreviewSize(1600, 1024) .build(); startCameraSource(); } private void startCameraSource() { try { mPreview.start(mCameraSource, mGraphicOverlay); scanning = true; } catch (IOException e) { mCameraSource.release(); mCameraSource = null; } } @Override protected void onResume() { super.onResume(); startCameraSource(); } @Override protected void onPause() { super.onPause(); mPreview.stop(); } @Override protected void onDestroy() { super.onDestroy(); mCameraSource.release(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.action_enter_email: showEmailDialog(); return true; case R.id.action_settings: startActivity(new Intent(this, PreferencesActivity.class)); return true; } return super.onOptionsItemSelected(item); } private void checkIfShowWelcomeActivity() { if (PreferencesUtils.getFirstLaunch(this) || PreferencesUtils.getVolunteerId(this).isEmpty()) { startActivity(new Intent(this, WelcomeActivity.class)); finish(); } } private void showEmailDialog() { final Dialog dialog = new Dialog(this); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.dialog_email); WindowManager.LayoutParams params = dialog.getWindow().getAttributes(); params.width = WindowManager.LayoutParams.MATCH_PARENT; dialog.getWindow().setAttributes(params); dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); dialog.show(); final EditText emailEditText = (EditText) dialog.findViewById(R.id.emailDialogEditText); emailEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE) { dialog.dismiss(); showConfirmationDialog(emailEditText.getText().toString()); } return true; } }); dialog.findViewById(R.id.emailDialogCancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); dialog.findViewById(R.id.emailDialogOk).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); showConfirmationDialog(emailEditText.getText().toString()); } }); } private void showConfirmationDialog(String email) { AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle); builder.setTitle(R.string.dialog_verify_title); builder.setMessage(email); builder.setPositiveButton(R.string.dialog_verify_approve, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO: Notify Nucleus dialog.dismiss(); scanning = true; } }); builder.setNegativeButton(R.string.dialog_verify_deny, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); scanning = true; } }); builder.show(); } }
package com.lvds2000.AcornAPI.course; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.lvds2000.AcornAPI.auth.RegistrationManager; import com.lvds2000.AcornAPI.enrol.EnrolledCourse; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class CourseSearcher{ private OkHttpClient client; private static OkHttpClient iitClient = new OkHttpClient.Builder().build();; private RegistrationManager registrationManager; public CourseSearcher(OkHttpClient client, RegistrationManager registrationManager){ this.client = client; this.registrationManager = registrationManager; this.iitClient = new OkHttpClient.Builder().build(); } public EnrolledCourse searchCourse(String courseCode, String courseSessionCode, String sectionCode, int registrationIndex){ return null; } /** * iit * @param r * @return */ public static void getCourseInfo(String code, final ResponseListener r) { Request request = new Request.Builder() .url("https://timetable.iit.artsci.utoronto.ca/api/20189/courses?code=" + code) .get() .build(); try { iitClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { r.failure(); } @Override public void onResponse(Call call, Response response) throws IOException { String body = response.body().string(); if(body.trim().equals("[]")) { r.failure(); return; } Map<String, JsonObject> courses = new HashMap<String, JsonObject>(); JsonParser parser = new JsonParser(); JsonObject obj = parser.parse(body).getAsJsonObject(); for(Entry<String, JsonElement> entry: obj.entrySet()){ String courseCode = entry.getKey().substring(0, 8); if(courses.keySet().contains(courseCode)) continue; courses.put(courseCode, entry.getValue().getAsJsonObject()); } r.response(courses); } }); } catch (Exception e) { e.printStackTrace(); } } }
package com.marverenic.music.instances; import android.content.Context; import android.os.Parcel; import android.os.Parcelable; import com.crashlytics.android.Crashlytics; import com.google.gson.annotations.SerializedName; import com.marverenic.music.Library; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; public class AutoPlaylist extends Playlist implements Parcelable { /** * Value representing an unlimited amount of song entries */ public static final int UNLIMITED_ENTRIES = -1; /** * An empty auto playlist instance */ public static final AutoPlaylist EMPTY = new AutoPlaylist(-1, "", UNLIMITED_ENTRIES, Rule.Field.NAME, Rule.Field.NAME, true, true, true, Rule.EMPTY); /** * How many items can be stored in this playlist. Default is unlimited */ @SerializedName("maximumEntries") public int maximumEntries; /** * The field to look at when truncating the playlist. Must be a member of {@link Rule.Field}. * {@link Rule.Field#ID} will yield a random trim */ @SerializedName("truncateMethod") public int truncateMethod; /** * Whether to trim the playlist ascending (A-Z, oldest to newest, or 0-infinity). * If false, sort descending (Z-A, newest to oldest, or infinity-0). */ @SerializedName("truncateAscending") public boolean truncateAscending; /** * Whether or not a song has to match all rules in order to appear in the playlist. */ @SerializedName("matchAllRules") public boolean matchAllRules; /** * The rules to match when building the playlist */ @SerializedName("rules") public Rule[] rules; /** * The field to look at when sorting the playlist. Must be a member of {@link Rule.Field} and * cannot be {@link Rule.Field#ID} */ @SerializedName("sortMethod") public int sortMethod; /** * Whether to sort the playlist ascending (A-Z, oldest to newest, or 0-infinity). * If false, sort descending (Z-A, newest to oldest, or infinity-0). * Default is true. */ @SerializedName("sortAscending") public boolean sortAscending; /** * AutoPlaylist Creator * @param playlistId A unique ID for the Auto Playlist. Must be unique and not conflict with the * MediaStore * @param playlistName The name given to this playlist by the user * @param maximumEntries The maximum number of songs this playlist should have. Use * {@link AutoPlaylist#UNLIMITED_ENTRIES} for no limit. This limit will * be applied after the list has been sorted. Any extra entries will be * truncated. * @param sortMethod The order the songs will be sorted (Must be one of * {@link AutoPlaylist.Rule.Field} and can't be ID * @param sortAscending Whether to sort this playlist ascending (A-Z or 0-infinity) or not * @param matchAllRules Whether or not all rules have to be matched for a song to appear in this * playlist * @param rules The rules that songs must follow in order to appear in this playlist */ public AutoPlaylist (int playlistId, String playlistName, int maximumEntries, int sortMethod, int truncateMethod, boolean truncateAscending, boolean sortAscending, boolean matchAllRules, Rule... rules){ super(playlistId, playlistName); this.maximumEntries = maximumEntries; this.matchAllRules = matchAllRules; this.rules = rules; this.truncateMethod = truncateMethod; this.truncateAscending = truncateAscending; this.sortMethod = sortMethod; this.sortAscending = sortAscending; } /** * Duplicate a playlist. The instantiated playlist will be completely independent of its parent * @param playlist The AutoPlaylist to become a copy of */ public AutoPlaylist(AutoPlaylist playlist) { this( playlist.playlistId, playlist.playlistName, playlist.maximumEntries, playlist.sortMethod, playlist.truncateMethod, playlist.truncateAscending, playlist.sortAscending, playlist.matchAllRules); this.rules = new Rule[playlist.rules.length]; for (int i = 0; i < this.rules.length; i++) { this.rules[i] = new Rule(playlist.rules[i]); } } /** * Generate the list of songs that match all rules for this playlist. * @param context A {@link Context} used for various operations like reading play counts and * checking playlist rules * @return An {@link ArrayList} of Songs that contains all songs in the library which match * the rules of this playlist */ public ArrayList<Song> generatePlaylist(Context context){ // In the event that the play counts in this process have gone stale, make // sure they're current Library.loadPlayCounts(context); ArrayList<Song> songs; if (matchAllRules) { songs = new ArrayList<>(Library.getSongs()); for (Rule r : rules) { if (r != null) { songs = r.evaluate(songs, context); } } } else{ HashSet<Song> songSet = new HashSet<>(); // Use a Set to prevent duplicates final ArrayList<Song> allSongs = new ArrayList<>(Library.getSongs()); for (Rule r : rules){ songSet.addAll(r.evaluate(allSongs, context)); } songs = new ArrayList<>(songSet); } return sort(trim(sort(songs, truncateMethod, truncateAscending)), sortMethod, sortAscending); } /** * Sorts an {@link ArrayList} of songs as specified by {@link AutoPlaylist#sortMethod} and * {@link AutoPlaylist#sortAscending}. Used in {@link AutoPlaylist#generatePlaylist(Context)} * @param in The {@link ArrayList} to be sorted * @return The original, sorted, {@link ArrayList} for convenience */ private static ArrayList<Song> sort(ArrayList<Song> in, int sortMethod, final boolean sortAscending){ switch (sortMethod){ case Rule.Field.ID: Collections.shuffle(in); break; case Rule.Field.NAME: Library.sortSongList(in); break; case Rule.Field.PLAY_COUNT: Collections.sort(in, new Comparator<Song>() { @Override public int compare(Song s1, Song s2) { if (sortAscending) return s1.playCount() - s2.playCount(); else return s2.playCount() - s1.playCount(); } }); break; case Rule.Field.SKIP_COUNT: Collections.sort(in, new Comparator<Song>() { @Override public int compare(Song s1, Song s2) { if (sortAscending) return s1.skipCount() - s2.skipCount(); else return s2.skipCount() - s1.skipCount(); } }); break; case Rule.Field.DATE_ADDED: Collections.sort(in, new Comparator<Song>() { @Override public int compare(Song s1, Song s2) { if (sortAscending) return s1.dateAdded - s2.dateAdded; else return s2.dateAdded - s1.dateAdded; } }); break; case Rule.Field.DATE_PLAYED: Collections.sort(in, new Comparator<Song>() { @Override public int compare(Song s1, Song s2) { if (sortAscending) return s1.playDate() - s2.playDate(); else return s2.playDate() - s1.playDate(); } }); break; case Rule.Field.YEAR: Collections.sort(in, new Comparator<Song>() { @Override public int compare(Song s1, Song s2) { if (sortAscending) return s1.year - s2.year; else return s2.year - s1.year; } }); break; } return in; } /** * Trims an {@link ArrayList} of Songs so that it contains no more songs than * {@link AutoPlaylist#maximumEntries}. Extra songs are truncated out of the list. * Used in {@link AutoPlaylist#generatePlaylist(Context)} * @param in The {@link ArrayList} to be trimmed * @return A new {@link ArrayList} that satisfies the maximum entry size */ private ArrayList<Song> trim(ArrayList<Song> in){ if (in.size() <= maximumEntries || maximumEntries == UNLIMITED_ENTRIES){ return in; } ArrayList<Song> trimmed = new ArrayList<>(maximumEntries); for (int i = 0; i < maximumEntries; i++){ trimmed.add(in.get(i)); } return trimmed; } /** * Used to determine if the rules of this AutoPlaylist are equal to that of another playlist. * This is different from .equals() because .equals() looks at ID's only which is required * behavior in other areas of the app. * @param other The AutoPlaylist to compare to * @return true if these AutoPlaylists have the same rules */ public boolean isEqual(AutoPlaylist other) { return other == this || other != null && other.matchAllRules == this.matchAllRules && other.sortAscending == this.sortAscending && other.truncateAscending == this.truncateAscending && other.maximumEntries == this.maximumEntries && other.playlistName.equals(this.playlistName); } public static final Parcelable.Creator<Parcelable> CREATOR = new Parcelable.Creator<Parcelable>() { public AutoPlaylist createFromParcel(Parcel in) { return new AutoPlaylist(in); } public AutoPlaylist[] newArray(int size) { return new AutoPlaylist[size]; } }; private AutoPlaylist(Parcel in) { super(in); maximumEntries = in.readInt(); matchAllRules = in.readByte() == 1; rules = in.createTypedArray(Rule.CREATOR); sortMethod = in.readInt(); truncateMethod = in.readInt(); truncateAscending = in.readByte() == 1; sortAscending = in.readByte() == 1; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeInt(maximumEntries); dest.writeByte((byte) ((matchAllRules) ? 1 : 0)); dest.writeTypedArray(rules, 0); dest.writeInt(sortMethod); dest.writeInt(truncateMethod); dest.writeByte((byte) ((truncateAscending) ? 1 : 0)); dest.writeByte((byte) ((sortAscending)? 1 : 0)); } public Rule[] getRules() { return rules.clone(); } public static class Rule implements Parcelable { public static final class Type { public static final int PLAYLIST = 0; public static final int SONG = 1; public static final int ARTIST = 2; public static final int ALBUM = 3; public static final int GENRE = 4; } public static final class Field { public static final int ID = 5; public static final int NAME = 6; public static final int PLAY_COUNT = 7; public static final int SKIP_COUNT = 8; public static final int YEAR = 9; public static final int DATE_ADDED = 10; public static final int DATE_PLAYED = 11; } public static final class Match { public static final int EQUALS = 12; public static final int NOT_EQUALS = 13; public static final int CONTAINS = 14; public static final int NOT_CONTAINS = 15; public static final int LESS_THAN = 16; public static final int GREATER_THAN = 17; } public static final Rule EMPTY = new Rule(Type.SONG, Field.NAME, Match.CONTAINS, ""); public int type; public int match; public int field; public String value; public Rule(int type, int field, int match, String value){ validate(type, field, match, value); this.type = type; this.field = field; this.match = match; this.value = value; } public Rule(Rule rule) { this(rule.type, rule.field, rule.match, rule.value); } private Rule(Parcel in) { type = in.readInt(); match = in.readInt(); field = in.readInt(); value = in.readString(); } public boolean equals(Object o) { if (!(o instanceof Rule)){ return false; } if (this == o) { return true; } Rule other = (Rule) o; return this.type == other.type && this.field == other.field && this.match == other.match && this.value.equals(other.value); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(type); dest.writeInt(match); dest.writeInt(field); dest.writeString(value); } public static final Parcelable.Creator<Rule> CREATOR = new Parcelable.Creator<Rule>() { public Rule createFromParcel(Parcel in) { return new Rule(in); } public Rule[] newArray(int size) { return new Rule[size]; } }; private void validate(int type, int field, int match, String value){ // Only Songs have play counts and skip counts if ((type != Type.SONG) && (field == Field.PLAY_COUNT || field == Field.SKIP_COUNT)) { throw new IllegalArgumentException(type + " type does not have field " + field); } // Only Songs have years if (type != Type.SONG && field == Field.YEAR){ throw new IllegalArgumentException(type + " type does not have field " + field); } // Only Songs have dates added if (type != Type.SONG && field == Field.DATE_ADDED){ throw new IllegalArgumentException(type + " type does not have field " + field); } if (field == Field.ID){ // IDs can only be compared by equals or !equals if (match == Match.CONTAINS || match == Match.NOT_CONTAINS || match == Match.LESS_THAN || match == Match.GREATER_THAN){ throw new IllegalArgumentException("ID cannot be compared by method " + match); } // Make sure the value is actually a number try{ //noinspection ResultOfMethodCallIgnored Long.parseLong(value); } catch (NumberFormatException e){ Crashlytics.logException(e); throw new IllegalArgumentException("ID cannot be compared to value " + value); } } else if (field == Field.NAME){ // Names can't be compared by < or >... that doesn't even make sense... if (match == Match.GREATER_THAN || match == Match.LESS_THAN){ throw new IllegalArgumentException("Name cannot be compared by method " + match); } } else if (field == Field.SKIP_COUNT || field == Field.PLAY_COUNT || field == Field.YEAR || field == Field.DATE_ADDED){ // Numeric values can't be compared by contains or !contains if (match == Match.CONTAINS || match == Match.NOT_CONTAINS){ throw new IllegalArgumentException(field + " cannot be compared by method " + match); } // Make sure the value is actually a number try{ //noinspection ResultOfMethodCallIgnored Long.parseLong(value); } catch (NumberFormatException e){ Crashlytics.logException(e); throw new IllegalArgumentException("ID cannot be compared to value " + value); } } } /** * Evaluate this rule on a data set * @param in The data to evaluate this rule on. Items in this list will be returned by this * method if they match the query. Nothing is removed from the original list. * @return The filtered data as an {@link ArrayList<Song>} that only contains songs that * match this rule that were in the original data set */ public ArrayList<Song> evaluate (ArrayList<Song> in, Context context){ switch (type){ case Type.PLAYLIST: return evaluatePlaylist(in, context); case Type.SONG: return evaluateSong(in, context); case Type.ARTIST: return evaluateArtist(in); case Type.ALBUM: return evaluateAlbum(in); case Type.GENRE: return evaluateGenre(in); } return null; } /** * Logic to evaluate playlist rules. See {@link AutoPlaylist.Rule#evaluate(ArrayList, Context)} * @param in The data to evaluate this rule on. Items in this list will be returned by this * method if they match the query. Nothing is removed from the original list. * @return The filtered data as an {@link ArrayList<Song>} that only contains songs that * match this rule that were in the original data set */ private ArrayList<Song> evaluatePlaylist (ArrayList<Song> in, Context context){ ArrayList<Song> filteredSongs = new ArrayList<>(); switch (field){ case Field.ID: final long id = Long.parseLong(value); for (Playlist p : Library.getPlaylists()){ if (p.playlistId == id ^ match == Match.NOT_EQUALS){ for (Song s : Library.getPlaylistEntries(context, p)){ if (in.contains(s) && !filteredSongs.contains(s)) filteredSongs.add(s); } } } break; case Field.NAME: if (match == Match.EQUALS || match == Match.NOT_EQUALS){ for (Playlist p : Library.getPlaylists()){ if (p.playlistName.equalsIgnoreCase(value) ^ match == Match.NOT_EQUALS){ for (Song s : Library.getPlaylistEntries(context, p)){ if (in.contains(s) && !filteredSongs.contains(s)) filteredSongs.add(s); } } } } else if (match == Match.CONTAINS || match == Match.NOT_CONTAINS){ for (Playlist p : Library.getPlaylists()){ if (p.playlistName.contains(value) ^ match == Match.NOT_EQUALS){ for (Song s : Library.getPlaylistEntries(context, p)){ if (in.contains(s) && !filteredSongs.contains(s)) filteredSongs.add(s); } } } } break; } return filteredSongs; } /** * Logic to evaluate song rules. See {@link AutoPlaylist.Rule#evaluate(ArrayList, Context)} * @param in The data to evaluate this rule on. Items in this list will be returned by this * method if they match the query. Nothing is removed from the original list * @param context A Context used to scan play and skip counts if necessary * @return The filtered data as an {@link ArrayList<Song>} that only contains songs that * match this rule that were in the original data set */ private ArrayList<Song> evaluateSong (ArrayList<Song> in, Context context){ ArrayList<Song> filteredSongs = new ArrayList<>(); switch (field){ case Field.ID: final long id = Long.parseLong(value); for (Song s : in){ if (s.songId == id ^ match == Match.NOT_EQUALS){ filteredSongs.add(s); } } break; case Field.NAME: if (match == Match.EQUALS || match == Match.NOT_EQUALS){ for (Song s : in){ if (s.songName.equals(value) ^ match == Match.NOT_EQUALS){ filteredSongs.add(s); } } } else if (match == Match.CONTAINS || match == Match.NOT_CONTAINS){ for (Song s : in){ if (s.songName.contains(value) ^ match == Match.NOT_CONTAINS){ filteredSongs.add(s); } } } break; case Field.PLAY_COUNT: final long playCount = Long.parseLong(value); if (match == Match.EQUALS || match == Match.NOT_EQUALS){ for (Song s : in){ if (s.playCount() == playCount ^ match == Match.NOT_EQUALS){ filteredSongs.add(s); } } } else if (match == Match.LESS_THAN || match == Match.GREATER_THAN){ for (Song s : in){ if (s.playCount() != playCount && (s.playCount() < playCount ^ match == Match.GREATER_THAN)){ filteredSongs.add(s); } } } break; case Field.SKIP_COUNT: final long skipCount = Long.parseLong(value); if (match == Match.EQUALS || match == Match.NOT_EQUALS){ for (Song s : in){ if (s.skipCount() == skipCount ^ match == Match.NOT_EQUALS){ filteredSongs.add(s); } } } else if (match == Match.LESS_THAN || match == Match.GREATER_THAN){ for (Song s : in){ if (s.skipCount() != skipCount && (s.skipCount() < skipCount ^ match == Match.GREATER_THAN)){ filteredSongs.add(s); } } } break; case Field.YEAR: final int year = Integer.parseInt(value); if (match == Match.EQUALS || match == Match.NOT_EQUALS){ for (Song s : in){ if (s.year == year ^ match == Match.NOT_EQUALS){ filteredSongs.add(s); } } } else if (match == Match.LESS_THAN || match == Match.GREATER_THAN){ for (Song s : in){ if (s.year < year ^ match == Match.GREATER_THAN){ filteredSongs.add(s); } } } break; case Field.DATE_ADDED: final int date = Integer.parseInt(value); if (match == Match.EQUALS || match == Match.NOT_EQUALS){ for (Song s : in){ // Look at the day the song was added, not the time // (This value is still in seconds) int dayAdded = s.dateAdded - s.dateAdded % 86400; // 24 * 60 * 60 if (dayAdded == date ^ match == Match.NOT_EQUALS){ filteredSongs.add(s); } } } else if (match == Match.LESS_THAN || match == Match.GREATER_THAN){ for (Song s : in){ // Look at the day the song was added, not the time // (This value is still in seconds) int dayAdded = s.dateAdded - s.dateAdded % 86400; // 24 * 60 * 60 if (dayAdded < date ^ match == Match.GREATER_THAN){ filteredSongs.add(s); } } } break; case Field.DATE_PLAYED: final int playDate = Integer.parseInt(value); if (match == Match.EQUALS || match == Match.NOT_EQUALS) { for (Song s : in){ // Look at the day the song was added, not the time // (This value is still in seconds) int dayAdded = s.playDate(); dayAdded -= dayAdded % 86400; // 24 * 60 * 60 if (dayAdded == playDate ^ match == Match.NOT_EQUALS) { filteredSongs.add(s); } } } else if (match == Match.LESS_THAN || match == Match.GREATER_THAN) { for (Song s : in){ // Look at the day the song was added, not the time // (This value is still in seconds) int dayAdded = s.playDate(); dayAdded -= dayAdded % 86400; // 24 * 60 * 60 if (dayAdded < playDate ^ match == Match.GREATER_THAN) { filteredSongs.add(s); } } } break; } return filteredSongs; } /** * Logic to evaluate artist rules. See {@link AutoPlaylist.Rule#evaluate(ArrayList, Context)} * @param in The data to evaluate this rule on. Items in this list will be returned by this * method if they match the query. Nothing is removed from the original list. * @return The filtered data as an {@link ArrayList<Song>} that only contains songs that * match this rule that were in the original data set */ private ArrayList<Song> evaluateArtist (ArrayList<Song> in){ ArrayList<Song> filteredSongs = new ArrayList<>(); switch (field){ case Field.ID: final long id = Long.parseLong(value); for (Song s : in){ if (s.artistId == id ^ match == Match.NOT_EQUALS){ filteredSongs.add(s); } } break; case Field.NAME: if (match == Match.EQUALS || match == Match.NOT_EQUALS){ for (Song s : in){ if (s.artistName.equals(value) ^ match == Match.NOT_EQUALS){ filteredSongs.add(s); } } } else if (match == Match.CONTAINS || match == Match.NOT_CONTAINS){ for (Song s : in){ if (s.artistName.contains(value) ^ match == Match.NOT_CONTAINS){ filteredSongs.add(s); } } } break; } return filteredSongs; } /** * Logic to evaluate album rules. See {@link AutoPlaylist.Rule#evaluate(ArrayList, Context)} * @param in The data to evaluate this rule on. Items in this list will be returned by this * method if they match the query. Nothing is removed from the original list. * @return The filtered data as an {@link ArrayList<Song>} that only contains songs that * match this rule that were in the original data set */ private ArrayList<Song> evaluateAlbum (ArrayList<Song> in){ ArrayList<Song> filteredSongs = new ArrayList<>(); switch (field) { case Field.ID: final long id = Long.parseLong(value); for (Song s : in) { if (s.albumId == id ^ match == Match.NOT_EQUALS){ filteredSongs.add(s); } } break; case Field.NAME: if (match == Match.EQUALS || match == Match.NOT_EQUALS) { for (Song s : in) { if (s.albumName.equals(value) ^ match == Match.NOT_EQUALS){ filteredSongs.add(s); } } } else if (match == Match.CONTAINS || match == Match.NOT_CONTAINS) { for (Song s : in) { if (s.albumName.contains(value) ^ match == Match.NOT_CONTAINS){ filteredSongs.add(s); } } } break; } return filteredSongs; } /** * Logic to evaluate genre rules. See {@link AutoPlaylist.Rule#evaluate(ArrayList, Context)} * @param in The data to evaluate this rule on. Items in this list will be returned by this * method if they match the query. Nothing is removed from the original list. * @return The filtered data as an {@link ArrayList<Song>} that only contains songs that * match this rule that were in the original data set */ private ArrayList<Song> evaluateGenre (ArrayList<Song> in){ ArrayList<Song> filteredSongs = new ArrayList<>(); switch (field) { case Field.ID: final Long id = Long.parseLong(value); for (Song s : in) { if (s.genreId == id ^ match == Match.NOT_EQUALS) filteredSongs.add(s); } break; case Field.NAME: if (match == Match.EQUALS || match == Match.NOT_EQUALS){ for (Genre g : Library.getGenres()){ if (g.genreName.equals(value) ^ match == Match.NOT_EQUALS) { for (Song s : in) { if (s.genreId == g.genreId) { filteredSongs.add(s); } } } } } else if (match == Match.CONTAINS || match == Match.NOT_CONTAINS){ for (Genre g : Library.getGenres()){ if (g.genreName.contains(value) ^ match == Match.NOT_CONTAINS) { for (Song s : in) { if (s.genreId == g.genreId) { filteredSongs.add(s); } } } } } break; } return filteredSongs; } } }
package com.mdg.droiders.samagra.shush; import android.Manifest; import android.app.NotificationManager; import android.content.ContentValues; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.Switch; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesNotAvailableException; import com.google.android.gms.common.GooglePlayServicesRepairableException; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.PendingResult; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.places.Place; import com.google.android.gms.location.places.PlaceBuffer; import com.google.android.gms.location.places.Places; import com.google.android.gms.location.places.ui.PlacePicker; import com.mdg.droiders.samagra.shush.data.PlacesContract; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LoaderManager.LoaderCallbacks<Cursor>{ //constants private static final String LOG_TAG = "MainActivity"; private static final int PERMISSIONS_REQUEST_FINE_LOCATION = 111; private static final int PLACE_PICKER_REQUEST = 1; //member variables private PlaceListAdapter mAdapter; private RecyclerView mRecyclerView; private Button addPlaceButton; private GoogleApiClient mClient; private Geofencing mGeofencing; private boolean mIsEnabled; private CheckBox mRingerPermissionCheckBox; /** * Called when the activity is starting. * * @param savedInstanceState Bundle that contains the data provided to onSavedInstanceState */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mRecyclerView = (RecyclerView) findViewById(R.id.places_list_recycler_view); mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mAdapter = new PlaceListAdapter(this,null); mRecyclerView.setAdapter(mAdapter); mRingerPermissionCheckBox = (CheckBox) findViewById(R.id.ringer_permissions_checkbox); mRingerPermissionCheckBox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onRingerPermissionsClicked(); } }); Switch onOffSwitch = (Switch) findViewById(R.id.enable_switch); mIsEnabled = getPreferences(MODE_PRIVATE).getBoolean(getString(R.string.setting_enabled),false); onOffSwitch.setChecked(mIsEnabled); onOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit(); editor.putBoolean(getString(R.string.setting_enabled),isChecked); editor.commit(); if (isChecked) mGeofencing.registerAllGeofences(); else mGeofencing.unRegisterAllGeofences(); } }); addPlaceButton = (Button) findViewById(R.id.add_location_button); addPlaceButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onAddPlaceButtonClicked(); } }); mClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .addApi(Places.GEO_DATA_API) .enableAutoManage(this,this) .build(); mGeofencing = new Geofencing(mClient,this); } /** * Button click event handler for the add place button. */ private void onAddPlaceButtonClicked() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED){ Toast.makeText(this, getString(R.string.need_location_permission_message), Toast.LENGTH_SHORT).show(); return; } Toast.makeText(this, getString(R.string.location_permissions_granted_message), Toast.LENGTH_SHORT).show(); try { PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder(); Intent placePickerIntent = builder.build(this); startActivityForResult(placePickerIntent,PLACE_PICKER_REQUEST); } catch (GooglePlayServicesRepairableException e) { e.printStackTrace(); } catch (GooglePlayServicesNotAvailableException e) { e.printStackTrace(); } } /*** * Called when the Place Picker Activity returns back with a selected place (or after canceling) * * @param requestCode The request code passed when calling startActivityForResult * @param resultCode The result code specified by the second activity * @param data The Intent that carries the result data. */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode==PLACE_PICKER_REQUEST&&resultCode==RESULT_OK){ Place place = PlacePicker.getPlace(this,data); if (place==null){ Log.i(LOG_TAG,"No place selected"); return; } String placeName = place.getName().toString(); String placeAddress = place.getAddress().toString(); String placeId = place.getId(); ContentValues values = new ContentValues(); values.put(PlacesContract.PlaceEntry.COLUMN_PLACE_ID,placeId); getContentResolver().insert(PlacesContract.PlaceEntry.CONTENT_URI,values); refreshPlacesData(); } } @Override protected void onResume() { super.onResume(); CheckBox locationPermissionsCheckBox = (CheckBox) findViewById(R.id.location_permission_checkbox); if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){ locationPermissionsCheckBox.setChecked(false); } else { locationPermissionsCheckBox.setChecked(true); locationPermissionsCheckBox.setEnabled(false); } NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); if (Build.VERSION.SDK_INT>=24 && !notificationManager.isNotificationPolicyAccessGranted()){ mRingerPermissionCheckBox.setChecked(false); } else { mRingerPermissionCheckBox.setChecked(true); mRingerPermissionCheckBox.setEnabled(false); } } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { return null; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { } @Override public void onLoaderReset(Loader<Cursor> loader) { } /** * Called when the google API client is successfully connected. * @param bundle Bundle of data provided to the clients by google play services. */ @Override public void onConnected(@Nullable Bundle bundle) { Log.i(LOG_TAG,"Api connection successful"); Toast.makeText(this, "onConnected", Toast.LENGTH_SHORT).show(); refreshPlacesData(); } /** * Called when the google API client is suspended * @param cause The reason for the disconnection. Defined by the constant CAUSE_*. */ @Override public void onConnectionSuspended(int cause) { Log.i(LOG_TAG,"API Client connection suspended."); } /** * Called when the google API client failed to connect to the PlayServices. * @param connectionResult A coonectionResult that can be used to solve the error. */ @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { Log.i(LOG_TAG,"API Connection client suspended."); Toast.makeText(this, "onConectionFailed", Toast.LENGTH_SHORT).show(); } public void refreshPlacesData(){ Uri uri = PlacesContract.PlaceEntry.CONTENT_URI; Cursor dataCursor = getContentResolver().query(uri, null, null, null,null,null); if (dataCursor==null||dataCursor.getCount()==0) return; List<String> placeIds = new ArrayList<String>(); while (dataCursor.moveToNext()){ placeIds.add(dataCursor.getString(dataCursor.getColumnIndex(PlacesContract.PlaceEntry.COLUMN_PLACE_ID))); } PendingResult<PlaceBuffer> placeBufferPendingResult = Places.GeoDataApi.getPlaceById(mClient, placeIds.toArray(new String[placeIds.size()])); placeBufferPendingResult.setResultCallback(new ResultCallback<PlaceBuffer>() { @Override public void onResult(@NonNull PlaceBuffer places) { mAdapter.swapPlaces(places); mGeofencing.updateGeofencesList(places); if (mIsEnabled) mGeofencing.registerAllGeofences(); } }); } private void onRingerPermissionsClicked(){ Intent intent = new Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS); startActivity(intent); } public void onLocationPermissionClicked (View view){ ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_FINE_LOCATION); } }
package com.tpb.hn.viewer.fragments; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.widget.NestedScrollView; import android.support.v4.widget.SwipeRefreshLayout; import android.text.Html; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.google.android.gms.analytics.HitBuilders; import com.google.android.gms.analytics.Tracker; import com.tpb.hn.Analytics; import com.tpb.hn.R; import com.tpb.hn.data.Item; import com.tpb.hn.network.Loader; import com.tpb.hn.settings.SharedPrefsController; import com.tpb.hn.viewer.FragmentPagerAdapter; import com.tpb.hn.viewer.ViewerActivity; import com.tpb.hn.viewer.views.HintingSeekBar; import com.tpb.hn.viewer.views.spritzer.ClickableTextView; import com.tpb.hn.viewer.views.spritzer.SpritzerTextView; import org.json.JSONException; import org.json.JSONObject; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.OnLongClick; import butterknife.OnTouch; import butterknife.Unbinder; public class SkimmerFragment extends LoadingFragment implements Loader.ItemLoader, Loader.TextLoader, FragmentPagerAdapter.FragmentCycleListener { private static final String TAG = SkimmerFragment.class.getSimpleName(); @BindView(R.id.skimmer_text_view) SpritzerTextView mTextView; @BindView(R.id.skimmer_text_body) ClickableTextView mTextBody; @BindView(R.id.skimmer_progress) HintingSeekBar mSkimmerProgress; @BindView(R.id.skimmer_error_textview) TextView mErrorView; @BindView(R.id.skimmer_body_scrollview) NestedScrollView mBodyScrollview; @BindView(R.id.spritzer_swiper) SwipeRefreshLayout mSwiper; private Tracker mTracker; private Unbinder unbinder; private ViewerActivity mParent; private Item mItem; private boolean mIsWaitingForAttach = false; private String mArticle; private boolean mBodyEnabled; @Override View createView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { final View inflated = inflater.inflate(R.layout.fragment_skimmer, container, false); mTracker = ((Analytics) getActivity().getApplication()).getDefaultTracker(); unbinder = ButterKnife.bind(this, inflated); final SharedPrefsController prefs = SharedPrefsController.getInstance(getContext()); if(prefs.showSeekBarHint()) { mSkimmerProgress.setPercentageProvider(); mSkimmerProgress.setTextSize(16); mSkimmerProgress.setTextColor(getResources().getColor(R.color.colorPrimaryTextInverse)); } mTextView.attachSeekBar(mSkimmerProgress); mBodyEnabled = prefs.getSkimmerBody(); if(mBodyEnabled) { mTextBody.setVisibility(View.VISIBLE); mTextView.attachScrollView(mBodyScrollview); mTextBody.setListener((pos) -> { mTextView.setPosition(pos); mTextBody.highlightWord(pos + 1); }); } mSwiper.setOnRefreshListener(() -> itemLoaded(mItem)); if(mContentReady) { setupSkimmer(); } else if(savedInstanceState != null) { if(savedInstanceState.getString("mArticle") != null) { mArticle = savedInstanceState.getString("mArticle"); setupSkimmer(); } } else { mSwiper.setRefreshing(true); } return inflated; } @Override void attach(Context context) { if(context instanceof ViewerActivity) { mParent = (ViewerActivity) context; } else { throw new IllegalArgumentException("Activity must be instance of " + ViewerActivity.class.getSimpleName()); } if(mIsWaitingForAttach) { Loader.getInstance(getContext()).loadArticle(mItem, true, this); } } @Override void bindData() { mSwiper.setRefreshing(false); mArticle = Html.fromHtml(mArticle).toString(); if(mBodyEnabled) mTextBody.setText(mArticle); setupSkimmer(); } @OnLongClick(R.id.skimmer_touch_area) boolean onAreaLongClick() { mTextView.play(); return false; } @OnTouch(R.id.skimmer_touch_area) boolean onAreaTouch(MotionEvent motionEvent) { if(motionEvent.getAction() == MotionEvent.ACTION_UP) { mTextView.pause(); } return false; } @OnLongClick(R.id.skimmer_text_body) boolean onBodyLongClick() { mTextBody.setClickEnabled(false); mTextView.play(); return false; } @OnTouch(R.id.skimmer_text_body) boolean onBodyTouch(MotionEvent motionEvent) { if(motionEvent.getAction() == MotionEvent.ACTION_UP) { mTextView.pause(); mTextBody.highlightWord(mTextView.getCurrentWordIndex()); mBodyScrollview.smoothScrollTo(0, mTextBody.getLayout().getLineTop( mTextBody.getLayout().getLineForOffset( mTextBody.getHighlightedPosition()))); mTextBody.postDelayed(() -> mTextBody.setClickEnabled(true), 20); } return false; } @OnClick(R.id.skimmer_text_view) void onSpritzerClick() { if(mBodyEnabled) { mTextView.showTextDialog(); } else { mTextView.showWPMDialog(); } } @OnLongClick(R.id.skimmer_text_view) boolean onSpritzerLongClick() { if(mBodyEnabled) mTextView.showWPMDialog(); return true; } private void displayErrorMessage() { mTextView.setVisibility(View.INVISIBLE); mSkimmerProgress.setVisibility(View.INVISIBLE); mErrorView.setVisibility(View.VISIBLE); mErrorView.setText(R.string.error_parsing_readable_text); } private void setupSkimmer() { if(Analytics.VERBOSE) Log.i(TAG, "setupSkimmer: " + mViewsReady + " | " + mTextView); mTextView.setVisibility(View.VISIBLE); mSkimmerProgress.setVisibility(View.VISIBLE); mTextView.setWpm(SharedPrefsController.getInstance(getContext()).getSkimmerWPM()); mTextView.setSpritzText(mArticle); mTextView.pause(); } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } @Override public void onPauseFragment() { mTextView.pause(); } @Override public void onResumeFragment() { mParent.setUpFab(R.drawable.ic_refresh, view -> { mTextView.setSpritzText(mArticle); mTextView.getSpritzer().start(); if(Build.VERSION.SDK_INT >= 24) { mSkimmerProgress.setProgress(0, true); } else { mSkimmerProgress.setProgress(0); } mBodyScrollview.scrollTo(0, 0); /* In order to skip one word, we have to wait for one minute / words per minute */ mTextView.postDelayed(() -> mTextView.getSpritzer().pause(), 60000 / mTextView.getSpritzer().getWpm()); }); mTracker.setScreenName(TAG); mTracker.send(new HitBuilders.ScreenViewBuilder().build()); } @Override public boolean onBackPressed() { return true; } @Override public void itemLoaded(Item item) { mItem = item; if(item.getUrl() != null) { if(mViewsReady) mSwiper.setRefreshing(true); if(mContextReady) { Loader.getInstance(getContext()).loadArticle(item, true, this); } else { mIsWaitingForAttach = true; } } else { mArticle = item.getText() == null ? "" : Html.fromHtml(item.getText()).toString(); mContentReady = true; if(mViewsReady) bindData(); } } @Override public void itemError(int id, int code) { } @Override public void textLoaded(JSONObject result) { try { mArticle = result.getString("content"); mContentReady = true; if(mViewsReady) bindData(); } catch(JSONException jse) { Log.e(TAG, "textLoaded: ", jse); displayErrorMessage(); } } @Override public void textError(String url, int code) { } }
package de.tum.in.securebitcoinwallet; import android.content.Context; import android.content.Intent; import de.tum.in.securebitcoinwallet.address.create.CreateAddressActivity; import de.tum.in.securebitcoinwallet.transactions.TransactionsActivity; import de.tum.in.securebitcoinwallet.transactions.create.CreateTransactionActivity; /** * A simple class responsible to navigate from one activity to another. * * @author Hannes Dorfmann */ public class IntentStarter { /** * Navigate to the list of transaction * * @param context The context * @param address The address you want to dispaly the transactions for */ public void showTransactions(Context context, String address) { Intent i = new Intent(context, TransactionsActivity.class); i.putExtra(TransactionsActivity.KEY_ADDRESS, address); context.startActivity(i); context.startActivity(i); } /** * Starts the activity to create a new address * * @param context the context * @param revealX the revealX position * @param revealY the revealY position */ public void showCreateAddress(Context context, int revealX, int revealY) { Intent i = new Intent(context, CreateAddressActivity.class); i.putExtra(CreateAddressActivity.KEY_REVEAL_X, revealX); i.putExtra(CreateAddressActivity.KEY_REVEAL_Y, revealY); context.startActivity(i); } /** * Stats the activity to create a new Transcation (send Bitcoins) * * @param context The context * @param senderAddress The address from which the bicoins will be sends * @param revealX the revealX position * @param revealY ther revealY position */ public void showCreateTransaction(Context context, String senderAddress, int revealX, int revealY) { Intent i = new Intent(context, CreateTransactionActivity.class); i.putExtra(CreateTransactionActivity.KEY_REVEAL_X, revealX); i.putExtra(CreateTransactionActivity.KEY_REVEAL_Y, revealY); i.putExtra(CreateTransactionActivity.KEY_SENDER_ADDRESS, senderAddress); context.startActivity(i); } }
package org.mozilla.focus.fragment; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ObjectAnimator; import android.app.Activity; import android.graphics.Typeface; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.text.SpannableString; import android.text.style.StyleSpan; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.animation.DecelerateInterpolator; import android.widget.FrameLayout; import android.widget.TextView; import org.mozilla.focus.R; import org.mozilla.focus.autocomplete.UrlAutoCompleteFilter; import org.mozilla.focus.telemetry.TelemetryWrapper; import org.mozilla.focus.utils.ThreadUtils; import org.mozilla.focus.utils.UrlUtils; import org.mozilla.focus.utils.ViewUtils; import org.mozilla.focus.widget.HintFrameLayout; import org.mozilla.focus.widget.InlineAutocompleteEditText; /** * Fragment for displaying he URL input controls. */ public class UrlInputFragment extends Fragment implements View.OnClickListener, InlineAutocompleteEditText.OnCommitListener, InlineAutocompleteEditText.OnFilterListener { public static final String FRAGMENT_TAG = "url_input"; private static final String ARGUMENT_URL = "url"; private static final String ARGUMENT_ANIMATION = "animation"; private static final String ARGUMENT_X = "x"; private static final String ARGUMENT_Y = "y"; private static final String ARGUMENT_WIDTH = "width"; private static final String ARGUMENT_HEIGHT = "height"; private static final String ANIMATION_HOME_SCREEN = "home_screen"; private static final String ANIMATION_BROWSER_SCREEN = "browser_screen"; private static final int ANIMATION_DURATION = 200; /** * Create a new UrlInputFragment and animate the url input view from the position/size of the * fake url bar view. */ public static UrlInputFragment createWithHomeScreenAnimation(View fakeUrlBarView) { int[] screenLocation = new int[2]; fakeUrlBarView.getLocationOnScreen(screenLocation); Bundle arguments = new Bundle(); arguments.putString(ARGUMENT_ANIMATION, ANIMATION_HOME_SCREEN); arguments.putInt(ARGUMENT_X, screenLocation[0]); arguments.putInt(ARGUMENT_Y, screenLocation[1]); arguments.putInt(ARGUMENT_WIDTH, fakeUrlBarView.getWidth()); arguments.putInt(ARGUMENT_HEIGHT, fakeUrlBarView.getHeight()); UrlInputFragment fragment = new UrlInputFragment(); fragment.setArguments(arguments); return fragment; } /** * Create a new UrlInputFragment and animate the url input view from the position/size of the * browser toolbar's URL view. */ public static UrlInputFragment createWithBrowserScreenAnimation(String url, View urlView) { final Bundle arguments = new Bundle(); arguments.putString(ARGUMENT_ANIMATION, ANIMATION_BROWSER_SCREEN); arguments.putString(ARGUMENT_URL, url); int[] screenLocation = new int[2]; urlView.getLocationOnScreen(screenLocation); arguments.putInt(ARGUMENT_X, screenLocation[0]); arguments.putInt(ARGUMENT_Y, screenLocation[1]); arguments.putInt(ARGUMENT_WIDTH, urlView.getWidth()); arguments.putInt(ARGUMENT_HEIGHT, urlView.getHeight()); final UrlInputFragment fragment = new UrlInputFragment(); fragment.setArguments(arguments); return fragment; } private InlineAutocompleteEditText urlView; private View clearView; private View searchViewContainer; private TextView searchView; private UrlAutoCompleteFilter urlAutoCompleteFilter; private View dismissView; private HintFrameLayout urlInputContainerView; private View urlInputBackgroundView; private View toolbarBackgroundView; private volatile boolean isAnimating; @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { final View view = inflater.inflate(R.layout.fragment_urlinput, container, false); dismissView = view.findViewById(R.id.dismiss); dismissView.setOnClickListener(this); clearView = view.findViewById(R.id.clear); clearView.setOnClickListener(this); searchViewContainer = view.findViewById(R.id.search_hint_container); searchView = (TextView) view.findViewById(R.id.search_hint); searchView.setOnClickListener(this); urlAutoCompleteFilter = new UrlAutoCompleteFilter(); urlAutoCompleteFilter.loadDomainsInBackground(getContext().getApplicationContext()); urlView = (InlineAutocompleteEditText) view.findViewById(R.id.url_edit); urlView.setOnFilterListener(this); urlView.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { // Avoid showing keyboard again when returning to the previous page by back key. if (hasFocus && !isAnimating) { ViewUtils.showKeyboard(urlView); } } }); toolbarBackgroundView = view.findViewById(R.id.toolbar_background); urlInputBackgroundView = view.findViewById(R.id.url_input_background); urlInputContainerView = (HintFrameLayout) view.findViewById(R.id.url_input_container); urlInputContainerView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { urlInputContainerView.getViewTreeObserver().removeOnPreDrawListener(this); animateFirstDraw(); return true; } }); urlView.setOnCommitListener(this); if (getArguments().containsKey(ARGUMENT_URL)) { urlView.setText(getArguments().getString(ARGUMENT_URL)); clearView.setVisibility(View.VISIBLE); } return view; } public boolean onBackPressed() { animateAndDismiss(); return true; } @Override public void onStart() { super.onStart(); urlView.requestFocus(); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.clear: urlView.setText(""); urlView.requestFocus(); break; case R.id.search_hint: onSearch(); break; case R.id.dismiss: animateAndDismiss(); break; default: throw new IllegalStateException("Unhandled view in onClick()"); } } private void animateFirstDraw() { final String animation = getArguments().getString(ARGUMENT_ANIMATION); if (ANIMATION_HOME_SCREEN.equals(animation)) { playHomeScreenAnimation(false); } else if (ANIMATION_BROWSER_SCREEN.equals(animation)) { playBrowserScreenAnimation(false); } } private void animateAndDismiss() { ThreadUtils.assertOnUiThread(); if (isAnimating) { // We are already animating some state change. Ignore all other requests. return; } // Don't allow any more clicks: dismissView is still visible until the animation ends, // but we don't want to restart animations and/or trigger hiding again (which could potentially // cause crashes since we don't know what state we're in). Ignoring further clicks is the simplest // solution, since dismissView is about to disappear anyway. dismissView.setClickable(false); final String animation = getArguments().getString(ARGUMENT_ANIMATION); if (ANIMATION_HOME_SCREEN.equals(animation)) { playHomeScreenAnimation(true); } else if (ANIMATION_BROWSER_SCREEN.equals(animation)) { playBrowserScreenAnimation(true); } else { dismiss(); } } /** * Play animation between home screen and the URL input. */ private void playHomeScreenAnimation(final boolean reverse) { if (isAnimating) { // We are already animating, let's ignore another request. return; } isAnimating = true; int[] screenLocation = new int[2]; urlInputContainerView.getLocationOnScreen(screenLocation); int leftDelta = getArguments().getInt(ARGUMENT_X) - screenLocation[0]; int topDelta = getArguments().getInt(ARGUMENT_Y) - screenLocation[1]; float widthScale = (float) getArguments().getInt(ARGUMENT_WIDTH) / urlInputContainerView.getWidth(); float heightScale = (float) getArguments().getInt(ARGUMENT_HEIGHT) / urlInputContainerView.getHeight(); if (!reverse) { // Move all views to the position of the fake URL bar on the home screen. Hide them until // the animation starts because we need to switch between fake URL bar and the actual URL // bar once the animation starts. urlInputContainerView.setAlpha(0); urlInputContainerView.setPivotX(0); urlInputContainerView.setPivotY(0); urlInputContainerView.setScaleX(widthScale); urlInputContainerView.setScaleY(heightScale); urlInputContainerView.setTranslationX(leftDelta); urlInputContainerView.setTranslationY(topDelta); urlInputContainerView.setAnimationOffset(1.0f); toolbarBackgroundView.setAlpha(0); dismissView.setAlpha(0); } // Move the URL bar from its position on the home screen to the actual position (and scale it). urlInputContainerView.animate() .setDuration(ANIMATION_DURATION) .scaleX(reverse ? widthScale : 1) .scaleY(reverse ? heightScale : 1) .translationX(reverse ? leftDelta : 0) .translationY(reverse ? topDelta : 0) .setInterpolator(new DecelerateInterpolator()) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { ViewUtils.updateAlphaIfViewExists(getActivity(), R.id.fake_urlbar, 0f); urlInputContainerView.setAlpha(1); if (reverse) { urlView.setText(""); urlView.setCursorVisible(false); urlView.clearFocus(); } } @Override public void onAnimationEnd(Animator animation) { if (reverse) { urlInputContainerView.setAlpha(0f); ViewUtils.updateAlphaIfViewExists(getActivity(), R.id.fake_urlbar, 1f); dismiss(); } else { urlView.setCursorVisible(true); } isAnimating = false; } }); final ObjectAnimator hintAnimator = ObjectAnimator.ofFloat( urlInputContainerView, "animationOffset", reverse ? 0f : 1f, reverse ? 1f : 0f); hintAnimator.setDuration(ANIMATION_DURATION); hintAnimator.start(); // Let the toolbar background come int from the top toolbarBackgroundView.animate() .alpha(reverse ? 0 : 1) .setDuration(ANIMATION_DURATION) .setInterpolator(new DecelerateInterpolator()); // Use an alpha animation on the transparent black background dismissView.animate() .alpha(reverse ? 0 : 1) .setDuration(ANIMATION_DURATION); } private void playBrowserScreenAnimation(final boolean reverse) { if (isAnimating) { // We are already animating, let's ignore another request. return; } isAnimating = true; { float containerMargin = ((FrameLayout.LayoutParams) urlInputContainerView.getLayoutParams()).bottomMargin; float width = urlInputBackgroundView.getWidth(); float height = urlInputBackgroundView.getHeight(); float widthScale = (width + (2 * containerMargin)) / width; float heightScale = (height + (2 * containerMargin)) / height; if (!reverse) { urlInputBackgroundView.setPivotX(0); urlInputBackgroundView.setPivotY(0); urlInputBackgroundView.setScaleX(widthScale); urlInputBackgroundView.setScaleY(heightScale); urlInputBackgroundView.setTranslationX(-containerMargin); urlInputBackgroundView.setTranslationY(-containerMargin); urlInputContainerView.setAnimationOffset(0f); clearView.setAlpha(0); } // Let the URL input use the full width/height and then shrink to the actual size urlInputBackgroundView.animate() .setDuration(ANIMATION_DURATION) .scaleX(reverse ? widthScale : 1) .scaleY(reverse ? heightScale : 1) .alpha(reverse ? 0 : 1) .translationX(reverse ? -containerMargin : 0) .translationY(reverse ? -containerMargin : 0) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { if (reverse) { clearView.setAlpha(0); } } @Override public void onAnimationEnd(Animator animation) { if (reverse) { dismiss(); } else { clearView.setAlpha(1); } isAnimating = false; } }); } { int[] screenLocation = new int[2]; urlView.getLocationOnScreen(screenLocation); int leftDelta = getArguments().getInt(ARGUMENT_X) - screenLocation[0] - urlView.getPaddingLeft(); if (!reverse) { urlView.setPivotX(0); urlView.setPivotY(0); urlView.setTranslationX(leftDelta); } // The URL moves from the right (at least if the lock is visible) to it's actual position urlView.animate() .setDuration(ANIMATION_DURATION) .translationX(reverse ? leftDelta : 0); } if (!reverse) { toolbarBackgroundView.setAlpha(0); clearView.setAlpha(0); } // The darker background appears with an alpha animation toolbarBackgroundView.animate() .setDuration(ANIMATION_DURATION) .alpha(reverse ? 0 : 1); } private void dismiss() { final Activity activity = getActivity(); if (activity == null) { return; } // This method is called from animation callbacks. In the short time frame between the animation // starting and ending the activity can be paused. In this case this code can throw an // this transaction is committed. To avoid this we commit while allowing a state loss here. // We do not save any state in this fragment (It's getting destroyed) so this should not be a problem. getActivity().getSupportFragmentManager() .beginTransaction() .remove(this) .commitAllowingStateLoss(); } @Override public void onCommit() { final String input = urlView.getText().toString(); if (!input.trim().isEmpty()) { ViewUtils.hideKeyboard(urlView); final boolean isUrl = UrlUtils.isUrl(input); final String url = isUrl ? UrlUtils.normalize(input) : UrlUtils.createSearchUrl(getContext(), input); openUrl(url); TelemetryWrapper.urlBarEvent(isUrl); } } private void onSearch() { final String searchUrl = UrlUtils.createSearchUrl(getContext(), urlView.getOriginalText()); openUrl(searchUrl); TelemetryWrapper.searchSelectEvent(); } private void openUrl(String url) { final FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); // Replace all fragments with a fresh browser fragment. This means we either remove the // HomeFragment with an UrlInputFragment on top or an old BrowserFragment with an // UrlInputFragment. final BrowserFragment browserFragment = (BrowserFragment) fragmentManager .findFragmentByTag(BrowserFragment.FRAGMENT_TAG); if (browserFragment != null && browserFragment.isVisible()) { // Reuse existing visible fragment - in this case we know the user is already browsing. // The fragment might exist if we "erased" a browsing session, hence we need to check // for visibility in addition to existence. browserFragment.loadUrl(url); // And this fragment can be removed again. fragmentManager.beginTransaction() .remove(this) .commit(); } else { fragmentManager .beginTransaction() .replace(R.id.container, BrowserFragment.create(url), BrowserFragment.FRAGMENT_TAG) .commit(); } } @Override public void onFilter(String searchText, InlineAutocompleteEditText view) { // If the UrlInputFragment has already been hidden, don't bother with filtering. Because of the text // input architecture on Android it's possible for onFilter() to be called after we've already // hidden the Fragment, see the relevant bug for more background: // https://github.com/mozilla-mobile/focus-android/issues/441#issuecomment-293691141 if (!isVisible()) { return; } urlAutoCompleteFilter.onFilter(searchText, view); if (searchText.trim().isEmpty()) { clearView.setVisibility(View.GONE); searchViewContainer.setVisibility(View.GONE); } else { clearView.setVisibility(View.VISIBLE); final String hint = getString(R.string.search_hint, searchText); final SpannableString content = new SpannableString(hint); content.setSpan(new StyleSpan(Typeface.BOLD), hint.length() - searchText.length(), hint.length(), 0); searchView.setText(content); searchViewContainer.setVisibility(View.VISIBLE); } } }
package org.xdevs23.management.config; import org.xdevs23.debugutils.Logging; import java.util.ArrayList; public class SPConfigEntry { public ArrayList<String> keys, values; public SPConfigEntry(String rawString) { this(); if ( rawString.isEmpty() || !rawString.contains(";;") ) return; String[] everything = rawString.split(";;"); for ( int i = 0; i < everything.length; i += 2) { keys .add(everything[i ]); values.add(everything[i+1]); } } public SPConfigEntry() { createNew(); } public SPConfigEntry createNew() { values = new ArrayList<>(); keys = new ArrayList<>(); return this; } public String getValue(String key) { for ( int i = 0; i < keys.size(); i++ ) if (keys.get(i).equals(key)) return values.get(i); return ""; } public String getKeyForValue(String value) { for ( int i = 0; i < values.size(); i++ ) if (values.get(i).equals(value)) return keys.get(i); return ""; } public void putValue(String key, String value) { for ( int i = 0; i < keys.size(); i++ ) if (keys.get(i).equals(key)) { values.set(i, value); return; } values .add(value); keys .add(key); } @Override public String toString() { String[] everything = new String[keys.size()*2]; // everything[0] = keys[0] // everything[1] = values[0] // everything[2] = keys[1] // everything[3] = values[1] for ( int i = 0; i < keys .size(); i++ ) { everything[i * 2] = keys.get(i); everything[i * 2 + 1] = values.get(i); } StringBuilder finalRawString = new StringBuilder(); for ( String s : everything ) finalRawString.append(s).append(";;"); return finalRawString .substring(0, finalRawString.length() - 2); // This is to remove the leading ;; } }
package com.google.sprint1; import java.io.File; import java.util.ArrayList; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.TextView; import com.google.sprint1.NetworkService.LocalBinder; import com.metaio.sdk.ARViewActivity; import com.metaio.sdk.GestureHandlerAndroid; import com.metaio.sdk.MetaioDebug; import com.metaio.sdk.jni.GestureHandler; import com.metaio.sdk.jni.IGeometry; import com.metaio.sdk.jni.IMetaioSDKCallback; import com.metaio.sdk.jni.Rotation; import com.metaio.sdk.jni.Vector3d; import com.metaio.tools.io.AssetsManager; /** * GameActivity to handle the game * */ public class GameActivity extends ARViewActivity // implements // OnGesturePerformedListener { /* Variables for objects in the game */ private IGeometry towerGeometry1; private IGeometry canonGeometry1; private IGeometry towerGeometry2; private IGeometry canonGeometry2; private IGeometry towerGeometry3; private IGeometry canonGeometry3; private IGeometry towerGeometry4; private IGeometry canonGeometry4; private IGeometry crosshair; private IGeometry arrowAim; private IGeometry aimPowerUp; private IGeometry ball; private IGeometry ballShadow; private ArrayList<IGeometry> ballPath; // lista med bollar som visar parabeln fr den flygande frgbollen private ArrayList<IGeometry> ballPathShadow; // skuggor till parabelsiktet GameState gameState; //Gesture handler private GestureHandlerAndroid mGestureHandler; private int mGestureMask; Ant ant; private Vector3d touchVec; // endTouch-startTouch Player player; // point count protected int point; TextView displayPoints; float temp; float scaleStart; // skalning av pilen fr siktet // Variables for Service handling private NetworkService mService; boolean mBound = false; // FPS specific variables private int frameCounter = 0; private double lastTime; public static final String TAG = "GameActivity"; protected void onDestroy() { // Unbind from service if (mBound) { unbindService(mServiceConnection); mBound = false; } super.onDestroy(); } @Override protected void onStart() { super.onStart(); // Bind to NetworkService Intent intent = new Intent(this, NetworkService.class); bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE); } /** Attaching layout to the activity */ @Override public int getGUILayout() { requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); return R.layout.activity_game; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); GameState.getState().exsisting_paint_balls = new ArrayList<PaintBall>(20); GameState.getState().ants = new ArrayList<Ant>(10); ballPath = new ArrayList<IGeometry>(10); ballPathShadow = new ArrayList<IGeometry>(10); // displayPoints = (TextView) findViewById(R.id.myPoints); touchVec = new Vector3d(0f, 0f, 0f); player = GameState.getState().players.get(1); temp = 20f; point = 0; scaleStart = 0f; //Gesture handler mGestureMask = GestureHandler.GESTURE_DRAG; mGestureHandler = new GestureHandlerAndroid(metaioSDK, mGestureMask); } /** Called when the user clicks the Exit button (krysset) */ public void onExitButtonClick(View v) { finish(); } public void onClickSendData(View v) { TestClass test = new TestClass(5, "hej"); mService.mConnection.sendData(test); } /** * Create a geometry, the string input gives the filepach (relative from the * asset folder) to the geometry First check if model is found ->Load and * create 3D geometry ->check if model was loaded successfully Returns the * loaded model if success, otherwise null */ private IGeometry Load3Dmodel(String filePath) { // Getting the full file path for a 3D geometry final File modelPath = AssetsManager.getAssetPathAsFile( getApplicationContext(), filePath); // First check if model is found if (modelPath != null) { // Load and create 3D geometry IGeometry model = metaioSDK.createGeometry(modelPath); // check if model was loaded successfully if (model != null) return model; else MetaioDebug.log(Log.ERROR, "Error loading geometry: " + modelPath); } else MetaioDebug.log(Log.ERROR, "Could not find 3D model"); return null; } /** Loads the marker and the 3D-models to the game */ @Override protected void loadContents() { try { /** Load Marker */ // Getting a file path for tracking configuration XML file File trackingConfigFile = AssetsManager.getAssetPathAsFile( getApplicationContext(), "marker/TrackingData_Marker.xml"); // Assigning tracking configuration boolean result = metaioSDK .setTrackingConfiguration(trackingConfigFile); MetaioDebug.log("Tracking data loaded: " + result); /** Load Object */ //Gesture handler //creates the tower towerGeometry1 = Load3Dmodel("tower/tower.mfbx"); geometryProperties(towerGeometry1, 2f, new Vector3d(-650f, -520f, 0f), new Rotation(0f, 0f, 0f)); canonGeometry1 = Load3Dmodel("tower/canon.mfbx"); geometryProperties(canonGeometry1, 2f, new Vector3d(-650f, -520f, 165f), new Rotation(0f, 0f, 0f)); mGestureHandler.addObject(canonGeometry1, 1); towerGeometry2 = Load3Dmodel("tower/tower.mfbx"); geometryProperties(towerGeometry2, 2f, new Vector3d(650f, 520f, 0f), new Rotation(0f, 0f, 0f)); canonGeometry2 = Load3Dmodel("tower/canon.mfbx"); geometryProperties(canonGeometry2, 2f, new Vector3d(650f, 520f, 165f), new Rotation(0f, 0f, 0f)); towerGeometry3 = Load3Dmodel("tower/tower.mfbx"); geometryProperties(towerGeometry3, 2f, new Vector3d(-650f, 520f, 0f), new Rotation(0f, 0f, 0f)); canonGeometry3 = Load3Dmodel("tower/canon.mfbx"); geometryProperties(canonGeometry3, 2f, new Vector3d(-650f, 520f, 165f), new Rotation(0f, 0f, 0f)); towerGeometry4 = Load3Dmodel("tower/tower.mfbx"); geometryProperties(towerGeometry4, 2f, new Vector3d(650f, -520f, 0f), new Rotation(0f, 0f, 0f)); canonGeometry4 = Load3Dmodel("tower/canon.mfbx"); geometryProperties(canonGeometry4, 2f, new Vector3d(650f, -520f, 165f), new Rotation(0f, 0f, 0f)); // Load crosshair crosshair = Load3Dmodel("crosshair/crosshair.mfbx"); geometryProperties(crosshair, 1f, new Vector3d(0f, 0f, 0f), new Rotation(0f, 0f, 0f)); crosshair.setVisible(false); arrowAim = Load3Dmodel("crosshair/arrow.obj"); geometryProperties(arrowAim, 2f, new Vector3d(-550, -450, 200f), new Rotation((float) (3 * Math.PI / 2), 0f, 0f)); arrowAim.setVisible(false); // Load powerUps aimPowerUp = Load3Dmodel("powerUps/aimPowerUp.mfbx"); geometryProperties(aimPowerUp, 2.1f, new Vector3d(0f, 0f, 0f), new Rotation(0f, 0f, 0f)); // creates the aim path for (int i = 0; i < 10; i++) { // create new paint ball ball = Load3Dmodel("tower/paintball.obj"); ballShadow = Load3Dmodel("tower/paintballShadow.mfbx"); geometryProperties(ball, 0.5f, new Vector3d(-550, -450, 200f), new Rotation(0f, 0f, 0f)); geometryProperties(ballShadow, 0.2f, new Vector3d(-550, -450, 0), new Rotation(0f, 0f, 0f)); ballPath.add(ball); ballPathShadow.add(ballShadow); ball.setVisible(false); ballShadow.setVisible(false); } // creates a list of ants for(int i = 0; i < 10; i++) { // create ant geometry ant = new Ant(Load3Dmodel("ant/formicaRufa.mfbx")); GameState.getState().ants.add(ant); } // creates a list of paint balls for (int i = 0; i < 20; i++) { // add paint ball to list of paint balls GameState.getState().exsisting_paint_balls.add( new PaintBall(i,Load3Dmodel("tower/paintball.obj"), Load3Dmodel("tower/splash.mfbx"), Load3Dmodel("tower/paintballShadow.mfbx"))); } } catch (Exception e) { MetaioDebug.printStackTrace(Log.ERROR, e); } } // function to set the properties for the geometry public void geometryProperties(IGeometry geometry, float scale, Vector3d translationVec, Rotation rotation) { geometry.setScale(scale); geometry.setTranslation(translationVec, true); geometry.setRotation(rotation, true); } /** Render Loop */ @Override public void onDrawFrame() { super.onDrawFrame(); // If content not loaded yet, do nothing if ( towerGeometry4== null || GameState.getState().exsisting_paint_balls.isEmpty()) return; //spawn ant at random and move ants for ( int i = 0; i < 10 ; i++) { if(!GameState.getState().ants.get(i).isActive()) { // if not already spawned, spawn at random GameState.getState().ants.get(i).spawnAnt(); } //move ants GameState.getState().ants.get(i).movement(); } powerUpAnimation(aimPowerUp); if (!GameState.getState().exsisting_paint_balls.isEmpty()) { for (PaintBall obj : GameState.getState().exsisting_paint_balls) { if (obj.isActive()) { obj.update(); for(int i = 0; i < 10 ; i++) { if (checkCollision(obj, GameState.getState().ants.get(i).ant)) { GameState.getState().ants.get(i).ant.setRotation(new Rotation( (float) (3 * Math.PI / 4), 0f, 0f), true); obj.splashGeometry.setTranslation(obj.geometry .getTranslation()); obj.splashGeometry.setVisible(true); obj.velocity = new Vector3d(0f, 0f, 0f); obj.geometry.setVisible(false); obj.paintballShadow.setVisible(false); point++; // displayPoints = // (TextView)findViewById(R.id.myPoints); // displayPoints.setText("Ponts:" + point); // displayPoints = // (TextView)findViewById(R.id.editText1); // (TextView)findViewById(R.id.editText1).setText("Ponts:" // + point); } } if (checkCollision(obj, aimPowerUp)) { player.superPower = true; aimPowerUp.setVisible(false); } } } } // onTouchEvent(null); updateFps(); } public boolean checkCollision(PaintBall obj, IGeometry obj2) { Vector3d min = obj2.getBoundingBox(true).getMin(); Vector3d max = obj2.getBoundingBox(true).getMax(); if (obj.geometry.getTranslation().getX() + obj.geometry.getBoundingBox().getMax().getX() > obj2.getTranslation().getX() - min.getX() - 15 && obj.geometry.getTranslation().getX() + obj.geometry.getBoundingBox().getMin().getX() < obj2.getTranslation().getX() + max.getX() + 15 && obj.geometry.getTranslation().getY() + obj.geometry.getBoundingBox().getMax().getY() > obj2.getTranslation().getY() - min.getY() - 15 && obj.geometry.getTranslation().getY() + obj.geometry.getBoundingBox().getMin().getY() < obj2.getTranslation().getY() + max.getY() + 15 && obj.geometry.getTranslation().getZ()+ obj.geometry.getBoundingBox().getMax().getZ() > obj2.getTranslation().getZ() - min.getZ() - 15 && obj.geometry.getTranslation().getZ()+ obj.geometry.getBoundingBox().getMin().getZ() < obj2.getTranslation().getZ() + max.getZ() + 15) return true; else return false; } /** function that activates when an object is being touched */ @Override protected void onGeometryTouched(IGeometry geometry) { // Only implemented because its required by the parent class } /** Function to draw the path of the ball (aim) */ private void drawBallPath(Vector3d touchVec) { float velocity =(float)(Math.abs(touchVec.getX()/4)* Math.sin(Math.PI/4)+ Math.abs(touchVec.getY()/4)*Math.sin(Math.PI/4));//(Math.abs(currentTouch.getX()) + Math.abs(currentTouch.getY())) / (4f * (float) Math.sqrt(2)); float timeToLanding = (float) (velocity / (2 * (float) Math.sqrt(2) * 9.8f) + Math.sqrt(Math.pow( velocity / (2 * Math.sqrt(2) * 9.8), 2) + 165 / 9.8)); // Log.d(TAG, "time to landing : " + timeToLanding); for (int i = 0; i < 10; i++) { ballPath.get(i).setTranslation( new Vector3d(player.position.getX() + (float) ((double) (i) / 5) * touchVec.getX(), player.position.getY() + (float) ((double) (i) / 5) * touchVec.getY(), getPathZPos( velocity, (i * timeToLanding / 10)))); ballPathShadow.get(i).setTranslation( new Vector3d(player.position.getX() + (float) ((double) (i) / 5) * touchVec.getX(), player.position.getY() + (float) ((double) (i) / 5) * touchVec.getY(), 0f)); } /* float Zpos = 165f; float Zvel = 0f; float timeStep = 0.2f; while (Zpos!=0) { Zvel = Zvel + timeStep*9.82f; Zpos = Zpos + timeStep*Zvel; stepcount ++; } */ } /** Function to get ballpath position in Z */ private float getPathZPos(float velocity, float time) { float pos = 0; pos = (float) (165 - 9.82 * Math.pow(time, 2) + velocity * time / Math.sqrt(2)); return pos; } /** Function for animation on the powerup */ private void powerUpAnimation(IGeometry powerUp) { if (powerUp.getScale().getX() > 2.0f) { scaleStart = -0.02f; } if (powerUp.getScale().getX() < 1.0f) { scaleStart = 0.02f; } powerUp.setScale(powerUp.getScale().add( new Vector3d(scaleStart, scaleStart, scaleStart))); // Log.d(TAG, "scale = " + powerUp.getScale()); } private PaintBall getAvailableBall(int id) { for(PaintBall obj : GameState.getState().exsisting_paint_balls) { if (!(obj.geometry.isVisible())) return obj; } return null; } /** Pause function, makes you return to the main menu when pressing "back" */ @Override public void onPause() { super.onPause(); // creates a fade between scenes overridePendingTransition(R.anim.fadein, R.anim.fadeout); } //Gesture handler @Override public boolean onTouch(View v, MotionEvent event) { super.onTouch(v, event); mGestureHandler.onTouch(v, event); //coordinates between tower and "slangbella" touchVec = new Vector3d(-(canonGeometry1.getTranslation().getX()-towerGeometry1.getTranslation().getX()), -(canonGeometry1.getTranslation().getY()-towerGeometry1.getTranslation().getY()), 0f); switch(event.getActionMasked()) { case MotionEvent.ACTION_DOWN: if(player.superPower == true) { crosshair.setVisible(true); } else //if(player.superPower == false) { for(int i = 0; i < 10; i++) { ballPath.get(i).setVisible(true); ballPathShadow.get(i).setVisible(true); } } break; case MotionEvent.ACTION_MOVE: if(player.superPower == true) { crosshair.setTranslation(new Vector3d( player.position.getX()+2.2f*touchVec.getX(), player.position.getY()+2.2f*touchVec.getY(), 0f)); } else //if(player.superPower == false) { drawBallPath(touchVec); } break; case MotionEvent.ACTION_UP: crosshair.setVisible(false); for(int i = 0; i < 10; i++) { ballPath.get(i).setVisible(false); ballPathShadow.get(i).setVisible(false); } // move "slangbella" to original position canonGeometry1.setTranslation(towerGeometry1.getTranslation()); canonGeometry1.setTranslation(new Vector3d(0f, 0f, 165f), true); PaintBall ball = getAvailableBall(1); if(ball != null) { Vector3d pos = player.position; // delat p sqrt(2) == gnger sin(45 grader) Vector3d vel = new Vector3d(touchVec.getX()/4, touchVec.getY()/4, (float)(Math.abs(touchVec.getX()/4)* Math.sin(Math.PI/4)+ Math.abs(touchVec.getY()/4)*Math.sin(Math.PI/4))); DataPackage data = new DataPackage(ball.id, vel, pos); mService.mConnection.sendData(data); ball.fire(vel, pos); } break; } return true; } @Override protected IMetaioSDKCallback getMetaioSDKCallbackHandler() { return null; } /** Defines callbacks for service binding, passed to bindService() */ private ServiceConnection mServiceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { // We've bound to LocalService, cast the IBinder and get // LocalService instance LocalBinder binder = (LocalBinder) service; mService = binder.getService(); mBound = true; } @Override public void onServiceDisconnected(ComponentName arg0) { mBound = false; } }; /**Updates Fps each frame and display it to user once every second*/ private void updateFps() { //Adds one each frame frameCounter++; //Uses internal clock to calculate the difference between current time and last time double currentTime = System.currentTimeMillis() - lastTime; //calculates the fps (*1000 due to milliseconds) final int fps = (int) (((double) frameCounter / currentTime) * 1000); //Only displays if current time is over one second if (currentTime > 1.0) { lastTime = System.currentTimeMillis(); frameCounter = 0; //Necessary to run on UI thread to be able to edit the TextView runOnUiThread(new Runnable() { @Override public void run() { TextView displayPoints = (TextView) findViewById(R.id.myPoints); displayPoints.setText("FPS: " + fps); } }); } } }
package org.crumbleworks.forge.karmen; import org.crumbleworks.forge.karmen.screen.AboutScreen; import org.crumbleworks.forge.karmen.screen.IntroScreen; import org.crumbleworks.forge.karmen.screen.MenuScreen; import org.crumbleworks.forge.karmen.screen.PlayScreen; import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; public class Karmen extends Game { public static final int SCREEN_WIDTH = 800; public static final int SCREEN_HEIGHT = 480; private SpriteBatch batch; private BitmapFont fontMedium; private BitmapFont fontLarge; public Screen introScreen; public Screen menuScreen; public Screen playScreen; public Screen aboutScreen; @Override public void create() { batch = new SpriteBatch(); fontMedium = new BitmapFont(Gdx.files.internal("fnt/NNPH_30.fnt")); fontLarge = new BitmapFont(Gdx.files.internal("fnt/NNPH_40.fnt")); introScreen = new IntroScreen(this); menuScreen = new MenuScreen(this); playScreen = new PlayScreen(this); aboutScreen = new AboutScreen(this); setScreen(introScreen); } @Override public void render() { // Gdx.gl.glClearColor(1, 0, 0, 1); // Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // batch.begin(); // batch.draw(img, 0, 0); // batch.end(); super.render(); } @Override public void dispose() { introScreen.dispose(); menuScreen.dispose(); batch.dispose(); fontMedium.dispose(); fontLarge.dispose(); } public SpriteBatch getBatch() { return batch; } public BitmapFont getFontMedium() { return fontMedium; } public BitmapFont getFontLarge() { return fontLarge; } public void changeScreen(Screen nextScreen) { setScreen(nextScreen); } }
package org.nnsoft.shs.core; import static java.lang.Thread.currentThread; import static java.nio.ByteBuffer.allocate; import static java.nio.channels.SelectionKey.OP_ACCEPT; import static java.nio.channels.SelectionKey.OP_READ; import static java.nio.channels.ServerSocketChannel.open; import static java.util.concurrent.Executors.newFixedThreadPool; import static org.nnsoft.shs.HttpServer.Status.INITIALIZED; import static org.nnsoft.shs.HttpServer.Status.RUNNING; import static org.nnsoft.shs.HttpServer.Status.STOPPED; import static org.nnsoft.shs.core.http.ResponseFactory.newResponse; import static org.nnsoft.shs.core.io.ByteBufferEnqueuerOutputStream.EOM; import static org.nnsoft.shs.http.Headers.CONNECTION; import static org.nnsoft.shs.http.Headers.KEEP_ALIVE; import static org.nnsoft.shs.http.Response.Status.BAD_REQUEST; import static org.nnsoft.shs.http.Response.Status.INTERNAL_SERVER_ERROR; import static org.slf4j.LoggerFactory.getLogger; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Queue; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicReference; import org.nnsoft.shs.HttpServer; import org.nnsoft.shs.HttpServerConfiguration; import org.nnsoft.shs.InitException; import org.nnsoft.shs.RunException; import org.nnsoft.shs.ShutdownException; import org.nnsoft.shs.core.http.RequestParseException; import org.nnsoft.shs.core.http.SessionManager; import org.nnsoft.shs.core.http.parse.RequestStreamingParser; import org.nnsoft.shs.core.http.serialize.ResponseSerializer; import org.nnsoft.shs.http.Request; import org.nnsoft.shs.http.Response; import org.slf4j.Logger; /** * A simple {@link HttpServer} implementation. * * This class must NOT be shared across threads, consider it be used inside main(String...) method. */ public final class SimpleHttpServer implements HttpServer { private static final String HTTP_11 = "1.1"; private final Logger logger = getLogger( getClass() ); private ExecutorService requestsExecutor; private ServerSocketChannel server; private Selector selector; private RequestDispatcher dispatcher; private SessionManager sessionManager; private int keepAliveTimeOut; private final AtomicReference<Status> currentStatus = new AtomicReference<Status>(); /** * Creates a new {@link HttpServer} instance. */ public SimpleHttpServer() { currentStatus.set( STOPPED ); } /** * {@inheritDoc} */ public void init( HttpServerConfiguration configuratoruration ) throws InitException { checkInitParameter( configuratoruration != null, "Impossible configure the server with a null configuration" ); checkInitParameter( STOPPED == currentStatus.get(), "Current server cannot be configured while in %s status.", currentStatus ); DefaultHttpServerConfigurator configurator = new DefaultHttpServerConfigurator(); configuratoruration.configure( configurator ); checkInitParameter( configurator.getHost() != null, "Impossible bind server to a null host" ); checkInitParameter( configurator.getPort() > 0, "Impossible to listening on port %s, it must be a positive number", configurator.getPort() ); checkInitParameter( configurator.getThreads() > 0, "Impossible to serve requests with negative or none threads" ); checkInitParameter( configurator.getSessionMaxAge() > 0, "Sessions without timelive won't exist" ); checkInitParameter( configurator.getKeepAliveTimeOut() >= 0, "Negative keep alive timeout not allowed" ); keepAliveTimeOut = configurator.getKeepAliveTimeOut() * 1000; logger.info( "Initializing server using {} threads...", configurator.getThreads() ); currentThread().setName( "socket-listener" ); requestsExecutor = newFixedThreadPool( configurator.getThreads(), new ProtocolProcessorThreadFactory() ); logger.info( "Done! Initializing the SessionManager ..." ); sessionManager = new SessionManager( configurator.getSessionMaxAge() * 1000 ); logger.info( "Done! Binding host {} listening on port {} ...", configurator.getHost(), configurator.getPort() ); try { server = open(); server.socket().bind( new InetSocketAddress( configurator.getHost(), configurator.getPort() ) ); server.configureBlocking( false ); selector = Selector.open(); server.register( selector, OP_ACCEPT ); } catch ( IOException e ) { throw new InitException( "Impossible to start server on port %s (with %s threads): %s", configurator.getPort(), configurator.getThreads(), e.getMessage() ); } this.dispatcher = configurator.getRequestDispatcher(); logger.info( "Done! Server has been successfully initialized, it can be now started" ); currentStatus.set( INITIALIZED ); } /** * Verifies a configuration parameter condition, throwing {@link InitException} if not verified. * * @param condition the condition to check * @param messageTemplate the message template string * @param args the message template arguments * @throws InitException if the input condition is not verified */ private static void checkInitParameter( boolean condition, String messageTemplate, Object...args ) throws InitException { if ( !condition ) { throw new InitException( messageTemplate, args ); } } /** * {@inheritDoc} */ public void start() throws RunException { if ( INITIALIZED != currentStatus.get() ) { throw new RunException( "Current server cannot be configured while in %s status, stop then init again before.", currentStatus ); } logger.info( "Server successfully started! Waiting for new requests..." ); currentStatus.set( RUNNING ); while ( RUNNING == currentStatus.get() ) { try { selector.select(); } catch ( Throwable t ) { throw new RunException( "Something wrong happened while listening for connections", t ); } Iterator<SelectionKey> keys = selector.selectedKeys().iterator(); while ( keys.hasNext() ) { SelectionKey key = keys.next(); if ( !key.isValid() ) { continue; } if ( !key.isReadable() ) { keys.remove(); } try { if ( key.isAcceptable() ) { accept( key ); } else if ( key.isReadable() ) { read( key, keys ); } else if ( key.isWritable() ) { write( key ); } } catch ( IOException e ) { logger.error( "An error occurred wile negotiation", e ); key.cancel(); } } } logger.info( "Server is shutting down..." ); try { if ( selector != null && selector.isOpen() ) { selector.close(); } } catch ( IOException e ) { throw new RunException( "An error occurred while disposing server resources: %s", e.getMessage() ); } finally { try { if ( server != null && server.isOpen() ) { server.close(); } } catch ( IOException e ) { throw new RunException( "An error occurred while disposing server resources: %s", e.getMessage() ); } finally { requestsExecutor.shutdown(); sessionManager.shutDown(); requestsExecutor = null; server = null; selector = null; dispatcher = null; sessionManager = null; logger.info( "Done! Server is now stopped. Bye!" ); } } } private void accept( SelectionKey key ) throws IOException { ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel(); SocketChannel socketChannel = serverChannel.accept(); if ( socketChannel == null ) { return; } socketChannel.configureBlocking( false ); Socket socket = socketChannel.socket(); if ( logger.isInfoEnabled() ) { logger.info( "Accepting new request from {}", socket.getInetAddress().getHostAddress() ); } switchToRead( socketChannel, socket ); } private void switchToRead( SocketChannel socketChannel, Socket socket ) throws IOException { socketChannel.register( selector, OP_READ, new RequestStreamingParser( socket.getInetAddress().getHostAddress(), socket.getLocalAddress().getHostName(), socket.getLocalPort() ) ); } private void read( SelectionKey key, Iterator<SelectionKey> keys ) throws IOException { SocketChannel serverChannel = (SocketChannel) key.channel(); RequestStreamingParser requestParser = (RequestStreamingParser) key.attachment(); ByteBuffer data = allocate( 100 ); try { push: while ( serverChannel.read( data ) != -1 && !requestParser.isRequestMessageComplete() ) { data.flip(); try { requestParser.onRequestPartRead( data ); } catch ( RequestParseException e ) { Response response = newResponse(); response.setStatus( BAD_REQUEST ); keys.remove(); try { new ResponseSerializer( key ).serialize( response ); } catch ( IOException ioe ) { key.cancel(); logger.error( "Impossible to stream Response to the client", e ); } break push; } data.clear(); } if ( requestParser.isRequestMessageComplete() ) { keys.remove(); key.interestOps( 0 ); Request request = requestParser.getParsedRequest(); boolean keepAlive = HTTP_11.equals( request.getProtocolVersion() ) || ( request.getHeaders().contains( CONNECTION ) && KEEP_ALIVE.equals( request.getHeaders().getFirstValue( CONNECTION ) ) ); if ( keepAlive ) { Socket socket = serverChannel.socket(); socket.setKeepAlive( true ); socket.setSoTimeout( keepAliveTimeOut ); } requestsExecutor.execute( new ProtocolProcessor( sessionManager, dispatcher, request, key ) ); } } catch ( IOException e ) { Response response = newResponse(); response.setStatus( INTERNAL_SERVER_ERROR ); keys.remove(); try { new ResponseSerializer( key ).serialize( response ); } catch ( IOException ioe ) { key.cancel(); logger.error( "Impossible to stream Response to the client", e ); } } } private void write( SelectionKey key ) throws IOException { SocketChannel serverChannel = (SocketChannel) key.channel(); @SuppressWarnings( "unchecked" ) // type is driven by the ProtocolProcessor Queue<ByteBuffer> responseBuffers = ( Queue<ByteBuffer> ) key.attachment(); ByteBuffer current = responseBuffers.poll(); if ( current != null ) { if ( EOM == current ) { Socket socket = serverChannel.socket(); if ( logger.isInfoEnabled() ) { logger.info( "Request with {} satisfied.", socket.getInetAddress().getHostAddress() ); } if ( socket.getKeepAlive() ) { if ( logger.isInfoEnabled() ) { logger.info( "Connection with {} will kept alive", socket.getInetAddress().getHostAddress() ); } switchToRead( serverChannel, socket ); } else { if ( logger.isInfoEnabled() ) { logger.info( "Terminating connection with {}", socket.getInetAddress().getHostAddress() ); } socket.close(); key.cancel(); } } else { serverChannel.write( current ); // free the memory current.clear(); } } } /** * {@inheritDoc} */ public void stop() throws ShutdownException { if ( RUNNING != currentStatus.get() ) { throw new ShutdownException( "Current server cannot be stopped while in %s status.", currentStatus ); } currentStatus.set( STOPPED ); } /** * {@inheritDoc} */ public Status getStatus() { return currentStatus.get(); } }
package com.apigee.proxywriter; import com.apigee.proxywriter.exception.ErrorParsingWsdlException; import com.apigee.utils.WsdlDefinitions; import org.junit.Assert; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class GenerateProxyTest { public static final String WEATHER_WSDL = "http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"; public static final String oMap = "<proxywriter><get><operation><pattern>get</pattern><location>beginsWith</location></operation><operation><pattern>inq</pattern><location>beginsWith</location></operation><operation><pattern>search</pattern><location>beginsWith</location></operation><operation><pattern>list</pattern><location>beginsWith</location></operation><operation><pattern>retrieve</pattern><location>beginsWith</location></operation></get><post><operation><pattern>create</pattern><location>contains</location></operation><operation><pattern>add</pattern><location>beginsWith</location></operation><operation><pattern>process</pattern><location>beginsWith</location></operation></post><put><operation><pattern>update</pattern><location>beginsWith</location></operation><operation><pattern>change</pattern><location>beginsWith</location></operation><operation><pattern>modify</pattern><location>beginsWith</location></operation><operation><pattern>set</pattern><location>beginsWith</location></operation></put><delete><operation><pattern>delete</pattern><location>beginsWith</location></operation><operation><pattern>remove</pattern><location>beginsWith</location></operation><operation><pattern>del</pattern><location>beginsWith</location></operation></delete></proxywriter>"; private void checkForFilesInBundle(List<String> filenames, InputStream inputStream) throws IOException { final ZipInputStream zipInputStream = new ZipInputStream(inputStream); ZipEntry zipEntry; while ((zipEntry = zipInputStream.getNextEntry()) != null) { Assert.assertTrue("Missing " + zipEntry.getName(), filenames.contains(zipEntry.getName())); } zipInputStream.close(); } private String readZipFileEntry(String filename, InputStream inputStream) throws IOException { final ZipInputStream zipInputStream = new ZipInputStream(inputStream); try { ZipEntry zipEntry; while ((zipEntry = zipInputStream.getNextEntry()) != null) { if (filename.equals(zipEntry.getName())) { final byte[] bytes = new byte[1024]; int read = 0; final StringBuilder sb = new StringBuilder(); while ( (read = zipInputStream.read(bytes, 0, 1024)) != -1) { sb.append(new String(bytes, 0, read)); } zipInputStream.closeEntry(); return sb.toString(); } } return null; } finally { zipInputStream.close(); } }; private int entryCount(InputStream inputStream) throws IOException { int count = 0; final ZipInputStream zipInputStream = new ZipInputStream(inputStream); ZipEntry zipEntry; while ((zipEntry = zipInputStream.getNextEntry()) != null) { count++; } zipInputStream.close(); return count; } @Test public void testGeneratePassthrough() throws Exception { final List<String> filenames = Arrays.asList( "apiproxy/policies/Extract-Operation-Name.xml", "apiproxy/policies/Invalid-SOAP.xml", "apiproxy/proxies/default.xml", "apiproxy/targets/default.xml", "apiproxy/Weather.xml"); final InputStream inputStream = GenerateProxy.generateProxy(new GenerateProxyOptions(WEATHER_WSDL, "WeatherSoap", true, "", "/foo", "default,secure", false, false, false, false, null)); checkForFilesInBundle(filenames, inputStream); inputStream.reset(); final String extractVariablesPolicy = readZipFileEntry("apiproxy/policies/Extract-Operation-Name.xml", inputStream); Assert.assertEquals(extractVariablesPolicy, "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + System.getProperty("line.separator") + "<ExtractVariables async=\"false\" continueOnError=\"false\" enabled=\"true\" name=\"Extract-Operation-Name\">" + System.getProperty("line.separator") + " <DisplayName>Extract Operation Name</DisplayName>" + System.getProperty("line.separator") + " <Properties/>" + System.getProperty("line.separator") + " <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>" + System.getProperty("line.separator") + " <Source clearPayload=\"false\">request</Source>" + System.getProperty("line.separator") + " <XMLPayload stopPayloadProcessing=\"false\">" + System.getProperty("line.separator") + " <Variable name=\"envelope\" type=\"String\">" + System.getProperty("line.separator") + " <XPath>local-name(/*/*[local-name() = 'Body'])</XPath>" + System.getProperty("line.separator") +
/* * $Log: HttpSender.java,v $ * Revision 1.38 2009-11-12 13:50:03 L190409 * added extra timeout setting * abort method on IOException * * Revision 1.37 2009/08/26 11:47:31 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * upgrade to HttpClient 3.0.1 - including idle connection cleanup * * Revision 1.36 2009/03/31 08:21:17 Peter Leeuwenburgh <peter.leeuwenburgh@ibissource.org> * bugfix in maxExecuteRetries and reduce the default maxRetries to 1 * * Revision 1.35 2008/08/14 14:52:54 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * increased default maxConnections to 10 * * Revision 1.34 2008/08/12 15:34:33 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * maxConnections must be positive * * Revision 1.33 2008/05/21 08:42:37 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * content-type configurable * * Revision 1.32 2008/03/20 12:00:10 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * set default path '/' * * Revision 1.31 2007/12/28 12:09:33 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added timeout exception detection * * Revision 1.30 2007/10/03 08:46:40 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added link to IBM site with JDK policy files * * Revision 1.29 2007/02/21 15:59:02 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * remove debug message * * Revision 1.28 2007/02/05 15:16:53 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * made number of connection- and execution retries configurable * * Revision 1.27 2006/08/24 11:01:25 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * retries instead of attempts * * Revision 1.26 2006/08/23 11:24:39 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * retry when method fails * * Revision 1.25 2006/08/21 07:56:41 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * return of the IbisMultiThreadedConnectionManager * * Revision 1.24 2006/07/17 09:02:46 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * corrected typos in documentation * * Revision 1.23 2006/06/14 09:40:35 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * improved logging * * Revision 1.22 2006/05/03 07:09:38 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * fixed null pointer exception that occured when no statusline was found * * Revision 1.21 2006/01/23 12:57:06 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * determine port-default if not found from uri * * Revision 1.20 2006/01/19 12:14:41 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * corrected logging output, improved javadoc * * Revision 1.19 2006/01/05 14:22:57 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * POST method now appends parameters to body instead of header * * Revision 1.18 2005/12/28 08:40:12 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * corrected javadoc * * Revision 1.17 2005/12/19 16:42:11 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added authentication using authentication-alias * * Revision 1.16 2005/10/18 07:06:48 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * improved logging config, based now on ISenderWithParametersBase * * Revision 1.15 2005/10/03 13:19:07 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * replaced IbisMultiThreadedConnectionManager with original MultiThreadedConnectionMananger * * Revision 1.14 2005/02/24 12:13:14 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added follow redirects and truststoretype * * Revision 1.13 2005/02/02 16:36:26 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added hostname verification, default=false * * Revision 1.12 2004/12/23 16:11:13 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * Explicit check for open connections * * Revision 1.11 2004/12/23 12:12:12 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * staleChecking optional * * Revision 1.10 2004/10/19 06:39:21 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * modified parameter handling, introduced IWithParameters * * Revision 1.9 2004/10/14 15:35:10 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * refactored AuthSSLProtocolSocketFactory group * * Revision 1.8 2004/10/12 15:10:17 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * made parameterized version * * Revision 1.7 2004/09/09 14:50:07 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added JDK1.3.x compatibility * * Revision 1.6 2004/09/08 14:18:34 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * early initialization of SocketFactory * * Revision 1.5 2004/09/01 12:24:16 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * improved fault handling * * Revision 1.4 2004/08/31 15:51:37 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added extractResult method * * Revision 1.3 2004/08/31 10:13:35 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added security handling * * Revision 1.2 2004/08/24 11:41:27 unknown <unknown@ibissource.org> * Remove warnings * * Revision 1.1 2004/08/20 13:04:40 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * first version * */ package nl.nn.adapterframework.http; import java.io.IOException; import java.net.URL; import java.net.URLEncoder; import java.security.Security; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.HasPhysicalDestination; import nl.nn.adapterframework.core.ParameterException; import nl.nn.adapterframework.core.SenderException; import nl.nn.adapterframework.core.SenderWithParametersBase; import nl.nn.adapterframework.core.TimeOutException; import nl.nn.adapterframework.parameters.ParameterResolutionContext; import nl.nn.adapterframework.parameters.ParameterValue; import nl.nn.adapterframework.parameters.ParameterValueList; import nl.nn.adapterframework.util.ClassUtils; import nl.nn.adapterframework.util.CredentialFactory; import nl.nn.adapterframework.util.Misc; import org.apache.commons.httpclient.Credentials; import org.apache.commons.httpclient.HostConfiguration; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.StatusLine; import org.apache.commons.httpclient.URI; import org.apache.commons.httpclient.URIException; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.lang.StringUtils; public class HttpSender extends SenderWithParametersBase implements HasPhysicalDestination { public static final String version = "$RCSfile: HttpSender.java,v $ $Revision: 1.38 $ $Date: 2009-11-12 13:50:03 $"; private String url; private String methodType="GET"; // GET or POST private String contentType="text/html; charset="+Misc.DEFAULT_INPUT_STREAM_ENCODING; private int timeout=10000; private int maxConnections=10; private int maxConnectionRetries=1; private int maxExecuteRetries=1; private String authAlias; private String userName; private String password; private String proxyHost; private int proxyPort=80; private String proxyAuthAlias; private String proxyUserName; private String proxyPassword; private String proxyRealm=null; private String keystoreType="pkcs12"; private String certificate; private String certificateAuthAlias; private String certificatePassword; private String truststore=null; private String truststorePassword=null; private String truststoreAuthAlias; private String truststoreType="jks"; private boolean verifyHostname=true; private boolean followRedirects=true; private boolean jdk13Compatibility=false; private boolean staleChecking=true; private boolean encodeMessages=false; protected URI uri; private MultiThreadedHttpConnectionManager connectionManager; protected HttpClient httpclient; // /* // * connection manager that checks connections to be open before handing them to HttpMethod. // * Use of this connection manager prevents SocketExceptions to occur. // * // */ // private class IbisMultiThreadedHttpConnectionManager extends MultiThreadedHttpConnectionManager { // protected boolean checkConnection(HttpConnection connection) { // boolean status = connection.isOpen(); // //log.debug(getLogPrefix()+"IbisMultiThreadedHttpConnectionManager connection open ["+status+"]"); // if (status) { // try { // connection.setSoTimeout(connection.getSoTimeout()); // } catch (SocketException e) { // log.warn(getLogPrefix()+"IbisMultiThreadedHttpConnectionManager SocketException while checking: "+ e.getMessage()); // connection.close(); // return false; // connection.close(); // return false; // return true; // public HttpConnection getConnection(HostConfiguration hostConfiguration) { // //log.debug(getLogPrefix()+"IbisMultiThreadedHttpConnectionManager getConnection(HostConfiguration)"); // HttpConnection result = super.getConnection(hostConfiguration); // int count=getMaxConnectionRetries(); // while (count-->0 && !checkConnection(result)) { // log.info("releasing failed connection, connectionRetries left ["+count+"]"); // releaseConnection(result); // result= super.getConnection(hostConfiguration); // return result; // public HttpConnection getConnection(HostConfiguration hostConfiguration, long timeout) throws HttpException { // //log.debug(getLogPrefix()+"IbisMultiThreadedHttpConnectionManager getConnection(HostConfiguration, timeout["+timeout+"])"); // HttpConnection result = super.getConnection(hostConfiguration, timeout); // int count=getMaxConnectionRetries(); // while (count-->0 && !checkConnection(result)) { // log.info("releasing failed connection, connectionRetries left ["+count+"]"); // releaseConnection(result); // result= super.getConnection(hostConfiguration, timeout); // return result; protected void addProvider(String name) { try { Class clazz = Class.forName(name); Security.addProvider((java.security.Provider)clazz.newInstance()); } catch (Throwable t) { log.error(getLogPrefix()+"cannot add provider ["+name+"], "+t.getClass().getName()+": "+t.getMessage()); } } public void configure() throws ConfigurationException { super.configure(); // System.setProperty("javax.net.debug","all"); // normaal Java // System.setProperty("javax.net.debug","true"); // IBM java httpclient = new HttpClient(); httpclient.setTimeout(getTimeout()); httpclient.setConnectionTimeout(getTimeout()); httpclient.setHttpConnectionFactoryTimeout(getTimeout()); if (paramList!=null) { paramList.configure(); } if (StringUtils.isEmpty(getUrl())) { throw new ConfigurationException(getLogPrefix()+"Url must be specified"); } if (getMaxConnections()<=0) { throw new ConfigurationException(getLogPrefix()+"maxConnections is set to ["+getMaxConnections()+"], which is not enough for adequate operation"); } try { uri = new URI(getUrl()); int port = uri.getPort(); if (port<1) { try { log.debug(getLogPrefix()+"looking up protocol for scheme ["+uri.getScheme()+"]"); port = Protocol.getProtocol(uri.getScheme()).getDefaultPort(); } catch (IllegalStateException e) { log.debug(getLogPrefix()+"protocol for scheme ["+uri.getScheme()+"] not found, setting port to 80",e); port=80; } } if (uri.getPath()==null) { uri.setPath("/"); } log.info(getLogPrefix()+"created uri: scheme=["+uri.getScheme()+"] host=["+uri.getHost()+"] port=["+port+"] path=["+uri.getPath()+"]"); URL certificateUrl=null; URL truststoreUrl=null; if (!StringUtils.isEmpty(getCertificate())) { certificateUrl = ClassUtils.getResourceURL(this, getCertificate()); if (certificateUrl==null) { throw new ConfigurationException(getLogPrefix()+"cannot find URL for certificate resource ["+getCertificate()+"]"); } log.info(getLogPrefix()+"resolved certificate-URL to ["+certificateUrl.toString()+"]"); } if (!StringUtils.isEmpty(getTruststore())) { truststoreUrl = ClassUtils.getResourceURL(this, getTruststore()); if (truststoreUrl==null) { throw new ConfigurationException(getLogPrefix()+"cannot find URL for truststore resource ["+getTruststore()+"]"); } log.info(getLogPrefix()+"resolved truststore-URL to ["+truststoreUrl.toString()+"]"); } HostConfiguration hostconfiguration = httpclient.getHostConfiguration(); if (certificateUrl!=null || truststoreUrl!=null) { AuthSSLProtocolSocketFactoryBase socketfactory ; try { CredentialFactory certificateCf = new CredentialFactory(getCertificateAuthAlias(), null, getCertificatePassword()); CredentialFactory truststoreCf = new CredentialFactory(getTruststoreAuthAlias(), null, getTruststorePassword()); if (isJdk13Compatibility()) { addProvider("sun.security.provider.Sun"); addProvider("com.sun.net.ssl.internal.ssl.Provider"); System.setProperty("java.protocol.handler.pkgs","com.sun.net.ssl.internal.www.protocol"); socketfactory = new AuthSSLProtocolSocketFactoryForJsse10x( certificateUrl, certificateCf.getPassword(), getKeystoreType(), truststoreUrl, truststoreCf.getPassword(), getTruststoreType(), isVerifyHostname()); } else { socketfactory = new AuthSSLProtocolSocketFactory( certificateUrl, certificateCf.getPassword(), getKeystoreType(), truststoreUrl, truststoreCf.getPassword(), getTruststoreType(),isVerifyHostname()); } socketfactory.initSSLContext(); } catch (Throwable t) { throw new ConfigurationException(getLogPrefix()+"cannot create or initialize SocketFactory",t); } Protocol authhttps = new Protocol(uri.getScheme(), socketfactory, port); hostconfiguration.setHost(uri.getHost(),port,authhttps); } else { hostconfiguration.setHost(uri.getHost(),port,uri.getScheme()); } log.info(getLogPrefix()+"configured httpclient for host ["+hostconfiguration.getHostURL()+"]"); CredentialFactory cf = new CredentialFactory(getAuthAlias(), getUserName(), getPassword()); if (!StringUtils.isEmpty(cf.getUsername())) { httpclient.getState().setAuthenticationPreemptive(true); Credentials defaultcreds = new UsernamePasswordCredentials(cf.getUsername(), cf.getPassword()); httpclient.getState().setCredentials(null, uri.getHost(), defaultcreds); } if (!StringUtils.isEmpty(getProxyHost())) { CredentialFactory pcf = new CredentialFactory(getProxyAuthAlias(), getProxyUserName(), getProxyPassword()); httpclient.getHostConfiguration().setProxy(getProxyHost(), getProxyPort()); httpclient.getState().setProxyCredentials(getProxyRealm(), getProxyHost(), new UsernamePasswordCredentials(pcf.getUsername(), pcf.getPassword())); } } catch (URIException e) { throw new ConfigurationException(getLogPrefix()+"cannot interprete uri ["+getUrl()+"]"); } } public void open() { // connectionManager = new IbisMultiThreadedHttpConnectionManager(); connectionManager = new HttpConnectionManager(0,getName()); connectionManager.setMaxConnectionsPerHost(getMaxConnections()); log.debug(getLogPrefix()+"set up connectionManager, stale checking ["+connectionManager.isConnectionStaleCheckingEnabled()+"]"); if (connectionManager.isConnectionStaleCheckingEnabled() != isStaleChecking()) { log.info(getLogPrefix()+"set up connectionManager, setting stale checking ["+isStaleChecking()+"]"); connectionManager.setConnectionStaleCheckingEnabled(isStaleChecking()); } httpclient.setHttpConnectionManager(connectionManager); } public void close() { connectionManager.shutdown(); connectionManager=null; } public boolean isSynchronous() { return true; } protected boolean appendParameters(boolean parametersAppended, StringBuffer path, ParameterValueList parameters) { if (parameters!=null) { log.debug(getLogPrefix()+"appending ["+parameters.size()+"] parameters"); } for(int i=0; i<parameters.size(); i++) { if (parametersAppended) { path.append("&"); } else { path.append("?"); parametersAppended = true; } ParameterValue pv = parameters.getParameterValue(i); String parameterToAppend=pv.getDefinition().getName()+"="+URLEncoder.encode(pv.asStringValue("")); log.debug(getLogPrefix()+"appending parameter ["+parameterToAppend+"]"); path.append(parameterToAppend); } return parametersAppended; } protected HttpMethod getMethod(String message, ParameterValueList parameters) throws SenderException { try { boolean queryParametersAppended = false; if (isEncodeMessages()) { message = URLEncoder.encode(message); } StringBuffer path = new StringBuffer(uri.getPath()); if (!StringUtils.isEmpty(uri.getQuery())) { path.append("?"+uri.getQuery()); queryParametersAppended = true; } if (getMethodType().equals("GET")) { if (parameters!=null) { queryParametersAppended = appendParameters(queryParametersAppended,path,parameters); log.debug(getLogPrefix()+"path after appending of parameters ["+path.toString()+"]"); } GetMethod result = new GetMethod(path+(parameters==null? message:"")); log.debug(getLogPrefix()+"HttpSender constructed GET-method ["+result.getQueryString()+"]"); return result; } else { if (getMethodType().equals("POST")) { PostMethod postMethod = new PostMethod(path.toString()); if (StringUtils.isNotEmpty(getContentType())) { postMethod.setRequestHeader("Content-Type",getContentType()); } if (parameters!=null) { StringBuffer msg = new StringBuffer(message); appendParameters(true,msg,parameters); if (StringUtils.isEmpty(message) && msg.length()>1) { message=msg.substring(1); } else { message=msg.toString(); } } postMethod.setRequestBody(message); return postMethod; } else { throw new SenderException("unknown methodtype ["+getMethodType()+"], must be either POST or GET"); } } } catch (URIException e) { throw new SenderException(getLogPrefix()+"cannot find path from url ["+getUrl()+"]", e); } } public String extractResult(HttpMethod httpmethod) throws SenderException, IOException { int statusCode = httpmethod.getStatusCode(); if (statusCode!=200) { throw new SenderException(getLogPrefix()+"httpstatus "+statusCode+": "+httpmethod.getStatusText()); } return httpmethod.getResponseBodyAsString(); } public String sendMessage(String correlationID, String message, ParameterResolutionContext prc) throws SenderException, TimeOutException { ParameterValueList pvl = null; try { if (prc !=null && paramList !=null) { pvl=prc.getValues(paramList); } } catch (ParameterException e) { throw new SenderException(getLogPrefix()+"Sender ["+getName()+"] caught exception evaluating parameters",e); } HttpMethod httpmethod=getMethod(message, pvl); if (!"POST".equals(getMethodType())) { httpmethod.setFollowRedirects(isFollowRedirects()); } String result = null; int statusCode = -1; int count=getMaxExecuteRetries(); String msg = null; try { while (count-->=0 && statusCode==-1) { try { log.debug(getLogPrefix()+"executing method"); statusCode = httpclient.executeMethod(httpmethod); log.debug(getLogPrefix()+"executed method"); if (log.isDebugEnabled()) { StatusLine statusline = httpmethod.getStatusLine(); if (statusline!=null) { log.debug(getLogPrefix()+"status:"+statusline.toString()); } else { log.debug(getLogPrefix()+"no statusline found"); } } result = extractResult(httpmethod); if (log.isDebugEnabled()) { log.debug(getLogPrefix()+"retrieved result ["+result+"]"); } } catch (HttpException e) { Throwable throwable = e.getCause(); String cause = null; if (throwable!=null) { cause = throwable.toString(); } if (e!=null) { msg = e.getMessage(); } log.warn("httpException with message [" + msg + "] and cause [" + cause + "], executeRetries left [" + count + "]"); } catch (IOException e) { httpmethod.abort(); throw new SenderException(e); } } } finally { httpmethod.releaseConnection(); } if (statusCode==-1){ if (StringUtils.contains(msg.toUpperCase(), "TIMEOUTEXCEPTION")) { //java.net.SocketTimeoutException: Read timed out throw new TimeOutException("Failed to recover from timeout exception"); } else { throw new SenderException("Failed to recover from exception"); } } return result; } public String sendMessage(String correlationID, String message) throws SenderException, TimeOutException { return sendMessage(correlationID, message, null); } public String getPhysicalDestinationName() { return getUrl(); } public String getUrl() { return url; } public String getProxyHost() { return proxyHost; } public String getProxyPassword() { return proxyPassword; } public int getProxyPort() { return proxyPort; } public String getProxyUserName() { return proxyUserName; } public void setUrl(String string) { url = string; } public void setProxyHost(String string) { proxyHost = string; } public void setProxyPassword(String string) { proxyPassword = string; } public void setProxyPort(int i) { proxyPort = i; } public void setProxyUserName(String string) { proxyUserName = string; } public String getProxyRealm() { return proxyRealm; } public void setProxyRealm(String string) { proxyRealm = string; } public String getPassword() { return password; } public String getUserName() { return userName; } public void setPassword(String string) { password = string; } public void setUserName(String string) { userName = string; } public String getMethodType() { return methodType; } public void setMethodType(String string) { methodType = string; } public String getCertificate() { return certificate; } public String getCertificatePassword() { return certificatePassword; } public String getKeystoreType() { return keystoreType; } public void setCertificate(String string) { certificate = string; } public void setCertificatePassword(String string) { certificatePassword = string; } public void setKeystoreType(String string) { keystoreType = string; } public String getTruststore() { return truststore; } public String getTruststorePassword() { return truststorePassword; } public void setTruststore(String string) { truststore = string; } public void setTruststorePassword(String string) { truststorePassword = string; } public int getTimeout() { return timeout; } public void setTimeout(int i) { timeout = i; } public int getMaxConnections() { return maxConnections; } public void setMaxConnections(int i) { maxConnections = i; } public boolean isJdk13Compatibility() { return jdk13Compatibility; } public void setJdk13Compatibility(boolean b) { jdk13Compatibility = b; } public boolean isEncodeMessages() { return encodeMessages; } public void setEncodeMessages(boolean b) { encodeMessages = b; } public boolean isStaleChecking() { return staleChecking; } public void setStaleChecking(boolean b) { staleChecking = b; } public boolean isVerifyHostname() { return verifyHostname; } public void setVerifyHostname(boolean b) { verifyHostname = b; } public boolean isFollowRedirects() { return followRedirects; } public void setFollowRedirects(boolean b) { followRedirects = b; } public String getTruststoreType() { return truststoreType; } public void setTruststoreType(String string) { truststoreType = string; } public String getAuthAlias() { return authAlias; } public String getCertificateAuthAlias() { return certificateAuthAlias; } public String getProxyAuthAlias() { return proxyAuthAlias; } public String getTruststoreAuthAlias() { return truststoreAuthAlias; } public void setAuthAlias(String string) { authAlias = string; } public void setCertificateAuthAlias(String string) { certificateAuthAlias = string; } public void setProxyAuthAlias(String string) { proxyAuthAlias = string; } public void setTruststoreAuthAlias(String string) { truststoreAuthAlias = string; } public void setMaxConnectionRetries(int i) { maxConnectionRetries = i; } public int getMaxConnectionRetries() { return maxConnectionRetries; } public void setMaxExecuteRetries(int i) { maxExecuteRetries = i; } public int getMaxExecuteRetries() { return maxExecuteRetries; } public void setContentType(String string) { contentType = string; } public String getContentType() { return contentType; } }
package org.joda.time.base; import java.io.Serializable; import org.joda.time.DateTimeUtils; import org.joda.time.ReadableDuration; import org.joda.time.ReadableInstant; import org.joda.time.convert.ConverterManager; import org.joda.time.convert.DurationConverter; import org.joda.time.field.FieldUtils; /** * BaseDuration is an abstract implementation of ReadableDuration that stores * data in a <code>long</code> duration milliseconds field. * <p> * This class should generally not be used directly by API users. * The {@link ReadableDuration} interface should be used when different * kinds of duration objects are to be referenced. * <p> * BaseDuration subclasses may be mutable and not thread-safe. * * @author Brian S O'Neill * @author Stephen Colebourne * @since 1.0 */ public class BaseDuration extends AbstractDuration implements ReadableDuration, Serializable { /** Serialization version */ private static final long serialVersionUID = 2581698638990L; /** The duration length */ private long iMillis; /** * Creates a duration from the given millisecond duration. * * @param duration the duration, in milliseconds */ public BaseDuration(long duration) { super(); iMillis = duration; } /** * Creates a duration from the given interval endpoints. * * @param startInstant interval start, in milliseconds * @param endInstant interval end, in milliseconds * @throws ArithmeticException if the duration exceeds a 64 bit long */ public BaseDuration(long startInstant, long endInstant) { super(); iMillis = FieldUtils.safeAdd(endInstant, -startInstant); } /** * Creates a duration from the given interval endpoints. * * @param start interval start, null means now * @param end interval end, null means now * @throws ArithmeticException if the duration exceeds a 64 bit long */ public BaseDuration(ReadableInstant start, ReadableInstant end) { super(); if (start == end) { iMillis = 0L; } else { long startMillis = DateTimeUtils.getInstantMillis(start); long endMillis = DateTimeUtils.getInstantMillis(end); iMillis = FieldUtils.safeAdd(endMillis, -startMillis); } } public BaseDuration(Object duration) { super(); DurationConverter converter = ConverterManager.getInstance().getDurationConverter(duration); iMillis = converter.getDurationMillis(duration); } /** * Gets the length of this duration in milliseconds. * * @return the length of the duration in milliseconds. */ public long getMillis() { return iMillis; } /** * Sets the length of this duration in milliseconds. * * @param duration the new length of the duration */ public void setMillis(long duration) { iMillis = duration; } }
package com.dmdirc.addons.ui_swing; import com.dmdirc.addons.ui_swing.components.menubar.MenuBar; import com.dmdirc.addons.ui_swing.components.statusbar.FeedbackNag; import com.dmdirc.addons.ui_swing.components.statusbar.SwingStatusBar; import com.dmdirc.addons.ui_swing.dialogs.DialogKeyListener; import com.dmdirc.addons.ui_swing.dialogs.url.URLDialogFactory; import com.dmdirc.addons.ui_swing.framemanager.buttonbar.ButtonBarProvider; import com.dmdirc.addons.ui_swing.framemanager.ctrltab.CtrlTabWindowManager; import com.dmdirc.addons.ui_swing.framemanager.tree.TreeFrameManagerProvider; import com.dmdirc.addons.ui_swing.wizard.firstrun.FirstRunWizardExecutor; import com.dmdirc.ui.WindowManager; import com.dmdirc.ui.core.components.StatusBarManager; import com.google.common.eventbus.EventBus; import java.awt.KeyboardFocusManager; import java.awt.Toolkit; import javax.inject.Inject; import javax.inject.Provider; import javax.inject.Singleton; /** * Manages swing components and dependencies. */ @Singleton public class SwingManager { /** The event queue to use. */ private final DMDircEventQueue eventQueue; /** The window factory in use. */ private final SwingWindowFactory windowFactory; /** The status bar manager to register our status bar with. */ private final StatusBarManager statusBarManager; private final MenuBar menuBar; /** The status bar in use. */ private final SwingStatusBar statusBar; /** The window manager to listen on for events. */ private final WindowManager windowManager; private final CtrlTabWindowManager ctrlTabManager; /** The key listener that supports dialogs. */ private final DialogKeyListener dialogKeyListener; /** Provider of first run executors. */ private final Provider<FirstRunWizardExecutor> firstRunExecutor; /** Provider of feedback nags. */ private final Provider<FeedbackNag> feedbackNagProvider; /** Factory to use to create URL dialogs. */ private final URLDialogFactory urlDialogFactory; /** Link handler for swing links. */ private final SwingLinkHandler linkHandler; /** Bus to listen on for events. */ private final EventBus eventBus; /** The provider to use to create tree-based frame managers. */ private final TreeFrameManagerProvider treeProvider; /** The provider to use to create button-based frame managers. */ private final ButtonBarProvider buttonProvider; /** The provider to use to create new main frames. */ private final Provider<MainFrame> mainFrameProvider; /** The main frame of the Swing UI. */ private MainFrame mainFrame; /** * Creates a new instance of {@link SwingManager}. * * @param eventQueue The event queue to use. * @param windowFactory The window factory in use. * @param windowManager The window manager to listen on for events. * @param statusBarManager The status bar manager to register our status bar with. * @param mainFrameProvider The provider to use for the main frame. * @param menuBar The menu bar to use for the main frame. * @param statusBar The status bar to use in the main frame. * @param ctrlTabManager The window manager that handles ctrl+tab behaviour. * @param dialogKeyListener The key listener that supports dialogs. * @param firstRunExecutor A provider of first run executors. * @param feedbackNagProvider Provider of feedback nags. * @param urlDialogFactory Factory to use to create URL dialogs. * @param linkHandler The handler to use when users click links. * @param eventBus The bus to listen on for events. * @param treeProvider Provider to use for tree-based frame managers. * @param buttonProvider Provider to use for button-based frame managers. */ @Inject public SwingManager( final DMDircEventQueue eventQueue, final SwingWindowFactory windowFactory, final WindowManager windowManager, final StatusBarManager statusBarManager, final Provider<MainFrame> mainFrameProvider, final MenuBar menuBar, final SwingStatusBar statusBar, final CtrlTabWindowManager ctrlTabManager, final DialogKeyListener dialogKeyListener, final Provider<FirstRunWizardExecutor> firstRunExecutor, final Provider<FeedbackNag> feedbackNagProvider, final URLDialogFactory urlDialogFactory, final SwingLinkHandler linkHandler, final EventBus eventBus, final TreeFrameManagerProvider treeProvider, final ButtonBarProvider buttonProvider) { this.eventQueue = eventQueue; this.windowFactory = windowFactory; this.windowManager = windowManager; this.menuBar = menuBar; this.statusBar = statusBar; this.statusBarManager = statusBarManager; this.mainFrameProvider = mainFrameProvider; this.ctrlTabManager = ctrlTabManager; this.dialogKeyListener = dialogKeyListener; this.firstRunExecutor = firstRunExecutor; this.feedbackNagProvider = feedbackNagProvider; this.urlDialogFactory = urlDialogFactory; this.linkHandler = linkHandler; this.eventBus = eventBus; this.treeProvider = treeProvider; this.buttonProvider = buttonProvider; } /** * Handles loading of the UI. */ public void load() { this.mainFrame = mainFrameProvider.get(); this.mainFrame.setMenuBar(menuBar); this.mainFrame.setWindowManager(ctrlTabManager); this.mainFrame.setStatusBar(statusBar); this.mainFrame.initComponents(); installEventQueue(); installKeyListener(); windowManager.addListenerAndSync(windowFactory); statusBarManager.registerStatusBar(statusBar); eventBus.register(linkHandler); } /** * Handles unloading of the UI. */ public void unload() { uninstallEventQueue(); uninstallKeyListener(); windowManager.removeListener(windowFactory); windowFactory.dispose(); mainFrame.dispose(); statusBarManager.unregisterStatusBar(statusBar); eventBus.unregister(linkHandler); } /** * Gets a first run wizard executor to use. * * @return A first run wizard executor. */ public FirstRunWizardExecutor getFirstRunExecutor() { return firstRunExecutor.get(); } @Deprecated public Provider<FeedbackNag> getFeedbackNagProvider() { return feedbackNagProvider; } @Deprecated public URLDialogFactory getUrlDialogFactory() { return urlDialogFactory; } /** * Retrieves the main frame. * * @return A main frame instance. * * @deprecated Should be injected. */ @Deprecated public MainFrame getMainFrame() { return mainFrame; } public TreeFrameManagerProvider getTreeProvider() { return treeProvider; } public ButtonBarProvider getButtonProvider() { return buttonProvider; } /** * Installs the DMDirc event queue. */ private void installEventQueue() { UIUtilities.invokeAndWait(new Runnable() { @Override public void run() { Toolkit.getDefaultToolkit().getSystemEventQueue().push(eventQueue); } }); } /** * Removes the DMDirc event queue. */ private void uninstallEventQueue() { eventQueue.pop(); } /** * Installs the dialog key listener. */ private void installKeyListener() { UIUtilities.invokeAndWait(new Runnable() { @Override public void run() { KeyboardFocusManager.getCurrentKeyboardFocusManager() .addKeyEventDispatcher(dialogKeyListener); } }); } /** * Removes the dialog key listener. */ private void uninstallKeyListener() { KeyboardFocusManager.getCurrentKeyboardFocusManager() .removeKeyEventDispatcher(dialogKeyListener); } }
package com.ecyrd.jspwiki; import java.util.Properties; import java.io.UnsupportedEncodingException; import javax.servlet.http.HttpServletRequest; public class DefaultURLConstructor implements URLConstructor { private WikiEngine m_engine; private String m_viewURLPattern = "%uWiki.jsp?page=%n"; /** Are URL styles relative or absolute? */ private boolean m_useRelativeURLStyle = true; public void initialize( WikiEngine engine, Properties properties ) { m_engine = engine; m_useRelativeURLStyle = "relative".equals( properties.getProperty( WikiEngine.PROP_REFSTYLE, "relative" ) ); } private final String doReplacement( String baseptrn, String name, boolean absolute ) { String baseurl = ""; if( absolute || !m_useRelativeURLStyle ) baseurl = m_engine.getBaseURL(); baseptrn = TextUtil.replaceString( baseptrn, "%u", baseurl ); baseptrn = TextUtil.replaceString( baseptrn, "%U", m_engine.getBaseURL() ); baseptrn = TextUtil.replaceString( baseptrn, "%n", m_engine.encodeName(name) ); return baseptrn; } /** * Constructs the actual URL based on the context. */ private String makeURL( String context, String name, boolean absolute ) { if( context.equals(WikiContext.VIEW) ) { if( name == null ) return makeURL("%uWiki.jsp","",absolute); // FIXME return doReplacement( m_viewURLPattern, name, absolute ); } else if( context.equals(WikiContext.EDIT) ) { return doReplacement( "%uEdit.jsp?page=%n", name, absolute ); } else if( context.equals(WikiContext.ATTACH) ) { return doReplacement( "%uattach/%n", name, absolute ); } else if( context.equals(WikiContext.INFO) ) { return doReplacement( "%uPageInfo.jsp?page=%n", name, absolute ); } else if( context.equals(WikiContext.DIFF) ) { return doReplacement( "%uDiff.jsp?page=%n", name, absolute ); } else if( context.equals(WikiContext.NONE) ) { return doReplacement( "%u%n", name, absolute ); } else if( context.equals(WikiContext.UPLOAD) ) { return doReplacement( "%uUpload.jsp?page=%n", name, absolute ); } else if( context.equals(WikiContext.COMMENT) ) { return doReplacement( "%uComment.jsp?page=%n", name, absolute ); } else if( context.equals(WikiContext.ERROR) ) { return doReplacement( "%uError.jsp", name, absolute ); } throw new InternalWikiException("Requested unsupported context "+context); } /** * Constructs the URL with a bunch of parameters. */ public String makeURL( String context, String name, boolean absolute, String parameters ) { if( parameters != null ) { if( context.equals(WikiContext.ATTACH) ) { parameters = "?"+parameters; } parameters = "&amp;"+parameters; } else { parameters = ""; } return makeURL( context, name, absolute )+parameters; } /** * Should parse the "page" parameter from the actual * request. */ public String parsePage( String context, HttpServletRequest request, String encoding ) throws UnsupportedEncodingException { String pagereq = m_engine.safeGetParameter( request, "page" ); if( context.equals(WikiContext.ATTACH) ) { pagereq = parsePageFromURL( request, encoding ); if( pagereq != null ) pagereq = TextUtil.urlDecodeUTF8(pagereq); } return pagereq; } /** * Takes the name of the page from the request URI. * The initial slash is also removed. If there is no page, * returns null. */ public static String parsePageFromURL( HttpServletRequest request, String encoding ) throws UnsupportedEncodingException { String name = request.getPathInfo(); if( name == null || name.length() <= 1 ) { return null; } else if( name.charAt(0) == '/' ) { name = name.substring(1); } name = new String(name.getBytes("ISO-8859-1"), encoding ); return name; } }
package com.fullmetalgalaxy.client; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import com.fullmetalgalaxy.client.board.DlgMessageEvent; import com.fullmetalgalaxy.client.board.MAppMessagesStack; import com.fullmetalgalaxy.client.ressources.Messages; import com.fullmetalgalaxy.model.ChatMessage; import com.fullmetalgalaxy.model.ConnectedUser; import com.fullmetalgalaxy.model.EnuZoom; import com.fullmetalgalaxy.model.GameFilter; import com.fullmetalgalaxy.model.GameType; import com.fullmetalgalaxy.model.ModelFmpUpdate; import com.fullmetalgalaxy.model.ModelUpdateListener; import com.fullmetalgalaxy.model.ModelUpdateListenerCollection; import com.fullmetalgalaxy.model.RpcFmpException; import com.fullmetalgalaxy.model.RpcUtil; import com.fullmetalgalaxy.model.Services; import com.fullmetalgalaxy.model.SourceModelUpdateEvents; import com.fullmetalgalaxy.model.constant.ConfigGameTime; import com.fullmetalgalaxy.model.constant.FmpConstant; import com.fullmetalgalaxy.model.persist.EbAccount; import com.fullmetalgalaxy.model.persist.EbGame; import com.fullmetalgalaxy.model.persist.EbRegistration; import com.fullmetalgalaxy.model.persist.gamelog.AnEvent; import com.fullmetalgalaxy.model.persist.gamelog.AnEventPlay; import com.fullmetalgalaxy.model.persist.gamelog.EbAdmin; import com.fullmetalgalaxy.model.persist.gamelog.EbEvtCancel; import com.fullmetalgalaxy.model.persist.gamelog.EbEvtMessage; import com.fullmetalgalaxy.model.persist.gamelog.EbEvtPlayerTurn; import com.fullmetalgalaxy.model.persist.gamelog.EbGameJoin; import com.fullmetalgalaxy.model.persist.gamelog.EventsPlayBuilder; import com.fullmetalgalaxy.model.persist.gamelog.GameLogType; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.RootPanel; /** * @author Vincent Legendre * */ public class ModelFmpMain implements SourceModelUpdateEvents { private static ModelFmpMain s_ModelFmpMain = new ModelFmpMain(); /** * @return a unique instance of the model on client side */ public static ModelFmpMain model() { return s_ModelFmpMain; } protected String m_gameId = null; protected EbGame m_game = new EbGame(); /** * the list of all widget which will be refreshed after any model change. */ protected ModelUpdateListenerCollection m_listenerCollection = new ModelUpdateListenerCollection(); protected GameFilter m_gameFilter = new GameFilter(); protected EventsPlayBuilder m_actionBuilder = new EventsPlayBuilder(); protected String m_myAccountLogin = null; protected String m_myAccountPseudo = null; protected long m_myAccountId = -1L; protected boolean m_myAccountAdmin = false; protected Date m_lastServerUpdate = new Date(); // connected players (or any other peoples) protected Set<ConnectedUser> m_connectedUsers = new HashSet<ConnectedUser>(); private Map<Long, EbAccount> m_accounts = null; // interface private boolean m_isGridDisplayed = false; private boolean m_isFireCoverDisplayed = false; private EnuZoom m_zoomDisplayed = new EnuZoom( EnuZoom.Medium ); // cloud layer private boolean m_isAtmosphereDisplayed = true; // standard land layer or custom map image private boolean m_isCustomMapDisplayed = false; /** * minimap or players connections informations */ private boolean m_isMiniMapDisplayed = true; /** * if set, user can't do anything else: * - navigate in past actions * - exiting this mode * - if game is puzzle or standard (turn by turn, no time limit) validate to cancel some actions */ private boolean m_isTimeLineMode = false; private int m_currentActionIndex = 0; /** game currentTimeStep at the moment we start time line mode */ private int m_lastTurnPlayed = 0; private boolean m_isModelUpdatePending = false; private int m_successiveRpcErrorCount = 0; protected Map<Long, EbAccount> getAccounts() { if( m_accounts == null ) { m_accounts = new HashMap<Long, EbAccount>(); } return m_accounts; } public EbAccount getAccount(long p_id) { EbAccount account = getAccounts().get( p_id ); if( account == null ) { account = new EbAccount(); account.setLogin( "Unknown" ); } return account; } public EbAccount getAccount(String p_pseudo) { for(Map.Entry<Long, EbAccount> account : getAccounts().entrySet()) { if(account.getValue().getPseudo() != null && account.getValue().getPseudo().equals( p_pseudo )) { return account.getValue(); } } return null; } /** * * @param p_accounts * @return true if at least one account was added */ public boolean addAllAccounts(Map<Long, EbAccount> p_accounts) { boolean added = false; // add all new accounts if( m_accounts == null ) { m_accounts = p_accounts; added = true; } else { for( Map.Entry<Long, EbAccount> entry : p_accounts.entrySet() ) { if( !m_accounts.containsKey( entry.getKey() ) ) { m_accounts.put( entry.getKey(), entry.getValue() ); added = true; } } } return added; } /* (non-Javadoc) * @see com.fullmetalgalaxy.model.SourceModelUpdateEvents#subscribeModelUpdateEvent(com.fullmetalgalaxy.client.ModelUpdateListener) */ @Override public void subscribeModelUpdateEvent(ModelUpdateListener p_listener) { m_listenerCollection.add( p_listener ); } /* (non-Javadoc) * @see com.fullmetalgalaxy.model.SourceModelUpdateEvents#removeModelUpdateEvent(com.fullmetalgalaxy.model.ModelUpdateListener) */ @Override public void removeModelUpdateEvent(ModelUpdateListener p_listener) { m_listenerCollection.remove( p_listener ); } /** * This method call 'notifyModelUpdate()' of all childs and father controller. * You should call this method every time the model associated with this controller is updated. * the sub method should first call 'super.notifyModelUpdate()' */ public void notifyModelUpdate() { // setLastUpdate( new Date() ); fireModelUpdate(); } public void fireModelUpdate() { m_listenerCollection.fireModelUpdate( this ); } public ModelFmpMain() { getActionBuilder().setAccountId( getMyAccountId() ); } public void load(EbGame p_model) { if( p_model==null ) { // TODO i18n Window.alert( "Partie non trouve...\nVerifier l'url, mais il ce peut qu'elle ai ete suprime" ); return; } m_updatePeriodInMS = 0; m_game = p_model; getActionBuilder().setGame( getGame() ); m_lastServerUpdate = getGame().getLastServerUpdate(); notifyModelUpdate(); if( p_model.getGameType() != GameType.MultiPlayer ) { LocalGame.loadGame( m_callbackFmpUpdate ); } scheduleUpdateTimer( true ); } /** * @return the gameFilter */ public GameFilter getGameFilter() { return m_gameFilter; } public void setGameFilter(GameFilter p_filter) { m_gameFilter = p_filter; } public EbRegistration getMyRegistration() { if( getGame().getGameType() == GameType.Puzzle ) { return getGame().getCurrentPlayerRegistration(); } if( !isLogged() ) { return null; } for( Iterator<EbRegistration> it = getGame().getSetRegistration().iterator(); it.hasNext(); ) { EbRegistration registration = (EbRegistration)it.next(); if( registration.getAccountId() == getMyAccountId() ) { return registration; } } return null; } private void loadAccountInfoFromPage() { RootPanel panel = RootPanel.get( "fmp_userlogin" ); if( panel == null ) { m_myAccountLogin = ""; } else { m_myAccountLogin = DOM.getElementAttribute( panel.getElement(), "content" ); } panel = RootPanel.get( "fmp_userpseudo" ); if( panel == null ) { m_myAccountPseudo = ""; } else { m_myAccountPseudo = DOM.getElementAttribute( panel.getElement(), "content" ); } panel = RootPanel.get( "fmp_userid" ); if( panel == null ) { m_myAccountId = 0; } else { m_myAccountId = Long.parseLong( DOM.getElementAttribute( panel.getElement(), "content" ) ); } panel = RootPanel.get( "fmp_useradmin" ); if( panel == null ) { m_myAccountAdmin = false; } else { m_myAccountAdmin = true; } } /** * @return the myAccount */ public long getMyAccountId() { if( m_myAccountId == -1 ) { loadAccountInfoFromPage(); } return m_myAccountId; } public boolean iAmAdmin() { if( m_myAccountId == -1 ) { loadAccountInfoFromPage(); } return m_myAccountAdmin; } public String getMyPseudo() { if( m_myAccountPseudo == null ) { loadAccountInfoFromPage(); } return m_myAccountPseudo; } public String getMyLogin() { if( m_myAccountLogin == null ) { loadAccountInfoFromPage(); } return m_myAccountLogin; } public boolean isLogged() { return getMyAccountId() != 0; } public boolean isJoined() { return getMyRegistration() != null; } /** * @return the action */ public ArrayList<AnEventPlay> getActionList() { return getActionBuilder().getActionList(); } public void reinitGame() { m_game = new EbGame(); m_gameId = null; notifyModelUpdate(); } public EbGame getGame() { return m_game; } public void setGameId(String p_id) { m_gameId = p_id; } public String getGameId() { if( m_gameId == null ) { return "" + getGame().getId(); } return m_gameId; } private boolean m_isActionPending = false; private FmpCallback<ModelFmpUpdate> m_callbackEvents = new FmpCallback<ModelFmpUpdate>() { @Override public void onSuccess(ModelFmpUpdate p_result) { super.onSuccess( p_result ); m_successiveRpcErrorCount = 0; m_isActionPending = false; AppMain.instance().stopLoading(); getActionBuilder().clear(); m_callbackFmpUpdate.onSuccess( p_result ); } @Override public void onFailure(Throwable p_caught) { m_successiveRpcErrorCount++; //super.onFailure( p_caught ); m_isActionPending = false; AppMain.instance().stopLoading(); getActionBuilder().cancel(); ModelFmpMain.model().notifyModelUpdate(); m_callbackFmpUpdate.onFailure( p_caught ); // maybe the action failed because the model isn't up to date if( m_successiveRpcErrorCount < 2 ) { serverUpdate(); } else { scheduleUpdateTimer( true ); } } }; public FmpCallback<ModelFmpUpdate> getCallbackEvents() { return m_callbackEvents; } private FmpCallback<ModelFmpUpdate> m_callbackFmpUpdate = new FmpCallback<ModelFmpUpdate>() { @Override public void onSuccess(ModelFmpUpdate p_result) { boolean isActive = false; m_successiveRpcErrorCount = 0; m_isModelUpdatePending = false; if( p_result == null ) { if( m_connectedUsers != null && m_connectedUsers.size() > 1 ) { isActive = true; } scheduleUpdateTimer( isActive ); return; } if( m_isActionPending ) { RpcUtil.logDebug( "model update while action is pending, ignore it." ); return; } try { super.onSuccess( p_result ); if( getLastServerUpdate().after( p_result.getFromUpdate() ) ) { // this is probably because we send an action while a get update was // pending RpcUtil.logDebug( "model update 'from' is after 'lastUpdate', ignore it..." ); scheduleUpdateTimer( isActive ); return; } // add all new accounts addAllAccounts( p_result.getMapAccounts() ); if( p_result.getMapAccounts().size() > 1 ) { isActive = true; } // handle game events first List<AnEvent> events = p_result.getGameEvents(); for( AnEvent event : events ) { if( event.getType() == GameLogType.EvtMessage ) { DlgMessageEvent dlgMsg = new DlgMessageEvent( (EbEvtMessage)event ); dlgMsg.center(); dlgMsg.show(); } if( getGame() != null ) { if( event.getType() == GameLogType.EvtCancel ) { ((EbEvtCancel)event).execCancel( getGame() ); } event.exec( getGame() ); // getGame().getLastUpdate().setTime( // event.getLastUpdate().getTime() ); if( event.getType() != GameLogType.EvtCancel ) { getGame().addEvent( event ); } getGame().getLastServerUpdate().setTime( event.getLastUpdate().getTime() ); getGame().updateLastTokenUpdate( null ); } isActive = true; } // handle chat messages if( p_result.getChatMessages() != null ) { for( ChatMessage message : p_result.getChatMessages() ) { MAppMessagesStack.s_instance.showMessage( message.getFromLogin() + " : " + message.getText() ); isActive = true; } } // handle connected player if( p_result.getConnectedUsers() != null ) { m_connectedUsers = p_result.getConnectedUsers(); if( m_connectedUsers.size() > 1 ) { isActive = true; } for( ConnectedUser connectedUser : m_connectedUsers ) { if( connectedUser.getEndTurnDate() != null ) { // update end turn date EbRegistration registration = getGame().getRegistrationByIdAccount( getAccount( connectedUser.getPseudo() ).getId() ); if( registration != null ) { registration.setEndTurnDate( connectedUser.getEndTurnDate() ); } } } } // last but not least... refresh general last server update getLastServerUpdate().setTime( p_result.getLastUpdate().getTime() ); // if( !updates.getGameEvents().isEmpty() || // !updates.getChatMessages().isEmpty() ) // assume that if we receive an update, something has changed ! ModelFmpMain.model().fireModelUpdate(); } catch( Throwable e ) { RpcUtil.logError( "error ", e ); Window.alert( "unexpected error : " + e ); } // we just receive a model update, schedule next update later scheduleUpdateTimer( isActive ); } @Override public void onFailure(Throwable p_caught) { m_isModelUpdatePending = false; m_successiveRpcErrorCount++; super.onFailure( p_caught ); // maybe the action failed because the model isn't up to date if( m_successiveRpcErrorCount < 2 ) { serverUpdate(); } else { scheduleUpdateTimer( true ); } } }; public Date getLastServerUpdate() { return m_lastServerUpdate; } /** * rpc call to run the current action. * Clear the current action. */ public void runSingleAction(AnEvent p_action) { if( m_isActionPending ) { Window.alert( "Une action a déjà été envoyé au serveur... sans réponse pour l'instant" ); return; } m_isActionPending = true; m_updateTimer.cancel(); AppMain.instance().startLoading(); try { if( !ModelFmpMain.model().isLogged() && getGame().getGameType() == GameType.MultiPlayer ) { // TODO i18n ??? throw new RpcFmpException( "You must be logged to do this action" ); } // do not check player is logged to let him join action // action.check(); cancelUpdateTimer(); if( getGame().getGameType() == GameType.MultiPlayer ) { Services.Util.getInstance().runEvent( p_action, getLastServerUpdate(), m_callbackEvents ); } else { LocalGame.runEvent( p_action, getGame().getLastServerUpdate(), m_callbackEvents ); } } catch( RpcFmpException ex ) { Window.alert( Messages.getString( ex ) ); m_isActionPending = false; AppMain.instance().stopLoading(); getActionBuilder().cancel(); ModelFmpMain.model().notifyModelUpdate(); } catch( Throwable p_caught ) { Window.alert( "Unknown error on client: " + p_caught ); m_isActionPending = false; AppMain.instance().stopLoading(); getActionBuilder().cancel(); } } /** * rpc call to run the current action. * Clear the current action. */ public void runCurrentAction() { if( m_isActionPending ) { Window.alert( "Une action a déjà été envoyé au serveur... sans réponse pour l'instant" ); return; } m_isActionPending = true; m_updateTimer.cancel(); AppMain.instance().startLoading(); try { if( !ModelFmpMain.model().isJoined() ) { // no i18n ? throw new RpcFmpException( "you didn't join this game." ); } // action.check(); cancelUpdateTimer(); getActionBuilder().unexec(); if( getGame().getGameType() == GameType.MultiPlayer ) { Services.Util.getInstance().runAction( getActionBuilder().getActionList(), getLastServerUpdate(), m_callbackEvents ); } else { LocalGame.runAction( getActionBuilder().getActionList(), getGame().getLastServerUpdate(), m_callbackEvents ); } } catch( RpcFmpException ex ) { Window.alert( Messages.getString( ex ) ); m_isActionPending = false; AppMain.instance().stopLoading(); getActionBuilder().cancel(); scheduleUpdateTimer( true ); } catch( Throwable p_caught ) { Window.alert( "Unknown error on client: " + p_caught ); m_isActionPending = false; AppMain.instance().stopLoading(); getActionBuilder().cancel(); ModelFmpMain.model().notifyModelUpdate(); scheduleUpdateTimer( true ); } } public boolean isModelUpdatePending() { return m_isModelUpdatePending; } /** * rpc call to run the current action. * Clear the current action. */ public void endTurn() { EbEvtPlayerTurn action = new EbEvtPlayerTurn(); action.setAccountId( model().getMyAccountId() ); action.setGame( model().getGame() ); runSingleAction( action ); } private int m_updatePeriodInMS = 0; private int getUpdatePeriodInMS() { if( ModelFmpMain.model().getGame().getGameType() == GameType.Puzzle ) { return FmpConstant.localResfreshingPeriod * 1000; } // since comet stuff // return 4000; if( m_updatePeriodInMS <= 0 ) { // compute period in second m_updatePeriodInMS = ModelFmpMain.model().getGame().getEbConfigGameTime() .getTimeStepDurationInSec() / ModelFmpMain.model().getGame().getEbConfigGameTime().getActionPtPerTimeStep(); if( m_updatePeriodInMS < FmpConstant.minimumResfreshingPeriod ) { m_updatePeriodInMS = FmpConstant.minimumResfreshingPeriod; } if( m_updatePeriodInMS > FmpConstant.maximumResfreshingPeriod || ModelFmpMain.model().getGame().getEbConfigGameTime().getTimeStepDurationInSec() == 0 ) { m_updatePeriodInMS = FmpConstant.maximumResfreshingPeriod; } if( getGame().isFinished() ) { m_updatePeriodInMS = FmpConstant.maximumResfreshingPeriod; } // then transform in milisecond m_updatePeriodInMS *= 1000; } return m_updatePeriodInMS; } /** * * after this call, the timer is scheduled to refresh permanently */ public void setUpdatePeriod2Minimum() { m_updatePeriodInMS = FmpConstant.minimumResfreshingPeriod * 1000; cancelUpdateTimer(); m_updateTimer.run(); } public boolean isUpdatePeriod2Minimum() { return m_updatePeriodInMS == FmpConstant.minimumResfreshingPeriod * 1000; } /** * Create a new timer that calls Window.alert(). */ private Timer m_updateTimer = new Timer() { @Override public void run() { cancelUpdateTimer(); serverUpdate(); } }; protected void scheduleUpdateTimer(boolean p_isActive) { cancelUpdateTimer(); if( (getGame().getCurrentPlayerRegistration() != null) && (getGame().getCurrentPlayerRegistration().getEndTurnDate() != null) && (getGame().getCurrentPlayerRegistration().getEndTurnDate().getTime() - System.currentTimeMillis() > 0) && (getGame().getCurrentPlayerRegistration().getEndTurnDate().getTime() - System.currentTimeMillis() < getUpdatePeriodInMS()) ) { m_updateTimer.schedule( (int)(getGame().getCurrentPlayerRegistration().getEndTurnDate() .getTime() - System.currentTimeMillis()) ); } else // if( p_isActive ) { m_updateTimer.schedule( getUpdatePeriodInMS() ); } /*else { m_updateTimer.schedule( FmpConstant.inactiveResfreshingPeriod * 1000 ); }*/ } private void cancelUpdateTimer() { m_updateTimer.cancel(); } /** * rpc call to update the model from server. * after this call, the timer is scheduled to refresh permanently */ protected void serverUpdate() { cancelUpdateTimer(); // if player just send an action to server, cancel this update as it will // come with action response if( m_isActionPending ) { return; } // if player is constructing an action, wait if( !getActionList().isEmpty() ) { m_updateTimer.schedule( 4 * 1000 ); return; } // then call the right service if( getGame().getGameType() == GameType.MultiPlayer ) { Services.Util.getInstance().getModelFmpUpdate( ModelFmpMain.model().getGame().getId(), getLastServerUpdate(), m_callbackFmpUpdate ); } else { LocalGame.modelUpdate( ModelFmpMain.model().getGame().getId(), getLastServerUpdate(), m_callbackFmpUpdate ); } m_isModelUpdatePending = true; } /** * @return the actionBuilder */ public EventsPlayBuilder getActionBuilder() { return m_actionBuilder; } /** * @return the isGridDisplayed */ public boolean isGridDisplayed() { return m_isGridDisplayed; } /** * @param p_isGridDisplayed the isGridDisplayed to set */ public void setGridDisplayed(boolean p_isGridDisplayed) { m_isGridDisplayed = p_isGridDisplayed; fireModelUpdate(); } /** * @return the isAtmosphereDisplayed */ public boolean isAtmosphereDisplayed() { return m_isAtmosphereDisplayed; } /** * @param p_isAtmosphereDisplayed the isAtmosphereDisplayed to set */ public void setAtmosphereDisplayed(boolean p_isAtmosphereDisplayed) { m_isAtmosphereDisplayed = p_isAtmosphereDisplayed; fireModelUpdate(); } /** * @return the isStandardLandDisplayed */ public boolean isCustomMapDisplayed() { return m_isCustomMapDisplayed; } /** * @param p_isCustomMapDisplayed the isStandardLandDisplayed to set */ public void setCustomMapDisplayed(boolean p_isCustomMapDisplayed) { m_isCustomMapDisplayed = p_isCustomMapDisplayed; fireModelUpdate(); } /** * @return the isFireCoverDisplayed */ public boolean isFireCoverDisplayed() { return m_isFireCoverDisplayed; } /** * @param p_isFireCoverDisplayed the isFireCoverDisplayed to set */ public void setFireCoverDisplayed(boolean p_isFireCoverDisplayed) { m_isFireCoverDisplayed = p_isFireCoverDisplayed; fireModelUpdate(); } /** * @return the zoomValueDisplayed */ public EnuZoom getZoomDisplayed() { return m_zoomDisplayed; } /** * @param p_zoomValueDisplayed the zoomValueDisplayed to set */ public void setZoomDisplayed(int p_zoomValueDisplayed) { m_zoomDisplayed = new EnuZoom( p_zoomValueDisplayed ); fireModelUpdate(); } public void setZoomDisplayed(EnuZoom p_zoomDisplayed) { m_zoomDisplayed = p_zoomDisplayed; fireModelUpdate(); } /** * @return the isMiniMapDisplayed */ public boolean isMiniMapDisplayed() { return m_isMiniMapDisplayed; } /** * @param p_isMiniMapDisplayed the isMiniMapDisplayed to set */ public void setMiniMapDisplayed(boolean p_isMiniMapDisplayed) { m_isMiniMapDisplayed = p_isMiniMapDisplayed; fireModelUpdate(); } /** * @return the isTimeLineMode */ public boolean isTimeLineMode() { return m_isTimeLineMode; } /** * @param p_isTimeLineMode the isTimeLineMode to set */ public void setTimeLineMode(boolean p_isTimeLineMode) { getActionBuilder().clear(); m_isTimeLineMode = p_isTimeLineMode; m_lastTurnPlayed = getGame().getCurrentTimeStep(); if( !p_isTimeLineMode ) { timePlay( 99999 ); } m_currentActionIndex = getGame().getLogs().size(); fireModelUpdate(); } public void timeBack(int p_actionCount) { List<AnEvent> logs = getGame().getLogs(); while( (m_currentActionIndex > 0) && (p_actionCount > 0) ) { m_currentActionIndex AnEvent action = logs.get( m_currentActionIndex ); if( !(action instanceof EbAdmin) && !(action instanceof EbGameJoin) && !(action instanceof EbEvtCancel) ) { // unexec action try { logs.get( m_currentActionIndex ).unexec( getGame() ); } catch( RpcFmpException e ) { RpcUtil.logError( "error ", e ); Window.alert( "unexpected error : " + e ); fireModelUpdate(); return; } // don't count automatic action as one action to play if( !action.isAuto() ) { p_actionCount } // if previous action is EvtConstruct, then unexec too if( m_currentActionIndex>0 && logs.get( m_currentActionIndex-1 ).getType() == GameLogType.EvtConstruct ) { p_actionCount++; } } } fireModelUpdate(); } public void timePlay(int p_actionCount) { List<AnEvent> logs = getGame().getLogs(); while( (m_currentActionIndex < logs.size()) && (p_actionCount > 0) ) { AnEvent action = logs.get( m_currentActionIndex ); if( !(action instanceof EbAdmin) && !(action instanceof EbGameJoin) && !(action instanceof EbEvtCancel) ) { // exec action try { action.exec( getGame() ); } catch( RpcFmpException e ) { RpcUtil.logError( "error ", e ); Window.alert( "unexpected error : " + e ); return; } // don't count automatic action as one action to play if( !action.isAuto() && action.getType() != GameLogType.EvtConstruct ) { p_actionCount } // if next action is automatic, then exec too if( m_currentActionIndex<logs.size()-1 && logs.get( m_currentActionIndex+1 ).isAuto() ) { p_actionCount++; } } m_currentActionIndex++; } fireModelUpdate(); } public int getCurrentActionIndex() { return m_currentActionIndex; } /** * User is allowed to cancel action if in puzzle or turn by turn on several day. * He must also be in his own turn. * @return true if user is allowed to cancel action up to 'getCurrentActionIndex()' */ public boolean canCancelAction() { if( getGame().getGameType()==GameType.Puzzle ) { return true; } if( iAmAdmin() ) { return true; } if( getMyRegistration() == null ) { return false; } if( m_lastTurnPlayed != getGame().getCurrentTimeStep() ) { return false; } if( getGame().getConfigGameTime() == ConfigGameTime.Standard && getMyRegistration() == getGame().getCurrentPlayerRegistration() ) { return true; } if( getGame().getConfigGameTime() == ConfigGameTime.StandardAsynch ) { AnEvent event = null; for( int i = m_currentActionIndex; i < getGame().getLogs().size(); i++ ) { event = getGame().getLogs().get( i ); if( event == null || !(event instanceof AnEventPlay) || ((AnEventPlay)event).getAccountId() != getMyAccountId() ) { return false; } } return true; } return false; } /** * @return the connectedPlayer */ public Set<ConnectedUser> getConnectedUsers() { return m_connectedUsers; } public boolean isUserConnected(String p_pseudo) { assert p_pseudo != null; for( ConnectedUser connectedUser : getConnectedUsers() ) { if( p_pseudo.equals( connectedUser.getPseudo() ) ) { return true; } } return false; } public boolean isUserConnected(long p_accountId) { return isUserConnected( model().getAccount( p_accountId ).getPseudo() ); } }
package com.germainz.dynamicalarmicon; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.os.Handler; import android.provider.Settings; import android.text.TextUtils; import android.text.format.DateFormat; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import static de.robv.android.xposed.XposedHelpers.callMethod; import static de.robv.android.xposed.XposedHelpers.callStaticMethod; import static de.robv.android.xposed.XposedHelpers.findAndHookMethod; import static de.robv.android.xposed.XposedHelpers.findClass; import static de.robv.android.xposed.XposedHelpers.getObjectField; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.XC_MethodHook; import de.robv.android.xposed.XC_MethodReplacement; import de.robv.android.xposed.callbacks.XC_LoadPackage; public class XposedMod implements IXposedHookLoadPackage { private ClockDrawable mClockDrawable; private static final String UPDATE_ALARM_ICON = "com.germainz.dynamicalarmicon.UPDATE_ALARM_ICON"; private static final String UPDATE_DESKCLOCK_ICON = "com.germainz.dynamicalarmicon.UPDATE_DESKCLOCK_ICON"; @Override public void handleLoadPackage(XC_LoadPackage.LoadPackageParam lpparam) throws Throwable { if (lpparam.packageName.equals("com.android.systemui")) hookSystemUI(lpparam.classLoader); else if (lpparam.packageName.equals("ch.bitspin.timely")) hookTimely(lpparam.classLoader); else if (lpparam.packageName.equals("com.android.deskclock")) hookDeskClock(lpparam.classLoader); } private void hookSystemUI(final ClassLoader classLoader) { findAndHookMethod("com.android.systemui.statusbar.phone.PhoneStatusBarPolicy", classLoader, "updateAlarm", Intent.class, new XC_MethodReplacement() { @Override protected Object replaceHookedMethod(MethodHookParam param) throws Throwable { boolean alarmSet = ((Intent) param.args[0]).getBooleanExtra("alarmSet", false); Object mService = getObjectField(param.thisObject, "mService"); callMethod(mService, "setIconVisibility", "alarm_clock", alarmSet); if (!alarmSet) return null; Context context = (Context) getObjectField(param.thisObject, "mContext"); String nextAlarm = Settings.System.getString(context.getContentResolver(), Settings.System.NEXT_ALARM_FORMATTED); if (nextAlarm.isEmpty()) return null; String[] nextAlarmTime = nextAlarm.split(" ")[1].split(":"); int nextAlarmHour = Integer.parseInt(nextAlarmTime[0]) % 12; int nextAlarmMinute = Integer.parseInt(nextAlarmTime[1]); Intent intent = new Intent(UPDATE_ALARM_ICON); intent.putExtra("hour", nextAlarmHour); intent.putExtra("minute", nextAlarmMinute); context.sendBroadcast(intent); return null; } } ); findAndHookMethod("com.android.systemui.statusbar.phone.PhoneStatusBar", classLoader, "makeStatusBarView", new XC_MethodHook() { @Override protected void afterHookedMethod(final MethodHookParam param) throws Throwable { BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(final Context context, final Intent intent) { /* Why the short delay? For two reasons: * 1- Some clock apps send the ALARM_CHANGED broadcast before setting * NEXT_ALARM_FORMATTED. * 2- The broadcast is sometimes received and handled *before* the notification is * actually added to the status bar (for UPDATE_DESKCLOCK_ICON). */ new Handler().postDelayed(new Runnable() { @Override public void run() { if (intent.getAction().equals(UPDATE_ALARM_ICON)) { updateAlarmIcon(intent, param.thisObject); } else if (intent.getAction().equals(UPDATE_DESKCLOCK_ICON)) { updateDeskClockIcon(context, param.thisObject); } } }, 5); } }; IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(UPDATE_ALARM_ICON); intentFilter.addAction(UPDATE_DESKCLOCK_ICON); Context context = (Context) getObjectField(param.thisObject, "mContext"); context.registerReceiver(broadcastReceiver, intentFilter); } } ); findAndHookMethod("com.android.systemui.statusbar.StatusBarIconView", classLoader, "updateDrawable", boolean.class, new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { if (getObjectField(param.thisObject, "mSlot").equals("alarm_clock")) param.setResult(false); } } ); } private void hookTimely(final ClassLoader classLoader) { findAndHookMethod("ch.bitspin.timely.alarm.AlarmManager", classLoader, "f", "ch.bitspin.timely.data.AlarmClock", new XC_MethodHook() { @Override protected void beforeHookedMethod(MethodHookParam param) throws Throwable { // Timely actually does this for Android 4.1 and less (but not for 4.2+) but only after the // ALARM_CHANGED intent is sent, which is too late. String nextAlarmFormatted = ""; Context context = (Context) getObjectField(param.thisObject, "e"); Object alarmClock = param.args[0]; if (alarmClock != null) { Object nextAlarmUTC = callStaticMethod(findClass("ch.bitspin.timely.alarm.e", classLoader), "a", alarmClock); if (nextAlarmUTC != null) { Object nextAlarmLocal = callMethod(nextAlarmUTC, "c", (Object) null); String timeFormat = "E kk:mm"; if (!DateFormat.is24HourFormat(context)) timeFormat = "E h:mm aa"; nextAlarmFormatted = (String) DateFormat.format(timeFormat, (Long) callMethod(nextAlarmLocal, "d")); } } Settings.System.putString(context.getContentResolver(), Settings.System.NEXT_ALARM_FORMATTED, nextAlarmFormatted); } } ); } private void hookDeskClock(final ClassLoader classLoader) { XC_MethodHook hook = new XC_MethodHook() { @Override protected void afterHookedMethod(MethodHookParam param) throws Throwable { Context context = (Context) param.args[0]; Intent intent = new Intent(UPDATE_DESKCLOCK_ICON); context.sendBroadcast(intent); } }; findAndHookMethod("com.android.deskclock.alarms.AlarmNotifications", classLoader, "showLowPriorityNotification", Context.class, "com.android.deskclock.provider.AlarmInstance", hook); findAndHookMethod("com.android.deskclock.alarms.AlarmNotifications", classLoader, "showHighPriorityNotification", Context.class, "com.android.deskclock.provider.AlarmInstance", hook); findAndHookMethod("com.android.deskclock.alarms.AlarmNotifications", classLoader, "showMissedNotification", Context.class, "com.android.deskclock.provider.AlarmInstance", hook); findAndHookMethod("com.android.deskclock.alarms.AlarmNotifications", classLoader, "showSnoozeNotification", Context.class, "com.android.deskclock.provider.AlarmInstance", hook); findAndHookMethod("com.android.deskclock.alarms.AlarmNotifications", classLoader, "showAlarmNotification", Context.class, "com.android.deskclock.provider.AlarmInstance", hook); } private void updateAlarmIcon(Intent intent, Object thiz) { int hour = intent.getIntExtra("hour", 0); int minute = intent.getIntExtra("minute", 0); if (mClockDrawable == null) { LinearLayout statusIcons = (LinearLayout) getObjectField(thiz, "mStatusIcons"); for (int i = 0; i < statusIcons.getChildCount(); i++) { View view = statusIcons.getChildAt(i); if (getObjectField(view, "mSlot").equals("alarm_clock")) { mClockDrawable = new ClockDrawable(hour, minute); callMethod(view, "setImageDrawable", mClockDrawable); } } } else { mClockDrawable.setTime(hour, minute); } } private void updateDeskClockIcon(Context context, Object thiz) { LinearLayout notificationIcons = (LinearLayout) getObjectField(thiz, "mNotificationIcons"); Object notificationData = getObjectField(thiz, "mNotificationData"); for (int i = 0; i < notificationIcons.getChildCount(); i++) { View view = notificationIcons.getChildAt(i); if (((String) getObjectField(view, "mSlot")).startsWith("com.android.deskclock/")) { int N = (Integer) callMethod(notificationData, "size"); Object entry = callMethod(notificationData, "get", N - i - 1); View content = (View) getObjectField(entry, "content"); // Get the time from the notification's text. int textId = context.getResources().getIdentifier("text", "id", "android"); String alarmText = (String) ((TextView) content.findViewById(textId)).getText(); String[] alarmTime = alarmText.split(" "); int index = 1; Context deskClockContext = null; try { deskClockContext = context.createPackageContext("com.android.deskclock", Context.CONTEXT_IGNORE_SECURITY); } catch (PackageManager.NameNotFoundException ignored) { } int snoozeUntilId = deskClockContext.getResources().getIdentifier("alarm_alert_snooze_until", "string", "com.android.deskclock"); String snoozeUntilString = deskClockContext.getString(snoozeUntilId); String[] snoozeUntilStringArray = TextUtils.split(snoozeUntilString, "%s"); snoozeUntilString = TextUtils.join("\\E.*\\Q", snoozeUntilStringArray); snoozeUntilString = "\\Q" + snoozeUntilString + "\\E"; if (alarmText.matches(snoozeUntilString)) index = snoozeUntilString.split(" ").length; alarmTime = alarmTime[index].split(":"); final int alarmHour = Integer.parseInt(alarmTime[0]) % 12; final int alarmMinute = Integer.parseInt(alarmTime[1]); // Set the small icon. ClockDrawable clockDrawable = new ClockDrawable(alarmHour, alarmMinute); callMethod(view, "setImageDrawable", new ClockDrawable(alarmHour, alarmMinute)); // Set the large icon (shown in the notification shade) for the normal and expanded views. int iconId = context.getResources().getIdentifier("icon", "id", "android"); ImageView icon = (ImageView) content.findViewById(iconId); icon.setImageDrawable(clockDrawable); View big = (View) getObjectField(entry, "expandedBig"); icon = (ImageView) big.findViewById(iconId); icon.setImageDrawable(clockDrawable); } } } }
package com.itmill.toolkit.ui; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.Locale; import java.util.Map; import java.util.Set; import com.itmill.toolkit.Application; import com.itmill.toolkit.event.EventRouter; import com.itmill.toolkit.event.MethodEventSource; import com.itmill.toolkit.terminal.ErrorMessage; import com.itmill.toolkit.terminal.PaintException; import com.itmill.toolkit.terminal.PaintTarget; import com.itmill.toolkit.terminal.Resource; import com.itmill.toolkit.terminal.VariableOwner; /** * An abstract class that defines default implementation for the * {@link Component} interface. Basic UI components that are not derived from an * external component can inherit this class to easily qualify as a IT Mill * Toolkit component. Most components in the toolkit do just that. * * @author IT Mill Ltd. * @version * @VERSION@ * @since 3.0 */ public abstract class AbstractComponent implements Component, MethodEventSource { /** * Style names. */ private ArrayList styles; /** * Caption text. */ private String caption; /** * Application specific data object. */ private Object applicationData; /** * Icon to be shown together with caption. */ private Resource icon; /** * Is the component enable (its normal usage is allowed). */ private boolean enabled = true; /** * Is the component visible (it is rendered). */ private boolean visible = true; /** * Is the component read-only ? */ private boolean readOnly = false; /** * Description of the usage (XML). */ private String description = null; /** * The container this component resides in. */ private Component parent = null; /** * The EventRouter used for the event model. */ private EventRouter eventRouter = null; /** * The internal error message of the component. */ private ErrorMessage componentError = null; /** * Immediate mode: if true, all variable changes are required to be sent * from the terminal immediately. */ private boolean immediate = false; /** * Locale of this component. */ private Locale locale; /** * List of repaint request listeners or null if not listened at all. */ private LinkedList repaintRequestListeners = null; /** * Are all the repaint listeners notified about recent changes ? */ private boolean repaintRequestListenersNotified = false; private String testingId; /* Sizeable fields */ private int width = SIZE_UNDEFINED; private int height = SIZE_UNDEFINED; private int widthUnit = UNITS_PIXELS; private int heightUnit = UNITS_PIXELS; /** * Constructs a new Component. */ public AbstractComponent() { } /** * Gets the UIDL tag corresponding to the component. * * @return the component's UIDL tag as <code>String</code> */ public abstract String getTag(); public void setDebugId(String id) { testingId = id; } public String getDebugId() { return testingId; } /** * Gets style for component. Multiple styles are joined with spaces. * * @return the component's styleValue of property style. * @deprecated Use getStyleName() instead; renamed for consistency and to * indicate that "style" should not be used to switch client * side implementation, only to style the component. */ public String getStyle() { return getStyleName(); } /** * Sets and replaces all previous style names of the component. This method * will trigger a * {@link com.itmill.toolkit.terminal.Paintable.RepaintRequestEvent RepaintRequestEvent}. * * @param style * the new style of the component. * @deprecated Use setStyleName() instead; renamed for consistency and to * indicate that "style" should not be used to switch client * side implementation, only to style the component. */ public void setStyle(String style) { setStyleName(style); } /* * Gets the component's style. Don't add a JavaDoc comment here, we use the * default documentation from implemented interface. */ public String getStyleName() { String s = ""; if (styles != null) { for (final Iterator it = styles.iterator(); it.hasNext();) { s += (String) it.next(); if (it.hasNext()) { s += " "; } } } return s; } /* * Sets the component's style. Don't add a JavaDoc comment here, we use the * default documentation from implemented interface. */ public void setStyleName(String style) { if (style == null || "".equals(style)) { styles = null; requestRepaint(); return; } if (styles == null) { styles = new ArrayList(); } styles.clear(); styles.add(style); requestRepaint(); } public void addStyleName(String style) { if (style == null || "".equals(style)) { return; } if (styles == null) { styles = new ArrayList(); } if (!styles.contains(style)) { styles.add(style); requestRepaint(); } } public void removeStyleName(String style) { styles.remove(style); requestRepaint(); } /* * Get's the component's caption. Don't add a JavaDoc comment here, we use * the default documentation from implemented interface. */ public String getCaption() { return caption; } /** * Sets the component's caption <code>String</code>. Caption is the * visible name of the component. This method will trigger a * {@link com.itmill.toolkit.terminal.Paintable.RepaintRequestEvent RepaintRequestEvent}. * * @param caption * the new caption <code>String</code> for the component. */ public void setCaption(String caption) { this.caption = caption; requestRepaint(); } /* * Don't add a JavaDoc comment here, we use the default documentation from * implemented interface. */ public Locale getLocale() { if (locale != null) { return locale; } if (parent != null) { return parent.getLocale(); } final Application app = getApplication(); if (app != null) { return app.getLocale(); } return null; } /** * Sets the locale of this component. * * @param locale * the locale to become this component's locale. */ public void setLocale(Locale locale) { this.locale = locale; } /* * Gets the component's icon resource. Don't add a JavaDoc comment here, we * use the default documentation from implemented interface. */ public Resource getIcon() { return icon; } /** * Sets the component's icon. This method will trigger a * {@link com.itmill.toolkit.terminal.Paintable.RepaintRequestEvent RepaintRequestEvent}. * * @param icon * the icon to be shown with the component's caption. */ public void setIcon(Resource icon) { this.icon = icon; requestRepaint(); } /* * Tests if the component is enabled or not. Don't add a JavaDoc comment * here, we use the default documentation from implemented interface. */ public boolean isEnabled() { return enabled && isVisible(); } /* * Enables or disables the component. Don't add a JavaDoc comment here, we * use the default documentation from implemented interface. */ public void setEnabled(boolean enabled) { if (this.enabled != enabled) { this.enabled = enabled; requestRepaint(); } } /* * Tests if the component is in the immediate mode. Don't add a JavaDoc * comment here, we use the default documentation from implemented * interface. */ public boolean isImmediate() { return immediate; } /** * Sets the component's immediate mode to the specified status. This method * will trigger a * {@link com.itmill.toolkit.terminal.Paintable.RepaintRequestEvent RepaintRequestEvent}. * * @param immediate * the boolean value specifying if the component should be in * the immediate mode after the call. * @see Component#isImmediate() */ public void setImmediate(boolean immediate) { this.immediate = immediate; requestRepaint(); } /* * Tests if the component is visible. Don't add a JavaDoc comment here, we * use the default documentation from implemented interface. */ public boolean isVisible() { return visible; } /* * Sets the components visibility. Don't add a JavaDoc comment here, we use * the default documentation from implemented interface. */ public void setVisible(boolean visible) { if (this.visible != visible) { this.visible = visible; // Instead of requesting repaint normally we // fire the event directly to assure that the // event goes through event in the component might // now be invisible fireRequestRepaintEvent(null); } } /** * <p> * Gets the component's description. The description can be used to briefly * describe the state of the component to the user. The description string * may contain certain XML tags: * </p> * * <p> * <table border=1> * <tr> * <td width=120><b>Tag</b></td> * <td width=120><b>Description</b></td> * <td width=120><b>Example</b></td> * </tr> * <tr> * <td>&lt;b></td> * <td>bold</td> * <td><b>bold text</b></td> * </tr> * <tr> * <td>&lt;i></td> * <td>italic</td> * <td><i>italic text</i></td> * </tr> * <tr> * <td>&lt;u></td> * <td>underlined</td> * <td><u>underlined text</u></td> * </tr> * <tr> * <td>&lt;br></td> * <td>linebreak</td> * <td>N/A</td> * </tr> * <tr> * <td>&lt;ul><br> * &lt;li>item1<br> * &lt;li>item1<br> * &lt;/ul></td> * <td>item list</td> * <td> * <ul> * <li>item1 * <li>item2 * </ul> * </td> * </tr> * </table> * </p> * * <p> * These tags may be nested. * </p> * * @return component's description <code>String</code> */ public String getDescription() { return description; } /** * Sets the component's description. See {@link #getDescription()} for more * information on what the description is. This method will trigger a * {@link com.itmill.toolkit.terminal.Paintable.RepaintRequestEvent RepaintRequestEvent}. * * @param description * the new description string for the component. */ public void setDescription(String description) { this.description = description; requestRepaint(); } /* * Gets the component's parent component. Don't add a JavaDoc comment here, * we use the default documentation from implemented interface. */ public Component getParent() { return parent; } /* * Sets the parent component. Don't add a JavaDoc comment here, we use the * default documentation from implemented interface. */ public void setParent(Component parent) { // If the parent is not changed, dont do nothing if (parent == this.parent) { return; } // Send detach event if the component have been connected to a window if (getApplication() != null) { detach(); this.parent = null; } // Connect to new parent this.parent = parent; // Send attach event if connected to a window if (getApplication() != null) { attach(); } } /** * Gets the error message for this component. * * @return ErrorMessage containing the description of the error state of the * component or null, if the component contains no errors. Extending * classes should override this method if they support other error * message types such as validation errors or buffering errors. The * returned error message contains information about all the errors. */ public ErrorMessage getErrorMessage() { return componentError; } /** * Gets the component's error message. * * @link Terminal.ErrorMessage#ErrorMessage(String, int) * * @return the component's error message. */ public ErrorMessage getComponentError() { return componentError; } /** * Sets the component's error message. The message may contain certain XML * tags, for more information see * * @link Component.ErrorMessage#ErrorMessage(String, int) * * @param componentError * the new <code>ErrorMessage</code> of the component. */ public void setComponentError(ErrorMessage componentError) { this.componentError = componentError; fireComponentErrorEvent(); requestRepaint(); } /* * Tests if the component is in read-only mode. Don't add a JavaDoc comment * here, we use the default documentation from implemented interface. */ public boolean isReadOnly() { return readOnly; } /* * Sets the component's read-only mode. Don't add a JavaDoc comment here, we * use the default documentation from implemented interface. */ public void setReadOnly(boolean readOnly) { this.readOnly = readOnly; requestRepaint(); } /* * Gets the parent window of the component. Don't add a JavaDoc comment * here, we use the default documentation from implemented interface. */ public Window getWindow() { if (parent == null) { return null; } else { return parent.getWindow(); } } /* * Notify the component that it's attached to a window. Don't add a JavaDoc * comment here, we use the default documentation from implemented * interface. */ public void attach() { requestRepaint(); } /* * Detach the component from application. Don't add a JavaDoc comment here, * we use the default documentation from implemented interface. */ public void detach() { } /* * Gets the parent application of the component. Don't add a JavaDoc comment * here, we use the default documentation from implemented interface. */ public Application getApplication() { if (parent == null) { return null; } else { return parent.getApplication(); } } /* Documented in super interface */ public void requestRepaintRequests() { repaintRequestListenersNotified = false; } /* * Paints the component into a UIDL stream. Don't add a JavaDoc comment * here, we use the default documentation from implemented interface. */ public final void paint(PaintTarget target) throws PaintException { if (!target.startTag(this, getTag()) || repaintRequestListenersNotified) { // Paint the contents of the component if (getHeight() >= 0) { target.addAttribute("height", "" + getHeight() + UNIT_SYMBOLS[getHeightUnits()]); } if (getWidth() >= 0) { target.addAttribute("width", "" + getWidth() + UNIT_SYMBOLS[getWidthUnits()]); } if (styles != null && styles.size() > 0) { target.addAttribute("style", getStyle()); } if (isReadOnly()) { target.addAttribute("readonly", true); } if (!isVisible()) { target.addAttribute("invisible", true); } if (isImmediate()) { target.addAttribute("immediate", true); } if (!isEnabled()) { target.addAttribute("disabled", true); } if (getCaption() != null) { target.addAttribute("caption", getCaption()); } if (getIcon() != null) { target.addAttribute("icon", getIcon()); } // Only paint content of visible components. if (isVisible()) { final String desc = getDescription(); if (desc != null && description.length() > 0) { target.addAttribute("description", getDescription()); } paintContent(target); final ErrorMessage error = getErrorMessage(); if (error != null) { error.paint(target); } } } else { // Contents have not changed, only cached presentation can be used target.addAttribute("cached", true); } target.endTag(getTag()); repaintRequestListenersNotified = false; } /** * Paints any needed component-specific things to the given UIDL stream. The * more general {@link #paint(PaintTarget)} method handles all general * attributes common to all components, and it calls this method to paint * any component-specific attributes to the UIDL stream. * * @param target * the target UIDL stream where the component should paint * itself to * @throws PaintException * if the paint operation failed. */ public void paintContent(PaintTarget target) throws PaintException { } /* Documentation copied from interface */ public void requestRepaint() { // The effect of the repaint request is identical to case where a // child requests repaint childRequestedRepaint(null); } /* Documentation copied from interface */ public void childRequestedRepaint(Collection alreadyNotified) { // Invisible components do not need repaints if (!isVisible()) { return; } fireRequestRepaintEvent(alreadyNotified); } /** * Fires the repaint request event. * * @param alreadyNotified */ private void fireRequestRepaintEvent(Collection alreadyNotified) { // Notify listeners only once if (!repaintRequestListenersNotified) { // Notify the listeners if (repaintRequestListeners != null && !repaintRequestListeners.isEmpty()) { final Object[] listeners = repaintRequestListeners.toArray(); final RepaintRequestEvent event = new RepaintRequestEvent(this); for (int i = 0; i < listeners.length; i++) { if (alreadyNotified == null) { alreadyNotified = new LinkedList(); } if (!alreadyNotified.contains(listeners[i])) { ((RepaintRequestListener) listeners[i]) .repaintRequested(event); alreadyNotified.add(listeners[i]); repaintRequestListenersNotified = true; } } } // Notify the parent final Component parent = getParent(); if (parent != null) { parent.childRequestedRepaint(alreadyNotified); } } } /* Documentation copied from interface */ public void addListener(RepaintRequestListener listener) { if (repaintRequestListeners == null) { repaintRequestListeners = new LinkedList(); } if (!repaintRequestListeners.contains(listener)) { repaintRequestListeners.add(listener); } } /* Documentation copied from interface */ public void removeListener(RepaintRequestListener listener) { if (repaintRequestListeners != null) { repaintRequestListeners.remove(listener); if (repaintRequestListeners.isEmpty()) { repaintRequestListeners = null; } } } /* * Invoked when the value of a variable has changed. Don't add a JavaDoc * comment here, we use the default documentation from implemented * interface. */ public void changeVariables(Object source, Map variables) { } /* Dependency -framework is deprecated */ public void dependsOn(VariableOwner depended) { } public void removeDirectDependency(VariableOwner depended) { } public Set getDirectDependencies() { return null; } private static final Method COMPONENT_EVENT_METHOD; static { try { COMPONENT_EVENT_METHOD = Component.Listener.class .getDeclaredMethod("componentEvent", new Class[] { Component.Event.class }); } catch (final java.lang.NoSuchMethodException e) { // This should never happen e.printStackTrace(); throw new java.lang.RuntimeException(); } } /** * <p> * Registers a new listener with the specified activation method to listen * events generated by this component. If the activation method does not * have any arguments the event object will not be passed to it when it's * called. * </p> * * <p> * For more information on the inheritable event mechanism see the * {@link com.itmill.toolkit.event com.itmill.toolkit.event package documentation}. * </p> * * @param eventType * the type of the listened event. Events of this type or its * subclasses activate the listener. * @param object * the object instance who owns the activation method. * @param method * the activation method. */ public void addListener(Class eventType, Object object, Method method) { if (eventRouter == null) { eventRouter = new EventRouter(); } eventRouter.addListener(eventType, object, method); } public void addListener(Class eventType, Object object, String methodName) { if (eventRouter == null) { eventRouter = new EventRouter(); } eventRouter.addListener(eventType, object, methodName); } /** * Removes all registered listeners matching the given parameters. Since * this method receives the event type and the listener object as * parameters, it will unregister all <code>object</code>'s methods that * are registered to listen to events of type <code>eventType</code> * generated by this component. * * <p> * For more information on the inheritable event mechanism see the * {@link com.itmill.toolkit.event com.itmill.toolkit.event package documentation}. * </p> * * @param eventType * the exact event type the <code>object</code> listens to. * @param target * the target object that has registered to listen to events * of type <code>eventType</code> with one or more methods. */ public void removeListener(Class eventType, Object target) { if (eventRouter != null) { eventRouter.removeListener(eventType, target); } } /** * Removes one registered listener method. The given method owned by the * given object will no longer be called when the specified events are * generated by this component. * * <p> * For more information on the inheritable event mechanism see the * {@link com.itmill.toolkit.event com.itmill.toolkit.event package documentation}. * </p> * * @param eventType * the exact event type the <code>object</code> listens to. * @param target * target object that has registered to listen to events of * type <code>eventType</code> with one or more methods. * @param method * the method owned by <code>target</code> that's * registered to listen to events of type * <code>eventType</code>. */ public void removeListener(Class eventType, Object target, Method method) { if (eventRouter != null) { eventRouter.removeListener(eventType, target, method); } } public void removeListener(Class eventType, Object target, String methodName) { if (eventRouter != null) { eventRouter.removeListener(eventType, target, methodName); } } /** * Sends the event to all listeners. * * @param event * the Event to be sent to all listeners. */ protected void fireEvent(Component.Event event) { if (eventRouter != null) { eventRouter.fireEvent(event); } } /* * Registers a new listener to listen events generated by this component. * Don't add a JavaDoc comment here, we use the default documentation from * implemented interface. */ public void addListener(Component.Listener listener) { if (eventRouter == null) { eventRouter = new EventRouter(); } eventRouter.addListener(Component.Event.class, listener, COMPONENT_EVENT_METHOD); } /* * Removes a previously registered listener from this component. Don't add a * JavaDoc comment here, we use the default documentation from implemented * interface. */ public void removeListener(Component.Listener listener) { if (eventRouter != null) { eventRouter.removeListener(Component.Event.class, listener, COMPONENT_EVENT_METHOD); } } /** * Emits the component event. It is transmitted to all registered listeners * interested in such events. */ protected void fireComponentEvent() { fireEvent(new Component.Event(this)); } /** * Emits the component error event. It is transmitted to all registered * listeners interested in such events. */ protected void fireComponentErrorEvent() { fireEvent(new Component.ErrorEvent(getComponentError(), this)); } /** * Sets the application specific data object. * * @param data * the Application specific data. * @since 3.1 */ public void setData(Object data) { applicationData = data; } /** * Gets the application specific data. * * @return the Application specific data set with setData function. * @since 3.1 */ public Object getData() { return applicationData; } /* Sizeable and other size related methods */ /* * (non-Javadoc) * * @see com.itmill.toolkit.terminal.Sizeable#getHeight() */ public int getHeight() { return height; } /* * (non-Javadoc) * * @see com.itmill.toolkit.terminal.Sizeable#getHeightUnits() */ public int getHeightUnits() { return heightUnit; } /* * (non-Javadoc) * * @see com.itmill.toolkit.terminal.Sizeable#getWidth() */ public int getWidth() { return width; } /* * (non-Javadoc) * * @see com.itmill.toolkit.terminal.Sizeable#getWidthUnits() */ public int getWidthUnits() { return widthUnit; } /* * (non-Javadoc) * * @see com.itmill.toolkit.terminal.Sizeable#setHeight(int) */ public void setHeight(int height) { this.height = height; requestRepaint(); } /* * (non-Javadoc) * * @see com.itmill.toolkit.terminal.Sizeable#setHeightUnits(int) */ public void setHeightUnits(int unit) { heightUnit = unit; requestRepaint(); } public void setHeight(int height, int unit) { setHeight(height); setHeightUnits(unit); } /* * (non-Javadoc) * * @see com.itmill.toolkit.terminal.Sizeable#setSizeFull() */ public void setSizeFull() { height = 100; width = 100; heightUnit = UNITS_PERCENTAGE; widthUnit = UNITS_PERCENTAGE; requestRepaint(); } /* * (non-Javadoc) * * @see com.itmill.toolkit.terminal.Sizeable#setSizeUndefined() */ public void setSizeUndefined() { height = -1; width = -1; heightUnit = UNITS_PIXELS; widthUnit = UNITS_PIXELS; requestRepaint(); } /* * (non-Javadoc) * * @see com.itmill.toolkit.terminal.Sizeable#setWidth(int) */ public void setWidth(int width) { this.width = width; requestRepaint(); } /* * (non-Javadoc) * * @see com.itmill.toolkit.terminal.Sizeable#setWidthUnits(int) */ public void setWidthUnits(int unit) { widthUnit = unit; requestRepaint(); } public void setWidth(int width, int unit) { setWidth(width); setWidthUnits(unit); } public void setWidth(String width) { int[] p = parseStringSize(width); setWidth(p[0]); setWidthUnits(p[1]); } public void setHeight(String width) { int[] p = parseStringSize(width); setHeight(p[0]); setHeightUnits(p[1]); } /* * returns array with size in index 0 unit in index 1 */ private static int[] parseStringSize(String s) { int[] values = new int[2]; s = s.trim(); if (s.indexOf("%") != -1) { values[1] = UNITS_PERCENTAGE; values[0] = (int) Float.parseFloat(s.substring(0, s.indexOf("%"))); } else { values[0] = (int) Float.parseFloat(s.substring(0, s.length() - 2)); if (s.endsWith("px")) { values[1] = UNITS_PIXELS; } else if (s.endsWith("em")) { values[1] = UNITS_EM; } else if (s.endsWith("ex")) { values[1] = UNITS_EX; } else if (s.endsWith("in")) { values[1] = UNITS_INCH; } else if (s.endsWith("cm")) { values[1] = UNITS_CM; } else if (s.endsWith("mm")) { values[1] = UNITS_MM; } else if (s.endsWith("pt")) { values[1] = UNITS_POINTS; } else if (s.endsWith("pc")) { values[1] = UNITS_PICAS; } } return values; } }
package mapeditor; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; public class CollisionPanel extends JPanel { static final int amountOfButtons = 8; JButton[] buttons = new JButton[amountOfButtons]; boolean[] selected = new boolean[amountOfButtons]; byte result = 0; static JLabel preview = new JLabel(); public CollisionPanel() { addButtons(); add(preview); updatePreview(); setPreferredSize(new Dimension(80, 608)); } private void addButtons() { for (int i = 0; i < amountOfButtons; i++) { addButton(i); } } int squareSize = 20; int glowRadius = 5; private void addButton(int i) { JButton button = new JButton(new ImageIcon(getImage(1<<i,squareSize,glowRadius,false))); button.setFocusPainted(false); final int ID = i; button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // if ((result & (1 << (ID-1))) == (1 << (ID-1))) { // result -= Math.pow(2, ID-1); // } else { // result += Math.pow(2, ID-1); pressed(ID); } }); buttons[i] = button; button.setPreferredSize(new Dimension(squareSize+2*glowRadius, squareSize+2*glowRadius)); add(button); } private void pressed(int ID) { selected[ID] = !selected[ID]; buttons[ID].setIcon(new ImageIcon(getImage(1<<ID,squareSize,glowRadius,selected[ID]))); updatePreview(); } public void updatePreview() { result = 0; for (int i = 0;i<selected.length;i++) { if (selected[i]) { result += 1<<i; } } preview.setIcon(new ImageIcon(getImage(result,45,10,false))); } public BufferedImage getImage(int i, int squareSize, int glowRadius, boolean selected) { int width = squareSize+2*glowRadius; int rsq = glowRadius*glowRadius; BufferedImage img = new BufferedImage(width, width, BufferedImage.TYPE_INT_ARGB); Graphics2D g = (Graphics2D) img.getGraphics(); g.setColor(Color.LIGHT_GRAY); g.fillRect(0, 0, width, width); if (selected) { g.setColor(new Color(70,255,70,70)); g.fillRect(0, 0, width, width); } for (int x = 0; x < (width); x++) { for (int y = 0; y < (width); y++) { double cx = x - glowRadius; double cy = y - glowRadius; if ((i & 1) == 1) {// BIT 1 = BASE SQUARE COLLISION cx = Math.max(0, Math.min(squareSize-1, cx)); cy = Math.max(0, Math.min(squareSize-1, cy)); } if ((i & 2) == 2) {// BIT 2 = TOP LEFT NO COLLISION if (cx + cy < squareSize) { cy = cy - squareSize; double scalar = (cx / Math.sqrt(2) - cy / Math.sqrt(2)); cx = scalar / Math.sqrt(2); // c = length * normaliserad vektor (1,-1) cy = -scalar / Math.sqrt(2); cy = cy + squareSize; } } if ((i & 4) == 4) {// BIT 3 = TOP RIGHT NO COLLISION if ((squareSize - cx) + cy < squareSize) { double scalar = (cx / Math.sqrt(2) + cy / Math.sqrt(2)); cx = scalar / Math.sqrt(2); // c = length * normaliserad vektor (1,1) cy = scalar / Math.sqrt(2); } } if ((i & 8) == 8) {// BIT 4 = BOTTOM LEFT NO COLLISION if (cx + (squareSize - cy) < squareSize) { double scalar = (cx / Math.sqrt(2) + cy / Math.sqrt(2)); cx = scalar / Math.sqrt(2); // c = length * normaliserad vektor (1,1) cy = scalar / Math.sqrt(2); } } if ((i & 16) == 16) {// BIT 5 = BOTTOM RIGHT NO COLLISION if ((squareSize - cx) + (squareSize - cy) < squareSize) { cy = cy - squareSize; double scalar = (cx / Math.sqrt(2) - cy / Math.sqrt(2)); cx = scalar / Math.sqrt(2); // c = length * normaliserad vektor (1,-1) cy = -scalar / Math.sqrt(2); cy = cy + squareSize; } } if ((i & 32) == 32) {// BIT 6 = LEFT EDGE NO COLLISION cx = Math.max(0, Math.min(width, cx)); if (cx < 1) { Point.Double collisionVector = new Point.Double(x - cx - glowRadius, y - cy - glowRadius); double sqDist = collisionVector.x * collisionVector.x + collisionVector.y * collisionVector.y; if (sqDist < rsq) { if (sqDist == 0) { g.setColor(new Color(255, 255, 255, 64)); } else { //int k = (int) (255*(Math.sqrt(sqDist)/(16))); int k = (int) (255 * (sqDist / (rsq))); g.setColor(new Color(255, 255-k, 255-k, 255 - k)); } g.fillRect(x, y, 1, 1); } cx = 100000; } } if ((i & 64) == 64) {// BIT 7 = RIGHT EDGE NO COLLISION cx = Math.max(-glowRadius, Math.min(squareSize-1, cx)); if (cx > squareSize-2) { Point.Double collisionVector = new Point.Double(x - cx - glowRadius, y - cy - glowRadius); double sqDist = collisionVector.x * collisionVector.x + collisionVector.y * collisionVector.y; if (sqDist < rsq) { if (sqDist == 0) { g.setColor(new Color(255, 255, 255, 64)); } else { //int k = (int) (255*(Math.sqrt(sqDist)/(16))); int k = (int) (255 * (sqDist / (rsq))); g.setColor(new Color(255, 255-k, 255-k, 255 - k)); } g.fillRect(x, y, 1, 1); } cx = 100000; } } if ((i & 128) == 128) {// BIT 8 = TOP EDGE NO COLLISION cy = Math.max(0, Math.min(width, cy)); if (cy < 1) { Point.Double collisionVector = new Point.Double(x - cx - glowRadius, y - cy - glowRadius); double sqDist = collisionVector.x * collisionVector.x + collisionVector.y * collisionVector.y; if (sqDist < rsq) { if (sqDist == 0) { g.setColor(new Color(255, 255, 255, 64)); } else { //int k = (int) (255*(Math.sqrt(sqDist)/(16))); int k = (int) (255 * (sqDist / (rsq))); g.setColor(new Color(255, 255-k, 255-k, 255 - k)); } g.fillRect(x, y, 1, 1); } cy = 100000; } } Point.Double collisionVector = new Point.Double(x - cx - glowRadius, y - cy - glowRadius); double sqDist = collisionVector.x * collisionVector.x + collisionVector.y * collisionVector.y; if (sqDist < rsq) { if (sqDist == 0) { g.setColor(new Color(255, 255, 255, 64)); } else { //int k = (int) (255*(Math.sqrt(sqDist)/(16))); int k = (int) (255 * (sqDist / (rsq))); g.setColor(new Color(255-k, 255, 255, 255 - k)); } g.fillRect(x, y, 1, 1); } } } return img; } }
package com.koroshiya.listeners; import android.content.Context; import android.util.Log; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.View; import com.koroshiya.controls.JImageView; import com.koroshiya.controls.JScrollView; import com.koroshiya.fragments.ReadFragment; public class GestureListener extends GestureDetector.SimpleOnGestureListener implements View.OnTouchListener { private final JScrollView jsv; private final ScaleGestureDetector sgd; private final GestureDetector gd; private final ReadFragment readFragment; private float startx, starty; private float currentx = 0, currenty = 0; private int pageStartx; private boolean lastDown = true; public GestureListener(JScrollView jsv, ReadFragment readFragment){ this.jsv = jsv; Context c = jsv.getContext(); this.sgd = new ScaleGestureDetector(c, new ScaleListener(jsv)); this.gd = new GestureDetector(c, this); this.readFragment = readFragment; } @Override public boolean onDown(MotionEvent e){ if (e.getPointerCount() > 1){ lastDown = false; sgd.onTouchEvent(e); }else{ lastDown = true; startx = currentx = e.getX(); starty = currenty = e.getY(); pageStartx = jsv.getScrollX(); } return true; } @Override public boolean onTouch(View v, MotionEvent event) { int action = event.getAction(); if (event.getPointerCount() > 1){ Log.i("GL", "Two fingers"); lastDown = false; sgd.onTouchEvent(event); }else { if (lastDown){ if (action == MotionEvent.ACTION_MOVE) { Log.i("GL", "Moving curX: "+currentx+", getX: "+event.getX()); Log.i("GL", "Moving curY: "+currenty+", getY: "+event.getY()); int x = (int)(currentx - event.getX()); int y = (int)(currenty - event.getY()); jsv.scrollBy(x, y); currentx -= x; currenty -= y; } else if (action == MotionEvent.ACTION_UP) { Log.i("GL", "Up"); up(v, event.getX(), event.getY()); } } if (!gd.onTouchEvent(event)) { jsv.onTouchEvent(event); } } return true; } public void up(View v, double x2, double y2) { JImageView jiv = jsv.getJImageView(); if (pageStartx == jsv.getRight() || pageStartx == jiv.getWidth() - jsv.getRight() || jsv.getRight() >= jiv.getWidth()) { Log.i("GL", "Right"); if ((Math.abs(startx - x2) > Math.abs(starty - y2))) { Log.i("GL", "Moving"); if (startx > x2) { readFragment.next(v); } else if (pageStartx == jsv.getLeft()) { //In case getLeft and getRight are the same (ie. no horizontal scroll) readFragment.previous(v); } } } else if (pageStartx == jsv.getLeft()) { Log.i("GL", "Left"); if ((Math.abs(startx - x2) > Math.abs(starty - y2)) && startx < x2) { readFragment.previous(v); } } else { Log.i("GL", "Scroll"); currentx -= x2; currenty -= y2; jsv.scrollBy((int)currentx, (int)currenty); currentx = jsv.getScrollX(); currenty = jsv.getScrollY(); } } }
package org.openspaces.grid.esm; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import org.openspaces.admin.Admin; import org.openspaces.admin.AdminFactory; import org.openspaces.admin.esm.deployment.DeploymentContext; import org.openspaces.admin.esm.deployment.ElasticDataGridDeployment; import org.openspaces.admin.esm.deployment.InternalElasticDataGridDeployment; import org.openspaces.admin.esm.deployment.MemorySla; import org.openspaces.admin.gsa.GridServiceAgent; import org.openspaces.admin.gsa.GridServiceContainerOptions; import org.openspaces.admin.gsc.GridServiceContainer; import org.openspaces.admin.machine.Machine; import org.openspaces.admin.pu.DeploymentStatus; import org.openspaces.admin.pu.ProcessingUnit; import org.openspaces.admin.pu.ProcessingUnitInstance; import org.openspaces.admin.pu.ProcessingUnits; import org.openspaces.admin.pu.events.BackupGridServiceManagerChangedEvent; import org.openspaces.admin.pu.events.ManagingGridServiceManagerChangedEvent; import org.openspaces.admin.pu.events.ProcessingUnitLifecycleEventListener; import org.openspaces.admin.pu.events.ProcessingUnitStatusChangedEvent; import org.openspaces.admin.space.SpaceDeployment; import org.openspaces.admin.space.SpaceInstance; import org.openspaces.admin.vm.VirtualMachineStatistics; import org.openspaces.admin.zone.Zone; import com.gigaspaces.cluster.activeelection.SpaceMode; import com.j_spaces.core.IJSpace; import com.j_spaces.core.admin.IRemoteJSpaceAdmin; import com.j_spaces.core.admin.SpaceRuntimeInfo; import com.j_spaces.kernel.ClassLoaderHelper; import com.j_spaces.kernel.TimeUnitProperty; public class EsmExecutor { public static void main(String[] args) { new EsmExecutor(); } /* * FINEST - step by step actions and decisions * FINER - * FINE - * INFO - actions user should know about * WARNING - * SEVERE - */ private final static Logger logger = Logger.getLogger("org.openspaces.grid.esm"); private final static long initialDelay = TimeUnitProperty.getProperty("org.openspaces.grid.esm.initialDelay", "5s"); private final static long fixedDelay = TimeUnitProperty.getProperty("org.openspaces.grid.esm.fixedDelay", "5s"); private final static int memorySafetyBufferInMB = MemorySettings.valueOf(System.getProperty("org.openspaces.grid.esm.memorySafetyBuffer", "100m")).toMB(); private final static NumberFormat NUMBER_FORMAT = NumberFormat.getInstance(); //maps pu-name to elastic-scale impl private final Map<String, ElasticScaleHandler> elasticScaleMap = new HashMap<String, ElasticScaleHandler>(); private final Admin admin = new AdminFactory().createAdmin(); private final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { final ThreadFactory factory = Executors.defaultThreadFactory(); public Thread newThread(Runnable r) { Thread newThread = factory.newThread(r); newThread.setName("ESM-ScheduledTask"); return newThread; } }); public EsmExecutor() { NUMBER_FORMAT.setMinimumFractionDigits(1); NUMBER_FORMAT.setMaximumFractionDigits(2); if (logger.isLoggable(Level.CONFIG)) { logger.config("Initial Delay: " + initialDelay + " ms"); logger.config("Fixed Delay: " + fixedDelay + " ms"); } if (Boolean.valueOf(System.getProperty("esm.enabled", "true"))) { executorService.scheduleWithFixedDelay(new ScheduledTask(), initialDelay, fixedDelay, TimeUnit.MILLISECONDS); admin.getProcessingUnits().addLifecycleListener(new UndeployedProcessingUnitLifecycleEventListener()); } } public void deploy(ElasticDataGridDeployment deployment) { DeploymentContext deploymentContext = ((InternalElasticDataGridDeployment)deployment).getDeploymentContext(); final String zoneName = deployment.getDataGridName(); SpaceDeployment spaceDeployment = new SpaceDeployment(deployment.getDataGridName()); spaceDeployment.addZone(zoneName); int numberOfParitions = calculateNumberOfPartitions(deploymentContext); if (deploymentContext.isHighlyAvailable()) { spaceDeployment.maxInstancesPerMachine(1); spaceDeployment.partitioned(numberOfParitions, 1); } else { spaceDeployment.partitioned(numberOfParitions, 0); } String initialJavaHeapSize = deploymentContext.getInitialJavaHeapSize(); String maximumJavaHeapSize = deploymentContext.getMaximumJavaHeapSize(); if (MemorySettings.valueOf(initialJavaHeapSize).isGreaterThan(MemorySettings.valueOf(maximumJavaHeapSize))) { initialJavaHeapSize = maximumJavaHeapSize; } spaceDeployment.setContextProperty("elastic", "true"); spaceDeployment.setContextProperty("minMemory", deploymentContext.getMinMemory()); spaceDeployment.setContextProperty("maxMemory", deploymentContext.getMaxMemory()); spaceDeployment.setContextProperty("initialJavaHeapSize", deploymentContext.getInitialJavaHeapSize()); spaceDeployment.setContextProperty("maximumJavaHeapSize", deploymentContext.getMaximumJavaHeapSize()); spaceDeployment.setContextProperty("deploymentIsolation", deploymentContext.getDeploymentIsolationLevel().name()); spaceDeployment.setContextProperty("sla", deploymentContext.getSlaDescriptors()); if (deployment.getElasticScaleConfig() != null) { spaceDeployment.setContextProperty("elasticScaleConfig", ElasticScaleHandlerConfigSerializer.toString(deployment.getElasticScaleConfig())); } if (!deployment.getContextProperties().isEmpty()) { Set<Entry<Object,Object>> entrySet = deployment.getContextProperties().entrySet(); for (Entry<Object,Object> entry : entrySet) { spaceDeployment.setContextProperty((String)entry.getKey(), (String)entry.getValue()); } } if (deploymentContext.getVmInputArguments()!= null) { spaceDeployment.setContextProperty("vmArguments", deploymentContext.getVmInputArguments()); } logger.finest("Deploying " + deployment.getDataGridName() + "\n\t Zone: " + zoneName + "\n\t Min Capacity: " + deploymentContext.getMinMemory() + "\n\t Max Capacity: " + deploymentContext.getMaxMemory() + "\n\t Initial Java Heap Size: " + initialJavaHeapSize + "\n\t Maximum Java Heap Size: " + maximumJavaHeapSize + "\n\t Deployment Isolation: " + deploymentContext.getDeploymentIsolationLevel().name() + "\n\t Highly Available? " + deploymentContext.isHighlyAvailable() + "\n\t Partitions: " + numberOfParitions + "\n\t SLA: " + deploymentContext.getSlaDescriptors()); admin.getGridServiceManagers().waitForAtLeastOne().deploy(spaceDeployment); } private int calculateNumberOfPartitions(DeploymentContext context) { int numberOfPartitions = MemorySettings.valueOf(context.getMaxMemory()).floorDividedBy(context.getMaximumJavaHeapSize()); if (context.isHighlyAvailable()) { numberOfPartitions /= 2; } return Math.max(1, numberOfPartitions); } /** * Life cycle listener of processing units which are un-deployed, and their resources should be scaled down. */ private final class UndeployedProcessingUnitLifecycleEventListener implements ProcessingUnitLifecycleEventListener { public void processingUnitAdded(ProcessingUnit processingUnit) { } public void processingUnitRemoved(ProcessingUnit processingUnit) { if (!PuCapacityPlanner.isElastic(processingUnit)) return; try { executorService.schedule(new UndeployHandler(new PuCapacityPlanner(processingUnit, getOnDemandElasticScale(processingUnit))), fixedDelay, TimeUnit.MILLISECONDS); } catch (Exception e) { logger.log(Level.SEVERE, "Failed to invoke undeploy handler for " +processingUnit.getName(), e); } } public void processingUnitStatusChanged(ProcessingUnitStatusChangedEvent event) { } public void processingUnitManagingGridServiceManagerChanged(ManagingGridServiceManagerChangedEvent event) { } public void processingUnitBackupGridServiceManagerChanged(BackupGridServiceManagerChangedEvent event) { } } private final class ScheduledTask implements Runnable { public ScheduledTask() { } public void run() { try { if (Level.OFF.equals(logger.getLevel())) { return; //turn off cruise control } ProcessingUnits processingUnits = admin.getProcessingUnits(); for (ProcessingUnit pu : processingUnits) { logger.finest(ToStringHelper.puToString(pu)); if (!PuCapacityPlanner.isElastic(pu)) continue; PuCapacityPlanner puCapacityPlanner = new PuCapacityPlanner(pu, getOnDemandElasticScale(pu)); logger.finest(ToStringHelper.puCapacityPlannerToString(puCapacityPlanner)); Workflow workflow = new Workflow(puCapacityPlanner); while (workflow.hasNext()) { Runnable nextInWorkflow = workflow.removeFirst(); nextInWorkflow.run(); } } } catch (Throwable t) { logger.log(Level.WARNING, "Caught exception: " + t, t); } } } private ElasticScaleHandler getOnDemandElasticScale(ProcessingUnit pu) throws Exception { ElasticScaleHandler onDemandElasticScale = elasticScaleMap.get(pu.getName()); if (onDemandElasticScale != null) { return onDemandElasticScale; } String elasticScaleConfigStr = pu.getBeanLevelProperties().getContextProperties().getProperty("elasticScaleConfig"); if (elasticScaleConfigStr == null) { return new NullElasticScaleHandler(); } ElasticScaleHandlerConfig elasticScaleConfig = ElasticScaleHandlerConfigSerializer.fromString(elasticScaleConfigStr); Class<? extends ElasticScaleHandler> clazz = ClassLoaderHelper.loadClass(elasticScaleConfig.getClassName()).asSubclass(ElasticScaleHandler.class); ElasticScaleHandler newInstance = clazz.newInstance(); newInstance.init(elasticScaleConfig); elasticScaleMap.put(pu.getName(), newInstance); return newInstance; } private class Workflow { private boolean isBroken = false; final List<Runnable> runnables = new ArrayList<Runnable>(); /** constructs an empty workflow */ public Workflow() { } public Workflow(PuCapacityPlanner puCapacityPlanner) { runnables.add(new UnderCapacityHandler(puCapacityPlanner, this)); runnables.add(new MemorySlaHandler(puCapacityPlanner, this)); runnables.add(new RebalancerHandler(puCapacityPlanner, this)); runnables.add(new GscCollectorHandler(puCapacityPlanner, this)); runnables.add(new CompromisedDeploymentHandler(puCapacityPlanner, this)); } public void add(Runnable runner) { runnables.add(runner); } public boolean hasNext() { return !runnables.isEmpty(); } public Runnable removeFirst() { return runnables.remove(0); } public void breakWorkflow() { isBroken = true; runnables.clear(); } public boolean isBroken() { return isBroken; } } private class UnderCapacityHandler implements Runnable { private final PuCapacityPlanner puCapacityPlanner; private final Workflow workflow; public UnderCapacityHandler(PuCapacityPlanner puCapacityPlanner, Workflow workflow) { this.puCapacityPlanner = puCapacityPlanner; this.workflow = workflow; } public void run() { logger.finest(UnderCapacityHandler.class.getSimpleName() + " invoked"); if (underMinCapcity()) { logger.info("Starting a minimum of ["+puCapacityPlanner.getMinNumberOfGSCs()+"] GSCs"); workflow.breakWorkflow(); workflow.add(new StartGscHandler(puCapacityPlanner, workflow)); } } private boolean underMinCapcity() { return puCapacityPlanner.getNumberOfGSCsInZone() < puCapacityPlanner.getMinNumberOfGSCs(); } } public class StartGscHandler implements Runnable { private final PuCapacityPlanner puCapacityPlanner; private final Workflow workflow; public StartGscHandler(PuCapacityPlanner puCapacityPlanner, Workflow workflow) { this.puCapacityPlanner = puCapacityPlanner; this.workflow = workflow; } public void run() { if (reachedMaxCapacity() && puCapacityPlanner.hasEnoughMachines()) { logger.warning("Reached Capacity Limit"); return; } final ZoneCorrelator zoneCorrelator = new ZoneCorrelator(admin, puCapacityPlanner.getZoneName()); List<Machine> machines = zoneCorrelator.getMachines(); //sort by least number of GSCs in zone //TODO when not dedicated, we might need to take other GSCs into account Collections.sort(machines, new Comparator<Machine>() { public int compare(Machine m1, Machine m2) { List<GridServiceContainer> gscsM1 = zoneCorrelator.getGridServiceContainersByMachine(m1); List<GridServiceContainer> gscsM2 = zoneCorrelator.getGridServiceContainersByMachine(m2); return gscsM1.size() - gscsM2.size(); } }); boolean needsNewMachine = true; for (Machine machine : machines) { if (!puCapacityPlanner.getElasticScale().accept(machine)) { logger.finest("Machine ["+ToStringHelper.machineToString(machine)+"] was filtered out by [" + puCapacityPlanner.getElasticScale().getClass().getName()+"]"); continue; } if (!machineHasAnAgent(machine)) { logger.finest("Can't start a GSC on machine ["+ToStringHelper.machineToString(machine)+"] - doesn't have an agent."); continue; } if (!meetsDedicatedIsolationConstraint(machine, puCapacityPlanner.getZoneName())) { logger.finest("Can't start GSC on machine ["+ToStringHelper.machineToString(machine)+"] - doesn't meet dedicated isolation constraint."); continue; } if (aboveMinCapcity() && machineHasAnEmptyGSC(zoneCorrelator, machine)) { logger.finest("Won't start a GSC on machine ["+ToStringHelper.machineToString(machine)+"] - already has an empty GSC."); // needsNewMachine = false; continue; } if (!hasEnoughMemoryForNewGSC(machine)) { logger.finest("Can't start a GSC on machine ["+ToStringHelper.machineToString(machine)+"] - doesn't have enough memory to start a new GSC"); continue; // can't start GSC here } startGscOnMachine(machine); needsNewMachine = false; break; } if (needsNewMachine) { logger.fine("Can't start a GSC on the available machines - needs a new machine."); ElasticScaleHandlerContext elasticScaleCommand = new ElasticScaleHandlerContext(); elasticScaleCommand.setMachines(machines); puCapacityPlanner.getElasticScale().scaleOut(elasticScaleCommand); } } // requires this machine to contain only GSCs matching the zone name provided private boolean meetsDedicatedIsolationConstraint(Machine machine, String zoneName) { for (GridServiceContainer gsc : machine.getGridServiceContainers()) { Map<String, Zone> gscZones = gsc.getZones(); if (gscZones.isEmpty() || !gscZones.containsKey(zoneName)) { return false; // GSC either has no zone or is of another zone } } return true; } private boolean reachedMaxCapacity() { return puCapacityPlanner.getNumberOfGSCsInZone() >= puCapacityPlanner.getMaxNumberOfGSCs(); } private boolean aboveMinCapcity() { return puCapacityPlanner.getNumberOfGSCsInZone() >= puCapacityPlanner.getMinNumberOfGSCs(); } // due to timing delays, a machine might have an empty GSC - don't start a GSC on it private boolean machineHasAnEmptyGSC(ZoneCorrelator zoneCorrelator, Machine machine) { List<GridServiceContainer> list = zoneCorrelator.getGridServiceContainersByMachine(machine); for (GridServiceContainer gscOnMachine : list) { if (gscOnMachine.getProcessingUnitInstances().length == 0) { return true; } } return false; } //if machine does not have an agent, it can't be used to start a new GSC private boolean machineHasAnAgent(Machine machine) { GridServiceAgent agent = machine.getGridServiceAgent(); return (agent != null); } // machine has enough memory to start a new GSC private boolean hasEnoughMemoryForNewGSC(Machine machine) { double totalPhysicalMemorySizeInMB = machine.getOperatingSystem() .getDetails() .getTotalPhysicalMemorySizeInMB(); int jvmSizeInMB = MemorySettings.valueOf(puCapacityPlanner.getMaxJavaHeapSize()).toMB(); int numberOfGSCsScaleLimit = (int) Math.floor(totalPhysicalMemorySizeInMB / jvmSizeInMB); int freePhysicalMemorySizeInMB = (int) Math.floor(machine.getOperatingSystem() .getStatistics() .getFreePhysicalMemorySizeInMB()); // Check according to the calculated limit, but also check that the physical memory is // enough return (machine.getGridServiceContainers().getSize() < numberOfGSCsScaleLimit && jvmSizeInMB < (freePhysicalMemorySizeInMB - memorySafetyBufferInMB)); } private void startGscOnMachine(Machine machine) { logger.info("Scaling up - Starting GSC on machine ["+ToStringHelper.machineToString(machine)+"]"); GridServiceContainerOptions vmInputArgument = new GridServiceContainerOptions() .vmInputArgument("-Xms" + puCapacityPlanner.getInitJavaHeapSize()) .vmInputArgument("-Xmx" + puCapacityPlanner.getMaxJavaHeapSize()) .vmInputArgument("-Dcom.gs.zones=" + puCapacityPlanner.getZoneName()) .vmInputArgument("-Dcom.gigaspaces.grid.gsc.serviceLimit=" + puCapacityPlanner.getScalingFactor()); if (puCapacityPlanner.getVmArguments() != null) { String[] vmArguments = puCapacityPlanner.getVmArguments().split(","); for (String vmArgument : vmArguments) { vmInputArgument.vmInputArgument(vmArgument); } } GridServiceContainer newGSC = machine.getGridServiceAgent().startGridServiceAndWait( vmInputArgument , 60, TimeUnit.SECONDS); if (newGSC == null) { logger.warning("Failed Scaling up - Failed to start GSC on machine ["+ToStringHelper.machineToString(machine)+"]"); } else { workflow.breakWorkflow(); logger.info("Successfully started GSC ["+ToStringHelper.gscToString(newGSC)+"] on machine ["+ToStringHelper.machineToString(newGSC.getMachine())+"]"); } } } private class MemorySlaHandler implements Runnable { private final PuCapacityPlanner puCapacityPlanner; private final Workflow workflow; private final MemorySla memorySla; public MemorySlaHandler(PuCapacityPlanner puCapacityPlanner, Workflow workflow) { this.puCapacityPlanner = puCapacityPlanner; this.workflow = workflow; SlaExtractor slaExtractor = new SlaExtractor(puCapacityPlanner.getProcessingUnit()); memorySla = slaExtractor.getMemorySla(); } public boolean hasMemorySla() { return memorySla != null; } public void run() { if (!hasMemorySla()) return; logger.finest(MemorySlaHandler.class.getSimpleName() + " invoked"); handleBreachAboveThreshold(); if (!workflow.isBroken()) handleBreachBelowThreshold(); } public void handleBreachAboveThreshold() { /* * Go over GSCs, and gather GSCs above threshold */ List<GridServiceContainer> gscs = new ArrayList<GridServiceContainer>(); for (ProcessingUnitInstance puInstance : puCapacityPlanner.getProcessingUnit()) { GridServiceContainer gsc = puInstance.getGridServiceContainer(); if (!gscs.contains(gsc)) { gscs.add(gsc); } } List<GridServiceContainer> gscsWithBreach = new ArrayList<GridServiceContainer>(); for (GridServiceContainer gsc : gscs) { double memoryHeapUsedPerc = gsc.getVirtualMachine().getStatistics().getMemoryHeapUsedPerc(); double avgMemoryHeapUsedPerc = getAvgMemoryHeapUsedPerc(gsc); if (avgMemoryHeapUsedPerc > memorySla.getThreshold()) { if (gsc.getProcessingUnitInstances().length == 1) { logger.warning("Can't amend GSC [" + ToStringHelper.gscToString(gsc) + "] - Memory [" + NUMBER_FORMAT.format(avgMemoryHeapUsedPerc) + "%] breached threshold of [" + NUMBER_FORMAT.format(memorySla.getThreshold()) + "%]"); } else { logger.warning("GSC [" + ToStringHelper.gscToString(gsc) + "] - Memory [" + NUMBER_FORMAT.format(avgMemoryHeapUsedPerc) + "%] breached threshold of [" + NUMBER_FORMAT.format(memorySla.getThreshold()) + "%]"); gscsWithBreach.add(gsc); } } else if (memoryHeapUsedPerc > memorySla.getThreshold()) { logger.warning("GSC [" + ToStringHelper.gscToString(gsc) + "] - Memory [" + NUMBER_FORMAT.format(memoryHeapUsedPerc) + "%] is fluctuating above threshold of [" + NUMBER_FORMAT.format(memorySla.getThreshold()) + "%]"); } } //nothing to do if (gscsWithBreach.isEmpty()) { logger.finest("None of the GSCs breached above the threshold of [" + NUMBER_FORMAT.format(memorySla.getThreshold()) +"]" ); return; } //sort from high to low Collections.sort(gscsWithBreach, new Comparator<GridServiceContainer>() { public int compare(GridServiceContainer gsc1, GridServiceContainer gsc2) { double memoryHeapUsedPerc1 = gsc1.getVirtualMachine().getStatistics().getMemoryHeapUsedPerc(); double memoryHeapUsedPerc2 = gsc2.getVirtualMachine().getStatistics().getMemoryHeapUsedPerc(); return (int)(memoryHeapUsedPerc2 - memoryHeapUsedPerc1); } }); ProcessingUnit pu = puCapacityPlanner.getProcessingUnit(); ZoneCorrelator zoneCorrelator = new ZoneCorrelator(admin, puCapacityPlanner.getZoneName()); for (GridServiceContainer gsc : gscsWithBreach) { double memoryHeapUsedPerc = gsc.getVirtualMachine().getStatistics().getMemoryHeapUsedPerc(); logger.finest("Trying to handle GSC [" + ToStringHelper.gscToString(gsc) + "] - Memory [" + NUMBER_FORMAT.format(memoryHeapUsedPerc) + "%] with [" + gsc.getProcessingUnitInstances().length + "] processing units"); for (ProcessingUnitInstance puInstanceToMaybeRelocate : gsc.getProcessingUnitInstances()) { int estimatedMemoryHeapUsedPercPerInstance = getEstimatedMemoryHeapUsedPercPerInstance(gsc, puInstanceToMaybeRelocate); logger.finer("Finding GSC that can hold [" + ToStringHelper.puInstanceToString(puInstanceToMaybeRelocate) + "] with an estimate of [" + NUMBER_FORMAT.format(estimatedMemoryHeapUsedPercPerInstance) + "%]"); List<GridServiceContainer> gscsInZone = zoneCorrelator.getGridServiceContainers(); //sort from low to high Collections.sort(gscsInZone, new Comparator<GridServiceContainer>() { public int compare(GridServiceContainer gsc1, GridServiceContainer gsc2) { double memoryHeapUsedPerc1 = gsc1.getVirtualMachine().getStatistics().getMemoryHeapUsedPerc(); double memoryHeapUsedPerc2 = gsc2.getVirtualMachine().getStatistics().getMemoryHeapUsedPerc(); return (int)(memoryHeapUsedPerc1 - memoryHeapUsedPerc2); } }); for (GridServiceContainer gscToRelocateTo : gscsInZone) { //if gsc is the same gsc as the pu instance we are handling - skip it if (gscToRelocateTo.equals(puInstanceToMaybeRelocate.getGridServiceContainer())) { continue; } //if gsc reached its scale limit (of processing units) then skip it if (!(gscToRelocateTo.getProcessingUnitInstances().length < puCapacityPlanner.getScalingFactor())) { logger.finest("Skipping GSC ["+ToStringHelper.gscToString(gscToRelocateTo)+"] - reached the scale limit"); continue; //can't use this GSC to scale } int memoryHeapUsedByThisGsc = (int)Math.ceil(gscToRelocateTo.getVirtualMachine().getStatistics().getMemoryHeapUsedPerc()); if (memoryHeapUsedByThisGsc + estimatedMemoryHeapUsedPercPerInstance > memorySla.getThreshold()) { logger.finest("Skipping GSC ["+ToStringHelper.gscToString(gscToRelocateTo)+"] - memory used ["+NUMBER_FORMAT.format(memoryHeapUsedByThisGsc)+"%]"); continue; } // if GSC on same machine, no need to check for co-location constraints // since these were already checked when instance was instantiated if (!gscToRelocateTo.getMachine().equals(puInstanceToMaybeRelocate.getMachine())) { //TODO add max-instances-per-vm and max-instances-per-zone if necessary //verify max instances per machine if (pu.getMaxInstancesPerMachine() > 0) { int instancesOnMachine = 0; for (ProcessingUnitInstance instance : puInstanceToMaybeRelocate.getPartition().getInstances()) { if (instance.getMachine().equals(gscToRelocateTo.getMachine())) { ++instancesOnMachine; } } if (instancesOnMachine >= pu.getMaxInstancesPerMachine()) { logger.finest("Skipping GSC ["+ToStringHelper.gscToString(gscToRelocateTo)+"] - reached max-instances-per-machine limit"); continue; //reached limit } } } //precaution - if we are about to relocate make sure there is a backup in a partition-sync2backup topology. if (puInstanceToMaybeRelocate.getProcessingUnit().getNumberOfBackups() > 0) { ProcessingUnitInstance backup = puInstanceToMaybeRelocate.getPartition().getBackup(); if (backup == null) { logger.finest("No backup found for instance : " +ToStringHelper.puInstanceToString(puInstanceToMaybeRelocate)); return; } } logger.finer("Found GSC [" + ToStringHelper.gscToString(gscToRelocateTo) + "] which has only ["+NUMBER_FORMAT.format(memoryHeapUsedByThisGsc)+"%] used."); logger.info("Memory above threshold - Relocating [" + ToStringHelper.puInstanceToString(puInstanceToMaybeRelocate) + "] from GSC [" + ToStringHelper.gscToString(gsc) + "] to GSC [" + ToStringHelper.gscToString(gscToRelocateTo) + "]"); puInstanceToMaybeRelocate.relocateAndWait(gscToRelocateTo, 60, TimeUnit.SECONDS); workflow.breakWorkflow(); return; //found a gsc } } } logger.finest("Needs to scale up/out to obey memory SLA"); workflow.breakWorkflow(); workflow.add(new StartGscHandler(puCapacityPlanner, workflow)); } private double getAvgMemoryHeapUsedPerc(GridServiceContainer gsc) { List<VirtualMachineStatistics> timeline = gsc.getVirtualMachine().getStatistics().getTimeline(); double avgMemoryHeapUsedPerc = 0.0; for (int i=0; i<memorySla.getSubsetSize() && i<timeline.size(); ++i) { VirtualMachineStatistics statistics = timeline.get(i); double memoryHeapUsedPerc = statistics.getMemoryHeapUsedPerc(); avgMemoryHeapUsedPerc += memoryHeapUsedPerc; } avgMemoryHeapUsedPerc /= memorySla.getSubsetSize(); return avgMemoryHeapUsedPerc; } public void handleBreachBelowThreshold() { //handle only if deployment is intact if (!puCapacityPlanner.getProcessingUnit().getStatus().equals(DeploymentStatus.INTACT)) { return; } /* * Go over GSCs, and gather GSCs below threshold */ List<GridServiceContainer> gscs = new ArrayList<GridServiceContainer>(); for (ProcessingUnitInstance puInstance : puCapacityPlanner.getProcessingUnit()) { GridServiceContainer gsc = puInstance.getGridServiceContainer(); if (!gscs.contains(gsc)) { gscs.add(gsc); } } List<GridServiceContainer> gscsWithoutBreach = new ArrayList<GridServiceContainer>(); for (GridServiceContainer gsc : gscs) { if (gsc.getProcessingUnitInstances().length == 1) { double memoryHeapUsedPerc = gsc.getVirtualMachine().getStatistics().getMemoryHeapUsedPerc(); double avgMemoryHeapUsedPerc = getAvgMemoryHeapUsedPerc(gsc); if (avgMemoryHeapUsedPerc < memorySla.getThreshold()) { logger.finest("GSC [" + ToStringHelper.gscToString(gsc) + "] - Memory [" + NUMBER_FORMAT.format(avgMemoryHeapUsedPerc) + "%] is below threshold of [" + NUMBER_FORMAT.format(memorySla.getThreshold()) + "%]"); gscsWithoutBreach.add(gsc); }else if (memoryHeapUsedPerc < memorySla.getThreshold()) { logger.finest("GSC [" + ToStringHelper.gscToString(gsc) + "] - Memory [" + NUMBER_FORMAT.format(memoryHeapUsedPerc) + "%] is fluctuating below threshold of [" + NUMBER_FORMAT.format(memorySla.getThreshold()) + "%]"); } } } //nothing to do if (gscsWithoutBreach.isEmpty()) { return; } //sort from low to high Collections.sort(gscsWithoutBreach, new Comparator<GridServiceContainer>() { public int compare(GridServiceContainer gsc1, GridServiceContainer gsc2) { double memoryHeapUsedPerc1 = gsc1.getVirtualMachine().getStatistics().getMemoryHeapUsedPerc(); double memoryHeapUsedPerc2 = gsc2.getVirtualMachine().getStatistics().getMemoryHeapUsedPerc(); return (int)(memoryHeapUsedPerc1 - memoryHeapUsedPerc2); } }); ProcessingUnit pu = puCapacityPlanner.getProcessingUnit(); ZoneCorrelator zoneCorrelator = new ZoneCorrelator(admin, puCapacityPlanner.getZoneName()); for (GridServiceContainer gsc : gscsWithoutBreach) { if (gsc.getProcessingUnitInstances().length > 1) { continue; } for (ProcessingUnitInstance puInstanceToMaybeRelocate : gsc.getProcessingUnitInstances()) { int estimatedMemoryHeapUsedInMB = (int)Math.ceil(gsc.getVirtualMachine().getStatistics().getMemoryHeapUsedInMB()); int estimatedMemoryHeapUsedPerc = (int)Math.ceil(gsc.getVirtualMachine().getStatistics().getMemoryHeapUsedPerc()); //getEstimatedMemoryHeapUsedPercPerInstance(gsc, puInstanceToMaybeRelocate); logger.finer("Finding GSC that can hold [" + ToStringHelper.puInstanceToString(puInstanceToMaybeRelocate) + "] with [" + NUMBER_FORMAT.format(estimatedMemoryHeapUsedPerc) + "%]"); List<GridServiceContainer> gscsInZone = zoneCorrelator.getGridServiceContainers(); //sort from low to high Collections.sort(gscsInZone, new Comparator<GridServiceContainer>() { public int compare(GridServiceContainer gsc1, GridServiceContainer gsc2) { double memoryHeapUsedPerc1 = gsc1.getVirtualMachine().getStatistics().getMemoryHeapUsedPerc(); double memoryHeapUsedPerc2 = gsc2.getVirtualMachine().getStatistics().getMemoryHeapUsedPerc(); return (int)(memoryHeapUsedPerc1 - memoryHeapUsedPerc2); } }); for (GridServiceContainer gscToRelocateTo : gscsInZone) { //if gsc is the same gsc as the pu instance we are handling - skip it if (gscToRelocateTo.equals(puInstanceToMaybeRelocate.getGridServiceContainer())) { //logger.finest("Skipping GSC ["+ToStringHelper.gscToString(gscToRelocateTo)+"] - same GSC as this instance"); continue; } //if gsc reached its scale limit (of processing units) then skip it if (!(gscToRelocateTo.getProcessingUnitInstances().length < puCapacityPlanner.getScalingFactor())) { logger.finest("Skipping GSC ["+ToStringHelper.gscToString(gscToRelocateTo)+"] - reached the scale limit"); continue; //can't use this GSC to scale } int memoryHeapUsedPercByThisGsc = (int)Math.ceil(gscToRelocateTo.getVirtualMachine().getStatistics().getMemoryHeapUsedPerc()); int memoryRequiredInPerc = memoryHeapUsedPercByThisGsc + estimatedMemoryHeapUsedPerc; if (memoryRequiredInPerc > memorySla.getThreshold()) { logger.finest("Skipping GSC ["+ToStringHelper.gscToString(gscToRelocateTo)+"] - memory used ["+NUMBER_FORMAT.format(memoryHeapUsedPercByThisGsc)+"%]" + " - required ["+ memoryRequiredInPerc+"%] exceeds threshold of ["+memorySla.getThreshold()+"%]"); continue; } int memoryHeapUsedInMB = (int)Math.ceil(gscToRelocateTo.getVirtualMachine().getStatistics().getMemoryHeapUsedInMB()); int memoryRequiredInMB = memoryHeapUsedInMB+estimatedMemoryHeapUsedInMB+memorySafetyBufferInMB; int memorySlaThresholdInMB = (int)Math.ceil((100.0-memorySla.getThreshold())*gscToRelocateTo.getVirtualMachine().getDetails().getMemoryHeapMaxInMB()/100); if (memoryRequiredInMB > memorySlaThresholdInMB) { logger.finest("Skipping GSC ["+ToStringHelper.gscToString(gscToRelocateTo)+"] - required ["+NUMBER_FORMAT.format(memoryRequiredInMB)+" MB] exceeds threshold of ["+memorySlaThresholdInMB+" MB]"); continue; } // if GSC on same machine, no need to check for co-location constraints // since these were already checked when instance was instantiated if (!gscToRelocateTo.getMachine().equals(puInstanceToMaybeRelocate.getMachine())) { //TODO add max-instances-per-vm and max-instances-per-zone if necessary //verify max instances per machine if (pu.getMaxInstancesPerMachine() > 0) { int instancesOnMachine = 0; for (ProcessingUnitInstance instance : puInstanceToMaybeRelocate.getPartition().getInstances()) { if (instance.getMachine().equals(gscToRelocateTo.getMachine())) { ++instancesOnMachine; } } if (instancesOnMachine >= pu.getMaxInstancesPerMachine()) { logger.finest("Skipping GSC ["+ToStringHelper.gscToString(gscToRelocateTo)+"] - reached max-instances-per-machine limit"); continue; //reached limit } } } logger.finer("Found GSC [" + ToStringHelper.gscToString(gscToRelocateTo) + "] which has only ["+NUMBER_FORMAT.format(memoryHeapUsedPercByThisGsc)+"%] used."); logger.info("Memory below threshold - Relocating [" + ToStringHelper.puInstanceToString(puInstanceToMaybeRelocate) + "] from GSC [" + ToStringHelper.gscToString(gsc) + "] to GSC [" + ToStringHelper.gscToString(gscToRelocateTo) + "]"); puInstanceToMaybeRelocate.relocateAndWait(gscToRelocateTo, 60, TimeUnit.SECONDS); workflow.breakWorkflow(); workflow.add(new GscCollectorHandler(puCapacityPlanner, workflow)); return; } } } return; } private int getEstimatedMemoryHeapUsedPercPerInstance(GridServiceContainer gsc, ProcessingUnitInstance puInstance) { int totalPuNumOfObjects = 0; int thisPuNumOfObjects = 0; for (ProcessingUnitInstance aPuInstance : gsc.getProcessingUnitInstances()) { try { IJSpace space = aPuInstance.getSpaceInstance().getGigaSpace().getSpace(); SpaceRuntimeInfo runtimeInfo = ((IRemoteJSpaceAdmin)space.getAdmin()).getRuntimeInfo(); Integer numOfEntries = runtimeInfo.m_NumOFEntries.isEmpty() ? 0 : runtimeInfo.m_NumOFEntries.get(0); Integer numOfTemplates = runtimeInfo.m_NumOFTemplates.isEmpty() ? 0 : runtimeInfo.m_NumOFTemplates.get(0); int nObjects = numOfEntries + numOfTemplates; totalPuNumOfObjects += nObjects; if (aPuInstance.equals(puInstance)) { thisPuNumOfObjects = nObjects; } }catch(Exception e) { e.printStackTrace(); } } double memoryHeapUsed = gsc.getVirtualMachine().getStatistics().getMemoryHeapUsedPerc(); int estimatedMemoryHeapUsedPerc = 0; if (thisPuNumOfObjects == 0) { if (totalPuNumOfObjects == 0) { estimatedMemoryHeapUsedPerc = (int)Math.ceil(memoryHeapUsed/gsc.getProcessingUnitInstances().length); } else { estimatedMemoryHeapUsedPerc = (int)Math.ceil(memoryHeapUsed/totalPuNumOfObjects); } } else { estimatedMemoryHeapUsedPerc = (int)Math.ceil((thisPuNumOfObjects * memoryHeapUsed)/totalPuNumOfObjects); } return estimatedMemoryHeapUsedPerc; } } private class RebalancerHandler implements Runnable { private final PuCapacityPlanner puCapacityPlanner; private final Workflow workflow; public RebalancerHandler(PuCapacityPlanner puCapacityPlanner, Workflow workflow) { this.puCapacityPlanner = puCapacityPlanner; this.workflow = workflow; } public void run() { if (!puCapacityPlanner.getProcessingUnit().getStatus().equals(DeploymentStatus.INTACT)) { return; } logger.finest(RebalancerHandler.class.getSimpleName() + " invoked"); List<Machine> machinesSortedByNumOfPrimaries = getMachinesSortedByNumPrimaries(puCapacityPlanner); Machine firstMachine = machinesSortedByNumOfPrimaries.get(0); int optimalNumberOfPrimariesPerMachine = (int)Math.ceil(1.0*puCapacityPlanner.getProcessingUnit().getNumberOfInstances() / puCapacityPlanner.getNumberOfMachinesInZone()); int numPrimariesOnMachine = getNumPrimariesOnMachine(puCapacityPlanner, firstMachine); if (numPrimariesOnMachine > optimalNumberOfPrimariesPerMachine) { logger.finer("Rebalancer - Expects [" + optimalNumberOfPrimariesPerMachine + "] primaries per machine; Machine [" + ToStringHelper.machineToString(firstMachine) + " has: " + numPrimariesOnMachine + " - rebalancing..."); findPrimaryProcessingUnitToRestart(puCapacityPlanner, machinesSortedByNumOfPrimaries); } else { logger.finest("Rebalancer - Machines are balanced; ["+optimalNumberOfPrimariesPerMachine+"] per machine"); } } private List<Machine> getMachinesSortedByNumPrimaries(final PuCapacityPlanner puCapacityPlanner) { String zoneName = puCapacityPlanner.getZoneName(); Zone zone = admin.getZones().getByName(zoneName); List<GridServiceContainer> gscList = Arrays.asList(zone.getGridServiceContainers().getContainers()); List<Machine> machinesInZone = new ArrayList<Machine>(); for (GridServiceContainer gsc : gscList) { if (!machinesInZone.contains(gsc.getMachine())) machinesInZone.add(gsc.getMachine()); } Collections.sort(machinesInZone, new Comparator<Machine>() { public int compare(Machine m1, Machine m2) { return getNumPrimariesOnMachine(puCapacityPlanner, m2) - getNumPrimariesOnMachine(puCapacityPlanner, m1); } }); return machinesInZone; } private int getNumPrimariesOnMachine(PuCapacityPlanner puCapacityPlanner, Machine machine) { String zoneName = puCapacityPlanner.getZoneName(); Zone zone = admin.getZones().getByName(zoneName); int numPrimaries = 0; ProcessingUnitInstance[] instances = zone.getProcessingUnitInstances(); for (ProcessingUnitInstance instance : instances) { if (!instance.getMachine().equals(machine)) { continue; } if (isPrimary(instance)) { numPrimaries++; } } return numPrimaries; } private boolean isPrimary(ProcessingUnitInstance instance) { SpaceInstance spaceInstance = instance.getSpaceInstance(); return (spaceInstance != null && spaceInstance.getMode().equals(SpaceMode.PRIMARY)); } //find primary processing unit that it's backup is on a machine with the least number of primaries and restart it private void findPrimaryProcessingUnitToRestart(PuCapacityPlanner puCapacityPlanner, List<Machine> machinesSortedByNumOfPrimaries) { Machine lastMachine = machinesSortedByNumOfPrimaries.get(machinesSortedByNumOfPrimaries.size() -1); for (Machine machine : machinesSortedByNumOfPrimaries) { List<GridServiceContainer> gscsSortedByNumPrimaries = getGscsSortedByNumPrimaries(puCapacityPlanner, machine); for (GridServiceContainer gsc : gscsSortedByNumPrimaries) { for (ProcessingUnitInstance puInstance : gsc.getProcessingUnitInstances()) { if (isPrimary(puInstance)) { ProcessingUnitInstance backup = puInstance.getPartition().getBackup(); if (backup == null) { logger.finest("Skipping - no backup found yet for instance : " + ToStringHelper.puInstanceToString(puInstance)); return; //something is wrong, wait for next reschedule } GridServiceContainer backupGsc = backup.getGridServiceContainer(); if (backupGsc.getMachine().equals(lastMachine)) { restartPrimaryInstance(puInstance); return; } } } } } } private List<GridServiceContainer> getGscsSortedByNumPrimaries(PuCapacityPlanner puCapacityPlanner, Machine machine) { String zoneName = puCapacityPlanner.getZoneName(); Zone zone = admin.getZones().getByName(zoneName); //extract only gscs within this machine which belong to this zone List<GridServiceContainer> gscList = new ArrayList<GridServiceContainer>(); for (GridServiceContainer gsc : zone.getGridServiceContainers().getContainers()) { if (gsc.getMachine().equals(machine)) { gscList.add(gsc); } } Collections.sort(gscList, new Comparator<GridServiceContainer>() { public int compare(GridServiceContainer gsc1, GridServiceContainer gsc2) { int puDiff = getNumPrimaries(gsc2) - getNumPrimaries(gsc1); return puDiff; } }); return gscList; } private int getNumPrimaries(GridServiceContainer gsc) { int numPrimaries = 0; ProcessingUnitInstance[] instances = gsc.getProcessingUnitInstances(); for (ProcessingUnitInstance instance : instances) { if (isPrimary(instance)) { numPrimaries++; } } return numPrimaries; } private void restartPrimaryInstance(ProcessingUnitInstance instance) { //Perquisite precaution - can happen if state changed if (!instance.getProcessingUnit().getStatus().equals(DeploymentStatus.INTACT)) { return; } logger.info("Rebalancing - Restarting instance " + ToStringHelper.puInstanceToString(instance) + " at GSC " + ToStringHelper.gscToString(instance.getGridServiceContainer())); ProcessingUnitInstance restartedInstance = instance.restartAndWait(); workflow.breakWorkflow(); boolean isBackup = restartedInstance.waitForSpaceInstance().waitForMode(SpaceMode.BACKUP, 10, TimeUnit.SECONDS); if (!isBackup) { logger.finest("Waited 10 seconds, instance " + ToStringHelper.puInstanceToString(instance) + " still not registered as backup"); return; } logger.finest("Done restarting instance " + ToStringHelper.puInstanceToString(instance)); } } private class GscCollectorHandler implements Runnable { private final PuCapacityPlanner puCapacityPlanner; private final Workflow workflow; public GscCollectorHandler(PuCapacityPlanner puCapacityPlanner, Workflow workflow) { this.puCapacityPlanner = puCapacityPlanner; this.workflow = workflow; } public void run() { //Perquisite precaution if (!puCapacityPlanner.getProcessingUnit().getStatus().equals(DeploymentStatus.INTACT)) { return; } logger.finest(GscCollectorHandler.class.getSimpleName() + " invoked"); String zoneName = puCapacityPlanner.getZoneName(); Zone zone = admin.getZones().getByName(zoneName); if (zone == null) return; for (GridServiceContainer gsc : zone.getGridServiceContainers()) { if (gsc.getProcessingUnitInstances().length == 0) { logger.info("Scaling down - Terminate empty GSC ["+ToStringHelper.gscToString(gsc)+"]"); gsc.kill(); workflow.breakWorkflow(); } if (gsc.getMachine().getGridServiceContainers().getSize() == 0) { logger.info("Scaling in - No need for machine ["+ToStringHelper.machineToString(gsc.getMachine())+"]"); puCapacityPlanner.getElasticScale().scaleIn(gsc.getMachine()); } } } } private class UndeployHandler implements Runnable { private final PuCapacityPlanner puCapacityPlanner; public UndeployHandler(PuCapacityPlanner puCapacityPlanner) { this.puCapacityPlanner = puCapacityPlanner; } public void run() { //Perquisite precaution //TODO due to bug in status, postpone this check // if (!puCapacityPlanner.getProcessingUnit().getStatus().equals(DeploymentStatus.UNDEPLOYED)) { // return; logger.finest(UndeployHandler.class.getSimpleName() + " invoked"); elasticScaleMap.remove(puCapacityPlanner.getProcessingUnit().getName()); String zoneName = puCapacityPlanner.getZoneName(); Zone zone = admin.getZones().getByName(zoneName); if (zone == null) return; for (GridServiceContainer gsc : zone.getGridServiceContainers()) { int gscsOnMachine = gsc.getMachine().getGridServiceContainers().getSize(); if (gsc.getProcessingUnitInstances().length == 0) { logger.info("Scaling down - Terminate empty GSC ["+ToStringHelper.gscToString(gsc)+"]"); gsc.kill(); gscsOnMachine } if (gscsOnMachine == 0) { logger.info("Scaling in - No need for machine ["+ToStringHelper.machineToString(gsc.getMachine())+"]"); puCapacityPlanner.getElasticScale().scaleIn(gsc.getMachine()); } } } } private final class CompromisedDeploymentHandler implements Runnable { private final PuCapacityPlanner puCapacityPlanner; private final Workflow workflow; public CompromisedDeploymentHandler(PuCapacityPlanner puCapacityPlanner, Workflow workflow) { this.puCapacityPlanner = puCapacityPlanner; this.workflow = workflow; } public void run() { if (deploymentStatusCompromised()) { logger.finest(CompromisedDeploymentHandler.class.getSimpleName() + " invoked"); workflow.breakWorkflow(); workflow.add(new StartGscHandler(puCapacityPlanner, workflow)); } } private boolean deploymentStatusCompromised() { DeploymentStatus status = puCapacityPlanner.getProcessingUnit().getStatus(); return DeploymentStatus.BROKEN.equals(status) || DeploymentStatus.COMPROMISED.equals(status); } } }
//TODO: this should be able to be removed @javax.xml.bind.annotation.XmlSchema(namespace = "https: package org.owasp.appsensor;
package com.readytalk.oss.dbms.server; import static com.readytalk.oss.dbms.imp.Util.list; import static com.readytalk.oss.dbms.imp.Util.set; import com.readytalk.oss.dbms.imp.Util; import com.readytalk.oss.dbms.imp.MyDBMS; import com.readytalk.oss.dbms.DBMS; import com.readytalk.oss.dbms.DBMS.Index; import com.readytalk.oss.dbms.DBMS.ColumnReference; import com.readytalk.oss.dbms.DBMS.Source; import com.readytalk.oss.dbms.DBMS.Expression; import com.readytalk.oss.dbms.DBMS.QueryTemplate; import com.readytalk.oss.dbms.DBMS.PatchTemplate; import com.readytalk.oss.dbms.DBMS.PatchContext; import com.readytalk.oss.dbms.DBMS.QueryResult; import com.readytalk.oss.dbms.DBMS.ResultType; import com.readytalk.oss.dbms.DBMS.ConflictResolver; import com.readytalk.oss.dbms.DBMS.Revision; import com.readytalk.oss.dbms.DBMS.JoinType; import com.readytalk.oss.dbms.DBMS.BinaryOperationType; import com.readytalk.oss.dbms.DBMS.UnaryOperationType; import com.readytalk.oss.dbms.DBMS.Row; import java.util.Collection; import java.util.List; import java.util.ArrayList; import java.util.Set; import java.util.HashSet; import java.util.Map; import java.util.HashMap; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Logger; import java.util.logging.Level; import java.io.Reader; import java.io.InputStreamReader; import java.io.IOException; import java.io.EOFException; import java.io.InputStream; import java.io.OutputStream; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.net.InetSocketAddress; import java.nio.channels.Channels; import java.nio.channels.SocketChannel; import java.nio.channels.ServerSocketChannel; public class SQLServer { private static final Logger log = Logger.getLogger("SQLServer"); public enum Request { Execute, Complete; } public enum Response { RowSet, NewDatabase, CopySuccess, Success, Error; } public enum RowSetFlag { InsertedRow, DeletedRow, End, Item; } private static final int ThreadPoolSize = 256; private static final Tree Nothing = new Leaf(); private static final Set<Index> EmptyIndexSet = new HashSet(); private static class Server { public final DBMS dbms; public final Parser parser = new ParserFactory().parser(); public final PatchTemplate insertOrUpdateDatabase; public final QueryTemplate listDatabases; public final QueryTemplate findDatabase; public final PatchTemplate deleteDatabase; public final PatchTemplate insertOrUpdateTable; public final QueryTemplate listTables; public final QueryTemplate findTable; public final PatchTemplate deleteDatabaseTables; public final PatchTemplate deleteTable; public final DBMS.Column tagsDatabase; public final DBMS.Column tagsName; public final DBMS.Column tagsTag; public final DBMS.Table tags; public final PatchTemplate insertOrUpdateTag; public final QueryTemplate listTags; public final QueryTemplate findTag; public final PatchTemplate deleteDatabaseTags; public final PatchTemplate deleteTag; public final AtomicReference<Revision> dbHead; public final Map<String, BinaryOperationType> binaryOperationTypes = new HashMap(); public final Map<String, UnaryOperationType> unaryOperationTypes = new HashMap(); public final Map<String, Class> columnTypes = new HashMap(); public final ConflictResolver rightPreferenceConflictResolver = new ConflictResolver() { public Row resolveConflict(DBMS.Table table, Collection<DBMS.Column> columns, Revision base, Row baseRow, Revision left, Row leftRow, Revision right, Row rightRow) { return leftPreferenceMerge(columns, baseRow, rightRow, leftRow); } }; public final ConflictResolver conflictResolver = new ConflictResolver() { public Row resolveConflict(DBMS.Table table, Collection<DBMS.Column> columns, Revision base, Row baseRow, Revision left, Row leftRow, Revision right, Row rightRow) { if (table == tags) { HashRow result = new HashRow(3); result.put(tagsDatabase, leftRow.value(tagsDatabase)); result.put(tagsName, leftRow.value(tagsName)); result.put(tagsTag, new Tag ((String) leftRow.value(tagsName), dbms.merge (baseRow == null ? dbms.revision() : ((Tag) baseRow.value(tagsTag)).revision, ((Tag) leftRow.value(tagsTag)).revision, ((Tag) rightRow.value(tagsTag)).revision, rightPreferenceConflictResolver))); return result; } else { return leftPreferenceMerge(columns, baseRow, rightRow, leftRow); } } }; public Server(DBMS dbms) { this.dbms = dbms; DBMS.Column databasesName = dbms.column(String.class); DBMS.Column databasesDatabase = dbms.column(Object.class); DBMS.Table databases = dbms.table (set(databasesName, databasesDatabase), dbms.index(list(databasesName), true), EmptyIndexSet); DBMS.TableReference databasesReference = dbms.tableReference(databases); this.insertOrUpdateDatabase = dbms.insertTemplate (databases, list(databasesName, databasesDatabase), list(dbms.parameter(), dbms.parameter()), true); this.listDatabases = dbms.queryTemplate (list((Expression) dbms.columnReference (databasesReference, databasesDatabase)), databasesReference, dbms.constant(true)); this.findDatabase = dbms.queryTemplate (list((Expression) dbms.columnReference (databasesReference, databasesDatabase)), databasesReference, dbms.operation (BinaryOperationType.Equal, dbms.columnReference(databasesReference, databasesName), dbms.parameter())); this.deleteDatabase = dbms.deleteTemplate (databasesReference, dbms.operation (BinaryOperationType.Equal, dbms.columnReference(databasesReference, databasesName), dbms.parameter())); DBMS.Column tablesDatabase = dbms.column(String.class); DBMS.Column tablesName = dbms.column(String.class); DBMS.Column tablesTable = dbms.column(Object.class); DBMS.Table tables = dbms.table (set(tablesDatabase, tablesName, tablesTable), dbms.index(list(tablesDatabase, tablesName), true), EmptyIndexSet); DBMS.TableReference tablesReference = dbms.tableReference(tables); this.insertOrUpdateTable = dbms.insertTemplate (tables, list(tablesDatabase, tablesName, tablesTable), list(dbms.parameter(), dbms.parameter(), dbms.parameter()), true); this.listTables = dbms.queryTemplate (list((Expression) dbms.columnReference(tablesReference, tablesTable)), tablesReference, dbms.operation (BinaryOperationType.Equal, dbms.columnReference(tablesReference, tablesDatabase), dbms.parameter())); this.findTable = dbms.queryTemplate (list((Expression) dbms.columnReference(tablesReference, tablesTable)), tablesReference, dbms.operation (BinaryOperationType.And, dbms.operation (BinaryOperationType.Equal, dbms.columnReference(tablesReference, tablesDatabase), dbms.parameter()), dbms.operation (BinaryOperationType.Equal, dbms.columnReference(tablesReference, tablesName), dbms.parameter()))); this.deleteDatabaseTables = dbms.deleteTemplate (tablesReference, dbms.operation (BinaryOperationType.Equal, dbms.columnReference(tablesReference, tablesDatabase), dbms.parameter())); this.deleteTable = dbms.deleteTemplate (tablesReference, dbms.operation (BinaryOperationType.And, dbms.operation (BinaryOperationType.Equal, dbms.columnReference(tablesReference, tablesDatabase), dbms.parameter()), dbms.operation (BinaryOperationType.Equal, dbms.columnReference(tablesReference, tablesName), dbms.parameter()))); this.tagsDatabase = dbms.column(String.class); this.tagsName = dbms.column(String.class); this.tagsTag = dbms.column(Object.class); this.tags = dbms.table (set(tagsDatabase, tagsName, tagsTag), dbms.index(list(tagsDatabase, tagsName), true), EmptyIndexSet); DBMS.TableReference tagsReference = dbms.tableReference(tags); this.insertOrUpdateTag = dbms.insertTemplate (tags, list(tagsDatabase, tagsName, tagsTag), list(dbms.parameter(), dbms.parameter(), dbms.parameter()), true); this.listTags = dbms.queryTemplate (list((Expression) dbms.columnReference(tagsReference, tagsTag)), tagsReference, dbms.operation (BinaryOperationType.Equal, dbms.columnReference(tagsReference, tagsDatabase), dbms.parameter())); this.findTag = dbms.queryTemplate (list((Expression) dbms.columnReference(tagsReference, tagsTag)), tagsReference, dbms.operation (BinaryOperationType.And, dbms.operation (BinaryOperationType.Equal, dbms.columnReference(tagsReference, tagsDatabase), dbms.parameter()), dbms.operation (BinaryOperationType.Equal, dbms.columnReference(tagsReference, tagsName), dbms.parameter()))); this.deleteDatabaseTags = dbms.deleteTemplate (tagsReference, dbms.operation (BinaryOperationType.Equal, dbms.columnReference(tagsReference, tagsDatabase), dbms.parameter())); this.deleteTag = dbms.deleteTemplate (tagsReference, dbms.operation (BinaryOperationType.And, dbms.operation (BinaryOperationType.Equal, dbms.columnReference(tagsReference, tagsDatabase), dbms.parameter()), dbms.operation (BinaryOperationType.Equal, dbms.columnReference(tagsReference, tagsName), dbms.parameter()))); this.dbHead = new AtomicReference(dbms.revision()); binaryOperationTypes.put("and", BinaryOperationType.And); binaryOperationTypes.put("or", BinaryOperationType.Or); binaryOperationTypes.put("=", BinaryOperationType.Equal); binaryOperationTypes.put("<>", BinaryOperationType.NotEqual); binaryOperationTypes.put(">", BinaryOperationType.GreaterThan); binaryOperationTypes.put(">=", BinaryOperationType.GreaterThanOrEqual); binaryOperationTypes.put("<", BinaryOperationType.LessThan); binaryOperationTypes.put("<=", BinaryOperationType.LessThanOrEqual); unaryOperationTypes.put("not", UnaryOperationType.Not); columnTypes.put("int32", Integer.class); columnTypes.put("int64", Long.class); columnTypes.put("string", String.class); } } private static boolean equal(Object left, Object right) { return left == right || (left != null && left.equals(right)); } private static Row leftPreferenceMerge(Collection<DBMS.Column> columns, Row base, Row left, Row right) { if (base == null) { return left; } else { HashRow result = new HashRow(columns.size()); for (DBMS.Column c: columns) { Object baseItem = base.value(c); Object leftItem = left.value(c); Object rightItem = right.value(c); if (equal(baseItem, leftItem)) { result.put(c, rightItem); } else { result.put(c, leftItem); } } return result; } } private static class LeftPreferenceConflictResolver implements ConflictResolver { public int conflictCount; public Row resolveConflict(DBMS.Table table, Collection<DBMS.Column> columns, Revision base, Row baseRow, Revision left, Row leftRow, Revision right, Row rightRow) { ++ conflictCount; return leftPreferenceMerge(columns, baseRow, leftRow, rightRow); } } private static class HashRow implements Row { public final Map<DBMS.Column, Object> values; public HashRow(int size) { this.values = new HashMap(size); } public void put(DBMS.Column column, Object value) { values.put(column, value); } public Object value(DBMS.Column column) { return values.get(column); } } private static class Transaction { public final Transaction next; public final Revision dbTail; public Revision dbHead; public Transaction(Transaction next, Revision dbTail) { this.next = next; this.dbTail = dbTail; this.dbHead = dbTail; } } private static class CopyContext { public final PatchContext context; public final PatchTemplate template; public final List<Class> columnTypes; public final StringBuilder stringBuilder = new StringBuilder(); public final Object[] parameters; public int count; public boolean trouble; public CopyContext(PatchContext context, PatchTemplate template, List<Class> columnTypes) { this.context = context; this.template = template; this.columnTypes = columnTypes; this.parameters = new Object[columnTypes.size()]; } } private static class Client implements Runnable { public final Server server; public final SocketChannel channel; public Transaction transaction; public Database database; public CopyContext copyContext; public Client(Server server, SocketChannel channel) { this.server = server; this.channel = channel; } public void run() { try { try { InputStream in = new BufferedInputStream (Channels.newInputStream(channel)); OutputStream out = new BufferedOutputStream (Channels.newOutputStream(channel)); while (channel.isOpen()) { handleRequest(this, in, out); } } finally { channel.close(); } } catch (Exception e) { log.log(Level.WARNING, null, e); } } } private enum NameType { Database, Table, Column, Tag; } private static class Database { public final String name; public Database(String name) { this.name = name; } } private static class Column { public final String name; public final DBMS.Column column; public final Class type; public Column(String name, DBMS.Column column, Class type) { this.name = name; this.column = column; this.type = type; } } private static class Table { public final String name; public final List<Column> columnList; public final Map<String, Column> columnMap; public final List<Column> primaryKeyColumns; public final DBMS.Table table; public Table(String name, List<Column> columnList, Map<String, Column> columnMap, List<Column> primaryKeyColumns, DBMS.Table table) { this.name = name; this.columnList = columnList; this.columnMap = columnMap; this.primaryKeyColumns = primaryKeyColumns; this.table = table; } } private static class Tag { public final String name; public final Revision revision; public Tag(String name, Revision revision) { this.name = name; this.revision = revision; } } private static class TableReference { public final Table table; public final DBMS.TableReference reference; public TableReference(Table table, DBMS.TableReference reference) { this.table = table; this.reference = reference; } } private static class ParseResult { public final Tree tree; public final String next; public final Set<String> completions; public Task task; public ParseResult(Tree tree, String next, Set<String> completions) { this.tree = tree; this.next = next; this.completions = completions; } } private static class ParseContext { public final Client client; public final String start; public Map<NameType, Set<String>> completions; public int depth; public ParseContext(Client client, String start) { this.client = client; this.start = start; } } private interface Parser { public ParseResult parse(ParseContext context, String in); } private static class LazyParser implements Parser { public Parser parser; public ParseResult parse(ParseContext context, String in) { if (context.depth++ > 10) throw new RuntimeException("debug"); return parser.parse(context, in); } } private interface Tree { public Tree get(int index); public int length(); } private static class TreeList implements Tree { public final List<Tree> list = new ArrayList(); public void add(Tree tree) { list.add(tree); } public Tree get(int index) { return list.get(index); } public int length() { return list.size(); } public String toString() { return list.toString(); } } private static class Leaf implements Tree { public Tree get(int index) { throw new UnsupportedOperationException(); } public int length() { throw new UnsupportedOperationException(); } } private static class Terminal extends Leaf { public final String value; public Terminal(String value) { this.value = value; } public String toString() { return "terminal[" + value + "]"; } } private static class Name extends Leaf { public final String value; public Name(String value) { this.value = value; } public String toString() { return "name[" + value + "]"; } } private static class StringLiteral extends Leaf { public final String value; public StringLiteral(String value) { this.value = value; } public String toString() { return "stringLiteral[" + value + "]"; } } private static class NumberLiteral extends Leaf { public final long value; public NumberLiteral(String value) { this.value = Long.parseLong(value); } public String toString() { return "numberLiteral[" + value + "]"; } } private static class BooleanLiteral extends Leaf { public final boolean value; public BooleanLiteral(boolean value) { this.value = value; } public String toString() { return "booleanLiteral[" + value + "]"; } } private interface Task { public void run(Client client, Tree tree, InputStream in, OutputStream out) throws IOException; } private static Revision dbHead(Client client) { if (client.transaction != null) { return client.transaction.dbHead; } else { return client.server.dbHead.get(); } } private static Database findDatabase(Client client, String name) { Server server = client.server; DBMS dbms = server.dbms; QueryResult result = dbms.diff (dbms.revision(), dbHead(client), server.findDatabase, name); if (result.nextRow() == ResultType.Inserted) { return (Database) result.nextItem(); } else { throw new RuntimeException("no such database: " + name); } } private static Tag findTag(Client client, String name) { Server server = client.server; DBMS dbms = server.dbms; if ("tail".equals(name)) { return new Tag(name, dbms.revision()); } QueryResult result = dbms.diff (dbms.revision(), dbHead(client), server.findTag, database(client).name, name); if (result.nextRow() == ResultType.Inserted) { return (Tag) result.nextItem(); } else if ("head".equals(name)) { return new Tag(name, dbms.revision()); } else { throw new RuntimeException("no such tag: " + name); } } private static Revision head(Client client) { return findTag(client, "head").revision; } private static Database database(Client client) { if (client.database == null) { throw new RuntimeException("no database specified"); } else { return client.database; } } private static Table findTable(Client client, String name) { DBMS dbms = client.server.dbms; QueryResult result = dbms.diff (dbms.revision(), dbHead(client), client.server.findTable, database(client).name, name); if (result.nextRow() == ResultType.Inserted) { return (Table) result.nextItem(); } else { throw new RuntimeException("no such table: " + name); } } private static Source makeSource(Client client, Tree tree, List<TableReference> tableReferences, List<Expression> tests) { if (tree instanceof Name) { Table table = findTable(client, ((Name) tree).value); DBMS.TableReference reference = client.server.dbms.tableReference (table.table); tableReferences.add(new TableReference(table, reference)); return reference; } else if (tree.get(0) instanceof Terminal) { return makeSource(client, tree.get(1), tableReferences, tests); } else { Source result = client.server.dbms.join ("left".equals(((Terminal) tree.get(1).get(0)).value) ? JoinType.LeftOuter : JoinType.Inner, makeSource(client, tree.get(0), tableReferences, tests), makeSource(client, tree.get(2), tableReferences, tests)); tests.add(makeExpression(client.server, tree.get(4), tableReferences)); return result; } } private static ColumnReference makeColumnReference (DBMS dbms, List<TableReference> tableReferences, String tableName, String columnName) { DBMS.TableReference reference = null; DBMS.Column column = null; for (TableReference r: tableReferences) { if (tableName == null || tableName.equals(r.table.name)) { Column c = r.table.columnMap.get(columnName); if (c != null) { if (column != null) { throw new RuntimeException("ambiguous column name: " + columnName); } else { reference = r.reference; column = c.column; if (tableName != null) { break; } } } } } if (column == null) { throw new RuntimeException ("no such column: " + (tableName == null ? "" : tableName + ".") + columnName); } return dbms.columnReference(reference, column); } private static UnaryOperationType findUnaryOperationType(Server server, String name) { return server.unaryOperationTypes.get(name); } private static BinaryOperationType findBinaryOperationType(Server server, String name) { return server.binaryOperationTypes.get(name); } private static Expression makeExpression (Server server, Tree tree, List<TableReference> tableReferences) { if (tree instanceof Name) { return makeColumnReference (server.dbms, tableReferences, null, ((Name) tree).value); } else if (tree instanceof StringLiteral) { return server.dbms.constant(((StringLiteral) tree).value); } else if (tree instanceof NumberLiteral) { return server.dbms.constant(((NumberLiteral) tree).value); } else if (tree instanceof BooleanLiteral) { return server.dbms.constant(((BooleanLiteral) tree).value); } if (tree.length() == 3) { if (tree.get(0) instanceof Name && ".".equals(((Terminal) tree.get(1)).value)) { return makeColumnReference (server.dbms, tableReferences, ((Name) tree.get(0)).value, ((Name) tree.get(2)).value); } return server.dbms.operation (findBinaryOperationType(server, ((Terminal) tree.get(1)).value), makeExpression(server, tree.get(0), tableReferences), makeExpression(server, tree.get(2), tableReferences)); } else { String value = ((Terminal) tree.get(0)).value; if ("(".equals(value)) { return makeExpression(server, tree.get(1), tableReferences); } else { return server.dbms.operation (findUnaryOperationType(server, value), makeExpression (server, tree.get(1), tableReferences)); } } } private static List<Expression> makeExpressionList (Server server, Tree tree, List<TableReference> tableReferences) { List<Expression> expressions = new ArrayList(); if (tree instanceof Terminal) { DBMS dbms = server.dbms; for (TableReference tableReference: tableReferences) { for (Column column: tableReference.table.columnList) { expressions.add (dbms.columnReference(tableReference.reference, column.column)); } } } else { for (int i = 0; i < tree.length(); ++i) { expressions.add (makeExpression(server, tree.get(i), tableReferences)); } } return expressions; } private static Expression makeExpressionFromWhere (Server server, Tree tree, List<TableReference> tableReferences) { if (tree == Nothing) { return server.dbms.constant(true); } else { return makeExpression(server, tree.get(1), tableReferences); } } private static Expression andExpressions(DBMS dbms, Expression expression, List<Expression> expressions) { for (Expression e: expressions) { expression = dbms.operation(BinaryOperationType.And, expression, e); } return expression; } private static QueryTemplate makeQueryTemplate(Client client, Tree tree, int[] expressionCount) { List<TableReference> tableReferences = new ArrayList(); List<Expression> tests = new ArrayList(); Source source = makeSource (client, tree.get(3), tableReferences, tests); List<Expression> expressions = makeExpressionList (client.server, tree.get(1), tableReferences); expressionCount[0] = expressions.size(); return client.server.dbms.queryTemplate (expressions, source, andExpressions (client.server.dbms, makeExpressionFromWhere (client.server, tree.get(4), tableReferences), tests)); } private static Column findColumn(Table table, String name) { Column c = table.columnMap.get(name); if (c == null) { throw new RuntimeException("no such column: " + name); } else { return c; } } private static List<DBMS.Column> makeColumnList(Table table, Tree tree) { List<DBMS.Column> columns = new ArrayList(tree.length()); for (int i = 0; i < tree.length(); ++i) { columns.add(findColumn(table, ((Name) tree.get(i)).value).column); } return columns; } private static List<DBMS.Column> makeOptionalColumnList(Table table, Tree tree) { if (tree == Nothing) { List<DBMS.Column> columns = new ArrayList(table.columnList.size()); for (Column c: table.columnList) { columns.add(c.column); } return columns; } else { return makeColumnList(table, tree.get(1)); } } private static PatchTemplate makeInsertTemplate(Client client, Tree tree) { Table table = findTable(client, ((Name) tree.get(2)).value); return client.server.dbms.insertTemplate (table.table, makeOptionalColumnList(table, tree.get(3)), makeExpressionList(client.server, tree.get(6), null), false); } private static PatchTemplate makeUpdateTemplate(Client client, Tree tree) { Table table = findTable(client, ((Name) tree.get(1)).value); TableReference tableReference = new TableReference (table, client.server.dbms.tableReference(table.table)); List<TableReference> tableReferences = list(tableReference); Tree operations = tree.get(3); List<DBMS.Column> columns = new ArrayList(); List<Expression> values = new ArrayList(); for (int i = 0; i < operations.length(); ++i) { Tree operation = operations.get(i); columns.add(findColumn(table, ((Name) operation.get(0)).value).column); values.add (makeExpression(client.server, operation.get(2), tableReferences)); } return client.server.dbms.updateTemplate (tableReference.reference, makeExpressionFromWhere (client.server, tree.get(4), tableReferences), columns, values); } private static PatchTemplate makeDeleteTemplate(Client client, Tree tree) { Table table = findTable(client, ((Name) tree.get(2)).value); TableReference tableReference = new TableReference (table, client.server.dbms.tableReference(table.table)); List<TableReference> tableReferences = list(tableReference); return client.server.dbms.deleteTemplate (tableReference.reference, makeExpressionFromWhere (client.server, tree.get(3), tableReferences)); } private static Column findColumn(Table table, DBMS.Column column) { for (Column c: table.columnList) { if (c.column == column) { return c; } } throw new RuntimeException(); } private static PatchTemplate makeCopyTemplate(Client client, Tree tree, List<Class> columnTypes) { Table table = findTable(client, ((Name) tree.get(1)).value); List<DBMS.Column> columns = makeOptionalColumnList(table, tree.get(2)); List<Expression> values = new ArrayList(columns.size()); DBMS dbms = client.server.dbms; for (DBMS.Column c: columns) { values.add(dbms.parameter()); columnTypes.add(findColumn(table, c).type); } return dbms.insertTemplate(table.table, columns, values, false); } private static Class findColumnType(Server server, String name) { Class type = server.columnTypes.get(name); if (type == null) { throw new RuntimeException("no such column type: " + name); } else { return type; } } private static Table makeTable(Server server, Tree tree) { Tree body = tree.get(4); Tree primaryKeyTree = null; List<Tree> columns = new ArrayList(); for (int i = 0; i < body.length(); ++i) { Tree item = body.get(i); if (item.get(0) instanceof Terminal) { if (primaryKeyTree != null) { throw new RuntimeException("more than one primary key specified"); } else { primaryKeyTree = item.get(3); } } else { columns.add(item); } } if (primaryKeyTree == null) { throw new RuntimeException("no primary key specified"); } DBMS dbms = server.dbms; List<Column> columnList = new ArrayList(columns.size()); Map<String, Column> columnMap = new HashMap(columns.size()); Set<DBMS.Column> columnSet = new HashSet(columns.size()); for (Tree column: columns) { Class type = findColumnType(server, ((Terminal) column.get(1)).value); DBMS.Column dbmsColumn = dbms.column(type); columnSet.add(dbmsColumn); Column myColumn = new Column (((Name) column.get(0)).value, dbmsColumn, type); columnList.add(myColumn); columnMap.put(myColumn.name, myColumn); } List<Column> myPrimaryKeyColumns = new ArrayList(primaryKeyTree.length()); List<DBMS.Column> dbmsPrimaryKeyColumns = new ArrayList (primaryKeyTree.length()); for (int i = 0; i < primaryKeyTree.length(); ++i) { Column c = columnMap.get(((Name) primaryKeyTree.get(i)).value); if (c == null) { throw new RuntimeException ("primary key refers to non-exisitant column " + ((Name) primaryKeyTree.get(i)).value); } else { myPrimaryKeyColumns.add(c); dbmsPrimaryKeyColumns.add(c.column); } } return new Table (((Name) tree.get(2)).value, columnList, columnMap, myPrimaryKeyColumns, dbms.table (columnSet, dbms.index(dbmsPrimaryKeyColumns, true), EmptyIndexSet)); } private static void writeInteger(OutputStream out, int v) throws IOException { out.write((v >>> 24) & 0xFF); out.write((v >>> 16) & 0xFF); out.write((v >>> 8) & 0xFF); out.write((v ) & 0xFF); } private static void writeString(OutputStream out, String string) throws IOException { byte[] bytes = string.getBytes("UTF-8"); writeInteger(out, bytes.length); out.write(bytes); } public static int readInteger(InputStream in) throws IOException { int b1 = in.read(); int b2 = in.read(); int b3 = in.read(); int b4 = in.read(); if (b4 == -1) throw new EOFException(); return (int) ((b1 << 24) | (b2 << 16) | (b3 << 8) | (b4)); } public static String readString(InputStream in) throws IOException { byte[] array = new byte[readInteger(in)]; int c; int offset = 0; while (offset < array.length && (c = in.read(array, offset, array.length - offset)) != -1) { offset += c; } return new String(array); } public static String makeList(Client client, Tree tree) { DBMS dbms = client.server.dbms; StringBuilder sb = new StringBuilder(); if (tree instanceof Terminal) { String type = ((Terminal) tree).value; if (type == "databases") { QueryResult result = dbms.diff (dbms.revision(), dbHead(client), client.server.listDatabases); while (result.nextRow() == ResultType.Inserted) { sb.append("\n"); sb.append(((Database) result.nextItem()).name); } } else if (type == "tables") { QueryResult result = dbms.diff (dbms.revision(), dbHead(client), client.server.listTables, database(client).name); while (result.nextRow() == ResultType.Inserted) { sb.append("\n"); sb.append(((Table) result.nextItem()).name); } } else if (type == "tags") { QueryResult result = dbms.diff (dbms.revision(), dbHead(client), client.server.listTags, database(client).name); while (result.nextRow() == ResultType.Inserted) { String name = ((Tag) result.nextItem()).name; if (! "head".equals(name)) { sb.append("\n"); sb.append(name); } } sb.append("\nhead\ntail"); } else { throw new RuntimeException("unexpected terminal: " + type); } } else { for (Column c: findTable (client, ((Name) tree.get(2)).value).columnList) { sb.append("\n"); sb.append(c.name); } } return sb.length() == 0 ? "\n no matches found" : sb.toString(); } public static String makeHelp() throws IOException { InputStream help = SQLServer.class.getResourceAsStream ("/sql-client-help.txt"); try { StringBuilder sb = new StringBuilder(); char[] buffer = new char[8096]; Reader in = new InputStreamReader(help); int c = 0; while ((c = in.read(buffer)) != -1) { sb.append(buffer, 0, c); } return sb.toString(); } finally { help.close(); } } private static void diff(DBMS dbms, Revision base, Revision fork, QueryTemplate template, int expressionCount, OutputStream out) throws IOException { QueryResult result = dbms.diff(base, fork, template); out.write(Response.RowSet.ordinal()); while (true) { ResultType resultType = result.nextRow(); switch (resultType) { case Inserted: out.write(RowSetFlag.InsertedRow.ordinal()); for (int i = 0; i < expressionCount; ++i) { out.write(RowSetFlag.Item.ordinal()); writeString(out, String.valueOf(result.nextItem())); } break; case Deleted: out.write(RowSetFlag.DeletedRow.ordinal()); for (int i = 0; i < expressionCount; ++i) { out.write(RowSetFlag.Item.ordinal()); writeString(out, String.valueOf(result.nextItem())); } break; case End: out.write(RowSetFlag.End.ordinal()); return; default: throw new RuntimeException("unexpected result type: " + resultType); } } } private static int apply(Client client, PatchTemplate template, Object ... parameters) { DBMS dbms = client.server.dbms; PatchContext context = dbms.patchContext(client.transaction.dbHead); int count = dbms.apply(context, template, parameters); client.transaction.dbHead = dbms.commit(context); return count; } private static void setDatabase(Client client, Database database) { apply(client, client.server.insertOrUpdateDatabase, database.name, database); } private static void setTable(Client client, Table table) { apply(client, client.server.insertOrUpdateTable, database(client).name, table.name, table); } private static void setTag(Client client, Tag tag) { if ("tail".equals(tag.name)) { throw new RuntimeException("cannot redefine tag \"tail\""); } apply(client, client.server.insertOrUpdateTag, database(client).name, tag.name, tag); } private static void pushTransaction(Client client) { Transaction next = client.transaction; client.transaction = new Transaction (next, next == null ? client.server.dbHead.get() : next.dbHead); } private static void commitTransaction(Client client) { if (client.transaction.next == null) { Revision myTail = client.transaction.dbTail; Revision myHead = client.transaction.dbHead; DBMS dbms = client.server.dbms; DBMS.ConflictResolver conflictResolver = client.server.conflictResolver; if (myTail != myHead) { AtomicReference<Revision> dbHead = client.server.dbHead; while (! dbHead.compareAndSet(myTail, myHead)) { Revision fork = dbHead.get(); myHead = dbms.merge(myTail, fork, myHead, conflictResolver); myTail = fork; } } } else { client.transaction.next.dbHead = client.transaction.dbHead; } } private static void popTransaction(Client client) { if (client.transaction == null) { throw new RuntimeException("no transaction in progress"); } client.transaction = client.transaction.next; } private static int apply(Client client, PatchTemplate template) { pushTransaction(client); try { DBMS dbms = client.server.dbms; PatchContext context = dbms.patchContext(head(client)); int count = dbms.apply(context, template); setTag(client, new Tag("head", dbms.commit(context))); commitTransaction(client); return count; } finally { popTransaction(client); } } private static Object convert(Class type, String value) { if (type == Integer.class || type == Long.class) { return Long.parseLong(value); } else if (type == String.class) { return value; } else { throw new RuntimeException("unexpected type: " + type); } } private static void copy(DBMS dbms, PatchContext context, PatchTemplate template, List<Class> columnTypes, StringBuilder sb, Object[] parameters, String line) throws IOException { boolean sawEscape = false; int index = 0; for (int i = 0; i < line.length(); ++i) { int c = line.charAt(i); switch (c) { case '\\': if (sawEscape) { sawEscape = false; sb.append((char) c); } else { sawEscape = true; } break; case ',': if (sawEscape) { sawEscape = false; sb.append((char) c); } else { parameters[index] = convert(columnTypes.get(index), sb.toString()); sb.setLength(0); ++ index; } break; default: if (sawEscape) { sawEscape = false; sb.append('\\'); } sb.append((char) c); break; } } if (sb.length() == 0 || index < parameters.length - 1) { throw new RuntimeException("not enough values specified"); } parameters[index] = convert(columnTypes.get(index), sb.toString()); sb.setLength(0); dbms.apply(context, template, parameters); } private static void applyCopy(Client client, String line, OutputStream out) throws IOException { CopyContext c = client.copyContext; if ("\\.".equals(line)) { setTag(client, new Tag("head", client.server.dbms.commit(c.context))); commitTransaction(client); popTransaction(client); out.write(Response.Success.ordinal()); writeString(out, "inserted " + c.count + " row(s)"); client.copyContext = null; } else if (! c.trouble) { try { copy(client.server.dbms, c.context, c.template, c.columnTypes, c.stringBuilder, c.parameters, line); ++ c.count; } catch (Exception e) { c.trouble = true; log.log(Level.WARNING, null, e); } } } private static void addCompletion(ParseContext context, NameType type, String name) { if (context.completions == null) { context.completions = new HashMap(); } Set<String> set = context.completions.get(type); if (set == null) { context.completions.put(type, set = new HashSet()); } set.add(name); } private static Set<String> findCompletions(Client client, NameType type, String start) { DBMS dbms = client.server.dbms; switch (type) { case Database: { QueryResult result = dbms.diff (dbms.revision(), dbHead(client), client.server.listDatabases); Set<String> set = new HashSet(); while (result.nextRow() == ResultType.Inserted) { String name = ((Database) result.nextItem()).name; if (name.startsWith(start)) { set.add(name); } } return set; } case Table: if (client.database != null) { QueryResult result = dbms.diff (dbms.revision(), dbHead(client), client.server.listTables, client.database.name); Set<String> set = new HashSet(); while (result.nextRow() == ResultType.Inserted) { String name = ((Table) result.nextItem()).name; if (name.startsWith(start)) { set.add(name); } } return set; } break; case Column: break; case Tag: if (client.database != null) { QueryResult result = dbms.diff (dbms.revision(), dbHead(client), client.server.listTags, client.database.name); Set<String> set = new HashSet(); while (result.nextRow() == ResultType.Inserted) { String name = ((Tag) result.nextItem()).name; if (name.startsWith(start)) { set.add(name); } } return set; } break; default: throw new RuntimeException("unexpected name type: " + type); } return null; } private static Set<String> findCompletions(ParseContext context, NameType type, String start) { if (type == NameType.Column) { if (context.completions != null) { Set<String> columnSet = context.completions.get(type); if (columnSet != null) { return columnSet; } else { Set<String> tableSet = context.completions.get(NameType.Table); if (tableSet != null && context.client.database != null) { DBMS dbms = context.client.server.dbms; Revision tail = dbms.revision(); Revision head = dbHead(context.client); Set<String> columns = new HashSet(); for (String tableName: tableSet) { QueryResult result = dbms.diff (tail, head, context.client.server.findTable, context.client.database.name, tableName); if (result.nextRow() == ResultType.Inserted) { for (Column c: ((Table) result.nextItem()).columnList) { if (c.name.startsWith(start)) { columns.add(c.name); } } } } if (columns.size() == 0) { return null; } else { return new HashSet(columns); } } else { return null; } } } else { return null; } } else { return findCompletions(context.client, type, start); } } private static class ParserFactory { public LazyParser expressionParser; public LazyParser sourceParser; public Parser parser() { return or (select(), diff(), insert(), update(), delete(), copy(), begin(), commit(), rollback(), tag(), merge(), list(), drop(), useDatabase(), createTable(), createDatabase(), help()); } public static Parser task(final Parser parser, final Task task) { return new Parser() { public ParseResult parse(ParseContext context, String in) { ParseResult result = parser.parse(context, in); if (result.tree != null) { result.task = task; } return result; } }; } public static ParseResult success(Tree tree, String next, Set<String> completions) { return new ParseResult(tree, next, completions); } public static ParseResult fail(Set<String> completions) { return new ParseResult(null, null, completions); } public static String skipSpace(String in) { int i = 0; while (i < in.length()) { if (Character.isSpace(in.charAt(i))) { ++ i; } else { break; } } return i == 0 ? in : in.substring(i); } public static String parseName(String in) { if (in.length() > 0) { char c = in.charAt(0); if (c == '_' || Character.isLetter(c)) { int i = 1; while (i < in.length()) { c = in.charAt(i); if (c == '_' || Character.isLetterOrDigit(c)) { ++ i; } else { break; } } return in.substring(0, i); } } return null; } public static Parser terminal(final String value, final boolean completeIfEmpty) { return new Parser() { private final Terminal terminal = new Terminal(value); public ParseResult parse(ParseContext context, String in) { String token = skipSpace(in); if (token.startsWith(value)) { return success(terminal, token.substring(value.length()), null); } else if ((token.length() > 0 || completeIfEmpty) && (token == context.start || token != in) && value.startsWith(token)) { return fail(set(value)); } else { return fail(null); } } }; } public static Parser terminal(final String value) { return terminal(value, true); } public static Parser or(final Parser ... parsers) { return new Parser() { public ParseResult parse(ParseContext context, String in) { Set<String> completions = null; for (Parser parser: parsers) { ParseResult result = parser.parse(context, in); if (result.tree != null) { return result; } else if (result.completions != null) { if (completions == null) { completions = new HashSet(); } completions.addAll(result.completions); } } return fail(completions); } }; } public static Parser list(final Parser parser) { return new Parser() { private final Parser comma = terminal(","); public ParseResult parse(ParseContext context, String in) { TreeList list = new TreeList(); while (true) { ParseResult result = parser.parse(context, in); if (result.tree != null) { list.add(result.tree); ParseResult commaResult = comma.parse(context, result.next); if (commaResult.tree != null) { in = commaResult.next; } else { return success(list, result.next, result.completions); } } else { return fail(result.completions); } } } }; } public static Parser sequence(final Parser ... parsers) { return new Parser() { public ParseResult parse(ParseContext context, String in) { TreeList list = new TreeList(); ParseResult previous = null; for (Parser parser: parsers) { ParseResult result = parser.parse(context, in); if (result.tree != null) { list.add(result.tree); if (in.length() > 0) { previous = result; } in = result.next; } else { if (in.length() == 0 && previous != null) { return fail(previous.completions); } return fail(result.completions); } } return success(list, in, previous.completions); } }; } public static Parser optional(final Parser parser) { return new Parser() { public ParseResult parse(ParseContext context, String in) { ParseResult result = parser.parse(context, in); if (result.tree != null) { return result; } else { return success(Nothing, in, result.completions); } } }; } public static Parser name(final NameType type, final boolean findCompletions, final boolean addCompletion) { return new Parser() { public ParseResult parse(ParseContext context, String in) { String token = skipSpace(in); String name = parseName(token); if (name != null) { if (addCompletion) { addCompletion(context, type, name); } return success (new Name(name), token.substring(name.length()), (token == context.start || token != in) && findCompletions ? findCompletions(context, type, name) : null); } else { return fail ((token == context.start || token != in) && findCompletions ? findCompletions(context, type, "") : null); } } }; } public static Parser stringLiteral() { return new Parser() { public ParseResult parse(ParseContext context, String in) { in = skipSpace(in); if (in.length() > 1) { StringBuilder sb = new StringBuilder(); char c = in.charAt(0); if (c == '\'') { boolean sawEscape = false; for (int i = 1; i < in.length(); ++i) { c = in.charAt(i); switch (c) { case '\\': if (sawEscape) { sawEscape = false; sb.append(c); } else { sawEscape = true; } break; case '\'': if (sawEscape) { sawEscape = false; sb.append(c); } else { return success(new StringLiteral(sb.toString()), in.substring(i + 1), null); } break; default: if (sawEscape) { sawEscape = false; sb.append('\\'); } sb.append(c); break; } } } } return fail(null); } }; } public static Parser numberLiteral() { return new Parser() { public ParseResult parse(ParseContext context, String in) { in = skipSpace(in); if (in.length() > 0) { char first = in.charAt(0); boolean negative = first == '-'; int start = negative ? 1 : 0; int i = start; while (i < in.length()) { char c = in.charAt(i); if (Character.isDigit(c)) { ++ i; } else { break; } } if (i > start) { return success(new NumberLiteral(in.substring(0, i)), in.substring(i), null); } else { return fail(null); } } return fail(null); } }; } public static Parser booleanLiteral() { return new Parser() { public ParseResult parse(ParseContext context, String in) { in = skipSpace(in); if (in.startsWith("true")) { return success(new BooleanLiteral(true), in.substring(4), null); } else if (in.startsWith("false")) { return success(new BooleanLiteral(false), in.substring(5), null); } else { return fail(null); } } }; } public Parser simpleExpression() { return or (columnName(), stringLiteral(), numberLiteral(), booleanLiteral(), sequence(terminal("(", false), expression(), terminal(")")), sequence(terminal("not", false), expression())); } public Parser comparison() { return sequence(simpleExpression(), or(terminal("="), terminal("<>"), terminal("<"), terminal("<="), terminal(">"), terminal(">=")), simpleExpression()); } public Parser expression() { if (expressionParser == null) { expressionParser = new LazyParser(); expressionParser.parser = or (sequence(or(comparison(), simpleExpression()), or(terminal("and"), terminal("or")), expression()), comparison(), simpleExpression()); } return expressionParser; } public Parser simpleSource() { return or (name(NameType.Table, true, true), sequence(terminal("(", false), source(), terminal(")"))); } public Parser source() { if (sourceParser == null) { sourceParser = new LazyParser(); sourceParser.parser = or (sequence(simpleSource(), sequence(or(terminal("left"), terminal("inner")), terminal("join")), source(), terminal("on"), expression()), simpleSource()); } return sourceParser; } public static Parser columnName() { return or (sequence(name(NameType.Table, false, false), terminal("."), name(NameType.Column, true, false)), name(NameType.Column, true, false)); } public Parser select() { return task (sequence (terminal("select"), or(terminal("*", false), list(expression())), terminal("from"), source(), optional(sequence(terminal("where"), expression()))), new Task() { public void run(Client client, Tree tree, InputStream in, OutputStream out) throws IOException { DBMS dbms = client.server.dbms; int[] expressionCount = new int[1]; SQLServer.diff (dbms, dbms.revision(), head(client), makeQueryTemplate (client, tree, expressionCount), expressionCount[0], out); } }); } public Parser diff() { return task (sequence (terminal("diff"), name(NameType.Tag, true, false), name(NameType.Tag, true, false), select()), new Task() { public void run(Client client, Tree tree, InputStream in, OutputStream out) throws IOException { DBMS dbms = client.server.dbms; int[] expressionCount = new int[1]; SQLServer.diff (dbms, findTag(client, ((Name) tree.get(1)).value).revision, findTag(client, ((Name) tree.get(2)).value).revision, makeQueryTemplate (client, tree.get(3), expressionCount), expressionCount[0], out); } }); } public Parser insert() { return task (sequence (terminal("insert"), terminal("into"), name(NameType.Table, true, true), optional(sequence(terminal("("), list(columnName()), terminal(")"))), terminal("values"), terminal("("), list(or(stringLiteral(), numberLiteral(), booleanLiteral())), terminal(")")), new Task() { public void run(Client client, Tree tree, InputStream in, OutputStream out) throws IOException { apply(client, makeInsertTemplate(client, tree)); out.write(Response.Success.ordinal()); writeString(out, "inserted 1 row"); } }); } public Parser update() { return task (sequence (terminal("update"), name(NameType.Table, true, true), terminal("set"), list(sequence(columnName(), terminal("="), expression())), optional(sequence(terminal("where"), expression()))), new Task() { public void run(Client client, Tree tree, InputStream in, OutputStream out) throws IOException { int count = apply(client, makeUpdateTemplate(client, tree)); out.write(Response.Success.ordinal()); writeString(out, "updated " + count + " row(s)"); } }); } public Parser delete() { return task (sequence (terminal("delete"), terminal("from"), name(NameType.Table, true, true), optional(sequence(terminal("where"), expression()))), new Task() { public void run(Client client, Tree tree, InputStream in, OutputStream out) throws IOException { int count = apply(client, makeDeleteTemplate(client, tree)); out.write(Response.Success.ordinal()); writeString(out, "deleted " + count + " row(s)"); } }); } public Parser copy() { return task (sequence (terminal("copy"), name(NameType.Table, true, true), optional(sequence(terminal("("), list(columnName()), terminal(")"))), terminal("from"), terminal("stdin")), new Task() { public void run(Client client, Tree tree, InputStream in, OutputStream out) throws IOException { List<Class> columnTypes = new ArrayList(); client.copyContext = new CopyContext (client.server.dbms.patchContext(head(client)), makeCopyTemplate (client, tree, columnTypes), columnTypes); pushTransaction(client); out.write(Response.CopySuccess.ordinal()); writeString(out, "reading row data until \"\\.\""); } }); } public static Parser begin() { return task (terminal("begin"), new Task() { public void run(Client client, Tree tree, InputStream in, OutputStream out) throws IOException { pushTransaction(client); out.write(Response.Success.ordinal()); writeString(out, "pushed new transaction context"); } }); } public static Parser commit() { return task (terminal("commit"), new Task() { public void run(Client client, Tree tree, InputStream in, OutputStream out) throws IOException { commitTransaction(client); popTransaction(client); out.write(Response.Success.ordinal()); writeString(out, "committed transaction"); } }); } public static Parser rollback() { return task (terminal("rollback"), new Task() { public void run(Client client, Tree tree, InputStream in, OutputStream out) throws IOException { popTransaction(client); out.write(Response.Success.ordinal()); writeString(out, "abandoned transaction"); } }); } public static Parser tag() { return task (sequence (terminal("tag"), name(NameType.Tag, false, false), name(NameType.Tag, true, false)), new Task() { public void run(Client client, Tree tree, InputStream in, OutputStream out) throws IOException { pushTransaction(client); try { setTag(client, new Tag (((Name) tree.get(1)).value, findTag(client, ((Name) tree.get(2)).value).revision)); commitTransaction(client); } finally { popTransaction(client); } out.write(Response.Success.ordinal()); writeString(out, "tag " + ((Name) tree.get(1)).value + " set to " + ((Name) tree.get(2)).value); } }); } public static Parser merge() { return task (sequence (terminal("merge"), name(NameType.Tag, true, false), name(NameType.Tag, true, false), name(NameType.Tag, true, false)), new Task() { public void run(Client client, Tree tree, InputStream in, OutputStream out) throws IOException { LeftPreferenceConflictResolver conflictResolver = new LeftPreferenceConflictResolver(); pushTransaction(client); try { setTag(client, new Tag ("head", client.server.dbms.merge (findTag(client, ((Name) tree.get(1)).value).revision, findTag(client, ((Name) tree.get(2)).value).revision, findTag(client, ((Name) tree.get(3)).value).revision, conflictResolver))); commitTransaction(client); } finally { popTransaction(client); } out.write(Response.Success.ordinal()); writeString(out, "head set to result of merge (" + conflictResolver.conflictCount + " conflict(s))"); } }); } public static Parser list() { return task (sequence (terminal("list"), or(terminal("databases"), terminal("tables"), terminal("tags"), sequence(terminal("columns"), terminal("of"), name(NameType.Table, true, false)))), new Task() { public void run(Client client, Tree tree, InputStream in, OutputStream out) throws IOException { String list = makeList(client, tree.get(1)); out.write(Response.Success.ordinal()); writeString(out, list); } }); } public static Parser drop() { return task (sequence (terminal("drop"), or(sequence(terminal("database"), name(NameType.Database, true, false)), sequence(terminal("table"), name(NameType.Table, true, false)), sequence(terminal("tag"), name(NameType.Tag, true, false)))), new Task() { public void run(Client client, Tree tree, InputStream in, OutputStream out) throws IOException { tree = tree.get(1); String type = ((Terminal) tree.get(0)).value; String name = ((Name) tree.get(1)).value; pushTransaction(client); try { DBMS dbms = client.server.dbms; PatchContext context = dbms.patchContext (client.transaction.dbHead); if ("database".equals(type)) { dbms.apply(context, client.server.deleteDatabase, name); dbms.apply(context, client.server.deleteDatabaseTables, name); dbms.apply(context, client.server.deleteDatabaseTags, name); } else if ("table".equals(type)) { dbms.apply(context, client.server.deleteTable, database(client).name, name); } else if ("tag".equals(type)) { dbms.apply(context, client.server.deleteTag, database(client).name, name); } else { throw new RuntimeException(); } client.transaction.dbHead = dbms.commit(context); commitTransaction(client); } finally { popTransaction(client); } out.write(Response.Success.ordinal()); writeString(out, "dropped " + type + " " + name); } }); } public static Parser useDatabase() { return task (sequence (terminal("use"), terminal("database"), name(NameType.Database, true, false)), new Task() { public void run(Client client, Tree tree, InputStream in, OutputStream out) throws IOException { String name = ((Name) tree.get(2)).value; client.database = findDatabase(client, name); out.write(Response.NewDatabase.ordinal()); writeString(out, name); writeString(out, "switched to database " + name); } }); } public static Parser createTable() { return task (sequence (terminal("create"), terminal("table"), name(NameType.Table, false, false), terminal("("), list(or(sequence(terminal("primary"), terminal("key"), terminal("("), list(name(NameType.Column, true, false)), terminal(")")), sequence(name(NameType.Column, false, true), or(terminal("int32"), terminal("int64"), terminal("string"), terminal("array"))))), terminal(")")), new Task() { public void run(Client client, Tree tree, InputStream in, OutputStream out) throws IOException { pushTransaction(client); try { setTable(client, makeTable(client.server, tree)); commitTransaction(client); } finally { popTransaction(client); } out.write(Response.Success.ordinal()); writeString(out, "table " + ((Name) tree.get(2)).value + " defined"); } }); } public static Parser createDatabase() { return task (sequence (terminal("create"), terminal("database"), name(NameType.Database, false, false)), new Task() { public void run(Client client, Tree tree, InputStream in, OutputStream out) throws IOException { String name = ((Name) tree.get(2)).value; pushTransaction(client); try { setDatabase(client, new Database(name)); commitTransaction(client); } finally { popTransaction(client); } out.write(Response.Success.ordinal()); writeString(out, "created database " + name); } }); } public static Parser help() { return task (terminal("help"), new Task() { public void run(Client client, Tree tree, InputStream in, OutputStream out) throws IOException { String help = makeHelp(); out.write(Response.Success.ordinal()); writeString(out, help); } }); } } private static void executeRequest(Client client, InputStream in, OutputStream out) throws IOException { String s = readString(in); log.info("execute \"" + s + "\""); try { if (client.copyContext == null) { ParseResult result = client.server.parser.parse (new ParseContext(client, s), s); if (result.task != null) { result.task.run(client, result.tree, in, out); } else { out.write(Response.Error.ordinal()); writeString(out, "Sorry, I don't understand."); } } else { applyCopy(client, s, out); } } catch (Exception e) { out.write(Response.Error.ordinal()); String message = e.getMessage(); writeString(out, message == null ? "see server logs" : message); log.log(Level.WARNING, null, e); } } private static void completeRequest(Client client, InputStream in, OutputStream out) throws IOException { String s = readString(in); log.info("complete \"" + s + "\""); if (client.copyContext == null) { ParseResult result = client.server.parser.parse (new ParseContext(client, s), s); out.write(Response.Success.ordinal()); if (result.completions == null) { log.info("no completions"); writeInteger(out, 0); } else { log.info("completions: " + result.completions); writeInteger(out, result.completions.size()); for (String completion: result.completions) { writeString(out, completion); } } } else { log.info("no completions in copy mode"); out.write(Response.Success.ordinal()); writeInteger(out, 0); } } private static void handleRequest(Client client, InputStream in, OutputStream out) throws IOException { int requestType = in.read(); if (requestType == -1) { client.channel.close(); return; } switch (Request.values()[requestType]) { case Execute: executeRequest(client, in, out); out.flush(); break; case Complete: completeRequest(client, in, out); out.flush(); break; default: throw new RuntimeException("unexpected request type: " + requestType); } } private static void listen(String address, int port) throws IOException { ServerSocketChannel serverChannel = ServerSocketChannel.open(); serverChannel.socket().bind(new InetSocketAddress(address, port)); ThreadPoolExecutor executor = new ThreadPoolExecutor (ThreadPoolSize, // core thread count ThreadPoolSize, // maximum thread count 60, TimeUnit.SECONDS, // maximum thread idle time new LinkedBlockingQueue<Runnable>()); executor.allowCoreThreadTimeOut(true); Server server = new Server(new MyDBMS()); while (true) { executor.execute(new Client(server, serverChannel.accept())); } } public static void main(String[] args) throws IOException { if (args.length == 2) { listen(args[0], Integer.parseInt(args[1])); } else { System.err.println("usage: java " + SQLServer.class.getName() + " <address> <port>"); System.exit(-1); } } }
package com.sigseg.android.worldmap; import android.util.Log; public class Application extends android.app.Application { // private final static String TAG = "Application"; public final static boolean DEBUG = true; @Override public void onCreate() { logMemory("app-start"); super.onCreate(); } private static void logMemory(String tag){ long freeMemory = Runtime.getRuntime().freeMemory(); long maxMemory = Runtime.getRuntime().maxMemory(); if (Application.DEBUG) Log.d(tag,String.format("maxMemory=%d, freeMemory=%d, diff=%d",maxMemory,freeMemory,maxMemory-freeMemory)); } }
// $Id: Doradeiosp.java,v 1.12 2006/04/19 20:24:49 yuanho Exp $ package ucar.nc2.iosp.dorade; import ucar.ma2.*; import ucar.nc2.*; import ucar.nc2.dataset.NetcdfDataset; import ucar.atd.dorade.*; import java.io.*; import java.util.*; //import java.awt.image.BufferedImage; /** * IOServiceProvider implementation abstract base class to read/write "version 3" netcdf files. * AKA "file format version 1" files. * * see concrete class */ public class Doradeiosp implements ucar.nc2.IOServiceProvider { protected boolean readonly; private ucar.nc2.NetcdfFile ncfile; private ucar.unidata.io.RandomAccessFile myRaf; protected Doradeheader headerParser; public static DoradeSweep mySweep = null; boolean littleEndian; public void setProperties( List iospProperties) { } public ucar.ma2.Array readNestedData(ucar.nc2.Variable v2, java.util.List section) throws java.io.IOException, ucar.ma2.InvalidRangeException { throw new UnsupportedOperationException("Dorade IOSP does not support nested variables"); } public boolean isValidFile( ucar.unidata.io.RandomAccessFile raf ) { Doradeheader localHeader = new Doradeheader(); return( localHeader.isValidFile( raf )); } // reading public void open(ucar.unidata.io.RandomAccessFile raf, ucar.nc2.NetcdfFile file, ucar.nc2.util.CancelTask cancelTask) throws IOException { ncfile = file; myRaf = raf; try { mySweep = new DoradeSweep(raf.getLocation()); } catch (DoradeSweep.DoradeSweepException ex) { ex.printStackTrace(); } catch (java.io.IOException ex) { ex.printStackTrace(); } if(mySweep.getScanMode(0) != ScanMode.MODE_SUR) { System.err.println("ScanMode is : " + mySweep.getScanMode(0).getName()); //System.exit(1); } try { headerParser = new Doradeheader(); headerParser.read(mySweep, ncfile, null); } catch (DoradeSweep.DoradeSweepException e) { e.printStackTrace(); } ncfile.finish(); } public Array readData(ucar.nc2.Variable v2, java.util.List section) throws IOException, InvalidRangeException { Array outputData = null; int nSensor = mySweep.getNSensors(); int nRays = mySweep.getNRays(); if ( v2.getName().equals( "elevation")) { float [] elev = mySweep.getElevations(); outputData = readData1(v2, section, elev); //outputData = Array.factory( v2.getDataType().getPrimitiveClassType(), v2.getShape(), elev); } else if ( v2.getName().equals( "rays_time")) { Date [] dd = mySweep.getTimes(); double [] d = new double [dd.length]; for(int i = 0; i < dd.length; i++ ) d[i] = (double) dd[i].getTime(); outputData = readData2(v2, section, d); //outputData = Array.factory( v2.getDataType().getPrimitiveClassType(), v2.getShape(), d); } else if (v2.getName().equals( "azimuth")) { float [] azim = mySweep.getAzimuths(); outputData = readData1(v2, section, azim); //outputData = Array.factory( v2.getDataType().getPrimitiveClassType(), v2.getShape(), azim); } else if (v2.getName().startsWith( "latitudes_")) { float [] allLats = new float[nSensor*nRays]; float [] lats = null; for (int i = 0; i < nSensor; i++){ lats = mySweep.getLatitudes(i); System.arraycopy(lats, 0, allLats, i*nRays, nRays); } outputData = readData1(v2, section, allLats); //outputData = Array.factory( v2.getDataType().getPrimitiveClassType(), v2.getShape(), allLats); } else if (v2.getName().startsWith( "longitudes_")) { float [] allLons = new float[nSensor*nRays]; float [] lons = null; for (int i = 0; i < nSensor; i++){ lons = mySweep.getLongitudes(i); System.arraycopy(lons, 0, allLons, i*nRays, nRays); } outputData = readData1(v2, section, allLons); //outputData = Array.factory( v2.getDataType().getPrimitiveClassType(), v2.getShape(), lons); } else if (v2.getName().startsWith( "altitudes_")) { float [] allAlts = new float [nSensor*nRays]; float [] alts = null; for (int i = 0; i < nSensor; i++){ alts = mySweep.getAltitudes(i); System.arraycopy(alts, 0, allAlts, i*nRays, nRays); } outputData = readData1(v2, section, allAlts); //outputData = Array.factory( v2.getDataType().getPrimitiveClassType(), v2.getShape(), alts); } else if (v2.getName().startsWith( "distance_")) { float [] dist = null; int j = 0; for (int i = 0; i < nSensor; i++) { String t = "" + i; if( v2.getName().endsWith(t) ) { j = i ; break; } } int nc = mySweep.getNCells(j); Array data = NetcdfDataset.makeArray( DataType.FLOAT, nc, (double) mySweep.getRangeToFirstCell(j), (double) mySweep.getCellSpacing(j)); dist = (float [])data.get1DJavaArray(Float.class); outputData = readData1(v2, section, dist);; } else if(v2.isScalar()) { float d = 0.0f; if( v2.getName().equals("Range_to_First_Cell") ) { d = mySweep.getRangeToFirstCell(0); } else if (v2.getName().equals("Cell_Spacing")) { d = mySweep.getCellSpacing(0); } else if (v2.getName().equals("Fixed_Angle")) { d = mySweep.getFixedAngle(); } else if (v2.getName().equals("Nyquist_Velocity")) { d = mySweep.getUnambiguousVelocity(0); } else if (v2.getName().equals("Unambiguous_Range")) { d = mySweep.getunambiguousRange(0); } else if (v2.getName().equals("Radar_Constant")) { d = mySweep.getradarConstant(0); }else if (v2.getName().equals("rcvr_gain")) { d = mySweep.getrcvrGain(0); } else if (v2.getName().equals("ant_gain")) { d = mySweep.getantennaGain(0); } else if (v2.getName().equals("sys_gain")) { d = mySweep.getsystemGain(0); } else if (v2.getName().equals("bm_width")) { d = mySweep.gethBeamWidth(0); } float [] dd = new float[1]; dd[0] = d; outputData = Array.factory( v2.getDataType().getPrimitiveClassType(), v2.getShape(), dd); } else { Range radialRange = (Range) section.get(0); Range gateRange = (Range) section.get(1); Array data = Array.factory(v2.getDataType().getPrimitiveClassType(), Range.getShape( section)); IndexIterator ii = data.getIndexIterator(); DoradePARM dp = mySweep.lookupParamIgnoreCase(v2.getName()); int ncells = dp.getNCells(); float[] rayValues = new float[ncells]; /* float[] allValues = new float[nRays * ncells]; for (int r = 0; r < nRays; r++) { try { rayValues = mySweep.getRayData(dp, r, rayValues); } catch (DoradeSweep.DoradeSweepException ex) { ex.printStackTrace(); } System.arraycopy(rayValues, 0, allValues, r*ncells, ncells); } */ for (int r=radialRange.first(); r<=radialRange.last(); r+= radialRange.stride()) { try { rayValues = mySweep.getRayData(dp, r, rayValues); } catch (DoradeSweep.DoradeSweepException ex) { ex.printStackTrace(); } for (int i=gateRange.first(); i<=gateRange.last(); i+= gateRange.stride()){ ii.setFloatNext( rayValues[i]); } } return data; //outputData = Array.factory( v2.getDataType().getPrimitiveClassType(), v2.getShape(), allValues); } return outputData; } public Array readData1(Variable v2, java.util.List section, float[] values) { Array data = Array.factory(v2.getDataType().getPrimitiveClassType(), Range.getShape( section)); IndexIterator ii = data.getIndexIterator(); Range radialRange = (Range) section.get(0); // radial range can also be gate range for (int r=radialRange.first(); r<=radialRange.last(); r+= radialRange.stride()) { ii.setFloatNext( values[r]); } return data; } public Array readData2(Variable v2, java.util.List section, double[] values) { Array data = Array.factory(v2.getDataType().getPrimitiveClassType(), Range.getShape( section)); IndexIterator ii = data.getIndexIterator(); Range radialRange = (Range) section.get(0); for (int r=radialRange.first(); r<=radialRange.last(); r+= radialRange.stride()) { ii.setDoubleNext(values[r]); } return data; } // all the work is here, so can be called recursively public Array readData(ucar.nc2.Variable v2, long dataPos, int [] origin, int [] shape, int [] stride) throws IOException, InvalidRangeException { return null; } // for the compressed data read all out into a array and then parse into requested // convert byte array to char array static protected char[] convertByteToChar( byte[] byteArray) { int size = byteArray.length; char[] cbuff = new char[size]; for (int i=0; i<size; i++) cbuff[i] = (char) byteArray[i]; return cbuff; } // convert char array to byte array static protected byte[] convertCharToByte( char[] from) { int size = from.length; byte[] to = new byte[size]; for (int i=0; i<size; i++) to[i] = (byte) from[i]; return to; } protected boolean fill; protected HashMap dimHash = new HashMap(50); public void flush() throws java.io.IOException { myRaf.flush(); } public void close() throws java.io.IOException { myRaf.close(); } public boolean syncExtend() { return false; } public boolean sync() { return false; } /** Debug info for this object. */ public String toStringDebug(Object o) { return null; } public String getDetailInfo() { return ""; } public static void main(String args[]) throws Exception, IOException, InstantiationException, IllegalAccessException { String fileIn = "/home/yuanho/dorade/swp.1020511015815.SP0L.573.1.2_SUR_v1"; //String fileIn = "c:/data/image/Dorade/n0r_20041013_1852"; ucar.nc2.NetcdfFile.registerIOProvider( ucar.nc2.iosp.dorade.Doradeiosp.class); ucar.nc2.NetcdfFile ncf = ucar.nc2.NetcdfFile.open(fileIn); //List alist = ncf.getGlobalAttributes(); ucar.unidata.io.RandomAccessFile file = new ucar.unidata.io.RandomAccessFile(fileIn, "r"); //open1(file, null, null); //ucar.nc2.Variable v = ncf.findVariable("BaseReflectivity"); //ncf.close(); } }
package main; import org.w3c.dom.ranges.RangeException; import java.util.ArrayList; public class Game { public enum states { STRIKE, STANDARD, SPARE, LAST_SPARE, LAST_STRIKE }; private ArrayList<Frame> frames; private final int MAX_FRAMES = 10; public Game() { frames = new ArrayList<>(10); } public int getFrameSize() { return frames.size(); } public boolean insertFrame(Frame f) { boolean result = frames.add(f); if (frames.size() > MAX_FRAMES) { throw new RangeException((short) 1, "Invalid range"); } return result; } public int getGameScore() { int sum = 0; boolean strike = false; boolean spare = false; int numOfStrikes = 0; for(int i = 0; i < frames.size(); i++) { if(spare) { spare = false; sum += frames.get(i).getArr(0); } if(isStrike(i) && i != MAX_FRAMES-1) { numOfStrikes++; strike = true; } else if(isSpare(i)) { spare = true; sum += 10; } else { sum += frames.get(i).getScore(1); } if(!strike) { for (int j = 0; j < numOfStrikes; j++) { if (j == 0) { sum += 10 + frames.get(i).getScore(-0); } else { sum += (numOfStrikes * 10) + frames.get(i).getArr(0); } } numOfStrikes = 0; } else if (numOfStrikes == 3) { sum += 30; numOfStrikes = 2; } strike = false; } return sum; } public boolean isStrike(){ return frames.get(frames.size()-1).getArr(0) == 10; } public boolean isStrike(int pos){ return frames.get(pos).getArr(0) == 10; } public boolean isSpare(){ if(frames.get(getFrameSize()-1).getArr(0) == 10){ return false; } else if(frames.get(getFrameSize()-1).getScore(-1) == 10){ return true; } return false; } public boolean isSpare(int pos){ if(frames.get(pos).getArr(0) == 10){ return false; } else if(frames.get(pos).getScore(1) == 10){ return true; } return false; } private void calculateStrikeSum() { } }
package main; import input.Listening; import java.applet.*; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Image; import java.awt.Point; import java.awt.Toolkit; import javax.swing.*; import world.World; import mobs.*; import mobs.grav.SquarePlayer; public class Main extends Applet implements Runnable { private static final long serialVersionUID = 8864158495101925325L; //because stupid warnings public static int pixelSize = 1; //change the scale the pixels are multiplied by when drawn to public static int tickTime = 50; public static int ticksPerSecond = (1000/Main.tickTime); public static boolean isRunning = false, isPaused = false, isGameOver = false; public static String windowName = "Shapes are awesome"; public static boolean debugMode = false; public static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); public static int screenWidth = (int)screenSize.getWidth(); public static int screenHeight = (int)screenSize.getHeight(); public static Dimension realSize; //size of whole window public static Dimension size = new Dimension(screenWidth*3/4,screenHeight*3/4); //drawable area public static Dimension pixel = new Dimension(size.width/pixelSize, size.height/pixelSize); //"pixels" in drawable area public static Point mse = new Point(0, 0); public static boolean isMouseLeft = false; public static boolean isMouseMiddle = false; public static boolean isMouseRight = false; public Image screen; public static JFrame frame; public static MessageQueue mq; public static World world; public Main() { Dimension fixedSize = new Dimension(size.width-10,size.height-10); setPreferredSize(fixedSize); requestFocus(); } public static void restart() { Main viewer = new Main(); viewer.start(); } public void start() { addKeyListener(new Listening()); addMouseListener(new Listening()); addMouseMotionListener(new Listening()); addMouseWheelListener(new Listening()); // addKeyListener(new Listening2()); // addMouseListener(new Listening2()); // addMouseMotionListener(new Listening2()); // addMouseWheelListener(new Listening2()); mq = new MessageQueue(10, 10); // Sounds.loadSounds(); // Sounds.groovy.loop(); //defining objects double worldSize = 1.0; // world = new World((int)(worldSize*pixel.width), (int)(worldSize*pixel.height)); world = new World(1000, 1000); double centerX = (world.width/2); double centerY = (world.height/2); SquarePlayer player = new SquarePlayer((int)centerX, (int)centerY); world.add(player); world.cam = player; //start the main loop isRunning = true; new Thread(this).start(); requestFocus(); } public void stop() { isRunning = false; } public void tick() { // if(frame.getWidth() != realSize.width || frame.getHeight() != realSize.height) // frame.pack(); world.tick(); } public void render() { Graphics g = screen.getGraphics(); g.setColor(new Color(200, 200, 200)); g.fillRect(0, 0, pixel.width, pixel.height); world.render(g); if(isPaused) drawTextScreen(g, "Game Paused (esc to unpause)", 3); else if(isGameOver) drawTextScreen(g, "Game Over", 2); if(!isPaused) { mq.addMessage("There are "+world.things.size()+" things"); mq.addMessage("Movemode: "+world.controller.getMoveMode()); mq.addMessage(Listening.mouseStates[Listening.currMouseState]); mq.addMessage("Controller: "+Main.world.controllerEnabled); // mq.addMessage("Keys: "+Listening.keysToString()); mq.render(g); } mq.clear(); g = getGraphics(); g.drawImage(screen, 0, 0, size.width, size.height, 0, 0, pixel.width, pixel.height, null); g.dispose(); //throw it away to avoid lag from too many graphics objects } public void drawTextScreen(Graphics g, String message, int scale) { int width = pixel.width; int height = pixel.height; g.setColor(new Color(100, 100, 100, 200)); g.fillRect(0, 0, width, height); // g.setColor(Color.white); // g.fillRect(width/scale, (height/scale)+(height/(scale*4)), width/scale, height/(scale*2)); Font fontSave = g.getFont(); g.setFont(new Font("Verdana", 6, 18)); g.setColor(Color.black); g.drawString(message, width/scale, height/2); g.setFont(fontSave); } public void run() { screen = createVolatileImage(pixel.width, pixel.height); //actually use the graphics card (less lag) render(); // if(!debugMode) // JOptionPane.showMessageDialog(null, "Hexagon thing\n\nControls:\nleft click - brighter\nmiddle click - random color\nright click - darker\nspace - toggle random colors mode (seizure warning!)"); while(isRunning) { if(!isPaused && !isGameOver) tick(); //do math and any calculations render(); try { Thread.sleep(tickTime); }catch(Exception e){ } } } public static void main(String[] args) { Main main = new Main(); frame = new JFrame(); frame.add(main); frame.pack(); realSize = new Dimension(frame.getWidth(), frame.getHeight()); frame.setTitle(windowName); frame.setResizable(false); frame.setLocationRelativeTo(null); //null makes it go to the center frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); main.start(); } }
package mr.format; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.github.mustachejava.DefaultMustacheFactory; import com.github.mustachejava.Mustache; import mr.AbstractIntegrationTest; import mr.TestUtils; import mr.model.MetaData; import mr.repository.MetaDataRepository; import org.apache.commons.io.IOUtils; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.ResourceLoader; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.nio.charset.Charset; import java.time.Clock; import java.time.Instant; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.*; public class ExporterTest implements TestUtils { private static final ObjectMapper objectMapper = new ObjectMapper(); static { objectMapper.registerModule(new Jdk8Module()); objectMapper.registerModule(new JavaTimeModule()); } private Exporter subject = new Exporter(Clock.fixed(Instant.from(DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse("2017-07-14T11:15:56.857+02:00")), ZoneId.systemDefault()), new DefaultResourceLoader(), "classpath:/metadata_export"); @Test public void exportToXml() throws Exception { MetaData metaData = this.metaData(); String xml = subject.exportToXml(metaData); assertNotNull(xml); //TODO // String expected = readFile("/xml/expected_metadata_export_saml20_sp.xml"); // assertEquals(expected, xml); } @Test public void exportToMapNested() throws Exception { MetaData metaData = this.metaData(); Map<String, Object> result = subject.exportToMap(metaData, true); String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(result); String expected = readFile("/json/expected_metadata_export_saml20_sp_nested.json"); assertEquals(expected, json); } @Test public void exportToMap() throws Exception { MetaData metaData = this.metaData(); Map<String, Object> result = subject.exportToMap(metaData, false); Exporter.excludedDataFields.forEach(Map.class.cast(metaData.getData())::remove); assertEquals(result, metaData.getData()); } private MetaData metaData() throws IOException { return objectMapper.readValue(new ClassPathResource("/json/exported_metadata_saml20_sp.json").getInputStream(), MetaData.class); } @Test public void testDelMe() throws IOException { ResourceLoader resourceLoader = new DefaultResourceLoader(); String s = IOUtils.toString(resourceLoader.getResource("classpath:/metadata_export/saml20_idp.xml") .getInputStream(), Charset.defaultCharset()); Mustache mustache = new DefaultMustacheFactory().compile(new StringReader(s),"saml20_idp.xml"); StringWriter writer = new StringWriter(); mustache.execute(writer, new HashMap<>()).flush(); String xml = writer.toString(); System.out.println(xml); } }
package cn.app.controller; import com.jfinal.core.Controller; public class IndexController extends Controller{ public void index(){ System.out.println("hello"); System.out.println("hello"); this.render("/index.jsp"); } public void sayhello(){ String userName=this.getPara("userName"); String sayhello="Hello "+userName+",ok"; this.setAttr("sayhello", sayhello); this.render("/hello.jsp"); } }
package net.machinemuse.utils; import net.machinemuse.general.geometry.Colour; import net.machinemuse.general.geometry.MusePoint2D; import net.machinemuse.general.geometry.SwirlyMuseCircle; import net.machinemuse.general.gui.MuseGui; import net.machinemuse.general.gui.clickable.IClickable; import net.machinemuse.powersuits.common.Config; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.model.PositionTextureVertex; import net.minecraft.client.model.TexturedQuad; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.RenderEngine; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.entity.RenderItem; import net.minecraft.item.ItemStack; import net.minecraft.util.Icon; import net.minecraft.util.Vec3; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.util.ArrayList; import java.util.List; /** * Contains a bunch of random OpenGL-related functions, accessed statically. * * @author MachineMuse */ public abstract class MuseRenderer { protected static RenderItem renderItem; protected static SwirlyMuseCircle selectionCircle; public static String TEXTURE_MAP = "/gui/items.png"; public static final String ITEM_TEXTURE_QUILT = "/gui/items.png"; public static final String BLOCK_TEXTURE_QUILT = "/terrain.png"; public static final String ICON_PREFIX = "mmmPowersuits:"; /** * Does the rotating green circle around the selection, e.g. in GUI. * * @param xoffset * @param yoffset * @param radius */ public static void drawCircleAround(double xoffset, double yoffset, double radius) { if (selectionCircle == null) { selectionCircle = new SwirlyMuseCircle(new Colour(0.0f, 1.0f, 0.0f, 0.0f), new Colour(0.8f, 1.0f, 0.8f, 1.0f)); } selectionCircle.draw(radius, xoffset, yoffset); } /** * Creates a list of points linearly interpolated between points a and b noninclusive. * * @return A list of num points */ public static List<MusePoint2D> pointsInLine(int num, MusePoint2D a, MusePoint2D b) { List<MusePoint2D> points = new ArrayList<MusePoint2D>(); if (num < 1) { return points; } else if (num < 2) { points.add(b.minus(a).times(0.5F).plus(a)); } else { MusePoint2D step = b.minus(a).times(1.0F / (num + 1)); for (int i = 1; i < num + 1; i++) { points.add(a.plus(step.times(i))); } } return points; } /** * Returns a DoubleBuffer full of colours that are gradually interpolated * * @param c1 * @param c2 * @param numsegments * @return */ public static DoubleBuffer getColourGradient(Colour c1, Colour c2, int numsegments) { DoubleBuffer buffer = BufferUtils.createDoubleBuffer(numsegments * 4); for (double i = 0; i < numsegments; i++) { Colour c3 = c1.interpolate(c2, i / numsegments); buffer.put(c3.r); buffer.put(c3.g); buffer.put(c3.b); buffer.put(c3.a); } buffer.flip(); return buffer; } /** * Efficient algorithm for drawing circles and arcs in pure opengl! * * @param startangle Start angle in radians * @param endangle End angle in radians * @param radius Radius of the circle (used in calculating number of segments to draw as well as size of the arc) * @param xoffset Convenience parameter, added to every vertex * @param yoffset Convenience parameter, added to every vertex * @param zoffset Convenience parameter, added to every vertex * @return */ public static DoubleBuffer getArcPoints(double startangle, double endangle, double radius, double xoffset, double yoffset, double zoffset) { // roughly 8 vertices per Minecraft 'pixel' - should result in at least // 2 vertices per real pixel on the screen. int numVertices = (int) Math.ceil(Math.abs((endangle - startangle) * 16 * Math.PI)); double theta = (endangle - startangle) / numVertices; DoubleBuffer buffer = BufferUtils.createDoubleBuffer(numVertices * 3); double x = radius * Math.sin(startangle); double y = radius * Math.cos(startangle); double tf = Math.tan(theta); // precompute tangent factor: how much to // move along the tangent line each // iteration double rf = Math.cos(theta); // precompute radial factor: how much to // move back towards the origin each // iteration double tx; double ty; for (int i = 0; i < numVertices; i++) { buffer.put(x + xoffset); buffer.put(y + yoffset); buffer.put(zoffset); tx = y; // compute tangent lines ty = -x; x += tx * tf; // add tangent line * tangent factor y += ty * tf; x *= rf; y *= rf; } buffer.flip(); return buffer; } /** * 2D rendering mode on/off */ public static void on2D() { GL11.glPushAttrib(GL11.GL_ENABLE_BIT); GL11.glDisable(GL11.GL_DEPTH_TEST); GL11.glDisable(GL11.GL_CULL_FACE); GL11.glDisable(GL11.GL_LIGHTING); // attempt at fake antialiasing // GL11.glBlendFunc(GL11.GL_SRC_ALPHA_SATURATE, GL11.GL_ONE); // GL11.glColorMask(false, false, false, true); // GL11.glClearColor(0, 0, 0, 0); // GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); // GL11.glColorMask(true, true, true, true); // GL11.glHint(GL11.GL_POINT_SMOOTH, GL11.GL_NICEST); // GL11.glHint(GL11.GL_LINE_SMOOTH, GL11.GL_NICEST); // GL11.glHint(GL11.GL_POLYGON_SMOOTH, GL11.GL_NICEST); // GL11.glDepthFunc(GL11.GL_GREATER); } public static void off2D() { GL11.glPopAttrib(); } /** * Arrays on/off */ public static void arraysOnC() { GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY); GL11.glEnableClientState(GL11.GL_COLOR_ARRAY); // GL11.glEnableClientState(GL11.GL_INDEX_ARRAY); } public static void arraysOnT() { GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY); GL11.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY); } public static void arraysOff() { GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY); GL11.glDisableClientState(GL11.GL_COLOR_ARRAY); GL11.glDisableClientState(GL11.GL_TEXTURE_COORD_ARRAY); } /** * Call before doing any pure geometry (ie. with colours rather than textures). */ public static void texturelessOn() { GL11.glDisable(GL11.GL_TEXTURE_2D); } /** * Call after doing pure geometry (ie. with colours) to go back to the texture mode (default). */ public static void texturelessOff() { GL11.glEnable(GL11.GL_TEXTURE_2D); } /** * Call before doing anything with alpha blending */ public static void blendingOn() { GL11.glPushAttrib(GL11.GL_COLOR_BUFFER_BIT); GL11.glPushAttrib(GL11.GL_LIGHTING_BIT); if (Minecraft.isFancyGraphicsEnabled()) { GL11.glShadeModel(GL11.GL_SMOOTH); // GL11.glEnable(GL11.GL_LINE_SMOOTH); // GL11.glEnable(GL11.GL_POLYGON_SMOOTH); GL11.glEnable(GL11.GL_BLEND); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); } } /** * Call after doing anything with alpha blending */ public static void blendingOff() { GL11.glPopAttrib(); GL11.glPopAttrib(); // GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); } /** * Makes the appropriate openGL calls and draws an item and overlay using the default icon */ public static void drawItemAt(double x, double y, ItemStack item) { on2D(); getRenderItem().renderItemAndEffectIntoGUI(getFontRenderer(), getRenderEngine(), item, (int) x, (int) y); getRenderItem().renderItemOverlayIntoGUI(getFontRenderer(), getRenderEngine(), item, (int) x, (int) y); off2D(); } /** * Draws a MuseIcon * * @param x * @param y * @param icon * @param colour */ public static void drawIconAt(double x, double y, Icon icon, Colour colour) { drawIconPartial(x, y, icon, colour, 0, 0, 16, 16); } /** * Draws a MuseIcon * * @param x * @param y * @param icon * @param colour */ public static void drawIconPartial(double x, double y, Icon icon, Colour colour, double left, double top, double right, double bottom) { if (icon == null) { return; } GL11.glPushMatrix(); on2D(); blendingOn(); if (colour != null) { colour.doGL(); } getRenderEngine().bindTexture(TEXTURE_MAP); Tessellator tess = Tessellator.instance; tess.startDrawingQuads(); float u1 = icon.getMinU(); float v1 = icon.getMinV(); float u2 = icon.getMaxU(); float v2 = icon.getMaxV(); double xoffset1 = left * (u2 - u1) / 16.0f; double yoffset1 = top * (v2 - v1) / 16.0f; double xoffset2 = right * (u2 - u1) / 16.0f; double yoffset2 = bottom * (v2 - v1) / 16.0f; tess.addVertexWithUV(x + left, y + top, 0, u1 + xoffset1, v1 + yoffset1); tess.addVertexWithUV(x + left, y + bottom, 0, u1 + xoffset1, v1 + yoffset2); tess.addVertexWithUV(x + right, y + bottom, 0, u1 + xoffset2, v1 + yoffset2); tess.addVertexWithUV(x + right, y + top, 0, u1 + xoffset2, v1 + yoffset1); tess.draw(); MuseRenderer.blendingOff(); off2D(); GL11.glPopMatrix(); } /** * Switches to relative coordinate frame (where -1,-1 is top left of the working area, and 1,1 is the bottom right) */ public static void relativeCoords(MuseGui gui) { GL11.glPushMatrix(); GL11.glTranslatef(gui.width / 2, gui.height / 2, 0); GL11.glScalef(gui.getxSize(), gui.getySize(), 0); } /** * Does the necessary openGL calls and calls the Minecraft font renderer to draw a string at the specified coords */ public static void drawString(String s, double x, double y) { RenderHelper.disableStandardItemLighting(); getFontRenderer().drawStringWithShadow(s, (int) x, (int) y, new Colour(1, 1, 1, 1).getInt()); } /** * Does the necessary openGL calls and calls the Minecraft font renderer to draw a string such that the xcoord is halfway through the string */ public static void drawCenteredString(String s, double x, double y) { double xradius = getFontRenderer().getStringWidth(s) / 2; drawString(s, x - xradius, y); } /** * Does the necessary openGL calls and calls the Minecraft font renderer to draw a string such that the xcoord is halfway through the string */ public static void drawRightAlignedString(String s, double x, double y) { drawString(s, x - getFontRenderer().getStringWidth(s), y); } /** * Draws a rectangular prism (cube or otherwise orthogonal) */ public static void drawRectPrism(double x, double d, double e, double f, double z, double g, float texturex, float texturey, float texturex2, float texturey2) { arraysOnT(); texturelessOff(); Vec3[] points = {Vec3.createVectorHelper(x, e, z), Vec3.createVectorHelper(d, e, z), Vec3.createVectorHelper(x, f, z), Vec3.createVectorHelper(d, f, z), Vec3.createVectorHelper(x, e, g), Vec3.createVectorHelper(d, e, g), Vec3.createVectorHelper(x, f, g), Vec3.createVectorHelper(d, f, g)}; PositionTextureVertex[] va1 = {new PositionTextureVertex(points[0], texturex, texturey2), new PositionTextureVertex(points[2], texturex2, texturey2), new PositionTextureVertex(points[3], texturex2, texturey), new PositionTextureVertex(points[1], texturex, texturey) }; new TexturedQuad(va1).draw(Tessellator.instance, 1.0F); PositionTextureVertex[] va2 = {new PositionTextureVertex(points[2], texturex, texturey2), new PositionTextureVertex(points[6], texturex2, texturey2), new PositionTextureVertex(points[7], texturex2, texturey), new PositionTextureVertex(points[3], texturex, texturey) }; new TexturedQuad(va2).draw(Tessellator.instance, 1.0F); PositionTextureVertex[] va3 = {new PositionTextureVertex(points[6], texturex, texturey2), new PositionTextureVertex(points[4], texturex2, texturey2), new PositionTextureVertex(points[5], texturex2, texturey), new PositionTextureVertex(points[7], texturex, texturey) }; new TexturedQuad(va3).draw(Tessellator.instance, 1.0F); PositionTextureVertex[] va4 = {new PositionTextureVertex(points[4], texturex, texturey2), new PositionTextureVertex(points[0], texturex2, texturey2), new PositionTextureVertex(points[1], texturex2, texturey), new PositionTextureVertex(points[5], texturex, texturey) }; new TexturedQuad(va4).draw(Tessellator.instance, 1.0F); PositionTextureVertex[] va5 = {new PositionTextureVertex(points[1], texturex, texturey2), new PositionTextureVertex(points[3], texturex2, texturey2), new PositionTextureVertex(points[7], texturex2, texturey), new PositionTextureVertex(points[5], texturex, texturey) }; new TexturedQuad(va5).draw(Tessellator.instance, 1.0F); PositionTextureVertex[] va6 = {new PositionTextureVertex(points[0], texturex, texturey2), new PositionTextureVertex(points[4], texturex2, texturey2), new PositionTextureVertex(points[6], texturex2, texturey), new PositionTextureVertex(points[2], texturex, texturey) }; new TexturedQuad(va6).draw(Tessellator.instance, 1.0F); // int[] indices = { // 0, 3, 1, // 0, 2, 3, // 2, 6, 7, // 2, 7, 3, // 6, 4, 5, // 6, 5, 7, // 4, 0, 1, // 4, 1, 5, // 1, 3, 7, // 1, 7, 5, // 0, 6, 2, // 0, 4, 6 // drawTriangles3DT(points, textures, indices); texturelessOff(); arraysOff(); } public static void drawStringsJustified(List<String> words, double x1, double x2, double y) { int totalwidth = 0; for (String word : words) { totalwidth += getFontRenderer().getStringWidth(word); } double spacing = (x2 - x1 - totalwidth) / (words.size() - 1); double currentwidth = 0; for (String word : words) { MuseRenderer.drawString(word, x1 + currentwidth, y); currentwidth += getFontRenderer().getStringWidth(word) + spacing; } } private static float lightmapLastX; private static float lightmapLastY; public static void glowOn() { GL11.glPushAttrib(GL11.GL_LIGHTING_BIT); lightmapLastX = OpenGlHelper.lastBrightnessX; lightmapLastY = OpenGlHelper.lastBrightnessY; RenderHelper.disableStandardItemLighting(); OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, 240.0F, 240.0F); } public static void glowOff() { OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, lightmapLastX, lightmapLastY); GL11.glPopAttrib(); } /** * Singleton pattern for FontRenderer */ public static FontRenderer getFontRenderer() { return Minecraft.getMinecraft().fontRenderer; } /** * Singleton pattern for RenderEngine */ public static RenderEngine getRenderEngine() { return Minecraft.getMinecraft().renderEngine; } /** * Singleton pattern for the RenderItem * * @return the static renderItem instance */ public static RenderItem getRenderItem() { if (renderItem == null) { renderItem = new RenderItem(); } return renderItem; } public static void drawLineBetween(IClickable firstClickable, IClickable secondClickable, Colour gradientColour) { long varia = System.currentTimeMillis() % 2000 - 1000; // ranges from // -1000 to 1000 // and around, // period = 2 // seconds double gradientRatio = 1.0 - ((varia + 1000) % 1000) / 1000.0; MusePoint2D midpoint = (firstClickable.getPosition().minus(secondClickable.getPosition()).times(Math.abs(varia / 1000.0)) .plus(secondClickable.getPosition())); MusePoint2D firstpoint, secondpoint; if (varia < 0) { firstpoint = secondClickable.getPosition(); secondpoint = firstClickable.getPosition(); } else { firstpoint = firstClickable.getPosition(); secondpoint = secondClickable.getPosition(); } GL11.glPushAttrib(GL11.GL_ENABLE_BIT); GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glBegin(GL11.GL_LINES); gradientColour.withAlpha(gradientRatio).doGL(); GL11.glVertex3d(midpoint.x(), midpoint.y(), 1); gradientColour.withAlpha(0.0).doGL(); GL11.glVertex3d(firstpoint.x(), firstpoint.y(), 1); gradientColour.withAlpha(gradientRatio).doGL(); GL11.glVertex3d(secondpoint.x(), secondpoint.y(), 1); Colour.WHITE.withAlpha(1.0).doGL(); GL11.glVertex3d(midpoint.x(), midpoint.y(), 1); GL11.glEnd(); GL11.glPopAttrib(); } public static void drawLightning(double x1, double y1, double z1, double x2, double y2, double z2, Colour colour) { drawLightningTextured(x1, y1, z1, x2, y2, z2, colour); } public static void drawMPDLightning(double x1, double y1, double z1, double x2, double y2, double z2, Colour colour, double displacement, double detail) { if (displacement < detail) { colour.doGL(); GL11.glBegin(GL11.GL_LINES); GL11.glVertex3d(x1, y1, z1); GL11.glVertex3d(x2, y2, z2); GL11.glEnd(); } else { double mid_x = (x1 + x2) / 2.0; double mid_y = (y1 + y2) / 2.0; double mid_z = (z1 + z2) / 2.0; mid_x += (Math.random() - 0.5) * displacement; mid_y += (Math.random() - 0.5) * displacement; mid_z += (Math.random() - 0.5) * displacement; drawMPDLightning(x1, y1, z1, mid_x, mid_y, mid_z, colour, displacement / 2, detail); drawMPDLightning(mid_x, mid_y, mid_z, x2, y2, z2, colour, displacement / 2, detail); } } public static void drawLightningTextured(double x1, double y1, double z1, double x2, double y2, double z2, Colour colour) { double tx = x2 - x1, ty = y2 - y1, tz = z2 - z1; double ax = 0, ay = 0, az = 0; double bx = 0, by = 0, bz = 0; double cx = 0, cy = 0, cz = 0; double jagfactor = 0.3; on2D(); GL11.glEnable(GL11.GL_DEPTH_TEST); getRenderEngine().bindTexture(Config.LIGHTNING_TEXTURE); blendingOn(); colour.doGL(); GL11.glBegin(GL11.GL_QUADS); while (Math.abs(cx) < Math.abs(tx) && Math.abs(cy) < Math.abs(ty) && Math.abs(cz) < Math.abs(tz)) { ax = x1 + cx; ay = y1 + cy; az = z1 + cz; cx += Math.random() * tx * jagfactor - 0.1 * tx; cy += Math.random() * ty * jagfactor - 0.1 * ty; cz += Math.random() * tz * jagfactor - 0.1 * tz; bx = x1 + cx; by = y1 + cy; bz = z1 + cz; int index = (int) Math.random() * 50; drawLightningBetweenPointsFast(ax, ay, az, bx, by, bz, index); } GL11.glEnd(); blendingOff(); off2D(); } public static void drawLightningBetweenPoints(double x1, double y1, double z1, double x2, double y2, double z2, int index) { getRenderEngine().bindTexture(Config.LIGHTNING_TEXTURE); double u1 = index / 50.0; double u2 = u1 + 0.02; double px = (y1 - y2) * 0.125; double py = (x2 - x1) * 0.125; GL11.glTexCoord2d(u1, 0); GL11.glVertex3d(x1 - px, y1 - py, z1); GL11.glTexCoord2d(u2, 0); GL11.glVertex3d(x1 + px, y1 + py, z1); GL11.glTexCoord2d(u1, 1); GL11.glVertex3d(x2 - px, y2 - py, z2); GL11.glTexCoord2d(u2, 1); GL11.glVertex3d(x2 + px, y2 + py, z2); } public static void drawLightningBetweenPointsFast(double x1, double y1, double z1, double x2, double y2, double z2, int index) { double u1 = index / 50.0; double u2 = u1 + 0.02; double px = (y1 - y2) * 0.125; double py = (x2 - x1) * 0.125; GL11.glTexCoord2d(u1, 0); GL11.glVertex3d(x1 - px, y1 - py, z1); GL11.glTexCoord2d(u2, 0); GL11.glVertex3d(x1 + px, y1 + py, z1); GL11.glTexCoord2d(u1, 1); GL11.glVertex3d(x2 - px, y2 - py, z2); GL11.glTexCoord2d(u2, 1); GL11.glVertex3d(x2 + px, y2 + py, z2); } public static void drawLightningLines(double x1, double y1, double z1, double x2, double y2, double z2, Colour colour) { double tx = x2 - x1, ty = y2 - y1, tz = z2 - z1, cx = 0, cy = 0, cz = 0; double jagfactor = 0.3; texturelessOn(); blendingOn(); on2D(); GL11.glBegin(GL11.GL_LINE_STRIP); while (Math.abs(cx) < Math.abs(tx) && Math.abs(cy) < Math.abs(ty) && Math.abs(cz) < Math.abs(tz)) { colour.doGL(); // GL11.glLineWidth(1); cx += Math.random() * tx * jagfactor - 0.1 * tx; cy += Math.random() * ty * jagfactor - 0.1 * ty; cz += Math.random() * tz * jagfactor - 0.1 * tz; GL11.glVertex3d(x1 + cx, y1 + cy, z1 + cz); // GL11.glLineWidth(3); // colour.withAlpha(0.5).doGL(); // GL11.glVertex3d(ox, oy, oz); // GL11.glLineWidth(5); // colour.withAlpha(0.1).doGL(); // GL11.glVertex3d(x1 + cx, y1 + cy, z1 + cz); } GL11.glEnd(); off2D(); blendingOff(); texturelessOff(); } private static float pythag(float x, float y, float z) { return (float) Math.sqrt(x * x + y * y + z * z); } public static void unRotate() { FloatBuffer matrix = BufferUtils.createFloatBuffer(16); GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, matrix); float scalex = pythag(matrix.get(0), matrix.get(1), matrix.get(2)); float scaley = pythag(matrix.get(4), matrix.get(5), matrix.get(6)); float scalez = pythag(matrix.get(8), matrix.get(9), matrix.get(10)); for (int i = 0; i < 12; i++) { matrix.put(i, 0); } matrix.put(0, scalex); matrix.put(5, scaley); matrix.put(10, scalez); GL11.glLoadMatrix(matrix); } public static void drawCheckmark(double x, double y, Colour colour) { GL11.glPushMatrix(); on2D(); blendingOn(); if (colour != null) { colour.doGL(); } getRenderEngine().bindTexture("/mods/mmmPowersuits/textures/gui/checkmark.png"); Tessellator tess = Tessellator.instance; tess.startDrawingQuads(); tess.addVertexWithUV(x, y, 0.0F, 0.0F, 0.0F); tess.addVertexWithUV(x, y + 16, 0.0F, 0.0F, 1.0F); tess.addVertexWithUV(x + 16, y + 16, 0.0F, 1.0F, 1.0F); tess.addVertexWithUV(x + 16, y, 0.0F, 1.0F, 0.0F); tess.draw(); MuseRenderer.blendingOff(); off2D(); GL11.glPopMatrix(); } }
package org.atlasapi.content; import com.google.api.client.repackaged.com.google.common.base.Strings; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.metabroadcast.common.ids.NumberToShortStringCodec; import com.metabroadcast.common.ids.SubstitutionTableNumberCodec; import org.atlasapi.entity.Id; import org.atlasapi.query.common.Query; import org.elasticsearch.common.lang3.StringUtils; import java.util.List; import java.util.Map; import java.util.Optional; /*** This is more or less a hack to allow parsing simple query params off of a HTTP request param map, found on a {@link Query}. It should be removed and replaced once a refactor of Deer's query parsing allows this sort of thing to be done easier and in a more general fashion. */ public class IndexQueryParser { private static final String NOT_OPERATOR = "!"; private final NumberToShortStringCodec codec = SubstitutionTableNumberCodec.lowerCaseOnly(); public IndexQueryParams parse(Query<?> query) { return new IndexQueryParams( titleQueryFrom(query), orderingFrom(query), regionIdFrom(query), broadcastWeightingFrom(query), titleWeightingFrom(query), topicIdsFrom(query), availabilityFilterFrom(query), brandIdFrom(query), actionableFilterParamsFrom(query), seriesIdFrom(query) ); } private Optional<Id> seriesIdFrom(Query<?> query) { String seriesId = query.getContext().getRequest().getParameter("series.id"); if (!Strings.isNullOrEmpty(seriesId)) { return Optional.of(Id.valueOf(codec.decode(seriesId))); } return Optional.empty(); } @VisibleForTesting public Optional<Map<String, String>> actionableFilterParamsFrom(Query<?> query) { String[] params = (String[]) query.getContext().getRequest().getParameterMap().get("actionableFilterParameters"); if (params == null || params.length == 0) { return Optional.empty(); } String filters = params[0]; List<String> splitFilters = Splitter.on(",").splitToList(filters); Splitter commaSplitter = Splitter.on(":"); ImmutableMap.Builder<String, String> result = ImmutableMap.builder(); for (String filter : splitFilters) { List<String> keyAndValue = commaSplitter.splitToList(filter); result.put(keyAndValue.get(0), keyAndValue.get(1)); } return Optional.of(result.build()); } private Optional<Id> brandIdFrom(Query<?> query) { String episodeBrandId = query.getContext().getRequest().getParameter("episode.brand.id"); if (!Strings.isNullOrEmpty(episodeBrandId)) { return Optional.of(Id.valueOf(codec.decode(episodeBrandId))); } String brandId = query.getContext().getRequest().getParameter("brand.id"); if (!Strings.isNullOrEmpty(brandId)) { return Optional.of(Id.valueOf(codec.decode(brandId))); } return Optional.empty(); } private Boolean availabilityFilterFrom(Query<?> query) { String available = query.getContext().getRequest().getParameter("available"); String brandSeriesAvailable = query.getContext().getRequest().getParameter("brand.series.available"); if (!Strings.isNullOrEmpty(available) || !Strings.isNullOrEmpty(brandSeriesAvailable)) { return true; } return false; } private Optional<List<List<InclusionExclusionId>>> topicIdsFrom(Query<?> query) { String topicIds = query.getContext().getRequest().getParameter("tags.topic.id"); if (Strings.isNullOrEmpty(topicIds)) { return Optional.empty(); } ImmutableList.Builder<List<InclusionExclusionId>> builder = ImmutableList.builder(); Splitter commaSplitter = Splitter.on(","); Splitter carretSplitter = Splitter.on("^"); for (String idCsv : commaSplitter.splitToList(topicIds)) { builder.add(Lists.transform(carretSplitter.splitToList(idCsv), this::parseInclusiveExclusiveId)); } return Optional.of(builder.build()); } private InclusionExclusionId parseInclusiveExclusiveId(String id) { if (StringUtils.startsWith(id, NOT_OPERATOR)) { return InclusionExclusionId.valueOf( Id.valueOf(codec.decode(StringUtils.removeStart(id, NOT_OPERATOR))), Boolean.FALSE ); } return InclusionExclusionId.valueOf(Id.valueOf(codec.decode(id)), Boolean.TRUE); } private Optional<Float> broadcastWeightingFrom(Query<?> query) { String broadcastWeight = query.getContext().getRequest().getParameter("broadcastWeight"); if (Strings.isNullOrEmpty(broadcastWeight)) { return Optional.empty(); } return Optional.of(Float.parseFloat(broadcastWeight)); } private Optional<Float> titleWeightingFrom(Query<?> query) { String titleWeight = query.getContext().getRequest().getParameter("titleWeight"); if (Strings.isNullOrEmpty(titleWeight)) { return Optional.empty(); } return Optional.of(Float.parseFloat(titleWeight)); } private Optional<Id> regionIdFrom(Query<?> query) { String stringRegionId = query.getContext().getRequest().getParameter("region"); if (Strings.isNullOrEmpty(stringRegionId)) { return Optional.empty(); } return Optional.of(Id.valueOf(codec.decode(stringRegionId))); } private Optional<QueryOrdering> orderingFrom(Query<?> query) { Map params = query.getContext().getRequest().getParameterMap(); if (!params.containsKey("order_by")) { return Optional.empty(); } String[] orderByVals = ((String[]) params.get("order_by")); if (orderByVals.length > 1) { throw new IllegalArgumentException("Cannot specify multiple order_by values"); } if (orderByVals.length == 0) { return Optional.empty(); } return Optional.ofNullable(QueryOrdering.fromOrderBy(orderByVals[0])); } private Optional<FuzzyQueryParams> titleQueryFrom(Query<?> query) { Optional<String> fuzzySearchString = getFuzzySearchString(query); if (!fuzzySearchString.isPresent()) { return Optional.empty(); } return Optional.ofNullable(new FuzzyQueryParams(fuzzySearchString.get(), getTitleBoostFrom(query))); } private Optional<Float> getTitleBoostFrom(Query<?> query) { Map params = query.getContext().getRequest().getParameterMap(); Object param = params.get("title_boost"); if (param == null) { return Optional.empty(); } String[] titleBoost = (String[]) param; if (titleBoost.length > 1) { throw new IllegalArgumentException("Title boost param (titleBoost) has been specified more than once"); } if (titleBoost.length == 0) { return Optional.empty(); } return Optional.ofNullable(Float.parseFloat(titleBoost[0])); } private Optional<String> getFuzzySearchString(Query<?> query) { Map params = query.getContext().getRequest().getParameterMap(); if (!params.containsKey("q")) { return Optional.empty(); } String[] searchParam = ((String[]) params.get("q")); if (searchParam.length > 1) { throw new IllegalArgumentException("Search param (q) has been specified more than once"); } if (searchParam[0] == null) { return Optional.empty(); } return Optional.of(searchParam[0]); } }
package at.fhj.swd14.pse.user; import java.io.Serializable; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; import at.fhj.swd14.pse.comment.Comment; import at.fhj.swd14.pse.community.Community; import at.fhj.swd14.pse.message.Message; @Entity @Table(name = "user") public class User implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; @Column private String username; @Column private String password; @Column private String salt; @ManyToMany private List<Community> communities; @ManyToMany(mappedBy = "users") private List<Comment> comments; @ManyToMany(mappedBy = "users") private List<Message> messages; public User(Long id) { this.id = id; } public User() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getMail() { return username; } public void setMail(String mail) { this.username = mail; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } public void setComments(List<Comment> comments) { this.comments = comments; } public List<Comment> getComments() { return this.comments; } public void setMessages(List<Message> messages) { this.messages = messages; } public List<Message> getMessages() { return this.messages; } @Override public String toString() { return "User{" + "id=" + id + ", mail='" + username + '\'' + '}'; } }
package org.intermine.bio.util; import java.io.File; import java.io.FileWriter; import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Iterator; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.query.Results; import org.intermine.objectstore.query.ResultsRow; import org.intermine.objectstore.query.iql.IqlQuery; /** * Create file to make site map * * @author Julie Sullivan */ public class CreateSiteMapLinkIns { // TODO get this from config file private static final String LOC = "http: private static final String SETOPEN = "<urlset xmlns=\"http: private static final String HEAD = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; private static final String SETCLOSE = "</urlset>"; private static final String ENDL = System.getProperty("line.separator"); private static final String EXT = ".xml"; private static String date; private static final String PREFIX = "http: private static final String WEIGHT = "0.5"; private static final String STARTWEIGHT = "0.8"; /** * Create sitemap * NOTE: Sitemaps can't contain more than 50000 entries or be over 10MB. See sitemap.org. * @param os ObjectStore to find Genes in * @param outputFile file to write to * @throws Exception if anything goes wrong */ public static void createSiteMap(ObjectStore os, String outputFile) throws Exception { Format formatter = new SimpleDateFormat("yyyy-MM-dd"); date = formatter.format(new Date()); String newFileName = outputFile + EXT; FileWriter writer = startFile(new File(newFileName)); writeStartPages(writer); closeFile(writer); String[] bioentity = {"gene", "protein"}; String[] ids = {"180454", "7227", "7237"}; // Only create new files if they don't already exist, we have no input file // to compare dates to so must rely on output directory being cleaned to // force creation of new sitemaps. for (String e : bioentity) { for (String id : ids) { File newFile = new File(outputFile + id + e + EXT); if (!newFile.exists()) { writer = startFile(newFile); Iterator i = getResults(os, e, id); while (i.hasNext()) { ResultsRow r = (ResultsRow) i.next(); String identifier = (String) r.get(0); writer.write(getURL(LOC + identifier + "&amp;class=" + e, WEIGHT)); } closeFile(writer); } } } } private static FileWriter startFile(File f) throws Exception { FileWriter writer = new FileWriter(f); writer.write(getHeader()); return writer; } private static void closeFile(FileWriter writer) throws Exception { writer.write(getFooter()); writer.flush(); writer.close(); } private static Iterator getResults(ObjectStore os, String whichQuery, String taxonId) { String query = null; if (whichQuery.equals("gene")) { query = "SELECT DISTINCT a1_.identifier as a3_ " + "FROM org.flymine.model.genomic.Gene AS a1_, " + "org.flymine.model.genomic.Organism AS a2_ WHERE " + "a2_.taxonId = " + taxonId + " " + "AND a1_.organism CONTAINS a2_ " + "AND a1_.identifier != \'\') " + "ORDER BY a1_.identifier\n"; } else { query = "SELECT DISTINCT a1_.identifier as a3_ " + "FROM org.flymine.model.genomic.Protein AS a1_, " + "org.flymine.model.genomic.Organism AS a2_ WHERE " + "a2_.taxonId = " + taxonId + " " + "AND a1_.organism CONTAINS a2_ " + "AND a1_.identifier != \'\') " + "ORDER BY a1_.identifier\n"; } IqlQuery q = new IqlQuery(query, os.getModel().getPackageName()); Results r = os.execute(q.toQuery()); r.setBatchSize(100000); Iterator i = r.iterator(); return i; } private static String getHeader() { return HEAD + ENDL + SETOPEN + ENDL; } private static String getFooter() { return SETCLOSE + ENDL; } private static String getURL(String identifier, String weight) { StringBuffer s = new StringBuffer("<url>" + ENDL); s.append("<loc>"); s.append(identifier); s.append("</loc>" + ENDL); s.append("<lastmod>"); s.append(date); s.append("</lastmod>" + ENDL); s.append("<priority>"); s.append(weight); s.append("</priority>" + ENDL); s.append("</url>" + ENDL); return s.toString(); } private static void writeStartPages(FileWriter writer) throws Exception { // TODO get these from config file String[] pages = {"begin.do", "templates.do", "bag.do?subtab=view", "dataCategories.do"}; for (String s : pages) { writer.write(getURL(PREFIX + s, STARTWEIGHT)); } } }
package info.izumin.android.bletia.action; import org.jdeferred.Deferred; import org.jdeferred.impl.DeferredObject; import info.izumin.android.bletia.BletiaException; public abstract class Action<T, I> extends info.izumin.android.bletia.core.action.Action<I> { private final Deferred<T, BletiaException, Void> mDeferred; public Action(I identity) { super(identity); mDeferred = new DeferredObject<>(); } public Deferred<T, BletiaException, Void> getDeferred() { return mDeferred; } }
package net.sf.jaer.eventio; import ch.systemsx.cisd.hdf5.HDF5DataClass; import ch.systemsx.cisd.hdf5.HDF5DataSetInformation; import ch.systemsx.cisd.hdf5.HDF5DataTypeInformation; import ch.systemsx.cisd.hdf5.HDF5FactoryProvider; import ch.systemsx.cisd.hdf5.IHDF5Reader; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.nio.LongBuffer; import java.nio.ShortBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collection; import java.util.List; import java.util.logging.Logger; import ncsa.hdf.hdf5lib.H5; import ncsa.hdf.hdf5lib.HDF5Constants; import net.sf.jaer.chip.AEChip; import ncsa.hdf.hdf5lib.HDFArray; /** * Reads HDF5 AER data files * * @author Tobi Delbruck */ public class Hdf5AedatFileInputReader { protected static Logger log=Logger.getLogger("Hdf5AedatFileInputReader"); private IHDF5Reader reader=null; public Hdf5AedatFileInputReader(File f, AEChip chip) throws IOException { int file_id = -1; int dataset_id = -1; int space = -1; int ndims = 0; long dims[] = new long[2]; long maxDims[] = new long[2]; int memtype = -1; // Open file using the default properties. try { file_id = H5.H5Fopen(f.getName(), HDF5Constants.H5F_ACC_RDWR, HDF5Constants.H5P_DEFAULT); // Open dataset using the default properties. if (file_id >= 0) { dataset_id = H5.H5Dopen(file_id, "data", HDF5Constants.H5P_DEFAULT); } if (dataset_id >= 0) { space = H5.H5Dget_space(dataset_id); ndims = H5.H5Sget_simple_extent_dims(space, dims, maxDims); } // Create the memory datatype. memtype = H5.H5Tvlen_create(HDF5Constants.H5T_NATIVE_INT8); } catch (Exception e) { e.printStackTrace(); } // Allocate array of pointers to two-dimensional arrays (the // elements of the dataset. String is a variable length array of char. int dataArrayLength = (int) dims[0] * (int) dims[1]; final String[] dataRead = new String[dataArrayLength]; try { if (space >= 0) H5.H5Tdetect_class(memtype, HDF5Constants.H5T_STRING); H5.H5DreadVL(dataset_id, memtype, HDF5Constants.H5S_ALL, HDF5Constants.H5S_ALL, HDF5Constants.H5P_DEFAULT, dataRead); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args){ try { Hdf5AedatFileInputReader r=new Hdf5AedatFileInputReader(new File("rec1498945830_result.hdf5"),null); } catch (IOException ex) { log.warning("caught "+ex.toString()); } } }
package net.sf.jaer.util.avioutput; import com.jogamp.common.nio.Buffers; import com.jogamp.opengl.GL; import com.jogamp.opengl.GL2; import com.jogamp.opengl.GLAutoDrawable; import com.jogamp.opengl.awt.GLCanvas; import java.awt.Desktop; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Date; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileFilter; import net.sf.jaer.Description; import net.sf.jaer.DevelopmentStatus; import net.sf.jaer.chip.AEChip; import net.sf.jaer.event.EventPacket; import net.sf.jaer.eventio.AEInputStream; import static net.sf.jaer.eventprocessing.EventFilter.log; import net.sf.jaer.eventprocessing.EventFilter2D; import net.sf.jaer.eventprocessing.EventFilter2DMouseAdaptor; import net.sf.jaer.graphics.AEViewer; import net.sf.jaer.graphics.FrameAnnotater; /** * Base class for EventFilters that write out AVI files from jAER * * @author Tobi */ @Description("Base class for EventFilters that write out AVI files from jAER") @DevelopmentStatus(DevelopmentStatus.Status.Stable) public class AbstractAviWriter extends EventFilter2DMouseAdaptor implements FrameAnnotater, PropertyChangeListener { protected final int LOG_EVERY_THIS_MANY_FRAMES = 100; // for logging concole messages protected AVIOutputStream aviOutputStream = null; protected static String DEFAULT_FILENAME = "jAER.avi"; protected String lastFileName = getString("lastFileName", DEFAULT_FILENAME); protected int framesWritten = 0; protected boolean writeTimecodeFile = getBoolean("writeTimecodeFile", true); protected static final String TIMECODE_SUFFIX = "-timecode.txt"; protected File timecodeFile = null; protected FileWriter timecodeWriter = null; protected boolean closeOnRewind = getBoolean("closeOnRewind", true); private boolean chipPropertyChangeListenerAdded = false; protected AVIOutputStream.VideoFormat format = AVIOutputStream.VideoFormat.valueOf(getString("format", AVIOutputStream.VideoFormat.RAW.toString())); protected int maxFrames = getInt("maxFrames", 0); protected float compressionQuality = getFloat("compressionQuality", 0.9f); private String[] additionalComments = null; private int frameRate=getInt("frameRate",30); private boolean saveFramesAsIndividualImageFiles=getBoolean("saveFramesAsIndividualImageFiles",false); private boolean writeOnlyWhenMousePressed=getBoolean("writeOnlyWhenMousePressed",false); protected volatile boolean writeEnabled=true; public AbstractAviWriter(AEChip chip) { super(chip); setPropertyTooltip("startRecordingAndSaveAVIAs", "Opens the output file and starts writing to it. The AVI file is in RAW format with pixel values 0-255 coming from ApsFrameExtractor displayed frames, which are offset and scaled by it."); setPropertyTooltip("closeFile", "Closes the output file if it is open."); setPropertyTooltip("writeTimecodeFile", "writes a file alongside AVI file (with suffix " + TIMECODE_SUFFIX + ") that maps from AVI frame to AER timestamp for that frame (the frame end timestamp)"); setPropertyTooltip("closeOnRewind", "closes recording on rewind event, to allow unattended operation"); setPropertyTooltip("resizeWindowTo16To9Format", "resizes AEViewer window to 19:9 format"); setPropertyTooltip("resizeWindowTo4To3Format", "resizes AEViewer window to 4:3 format"); setPropertyTooltip("format", "video file is writtent to this output format (note that RLE will throw exception because OpenGL frames are not 4 or 8 bit images)"); setPropertyTooltip("maxFrames", "file is automatically closed after this many frames have been written; set to 0 to disable"); setPropertyTooltip("framesWritten", "READONLY, shows number of frames written"); setPropertyTooltip("compressionQuality", "In PNG or JPG format, sets compression quality; 0 is lowest quality and 1 is highest, 0.9 is default value"); setPropertyTooltip("showFolderInDesktop", "Opens the folder containging the last-written AVI file"); setPropertyTooltip("frameRate", "Specifies frame rate of AVI file."); setPropertyTooltip("saveFramesAsIndividualImageFiles", "If selected, then the frames are saved as individual image files in the selected folder"); setPropertyTooltip("writeOnlyWhenMousePressed", "If selected, then the frames are are saved only when the mouse is pressed in the AEViewer window"); setPropertyTooltip("writeEnabled", "Selects if writing frames is enabled. Use this to temporarily disable output, or in conjunction with writeOnlyWhenMousePressed"); chip.getSupport().addPropertyChangeListener(this); } @Override synchronized public EventPacket<?> filterPacket(EventPacket<?> in) { if (!chipPropertyChangeListenerAdded) { if (chip.getAeViewer() != null) { chip.getAeViewer().addPropertyChangeListener(AEInputStream.EVENT_REWIND, this); chipPropertyChangeListenerAdded = true; } } return in; } @Override public void resetFilter() { } @Override public void initFilter() { } public void doResizeWindowTo4To3Format() { resizeWindowTo(640, 480); } public void doResizeWindowTo16To9Format() { resizeWindowTo(640, 360); } private void resizeWindowTo(int w, int h) { if(aviOutputStream!=null){ log.warning("resizing disabled during recording to prevent AVI corruption"); return; } AEViewer v = chip.getAeViewer(); if (v == null) { log.warning("No AEViewer"); return; } GLCanvas c = (GLCanvas) (chip.getCanvas().getCanvas()); if (c == null) { log.warning("No Canvas to resize"); return; } int ww = c.getWidth(), hh = c.getHeight(); int vw=v.getWidth(), vh=v.getHeight(); v.setSize(w + (vw-ww), h + (vh-hh)); v.revalidate(); int ww2 = c.getWidth(), hh2 = c.getHeight(); log.info(String.format("Canvas resized from %d x %d to %d x %d pixels", ww, hh, ww2, hh2)); } public void doShowFolderInDesktop() { if (!Desktop.isDesktopSupported()) { log.warning("Sorry, desktop operations are not supported"); return; } try { Desktop desktop = Desktop.getDesktop(); File f = new File(lastFileName); if (f.exists()) { desktop.open(f.getParentFile()); } } catch (Exception e) { log.warning(e.toString()); } } synchronized public void doStartRecordingAndSaveAVIAs() { if (aviOutputStream != null) { JOptionPane.showMessageDialog(null, "AVI output stream is already opened"); return; } JFileChooser c = new JFileChooser(lastFileName); c.setFileFilter(new FileFilter() { @Override public boolean accept(File f) { return f.isDirectory() || f.getName().toLowerCase().endsWith(".avi"); } @Override public String getDescription() { return "AVI (Audio Video Interleave) Microsoft video file"; } }); c.setSelectedFile(new File(lastFileName)); int ret = c.showSaveDialog(null); if (ret != JFileChooser.APPROVE_OPTION) { return; } if (!c.getSelectedFile().getName().toLowerCase().endsWith(".avi")) { String newName = c.getSelectedFile().toString() + ".avi"; c.setSelectedFile(new File(newName)); } lastFileName = c.getSelectedFile().toString(); if (c.getSelectedFile().exists()) { int r = JOptionPane.showConfirmDialog(null, "File " + c.getSelectedFile().toString() + " already exists, overwrite it?"); if (r != JOptionPane.OK_OPTION) { return; } } openAVIOutputStream(c.getSelectedFile(), additionalComments); } synchronized public void doCloseFile() { if (aviOutputStream != null) { try { aviOutputStream.close(); aviOutputStream = null; if (timecodeWriter != null) { timecodeWriter.close(); log.info("Closed timecode file " + timecodeFile.toString()); timecodeWriter = null; } setWriteEnabled(false); log.info("Closed " + lastFileName + " in format " + format + " with " + framesWritten + " frames"); } catch (Exception ex) { log.warning(ex.toString()); ex.printStackTrace(); aviOutputStream = null; } } } /** * Opens AVI output stream and optionally the timecode file. * * @param f the file * @param additionalComments additional comments to be written to timecode * file, Comment header characters are added if not supplied. * */ public void openAVIOutputStream(File f, String[] additionalComments) { try { aviOutputStream = new AVIOutputStream(f, format); // aviOutputStream.setFrameRate(chip.getAeViewer().getFrameRate()); aviOutputStream.setFrameRate(frameRate); aviOutputStream.setVideoCompressionQuality(compressionQuality); // aviOutputStream.setVideoDimension(chip.getSizeX(), chip.getSizeY()); lastFileName = f.toString(); putString("lastFileName", lastFileName); if (writeTimecodeFile) { String s = f.toString().subSequence(0, f.toString().lastIndexOf(".")).toString() + TIMECODE_SUFFIX; timecodeFile = new File(s); timecodeWriter = new FileWriter(timecodeFile); timecodeWriter.write(String.format("# timecode file relating frames of AVI file to AER timestamps\n")); timecodeWriter.write(String.format("# written %s\n", new Date().toString())); if (additionalComments != null) { for (String st : additionalComments) { if (!st.startsWith(" st = " } if (!st.endsWith("\n")) { st = st + "\n"; } timecodeWriter.write(st); } } timecodeWriter.write(String.format("# frameNumber timestamp\n")); log.info("Opened timecode file " + timecodeFile.toString()); } log.info("Opened AVI output file " + f.toString() + " with format " + format); setFramesWritten(0); getSupport().firePropertyChange("framesWritten", null, framesWritten); } catch (IOException ex) { JOptionPane.showMessageDialog(null, ex.toString(), "Couldn't create output file stream", JOptionPane.WARNING_MESSAGE, null); return; } } /** * @return the writeTimecodeFile */ public boolean isWriteTimecodeFile() { return writeTimecodeFile; } /** * @param writeTimecodeFile the writeTimecodeFile to set */ public void setWriteTimecodeFile(boolean writeTimecodeFile) { this.writeTimecodeFile = writeTimecodeFile; putBoolean("writeTimecodeFile", writeTimecodeFile); } /** * @return the closeOnRewind */ public boolean isCloseOnRewind() { return closeOnRewind; } /** * @param closeOnRewind the closeOnRewind to set */ public void setCloseOnRewind(boolean closeOnRewind) { this.closeOnRewind = closeOnRewind; putBoolean("closeOnRewind", closeOnRewind); } @Override public void annotate(GLAutoDrawable drawable) { } /** * Turns gl to BufferedImage with fixed format * * @param gl * @param w * @param h * @return */ protected BufferedImage toImage(GL2 gl, int w, int h) { gl.glReadBuffer(GL.GL_FRONT); // or GL.GL_BACK ByteBuffer glBB = Buffers.newDirectByteBuffer(4 * w * h); gl.glReadPixels(0, 0, w, h, GL2.GL_BGRA, GL.GL_BYTE, glBB); BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_BGR); int[] bd = ((DataBufferInt) bi.getRaster().getDataBuffer()).getData(); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { int b = 2 * glBB.get(); int g = 2 * glBB.get(); int r = 2 * glBB.get(); int a = glBB.get(); // not using bd[(h - y - 1) * w + x] = (b << 16) | (g << 8) | r | 0xFF000000; } } return bi; } protected void writeTimecode(int timestamp) throws IOException { if (timecodeWriter != null) { timecodeWriter.write(String.format("%d %d\n", framesWritten, timestamp)); } } protected void incrementFramecountAndMaybeCloseOutput() { if (++framesWritten % LOG_EVERY_THIS_MANY_FRAMES == 0) { log.info(String.format("wrote %d frames", framesWritten)); } getSupport().firePropertyChange("framesWritten", null, framesWritten); if (maxFrames > 0 && framesWritten >= maxFrames) { log.info("wrote maxFrames=" + maxFrames + " frames; closing AVI file"); doCloseFile(); } } /** * @return the format */ public AVIOutputStream.VideoFormat getFormat() { return format; } /** * @param format the format to set */ public void setFormat(AVIOutputStream.VideoFormat format) { this.format = format; putString("format", format.toString()); } /** * @return the maxFrames */ public int getMaxFrames() { return maxFrames; } /** * @param maxFrames the maxFrames to set */ public void setMaxFrames(int maxFrames) { this.maxFrames = maxFrames; putInt("maxFrames", maxFrames); } /** * @return the framesWritten */ public int getFramesWritten() { return framesWritten; } /** * @param framesWritten the framesWritten to set */ public void setFramesWritten(int framesWritten) { int old = this.framesWritten; this.framesWritten = framesWritten; getSupport().firePropertyChange("framesWritten", old, framesWritten); } /** * @return the compressionQuality */ public float getCompressionQuality() { return compressionQuality; } /** * @param compressionQuality the compressionQuality to set */ public void setCompressionQuality(float compressionQuality) { if (compressionQuality < 0) { compressionQuality = 0; } else if (compressionQuality > 1) { compressionQuality = 1; } this.compressionQuality = compressionQuality; putFloat("compressionQuality", compressionQuality); } @Override public void propertyChange(PropertyChangeEvent evt) { if (closeOnRewind && evt.getPropertyName() == AEInputStream.EVENT_REWIND) { doCloseFile(); } } /** * @return the additionalComments */ public String[] getAdditionalComments() { return additionalComments; } /** * Sets array of additional comment strings to be written to timecode file. * * @param additionalComments the additionalComments to set */ public void setAdditionalComments(String[] additionalComments) { this.additionalComments = additionalComments; } /** * @return the frameRate */ public int getFrameRate() { return frameRate; } /** * @param frameRate the frameRate to set */ public void setFrameRate(int frameRate) { if(frameRate<1)frameRate=1; this.frameRate = frameRate; putInt("frameRate",frameRate); } // /** // * @return the saveFramesAsIndividualImageFiles // */ // public boolean isSaveFramesAsIndividualImageFiles() { // return saveFramesAsIndividualImageFiles; // /** // * @param saveFramesAsIndividualImageFiles the saveFramesAsIndividualImageFiles to set // */ // public void setSaveFramesAsIndividualImageFiles(boolean saveFramesAsIndividualImageFiles) { // this.saveFramesAsIndividualImageFiles = saveFramesAsIndividualImageFiles; // putBoolean("saveFramesAsIndividualImageFiles",saveFramesAsIndividualImageFiles); /** * @return the writeOnlyWhenMousePressed */ public boolean isWriteOnlyWhenMousePressed() { return writeOnlyWhenMousePressed; } /** * @param writeOnlyWhenMousePressed the writeOnlyWhenMousePressed to set */ public void setWriteOnlyWhenMousePressed(boolean writeOnlyWhenMousePressed) { this.writeOnlyWhenMousePressed = writeOnlyWhenMousePressed; putBoolean("writeOnlyWhenMousePressed",writeOnlyWhenMousePressed); } @Override public void mouseReleased(MouseEvent e) { if(writeOnlyWhenMousePressed) setWriteEnabled(false); } @Override public void mousePressed(MouseEvent e) { if(writeOnlyWhenMousePressed) setWriteEnabled(true); } public boolean isWriteEnabled(){ return writeEnabled; } public void setWriteEnabled(boolean yes){ boolean old=this.writeEnabled; writeEnabled=yes; getSupport().firePropertyChange("writeEnabled",old, yes); log.info("writeEnabled="+writeEnabled); } }
package cx2x.xcodeml.xnode; import org.w3c.dom.Element; import org.w3c.dom.Node; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; /** * The XglobalDeclTable represents the typeTable (5.1) element in XcodeML * intermediate representation. * * Elements: (FfunctionDefinition | FmoduleDefinition)* * - Optional: * - FfunctionDefinition (XfunctionDefinition) * - FmoduleDefinition (XmoduleDefinition) * * @author clementval */ public class XglobalDeclTable extends Xnode { /* Hashtable containing the global declaration elements. Key is the name of * the function or the module. */ private final Hashtable<String, Xnode> _table; /** * Element standard ctor. Pass the base element to the base class and read * inner information (elements and attributes). * @param baseElement The root of the element. */ public XglobalDeclTable(Element baseElement){ super(baseElement); _table = new Hashtable<>(); readTable(); } /** * Read the declaration table */ private void readTable(){ Node currentNode = _baseElement.getFirstChild(); while(currentNode != null){ if (currentNode.getNodeType() == Node.ELEMENT_NODE) { Element el = (Element)currentNode; if(el.getTagName().equals(Xname.F_FUNCTION_DEFINITION)){ XfunctionDefinition fctDef = new XfunctionDefinition(el); _table.put(fctDef.getName().getValue(), fctDef); } else if(el.getTagName().equals(Xname.F_MODULE_DEFINITION)){ XmoduleDefinition moduleDef = new XmoduleDefinition(el); _table.put(moduleDef.getName(), moduleDef); } } currentNode = currentNode.getNextSibling(); } } /** * Get a specific function declaration based on its name. * @param name The name of the function to be returned. * @return A XfunctionDefinition object if key is found. Null otherwise. */ public XfunctionDefinition getFctDefinition(String name){ if(_table.containsKey(name)) { Xnode el = _table.get(name); if(el instanceof XfunctionDefinition){ return (XfunctionDefinition)el; } } return null; } /** * Get a specific module declaration based on its name. * @param name The name of the module to be returned. * @return A XmoduleDefinition object if key is found. Null otherwise. */ public XmoduleDefinition getModuleDefinition(String name){ if(_table.containsKey(name)){ Xnode el = _table.get(name); if(el instanceof XmoduleDefinition){ return (XmoduleDefinition)el; } } return null; } /** * Check if there is a definition for the given name. * @param name Name to be searched. * @return True if there is a definition. False otherwise. */ public boolean hasDefinition(String name){ return _table.containsKey(name); } /** * Check if there is a module definition for the given name. * @param name Name to be searched. * @return True if there is a definition. False otherwise. */ public boolean hasModuleDefinition(String name) { return _table.containsKey(name) && (_table.get(name) instanceof XmoduleDefinition); } /** * Check if there is a function definition for the given name. * @param name Name to be searched. * @return True if there is a definition. False otherwise. */ public boolean hasFunctionDefinition(String name){ return _table.containsKey(name) && (_table.get(name) instanceof XfunctionDefinition); } /** * Get the number of declarations in the table. * @return The number of declarations in the table. */ public int count(){ return _table.size(); } /** * Get an iterator over the table. * @return Iterator. */ public Iterator<Map.Entry<String, Xnode>> getIterator(){ return _table.entrySet().iterator(); } @Override public XglobalDeclTable cloneObject() { Element clone = (Element)cloneNode(); return new XglobalDeclTable(clone); } }
package net.sf.jaer.util.avioutput; import static net.sf.jaer.graphics.AEViewer.DEFAULT_CHIP_CLASS; import static net.sf.jaer.graphics.AEViewer.prefs; import java.awt.Dimension; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.BoxLayout; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.filechooser.FileFilter; import com.jogamp.opengl.GLAutoDrawable; import ch.unizh.ini.jaer.projects.davis.frames.ApsFrameExtractor; import ch.unizh.ini.jaer.projects.npp.DvsFramer.TimeSliceMethod; import ch.unizh.ini.jaer.projects.npp.DvsFramerSingleFrame; import ch.unizh.ini.jaer.projects.npp.TargetLabeler; import ch.unizh.ini.jaer.projects.npp.TargetLabeler.TargetLocation; import eu.seebetter.ini.chips.DavisChip; import ml.options.Options; import ml.options.Options.Multiplicity; import ml.options.Options.Separator; import net.sf.jaer.Description; import net.sf.jaer.DevelopmentStatus; import net.sf.jaer.aemonitor.AEPacketRaw; import net.sf.jaer.chip.AEChip; import net.sf.jaer.chip.EventExtractor2D; import net.sf.jaer.event.BasicEvent; import net.sf.jaer.event.EventPacket; import net.sf.jaer.event.PolarityEvent; import net.sf.jaer.eventio.AEFileInputStream; import net.sf.jaer.eventio.AEInputStream; import net.sf.jaer.eventprocessing.FilterChain; import net.sf.jaer.graphics.FrameAnnotater; import net.sf.jaer.graphics.ImageDisplay; import net.sf.jaer.graphics.MultilineAnnotationTextRenderer; import net.sf.jaer.util.avioutput.AVIOutputStream.VideoFormat; import net.sf.jaer.util.filter.LowpassFilter; /** * Writes out AVI movie with DVS time or event slices as AVI frame images with * desired output resolution * * @author Tobi Delbruck */ @Description("Writes out AVI movie with DVS constant-number-of-event subsampled 2D histogram slices as AVI frame images with desired output resolution") @DevelopmentStatus(DevelopmentStatus.Status.Stable) public class DvsSliceAviWriter extends AbstractAviWriter implements FrameAnnotater { private DvsFramerSingleFrame dvsFrame = null; private ApsFrameExtractor frameExtractor = null; private TargetLabeler targetLabeler = null; private float frameRateEstimatorTimeConstantMs = getFloat("frameRateEstimatorTimeConstantMs", 10f); private JFrame frame = null; public ImageDisplay display; private boolean showOutput; private volatile boolean newApsFrameAvailable = false; private int endOfFrameTimestamp = 0, lastTimestamp = 0; protected boolean writeDvsSliceImageOnApsFrame = getBoolean("writeDvsSliceImageOnApsFrame", false); private boolean writeDvsFrames = getBoolean("writeDvsFrames", true); private boolean writeApsFrames = getBoolean("writeApsFrames", false); private boolean writeTargetLocations = getBoolean("writeTargetLocations", true); private boolean writeDvsEventsToTextFile = getBoolean("writeDvsEventsToTextFile", false); protected static final String EVENTS_SUFFIX = "-events.txt"; protected FileWriter eventsWriter = null; protected File eventsFile = null; protected File targetLocationsFile = null; private FileWriter targetLocationsWriter = null; private boolean rendererPropertyChangeListenerAdded = false; private LowpassFilter lowpassFilter = new LowpassFilter(frameRateEstimatorTimeConstantMs); private int lastDvsFrameTimestamp = 0; private float avgDvsFrameIntervalMs = 0; private boolean showStatistics = getBoolean("showStatistics", false); private String TARGETS_LOCATIONS_SUFFIX = "-targetLocations.txt"; private String APS_OUTPUT_SUFFIX = "-aps.avi"; private String DVS_OUTPUT_SUFFIX = "-dvs.avi"; // used for separate output option private BufferedImage aviOutputImage = null; // holds either dvs or aps or both iamges public DvsSliceAviWriter(AEChip chip) { super(chip); FilterChain chain = new FilterChain(chip); if (chip instanceof DavisChip) { frameExtractor = new ApsFrameExtractor(chip); chain.add(frameExtractor); frameExtractor.getSupport().addPropertyChangeListener(this); } targetLabeler = new TargetLabeler(chip); chain.add(targetLabeler); dvsFrame = new DvsFramerSingleFrame(chip); chain.add(dvsFrame); setEnclosedFilterChain(chain); showOutput = getBoolean("showOutput", true); DEFAULT_FILENAME = "DvsEventSlices.avi"; setPropertyTooltip("showOutput", "shows output in JFrame/ImageDisplay"); setPropertyTooltip("frameRateEstimatorTimeConstantMs", "time constant of lowpass filter that shows average DVS slice frame rate"); setPropertyTooltip("writeDvsSliceImageOnApsFrame", "<html>write DVS slice image for each APS frame end event (dvsMinEvents ignored).<br>The frame is written at the end of frame APS event.<br><b>Warning: to capture all frames, ensure that playback time slices are slow enough that all frames are rendered</b>"); setPropertyTooltip("writeApsFrames", "<html>write APS frames to file<br><b>Warning: to capture all frames, ensure that playback time slices are slow enough that all frames are rendered</b>"); setPropertyTooltip("writeDvsFrames", "<html>write DVS frames to file<br>"); setPropertyTooltip("writeTargetLocations", "<html>If TargetLabeler has locations, write them to a file named XXX-targetlocations.txt<br>"); setPropertyTooltip("writeDvsEventsToTextFile", "<html>write DVS events to text file, one event per line, timestamp, x, y, pol<br>"); setPropertyTooltip("showStatistics", "shows statistics of DVS frame (most off and on counts, frame rate, sparsity)"); } @Override synchronized public EventPacket<?> filterPacket(EventPacket<?> in) { // frameExtractor.filterPacket(in); // extracts frames with nornalization (brightness, contrast) and sends to apsNet on each frame in PropertyChangeListener // send DVS timeslice to convnet super.filterPacket(in); frameExtractor.filterPacket(in); // process frame extractor, target labeler and dvsframer targetLabeler.filterPacket(in); dvsFrame.checkParameters(); checkSubsampler(); for (BasicEvent e : in) { if (e.isSpecial() || e.isFilteredOut()) { continue; } PolarityEvent p = (PolarityEvent) e; lastTimestamp = e.timestamp; dvsFrame.addEvent(p); try { writeEvent(p); } catch (IOException ex) { Logger.getLogger(DvsSliceAviWriter.class.getName()).log(Level.SEVERE, null, ex); doCloseFile(); } if ((writeDvsSliceImageOnApsFrame && newApsFrameAvailable && (e.timestamp >= endOfFrameTimestamp)) || ((!writeDvsSliceImageOnApsFrame && dvsFrame.getDvsFrame().isFilled()) && ((chip.getAeViewer() == null) || !chip.getAeViewer().isPaused()))) { // added check for nonnull aeviewer in case filter is called from separate program if (writeDvsSliceImageOnApsFrame) { newApsFrameAvailable = false; } dvsFrame.normalizeFrame(); maybeShowOutput(dvsFrame); if (writeDvsFrames && (getAviOutputStream() != null) && isWriteEnabled()) { BufferedImage bi = toImage(dvsFrame); try { writeTimecode(e.timestamp); writeTargetLocation(e.timestamp, framesWritten); getAviOutputStream().writeFrame(bi); incrementFramecountAndMaybeCloseOutput(); } catch (IOException ex) { doCloseFile(); log.warning(ex.toString()); ex.printStackTrace(); setFilterEnabled(false); } } // dvsFrame.clear(); // already cleared by next event when next event added if (lastDvsFrameTimestamp != 0) { int lastFrameInterval = lastTimestamp - lastDvsFrameTimestamp; avgDvsFrameIntervalMs = 1e-3f * lowpassFilter.filter(lastFrameInterval, lastTimestamp); } lastDvsFrameTimestamp = lastTimestamp; } } if (writeDvsSliceImageOnApsFrame && ((lastTimestamp - endOfFrameTimestamp) > 1000000)) { log.warning("last frame event was received more than 1s ago; maybe you need to enable Display Frames in the User Control Panel?"); } return in; } public DvsFramerSingleFrame getDvsFrame() { return dvsFrame; } @Override public void annotate(GLAutoDrawable drawable) { if (dvsFrame == null) { return; } if (!isShowStatistics()) { return; } MultilineAnnotationTextRenderer.resetToYPositionPixels(chip.getSizeY() * .8f); MultilineAnnotationTextRenderer.setScale(.3f); float avgFrameRate = avgDvsFrameIntervalMs == 0 ? Float.NaN : 1000 / avgDvsFrameIntervalMs; String s = null; if (dvsFrame.isNormalizeFrame()) { s = String.format("mostOffCount=%d\n mostOnCount=%d\navg frame rate=%.1f\nsparsity=%.2f%%", dvsFrame.getMostOffCount(), dvsFrame.getMostOnCount(), avgFrameRate, 100 * dvsFrame.getSparsity()); } else { s = String.format("mostOffCount=%d\n mostOnCount=%d\navg frame rate=%.1f", dvsFrame.getMostOffCount(), dvsFrame.getMostOnCount(), avgFrameRate); } MultilineAnnotationTextRenderer.renderMultilineString(s); } @Override public synchronized void doStartRecordingAndSaveAVIAs() { String[] s = { "width=" + dvsFrame.getOutputImageWidth(), "height=" + dvsFrame.getOutputImageHeight(), "timeslicemethod=" + dvsFrame.getTimeSliceMethod().toString(), "grayScale=" + dvsFrame.getDvsGrayScale(), "normalize=" + dvsFrame.isNormalizeFrame(), "normalizeDVSForZsNullhop=" + dvsFrame.isNormalizeDVSForZsNullhop(), "dvsMinEvents=" + dvsFrame.getDvsEventsPerFrame(), "timeDurationUsPerFrame=" + dvsFrame.getTimeDurationUsPerFrame(), "format=" + format.toString(), "compressionQuality=" + compressionQuality }; setAdditionalComments(s); if (getAviOutputStream() != null) { JOptionPane.showMessageDialog(null, "AVI output stream is already opened"); return; } JFileChooser c = new JFileChooser(lastFile); c.setFileFilter(new FileFilter() { @Override public boolean accept(File f) { return f.isDirectory() || f.getName().toLowerCase().endsWith(".avi"); } @Override public String getDescription() { return "AVI (Audio Video Interleave) Microsoft video file"; } }); c.setSelectedFile(new File(lastFileName)); int ret = c.showSaveDialog(null); if (ret != JFileChooser.APPROVE_OPTION) { return; } // above chooses base filename. Now we need to see if we just write to this file, or make two files for separate DVS and APS outputs if (!c.getSelectedFile().getName().toLowerCase().endsWith(".avi")) { String newName = c.getSelectedFile().toString() + ".avi"; c.setSelectedFile(new File(newName)); } lastFileName = c.getSelectedFile().toString(); if (c.getSelectedFile().exists()) { int r = JOptionPane.showConfirmDialog(null, "File " + c.getSelectedFile().toString() + " already exists, overwrite it?"); if (r != JOptionPane.OK_OPTION) { return; } } lastFile = c.getSelectedFile(); setAviOutputStream(openAVIOutputStream(c.getSelectedFile(), getAdditionalComments())); openEventsTextFile(c.getSelectedFile(), getAdditionalComments()); openTargetLabelsFile(c.getSelectedFile(), getAdditionalComments()); if (isRewindBeforeRecording()) { ignoreRewinwdEventFlag = true; chip.getAeViewer().getAePlayer().rewind(); ignoreRewinwdEventFlag = true; } aviOutputImage = new BufferedImage(getOutputImageWidth(), dvsFrame.getOutputImageHeight(), BufferedImage.TYPE_INT_BGR); } private int getOutputImageWidth() { return (writeApsFrames && writeDvsFrames) ? dvsFrame.getOutputImageWidth() * 2 : dvsFrame.getOutputImageWidth(); } private int getDvsStartingX() { return (writeApsFrames && writeDvsFrames) ? dvsFrame.getOutputImageWidth() : 0; } protected void writeEvent(PolarityEvent e) throws IOException { if (eventsWriter != null) { eventsWriter.write(String.format("%d,%d,%d,%d\n", e.timestamp, e.x, e.y, e.getPolaritySignum())); } } private void openTargetLabelsFile(File f, String[] additionalComments) { if (writeTargetLocations) { try { String s = null; if (f.toString().lastIndexOf(".") == -1) { s = f.toString() + TARGETS_LOCATIONS_SUFFIX; } else { s = f.toString().subSequence(0, f.toString().lastIndexOf(".")).toString() + TARGETS_LOCATIONS_SUFFIX; } targetLocationsFile = new File(s); targetLocationsWriter = new FileWriter(targetLocationsFile); targetLocationsWriter.write(String.format("# labeled target locations file\n")); targetLocationsWriter.write(String.format("# written %s\n", new Date().toString())); if (additionalComments != null) { for (String st : additionalComments) { if (!st.startsWith(" st = " } if (!st.endsWith("\n")) { st = st + "\n"; } targetLocationsWriter.write(st); } } targetLocationsWriter.write(String.format("# frameNumber timestamp x y targetTypeID width height\n")); log.info("Opened labeled target locations file " + targetLocationsFile.toString()); } catch (IOException ex) { Logger.getLogger(DvsSliceAviWriter.class.getName()).log(Level.SEVERE, null, ex); } } } private void openEventsTextFile(File f, String[] additionalComments) { if (writeDvsEventsToTextFile) { try { String s = null; if (f.toString().lastIndexOf(".") == -1) { s = f.toString() + EVENTS_SUFFIX; } else { s = f.toString().subSequence(0, f.toString().lastIndexOf(".")).toString() + EVENTS_SUFFIX; } eventsFile = new File(s); eventsWriter = new FileWriter(eventsFile); eventsWriter.write(String.format("# events file\n")); eventsWriter.write(String.format("# written %s\n", new Date().toString())); if (additionalComments != null) { for (String st : additionalComments) { if (!st.startsWith(" st = " } if (!st.endsWith("\n")) { st = st + "\n"; } eventsWriter.write(st); } } eventsWriter.write(String.format("# timestamp,x,y,pol\n")); log.info("Opened events file " + eventsFile.toString()); } catch (IOException ex) { Logger.getLogger(DvsSliceAviWriter.class.getName()).log(Level.SEVERE, null, ex); } } } @Override public synchronized void doCloseFile() { setWriteEnabled(false); if (eventsWriter != null) { try { eventsWriter.close(); log.info("Closed events file " + eventsFile.toString()); eventsWriter = null; } catch (IOException ex) { Logger.getLogger(DvsSliceAviWriter.class.getName()).log(Level.SEVERE, null, ex); } } if (targetLocationsWriter != null) { try { targetLocationsWriter.close(); log.info("Closed target locations file " + targetLocationsFile.toString()); targetLocationsWriter = null; } catch (IOException ex) { Logger.getLogger(DvsSliceAviWriter.class.getName()).log(Level.SEVERE, null, ex); } finally { targetLocationsWriter = null; } } if (timecodeWriter != null) { try { timecodeWriter.close(); log.info("Closed timecode file " + timecodeFile.toString()); } catch (IOException ex) { Logger.getLogger(DvsSliceAviWriter.class.getName()).log(Level.SEVERE, null, ex); } finally { timecodeWriter = null; } } super.doCloseFile(); } private void checkSubsampler() { } private BufferedImage toImage(DvsFramerSingleFrame dvsFramer) { int[] bd = ((DataBufferInt) aviOutputImage.getRaster().getDataBuffer()).getData(); for (int y = 0; y < dvsFrame.getOutputImageHeight(); y++) { for (int x = 0; x < dvsFrame.getOutputImageWidth(); x++) { int b = (int) (255 * dvsFramer.getValueAtPixel(x, y)); int g = b; int r = b; int idx = ((dvsFrame.getOutputImageHeight() - y - 1) * getOutputImageWidth()) + x + getDvsStartingX(); // DVS image is right half if (idx >= bd.length) { throw new RuntimeException(String.format("index %d out of bounds for x=%d y=%d", idx, x, y)); } bd[idx] = (b << 16) | (g << 8) | r | 0xFF000000; } } return aviOutputImage; } private BufferedImage toImage(ApsFrameExtractor frameExtractor) { int[] bd = ((DataBufferInt) aviOutputImage.getRaster().getDataBuffer()).getData(); int srcwidth = chip.getSizeX(), srcheight = chip.getSizeY(), targetwidth = dvsFrame.getOutputImageWidth(), targetheight = dvsFrame.getOutputImageHeight(); float[] frame = frameExtractor.getNewFrame(); for (int y = 0; y < dvsFrame.getOutputImageHeight(); y++) { for (int x = 0; x < dvsFrame.getOutputImageWidth(); x++) { int xsrc = (int) Math.floor((x * (float) srcwidth) / targetwidth), ysrc = (int) Math.floor((y * (float) srcheight) / targetheight); int b = (int) (255 * frame[frameExtractor.getIndex(xsrc, ysrc)]); // TODO simplest possible downsampling, can do better with linear or bilinear interpolation but code more complex int g = b; int r = b; int idx = ((dvsFrame.getOutputImageHeight() - y - 1) * getOutputImageWidth()) + x + 0; // aps image is left half if combined if (idx >= bd.length) { throw new RuntimeException(String.format("index %d out of bounds for x=%d y=%d", idx, x, y)); } bd[idx] = (b << 16) | (g << 8) | r | 0xFF000000; } } return aviOutputImage; } synchronized public void maybeShowOutput(DvsFramerSingleFrame dvsFramer) { if (!showOutput) { return; } if (frame == null) { String windowName = "DVS slice"; frame = new JFrame(windowName); frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS)); frame.setPreferredSize(new Dimension(600, 600)); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); display = ImageDisplay.createOpenGLCanvas(); display.setBorderSpacePixels(10); display.setImageSize(dvsFrame.getOutputImageWidth(), dvsFrame.getOutputImageHeight()); display.setSize(200, 200); panel.add(display); frame.getContentPane().add(panel); frame.pack(); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { setShowOutput(false); } }); } if (!frame.isVisible()) { frame.setVisible(true); } if ((display.getWidth() != dvsFrame.getOutputImageWidth()) || (display.getHeight() != dvsFrame.getOutputImageHeight())) { display.setImageSize(dvsFrame.getOutputImageWidth(), dvsFrame.getOutputImageHeight()); } for (int x = 0; x < dvsFrame.getOutputImageWidth(); x++) { for (int y = 0; y < dvsFrame.getOutputImageHeight(); y++) { display.setPixmapGray(x, y, dvsFramer.getValueAtPixel(x, y)); } } display.repaint(); } /** * @return the showOutput */ public boolean isShowOutput() { return showOutput; } /** * @param showOutput the showOutput to set */ public void setShowOutput(boolean showOutput) { boolean old = this.showOutput; this.showOutput = showOutput; putBoolean("showOutput", showOutput); getSupport().firePropertyChange("showOutput", old, showOutput); } /** * @return the writeDvsSliceImageOnApsFrame */ public boolean isWriteDvsSliceImageOnApsFrame() { return writeDvsSliceImageOnApsFrame; } /** * @param writeDvsSliceImageOnApsFrame the writeDvsSliceImageOnApsFrame to * set */ public void setWriteDvsSliceImageOnApsFrame(boolean writeDvsSliceImageOnApsFrame) { this.writeDvsSliceImageOnApsFrame = writeDvsSliceImageOnApsFrame; putBoolean("writeDvsSliceImageOnApsFrame", writeDvsSliceImageOnApsFrame); } @Override public void propertyChange(PropertyChangeEvent evt) { super.propertyChange(evt); if ((evt.getPropertyName() == ApsFrameExtractor.EVENT_NEW_FRAME)) { endOfFrameTimestamp = frameExtractor.getLastFrameTimestamp(); newApsFrameAvailable = true; if (writeApsFrames && (getAviOutputStream() != null) && isWriteEnabled() && ((chip.getAeViewer() == null) || !chip.getAeViewer().isPaused())) { BufferedImage bi = toImage(frameExtractor); try { writeTimecode(endOfFrameTimestamp); writeTargetLocation(endOfFrameTimestamp, framesWritten); getAviOutputStream().writeFrame(bi); incrementFramecountAndMaybeCloseOutput(); } catch (IOException ex) { log.warning(ex.toString()); ex.printStackTrace(); setFilterEnabled(false); } } } } /** * @return the frameRateEstimatorTimeConstantMs */ public float getFrameRateEstimatorTimeConstantMs() { return frameRateEstimatorTimeConstantMs; } /** * @param frameRateEstimatorTimeConstantMs the * frameRateEstimatorTimeConstantMs to set */ public void setFrameRateEstimatorTimeConstantMs(float frameRateEstimatorTimeConstantMs) { this.frameRateEstimatorTimeConstantMs = frameRateEstimatorTimeConstantMs; lowpassFilter.setTauMs(frameRateEstimatorTimeConstantMs); putFloat("frameRateEstimatorTimeConstantMs", frameRateEstimatorTimeConstantMs); } public static final String USAGE = "java DvsSliceAviWriter \n" + " [-aechip=aechipclassname (either shortcut dvs128, davis240c or davis346mini, or fully qualified class name, e.g. eu.seebetter.ini.chips.davis.DAVIS240C)] " + " [-width=36] [-height=36] [-quality=.9] [-format=PNG|JPG|RLE|RAW] [-framerate=30] [-grayscale=200] " + " [-writedvssliceonapsframe=false] \n" + " [-writetimecodefile=true] \n" + " [-writeapsframes=false] \n" + " [-writedvsframes=true] \n" + " [-writedvseventstotextfile=false] \n" + " [-writetargetlocations=false] \n" + " [-timeslicemethod=EventCount|TimeIntervalUs] [-numevents=2000] [-framedurationus=10000]\n" + " [-rectify=false] [-normalize=true] [-showoutput=true] [-maxframes=0] " + " inputFile.aedat [outputfile.avi]" + "\n" + "numevents and framedurationus are exclusively possible\n" + "Arguments values are assigned with =, not space\n" + "If outputfile is not provided its name is generated from the input file with appended .avi"; public static final HashMap<String, String> chipClassesMap = new HashMap(); public static void main(String[] args) { // make hashmap of common chip classes chipClassesMap.put("dvs128", "ch.unizh.ini.jaer.chip.retina.DVS128"); chipClassesMap.put("davis240c", "eu.seebetter.ini.chips.davis.DAVIS240C"); chipClassesMap.put("davis346blue", "eu.seebetter.ini.chips.davis.Davis346blue"); chipClassesMap.put("davis346red", "eu.seebetter.ini.chips.davis.Davis346red"); // command line // uses last settings of everything // java DvsSliceAviWriter inputFile.aedat outputfile.avi Options opt = new Options(args, 1, 2); opt.getSet().addOption("aechip", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); opt.getSet().addOption("width", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); opt.getSet().addOption("height", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); opt.getSet().addOption("quality", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); opt.getSet().addOption("format", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); opt.getSet().addOption("framerate", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); opt.getSet().addOption("grayscale", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); opt.getSet().addOption("writedvssliceonapsframe", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); opt.getSet().addOption("writedvsframes", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); opt.getSet().addOption("writeapsframes", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); opt.getSet().addOption("writedvseventstotextfile", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); opt.getSet().addOption("writetimecodefile", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); opt.getSet().addOption("numevents", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); opt.getSet().addOption("framedurationus", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); opt.getSet().addOption("timeslicemethod", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); opt.getSet().addOption("rectify", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); opt.getSet().addOption("normalize", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); opt.getSet().addOption("nullhopnormalize", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); opt.getSet().addOption("showoutput", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); opt.getSet().addOption("maxframes", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); opt.getSet().addOption("writetargetlocations", Separator.EQUALS, Multiplicity.ZERO_OR_ONE); if (!opt.check()) { System.err.println(opt.getCheckErrors()); System.err.println(USAGE); System.exit(1); } if (opt.getSet().getData().isEmpty()) { System.err.println("no output file specified"); System.exit(1); } if (opt.getSet().getData().size() > 2) { System.err.println("too many input/output file arguments (only one or two allowed)"); System.exit(1); } String inpfilename = opt.getSet().getData().get(0); if (!(inpfilename.toLowerCase().endsWith("aedat"))) { System.err.println("Warning: Input filename does not end with aedat: " + inpfilename); } String outfilename = null; if (opt.getSet().getData().size() == 2) { outfilename = opt.getSet().getData().get(1); } else { outfilename = inpfilename.substring(0, inpfilename.lastIndexOf(".")) + ".avi"; System.out.println("Writing to output file " + outfilename); } AEChip chip = null; String chipname = null; if (opt.getSet().isSet("aechip")) { chipname = opt.getSet().getOption("aechip").getResultValue(0); } else { chipname = prefs.get("AEViewer.aeChipClassName", DEFAULT_CHIP_CLASS); } try { String className = chipClassesMap.get(chipname.toLowerCase()); if (className == null) { className = chipname; } else { System.out.println("from " + chipname + " found fully qualified class name " + className); } System.out.println("constructing AEChip " + className); Class chipClass = Class.forName(className); Constructor<AEChip> constructor = chipClass.getConstructor(); chip = constructor.newInstance((java.lang.Object[]) null); } catch (Exception ex) { System.err.println("Could not construct instance of aechip=" + chipname + ": " + ex.toString()); System.exit(1); } AEFileInputStream ais = null; File inpfile = new File(inpfilename); File outfile = new File(outfilename); AEPacketRaw aeRaw = null; final DvsSliceAviWriter writer = new DvsSliceAviWriter(chip); boolean oldCloseOnRewind = writer.isCloseOnRewind(); writer.setCloseOnRewind(false); writer.getSupport().addPropertyChangeListener(writer); // handle options if (opt.getSet().isSet("width")) { try { int n = Integer.parseInt(opt.getSet().getOption("width").getResultValue(0)); writer.getDvsFrame().setOutputImageWidth(n); } catch (NumberFormatException e) { System.err.println("Bad width argument: " + e.toString()); System.exit(1); } } if (opt.getSet().isSet("height")) { try { int n = Integer.parseInt(opt.getSet().getOption("height").getResultValue(0)); writer.getDvsFrame().setOutputImageHeight(n); } catch (NumberFormatException e) { System.err.println("Bad height argument: " + e.toString()); System.exit(1); } } if (opt.getSet().isSet("quality")) { try { float f = Float.parseFloat(opt.getSet().getOption("quality").getResultValue(0)); writer.setCompressionQuality(f); } catch (NumberFormatException e) { System.err.println("Bad quality argument: " + e.toString()); System.exit(1); } } if (opt.getSet().isSet("format")) { try { String type = (opt.getSet().getOption("format").getResultValue(0)); VideoFormat format = VideoFormat.valueOf(type.toUpperCase()); writer.setFormat(format); } catch (IllegalArgumentException e) { System.err.println("Bad format argument: " + e.toString() + "; use PNG, JPG, RAW, or RLE"); } } if (opt.getSet().isSet("framerate")) { try { int n = Integer.parseInt(opt.getSet().getOption("framerate").getResultValue(0)); writer.setFrameRate(n); } catch (NumberFormatException e) { System.err.println("Bad framerate argument: " + e.toString()); System.exit(1); } } if (opt.getSet().isSet("grayscale")) { try { int n = Integer.parseInt(opt.getSet().getOption("grayscale").getResultValue(0)); writer.getDvsFrame().setDvsGrayScale(n); } catch (NumberFormatException e) { System.err.println("Bad grayscale argument: " + e.toString()); System.exit(1); } } if (opt.getSet().isSet("writedvssliceonapsframe")) { boolean b = Boolean.parseBoolean(opt.getSet().getOption("writedvssliceonapsframe").getResultValue(0)); writer.setWriteDvsSliceImageOnApsFrame(b); } if (opt.getSet().isSet("writetimecodefile")) { boolean b = Boolean.parseBoolean(opt.getSet().getOption("writetimecodefile").getResultValue(0)); writer.setWriteDvsSliceImageOnApsFrame(b); } if (opt.getSet().isSet("writedvsframes")) { boolean b = Boolean.parseBoolean(opt.getSet().getOption("writedvsframes").getResultValue(0)); writer.setWriteDvsFrames(b); } if (opt.getSet().isSet("writeapsframes")) { boolean b = Boolean.parseBoolean(opt.getSet().getOption("writeapsframes").getResultValue(0)); writer.setWriteApsFrames(b); } if (opt.getSet().isSet("writetargetlocations")) { boolean b = Boolean.parseBoolean(opt.getSet().getOption("writetargetlocations").getResultValue(0)); writer.setWriteTargetLocations(b); } if (opt.getSet().isSet("numevents")) { try { int n = Integer.parseInt(opt.getSet().getOption("numevents").getResultValue(0)); writer.getDvsFrame().setDvsEventsPerFrame(n); } catch (NumberFormatException e) { System.err.println("Bad numevents argument: " + e.toString()); System.exit(1); } } if (opt.getSet().isSet("framedurationus")) { try { int n = Integer.parseInt(opt.getSet().getOption("framedurationus").getResultValue(0)); writer.getDvsFrame().setTimeDurationUsPerFrame(n); } catch (NumberFormatException e) { System.err.println("Bad numevents argument: " + e.toString()); System.exit(1); } } if (opt.getSet().isSet("timeslicemethod")) { try { String methodName = opt.getSet().getOption("timeslicemethod").getResultValue(0); TimeSliceMethod method = TimeSliceMethod.valueOf(methodName); writer.getDvsFrame().setTimeSliceMethod(method); } catch (Exception e) { System.err.println("Bad timeslicemethod argument: " + e.toString() + "; use EventCount or TimeIntervalUs"); System.exit(1); } } if (opt.getSet().isSet("rectify")) { boolean b = Boolean.parseBoolean(opt.getSet().getOption("rectify").getResultValue(0)); writer.getDvsFrame().setRectifyPolarities(b); } if (opt.getSet().isSet("normalize")) { boolean b = Boolean.parseBoolean(opt.getSet().getOption("normalize").getResultValue(0)); writer.getDvsFrame().setNormalizeFrame(b); } if (opt.getSet().isSet("nullhopnormalize")) { boolean b = Boolean.parseBoolean(opt.getSet().getOption("nullhopnormalize").getResultValue(0)); writer.getDvsFrame().setNormalizeDVSForZsNullhop(b); } if (opt.getSet().isSet("showoutput")) { boolean b = Boolean.parseBoolean(opt.getSet().getOption("showoutput").getResultValue(0)); writer.setShowOutput(b); } if (opt.getSet().isSet("maxframes")) { try { int n = Integer.parseInt(opt.getSet().getOption("maxframes").getResultValue(0)); writer.setMaxFrames(n); } catch (NumberFormatException e) { System.err.println("Bad maxframes argument: " + e.toString()); System.exit(1); } } else { writer.setMaxFrames(0); } writer.openAVIOutputStream(outfile, args); int lastNumFramesWritten = 0, numPrinted = 0; try { ais = new AEFileInputStream(inpfile, chip); ais.getSupport().addPropertyChangeListener(writer); // get informed about rewind events } catch (IOException ex) { System.err.println("Couldn't open file " + inpfile + " from working directory " + System.getProperty("user.dir") + " : " + ex.toString()); System.exit(1); } EventExtractor2D extractor = chip.getEventExtractor(); System.out.println(String.format("Frames written: ")); // need an object here to register as propertychange listener for the rewind event // generated when reading the file and getting to the end, // since the AEFileInputStream will not generate end of file exceptions final WriterControl writerControl = new WriterControl(); PropertyChangeListener rewindListener = new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent pce) { if (pce.getPropertyName() == AEInputStream.EVENT_EOF) { writerControl.end(); } } }; ais.getSupport().addPropertyChangeListener(rewindListener); ais.setNonMonotonicTimeExceptionsChecked(false); // to avoid wrap and big wrap exceptions, possibly, in long recordings while (writerControl.writing) { try { aeRaw = ais.readPacketByNumber(writer.getDvsFrame().getDvsEventsPerFrame()); // read at most this many events to avoid writing duplicate frames at end of movie from start of file, which would happen automatically by EventPacket cooked = extractor.extractPacket(aeRaw); writer.filterPacket(cooked); int numFramesWritten = writer.getFramesWritten(); if (numFramesWritten >= (lastNumFramesWritten + 500)) { lastNumFramesWritten = numFramesWritten; System.out.println(String.format("%d frames", numFramesWritten)); } if ((writer.getMaxFrames() > 0) && (writer.getFramesWritten() >= writer.getMaxFrames())) { break; } } catch (IOException e) { e.printStackTrace(); try { System.err.println("IOException: " + e.getMessage()); if (ais != null) { ais.close(); } if (writer != null) { writer.doCloseFile(); } System.exit(1); } catch (Exception e3) { System.err.println("Exception closing file: " + e3.getMessage()); System.exit(1); } } } // end of loop to read and write file try { ais.close(); } catch (IOException ex) { System.err.println("exception closing file: " + ex.toString()); } writer.setShowOutput(false); writer.setCloseOnRewind(oldCloseOnRewind); writer.doCloseFile(); System.out.println(String.format("Settings: aechip=%s\nwidth=%d height=%d quality=%f format=%s framerate=%d grayscale=%d\n" + "writedvssliceonapsframe=%s writetimecodefile=%s\n" + "timeslicemethod=%s numevents=%d framedurationus=%d\n" + " rectify=%s normalize=%s nullhopnormalize=%s showoutput=%s maxframes=%d", chipname, writer.getDvsFrame().getOutputImageWidth(), writer.getDvsFrame().getOutputImageHeight(), writer.getCompressionQuality(), writer.getFormat().toString(), writer.getFrameRate(), writer.getDvsFrame().getDvsGrayScale(), writer.isWriteDvsSliceImageOnApsFrame(), writer.isWriteTimecodeFile(), writer.getDvsFrame().getTimeSliceMethod().toString(), writer.getDvsFrame().getDvsEventsPerFrame(), writer.getDvsFrame().getTimeDurationUsPerFrame(), writer.getDvsFrame().isRectifyPolarities(), writer.getDvsFrame().isNormalizeFrame(), writer.getDvsFrame().isNormalizeDVSForZsNullhop(), writer.isShowOutput(), writer.getMaxFrames())); System.out.println("Successfully wrote file " + outfile + " with " + writer.getFramesWritten() + " frames"); System.exit(0); } public boolean isShowStatistics() { return showStatistics; } public void setShowStatistics(boolean showStatistics) { this.showStatistics = showStatistics; putBoolean("showStatistics", showStatistics); } /** * Writes the targets just before the timestamp to the target locations * file, if writeTargetLocation is true * * @param timestamp to search for targets just before timestamp * @throws IOException */ private void writeTargetLocation(int timestamp, int frameNumber) throws IOException { if (!writeTargetLocations) { return; } if (targetLabeler.hasLocations()) { ArrayList<TargetLabeler.TargetLocation> targets = targetLabeler.findTargetsBeforeTimestamp(timestamp); if (targets == null) { // log.warning(String.format("null labeled target locations for timestamp=%d, frameNumber=%d", timestamp, frameNumber)); targetLocationsWriter.write(String.format("%d %d %d -1 -1 -1 -1 -1\n", framesWritten, 0, timestamp)); } else { try { // TODO debug for (TargetLocation l : targets) { if ((l != null) && (l.location != null)) { // scale locations and size to AVI output resolution float scaleX = (float) dvsFrame.getOutputImageWidth() / chip.getSizeX(); float scaleY = (float) dvsFrame.getOutputImageHeight() / chip.getSizeY(); targetLocationsWriter.write(String.format("%d %d %d %d %d %d %d %d\n", framesWritten, 0, timestamp, Math.round(scaleX * l.location.x), Math.round(scaleY * l.location.y), l.targetClassID, l.width, l.height)); } else { targetLocationsWriter.write(String.format("%d %d %d -1 -1 -1 -1 -1\n", framesWritten, 0, timestamp)); } break; // skip rest of labels, write only 1 per frame } } catch (NullPointerException e) { log.warning("null pointer " + e); } } } } // stupid static class just to control writing and handle rewind event static class WriterControl { boolean writing = true; void end() { writing = false; } } /** * @return the writeDvsFrames */ public boolean isWriteDvsFrames() { return writeDvsFrames; } /** * @param writeDvsFrames the writeDvsFrames to set */ public void setWriteDvsFrames(boolean writeDvsFrames) { this.writeDvsFrames = writeDvsFrames; putBoolean("writeDvsFrames", writeDvsFrames); } /** * @return the writeApsFrames */ public boolean isWriteApsFrames() { return writeApsFrames; } /** * @param writeApsFrames the writeApsFrames to set */ public void setWriteApsFrames(boolean writeApsFrames) { this.writeApsFrames = writeApsFrames; putBoolean("writeApsFrames", writeApsFrames); } /** * @return the writeDvsEventsToTextFile */ public boolean isWriteDvsEventsToTextFile() { return writeDvsEventsToTextFile; } /** * @param writeDvsEventsToTextFile the writeDvsEventsToTextFile to set */ public void setWriteDvsEventsToTextFile(boolean writeDvsEventsToTextFile) { this.writeDvsEventsToTextFile = writeDvsEventsToTextFile; putBoolean("writeDvsEventsToTextFile", writeDvsEventsToTextFile); } /** * @return the writeTargetLocations */ public boolean isWriteTargetLocations() { return writeTargetLocations; } /** * @param writeTargetLocations the writeTargetLocations to set */ public void setWriteTargetLocations(boolean writeTargetLocations) { this.writeTargetLocations = writeTargetLocations; putBoolean("writeTargetLocations", writeTargetLocations); } }
package net.wigle.wigleandroid.listener; import static android.location.LocationManager.GPS_PROVIDER; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.Comparator; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import net.wigle.wigleandroid.ConcurrentLinkedHashMap; import net.wigle.wigleandroid.DashboardActivity; import net.wigle.wigleandroid.DatabaseHelper; import net.wigle.wigleandroid.ListActivity; import net.wigle.wigleandroid.Network; import net.wigle.wigleandroid.NetworkListAdapter; import net.wigle.wigleandroid.NetworkType; import net.wigle.wigleandroid.ListActivity.TrailStat; import org.osmdroid.util.GeoPoint; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.location.Location; import android.net.wifi.ScanResult; import android.net.wifi.WifiManager; import android.os.BatteryManager; import android.os.Handler; import android.telephony.CellLocation; import android.telephony.TelephonyManager; import android.telephony.gsm.GsmCellLocation; import android.widget.Toast; public class WifiReceiver extends BroadcastReceiver { private ListActivity listActivity; private final DatabaseHelper dbHelper; private NetworkListAdapter listAdapter; private SimpleDateFormat timeFormat; private NumberFormat numberFormat1; private Handler wifiTimer; private Location prevGpsLocation; private long scanRequestTime = Long.MIN_VALUE; private long lastScanResponseTime = Long.MIN_VALUE; private long lastWifiUnjamTime = Long.MIN_VALUE; private long lastSaveLocationTime = Long.MIN_VALUE; private int pendingWifiCount = 0; private int pendingCellCount = 0; private long previousTalkTime = System.currentTimeMillis(); private final Set<String> runNetworks = new HashSet<String>(); private long prevNewNetCount; private long prevNewCellCount; private long prevScanPeriod; public static final int SIGNAL_COMPARE = 10; public static final int CHANNEL_COMPARE = 11; public static final int CRYPTO_COMPARE = 12; public static final int FIND_TIME_COMPARE = 13; public static final int SSID_COMPARE = 14; private static final Comparator<Network> signalCompare = new Comparator<Network>() { public int compare( Network a, Network b ) { return b.getLevel() - a.getLevel(); } }; private static final Comparator<Network> channelCompare = new Comparator<Network>() { public int compare( Network a, Network b ) { return a.getFrequency() - b.getFrequency(); } }; private static final Comparator<Network> cryptoCompare = new Comparator<Network>() { public int compare( Network a, Network b ) { return b.getCrypto() - a.getCrypto(); } }; private static final Comparator<Network> findTimeCompare = new Comparator<Network>() { public int compare( Network a, Network b ) { return (int) (b.getConstructionTime() - a.getConstructionTime()); } }; private static final Comparator<Network> ssidCompare = new Comparator<Network>() { public int compare( Network a, Network b ) { return a.getSsid().compareTo( b.getSsid() ); } }; public WifiReceiver( final ListActivity listActivity, final DatabaseHelper dbHelper, final NetworkListAdapter listAdapter ) { this.listActivity = listActivity; this.dbHelper = dbHelper; this.listAdapter = listAdapter; ListActivity.lameStatic.runNetworks = runNetworks; // formats for speech timeFormat = new SimpleDateFormat( "h mm aa" ); numberFormat1 = NumberFormat.getNumberInstance( Locale.US ); if ( numberFormat1 instanceof DecimalFormat ) { ((DecimalFormat) numberFormat1).setMaximumFractionDigits( 1 ); } } public void setListActivity( final ListActivity listActivity ) { this.listActivity = listActivity; } public void setListAdapter( final NetworkListAdapter listAdapter ) { this.listAdapter = listAdapter; } public int getRunNetworkCount() { return runNetworks.size(); } @Override public void onReceive( final Context context, final Intent intent ){ final long now = System.currentTimeMillis(); lastScanResponseTime = now; // final long start = now; final WifiManager wifiManager = (WifiManager) listActivity.getSystemService(Context.WIFI_SERVICE); final List<ScanResult> results = wifiManager.getScanResults(); // return can be null! long nonstopScanRequestTime = Long.MIN_VALUE; final SharedPreferences prefs = listActivity.getSharedPreferences( ListActivity.SHARED_PREFS, 0 ); final long period = getScanPeriod(); if ( period == 0 ) { // treat as "continuous", so request scan in here doWifiScan(); nonstopScanRequestTime = now; } final long prefPeriod = prefs.getLong(ListActivity.GPS_SCAN_PERIOD, ListActivity.LOCATION_UPDATE_INTERVAL); long setPeriod = prefPeriod; if (setPeriod == 0 ){ setPeriod = Math.max(period, ListActivity.LOCATION_UPDATE_INTERVAL); } if ( setPeriod != prevScanPeriod && listActivity.isScanning() ) { // update our location scanning speed ListActivity.info("setting location updates to: " + setPeriod); listActivity.setLocationUpdates(setPeriod, 0f); prevScanPeriod = setPeriod; } final Location location = listActivity.getGPSListener().getLocation(); // save the location every minute, for later runs, or viewing map during loss of location. if (now - lastSaveLocationTime > 60000L && location != null) { listActivity.getGPSListener().saveLocation(); lastSaveLocationTime = now; } final boolean showCurrent = prefs.getBoolean( ListActivity.PREF_SHOW_CURRENT, true ); if ( showCurrent ) { listAdapter.clear(); } final int preQueueSize = dbHelper.getQueueSize(); final boolean fastMode = dbHelper.isFastMode(); final ConcurrentLinkedHashMap<String,Network> networkCache = ListActivity.getNetworkCache(); boolean somethingAdded = false; int resultSize = 0; int newWifiForRun = 0; // can be null on shutdown if ( results != null ) { resultSize = results.size(); for ( ScanResult result : results ) { Network network = networkCache.get( result.BSSID ); if ( network == null ) { network = new Network( result ); networkCache.put( network.getBssid(), network ); } else { // cache hit, just set the level network.setLevel( result.level ); } final boolean added = runNetworks.add( result.BSSID ); if ( added ) { newWifiForRun++; } somethingAdded |= added; if ( location != null && (added || network.getGeoPoint() == null) ) { // set the geopoint for mapping final GeoPoint geoPoint = new GeoPoint( location ); network.setGeoPoint( geoPoint ); } // if we're showing current, or this was just added, put on the list if ( showCurrent || added ) { listAdapter.add( network ); // load test // for ( int i = 0; i< 10; i++) { // listAdapter.add( network ); } else { // not showing current, and not a new thing, go find the network and update the level // this is O(n), ohwell, that's why showCurrent is the default config. for ( int index = 0; index < listAdapter.getCount(); index++ ) { final Network testNet = listAdapter.getItem(index); if ( testNet.getBssid().equals( network.getBssid() ) ) { testNet.setLevel( result.level ); } } } if ( dbHelper != null ) { if ( location != null ) { // if in fast mode, only add new-for-run stuff to the db queue if ( fastMode && ! added ) { ListActivity.info( "in fast mode, not adding seen-this-run: " + network.getBssid() ); } else { // loop for stress-testing // for ( int i = 0; i < 10; i++ ) { dbHelper.addObservation( network, location, added ); } } else { // no location dbHelper.pendingObservation( network, added ); } } } } // check if there are more "New" nets final long newNetCount = dbHelper.getNewNetworkCount(); final long newWifiCount = dbHelper.getNewWifiCount(); final long newNetDiff = newWifiCount - prevNewNetCount; prevNewNetCount = newWifiCount; // check for "New" cell towers final long newCellCount = dbHelper.getNewCellCount(); final long newCellDiff = newCellCount - prevNewCellCount; prevNewCellCount = newCellCount; if ( ! listActivity.isMuted() ) { final boolean playRun = prefs.getBoolean( ListActivity.PREF_FOUND_SOUND, true ); final boolean playNew = prefs.getBoolean( ListActivity.PREF_FOUND_NEW_SOUND, true ); if ( newNetDiff > 0 && playNew ) { listActivity.playNewNetSound(); } else if ( somethingAdded && playRun ) { listActivity.playRunNetSound(); } } // check cell tower info final int preCellForRun = runNetworks.size(); int newCellForRun = 0; final Network cellNetwork = recordCellInfo(location); if ( cellNetwork != null ) { resultSize++; if ( showCurrent ) { listAdapter.add(cellNetwork); } if ( runNetworks.size() > preCellForRun ) { newCellForRun++; } } final int sort = prefs.getInt(ListActivity.PREF_LIST_SORT, SIGNAL_COMPARE); Comparator<Network> comparator = signalCompare; switch ( sort ) { case SIGNAL_COMPARE: comparator = signalCompare; break; case CHANNEL_COMPARE: comparator = channelCompare; break; case CRYPTO_COMPARE: comparator = cryptoCompare; break; case FIND_TIME_COMPARE: comparator = findTimeCompare; break; case SSID_COMPARE: comparator = ssidCompare; break; } listAdapter.sort( comparator ); final long dbNets = dbHelper.getNetworkCount(); final long dbLocs = dbHelper.getLocationCount(); // update stat listActivity.setNetCountUI(); // set the statics for the map ListActivity.lameStatic.runNets = runNetworks.size(); ListActivity.lameStatic.newNets = newNetCount; ListActivity.lameStatic.newWifi = newWifiCount; ListActivity.lameStatic.newCells = newCellCount; ListActivity.lameStatic.currNets = resultSize; ListActivity.lameStatic.preQueueSize = preQueueSize; ListActivity.lameStatic.dbNets = dbNets; ListActivity.lameStatic.dbLocs = dbLocs; // do this if trail is empty, so as soon as we get first gps location it gets triggered // and will show up on map if ( newWifiForRun > 0 || newCellForRun > 0 || ListActivity.lameStatic.trail.isEmpty() ) { if ( location == null ) { // save for later pendingWifiCount += newWifiForRun; pendingCellCount += newCellForRun; // ListActivity.info("pendingCellCount: " + pendingCellCount); } else { final GeoPoint geoPoint = new GeoPoint( location ); TrailStat trailStat = ListActivity.lameStatic.trail.get( geoPoint ); if ( trailStat == null ) { trailStat = new TrailStat(); ListActivity.lameStatic.trail.put( geoPoint, trailStat ); } trailStat.newWifiForRun += newWifiForRun; trailStat.newWifiForDB += newNetDiff; // ListActivity.info("newCellForRun: " + newCellForRun); trailStat.newCellForRun += newCellForRun; trailStat.newCellForDB += newCellDiff; // add any pendings // don't go crazy if ( pendingWifiCount > 25 ) { pendingWifiCount = 25; } trailStat.newWifiForRun += pendingWifiCount; pendingWifiCount = 0; if ( pendingCellCount > 25 ) { pendingCellCount = 25; } trailStat.newCellForRun += pendingCellCount; pendingCellCount = 0; } } // info( savedStats ); // notify listAdapter.notifyDataSetChanged(); if ( scanRequestTime <= 0 ) { // wasn't set, set to now scanRequestTime = now; } final String status = resultSize + " scanned in " + (now - scanRequestTime) + "ms. DB Queue: " + preQueueSize; listActivity.setStatusUI( status ); // we've shown it, reset it to the nonstop time above, or min_value if nonstop wasn't set. scanRequestTime = nonstopScanRequestTime; // do lerp if need be if ( location == null ) { if ( prevGpsLocation != null ) { dbHelper.lastLocation( prevGpsLocation ); // ListActivity.info("set last location for lerping"); } } else { dbHelper.recoverLocations( location ); } // do distance calcs if ( location != null && GPS_PROVIDER.equals( location.getProvider() ) && location.getAccuracy() <= ListActivity.MIN_DISTANCE_ACCURACY ) { if ( prevGpsLocation != null ) { float dist = location.distanceTo( prevGpsLocation ); // info( "dist: " + dist ); if ( dist > 0f ) { final Editor edit = prefs.edit(); edit.putFloat( ListActivity.PREF_DISTANCE_RUN, dist + prefs.getFloat( ListActivity.PREF_DISTANCE_RUN, 0f ) ); edit.putFloat( ListActivity.PREF_DISTANCE_TOTAL, dist + prefs.getFloat( ListActivity.PREF_DISTANCE_TOTAL, 0f ) ); edit.commit(); } } // set for next time prevGpsLocation = location; } final long speechPeriod = prefs.getLong( ListActivity.PREF_SPEECH_PERIOD, ListActivity.DEFAULT_SPEECH_PERIOD ); if ( speechPeriod != 0 && now - previousTalkTime > speechPeriod * 1000L ) { doAnnouncement( preQueueSize, newWifiCount, newCellCount, now ); } } public String getNetworkTypeName() { TelephonyManager tele = (TelephonyManager) listActivity.getSystemService( Context.TELEPHONY_SERVICE ); if ( tele == null ) { return null; } switch (tele.getNetworkType()) { case TelephonyManager.NETWORK_TYPE_GPRS: return "GPRS"; case TelephonyManager.NETWORK_TYPE_EDGE: return "EDGE"; case TelephonyManager.NETWORK_TYPE_UMTS: return "UMTS"; case 4: return "CDMA"; case 5: return "CDMA - EvDo rev. 0"; case 6: return "CDMA - EvDo rev. A"; case 7: return "CDMA - 1xRTT"; case 8: return "HSDPA"; case 9: return "HSUPA"; case 10: return "HSPA"; case 11: return "IDEN"; case 12: return "CDMA - EvDo rev. B"; default: return "UNKNOWN"; } } private Network recordCellInfo(final Location location) { TelephonyManager tele = (TelephonyManager) listActivity.getSystemService( Context.TELEPHONY_SERVICE ); Network network = null; if ( tele != null ) { /* List<NeighboringCellInfo> list = tele.getNeighboringCellInfo(); for (final NeighboringCellInfo cell : list ) { ListActivity.info("neigh cell: " + cell + " class: " + cell.getClass().getCanonicalName() ); ListActivity.info("cid: " + cell.getCid()); // api level 5!!!! ListActivity.info("lac: " + cell.getLac() ); ListActivity.info("psc: " + cell.getPsc() ); ListActivity.info("net type: " + cell.getNetworkType() ); ListActivity.info("nettypename: " + getNetworkTypeName() ); } */ String bssid = null; NetworkType type = null; CellLocation cellLocation = null; try { cellLocation = tele.getCellLocation(); } catch ( NullPointerException ex ) { // bug in Archos7 can NPE there, just ignore } if ( cellLocation == null ) { // ignore } else if ( cellLocation.getClass().getSimpleName().equals("CdmaCellLocation") ) { try { final int systemId = (Integer) cellLocation.getClass().getMethod("getSystemId").invoke(cellLocation); final int networkId = (Integer) cellLocation.getClass().getMethod("getNetworkId").invoke(cellLocation); final int baseStationId = (Integer) cellLocation.getClass().getMethod("getBaseStationId").invoke(cellLocation); if ( systemId > 0 && networkId >= 0 && baseStationId >= 0 ) { bssid = systemId + "_" + networkId + "_" + baseStationId; type = NetworkType.CDMA; } } catch ( Exception ex ) { ListActivity.error("cdma reflection exception: " + ex); } } else if ( cellLocation instanceof GsmCellLocation ) { GsmCellLocation gsmCellLocation = (GsmCellLocation) cellLocation; if ( gsmCellLocation.getLac() >= 0 && gsmCellLocation.getCid() >= 0 ) { bssid = tele.getNetworkOperator() + "_" + gsmCellLocation.getLac() + "_" + gsmCellLocation.getCid(); type = NetworkType.GSM; } } if ( bssid != null ) { final String ssid = tele.getNetworkOperatorName(); final String networkType = getNetworkTypeName(); final String capabilities = networkType + ";" + tele.getNetworkCountryIso(); int strength = 0; PhoneState phoneState = listActivity.getPhoneState(); if (phoneState != null) { strength = phoneState.getStrength(); } if ( NetworkType.GSM.equals(type) ) { strength = gsmRssiMagicDecoderRing( strength ); } if ( false ) { ListActivity.info( "bssid: " + bssid ); ListActivity.info( "strength: " + strength ); ListActivity.info( "ssid: " + ssid ); ListActivity.info( "capabilities: " + capabilities ); ListActivity.info( "networkType: " + networkType ); ListActivity.info( "location: " + location ); } final ConcurrentLinkedHashMap<String,Network> networkCache = ListActivity.getNetworkCache(); final boolean newForRun = runNetworks.add( bssid ); network = networkCache.get( bssid ); if ( network == null ) { network = new Network( bssid, ssid, 0, capabilities, strength, type ); networkCache.put( network.getBssid(), network ); } else { network.setLevel(strength); } if ( location != null && (newForRun || network.getGeoPoint() == null) ) { // set the geopoint for mapping final GeoPoint geoPoint = new GeoPoint( location ); network.setGeoPoint( geoPoint ); } if ( location != null ) { dbHelper.addObservation(network, location, newForRun); } } } return network; } private int gsmRssiMagicDecoderRing( int strength ) { int retval = -113; if ( strength == 99 ) { // unknown retval = -113; } else { retval = ((strength - 31) * 2) - 51; } // ListActivity.info("strength: " + strength + " retval: " + retval); return retval; } private void doAnnouncement( int preQueueSize, long newWifiCount, long newCellCount, long now ) { final SharedPreferences prefs = listActivity.getSharedPreferences( ListActivity.SHARED_PREFS, 0 ); StringBuilder builder = new StringBuilder(); if ( listActivity.getGPSListener().getLocation() == null ) { builder.append( "no gps fix, " ); } // run, new, queue, miles, time, battery if ( prefs.getBoolean( ListActivity.PREF_SPEAK_RUN, true ) ) { builder.append( "run " ).append( runNetworks.size() ).append( ", " ); } if ( prefs.getBoolean( ListActivity.PREF_SPEAK_NEW_WIFI, true ) ) { builder.append( "new wifi " ).append( newWifiCount ).append( ", " ); } if ( prefs.getBoolean( ListActivity.PREF_SPEAK_NEW_CELL, true ) ) { builder.append( "new cell " ).append( newCellCount ).append( ", " ); } if ( preQueueSize > 0 && prefs.getBoolean( ListActivity.PREF_SPEAK_QUEUE, true ) ) { builder.append( "queue " ).append( preQueueSize ).append( ", " ); } if ( prefs.getBoolean( ListActivity.PREF_SPEAK_MILES, true ) ) { final float dist = prefs.getFloat( ListActivity.PREF_DISTANCE_RUN, 0f ); final String distString = DashboardActivity.metersToString( numberFormat1, listActivity, dist, false ); builder.append( "from " ).append( distString ); } if ( prefs.getBoolean( ListActivity.PREF_SPEAK_TIME, true ) ) { String time = timeFormat.format( new Date() ); // time is hard to say. time = time.replace(" 00", " owe clock"); time = time.replace(" 0", " owe "); builder.append( time ).append( ", " ); } final int batteryLevel = listActivity.getBatteryLevelReceiver().getBatteryLevel(); if ( batteryLevel >= 0 && prefs.getBoolean( ListActivity.PREF_SPEAK_BATTERY, true ) ) { builder.append( "battery " ).append( batteryLevel ).append( " percent, " ); } ListActivity.info( "speak: " + builder.toString() ); listActivity.speak( builder.toString() ); previousTalkTime = now; } public void setupWifiTimer( final boolean turnedWifiOn ) { ListActivity.info( "create wifi timer" ); if ( wifiTimer == null ) { wifiTimer = new Handler(); final Runnable mUpdateTimeTask = new Runnable() { public void run() { // make sure the app isn't trying to finish if ( ! listActivity.isFinishing() ) { // info( "timer start scan" ); doWifiScan(); if ( scanRequestTime <= 0 ) { scanRequestTime = System.currentTimeMillis(); } long period = getScanPeriod(); // check if set to "continuous" if ( period == 0L ) { // set to default here, as a scan will also be requested on the scan result listener period = ListActivity.SCAN_DEFAULT; } // info("wifitimer: " + period ); wifiTimer.postDelayed( this, period ); } else { ListActivity.info( "finishing timer" ); } } }; wifiTimer.removeCallbacks( mUpdateTimeTask ); wifiTimer.postDelayed( mUpdateTimeTask, 100 ); if ( turnedWifiOn ) { ListActivity.info( "not immediately running wifi scan, since it was just turned on" + " it will block for a few seconds and fail anyway"); } else { ListActivity.info( "start first wifi scan"); // starts scan, sends event when done final boolean scanOK = doWifiScan(); if ( scanRequestTime <= 0 ) { scanRequestTime = System.currentTimeMillis(); } ListActivity.info( "startup finished. wifi scanOK: " + scanOK ); } } } public long getScanPeriod() { final SharedPreferences prefs = listActivity.getSharedPreferences( ListActivity.SHARED_PREFS, 0 ); String scanPref = ListActivity.PREF_SCAN_PERIOD; long defaultRate = ListActivity.SCAN_DEFAULT; // if over 5 mph final Location location = listActivity.getGPSListener().getLocation(); if ( location != null && location.getSpeed() >= 2.2352f ) { scanPref = ListActivity.PREF_SCAN_PERIOD_FAST; defaultRate = ListActivity.SCAN_FAST_DEFAULT; } else if ( location == null || location.getSpeed() < 0.1f ) { scanPref = ListActivity.PREF_SCAN_PERIOD_STILL; defaultRate = ListActivity.SCAN_STILL_DEFAULT; } return prefs.getLong( scanPref, defaultRate ); } public void scheduleScan() { wifiTimer.post(new Runnable() { public void run() { doWifiScan(); } }); } /** * only call this from a Handler * @return */ private boolean doWifiScan() { // ListActivity.info("do wifi scan. lastScanTime: " + lastScanResponseTime); final WifiManager wifiManager = (WifiManager) listActivity.getSystemService(Context.WIFI_SERVICE); boolean retval = false; if ( listActivity.isUploading() ) { ListActivity.info( "uploading, not scanning for now" ); // reset this lastScanResponseTime = Long.MIN_VALUE; } else if (listActivity.isScanning()){ retval = wifiManager.startScan(); final long now = System.currentTimeMillis(); if ( lastScanResponseTime < 0 ) { // use now, since we made a request lastScanResponseTime = now; } else { final long sinceLastScan = now - lastScanResponseTime; final SharedPreferences prefs = listActivity.getSharedPreferences( ListActivity.SHARED_PREFS, 0 ); final long resetWifiPeriod = prefs.getLong( ListActivity.PREF_RESET_WIFI_PERIOD, ListActivity.DEFAULT_RESET_WIFI_PERIOD ); if ( resetWifiPeriod > 0 && sinceLastScan > resetWifiPeriod ) { ListActivity.warn("Time since last scan: " + sinceLastScan + " milliseconds"); if ( lastWifiUnjamTime < 0 || now - lastWifiUnjamTime > resetWifiPeriod ) { Toast.makeText( listActivity, "Wifi appears jammed, Turning off, and then on, WiFi.", Toast.LENGTH_LONG ).show(); wifiManager.setWifiEnabled(false); wifiManager.setWifiEnabled(true); lastWifiUnjamTime = now; listActivity.speak("Warning, latest wifi scan completed " + (sinceLastScan / 1000L) + " seconds ago. Restarting wifi."); } } } } else { // scanning is off. since we're the only timer, update the UI listActivity.setNetCountUI(); listActivity.setLocationUI(); listActivity.setStatusUI( "Scanning Turned Off" ); // keep the scan times from getting huge scanRequestTime = System.currentTimeMillis(); // reset this lastScanResponseTime = Long.MIN_VALUE; } // battery kill if ( ! listActivity.isUploading() ) { final SharedPreferences prefs = listActivity.getSharedPreferences( ListActivity.SHARED_PREFS, 0 ); final long batteryKill = prefs.getLong( ListActivity.PREF_BATTERY_KILL_PERCENT, ListActivity.DEFAULT_BATTERY_KILL_PERCENT); if ( listActivity.getBatteryLevelReceiver() != null ) { final int batteryLevel = listActivity.getBatteryLevelReceiver().getBatteryLevel(); final int batteryStatus = listActivity.getBatteryLevelReceiver().getBatteryStatus(); // ListActivity.info("batteryStatus: " + batteryStatus); if ( batteryKill > 0 && batteryLevel > 0 && batteryLevel <= batteryKill && batteryStatus != BatteryManager.BATTERY_STATUS_CHARGING) { final String text = "Battery level at " + batteryLevel + " percent, shutting down Wigle Wifi"; Toast.makeText( listActivity, text, Toast.LENGTH_LONG ).show(); listActivity.speak( "low battery" ); listActivity.finish(); } } } return retval; } }
package net.wurstclient.features.commands; import java.lang.reflect.Field; import java.util.Collection; import java.util.Comparator; import java.util.TreeMap; import net.minecraft.crash.CrashReport; import net.minecraft.crash.CrashReportCategory; import net.minecraft.util.ReportedException; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.event.ClickEvent; import net.minecraft.util.text.event.ClickEvent.Action; import net.wurstclient.WurstClient; import net.wurstclient.events.ChatOutputEvent; import net.wurstclient.events.listeners.ChatOutputListener; import net.wurstclient.features.commands.Cmd.CmdSyntaxError; import net.wurstclient.utils.ChatUtils; public final class CmdManager implements ChatOutputListener { private final TreeMap<String, Cmd> cmds = new TreeMap<>(new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } }); public final AddAltCmd addAltCmd = new AddAltCmd(); public final AnnoyCmd annoyCmd = new AnnoyCmd(); public final AuthorCmd authorCmd = new AuthorCmd(); public final BindsCmd bindsCmd = new BindsCmd(); public final BlinkCmd blinkCmd = new BlinkCmd(); public final ClearCmd clearCmd = new ClearCmd(); public final CopyItemCmd copyitemCmd = new CopyItemCmd(); public final DamageCmd damageCmd = new DamageCmd(); public final DropCmd dropCmd = new DropCmd(); public final EnchantCmd enchantCmd = new EnchantCmd(); public final FeaturesCmd featuresCmd = new FeaturesCmd(); public final FollowCmd followCmd = new FollowCmd(); public final FriendsCmd friendsCmd = new FriendsCmd(); public final GetPosCmd getPosCmd = new GetPosCmd(); public final GhostHandCmd ghostHandCmd = new GhostHandCmd(); public final GiveCmd giveCmd = new GiveCmd(); public final GmCmd gmCmd = new GmCmd(); public final GoToCmd goToCmd = new GoToCmd(); public final HelpCmd HhelpCmd = new HelpCmd(); public final InvseeCmd invseeCmd = new InvseeCmd(); public final IpCmd ipCmd = new IpCmd(); public final JumpCmd jumpCmd = new JumpCmd(); public final LeaveCmd leaveCmd = new LeaveCmd(); public final ModifyCmd modifyCmd = new ModifyCmd(); public final NothingCmd nothingCmd = new NothingCmd(); public final NukerCmd nukerCmd = new NukerCmd(); public final PathCmd pathCmd = new PathCmd(); public final PotionCmd potionCmd = new PotionCmd(); public final ProtectCmd protectCmd = new ProtectCmd(); public final RenameCmd renameCmd = new RenameCmd(); public final RepairCmd repairCmd = new RepairCmd(); public final RvCmd rvCmd = new RvCmd(); public final SvCmd svCmd = new SvCmd(); public final SayCmd sayCmd = new SayCmd(); public final SearchCmd searchCmd = new SearchCmd(); public final SetCheckboxCmd setCheckboxCmd = new SetCheckboxCmd(); public final SetModeCmd setModeCmd = new SetModeCmd(); public final SetSliderCmd setSliderCmd = new SetSliderCmd(); public final SpammerCmd spammerCmd = new SpammerCmd(); public final TacoCmd tacoCmd = new TacoCmd(); public final TCmd tCmd = new TCmd(); public final ThrowCmd throwCmd = new ThrowCmd(); public final TpCmd tpCmd = new TpCmd(); public final VClipCmd vClipCmd = new VClipCmd(); public final WmsCmd wmsCmd = new WmsCmd(); public final XRayCmd xRayCmd = new XRayCmd(); public CmdManager() { try { for(Field field : CmdManager.class.getFields()) if(field.getName().endsWith("Cmd")) { Cmd cmd = (Cmd)field.get(this); cmds.put(cmd.getCmdName(), cmd); } }catch(Exception e) { e.printStackTrace(); } } @Override public void onSentMessage(ChatOutputEvent event) { if(!WurstClient.INSTANCE.isEnabled()) return; String message = event.getMessage(); if(message.startsWith(".")) { event.cancel(); String input = message.substring(1); String commandName = input.split(" ")[0]; String[] args; if(input.contains(" ")) args = input.substring(input.indexOf(" ") + 1).split(" "); else args = new String[0]; Cmd cmd = getCommandByName(commandName); if(cmd != null) try { cmd.execute(args); }catch(CmdSyntaxError e) { if(e.getMessage() != null) ChatUtils .message("4Syntax error:r " + e.getMessage()); else ChatUtils.message("4Syntax error!r"); cmd.printSyntax(); }catch(Cmd.CmdError e) { ChatUtils.error(e.getMessage()); }catch(Throwable e) { CrashReport crashReport = CrashReport.makeCrashReport(e, "Running Wurst command"); CrashReportCategory crashReportCategory = crashReport.makeCategory("Affected command"); crashReportCategory.setDetail("Command input", () -> message); throw new ReportedException(crashReport); } else switch(message) { case "...": case ".legit": ITextComponent link = new TextComponentString("more info"); link.getStyle().setColor(TextFormatting.AQUA) .setClickEvent(new ClickEvent(Action.OPEN_URL, "https: ChatUtils .component(new TextComponentString("Try using .say (") .appendSibling(link).appendText(")")); break; default: ChatUtils.error( "\"." + commandName + "\" is not a valid command."); break; } } } public Cmd getCommandByName(String name) { return cmds.get(name); } public Collection<Cmd> getAllCommands() { return cmds.values(); } public int countCommands() { return cmds.size(); } }
package org.spine3.base; import com.google.common.base.Optional; import com.google.common.reflect.TypeToken; import com.google.protobuf.Timestamp; import com.google.protobuf.util.Timestamps; import java.text.ParseException; import java.util.regex.Pattern; import static com.google.common.base.Preconditions.checkNotNull; import static java.lang.String.format; import static org.spine3.util.Exceptions.conversionArgumentException; /** * Utility class for working with {@code Stringifier}s. * * @author Alexander Yevsyukov * @author Illia Shepilov */ public class Stringifiers { private Stringifiers() { // Disable instantiation of this utility class. } public static <I> String toString(I valueToConvert, TypeToken<I> typeToken) { checkNotNull(valueToConvert); checkNotNull(typeToken); final Stringifier<I> stringifier = getStringifier(typeToken); final String result = stringifier.convert(valueToConvert); return result; } public static <I> I parse(String valueToParse, TypeToken<I> typeToken) { checkNotNull(valueToParse); checkNotNull(typeToken); final Stringifier<I> stringifier = getStringifier(typeToken); final I result = stringifier.reverse() .convert(valueToParse); return result; } private static <I> Stringifier<I> getStringifier(TypeToken<I> typeToken) { final Optional<Stringifier<I>> stringifierOptional = StringifierRegistry.getInstance() .get(typeToken); if (!stringifierOptional.isPresent()) { final String exMessage = format("Stringifier for the %s is not provided", typeToken); throw conversionArgumentException(exMessage); } final Stringifier<I> stringifier = stringifierOptional.get(); return stringifier; } protected static class TimestampStringifer extends Stringifier<Timestamp> { private static final Pattern PATTERN_COLON = Pattern.compile(":"); private static final Pattern PATTERN_T = Pattern.compile("T"); @Override protected String doForward(Timestamp timestamp) { final String result = toString(timestamp); return result; } @Override protected Timestamp doBackward(String s) { try { return Timestamps.parse(s); } catch (ParseException ignored) { throw conversionArgumentException("Occurred exception during conversion"); } } /** * Converts the passed timestamp to the string. * * @param timestamp the value to convert * @return the string representation of the timestamp */ private static String toString(Timestamp timestamp) { String result = Timestamps.toString(timestamp); result = PATTERN_COLON.matcher(result) .replaceAll("-"); result = PATTERN_T.matcher(result) .replaceAll("_T"); return result; } } protected static class EventIdStringifier extends Stringifier<EventId> { @Override protected String doForward(EventId eventId) { final String result = eventId.getUuid(); return result; } @Override protected EventId doBackward(String s) { final EventId result = EventId.newBuilder() .setUuid(s) .build(); return result; } } protected static class CommandIdStringifier extends Stringifier<CommandId> { @Override protected String doForward(CommandId commandId) { final String result = commandId.getUuid(); return result; } @Override protected CommandId doBackward(String s) { final CommandId result = CommandId.newBuilder() .setUuid(s) .build(); return result; } } }
package org.spine3.validate; import com.google.protobuf.Message; import com.google.protobuf.Timestamp; import org.spine3.base.CommandId; import org.spine3.base.EventId; import org.spine3.protobuf.TypeName; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static org.spine3.base.Identifiers.EMPTY_ID; import static org.spine3.base.Identifiers.idToString; /** * This class provides general validation routines. * * @author Alexander Yevsyukov */ public class Validate { private static final String MUST_BE_A_POSITIVE_VALUE = "%s must be a positive value"; private static final String MUST_BE_IN_BOUNDS = "%s should be in bounds of %d and %d values inclusive. Found: %d"; private Validate() { } /** * Verifies if the passed message object is its default state and is not {@code null}. * * @param object the message to inspect * @return true if the message is in the default state, false otherwise */ public static boolean isDefault(Message object) { checkNotNull(object); final boolean result = object.getDefaultInstanceForType() .equals(object); return result; } /** * Verifies if the passed message object is not its default state and is not {@code null}. * * @param object the message to inspect * @return true if the message is not in the default state, false otherwise */ public static boolean isNotDefault(Message object) { checkNotNull(object); final boolean result = !isDefault(object); return result; } public static <M extends Message> M checkNotDefault(M object, @Nullable Object errorMessage) { checkNotNull(object); checkState(isNotDefault(object), errorMessage); return object; } @SuppressWarnings("OverloadedVarargsMethod") public static <M extends Message> M checkNotDefault(M object, String errorMessageTemplate, Object... errorMessageArgs) { checkNotNull(object); checkState(isNotDefault(object), errorMessageTemplate, errorMessageArgs); return object; } public static <M extends Message> M checkNotDefault(M object) { checkNotNull(object); checkNotDefault(object, "The message is in the default state: %s", TypeName.of(object)); return object; } public static <M extends Message> M checkDefault(M object, @Nullable Object errorMessage) { checkNotNull(object); checkState(isDefault(object), errorMessage); return object; } @SuppressWarnings("OverloadedVarargsMethod") public static <M extends Message> M checkDefault(M object, String errorMessageTemplate, Object... errorMessageArgs) { checkNotNull(object); checkState(isDefault(object), errorMessageTemplate, errorMessageArgs); return object; } public static <M extends Message> M checkDefault(M object) { checkNotNull(object); if (!isDefault(object)) { final String typeName = TypeName.of(object); final String errorMessage = "The message is not in the default state: " + typeName; throw new IllegalStateException(errorMessage); } return object; } public static void checkParameter(boolean expression, String parameterName, String errorMessageFormat) { if (!expression) { final String errorMessage = String.format(errorMessageFormat, parameterName); throw new IllegalArgumentException(errorMessage); } } public static String checkNotEmptyOrBlank(String stringToCheck, String fieldName) { checkNotNull(stringToCheck, fieldName + " must not be null."); checkParameter(!stringToCheck.isEmpty(), fieldName, "%s must not be an empty string."); checkParameter(stringToCheck.trim() .length() > 0, fieldName, "%s must not be a blank string."); return stringToCheck; } public static Timestamp checkPositive(Timestamp timestamp, String argumentName) { checkNotNull(timestamp, argumentName); checkParameter(timestamp.getSeconds() > 0, argumentName, "%s must have a positive number of seconds."); checkParameter(timestamp.getNanos() >= 0, argumentName, "%s must not have a negative number of nanoseconds."); return timestamp; } public static void checkPositive(long value) { checkPositive(value, ""); } public static void checkPositive(long value, String argumentName) { checkParameter(value > 0L, argumentName, MUST_BE_A_POSITIVE_VALUE); } public static void checkPositiveOrZero(long value) { checkArgument(value >= 0); } /** * Ensures that target value is in between passed bounds. * * @param value target value * @param paramName value name * @param lowBound lower bound to check * @param highBound higher bound */ public static void checkBounds(int value, String paramName, int lowBound, int highBound) { if (!isBetween(value, lowBound, highBound)) { final String errMsg = String.format(MUST_BE_IN_BOUNDS, paramName, lowBound, highBound, value); throw new IllegalArgumentException(errMsg); } } private static boolean isBetween(int value, int lowBound, int highBound) { return lowBound <= value && value <= highBound; } public static EventId checkValid(EventId id) { checkNotNull(id); checkNotEmptyOrBlank(id.getUuid(), "event ID"); return id; } public static CommandId checkValid(CommandId id) { checkNotNull(id); final String idStr = idToString(id); checkArgument(!idStr.equals(EMPTY_ID), "Command ID must not be an empty string."); return id; } }
// FILE: c:/projects/jetel/org/jetel/data/DateDataField.java package org.jetel.data; import java.util.*; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharsetEncoder; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharacterCodingException; import java.sql.Timestamp; import java.text.DateFormat; import java.text.ParseException; import java.text.ParsePosition; import java.text.SimpleDateFormat; import org.jetel.exception.BadDataFormatException; import org.jetel.metadata.DataFieldMetadata; /** * A class that represents ... * * @author D.Pavlis * @since March 28, 2002 * @revision $Revision$ * @created January 26, 2003 * @see OtherClasses */ public class DateDataField extends DataField { // Attributes /** * An attribute that represents ... * * @since March 28, 2002 */ private Date value; private DateFormat dateFormat; private ParsePosition parsePosition; private final static int FIELD_SIZE_BYTES = 8;// standard size of field // Associations // Operations /** * Constructor for the DateDataField object * * @param _metadata Description of Parameter * @since April 23, 2002 */ public DateDataField(DataFieldMetadata _metadata) { super(_metadata); Locale locale; // handle locale if (_metadata.getLocaleStr()!=null){ String[] localeLC=_metadata.getLocaleStr().split(Defaults.DEFAULT_LOCALE_STR_DELIMITER_REGEX); if (localeLC.length>1){ locale=new Locale(localeLC[0],localeLC[1]); }else{ locale=new Locale(localeLC[0]); } //probably wrong locale string defined if (locale==null){ throw new RuntimeException("Can't create Locale based on "+_metadata.getLocaleStr()); } }else{ locale=null; } // handle format string String formatString; formatString = _metadata.getFormatStr(); if ((formatString != null) && (formatString.length() != 0)) { if (locale!=null){ dateFormat = new SimpleDateFormat(formatString,locale); }else{ dateFormat = new SimpleDateFormat(formatString); } dateFormat.setLenient(false); } else if (locale!=null){ dateFormat = DateFormat.getDateInstance(DateFormat.DEFAULT,locale); dateFormat.setLenient(false); } if (dateFormat!=null){ parsePosition = new ParsePosition(0); } } /** * Constructor for the DateDataField object * * @param _metadata Description of Parameter * @param _value Description of Parameter * @since April 23, 2002 */ public DateDataField(DataFieldMetadata _metadata, Date _value) { this(_metadata); setValue(_value); } /** * Private constructor to be used internally when clonning object. * Optimized for performance. Many checks waved. * * @param _metadata * @param _value * @param _dateFormat */ private DateDataField(DataFieldMetadata _metadata, Date _value, DateFormat _dateFormat){ super(_metadata); setValue(_value); this.dateFormat=_dateFormat; this.parsePosition= (_dateFormat!=null) ? new ParsePosition(0) : null; } /* (non-Javadoc) * @see org.jetel.data.DataField#copy() */ public DataField duplicate(){ DateDataField newField=new DateDataField(metadata,value,dateFormat); newField.setNull(isNull()); return newField; } /* (non-Javadoc) * @see org.jetel.data.DataField#copyField(org.jetel.data.DataField) */ public void copyFrom(DataField fromField){ if (fromField instanceof DateDataField){ if (!fromField.isNull){ this.value.setTime(((DateDataField)fromField).value.getTime()); } setNull(fromField.isNull); } } /** * Sets the date represented by DateDataField object * * @param _value The new Value value * @exception BadDataFormatException Description of the Exception * @since April 23, 2002 */ public void setValue(Object _value) throws BadDataFormatException { if ( _value instanceof Date ) { if (value==null){ value = new Date(((Date) _value).getTime()); }else{ value.setTime(((Date) _value).getTime()); } setNull(false); }else if (_value instanceof Timestamp){ if (value==null){ value = new Date(((Timestamp)_value).getTime()); }else{ value.setTime(((Timestamp)_value).getTime()); } setNull(false); }else { if (this.metadata.isNullable()) { value = null; super.setNull(true); } else { throw new BadDataFormatException(getMetadata().getName() + " field can not be set with this object - " + _value.toString(), _value.toString()); } } } /** * Sets the date represented by DateDataField object * * @param time the number of milliseconds since January 1, 1970, 00:00:00 GM */ public void setValue(long time){ if (value==null){ value = new Date(time); }else{ value.setTime(time); } setNull(false); } /** * Gets the date represented by DateDataField object * * @return The Value value * @since April 23, 2002 */ public Object getValue() { return value; } /** * Gets the date attribute of the DateDataField object * * @return The date value */ public Date getDate() { return value; } /** * Sets the Null value indicator * * @param isNull The new Null value * @since October 29, 2002 */ public void setNull(boolean isNull) { super.setNull(isNull); if (isNull) { setValue(null); } } /** * Gets the DataField type * * @return The Type value * @since April 23, 2002 */ public char getType() { return DataFieldMetadata.DATE_FIELD; } /** * Formats the internal date value into a string representation.<b> If * metadata describing DateField contains formating string, that string is * used to create output. Otherwise the standard format is used. * * @return Description of the Returned Value * @since April 23, 2002 */ public String toString() { if (value == null) { return ""; } if ((dateFormat != null)) { return dateFormat.format(value); } else { return value.toString(); } } /** * Description of the Method * * @param dataBuffer Description of Parameter * @param decoder Description of Parameter * @exception CharacterCodingException Description of Exception * @since October 31, 2002 */ public void fromByteBuffer(ByteBuffer dataBuffer, CharsetDecoder decoder) throws CharacterCodingException { fromString(decoder.decode(dataBuffer).toString()); } /** * Description of the Method * * @param dataBuffer Description of Parameter * @param encoder Description of Parameter * @exception CharacterCodingException Description of Exception * @since October 31, 2002 */ public void toByteBuffer(ByteBuffer dataBuffer, CharsetEncoder encoder) throws CharacterCodingException { dataBuffer.put(encoder.encode(CharBuffer.wrap(toString()))); } /** * Parses date value from string representation. If format string is defined, * then it is used as expected pattern. * * @param _valueStr Description of Parameter * @since April 23, 2002 */ public void fromString(String _valueStr) { //parsePosition.setIndex(0); if (_valueStr == null || _valueStr.equals("")) { if (this.metadata.isNullable()) { value = null; super.setNull(true); } else { throw new BadDataFormatException(getMetadata().getName() + " field can not be set to null!(nullable=false)", _valueStr); } return; } try { if (dateFormat != null) { value = dateFormat.parse(_valueStr);//, parsePosition); } else { value = SimpleDateFormat.getDateInstance().parse(_valueStr); } super.setNull(false); } catch (ParseException e) { super.setNull(true); throw new BadDataFormatException("not a Date", _valueStr); } } /** * Performs serialization of the internal value into ByteBuffer (used when * moving data records between components). * * @param buffer Description of Parameter * @since April 23, 2002 */ public void serialize(ByteBuffer buffer) { if (value != null) { buffer.putLong(value.getTime()); } else { buffer.putLong(0); } } /** * Performs deserialization of data * * @param buffer Description of Parameter * @since April 23, 2002 */ public void deserialize(ByteBuffer buffer) { long tmpl = buffer.getLong(); if (tmpl == 0) { setValue(null); return; } if (value == null) { value = new Date(tmpl); } else { value.setTime(tmpl); } setNull(false); } /** * Description of the Method * * @param obj Description of Parameter * @return Description of the Returned Value * @since April 23, 2002 */ public boolean equals(Object obj) { return (this.value.equals((((DateDataField) obj).getValue()))); } /** * Compares this object with the specified object for order * * @param obj Description of the Parameter * @return Description of the Return Value */ public int compareTo(Object obj) { if (obj instanceof Date){ return value.compareTo((Date) obj); }else if (obj instanceof DateDataField){ return value.compareTo(((DateDataField) obj).getDate()); }else throw new RuntimeException("Object does not represent a Date value: "+obj); } /** * Description of the Method * * @param obj Description of the Parameter * @return Description of the Return Value */ public int compareTo(java.util.Date obj) { return value.compareTo(obj); } public int hashCode(){ return value.hashCode(); } /** * Gets the size attribute of the IntegerDataField object * * @return The size value * @see org.jetel.data.DataField */ public int getSizeSerialized() { return FIELD_SIZE_BYTES; } } /* * end class DateDataField */
package net.aoringo.ircex.cmd; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Objects; import java.util.logging.Level; import java.util.logging.Logger; /** * Sends command to the UI. * * @author mikan */ public class Commander { private static final String DEFAULT_HOST = "localhost:10000"; private static final Logger LOG = Logger.getLogger(Commander.class.getSimpleName()); /** * Main method. * * @param args args[0]: command (required), args[1]: host:port (optional) */ public static void main(String[] args) { if (args == null || args.length == 0) { LOG.severe("Commander: You must specify a command."); return; } String command = args[0]; String host = args.length == 1 ? DEFAULT_HOST : args[1]; LOG.log(Level.INFO, "Commander: Sending command: {0}", command); try { new Commander().executePost(command, host); } catch (IOException ex) { LOG.log(Level.SEVERE, "Sending failed: {0}", ex.getMessage()); } } public void executePost(String command) throws IOException { executePost(command, DEFAULT_HOST); } public void executePost(String command, String host) throws IOException { Objects.requireNonNull(command); Objects.requireNonNull(host); String hostWithPort = host; if (!host.contains(":")) { hostWithPort += ":10000"; } HttpURLConnection connection = null; try { // Request URL url = new URL("http://" + hostWithPort + "/"); LOG.log(Level.INFO, "URL: {0}", url.toString()); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setInstanceFollowRedirects(false); connection.connect(); String parameter = "command=" + command; try (PrintWriter writer = new PrintWriter(connection.getOutputStream())) { writer.print(parameter); } LOG.log(Level.INFO, "Request sent."); // Response int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { try (BufferedReader reader = new BufferedReader( new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } LOG.info("Sending succeeded."); } else { LOG.log(Level.SEVERE, "Sending failed: HTTP {0}", responseCode); } } catch (MalformedURLException ex) { throw new IllegalArgumentException("Malformed URL.", ex); } finally { if (connection != null) { connection.disconnect(); } } } }
package org.TexasTorque.TorqueLib.util; import com.sun.squawk.io.BufferedWriter; import com.sun.squawk.microedition.io.*; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.Watchdog; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Hashtable; import javax.microedition.io.*; public class TorqueLogging extends Thread { private static TorqueLogging instance; private FileConnection fileConnection = null; private BufferedWriter fileIO = null; private static String fileName = "TorqueLog.txt"; private String filePath = "file:///ni-rt/startup/"; private static boolean logToDashboard = false; private static long threadLoopTime = 2; private Hashtable table; private String keys; private String values; private int numLines; public static void setFileName(String fileNm) { fileName = fileNm; } public static void setDashboardLogging(boolean log) { logToDashboard = log; } public static void setLoopTime(int loopTime) { threadLoopTime = loopTime; } public synchronized static TorqueLogging getInstance() { return (instance == null) ? instance = new TorqueLogging() : instance; } public TorqueLogging() { try { fileConnection = (FileConnection) Connector.open(filePath + fileName); if(!fileConnection.exists()) { fileConnection.create(); fileIO = new BufferedWriter(new OutputStreamWriter(fileConnection.openOutputStream())); } else { fileIO = new BufferedWriter(new OutputStreamWriter(fileConnection.openOutputStream())); } } catch(IOException e) { System.err.println("Error creating file in TorqueLogging."); } table = new Hashtable(); keys = "FrameNumber,"; values = ""; numLines = 1; table.put("FrameNumber", "" + numLines); } public void startLogging() { this.start(); } public void init() { if(logToDashboard) { SmartDashboard.putString("TorqueLog", keys); } else { writeKeysToFile(); } } public void run() { init(); DriverStation ds = DriverStation.getInstance(); Watchdog dog = Watchdog.getInstance(); while(true) { dog.feed(); while(ds.isDisabled()) { dog.feed(); } calculateValueString(); if(logToDashboard) { SmartDashboard.putString("TorqueLog", values); } else { writeValuesToFile(); } this.logValue("FrameNumber", numLines++); try { Thread.sleep(threadLoopTime); try { fileIO.flush(); } catch (IOException ex){} } catch (InterruptedException ex){} } } public synchronized void setKeyMapping(String mapping) { table.clear(); if(mapping.charAt(mapping.length() - 1) != ',') { mapping += ","; } keys = mapping; int start = 0; int index = 0; while(index != -1) { Watchdog.getInstance().feed(); index = keys.indexOf(",", start); if(index != -1) { String keyName = keys.substring(start, index); table.put(keyName, "0"); start = index + 1; } } } public synchronized void logValue(String name, int value) { if(table.get(name) == null) { keys += name + ","; } table.put(name, "" + value); } public synchronized void logValue(String name, boolean value) { if(table.get(name) == null) { keys += name + ","; } table.put(name, "" + value); } public synchronized void logValue(String name, double value) { if(table.get(name) == null) { keys += name + ","; } table.put(name, "" + value); } public synchronized void logValue(String name, String value) { if(table.get(name) == null) { keys += name + ","; } table.put(name, value); } private void writeKeysToFile() { try { fileIO.write(keys.substring(0, keys.length() - 1)); } catch(IOException e){} } private void calculateValueString() { values = ""; int start = 0; int index = 0; boolean first = true; while(index != -1) { index = keys.indexOf(",", start); if(index != -1) { String keyName = keys.substring(start, index); if(first) { values += table.get(keyName); first = false; } else { values += "," + table.get(keyName); } start = index + 1; } } } private void writeValuesToFile() { try { fileIO.newLine(); fileIO.write(values); } catch(IOException e){} } }
package org.concord.data.state; import java.io.IOException; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.util.Vector; import java.util.logging.Logger; import org.concord.data.Unit; import org.concord.data.stream.DataStoreUtil; import org.concord.data.stream.ProducerDataStore; import org.concord.framework.data.stream.DataChannelDescription; import org.concord.framework.data.stream.DataProducer; import org.concord.framework.data.stream.DataStoreEvent; import org.concord.framework.data.stream.DataStoreListener; import org.concord.framework.data.stream.DataStreamDescription; import org.concord.framework.data.stream.WritableArrayDataStore; import org.concord.framework.otrunk.OTChangeEvent; import org.concord.framework.otrunk.OTChangeListener; import org.concord.framework.otrunk.OTObject; import org.concord.framework.otrunk.OTObjectList; import org.concord.framework.otrunk.OTObjectService; import org.concord.framework.otrunk.OTResourceList; /** * OTDataStoreRealObject * * This object is synchronized with a OTDataStore object using the OTDataStoreController class * it partially supports the use of virtual or incrementing channels. But * * Date created: Nov 18, 2004 * * @author scytacki<p> * */ public class OTDataStoreRealObject extends ProducerDataStore implements WritableArrayDataStore { private static final Logger logger = Logger .getLogger(OTDataStoreRealObject.class.getCanonicalName()); protected OTDataStore otDataStore; DataStoreEvent changeEvent = new DataStoreEvent(this, DataStoreEvent.DATA_CHANGED); DataStoreEvent removeEvent = new DataStoreEvent(this, DataStoreEvent.DATA_REMOVED); // Because the OTDataStore is slow we need to cache the properties here so access can be faster private int numChannels; private boolean virtualChannels; private float dt; private OTResourceList values; private OTChangeListener myListener = new OTChangeListener(){ public void stateChanged(OTChangeEvent e) { if("values".equals(e.getProperty())){ String op = e.getOperation(); if(OTChangeEvent.OP_ADD == op){ notifyDataAdded(); } else if(OTChangeEvent.OP_CHANGE == op || OTChangeEvent.OP_SET == op){ notifyDataChanged(); } else if(OTChangeEvent.OP_REMOVE == op || OTChangeEvent.OP_REMOVE_ALL == op){ notifyDataRemoved(); } } else if("numberChannels".equals(e.getProperty())){ numChannels = otDataStore.getNumberChannels(); } else if("virtualChannels".equals(e.getProperty())){ virtualChannels = otDataStore.isVirtualChannels(); } else if("dt".equals(e.getProperty())){ dt = otDataStore.getDt(); } } }; public void setOTDataStore(OTDataStore otDataStore) { this.otDataStore = otDataStore; // We need to listen to the otDataStore so when it changes we can // throw a datastore change or remove event otDataStore.addOTChangeListener(myListener); // Save these values for performance numChannels = otDataStore.getNumberChannels(); virtualChannels = otDataStore.isVirtualChannels(); dt = otDataStore.getDt(); // This is typically a bad idea incase the data object changes underneath // but for performance it is better. values = otDataStore.getValues(); String valueStr = otDataStore.getValuesString(); if(valueStr == null) return; otDataStore.setValuesString(null); try { DataStoreUtil.loadData(valueStr, this, false); } catch ( IOException e) { e.printStackTrace(); } } /* (non-Javadoc) * @see org.concord.framework.data.stream.DataStore#clearValues() */ public void clearValues() { values.removeAll(); // this will happen when otDataStore notifies our listener that the data was removed // notifyDataRemoved(); } /* (non-Javadoc) * @see org.concord.framework.data.stream.DataStore#getTotalNumChannels() */ public int getTotalNumChannels() { int otNumberOfChannels = numChannels; if(otNumberOfChannels == -1) return 1; // If virtual channels is turned on and there is a dt then // the first channel is not stored directly in the otDataStore. // the numberChannels property refers to the number of channels actually // in the values property. if(isIncrementalChannel(0)){ otNumberOfChannels++; } return otNumberOfChannels; } /* (non-Javadoc) * @see org.concord.framework.data.stream.DataStore#getTotalNumSamples() */ public synchronized int getTotalNumSamples() { int dataArrayStride = getDataArrayStride(); if(dataArrayStride == 0){ System.err.println("Warning OTDataStoreRealObject is being used without initializing the number of channels"); return 0; } // scytacki: it is an interesting question if the a data store should return it has // a sample even if it is partial sample. Because there isn't a way to tell if a sample // is complete or not it seems safer to only report complete samples. int size = values.size(); int rows = size / dataArrayStride; if (size % dataArrayStride > 0){ logger.finest("requesting the number of samples while the data store has a partial sample"); } return rows; } /** * @see org.concord.framework.data.stream.DataStore#getValueAt(int, int) */ public synchronized Object getValueAt(int numSample, int numChannel) { //Special case: when dt is a channel, it's the channel -1 if (isIncrementalChannel(numChannel)){ return new Float(numSample * getIncrement()); } int index = getIndex(numSample, numChannel); if(index >= values.size()) { return null; } else if (index < 0){ return null; } return values.get(index); } /** * This method returns the index into the dataArray of a particular * channel and sample. It takes virtual channels into account. * * @param sampleNumber * @param channelNumber * @return */ public int getIndex(int sampleNumber, int channelNumber) { if(isIncrementalChannel(0)){ // the auto incrementing channel is 0 so we aren't storing that // in the data array, so the channel being searched for should // be reduced by one. if(channelNumber == 0){ System.err.println("Trying to lookup the auto increment channel"); return Integer.MIN_VALUE; } channelNumber } int dataArrayStride = getDataArrayStride(); if(channelNumber >= dataArrayStride) { throw new IndexOutOfBoundsException("Trying to lookup an invalid channel: " + channelNumber); } return sampleNumber * dataArrayStride + channelNumber; } /** * Return the size of a row in the values list (dataArray). * * @return */ protected int getDataArrayStride() { // this used to always be the totalNumChannels but with virtual // channels this can be one less than that. int numChannels = getTotalNumChannels(); if(isIncrementalChannel(0)){ return numChannels - 1; } return numChannels; } public void setValueAt(int numSample, int numChannel, Object value) { int numChannels = getTotalNumChannels(); if(numChannel >= numChannels) { // FIXME // increase the number of channels // if we have existing data then we need to insert a lot of nulls // or something to fill the space. numChannels = numChannel+1; if(isIncrementalChannel(0)){ numChannels } otDataStore.setNumberChannels(numChannels); } int index = getIndex(numSample, numChannel); if(index >= values.size()) { //System.out.println("add new value at "+index); //Add empty values until we get to the desired index int j = values.size(); for (; j < index; j++){ values.add(j, null); } values.add(index, value); } else { values.set(index, value); } /* * This real object doesn't need to send out notifications directly. Because the line: * values.set() or values.add() modify the OTResourceList, that causes an event to be * sent out by the OTDataStore object. Which is then caught by our inner class "myListener", * and at that point the standard data store event is sent out. * */ } public void setValues(int numbChannels,float []values) { otDataStore.setDoNotifyChangeListeners(false); // If this datastore is using virtual channels then should // the passed in values actually start at channel 1 not channel 0 for(int i=0;i<values.length;i++) { int channelNumber = i%numbChannels; setValueAt(i/numbChannels, channelNumber, new Float(values[i])); } otDataStore.setDoNotifyChangeListeners(true); notifyOTValuesChange(); } /** * Adds a value to the channel indicated * If the channel doesn't exist, it doesn't do anything * * @param numChannel channel number, starting from 0, >0 * @param value value to add */ protected void addValue(int numSample, int numChannel, Object value) { setValueAt(numSample, numChannel, value); } protected void addSamples(float [] values, int offset, int numberOfSamples, int localNextSampleOffset) { synchronized(otDataStore) { otDataStore.setDoNotifyChangeListeners(false); int numChannels = getNumberOfProducerChannels(); int firstSample = getTotalNumSamples(); int firstChannelOffset = 0; if(isIncrementalChannel(0)){ firstChannelOffset = 1; } for(int i=0; i<numberOfSamples; i++) { for(int j=0; j<numChannels; j++) { Float value = new Float(values[offset+(i*localNextSampleOffset)+j]); setValueAt(firstSample + i, firstChannelOffset + j, value); } } otDataStore.setDoNotifyChangeListeners(true); } notifyOTValuesChange(); } protected void replaceSamples(float [] values, int numberOfSamples) { synchronized(otDataStore) { otDataStore.setDoNotifyChangeListeners(false); int numChannels = getNumberOfProducerChannels(); for(int i=0; i<numberOfSamples; i++) { Float value = new Float(values[i]); addValue(i, 0, value); } otDataStore.setDoNotifyChangeListeners(true); } notifyOTValuesChange(); } protected void notifyOTValuesChange() { otDataStore.notifyOTChange("values", OTChangeEvent.OP_CHANGE, null, null); } protected void notifyOTValuesRemove() { otDataStore.notifyOTChange("values", OTChangeEvent.OP_REMOVE, null, null); } /** * @see org.concord.framework.data.stream.WritableDataStore#removeSampleAt(int) */ public void removeSampleAt(int numSample) { int index = getIndex(numSample, 0); otDataStore.setDoNotifyChangeListeners(false); int dataArrayStride = getDataArrayStride(); for(int i=0; i<dataArrayStride; i++) { values.remove(index); } otDataStore.setDoNotifyChangeListeners(true); notifyOTValuesRemove(); } /** * @see org.concord.framework.data.stream.WritableDataStore#insertSampleAt(int) */ public void insertSampleAt(int numSample) { int index = getIndex(numSample, 0); otDataStore.setDoNotifyChangeListeners(false); int dataArrayStride = getDataArrayStride(); for(int i=0; i<dataArrayStride; i++) { values.add(index, null); } otDataStore.setDoNotifyChangeListeners(true); notifyOTValuesChange(); } public void setDataProducer(DataProducer dataProducer) { super.setDataProducer(dataProducer); } /** * This is currently the only way to set the number of channels. * * @see org.concord.framework.data.stream.WritableDataStore#setDataChannelDescription(int, org.concord.framework.data.stream.DataChannelDescription) */ @Override public void setDataChannelDescription(int channelIndex, DataChannelDescription desc) { // FIXME this is not fully supported yet // if 0 is the auto increment channel then the number of channels of this data store is // one less because it doesn't store data for the incremental channel. if(isIncrementalChannel(0)){ channelIndex } if(channelIndex < numChannels){ return; } if(getTotalNumSamples() > 0){ logger.warning("There is data in the data store and the number of channels is being changed"); } otDataStore.setNumberChannels(channelIndex+1); } /* (non-Javadoc) * @see org.concord.framework.data.stream.DataStore#getDataChannelDescription(int) */ public DataChannelDescription getDataChannelDescription(int numChannel) { if(getDataProducer() != null) { // need to make sure that these values are saved // so if this data store is disconnected from the // the data producer it will preserve this info if (dataStreamDesc == null) return null; //Special case: if the channel equals the incrementing channel // then return the dt channel description. if (isIncrementalChannel(numChannel)){ return dataStreamDesc.getDtChannelDescription(); } // shift the channel down if the incremental channel is 0 // in that case channel 0 of the data store is actually the // dt channel, and channel 1 of the data store is actually // channel 0 of the dataProducer. if (isIncrementalChannel(0)){ numChannel } return dataStreamDesc.getChannelDescription(numChannel); } // If we have an incremental channel, then ot channel description at index // 0 describes the incremental channel, and the ot channel description at 1 is // the first real channel description. // A caller of this method can request the incremental channel description either // by passing in -1 or 0 depending of virtualChannels are enabled. // If virtualChannels are enabled and there is a incremental channel, // then the caller passes in 0 to get the incremental description. // If virtualChannels are not enabled and there is a incremental channel, // then the caller passes in -1 to get the incremental description. int otChannelDescriptionIndex = numChannel; // If -1 is the incremental channel then increase the channel description so // the correct one in the OT channel descriptions list is used if(isIncrementalChannel(-1)){ otChannelDescriptionIndex++; } OTObjectList channelDescriptions = otDataStore.getChannelDescriptions(); if(otChannelDescriptionIndex >= channelDescriptions.size()) { return null; } OTDataChannelDescription otChDesc = (OTDataChannelDescription)channelDescriptions.get(otChannelDescriptionIndex); DataChannelDescription chDesc = new DataChannelDescription(); chDesc.setAbsoluteMax(otChDesc.getAbsoluteMax()); chDesc.setAbsoluteMin(otChDesc.getAbsoluteMin()); chDesc.setNumericData(otChDesc.getNumericData()); chDesc.setLocked(otChDesc.getLocked()); chDesc.setName(otChDesc.getName()); int precision = otChDesc.getPrecision(); if(precision != Integer.MAX_VALUE) { chDesc.setPrecision(precision); } chDesc.setRecommendMax(otChDesc.getRecommendMax()); chDesc.setRecommendMin(otChDesc.getRecommendMin()); String unitStr = otChDesc.getUnit(); Unit unit = Unit.findUnit(unitStr); chDesc.setUnit(unit); chDesc.getPossibleValues().addAll(otChDesc.getPossibleValues()); return chDesc; } protected OTDataChannelDescription createOTDataChannelDescription(DataChannelDescription dCDesc) throws Exception { OTObjectService objService = otDataStore.getOTObjectService(); OTDataChannelDescription otDCDesc = objService.createObject(OTDataChannelDescription.class); if(dCDesc == null){ return otDCDesc; } otDCDesc.setName(dCDesc.getName()); if(dCDesc.getUnit() != null){ otDCDesc.setUnit(dCDesc.getUnit().getDimension()); } float absMax = dCDesc.getAbsoluteMax(); if(!Float.isNaN(absMax)){ otDCDesc.setAbsoluteMax(absMax); } float absMin = dCDesc.getAbsoluteMin(); if(!Float.isNaN(absMin)){ otDCDesc.setAbsoluteMin(absMin); } float recMax = dCDesc.getRecommendMax(); if(!Float.isNaN(recMax)){ otDCDesc.setRecommendMax(recMax); } float recMin = dCDesc.getRecommendMin(); if(!Float.isNaN(recMin)){ otDCDesc.setRecommendMin(recMin); } if(dCDesc.isUsePrecision()){ otDCDesc.setPrecision(dCDesc.getPrecision()); } otDCDesc.setNumericData(dCDesc.isNumericData()); for (Object o : dCDesc.getPossibleValues()) { if (o instanceof OTObject) { otDCDesc.getPossibleValues().add((OTObject)o); } } return otDCDesc; } protected void updateDataDescription(DataStreamDescription desc) { super.updateDataDescription(desc); // Save all the dataChannelDescriptions if(desc == null){ return; } try { otDataStore.getChannelDescriptions().clear(); if(isAutoIncrementing()){ // if we are using the dt as a channel then the first element in the channelDescriptions list // is the channel description of the dt DataChannelDescription dCDesc = desc.getDtChannelDescription(); OTDataChannelDescription otDCDesc = createOTDataChannelDescription(dCDesc); otDataStore.getChannelDescriptions().add(otDCDesc); } for(int i=0; i<desc.getChannelsPerSample(); i++){ DataChannelDescription dCDesc = desc.getChannelDescription(i); if(dCDesc == null){ System.err.println("Warning: null data channel description: " + i); } OTDataChannelDescription otDCDesc = createOTDataChannelDescription(dCDesc); otDataStore.getChannelDescriptions().add(otDCDesc); } // initialize the number of samples the datastore is going to be using, if this // data store is using virtual channels and there is a dt channel this should // be the actual number of channels - 1. int channelsPerSample = desc.getChannelsPerSample(); otDataStore.setNumberChannels(channelsPerSample); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /* (non-Javadoc) * @see org.concord.framework.data.stream.WritableArrayDataStore#setDt(float) */ public void setDt(float dt) { otDataStore.setDt(dt); } /** * This returns the dt of the datastore. If there is no * dt it returns Float.NaN */ public float getIncrement() { return dt; } /** * @return Returns the useDtAsChannel. */ public boolean isAutoIncrementing() { return !Float.isNaN(dt); } /** * @param useDtAsChannel The useDtAsChannel to set. */ public void setUseDtAsChannel(boolean useDtAsChannel) { if(!useDtAsChannel) { setDt(Float.NaN); } else { if(Float.isNaN(getIncrement())) { System.err.println("Warning: trying to use dt as a channel without a valid value"); } } } /* (non-Javadoc) * @see org.concord.framework.data.stream.WritableArrayDataStore#setValues(int, float[], int, int, int) */ public void setValues(int numChannels, float[] values, int offset, int numSamples, int nextSampleOffset) { otDataStore.setDoNotifyChangeListeners(false); // If this data store is using virtual channels what do we do here? // assume the values are starting at channel 1? for(int i=0; i<numSamples*nextSampleOffset; i+=nextSampleOffset) { for(int j=0;j<numChannels;j++) { Float fValue = new Float(values[offset+i+j]); setValueAt(i/nextSampleOffset, j, fValue); } } otDataStore.setDoNotifyChangeListeners(true); notifyOTValuesChange(); } public void setUseVirtualChannels(boolean flag) { otDataStore.setVirtualChannels(flag); } public boolean useVirtualChannels() { return virtualChannels; } /** * @see org.concord.framework.data.stream.DataStore#addDataStoreListener(org.concord.framework.data.stream.DataStoreListener) */ public void addDataStoreListener(DataStoreListener l) { WeakReference ref = new WeakReference(l); if (!dataStoreListeners.contains(ref)){ dataStoreListeners.add(ref); } } /** * @see org.concord.framework.data.stream.DataStore#removeDataStoreListener(org.concord.framework.data.stream.DataStoreListener) */ public void removeDataStoreListener(DataStoreListener l) { Vector listenersClone = (Vector) dataStoreListeners.clone(); for(int i=0; i<listenersClone.size(); i++){ WeakReference listenerRef = (WeakReference) listenersClone.get(i); if(listenerRef.get() == l){ dataStoreListeners.remove(listenerRef); } } } protected void notifyDataAdded() { DataStoreEvent evt = new DataStoreEvent(this, DataStoreEvent.DATA_ADDED); DataStoreListener l; for (int i=0; i<dataStoreListeners.size(); i++){ Reference ref = (Reference)dataStoreListeners.elementAt(i); l = (DataStoreListener)ref.get(); // ignore references that have been gc'd if(l == null) continue; l.dataAdded(evt); } } protected void notifyDataRemoved() { DataStoreEvent evt = new DataStoreEvent(this, DataStoreEvent.DATA_REMOVED); DataStoreListener l; // Clone our listeners so they can remove them selves from the list // without the vector up. Vector listenersClone = (Vector) dataStoreListeners.clone(); for (int i=0; i<listenersClone.size(); i++){ Reference ref = (Reference)listenersClone.elementAt(i); l = (DataStoreListener)ref.get(); // ignore references that have been gc'd if(l == null) continue; l.dataRemoved(evt); } } protected void notifyDataChanged() { DataStoreEvent evt = new DataStoreEvent(this, DataStoreEvent.DATA_ADDED); DataStoreListener l; for (int i=0; i<dataStoreListeners.size(); i++){ Reference ref = (Reference)dataStoreListeners.elementAt(i); l = (DataStoreListener)ref.get(); // ignore references that have been gc'd if(l == null) continue; l.dataChanged(evt); } } protected void notifyChannelDescChanged() { DataStoreEvent evt = new DataStoreEvent(this, DataStoreEvent.DATA_DESC_CHANGED); DataStoreListener l; for (int i=0; i<dataStoreListeners.size(); i++){ Reference ref = (Reference)dataStoreListeners.elementAt(i); l = (DataStoreListener)ref.get(); // ignore references that have been gc'd if(l == null) continue; l.dataChannelDescChanged(evt); } } }
package org.ensembl.healthcheck; import org.ensembl.healthcheck.configuration.ConfigurationUserParameters; import org.ensembl.healthcheck.util.SqlTemplate; import uk.co.flamingpenguin.jewel.cli.Option; /** * Copies certain configuration properties into system properties. They are * used by some healthchecks, but also by modules like the {@link ReportManager}. * * {@link org.ensembl.healthcheck.util.DBUtils} used to use system properties * as well, but has been refactored to take in a configuration object and use * that instead. * */ public class SystemPropertySetter { protected final ConfigurationUserParameters configuration; public SystemPropertySetter(ConfigurationUserParameters configuration) { this.configuration = configuration; } public void setPropertiesForReportManager_createDatabaseSession() { System.setProperty("output.password", configuration.getOutputPassword()); System.setProperty("host", configuration.getHost() ); System.setProperty("port", configuration.getPort() ); System.setProperty("output.release", configuration.getOutputRelease() ); } public void setPropertiesForReportManager_connectToOutputDatabase() { System.setProperty("output.driver", configuration.getDriver()); System.setProperty( "output.databaseURL", "jdbc:mysql: + configuration.getOutputHost() + ":" + configuration.getOutputPort() + "/" ); System.setProperty("output.database", configuration.getOutputDatabase()); System.setProperty("output.user", configuration.getOutputUser()); System.setProperty("output.password", configuration.getOutputPassword()); } /** * Sets system properties for the healthchecks. * */ public void setPropertiesForHealthchecks() { if (configuration.isBiotypesFile()) { // Used in: // org.ensembl.healthcheck.testcase.generic.Biotypes System.setProperty("biotypes.file", configuration.getBiotypesFile()); } if (configuration.isIgnorePreviousChecks()) { // Used in: // org.ensembl.healthcheck.testcase.generic.ComparePreviousVersionExonCoords // org.ensembl.healthcheck.testcase.generic.ComparePreviousVersionBase // org.ensembl.healthcheck.testcase.generic.GeneStatus System.setProperty("ignore.previous.checks", configuration.getIgnorePreviousChecks()); } if (configuration.isSchemaFile()) { // Used in: // org.ensembl.healthcheck.testcase.generic.CompareSchema System.setProperty("schema.file", configuration.getSchemaFile()); } if (configuration.isVariationSchemaFile()) { // Used in: // org.ensembl.healthcheck.testcase.variation.CompareVariationSchema System.setProperty("variation_schema.file", configuration.getVariationSchemaFile()); } if (configuration.isFuncgenSchemaFile()) { // Used in: // org.ensembl.healthcheck.testcase.funcgen.CompareFuncgenSchema System.setProperty("funcgen_schema.file", configuration.getFuncgenSchemaFile()); } if (configuration.isMasterSchema()) { // Used in: // org.ensembl.healthcheck.testcase.generic.CompareSchema // org.ensembl.healthcheck.testcase.funcgen.CompareFuncgenSchema System.setProperty("master.schema", configuration.getMasterSchema()); } if (configuration.isLogicnamesFile()) { // Used in: // org.ensembl.healthcheck.testcase.generic.LogicNamesDisplayable System.setProperty("logicnames.file", configuration.getLogicnamesFile()); } if (configuration.isPerl()) { // Used in: // org.ensembl.healthcheck.testcase.AbstractPerlBasedTestCase System.setProperty( org.ensembl.healthcheck.testcase.AbstractPerlBasedTestCase.PERL, configuration.getPerl() ); } if (configuration.isMasterVariationSchema()) { // Used in: // org.ensembl.healthcheck.testcase.variation.CompareVariationSchema System.setProperty("master.variation_schema", configuration.getMasterVariationSchema()); } if (configuration.isUserDir()) { // Used in: // org.ensembl.healthcheck.testcase.EnsTestCase System.setProperty("user.dir", configuration.getUserDir()); } if (configuration.isFileSeparator()) { // Used in: // org.ensembl.healthcheck.testcase.EnsTestCase System.setProperty("file.separator", configuration.getFileSeparator()); } if (configuration.isDriver()) { // Used in: // org.ensembl.healthcheck.testcase.EnsTestCase System.setProperty("driver", configuration.getDriver()); } if (configuration.isDatabaseURL()) { // Used in: // org.ensembl.healthcheck.testcase.EnsTestCase System.setProperty("databaseURL", configuration.getDatabaseURL()); } else { // Used in: // org.ensembl.healthcheck.testcase.EnsTestCase importSchema // when running CompareSchema tests. I have absolutely no idea where // the this is supposed to get set in the legacy code. System.setProperty( "databaseURL", "jdbc:mysql: + configuration.getHost() + ":" + configuration.getPort() + "/" ); } if (configuration.isUser()) { // Used in: // org.ensembl.healthcheck.testcase.EnsTestCase System.setProperty("user", configuration.getUser()); } if (configuration.isPassword()) { // Used in: // org.ensembl.healthcheck.testcase.EnsTestCase System.setProperty("password", configuration.getPassword()); } if (configuration.isMasterFuncgenSchema()) { // Used in: // org.ensembl.healthcheck.testcase.funcgen.CompareFuncgenSchema System.setProperty("master.funcgen_schema", configuration.getMasterFuncgenSchema()); } } }
package org.ensembl.healthcheck.testcase; import java.io.*; import java.util.*; import java.sql.*; import java.util.logging.*; import org.ensembl.healthcheck.*; import org.ensembl.healthcheck.util.*; /** * <p>The EnsTestCase class is the base class for all test cases in the EnsEMBL Healthcheck system. * <em>It is not intended to be instantiated directly</em>; subclasses should implement the <code>run()</code> * method and use that to provide test-case specific behaviour.</p> * *<p>EnsTestCase provides a number of methods which are intended to make writing test cases simple; in many cases * an extension test case will involve little more than calling one of the methods in this class and * setting some return value based on the result.</p> * * <p>For example, the following test case gets a {@link org.ensembl.healthcheck.util.DatabaseConnectionIterator DatabaseConnectionIterator}, then uses it to loop over each * affected database and call the <code>countOrphans()</code> method in EnsTestCase. In this particular situation, * if there are any orphans in any of the databases, the test fails.</p> * <pre> * public class OrphanTestCase extends EnsTestCase { * * public OrphanTestCase() { * databaseRegexp = "^homo_sapiens_core_\\d.*"; * addToGroup("group2"); * } * * TestResult run() { * * boolean result = true; * * DatabaseConnectionIterator it = getDatabaseConnectionIterator(); * * while (it.hasNext()) { * * Connection con = (Connection)it.next(); * int orphans = super.countOrphans(con, "gene", "gene_id", "gene_stable_id", "gene_id", false); * result &= (orphans == 0); * * } * * return new TestResult(getShortTestName(), result, ""); * * } * * } // OrphanTestCase * </pre> * * <p>Most test cases you write will take this form:</p> * <ol> * <li>Set up the database regexp and any groups that this test case is a member of; Note that all tests by * default are members of a group called "all". There is no need to explicitly add your new test to this group.</li> * <li>Implement the run() method; normally this will involve getting a DatabaseConnectionIterator, * calling one or more superclass methods on each database connection.</li> * <li>Create and return a TestResult object according to the results of your tests.</li> * </ol> * * */ public abstract class EnsTestCase { /** Regexp that, when combined with a species name, will match core databases */ protected static final String CORE_DB_REGEXP = "\\w+_\\w+_(core|est|estgene|vega)_\\d+_.*"; /** The TestRunner associated with this EnsTestCase */ protected TestRunner testRunner; /** The regular expression to match the names of the databases that the test case will apply to. */ protected String databaseRegexp = CORE_DB_REGEXP; /** If set, this is applied to the database names before databaseRegexp. */ protected String preFilterRegexp = ""; /** A list of Strings representing the groups that this test is a member of. * All tests are members of the group "all", and also of a group with the same name as the test. */ protected List groups; /** Each test has a set of conditions that it needs to be fulfilled in order for it to run */ protected List conditions; /** Description field */ protected String description; /** Logger object to use */ protected static Logger logger = Logger.getLogger("HealthCheckLogger"); /** * Creates a new instance of EnsTestCase */ public EnsTestCase() { groups = new ArrayList(); addToGroup("all"); // everything is in all, by default addToGroup(getShortTestName()); // each test is in a one-test group setDescription("No description set for this test."); conditions = new ArrayList(); } // EnsTestCase /** * The principal run method. Subclasses of EnsTestCase should implement this * to provide test-specific behaviour. * @return A TestResult object representing the result of the test. */ public abstract TestResult run(); /** * Get the TestRunner that is controlling this EnsTestCase. * @return The parent TestRunner. */ public TestRunner getTestRunner() { return testRunner; } // getTestRunner /** * Sets up this test. <B>Must</B> be called before the object is used. * @param tr The TestRunner to associate with this test. Usually just <CODE>this</CODE> * if being called from the TestRunner. */ public void init(TestRunner tr) { this.testRunner = tr; } // init /** * Gets the full name of this test. * @return The full name of the test, e.g. org.ensembl.healthcheck.EnsTestCase */ public String getTestName() { return this.getClass().getName(); } /** * Gets the full name of this test. * @return The full name of the test, e.g. org.ensembl.healthcheck.EnsTestCase */ public String getName() { return this.getClass().getName(); } /** * Get the short form of the test name, ie the name of the test class without the * package qualifier. * * @return The short test name, e.g. EnsTestCase */ public String getShortTestName() { String longName = getTestName(); return longName.substring(longName.lastIndexOf('.')+1); } /** * Get the very short form of the test name; i.e. that returned by getShortTestName() without the trailing "TestCase" * * @return The very short test name, e.g. CheckMetaTables */ public String getVeryShortTestName() { String name = getShortTestName(); return name.substring(0, name.lastIndexOf("TestCase")); } /** * Get a list of the names of the groups which this test case is a member of. * @return The list of names as Strings. */ public List getGroups() { return groups; } /** * Get a list of the groups that this test case is a member of, formatted for easy * printing. * @return The comma-separated list of group names. */ public String getCommaSeparatedGroups() { StringBuffer gString = new StringBuffer(); java.util.Iterator it = groups.iterator(); while (it.hasNext()) { gString.append((String)it.next()); if (it.hasNext()) { gString.append(","); } } return gString.toString(); } /** * Convenience method for assigning this test case to several groups at once. * @param s A list of Strings containing the group names. */ public void setGroups(List s) { groups = s; } /** * Convenience method for assigning this test case to several groups at once. * @param s Array of group names. */ public void setGroups(String[] s) { for (int i = 0; i < s.length; i++) { groups.add(s[i]); } } /** * Add this test case to a new group. * If the test case is already a member of the group, a warning is printed and * it is not added again. * @param newGroupName The name of the new group. */ public void addToGroup(String newGroupName) { if (!groups.contains(newGroupName)) { groups.add(newGroupName); } else { logger.warning(getTestName() + " is already a member of " + newGroupName + " not added again."); } } // addToGroup /** * Remove this test case from the specified group. * If the test case is not a member of the specified group, a warning is printed. * @param groupName The name of the group from which this test case is to be removed. */ public void removeFromGroup(String groupName) { if (groups.contains(groupName)) { groups.remove(groupName); } else { logger.warning(getTestName() + " was not a memeber of " + groupName); } } // removeFromGroup /** * Test if this test case is a member of a particular group. * @param group The name of the group to check. * @return True if this test case is a member of the named group, false otherwise. */ public boolean inGroup(String group) { return groups.contains(group); } /** * Convenience method for checking if this test case belongs to any of several groups. * @param checkGroups The list of group names to check. * @return True if this test case is in any of the groups, false if it is in none. */ public boolean inGroups(List checkGroups) { boolean result = false; java.util.Iterator it = checkGroups.iterator(); while (it.hasNext()) { if (inGroup((String)it.next())) { result = true; } } return result; } // inGroups /** * Get a list of the databases matching a particular pattern. * Uses pre-filter regexp if it is defined. * @return The list of database names matched. */ public String[] getAffectedDatabases() { return testRunner.getListOfDatabaseNames(databaseRegexp); } // getAffectedDatabases /** * Convenience method to return a DatabaseConnectionIterator from the * parent TestRunner class, with the current database regular expression. * @return A new DatabaseConnectionIterator. */ public DatabaseConnectionIterator getDatabaseConnectionIterator() { return testRunner.getDatabaseConnectionIterator(databaseRegexp); } /** * Prints (to stdout) all the databases that match the current class' database regular expression. * Uses pre-filter regexp if it is defined. */ public void printAffectedDatabases() { System.out.println("Databases matching " + databaseRegexp + ":"); String[] databaseList = getAffectedDatabases(); Utils.printArray(databaseList); for (int i = 0; i < databaseList.length; i++) { System.out.println("\t\t" + databaseList[i]); } } // printAffectedDatabases /** * Count the number of rows in a table. * @param con The database connection to use. Should have been opened already. * @param table The name of the table to analyse. * @return The number of rows in the table. */ public int countRowsInTable(Connection con, String table) { if (con == null) { logger.severe("countRowsInTable: Database connection is null"); } return getRowCount(con, "SELECT COUNT(*) FROM " + table); } // countRowsInTable /** * Use SELECT COUNT(*) to get a row count. */ private int getRowCountFast(Connection con, String sql) { int result = -1; try { Statement stmt = con.createStatement(); //System.out.println("Executing " + sql); ResultSet rs = stmt.executeQuery(sql); if (rs != null) { if (rs.first()) { result = rs.getInt(1); } else { result = -1; // probably signifies an empty ResultSet } } rs.close(); stmt.close(); } catch (Exception e) { e.printStackTrace(); } return result; } // getRowCountFast /** * Use a row-by-row approach to counting the rows in a table. */ private int getRowCountSlow(Connection con, String sql) { int result = -1; try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql); if (rs != null) { if (rs.last()) { result = rs.getRow(); } else { result = -1; // probably signifies an empty ResultSet } } rs.close(); stmt.close(); } catch (Exception e) { e.printStackTrace(); } return result; } // getRowCountSlow /** * Count the rows in a particular table or query. * @param con A connection to the database. Should already be open. * @param sql The SQL to execute. Note that if possible this should begin with <code>SELECT COUNT FROM</code> * since this is much quicker to execute. If a standard SELECT statement is used, a row-by-row count will * be performed, which may be slow if the table is large. * @return The number of matching rows, or -1 if the query did not execute for some reason. */ public int getRowCount(Connection con, String sql) { if (con == null) { logger.severe("getRowCount: Database connection is null"); } int result = -1; // check if the SQL starts with SELECT COUNT - if so it's a lot quicker if (sql.toLowerCase().indexOf("select count") >= 0) { result = getRowCountFast(con, sql); } else { // if not, do it row-by-row logger.warning("getRowCount() executing SQL which does not appear to begin with SELECT COUNT - performing row-by-row count, which may take a long time if the table is large."); result = getRowCountSlow(con, sql); } return result; } // getRowCount /** * Execute a SQL statement and return the value of one column of one row. * Only the FIRST row matched is returned. * @param con The Connection to use. * @param sql The SQL to check; should return ONE value. * @return The value returned by the SQL. */ public String getRowColumnValue(Connection con, String sql) { String result = ""; try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql); if (rs != null && rs.first()) { result = rs.getString(1); } rs.close(); stmt.close(); } catch (Exception e) { e.printStackTrace(); } return result; } // getRowColumnValue /** * Execute a SQL statement and return the values of one column of the result. * @param con The Connection to use. * @param sql The SQL to check; should return ONE column. * @return The value(s) making up the column, in the order that they were read. */ public String[] getColumnValues(Connection con, String sql) { ArrayList list = new ArrayList(); try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql); if (rs != null) { while (rs.next()) { list.add(rs.getString(1)); } } } catch (Exception e) { e.printStackTrace(); } return (String[])list.toArray(new String[list.size()]); } // getRowColumnValue /** * Verify foreign-key relations. * @param con A connection to the database to be tested. Should already be open. * @param table1 With col1, specifies the first key to check. * @param col1 Column in table1 to check. * @param table2 With col2, specifies the second key to check. * @param col2 Column in table2 to check. * @param oneWayOnly If false, only a "left join" is performed on table1 and table2. If false, the * @return The number of "orphans" */ public int countOrphans(Connection con, String table1, String col1, String table2, String col2, boolean oneWayOnly) { if (con == null) { logger.severe("countOrphans: Database connection is null"); } int resultLeft, resultRight; String sql = " FROM " + table1 + " LEFT JOIN " + table2 + " ON " + table1 + "." + col1 + " = " + table2 + "." + col2 + " WHERE " + table2 + "." + col2 + " iS NULL"; resultLeft = getRowCount(con, "SELECT COUNT(*)" + sql); if( resultLeft > 0 ) { String values[] = getColumnValues( con, "SELECT " + table1 + "." + col1 + sql + " LIMIT 20" ); for( int i=0; i<values.length; i++ ) { ReportManager.info( this, con, table1 + "." + col1 + " " + values[i] + " is not linked." ); } } if (!oneWayOnly) { // and the other way ... (a right join?) sql = " FROM " + table2 + " LEFT JOIN " + table1 + " ON " + table2 + "." + col2 + " = " + table1 + "." + col1 + " WHERE " + table1 + "." + col1 + " IS NULL"; resultRight = getRowCount(con, "SELECT COUNT(*)" + sql); if( resultRight > 0 ) { String values[] = getColumnValues( con, "SELECT " + table2 + "." + col2 + sql + " LIMIT 20" ); for( int i=0; i<values.length; i++ ) { ReportManager.info( this, con, table2 + "." + col2 + " " + values[i] + " is not linked." ); } } } else { resultRight = 0; } logger.finest("Left: " + resultLeft + " Right: " + resultRight); return resultLeft + resultRight; } // countOrphans /** * Check that a particular SQL statement has the same result when executed * on more than one database. * @return True if all matched databases provide the same result, false otherwise. * @param sql The SQL query to execute. * @param regexp A regexp matching the database names to check. */ public boolean checkSameSQLResult(String sql, String regexp) { ArrayList resultSetGroup = new ArrayList(); ArrayList statements = new ArrayList(); DatabaseConnectionIterator dcit = testRunner.getDatabaseConnectionIterator(regexp); while (dcit.hasNext()) { Connection con = (Connection)dcit.next(); try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql); if (rs != null) { resultSetGroup.add(rs); } logger.fine("Added ResultSet for " + sql); //DBUtils.printResultSet(rs, 100); // note that the Statement can't be closed here as we use the ResultSet elsewhere // so store a reference to it for closing later statements.add(stmt); //con.close(); } catch (Exception e) { e.printStackTrace(); } } logger.finest("Number of ResultSets to compare: " + resultSetGroup.size()); boolean same = DBUtils.compareResultSetGroup(resultSetGroup, this); Iterator it = statements.iterator(); while (it.hasNext()) { try { ((Statement)it.next()).close(); } catch (Exception e) { e.printStackTrace(); } } return same; } // checkSameSQLResult /** * Check that a particular SQL statement has the same result when executed * on more than one database. * The test case's build-in regexp is used to decide which database names to match. * @return True if all matched databases provide the same result, false otherwise. * @param sql The SQL query to execute. */ public boolean checkSameSQLResult(String sql) { return checkSameSQLResult(sql, databaseRegexp); } // checkSameSQLResult /** * Over-ride the database regular expression set in the subclass' constructor. * @param re The new regular expression to use. */ public void setDatabaseRegexp(String re) { databaseRegexp = re; } // setDatabaseRegexp /** * Get the database regular expression that this test case is using. * @return The database regular expression that this test case is using. */ public String getDatabaseRegexp() { return databaseRegexp; } // getDatabaseRegexp /** * Get the regular expression that will be applied to database names before the built-in regular expression. * @return The value of preFilterRegexp */ public String getPreFilterRegexp() { return preFilterRegexp; } /** * Set the regular expression that will be applied to database names before the built-in regular expression. * @param s The new value for preFilterRegexp. **/ public void setPreFilterRegexp(String s) { preFilterRegexp = s; } /** * Check for the presence of a particular String in a table column. * @param con The database connection to use. * @param table The name of the table to examine. * @param column The name of the column to look in. * @param str The string to search for; can use database wildcards (%, _) Note that if you want to search for one of these special characters, it must be backslash-escaped. * @return The number of times the string is matched. */ public int findStringInColumn(Connection con, String table, String column, String str) { if (con == null) { logger.severe("findStringInColumn: Database connection is null"); } String sql = "SELECT COUNT(*) FROM " + table + " WHERE " + column + " LIKE \"" + str + "\""; logger.fine(sql); return getRowCount(con, sql); } // findStringInColumn /** * Check that all entries in column match a particular pattern. * @param con The database connection to use. * @param table The name of the table to examine. * @param column The name of the column to look in. * @param pattern The SQL pattern (can contain _,%) to look for. * @return The number of columns that <em>DO NOT</em> match the pattern. */ public int checkColumnPattern(Connection con, String table, String column, String pattern) { // @todo - what about NULLs? // cheat by looking for any rows that DO NOT match the pattern String sql = "SELECT COUNT(*) FROM " + table + " WHERE " + column + " NOT LIKE \"" + pattern + "\""; logger.fine(sql); return getRowCount(con, sql); } // checkColumnPattern /** * Check that all entries in column match a particular value. * @param con The database connection to use. * @param table The name of the table to examine. * @param column The name of the column to look in. * @param value The string to look for (not a pattern). * @return The number of columns that <em>DO NOT</em> match value. */ public int checkColumnValue(Connection con, String table, String column, String value) { // @todo - what about NULLs? // cheat by looking for any rows that DO NOT match the pattern String sql = "SELECT COUNT(*) FROM " + table + " WHERE " + column + " != '" + value + "'"; logger.fine(sql); return getRowCount(con, sql); } // checkColumnPattern /** * Check if there are any blank entires in a column that is not supposed to be null. * @param con The database connection to use. * @param table The table to use. * @param column The column to examine. * @return An list of the row indices of any blank entries. Will be zero-length if there are none. */ public List checkBlankNonNull(Connection con, String table, String column) { if (con == null) { logger.severe("checkBlankNonNull (column): Database connection is null"); } ArrayList blanks = new ArrayList(); String sql = "SELECT " + column + " FROM " + table; try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql); ResultSetMetaData rsmd = rs.getMetaData(); while (rs.next()) { String columnValue = rs.getString(1); // should it be non-null? if (rsmd.isNullable(1) == rsmd.columnNoNulls) { if (columnValue == null || columnValue.equals("")) { blanks.add("" + rs.getRow()); } } } rs.close(); stmt.close(); } catch (Exception e) { e.printStackTrace(); } return blanks; } // checkBlankNonNull /** * Check all columns of a table for blank entires in columns that are marked as being NOT NULL. * @param con The database connection to use. * @param table The table to use. * @return The total number of blank null enums. */ public int checkBlankNonNull(Connection con, String table) { if (con == null) { logger.severe("checkBlankNonNull (table): Database connection is null"); } int blanks = 0; String sql = "SELECT * FROM " + table; try { Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql); ResultSetMetaData rsmd = rs.getMetaData(); while (rs.next()) { for (int i = 1; i <= rsmd.getColumnCount(); i++) { String columnValue = rs.getString(i); String columnName = rsmd.getColumnName(i); // should it be non-null? if (rsmd.isNullable(i) == rsmd.columnNoNulls) { if (columnValue == null || columnValue.equals("")) { blanks++; logger.warning("Found blank non-null value in column " + columnName + " in " + table); } } } // for column } // while rs rs.close(); stmt.close(); } catch (Exception e) { e.printStackTrace(); } return blanks; } // checkBlankNonNull /** * Check if a particular table exists in a database. * @param con The database connection to check. * @param table The table to check for. * @return true if the table exists in the database. */ public boolean checkTableExists(Connection con, String table) { String tables = getRowColumnValue(con, "SHOW TABLES LIKE '" + table + "'"); boolean result = false; if (tables != null && tables.length() != 0) { result = true; } return result; } // checkTableExists /** * Print a warning message about a specific database. * @param con The database connection involved. * @param message The message to print. */ protected void warn(Connection con, String message) { logger.warning( "Problem in " + DBUtils.getShortDatabaseName( con )); logger.warning( message ); } //warn /** * Get a list of the databases which represent species. Filter out any which don't seem to represent species. * @return A list of the species; each species will occur only once, and be of the form homo_sapiens (no trailing _). */ public String[] getListOfSpecies() { ArrayList list = new ArrayList(); DatabaseConnectionIterator dbci = testRunner.getDatabaseConnectionIterator(".*"); while (dbci.hasNext()) { String dbName = DBUtils.getShortDatabaseName((Connection)dbci.next()); String[] bits = dbName.split("_"); if (bits.length > 2) { String species = bits[0] + "_" + bits[1]; if (!list.contains(species)) { list.add(species); } } else { logger.fine("Database " + dbName + " does not seem to represent a species; ignored"); } } return (String[])list.toArray(new String[list.size()]); } /** * Get the description. * @return The description for this test. */ public String getDescription() { return description; } // getDescription /** * Set the text description of this test case. * @param s The new description. */ public void setDescription(String s) { description = s; } // setDescription /** * Read a database schema from a file and create a temporary database from it. * @param fileName The name of the schema to read. * @return A connection to a database buit from the schema. */ public Connection importSchema(String fileName) { Connection con = null; // Parse the file first in case there are problems SQLParser sqlParser = new SQLParser(); try { List sqlCommands = sqlParser.parse(fileName); //sqlParser.printLines(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } // TODO exceptions? // create the database String tempDBName = DBUtils.generateTempDatabaseName(); // read properties file String propsFile = System.getProperty("user.dir") + System.getProperty("file.separator") + "database.properties"; Properties dbProps = Utils.readPropertiesFile(propsFile); logger.fine("Read database properties from " + propsFile); try { Class.forName(dbProps.getProperty("driver")); Connection tmp_con = DriverManager.getConnection(dbProps.getProperty("databaseURL"), dbProps.getProperty("user"), dbProps.getProperty("password")); String sql = "CREATE DATABASE " + tempDBName; logger.finest(sql); Statement stmt = tmp_con.createStatement(); stmt.execute(sql); logger.fine("Database " + tempDBName + " created!"); // close the temporary connection and create a "real" one tmp_con.close(); con = DriverManager.getConnection(dbProps.getProperty("databaseURL") + tempDBName, dbProps.getProperty("user"), dbProps.getProperty("password")); } catch (Exception e) { e.printStackTrace(); System.exit(1); } // Build the schema try { Statement stmt = con.createStatement(); // Fill the batch of SQL commands stmt = sqlParser.populateBatch(stmt); // execute the batch that has been built up previously logger.info("Creating temporary database ..."); stmt.executeBatch(); logger.info("Done."); // close statement stmt.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } return con; } public void removeDatabase(Connection con) { String dbName = DBUtils.getShortDatabaseName(con); try { String sql = "DROP DATABASE " + dbName; logger.finest(sql); Statement stmt = con.createStatement(); stmt.execute(sql); logger.fine("Database " + dbName + " removed!"); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } /** * Get a list of all the table names. * @param con The database connection to use. * @return A list of Strings representing the names of the tables, obtained * from the SHOW TABLES command. */ public List getTableNames(Connection con) { return DBUtils.getTableNames(con); } /** * Convenience method for getting a connection to a named schema. * @param schema The name of the schema to connect to. * @return A connection to schema. */ public Connection getSchemaConnection(String schema) { Connection con = DBUtils.openConnection(System.getProperty("driver"), System.getProperty("databaseURL") + schema, System.getProperty("user"), System.getProperty("password")); return con; } /** * Compare two schemas to see if they have the same tables. * The comparison is done in both directions, so will return false if a table * exists in schema1 but not in schema2, <em>or</em> if a table exists in schema2 * but not in schema2. * @param schema1 The first schema to compare. * @param schema2 The second schema to compare. * @return true if all tables in schema1 exist in schema2, and vice-versa. */ public boolean compareTablesInSchema(Connection schema1, Connection schema2) { boolean result = true; String name1 = DBUtils.getShortDatabaseName(schema1); String name2 = DBUtils.getShortDatabaseName(schema2); // check each table in turn List tables = getTableNames(schema1); Iterator it = tables.iterator(); while (it.hasNext()) { String table = (String)it.next(); if (!checkTableExists(schema2, table)) { ReportManager.problem(this, schema1, "Table " + table + " exists in " + name1 + " but not in " + name2); result = false; } } // and now the other way tables = getTableNames(schema2); it = tables.iterator(); while (it.hasNext()) { String table = (String)it.next(); if (!checkTableExists(schema1, table)) { ReportManager.problem(this, schema2, "Table " + table + " exists in " + name2 + " but not in " + name1); result = false; } } return result; } /** * Check if the current test has repair capability. Signified by implementing * the Repair interface. * @return True if this test implements Repair, false otherwise. */ public boolean canRepair() { return (this instanceof Repair); } /** * Add a condition to the list. * @param cond The condition to add. */ public void addCondition(SchemaMatchCondition cond) { conditions.add(cond); } /** * * Get the list of conditions for this test. * @return The conditions. */ public List getConditions() { return conditions; } /** * Run all the schema matching conditions defined in this test case against the * known schemas to see which ones match. * @return A DatabaseConnectionIterator that will give connections to any * schemas that match <em>all</em> the conditions. */ public DatabaseConnectionIterator getMatchingSchemaIterator() { return new DatabaseConnectionIterator(System.getProperty("driver"), System.getProperty("databaseURL"), System.getProperty("user"), System.getProperty("password"), testRunner.getMatchingSchemas(conditions)); } /** * Check if a table has rows. * @param con The connection to the database to use. * @param table The table to check. * @return true if the table has >0 rows, false otherwise. */ public boolean tableHasRows(Connection con, String table) { return (getRowCount(con, "SELECT COUNT(*) FROM " + table) > 0); } } // EnsTestCase
package org.ittek14.nekoden.resource; import java.util.ArrayList; import org.newdawn.slick.SlickException; import org.newdawn.slick.util.xml.XMLElement; import org.newdawn.slick.util.xml.XMLElementList; import org.newdawn.slick.util.xml.XMLParser; public class ResourceManager { public static ArrayList<ImageResource> imageResources = new ArrayList<ImageResource>(); public static ArrayList<AudioResource> audioResources = new ArrayList<AudioResource>(); public static void loadResourcePack(String path) { XMLParser parser = new XMLParser(); XMLElement origin; try { origin = parser.parse(path); XMLElementList imgElements = origin.getChildrenByName("IMG"); for(int i = 0; i < imgElements.size(); i++) { ImageResource imgRes = new ImageResource(imgElements.get(i).getAttribute("id")); imgRes.loadResource(imgElements.get(i).getAttribute("path")); imageResources.add(imgRes); } XMLElementList audElements = origin.getChildrenByName("AUDIO"); for(int i = 0; i < audElements.size(); i++) { AudioResource audRes = new AudioResource(audElements.get(i).getAttribute("id")); audRes.loadResource(audElements.get(i).getAttribute("path")); audioResources.add(audRes); } } catch (SlickException e) { e.printStackTrace(); } } public static ImageResource getImageResource(String id) { for(ImageResource resource : imageResources) { System.out.println(resource.getID() + ":" + id); if(resource.getID().equals(id)) { System.out.println("Oh"); return resource; } } return null; } public static AudioResource getAudioResource(String id) { for(AudioResource resource : audioResources) { if(resource.getID() == id) { return resource; } } return null; } public static Resource getResource(String id) { for(Resource resource : imageResources) { if(resource.getID() == id) { return resource; } } for(Resource resource : audioResources) { if(resource.getID() == id) { return resource; } } return null; } }
package org.joval.protocol.http; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.ProtocolException; import java.net.Proxy; import java.net.Socket; import java.net.URL; import java.nio.charset.Charset; import java.security.Permission; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import javax.net.ssl.SSLSocketFactory; import org.joval.util.RFC822; public class HttpSocketConnection extends AbstractConnection { private static int defaultChunkLength = 512; private boolean secure, tunnelFailure; private Socket socket; private Proxy proxy; private String host; // host:port private boolean gotResponse; private HSOutputStream stream; /** * Create a direct connection. */ public HttpSocketConnection(URL url) { this(url, null); } /** * Create a connection through a proxy. */ public HttpSocketConnection(URL url, Proxy proxy) throws IllegalArgumentException { super(url); if (url.getProtocol().equalsIgnoreCase("HTTPS")) { secure = true; } else if (url.getProtocol().equalsIgnoreCase("HTTP")) { secure = false; } else { throw new IllegalArgumentException("Unsupported protocol: " + url.getProtocol()); } setProxy(proxy); StringBuffer sb = new StringBuffer(url.getHost()); if (url.getPort() == -1) { if (secure) { sb.append(":443"); } else { sb.append(":80"); } } else { sb.append(":").append(Integer.toString(url.getPort())); } host = sb.toString(); reset(); } // Overrides for HttpURLConnection @Override public Permission getPermission() throws IOException { return new java.net.SocketPermission(host, "connect"); } @Override public boolean usingProxy() { return proxy != null; } /** * If a fixed content length has not been set, this method causes the connection to use chunked encoding. */ @Override public OutputStream getOutputStream() throws IOException { if (doOutput) { if (stream == null) { switch(fixedContentLength) { case -1: stream = new HSChunkedOutputStream(chunkLength); break; default: stream = new HSOutputStream(fixedContentLength); break; } } connect(); return stream; } else { throw new IllegalStateException("Output not allowed"); } } @Override public void setRequestProperty(String key, String value) { if (connected) { throw new IllegalStateException("Already connected"); } setMapProperty(key, value, requestProperties); } @Override public void addRequestProperty(String key, String value) { if (connected) { throw new IllegalStateException("Already connected"); } addMapProperty(key, value, requestProperties); } @Override public String getRequestProperty(String key) { for (Map.Entry<String, List<String>> entry : requestProperties.entrySet()) { if (key.equalsIgnoreCase(entry.getKey())) { return entry.getValue().get(0); } } return null; } @Override public Map<String, List<String>> getRequestProperties() { Map<String, List<String>> map = new HashMap<String, List<String>>(); for (Map.Entry<String, List<String>> entry : requestProperties.entrySet()) { map.put(entry.getKey(), Collections.unmodifiableList(entry.getValue())); } return Collections.unmodifiableMap(map); } @Override public void disconnect() { if (connected) { try { socket.close(); } catch (IOException e) { } connected = false; } } @Override public void connect() throws IOException { if (connected) { return; } if (socket == null || socket.isClosed()) { if (proxy == null) { socket = new Socket(url.getHost(), url.getPort()); } else { socket = new Socket(); socket.connect(proxy.address()); } } if (secure && proxy != null) { // Establish a tunnel through the proxy write(new StringBuffer("CONNECT ").append(host).append(" HTTP/1.1").toString()); write(CRLF); String temp = getRequestProperty("Proxy-authorization"); if (temp != null) { write(new KVP("Proxy-authorization", temp)); } temp = getRequestProperty("User-Agent"); if (temp != null) { write(new KVP("User-Agent", temp)); } if (method.equalsIgnoreCase("GET") && ifModifiedSince > 0) { write(new KVP("If-Modified-Since", RFC822.toString(ifModifiedSince))); } write(new KVP("Connection", "Keep-Alive")); write(CRLF); InputStream in = socket.getInputStream(); Map<String, List<String>> map = new HashMap<String, List<String>>(); KVP pair = null; while((pair = readKVP(in)) != null) { if (pair.key().length() == 0) { parseResponse(pair.value()); } if (responseCode != HTTP_OK) { if (orderedHeaderFields.size() > 0) { addMapProperties(pair, map); } orderedHeaderFields.add(pair); } } if (responseCode == HTTP_OK) { // Establish a socket tunnel int port = Integer.parseInt(host.substring(host.indexOf(":") + 1)); socket = ((SSLSocketFactory)SSLSocketFactory.getDefault()).createSocket(socket, url.getHost(), port, true); } else { stream = new HSDevNull(); headerFields = Collections.unmodifiableMap(map); gotResponse = true; } } else { StringBuffer req = new StringBuffer(getRequestMethod()).append(" "); if (proxy == null) { String path = url.getPath(); if (!path.startsWith("/")) { req.append("/"); } req.append(path); } else { req.append(url.toString()); } req.append(" HTTP/1.1"); setRequestProperty("Connection", "Keep-Alive"); setRequestProperty("Host", host); if (doOutput) { if (fixedContentLength != -1) { setRequestProperty("Content-Length", Integer.toString(fixedContentLength)); } else { if (chunkLength == -1) { chunkLength = defaultChunkLength; } setRequestProperty("Transfer-Encoding", "chunked"); } } write(req.toString()); write(CRLF); for (Map.Entry<String, List<String>> entry : requestProperties.entrySet()) { write(new KVP(entry)); } write(CRLF); } connected = true; } // Internal /** * Set a proxy. */ void setProxy(Proxy proxy) { if (proxy != null) { switch(proxy.type()) { case HTTP: this.proxy = proxy; break; case SOCKS: throw new IllegalArgumentException("Illegal proxy type: SOCKS"); case DIRECT: default: this.proxy = null; break; } } } /** * Reset the connection to a pristine state. */ void reset() { initialize(); setRequestProperty("User-Agent", "jOVAL HTTP Client"); if (stream != null) { try { stream.close(); } catch (IOException e) { disconnect(); } stream = null; } gotResponse = false; } /** * Read the response over the socket. */ @Override void getResponse() throws IOException { if (gotResponse) return; connect(); try { if (stream == null) { switch(fixedContentLength) { case -1: // connect() would have assumed chunked transfer-encoding, so write a final 0-length chunk. write("0"); write(CRLF); write(CRLF); // fall-thru case 0: break; default: throw new IllegalStateException("You promised to write " + fixedContentLength + " bytes!"); } } else if (!stream.complete()) { throw new IllegalStateException("You must write " + stream.remaining() + " more bytes!"); } else { stream.close(); } orderedHeaderFields = new ArrayList<KVP>(); Map<String, List<String>> map = new HashMap<String, List<String>>(); boolean chunked = false; InputStream in = socket.getInputStream(); KVP pair = null; while((pair = readKVP(in)) != null) { if (orderedHeaderFields.size() == 0) { parseResponse(pair.value()); } else { addMapProperties(pair, map); } orderedHeaderFields.add(pair); if ("Content-Length".equalsIgnoreCase(pair.key())) { contentLength = Integer.parseInt(pair.value()); } else if ("Content-Type".equalsIgnoreCase(pair.key())) { contentType = pair.value(); } else if ("Content-Encoding".equalsIgnoreCase(pair.key())) { contentEncoding = pair.value(); } else if ("Transfer-Encoding".equalsIgnoreCase(pair.key())) { chunked = pair.value().equalsIgnoreCase("chunked"); } else if ("Date".equalsIgnoreCase(pair.key())) { try { date = RFC822.valueOf(pair.value()); } catch (IllegalArgumentException e) { } } else if ("Last-Modified".equalsIgnoreCase(pair.key())) { try { lastModified = RFC822.valueOf(pair.value()); } catch (IllegalArgumentException e) { } } else if ("Expires".equalsIgnoreCase(pair.key())) { try { expiration = RFC822.valueOf(pair.value()); } catch (IllegalArgumentException e) { } } } if (chunked) { HSBufferedOutputStream buffer = new HSBufferedOutputStream(); int len = 0; while((len = readChunkLength(in)) > 0) { byte[] bytes = new byte[len]; posit(len == in.read(bytes, 0, len)); buffer.write(bytes); posit(in.read() == '\r'); posit(in.read() == '\n'); } responseData = new HSBufferedInputStream(buffer); contentLength = ((HSBufferedInputStream)responseData).size(); // Read footers (if any) while((pair = readKVP(in)) != null) { orderedHeaderFields.add(pair); addMapProperties(pair, map); } } else { byte[] bytes = new byte[contentLength]; for (int offset=0; offset < contentLength; ) { offset += in.read(bytes, offset, contentLength - offset); } responseData = new HSBufferedInputStream(bytes); } headerFields = Collections.unmodifiableMap(map); } finally { gotResponse = true; if (headerFields == null || "Close".equalsIgnoreCase(getHeaderField("Connection"))) { disconnect(); } } } // Private private void write(KVP header) throws IOException { write(header.toString()); write(CRLF); } private void write(String s) throws IOException { write(s.getBytes("US-ASCII")); } private void write(int ch) throws IOException { socket.getOutputStream().write(ch); } private void write(byte[] bytes) throws IOException { write(bytes, 0, bytes.length); } private void write(byte[] bytes, int offset, int len) throws IOException { socket.getOutputStream().write(bytes, offset, len); socket.getOutputStream().flush(); } /** * Parse the HTTP response line. */ private void parseResponse(String line) throws IllegalArgumentException { StringTokenizer tok = new StringTokenizer(line, " "); if (tok.countTokens() < 2) { throw new IllegalArgumentException(line); } String httpVersion = tok.nextToken(); responseCode = Integer.parseInt(tok.nextToken()); if (tok.hasMoreTokens()) { responseMessage = tok.nextToken("\r\n"); } } /** * Read a line ending in CRLF that indicates the length of the next chunk. */ private int readChunkLength(InputStream in) throws IOException { StringBuffer sb = new StringBuffer(); boolean done = false; boolean cr = false; while(!done) { int ch = in.read(); switch(ch) { case -1: throw new IOException("Connection was closed!"); case '\r': if (sb.length() == 0) { cr = true; } break; case '\n': if (cr) { done = true; } break; default: sb.append((char)ch); break; } } String line = sb.toString(); int ptr = line.indexOf(";"); if (ptr > 0) { return Integer.parseInt(line.substring(0,ptr), 16); } else { return Integer.parseInt(line, 16); } } /** * Like assert, but always enabled. */ private void posit(boolean test) throws AssertionError { if (!test) throw new AssertionError(); } /** * ByteArrayOutputStream that provides access to the underlying memory buffer. */ class HSBufferedOutputStream extends ByteArrayOutputStream { HSBufferedOutputStream() { super(); } /** * Access the underlying buffer -- NOT A COPY. */ byte[] getBuf() { return buf; } } /** * InputStream that resets this connection when closed. */ class HSBufferedInputStream extends ByteArrayInputStream { private boolean closed; HSBufferedInputStream(HSBufferedOutputStream out) { super(out.getBuf(), 0, out.size()); closed = false; } HSBufferedInputStream(byte[] buffer) { super(buffer); closed = false; } int size() { return count; } @Override public void close() throws IOException { if (!closed) { super.close(); reset(); closed = true; } } } /** * An OutputStream for a fixed-length stream. */ class HSOutputStream extends OutputStream { private int size; int ptr; boolean closed; HSOutputStream(int size) { this.size = size; ptr = 0; closed = false; } boolean complete() { return remaining() == 0; } int remaining() { return size - ptr; } // InputStream overrides @Override public void write(int ch) throws IOException { if (closed) throw new IOException("stream closed"); ptr++; if (ptr > size) { throw new IOException("Buffer overflow " + ptr); } HttpSocketConnection.this.write(ch); } @Override public void write(byte[] b) throws IOException { if (closed) throw new IOException("stream closed"); write(b, 0, b.length); } @Override public void write(byte[] b, int off, int len) throws IOException { if (closed) throw new IOException("stream closed"); ptr = ptr + len; if (ptr > size) { throw new IOException("Buffer overflow " + ptr + ", size=" + size); } HttpSocketConnection.this.write(b, off, len); } @Override public void flush() throws IOException { if (closed) throw new IOException("stream closed"); socket.getOutputStream().flush(); } @Override public void close() throws IOException { if (!closed) { if (complete()) { flush(); closed = true; } else { throw new IOException("You need to write " + remaining() + " more bytes!"); } } } } /** * A safe place (i.e., nowhere) to write output in the event of a failure to establish a CONNECT tunnel through * an HTTP proxy. */ class HSDevNull extends HSOutputStream { HSDevNull() { super(0); } @Override public void write(int ch) {} @Override public void write(byte[] b) {} @Override public void write(byte[] b, int offset, int len) {} @Override public void flush() {} @Override public void close() {} } /** * An OutputStream for chunked stream encoding. */ class HSChunkedOutputStream extends HSOutputStream { private byte[] buffer; HSChunkedOutputStream(int chunkSize) { super(chunkSize); buffer = new byte[chunkSize]; } @Override boolean complete() { return ptr == 0; } @Override public void write(int ch) throws IOException { if (closed) throw new IOException("stream closed"); int end = ptr + 1; if (end <= buffer.length) { buffer[ptr++] = (byte)(ch & 0xFF); if (end == buffer.length) { flush(); } } else { throw new IOException("Buffer overrun " + ptr); } } @Override public void write(byte[] buff) throws IOException { if (closed) throw new IOException("stream closed"); write(buff, 0, buff.length); } @Override public void write(byte[] buff, int offset, int len) throws IOException { if (closed) throw new IOException("stream closed"); len = Math.min(buff.length - offset, len); int end = ptr + len; if (end <= buffer.length) { System.arraycopy(buff, offset, buffer, ptr, len); ptr = end; if (end == buffer.length) { flush(); } } else { int remainder = buffer.length - ptr; write(buff, offset, remainder); write(buff, offset + remainder, len - remainder); } } @Override public void flush() throws IOException { if (closed) throw new IOException("stream closed"); if (ptr > 0) { HttpSocketConnection.this.write(Integer.toHexString(ptr)); HttpSocketConnection.this.write(CRLF); HttpSocketConnection.this.write(buffer, 0, ptr); HttpSocketConnection.this.write(CRLF); buffer = new byte[buffer.length]; ptr = 0; } } @Override public void close() throws IOException { if (!closed) { flush(); HttpSocketConnection.this.write("0"); HttpSocketConnection.this.write(CRLF); HttpSocketConnection.this.write(CRLF); closed = true; } } } /** * An output stream to nowhere. */ class DevNull extends OutputStream { DevNull() {} @Override public void write(int ch) {} } }
package org.metawatch.manager.widgets; import java.util.ArrayList; import java.util.Calendar; import java.util.Map; import org.metawatch.manager.FontCache; import org.metawatch.manager.MetaWatch; import org.metawatch.manager.MetaWatchService.Preferences; import org.metawatch.manager.Monitors; import org.metawatch.manager.Utils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint.Align; import android.text.Layout; import android.text.StaticLayout; import android.text.TextPaint; import android.util.Log; public class CalendarWidget implements InternalWidget { public final static String id_0 = "Calendar_24_32"; final static String desc_0 = "Next Calendar Appointment (24x32)"; public final static String id_1 = "Calendar_96_32"; final static String desc_1 = "Next Calendar Appointment (96x32)"; private Context context; private TextPaint paintSmall; private TextPaint paintNumerals; private String meetingTime = "None"; private String meetingTitle; private String meetingLocation; private long meetingStartTimestamp = 0; private long meetingEndTimestamp = 0; public void init(Context context, ArrayList<CharSequence> widgetIds) { this.context = context; paintSmall = new TextPaint(); paintSmall.setColor(Color.BLACK); paintSmall.setTextSize(FontCache.instance(context).Small.size); paintSmall.setTypeface(FontCache.instance(context).Small.face); paintSmall.setTextAlign(Align.CENTER); paintNumerals = new TextPaint(); paintNumerals.setColor(Color.BLACK); paintNumerals.setTextSize(FontCache.instance(context).Numerals.size); paintNumerals.setTypeface(FontCache.instance(context).Numerals.face); paintNumerals.setTextAlign(Align.CENTER); } public void shutdown() { paintSmall = null; } long lastRefresh = 0; public void refresh(ArrayList<CharSequence> widgetIds) { boolean readCalendar = false; long time = System.currentTimeMillis(); if ((time - lastRefresh > 5*60*1000) || (Monitors.calendarChanged)) { readCalendar = true; lastRefresh = System.currentTimeMillis(); } if (!Preferences.readCalendarDuringMeeting) { // Only update the current meeting if it is not ongoing if ((time>=meetingStartTimestamp) && (time<meetingEndTimestamp-Preferences.readCalendarMinDurationToMeetingEnd*60*1000)) { readCalendar = false; } } if (readCalendar) { if (Preferences.logging) Log.d(MetaWatch.TAG, "CalendarWidget.refresh() start"); meetingTime = Utils.readCalendar(context, 0); meetingStartTimestamp = Utils.Meeting_StartTimestamp; meetingEndTimestamp = Utils.Meeting_EndTimestamp; meetingLocation = Utils.Meeting_Location; meetingTitle = Utils.Meeting_Title; if (Preferences.logging) Log.d(MetaWatch.TAG, "CalendarWidget.refresh() stop"); } } public void get(ArrayList<CharSequence> widgetIds, Map<String,WidgetData> result) { if(widgetIds == null || widgetIds.contains(id_0)) { result.put(id_0, GenWidget(id_0)); } if(widgetIds == null || widgetIds.contains(id_1)) { result.put(id_1, GenWidget(id_1)); } } private InternalWidget.WidgetData GenWidget(String widget_id) { InternalWidget.WidgetData widget = new InternalWidget.WidgetData(); widget.priority = meetingTime.equals("None") ? 0 : 1; if (widget_id.equals(id_0)) { widget.id = id_0; widget.description = desc_0; widget.width = 24; widget.height = 32; } else if (widget_id.equals(id_1)) { widget.id = id_1; widget.description = desc_1; widget.width = 96; widget.height = 32; } Bitmap icon = Utils.loadBitmapFromAssets(context, "idle_calendar.bmp"); widget.bitmap = Bitmap.createBitmap(widget.width, widget.height, Bitmap.Config.RGB_565); Canvas canvas = new Canvas(widget.bitmap); canvas.drawColor(Color.WHITE); canvas.drawBitmap(icon, 0, 3, null); if ((Preferences.displayLocationInSmallCalendarWidget)&& (!meetingTime.equals("None"))&&(meetingLocation!=null)&& (!meetingLocation.equals("---"))&&(widget_id.equals(id_0))&& (meetingLocation.length()>0)&&(meetingLocation.length()<=3)) { canvas.drawText(meetingLocation, 12, 15, paintSmall); } else { Calendar c = Calendar.getInstance(); int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); if(dayOfMonth<10) { canvas.drawText(""+dayOfMonth, 12, 16, paintNumerals); } else { canvas.drawText(""+dayOfMonth/10, 9, 16, paintNumerals); canvas.drawText(""+dayOfMonth%10, 15, 16, paintNumerals); } } canvas.drawText(meetingTime, 12, 30, paintSmall); if (widget_id.equals(id_1)) { paintSmall.setTextAlign(Align.LEFT); String text = meetingTitle; if ((meetingLocation !=null) && (meetingLocation.length()>0)) text += " - " + meetingLocation; canvas.save(); StaticLayout layout = new StaticLayout(text, paintSmall, 70, Layout.Alignment.ALIGN_CENTER, 1.2f, 0, false); int height = layout.getHeight(); int textY = 16 - (height/2); if(textY<0) { textY=0; } canvas.translate(25, textY); //position the text layout.draw(canvas); canvas.restore(); paintSmall.setTextAlign(Align.CENTER); } return widget; } }
package org.nschmidt.ldparteditor.data; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; import org.eclipse.swt.dnd.Clipboard; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.widgets.Display; import org.nschmidt.ldparteditor.enums.View; import org.nschmidt.ldparteditor.helpers.math.HashBiMap; import org.nschmidt.ldparteditor.helpers.math.ThreadsafeHashMap; import org.nschmidt.ldparteditor.helpers.math.ThreadsafeTreeMap; import org.nschmidt.ldparteditor.text.DatParser; import org.nschmidt.ldparteditor.text.StringHelper; class VM99Clipboard extends VM24MeshReducer { private static final List<GData> CLIPBOARD = new ArrayList<GData>(); private static final Set<GData> CLIPBOARD_InvNext = Collections.newSetFromMap(new ThreadsafeHashMap<GData, Boolean>()); protected VM99Clipboard(DatFile linkedDatFile) { super(linkedDatFile); } public static List<GData> getClipboard() { return CLIPBOARD; } public void copy() { // Has to copy what IS selected, nothing more, nothing less. CLIPBOARD.clear(); CLIPBOARD_InvNext.clear(); final Set<Vertex> singleVertices = Collections.newSetFromMap(new ThreadsafeTreeMap<Vertex, Boolean>()); final HashSet<GData2> effSelectedLines = new HashSet<GData2>(); final HashSet<GData3> effSelectedTriangles = new HashSet<GData3>(); final HashSet<GData4> effSelectedQuads = new HashSet<GData4>(); final HashSet<GData5> effSelectedCondlines = new HashSet<GData5>(); final TreeSet<Vertex> effSelectedVertices2 = new TreeSet<Vertex>(selectedVertices); final HashSet<GData2> effSelectedLines2 = new HashSet<GData2>(selectedLines); final HashSet<GData3> effSelectedTriangles2 = new HashSet<GData3>(selectedTriangles); final HashSet<GData4> effSelectedQuads2 = new HashSet<GData4>(selectedQuads); final HashSet<GData5> effSelectedCondlines2 = new HashSet<GData5>(selectedCondlines); selectedData.clear(); { final Set<Vertex> objectVertices = Collections.newSetFromMap(new ThreadsafeTreeMap<Vertex, Boolean>()); // 0. Deselect selected subfile data I (for whole selected subfiles) for (GData1 subf : selectedSubfiles) { Set<VertexInfo> vis = lineLinkedToVertices.get(subf); for (VertexInfo vertexInfo : vis) { selectedVertices.remove(vertexInfo.getVertex()); GData g = vertexInfo.getLinkedData(); switch (g.type()) { case 2: selectedLines.remove(g); { Vertex[] verts = lines.get(g); if (verts == null) continue; for (Vertex vertex : verts) { objectVertices.add(vertex); } } break; case 3: selectedTriangles.remove(g); { Vertex[] verts = triangles.get(g); if (verts == null) continue; for (Vertex vertex : verts) { objectVertices.add(vertex); } } break; case 4: selectedQuads.remove(g); { Vertex[] verts = quads.get(g); if (verts == null) continue; for (Vertex vertex : verts) { objectVertices.add(vertex); } } break; case 5: selectedCondlines.remove(g); { Vertex[] verts = condlines.get(g); if (verts == null) continue; for (Vertex vertex : verts) { objectVertices.add(vertex); } } break; default: break; } } } // 1. Vertex Based Selection { HashMap<GData, Integer> occurMap = new HashMap<GData, Integer>(); for (Vertex vertex : selectedVertices) { Set<VertexManifestation> occurences = vertexLinkedToPositionInFile.get(vertex); if (occurences == null) continue; for (VertexManifestation vm : occurences) { GData g = vm.getGdata(); int val = 1; int type = g.type(); if (occurMap.containsKey(g)) { val = occurMap.get(g); if (type != 5 || vm.getPosition() < 2) { val++; occurMap.put(g, val); } } else if (type != 5 || vm.getPosition() < 2) { occurMap.put(g, val); } switch (type) { case 2: GData2 line = (GData2) g; if (val == 2) { selectedLines.add(line); } break; case 3: GData3 triangle = (GData3) g; if (val == 3) { selectedTriangles.add(triangle); } break; case 4: GData4 quad = (GData4) g; if (val == 4) { selectedQuads.add(quad); } break; case 5: GData5 condline = (GData5) g; if (val == 2) { selectedCondlines.add(condline); } break; } } } } // 2. Deselect selected subfile data II (for whole selected // subfiles, remove all from selection, which belongs to a // completely selected subfile) for (GData1 subf : selectedSubfiles) { Set<VertexInfo> vis = lineLinkedToVertices.get(subf); for (VertexInfo vertexInfo : vis) { GData g = vertexInfo.getLinkedData(); switch (g.type()) { case 2: selectedLines.remove(g); { Vertex[] verts = lines.get(g); if (verts == null) continue; for (Vertex vertex : verts) { objectVertices.add(vertex); } } break; case 3: selectedTriangles.remove(g); { Vertex[] verts = triangles.get(g); if (verts == null) continue; for (Vertex vertex : verts) { objectVertices.add(vertex); } } break; case 4: selectedQuads.remove(g); { Vertex[] verts = quads.get(g); if (verts == null) continue; for (Vertex vertex : verts) { objectVertices.add(vertex); } } break; case 5: selectedCondlines.remove(g); { Vertex[] verts = condlines.get(g); if (verts == null) continue; for (Vertex vertex : verts) { objectVertices.add(vertex); } } break; default: break; } } } // 3. Object Based Selection for (GData2 line : selectedLines) { if (line.parent.equals(View.DUMMY_REFERENCE)) { effSelectedLines.add(line); } else { Vertex[] verts = lines.get(line); if (verts == null) continue; effSelectedLines.add(new GData2(verts[0], verts[1], line.parent, new GColour(line.colourNumber, line.r, line.g, line.b, line.a))); } Vertex[] verts = lines.get(line); if (verts == null) continue; for (Vertex vertex : verts) { objectVertices.add(vertex); } } for (GData3 triangle : selectedTriangles) { if (triangle.parent.equals(View.DUMMY_REFERENCE)) { effSelectedTriangles.add(triangle); } else { Vertex[] verts = triangles.get(triangle); if (verts == null) continue; effSelectedTriangles.add(new GData3(verts[0], verts[1], verts[2], triangle.parent, new GColour(triangle.colourNumber, triangle.r, triangle.g, triangle.b, triangle.a))); } Vertex[] verts = triangles.get(triangle); if (verts == null) continue; for (Vertex vertex : verts) { objectVertices.add(vertex); } } for (GData4 quad : selectedQuads) { if (quad.parent.equals(View.DUMMY_REFERENCE)) { effSelectedQuads.add(quad); } else { Vertex[] verts = quads.get(quad); if (verts == null) continue; effSelectedQuads.add(new GData4(verts[0], verts[1], verts[2], verts[3], quad.parent, new GColour(quad.colourNumber, quad.r, quad.g, quad.b, quad.a))); } Vertex[] verts = quads.get(quad); if (verts == null) continue; for (Vertex vertex : verts) { objectVertices.add(vertex); } } for (GData5 condline : selectedCondlines) { if (condline.parent.equals(View.DUMMY_REFERENCE)) { effSelectedCondlines.add(condline); } else { Vertex[] verts = condlines.get(condline); if (verts == null) continue; effSelectedCondlines.add(new GData5(verts[0], verts[1], verts[2], verts[3], condline.parent, new GColour(condline.colourNumber, condline.r, condline.g, condline.b, condline.a))); } Vertex[] verts = condlines.get(condline); if (verts == null) continue; for (Vertex vertex : verts) { objectVertices.add(vertex); } } singleVertices.addAll(selectedVertices); singleVertices.removeAll(objectVertices); // 4. Copy of the selected data (no whole subfiles!!) CLIPBOARD.addAll(effSelectedLines); CLIPBOARD.addAll(effSelectedTriangles); CLIPBOARD.addAll(effSelectedQuads); CLIPBOARD.addAll(effSelectedCondlines); // 4. Subfile Based Copy (with INVERTNEXT) if (!selectedSubfiles.isEmpty()) { for (GData1 subf : selectedSubfiles) { boolean hasInvertnext = false; GData invertNextData = subf.getBefore(); while (invertNextData != null && invertNextData.type() != 1 && (invertNextData.type() != 6 || ((GDataBFC) invertNextData).type != BFC.INVERTNEXT)) { invertNextData = invertNextData.getBefore(); } if (invertNextData != null && invertNextData.type() == 6) { hasInvertnext = true; } if (hasInvertnext) { CLIPBOARD_InvNext.add(subf); } } CLIPBOARD.addAll(selectedSubfiles); } // Sort the clipboard content by linenumber (or ID if the linenumber is the same) { final HashBiMap<Integer, GData> dpl = linkedDatFile.getDrawPerLine_NOCLONE(); Collections.sort(CLIPBOARD, new Comparator<GData>(){ @Override public int compare(GData o1, GData o2) { if (dpl.containsValue(o1)) { if (dpl.containsValue(o2)) { return dpl.getKey(o1).compareTo(dpl.getKey(o2)); } else { switch (o2.type()) { case 1: return dpl.getKey(o1).compareTo(dpl.getKey(((GData1) o2).firstRef)); case 2: return dpl.getKey(o1).compareTo(dpl.getKey(((GData2) o2).parent.firstRef)); case 3: return dpl.getKey(o1).compareTo(dpl.getKey(((GData3) o2).parent.firstRef)); case 4: return dpl.getKey(o1).compareTo(dpl.getKey(((GData4) o2).parent.firstRef)); case 5: return dpl.getKey(o1).compareTo(dpl.getKey(((GData5) o2).parent.firstRef)); default: GData t = o2.getBefore(); while (t != null && t.getBefore() != null) { t = t.getBefore(); } return dpl.getKey(o1).compareTo(dpl.getKey(((GDataInit) t).getParent().firstRef)); } } } else { if (dpl.containsValue(o2)) { switch (o1.type()) { case 1: return dpl.getKey(((GData1) o1).firstRef).compareTo(dpl.getKey(o2)); case 2: return dpl.getKey(((GData2) o1).parent.firstRef).compareTo(dpl.getKey(o2)); case 3: return dpl.getKey(((GData3) o1).parent.firstRef).compareTo(dpl.getKey(o2)); case 4: return dpl.getKey(((GData4) o1).parent.firstRef).compareTo(dpl.getKey(o2)); case 5: return dpl.getKey(((GData5) o1).parent.firstRef).compareTo(dpl.getKey(o2)); default: GData t = o2.getBefore(); while (t != null && t.getBefore() != null) { t = t.getBefore(); } return dpl.getKey(((GDataInit) t).getParent().firstRef).compareTo(dpl.getKey(o2)); } } else { final Integer co1; final Integer co2; { switch (o1.type()) { case 1: co1 = dpl.getKey(((GData1) o1).firstRef); break; case 2: co1 = dpl.getKey(((GData2) o1).parent.firstRef); break; case 3: co1 = dpl.getKey(((GData3) o1).parent.firstRef); break; case 4: co1 = dpl.getKey(((GData4) o1).parent.firstRef); break; case 5: co1 = dpl.getKey(((GData5) o1).parent.firstRef); break; default: GData t = o2.getBefore(); while (t != null && t.getBefore() != null) { t = t.getBefore(); } co1 = dpl.getKey(((GDataInit) t).getParent().firstRef); } } { switch (o2.type()) { case 1: co2 = dpl.getKey(((GData1) o2).firstRef); break; case 2: co2 = dpl.getKey(((GData2) o2).parent.firstRef); break; case 3: co2 = dpl.getKey(((GData3) o2).parent.firstRef); break; case 4: co2 = dpl.getKey(((GData4) o2).parent.firstRef); break; case 5: co2 = dpl.getKey(((GData5) o2).parent.firstRef); break; default: GData t = o2.getBefore(); while (t != null && t.getBefore() != null) { t = t.getBefore(); } co2 = dpl.getKey(((GDataInit) t).getParent().firstRef); } } int comparism = co1.compareTo(co2); if (comparism == 0) { if (o1.ID > o2.ID) { // The id can "never" be equal! return 1; } else { return -1; } } else { return comparism; } } } } }); } for (Vertex v : singleVertices) { CLIPBOARD.add(new GData0("0 !LPE VERTEX " + bigDecimalToString(v.X) + " " + bigDecimalToString(v.Y) + " " + bigDecimalToString(v.Z))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$) } // 5. Create text data entry in the OS clipboard final StringBuilder cbString = new StringBuilder(); for (GData data : CLIPBOARD) { if (CLIPBOARD_InvNext.contains(data)) { cbString.append("0 BFC INVERTNEXT"); //$NON-NLS-1$ cbString.append(StringHelper.getLineDelimiter()); cbString.append(data.toString()); cbString.append(StringHelper.getLineDelimiter()); } else { cbString.append(data.toString()); cbString.append(StringHelper.getLineDelimiter()); } } final String cbs = cbString.toString(); if (!cbs.isEmpty()) { Display display = Display.getCurrent(); Clipboard clipboard = new Clipboard(display); clipboard.setContents(new Object[] { cbs }, new Transfer[] { TextTransfer.getInstance() }); clipboard.dispose(); } // 6. Restore selection // Reduce the amount of superflous selected data selectedVertices.clear(); selectedVertices.addAll(effSelectedVertices2); selectedLines.clear(); selectedLines.addAll(effSelectedLines2); selectedTriangles.clear(); selectedTriangles.addAll(effSelectedTriangles2); selectedQuads.clear(); selectedQuads.addAll(effSelectedQuads2); selectedCondlines.clear(); selectedCondlines.addAll(effSelectedCondlines2); selectedData.addAll(selectedLines); selectedData.addAll(selectedTriangles); selectedData.addAll(selectedQuads); selectedData.addAll(selectedCondlines); selectedData.addAll(selectedSubfiles); selectedVertices.retainAll(vertexLinkedToPositionInFile.keySet()); } } public void paste() { // FIXME Needs Implementation for Issue if (linkedDatFile.isReadOnly()) return; if (!CLIPBOARD.isEmpty()) { clearSelection(); final HashBiMap<Integer, GData> dpl = linkedDatFile.getDrawPerLine_NOCLONE(); int linecount = dpl.size(); GData before = linkedDatFile.getDrawChainTail(); GData tailData = null; for (GData g : CLIPBOARD) { Set<String> alreadyParsed = new HashSet<String>(); alreadyParsed.add(linkedDatFile.getShortName()); if (CLIPBOARD_InvNext.contains(g)) { GDataBFC invNext = new GDataBFC(BFC.INVERTNEXT); before.setNext(invNext); before = invNext; linecount++; dpl.put(linecount, invNext); } ArrayList<ParsingResult> result = DatParser.parseLine(g.toString(), -1, 0, 0.5f, 0.5f, 0.5f, 1.1f, View.DUMMY_REFERENCE, View.ID, View.ACCURATE_ID, linkedDatFile, false, alreadyParsed, false); GData pasted = result.get(0).getGraphicalData(); if (pasted == null) pasted = new GData0(g.toString()); linecount++; dpl.put(linecount, pasted); selectedData.add(pasted); switch (pasted.type()) { case 0: selectedData.remove(pasted); Vertex vertex = ((GData0) pasted).getVertex(); if (vertex != null) { selectedVertices.add(vertex); } break; case 1: selectedSubfiles.add((GData1) pasted); Set<VertexInfo> vis = lineLinkedToVertices.get(pasted); for (VertexInfo vertexInfo : vis) { selectedVertices.add(vertexInfo.getVertex()); GData gs = vertexInfo.getLinkedData(); selectedData.add(gs); switch (gs.type()) { case 0: selectedData.remove(gs); Vertex vertex2 = ((GData0) gs).getVertex(); if (vertex2 != null) { selectedVertices.add(vertex2); } break; case 2: selectedLines.add((GData2) gs); break; case 3: selectedTriangles.add((GData3) gs); break; case 4: selectedQuads.add((GData4) gs); break; case 5: selectedCondlines.add((GData5) gs); break; default: break; } } break; case 2: selectedLines.add((GData2) pasted); break; case 3: selectedTriangles.add((GData3) pasted); break; case 4: selectedQuads.add((GData4) pasted); break; case 5: selectedCondlines.add((GData5) pasted); break; default: break; } before.setNext(pasted); before = pasted; tailData = pasted; } linkedDatFile.setDrawChainTail(tailData); setModified(true, true); updateUnsavedStatus(); } } }
package org.objectweb.proactive.p2p.api.core; import org.apache.log4j.Logger; import org.objectweb.proactive.ActiveObjectCreationException; import org.objectweb.proactive.Body; import org.objectweb.proactive.InitActive; import org.objectweb.proactive.ProActive; import org.objectweb.proactive.Service; import org.objectweb.proactive.core.ProActiveException; import org.objectweb.proactive.core.group.ExceptionListException; import org.objectweb.proactive.core.group.Group; import org.objectweb.proactive.core.group.ProActiveGroup; import org.objectweb.proactive.core.mop.ClassNotReifiableException; import org.objectweb.proactive.core.node.Node; import org.objectweb.proactive.core.node.NodeException; import org.objectweb.proactive.core.util.log.Loggers; import org.objectweb.proactive.core.util.log.ProActiveLogger; import org.objectweb.proactive.core.util.wrapper.BooleanWrapper; import java.io.Serializable; import java.util.Iterator; import java.util.Vector; public class Manager implements Serializable, InitActive { private static Logger logger = ProActiveLogger.getLogger(Loggers.P2P_SKELETONS_MANAGER); private Task rootTask = null; private Node[] nodes = null; private Worker workerGroup; private Vector tasks; private boolean isComputing = false; private Vector futureTaskList = new Vector(); private Vector pendingTaskList = new Vector(); private Vector workingWorkerList = new Vector(); private Vector allResults = new Vector(); private Result finalResult = null; /** * The no args constructor for ProActive. */ public Manager() { // nothing to do } /** * @param root the root task. * @param nodes the array of nodes for the computation. */ public Manager(Task root, Node[] nodes) { try { this.rootTask = (Task) ProActive.turnActive(root); } catch (ActiveObjectCreationException e) { logger.fatal("Problem with the turn active of the root task", e); throw new RuntimeException(e); } catch (NodeException e) { logger.fatal("Problem with the node of the root task", e); throw new RuntimeException(e); } this.nodes = nodes; } public void initActivity(Body body) { // Group of Worker Object[][] args = new Object[this.nodes.length][1]; for (int i = 0; i < args.length; i++) { args[i][0] = ProActive.getStubOnThis(); } try { this.workerGroup = (Worker) ProActiveGroup.newGroup(Worker.class.getName(), args, this.nodes); } catch (ClassNotReifiableException e) { logger.fatal("The Worker is not reifiable", e); } catch (ActiveObjectCreationException e) { logger.fatal("Problem with active objects creation", e); } catch (NodeException e) { logger.fatal("Problem with a node", e); } catch (ClassNotFoundException e) { logger.fatal("The class for worker was not found", e); } try { this.workerGroup.setWorkerGroup(this.workerGroup); } catch (ExceptionListException e) { // TODO find a fix logger.debug("A worker is down", e); } // Spliting logger.info("Compute the lower bound for the root task"); this.rootTask.initLowerBound(); logger.info("Compute the upper bound for the root task"); this.rootTask.initUpperBound(); logger.info("Calling for the first time split on the root task"); this.tasks = this.rootTask.split(); } public void start() { Body body = ProActive.getBodyOnThis(); if (!body.isActive()) { logger.fatal("The manager is not active"); throw new RuntimeException("The manager is not active"); } if (this.isComputing) { // nothing to do logger.info("The manager is already started"); return; } this.isComputing = true; Iterator taskIt = this.tasks.iterator(); Group group = ProActiveGroup.getGroup(this.workerGroup); Iterator workerIt = group.iterator(); while ((workerIt.hasNext()) && taskIt.hasNext()) { this.assignTaskToWorker((Worker) workerIt.next(), (Task) taskIt.next()); } while (taskIt.hasNext()) { // wait for a free worker int index = ProActive.waitForAny(this.futureTaskList); this.allResults.add(this.futureTaskList.get(index)); this.pendingTaskList.remove(index); Worker freeWorker = (Worker) this.workingWorkerList.remove(index); this.assignTaskToWorker(freeWorker, (Task) taskIt.next()); } // Serving requests and waiting for results Service service = new Service(body); while (this.allResults.size() != this.tasks.size()) { try { int index = ProActive.waitForAny(this.futureTaskList, 1000); this.allResults.add(this.futureTaskList.get(index)); // this.pendingTaskList.remove(index); } catch (ProActiveException e) { while (service.getRequestCount() > 0) { service.serveOldest(); } continue; } } // Set the final result this.finalResult = this.rootTask.gather((Result[]) this.allResults.toArray( new Result[this.allResults.size()])); this.isComputing = false; } /** * Assign a task to a worker. * @param worker the worker. * @param task the task. */ private void assignTaskToWorker(Worker worker, Task task) { this.futureTaskList.add(worker.execute(task)); this.pendingTaskList.add(task); this.workingWorkerList.add(worker); } public BooleanWrapper isFinish() { return new BooleanWrapper(!this.isComputing); } public Result getFinalResult() { return this.finalResult; } }
package org.opencms.jsp.util; import org.opencms.ade.contenteditor.CmsContentService; import org.opencms.file.CmsFile; import org.opencms.file.CmsObject; import org.opencms.file.CmsProject; import org.opencms.file.CmsResource; import org.opencms.file.CmsResourceFilter; import org.opencms.file.types.CmsResourceTypeXmlPage; import org.opencms.i18n.CmsEncoder; import org.opencms.i18n.CmsLocaleManager; import org.opencms.lock.CmsLock; import org.opencms.main.CmsException; import org.opencms.main.CmsRuntimeException; import org.opencms.main.OpenCms; import org.opencms.security.CmsPermissionSet; import org.opencms.util.CmsCollectionsGenericWrapper; import org.opencms.util.CmsConstantMap; import org.opencms.util.CmsUUID; import org.opencms.xml.I_CmsXmlDocument; import org.opencms.xml.content.CmsXmlContentFactory; import org.opencms.xml.page.CmsXmlPageFactory; import org.opencms.xml.types.I_CmsXmlContentValue; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import org.apache.commons.collections.Transformer; /** * Allows access to the individual elements of an XML content, usually used inside a loop of a * <code>&lt;cms:contentload&gt;</code> tag.<p> * * The implementation is optimized for performance and uses lazy initializing of the * requested values as much as possible.<p> * * @since 7.0.2 * * @see org.opencms.jsp.CmsJspTagContentAccess */ public class CmsJspContentAccessBean { /** * Provides Booleans that indicate if a specified locale is available in the XML content, * the input is assumed to be a String that represents a Locale.<p> */ public class CmsHasLocaleTransformer implements Transformer { /** * @see org.apache.commons.collections.Transformer#transform(java.lang.Object) */ public Object transform(Object input) { return Boolean.valueOf(getRawContent().hasLocale(CmsJspElFunctions.convertLocale(input))); } } /** * Provides Booleans that indicate if a specified path exists in the XML content, * the input is assumed to be a String that represents an xpath in the XML content.<p> */ public class CmsHasLocaleValueTransformer implements Transformer { /** * @see org.apache.commons.collections.Transformer#transform(java.lang.Object) */ public Object transform(Object input) { Locale locale = CmsJspElFunctions.convertLocale(input); Map<String, Boolean> result; if (getRawContent().hasLocale(locale)) { result = CmsCollectionsGenericWrapper.createLazyMap(new CmsHasValueTransformer(locale)); } else { result = CmsConstantMap.CONSTANT_BOOLEAN_FALSE_MAP; } return result; } } /** * Provides a Map with Booleans that indicate if a specified path exists in the XML content in the selected Locale, * the input is assumed to be a String that represents an xpath in the XML content.<p> */ public class CmsHasValueTransformer implements Transformer { /** The selected locale. */ private Locale m_selectedLocale; /** * Constructor with a locale.<p> * * @param locale the locale to use */ public CmsHasValueTransformer(Locale locale) { m_selectedLocale = locale; } /** * @see org.apache.commons.collections.Transformer#transform(java.lang.Object) */ public Object transform(Object input) { return Boolean.valueOf(getRawContent().hasValue(String.valueOf(input), m_selectedLocale)); } } /** * Transformer used for the 'imageDnd' EL attribute which is used to annotate images which can be replaced by drag and drop.<p> */ public class CmsImageDndTransformer implements Transformer { /** * Creates a new instance.<p> */ public CmsImageDndTransformer() { // do nothing } /** * @see org.apache.commons.collections.Transformer#transform(java.lang.Object) */ public Object transform(Object input) { String result; if (CmsJspContentAccessValueWrapper.isDirectEditEnabled(getCmsObject())) { result = createImageDndAttr( getRawContent().getFile().getStructureId(), String.valueOf(input), String.valueOf(getLocale())); } else { result = ""; } return result; } } /** * Provides a Map which lets the user access the list of element names from the selected locale in an XML content, * the input is assumed to be a String that represents a Locale.<p> */ public class CmsLocaleNamesTransformer implements Transformer { /** * @see org.apache.commons.collections.Transformer#transform(java.lang.Object) */ public Object transform(Object input) { Locale locale = CmsLocaleManager.getLocale(String.valueOf(input)); return getRawContent().getNames(locale); } } /** * Provides a Map which lets the user access the RDFA tags for all values in the selected locale in an XML content, * the input is assumed to be a String that represents a Locale.<p> */ public class CmsLocaleRdfaTransformer implements Transformer { /** * @see org.apache.commons.collections.Transformer#transform(java.lang.Object) */ public Object transform(Object input) { Locale locale = CmsLocaleManager.getLocale(String.valueOf(input)); Map<String, String> result; if (getRawContent().hasLocale(locale)) { result = CmsCollectionsGenericWrapper.createLazyMap(new CmsRdfaTransformer(locale)); } else { // return a map that always returns an empty string result = CmsConstantMap.CONSTANT_EMPTY_STRING_MAP; } return result; } } /** * Provides a Map which lets the user access sub value Lists from the selected locale in an XML content, * the input is assumed to be a String that represents a Locale.<p> */ public class CmsLocaleSubValueListTransformer implements Transformer { /** * @see org.apache.commons.collections.Transformer#transform(java.lang.Object) */ public Object transform(Object input) { Locale locale = CmsJspElFunctions.convertLocale(input); Map<String, List<CmsJspContentAccessValueWrapper>> result; if (getRawContent().hasLocale(locale)) { result = CmsCollectionsGenericWrapper.createLazyMap(new CmsSubValueListTransformer(locale)); } else { result = CmsConstantMap.CONSTANT_EMPTY_LIST_MAP; } return result; } } /** * Provides a Map which lets the user access value Lists from the selected locale in an XML content, * the input is assumed to be a String that represents a Locale.<p> */ public class CmsLocaleValueListTransformer implements Transformer { /** * @see org.apache.commons.collections.Transformer#transform(java.lang.Object) */ public Object transform(Object input) { Locale locale = CmsJspElFunctions.convertLocale(input); Map<String, List<CmsJspContentAccessValueWrapper>> result; if (getRawContent().hasLocale(locale)) { result = CmsCollectionsGenericWrapper.createLazyMap(new CmsValueListTransformer(locale)); } else { result = CmsConstantMap.CONSTANT_EMPTY_LIST_MAP; } return result; } } /** * Provides a Map which lets the user access a value from the selected locale in an XML content, * the input is assumed to be a String that represents a Locale.<p> */ public class CmsLocaleValueTransformer implements Transformer { /** * @see org.apache.commons.collections.Transformer#transform(java.lang.Object) */ public Object transform(Object input) { Locale locale = CmsLocaleManager.getLocale(String.valueOf(input)); Map<String, CmsJspContentAccessValueWrapper> result; if (getRawContent().hasLocale(locale)) { result = CmsCollectionsGenericWrapper.createLazyMap(new CmsValueTransformer(locale)); } else { result = CONSTANT_NULL_VALUE_WRAPPER_MAP; } return result; } } /** * Provides a Map which lets the user access the RDFA tag for a value in an XML content, * the input is assumed to be a String that represents an xpath in the XML content.<p> */ public class CmsRdfaTransformer implements Transformer { /** The selected locale. */ private Locale m_selectedLocale; /** * Constructor with a locale.<p> * * @param locale the locale to use */ public CmsRdfaTransformer(Locale locale) { m_selectedLocale = locale; } /** * @see org.apache.commons.collections.Transformer#transform(java.lang.Object) */ public Object transform(Object input) { if (CmsJspContentAccessValueWrapper.isDirectEditEnabled(getCmsObject())) { return CmsContentService.getRdfaAttributes(getRawContent(), m_selectedLocale, String.valueOf(input)); } else { return ""; } } } /** * Provides a Map which lets the user access sub value Lists in an XML content, * the input is assumed to be a String that represents an xpath in the XML content.<p> */ public class CmsSubValueListTransformer implements Transformer { /** The selected locale. */ private Locale m_selectedLocale; /** * Constructor with a locale.<p> * * @param locale the locale to use */ public CmsSubValueListTransformer(Locale locale) { m_selectedLocale = locale; } /** * @see org.apache.commons.collections.Transformer#transform(java.lang.Object) */ public Object transform(Object input) { List<I_CmsXmlContentValue> values = getRawContent().getSubValues(String.valueOf(input), m_selectedLocale); List<CmsJspContentAccessValueWrapper> result = new ArrayList<CmsJspContentAccessValueWrapper>(); Iterator<I_CmsXmlContentValue> i = values.iterator(); while (i.hasNext()) { // XML content API offers List of values only as Objects, must iterate them and create Strings I_CmsXmlContentValue value = i.next(); result.add(CmsJspContentAccessValueWrapper.createWrapper(getCmsObject(), value)); } return result; } } /** * Provides a Map which lets the user access value Lists in an XML content, * the input is assumed to be a String that represents an xpath in the XML content.<p> */ public class CmsValueListTransformer implements Transformer { /** The selected locale. */ private Locale m_selectedLocale; /** * Constructor with a locale.<p> * * @param locale the locale to use */ public CmsValueListTransformer(Locale locale) { m_selectedLocale = locale; } /** * @see org.apache.commons.collections.Transformer#transform(java.lang.Object) */ public Object transform(Object input) { List<I_CmsXmlContentValue> values = getRawContent().getValues(String.valueOf(input), m_selectedLocale); List<CmsJspContentAccessValueWrapper> result = new ArrayList<CmsJspContentAccessValueWrapper>(); Iterator<I_CmsXmlContentValue> i = values.iterator(); while (i.hasNext()) { // XML content API offers List of values only as Objects, must iterate them and create Strings I_CmsXmlContentValue value = i.next(); result.add(CmsJspContentAccessValueWrapper.createWrapper(getCmsObject(), value)); } return result; } } /** * Provides a Map which lets the user access a value in an XML content, * the input is assumed to be a String that represents an xpath in the XML content.<p> */ public class CmsValueTransformer implements Transformer { /** The selected locale. */ private Locale m_selectedLocale; /** * Constructor with a locale.<p> * * @param locale the locale to use */ public CmsValueTransformer(Locale locale) { m_selectedLocale = locale; } /** * @see org.apache.commons.collections.Transformer#transform(java.lang.Object) */ public Object transform(Object input) { I_CmsXmlContentValue value = getRawContent().getValue(String.valueOf(input), m_selectedLocale); return CmsJspContentAccessValueWrapper.createWrapper(getCmsObject(), value); } } /** Constant Map that always returns the {@link CmsJspContentAccessValueWrapper#NULL_VALUE_WRAPPER}.*/ protected static final Map<String, CmsJspContentAccessValueWrapper> CONSTANT_NULL_VALUE_WRAPPER_MAP = new CmsConstantMap<String, CmsJspContentAccessValueWrapper>( CmsJspContentAccessValueWrapper.NULL_VALUE_WRAPPER); /** The OpenCms context of the current user. */ private CmsObject m_cms; /** The XML content to access. */ private I_CmsXmlDocument m_content; /** The lazy initialized map for the "has locale" check. */ private Map<String, Boolean> m_hasLocale; /** The lazy initialized map for the "has locale value" check. */ private Map<String, Map<String, Boolean>> m_hasLocaleValue; /** Lazy map for imageDnd annotations. */ private Map<String, String> m_imageDnd; /** The locale used for accessing entries from the XML content, this may be a fallback default locale. */ private Locale m_locale; /** The lazy initialized with the locale names. */ private Map<String, List<String>> m_localeNames; /** Lazy initialized map of RDFA maps by locale. */ private Map<String, Map<String, String>> m_localeRdfa; /** The lazy initialized with the locale sub value lists. */ private Map<String, Map<String, List<CmsJspContentAccessValueWrapper>>> m_localeSubValueList; /** The lazy initialized with the locale value. */ private Map<String, Map<String, CmsJspContentAccessValueWrapper>> m_localeValue; /** The lazy initialized with the locale value lists. */ private Map<String, Map<String, List<CmsJspContentAccessValueWrapper>>> m_localeValueList; /** The original locale requested for accessing entries from the XML content. */ private Locale m_requestedLocale; /** Resource the XML content is created from. */ private CmsResource m_resource; /** The categories assigned to the resource. */ private CmsJspCategoryAccessBean m_categories; /** * No argument constructor, required for a JavaBean.<p> * * You must call {@link #init(CmsObject, Locale, I_CmsXmlDocument, CmsResource)} and provide the * required values when you use this constructor.<p> * * @see #init(CmsObject, Locale, I_CmsXmlDocument, CmsResource) */ public CmsJspContentAccessBean() { // must call init() manually later } /** * Creates a content access bean based on a Resource, using the current request context locale.<p> * * @param cms the OpenCms context of the current user * @param resource the resource to create the content from */ public CmsJspContentAccessBean(CmsObject cms, CmsResource resource) { this(cms, cms.getRequestContext().getLocale(), resource); } /** * Creates a content access bean based on a Resource.<p> * * @param cms the OpenCms context of the current user * @param locale the Locale to use when accessing the content * @param resource the resource to create the content from */ public CmsJspContentAccessBean(CmsObject cms, Locale locale, CmsResource resource) { init(cms, locale, null, resource); } /** * Creates a content access bean based on an XML content object.<p> * * @param cms the OpenCms context of the current user * @param locale the Locale to use when accessing the content * @param content the content to access */ public CmsJspContentAccessBean(CmsObject cms, Locale locale, I_CmsXmlDocument content) { init(cms, locale, content, content.getFile()); } /** * Generates the HTML attribute "data-imagednd" that enables the ADE image drag and drop feature.<p> * * @param structureId the structure ID of the XML document to insert the image * @param locale the locale to generate the image in * @param imagePath the XML path to the image source node. * * @return the HTML attribute "data-imagednd" that enables the ADE image drag and drop feature */ protected static String createImageDndAttr(CmsUUID structureId, String imagePath, String locale) { String attrValue = structureId + "|" + imagePath + "|" + locale; String escapedAttrValue = CmsEncoder.escapeXml(attrValue); return ("data-imagednd=\"" + escapedAttrValue + "\""); } /** * Returns the OpenCms user context this bean was initialized with.<p> * * @return the OpenCms user context this bean was initialized with */ public CmsObject getCmsObject() { return m_cms; } /** * Returns the raw VFS file object the content accessed by this bean was created from.<p> * * This can be used to access information from the raw file on a JSP.<p> * * Usage example on a JSP with the JSTL:<pre> * &lt;cms:contentload ... &gt; * &lt;cms:contentaccess var="content" /&gt; * Root path of the resource: ${content.file.rootPath} * &lt;/cms:contentload&gt;</pre> * * @return the raw VFS file object the content accessed by this bean was created from */ public CmsFile getFile() { return getRawContent().getFile(); } /** * Returns the site path of the current resource, that is the result of * {@link CmsObject#getSitePath(CmsResource)} with the resource * obtained by {@link #getFile()}.<p> * * Usage example on a JSP with the JSTL:<pre> * &lt;cms:contentload ... &gt; * &lt;cms:contentaccess var="content" /&gt; * Site path of the resource: "${content.filename}"; * &lt;/cms:contentload&gt;</pre> * * @return the site path of the current resource * * @see CmsObject#getSitePath(CmsResource) */ public String getFilename() { return m_cms.getSitePath(getRawContent().getFile()); } /** * Returns a lazy initialized Map that provides Booleans that indicate if a specified Locale is available * in the XML content.<p> * * The provided Map key is assumed to be a String that represents a Locale.<p> * * Usage example on a JSP with the JSTL:<pre> * &lt;cms:contentload ... &gt; * &lt;cms:contentaccess var="content" /&gt; * &lt;c:if test="${content.hasLocale['de']}" &gt; * The content has a "de" Locale! * &lt;/c:if&gt; * &lt;/cms:contentload&gt;</pre> * * @return a lazy initialized Map that provides Booleans that indicate if a specified Locale is available * in the XML content */ public Map<String, Boolean> getHasLocale() { if (m_hasLocale == null) { m_hasLocale = CmsCollectionsGenericWrapper.createLazyMap(new CmsHasLocaleTransformer()); } return m_hasLocale; } /** * Returns a lazy initialized Map that provides a Map that provides Booleans that * indicate if a value (xpath) is available in the XML content in the selected locale.<p> * * The first provided Map key is assumed to be a String that represents the Locale, * the second provided Map key is assumed to be a String that represents the xpath to the value.<p> * * Usage example on a JSP with the JSTL:<pre> * &lt;cms:contentload ... &gt; * &lt;cms:contentaccess var="content" /&gt; * &lt;c:if test="${content.hasLocaleValue['de']['Title']}" &gt; * The content has a "Title" value in the "de" Locale! * &lt;/c:if&gt; * &lt;/cms:contentload&gt;</pre> * * Please note that you can also test if a locale value exists like this:<pre> * &lt;c:if test="${content.value['de']['Title'].exists}" &gt; ... &lt;/c:if&gt;</pre> * * @return a lazy initialized Map that provides a Map that provides Booleans that * indicate if a value (xpath) is available in the XML content in the selected locale * * @see #getHasValue() */ public Map<String, Map<String, Boolean>> getHasLocaleValue() { if (m_hasLocaleValue == null) { m_hasLocaleValue = CmsCollectionsGenericWrapper.createLazyMap(new CmsHasLocaleValueTransformer()); } return m_hasLocaleValue; } /** * Returns a lazy initialized Map that provides Booleans that * indicate if a value (xpath) is available in the XML content in the current locale.<p> * * The provided Map key is assumed to be a String that represents the xpath to the value.<p> * * Usage example on a JSP with the JSTL:<pre> * &lt;cms:contentload ... &gt; * &lt;cms:contentaccess var="content" /&gt; * &lt;c:if test="${content.hasValue['Title']}" &gt; * The content has a "Title" value in the current locale! * &lt;/c:if&gt; * &lt;/cms:contentload&gt;</pre> * * Please note that you can also test if a value exists like this:<pre> * &lt;c:if test="${content.value['Title'].exists}" &gt; ... &lt;/c:if&gt;</pre> * * @return a lazy initialized Map that provides Booleans that * indicate if a value (xpath) is available in the XML content in the current locale * * @see #getHasLocaleValue() */ public Map<String, Boolean> getHasValue() { return getHasLocaleValue().get(getLocale()); } /** * Returns the structure ID of the current resource, that is the ID of * the resource obtained by {@link #getFile()}.<p> * * Usage example on a JSP with the JSTL:<pre> * &lt;cms:contentload ... &gt; * &lt;cms:contentaccess var="content" /&gt; * Site path of the resource: "${content.id}"; * &lt;/cms:contentload&gt;</pre> * * @return the structure ID of the current resource * * @see CmsResource#getStructureId() */ public CmsUUID getId() { return getRawContent().getFile().getStructureId(); } /** * Gets the lazy imageDnd map.<p> * * @return the lazy imageDnd map */ public Map<String, String> getImageDnd() { if (m_imageDnd == null) { m_imageDnd = CmsCollectionsGenericWrapper.createLazyMap(new CmsImageDndTransformer()); } return m_imageDnd; } public boolean getIsEditable() { boolean result = false; try { CmsObject cms; if (m_cms.getRequestContext().getCurrentProject().isOnlineProject()) { // we are in the online project, which means we must first switch to an offline project cms = OpenCms.initCmsObject(m_cms); List<CmsProject> projects = OpenCms.getOrgUnitManager().getAllAccessibleProjects( cms, cms.getRequestContext().getOuFqn(), false); if ((projects != null) && (projects.size() > 0)) { // there is at least one project available for (CmsProject p : projects) { // need to iterate because the online project will be part of the result list if (!p.isOnlineProject()) { cms.getRequestContext().setCurrentProject(p); break; } } } } else { // not in the online project, so just use the current project cms = m_cms; } result = cms.hasPermissions( m_resource, CmsPermissionSet.ACCESS_WRITE, false, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED); if (result) { // still need to check the lock status CmsLock lock = cms.getLock(m_resource); if (!lock.isLockableBy(cms.getRequestContext().getCurrentUser())) { // resource is locked from a different user result = false; } } } catch (@SuppressWarnings("unused") CmsException e) { // should not happen, in case it does just assume not editable } return result; } /** * Returns the Locale this bean is using for content access, this may be a default fall back Locale.<p> * * @return the Locale this bean is using for content access, this may be a default fall back Locale */ public Locale getLocale() { // check the content if the locale has not been set yet if (m_locale == null) { getRawContent(); } return m_locale; } /** * Returns a lazy initialized Map that provides a List with all available elements paths (Strings) * used in this document in the selected locale.<p> * * The provided Map key is assumed to be a String that represents the Locale.<p> * * Usage example on a JSP with the JSTL:<pre> * &lt;cms:contentload ... &gt; * &lt;cms:contentaccess var="content" /&gt; * &lt;c:forEach items="${content.localeNames['de']}" var="elem"&gt; * &lt;c:out value="${elem}" /&gt; * &lt;/c:forEach&gt; * &lt;/cms:contentload&gt;</pre> * * @return a lazy initialized Map that provides a Map that provides * values from the XML content in the selected locale * * @see #getNames() */ public Map<String, List<String>> getLocaleNames() { if (m_localeNames == null) { m_localeNames = CmsCollectionsGenericWrapper.createLazyMap(new CmsLocaleNamesTransformer()); } return m_localeNames; } /** * Returns the map of RDFA maps by locale.<p> * * @return the map of RDFA maps by locale */ public Map<String, Map<String, String>> getLocaleRdfa() { if (m_localeRdfa == null) { m_localeRdfa = CmsCollectionsGenericWrapper.createLazyMap(new CmsLocaleRdfaTransformer()); } return m_localeRdfa; } /** * Returns a lazy initialized Map that provides a Map that provides Lists of direct sub values * from the XML content in the selected locale.<p> * * The first provided Map key is assumed to be a String that represents the Locale, * the second provided Map key is assumed to be a String that represents the xpath to the value.<p> * * Usage example on a JSP with the JSTL:<pre> * &lt;cms:contentload ... &gt; * &lt;cms:contentaccess var="content" /&gt; * &lt;c:forEach var="item" items="${content.localeSubValueList['de']['Items']}"&gt; * ${item} * &lt;/c:forEach&gt; * &lt;/cms:contentload&gt;</pre> * * @return a lazy initialized Map that provides a Map that provides Lists of direct sub values * from the XML content in the selected locale * * @see #getLocaleValue() */ public Map<String, Map<String, List<CmsJspContentAccessValueWrapper>>> getLocaleSubValueList() { if (m_localeSubValueList == null) { m_localeSubValueList = CmsCollectionsGenericWrapper.createLazyMap(new CmsLocaleSubValueListTransformer()); } return m_localeSubValueList; } /** * Returns a lazy initialized Map that provides a Map that provides * values from the XML content in the selected locale.<p> * * The first provided Map key is assumed to be a String that represents the Locale, * the second provided Map key is assumed to be a String that represents the xpath to the value.<p> * * Usage example on a JSP with the JSTL:<pre> * &lt;cms:contentload ... &gt; * &lt;cms:contentaccess var="content" /&gt; * The Title in Locale "de": ${content.localeValue['de']['Title']} * &lt;/cms:contentload&gt;</pre> * * @return a lazy initialized Map that provides a Map that provides * values from the XML content in the selected locale * * @see #getValue() */ public Map<String, Map<String, CmsJspContentAccessValueWrapper>> getLocaleValue() { if (m_localeValue == null) { m_localeValue = CmsCollectionsGenericWrapper.createLazyMap(new CmsLocaleValueTransformer()); } return m_localeValue; } /** * Returns a lazy initialized Map that provides a Map that provides Lists of values * from the XML content in the selected locale.<p> * * The first provided Map key is assumed to be a String that represents the Locale, * the second provided Map key is assumed to be a String that represents the xpath to the value.<p> * * Usage example on a JSP with the JSTL:<pre> * &lt;cms:contentload ... &gt; * &lt;cms:contentaccess var="content" /&gt; * &lt;c:forEach var="teaser" items="${content.localeValueList['de']['Teaser']}"&gt; * ${teaser} * &lt;/c:forEach&gt; * &lt;/cms:contentload&gt;</pre> * * @return a lazy initialized Map that provides a Map that provides Lists of values * from the XML content in the selected locale * * @see #getLocaleValue() */ public Map<String, Map<String, List<CmsJspContentAccessValueWrapper>>> getLocaleValueList() { if (m_localeValueList == null) { m_localeValueList = CmsCollectionsGenericWrapper.createLazyMap(new CmsLocaleValueListTransformer()); } return m_localeValueList; } /** * Returns a list with all available elements paths (Strings) used in this document * in the current locale.<p> * * Usage example on a JSP with the JSTL:<pre> * &lt;cms:contentload ... &gt; * &lt;cms:contentaccess var="content" /&gt; * &lt;c:forEach items="${content.names}" var="elem"&gt; * &lt;c:out value="${elem}" /&gt; * &lt;/c:forEach&gt; * &lt;/cms:contentload&gt;</pre> * * @return a list with all available elements paths (Strings) used in this document in the current locale * * @see #getLocaleNames() */ public List<String> getNames() { return getLocaleNames().get(getLocale()); } /** * Returns the raw XML content object that is accessed by this bean.<p> * * @return the raw XML content object that is accessed by this bean */ public I_CmsXmlDocument getRawContent() { if (m_content == null) { // content has not been provided, must unmarshal XML first CmsFile file; try { file = m_cms.readFile(m_resource); if (CmsResourceTypeXmlPage.isXmlPage(file)) { // this is an XML page m_content = CmsXmlPageFactory.unmarshal(m_cms, file); } else { // this is an XML content m_content = CmsXmlContentFactory.unmarshal(m_cms, file); } } catch (CmsException e) { // this usually should not happen, as the resource already has been read by the current user // and we just upgrade it to a File throw new CmsRuntimeException( Messages.get().container(Messages.ERR_XML_CONTENT_UNMARSHAL_1, m_resource.getRootPath()), e); } } // make sure a valid locale is used if (m_locale == null) { m_locale = m_requestedLocale; // check if the requested locale is available if (!m_content.hasLocale(m_locale)) { Iterator<Locale> it = OpenCms.getLocaleManager().getDefaultLocales().iterator(); while (it.hasNext()) { Locale locale = it.next(); if (m_content.hasLocale(locale)) { // found a matching locale m_locale = locale; break; } } } } return m_content; } /** * Returns RDFA by value name map.<p> * * @return RDFA by value name map */ public Map<String, String> getRdfa() { return getLocaleRdfa().get(getLocale()); } /** * Reads and returns the categories assigned to the content's VFS resource. * @return the categories assigned to the content's VFS resource. */ public CmsJspCategoryAccessBean getReadCategories() { if (null == m_categories) { m_categories = readCategories(); } return m_categories; } /** * Returns a lazy initialized Map that provides Lists of direct sub values * of the given value from the XML content in the current locale.<p> * * The provided Map key is assumed to be a String that represents the xpath to the value. * Use this method in case you want to iterate over a List of sub values from the XML content.<p> * * Usage example on a JSP with the JSTL:<pre> * &lt;cms:contentload ... &gt; * &lt;cms:contentaccess var="content" /&gt; * &lt;c:forEach var="teaser" items="${content.subValueList['Items']}"&gt; * ${item} * &lt;/c:forEach&gt; * &lt;/cms:contentload&gt;</pre> * * @return a lazy initialized Map that provides Lists of values from the XML content in the current locale * * @see #getLocaleValueList() */ public Map<String, List<CmsJspContentAccessValueWrapper>> getSubValueList() { return getLocaleSubValueList().get(getLocale()); } /** * Returns a lazy initialized Map that provides values from the XML content in the current locale.<p> * * The provided Map key is assumed to be a String that represents the xpath to the value.<p> * * Usage example on a JSP with the JSTL:<pre> * &lt;cms:contentload ... &gt; * &lt;cms:contentaccess var="content" /&gt; * The Title: ${content.value['Title']} * &lt;/cms:contentload&gt;</pre> * * @return a lazy initialized Map that provides values from the XML content in the current locale * * @see #getLocaleValue() */ public Map<String, CmsJspContentAccessValueWrapper> getValue() { return getLocaleValue().get(getLocale()); } /** * Returns a lazy initialized Map that provides Lists of values from the XML content in the current locale.<p> * * The provided Map key is assumed to be a String that represents the xpath to the value. * Use this method in case you want to iterate over a List of values form the XML content.<p> * * Usage example on a JSP with the JSTL:<pre> * &lt;cms:contentload ... &gt; * &lt;cms:contentaccess var="content" /&gt; * &lt;c:forEach var="teaser" items="${content.valueList['Teaser']}"&gt; * ${teaser} * &lt;/c:forEach&gt; * &lt;/cms:contentload&gt;</pre> * * @return a lazy initialized Map that provides Lists of values from the XML content in the current locale * * @see #getLocaleValueList() */ public Map<String, List<CmsJspContentAccessValueWrapper>> getValueList() { return getLocaleValueList().get(getLocale()); } /** * Returns an instance of a VFS access bean, * initialized with the OpenCms user context this bean was created with.<p> * * @return an instance of a VFS access bean, * initialized with the OpenCms user context this bean was created with */ public CmsJspVfsAccessBean getVfs() { return CmsJspVfsAccessBean.create(m_cms); } /** * Initialize this instance.<p> * * @param cms the OpenCms context of the current user * @param locale the Locale to use when accessing the content * @param content the XML content to access * @param resource the resource to create the content from */ public void init(CmsObject cms, Locale locale, I_CmsXmlDocument content, CmsResource resource) { m_cms = cms; m_requestedLocale = locale; m_content = content; m_resource = resource; } /** * Reads the categories assigned to the content's VFS resource. * @return the categories assigned to the content's VFS resource. */ private CmsJspCategoryAccessBean readCategories() { return new CmsJspCategoryAccessBean(getCmsObject(), m_resource); } }
package org.pentaho.agilebi.spoon; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import org.apache.commons.httpclient.Credentials; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.multipart.FilePart; import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; import org.apache.commons.httpclient.methods.multipart.Part; import org.dom4j.DocumentHelper; import org.pentaho.agilebi.modeler.ModelerException; import org.pentaho.agilebi.modeler.ModelerWorkspace; import org.pentaho.agilebi.spoon.publish.BiServerConnection; import org.pentaho.agilebi.spoon.publish.PublishOverwriteDelegate; import org.pentaho.commons.util.repository.type.CmisObject; import org.pentaho.commons.util.repository.type.PropertiesBase; import org.pentaho.commons.util.repository.type.TypesOfFileableObjects; import org.pentaho.di.core.Const; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleDatabaseException; import org.pentaho.di.core.gui.SpoonFactory; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.metadata.model.LogicalModel; import org.pentaho.metadata.util.MondrianModelExporter; import org.pentaho.platform.api.repository.ISolutionRepository; import org.pentaho.platform.dataaccess.client.ConnectionServiceClient; import org.pentaho.platform.dataaccess.datasource.IConnection; import org.pentaho.platform.dataaccess.datasource.beans.Connection; import org.pentaho.platform.dataaccess.datasource.wizard.service.ConnectionServiceException; import org.pentaho.platform.util.client.BiPlatformRepositoryClient; import org.pentaho.platform.util.client.BiPlatformRepositoryClientNavigationService; import org.pentaho.platform.util.client.PublisherUtil; import org.pentaho.platform.util.client.ServiceException; /** * A utility class for publishing models to a BI server. Also helps synchronize database connections. * @author jamesdixon * */ public class ModelServerPublish { public static final int PUBLISH_UNKNOWN_PROBLEM = -1; public static final int PUBLISH_FILE_EXISTS = 1; public static final int PUBLISH_FAILED = 2; public static final int PUBLISH_SUCCESS = 3; public static final int PUBLISH_INVALID_PASSWORD = 4; public static final int PUBLISH_INVALID_USER_OR_PASSWORD = 5; public static final int PUBLISH_DATASOURCE_PROBLEM = 6; public static final int PUBLISH_CATALOG_EXISTS = 7; public static final int REMOTE_CONNECTION_MISSING = 1; public static final int REMOTE_CONNECTION_DIFFERENT = 2; public static final int REMOTE_CONNECTION_SAME = 4; public static final int REMOTE_CONNECTION_MUST_BE_JNDI = 8; private BiServerConnection biServerConnection; private IConnection remoteConnection; private ModelerWorkspace model; private int serviceClientStatus = 0; private BiPlatformRepositoryClientNavigationService navigationService; //TODO: find a better way to communicate the UI delegate public static PublishOverwriteDelegate overwriteDelegate; public ModelServerPublish() { } /** * Lists the database connections that are available on the current BI server * @return * @throws ConnectionServiceException */ public List<IConnection> listRemoteConnections() throws ConnectionServiceException { // get information about the remote connection ConnectionServiceClient serviceClient = new ConnectionServiceClient(); serviceClient.setHost(biServerConnection.getUrl()); serviceClient.setUserId(biServerConnection.getUserId()); serviceClient.setPassword(biServerConnection.getPassword()); List<IConnection> connections = serviceClient.getConnections(); // serviceClientStatus = serviceClient.getStatus(); return connections; } /** * Returns the remote connection. If the force flag is set the connection is * always refreshed from the remote BI server. If the force flag is not set * a cached connection is returned. * @return */ public IConnection getRemoteConnection( String connectionName, boolean force ) throws ConnectionServiceException { if( remoteConnection == null || force ) { // get information about the remote connection ConnectionServiceClient serviceClient = new ConnectionServiceClient(); serviceClient.setHost(biServerConnection.getUrl()); serviceClient.setUserId(biServerConnection.getUserId()); serviceClient.setPassword(biServerConnection.getPassword()); remoteConnection = serviceClient.getConnectionByName(connectionName); // serviceClientStatus = serviceClient.getStatus(); } return remoteConnection; } /** * Compares a provided DatabaseMeta with the database connections available on the current BI server. * Returns the result of the comparison - missing, same, different. * This only works for native connections (JNDI) * @param databaseMeta * @return * @throws ConnectionServiceException * @throws KettleDatabaseException */ public int compareDataSourceWithRemoteConnection( DatabaseMeta databaseMeta ) throws ConnectionServiceException, KettleDatabaseException { int result = 0; if( databaseMeta.getAccessType() != DatabaseMeta.TYPE_ACCESS_NATIVE) { result += REMOTE_CONNECTION_MUST_BE_JNDI; } // compare the local database meta with the remote connection String connectionName = databaseMeta.getName(); IConnection connection = getRemoteConnection( connectionName, false ); if( connection == null ) { // the connection does not exist (with the same name) on the remote BI server result += REMOTE_CONNECTION_MISSING; return result; } // see if the driver, url, and user are the same for both connections... String url = databaseMeta.getURL(); String userName = databaseMeta.getUsername(); String driverClass = databaseMeta.getDriverClass(); boolean urlMatch = url.equals( connection.getUrl() ); boolean userMatch = (userName == null && connection.getUsername() == null )|| userName.equals( connection.getUsername() ); boolean driverMatch = (driverClass == null && connection.getDriverClass() == null )|| driverClass.equals( connection.getDriverClass() ); // return 'same' or 'different' if( urlMatch && userMatch && driverMatch) { result += REMOTE_CONNECTION_SAME; } else { result += REMOTE_CONNECTION_DIFFERENT; } return result; } /** * Returns a list of repository folders * @param depth * @return * @throws Exception */ public List<CmisObject> getRepositoryFiles( CmisObject folder, int depth, boolean foldersOnly ) throws Exception { getNavigationService(); TypesOfFileableObjects folderTypes; if( foldersOnly ) { folderTypes = new TypesOfFileableObjects( TypesOfFileableObjects.FOLDERS ); } else { folderTypes = new TypesOfFileableObjects( TypesOfFileableObjects.ANY ); } String startLocation = ""; //$NON-NLS-1$ if( folder != null ) { startLocation = folder.findIdProperty( PropertiesBase.OBJECTID, null ); } List<CmisObject> objects = getNavigationService().getDescendants(BiPlatformRepositoryClient.PLATFORMORIG, startLocation, folderTypes, depth, null, false, false); return objects; } public int publishFile( String repositoryPath, File[] files, boolean showFeedback ) { for(int i=0; i< files.length; i++){ if(checkForExistingFile(repositoryPath, files[i].getName())){ boolean overwrite = overwriteDelegate.handleOverwriteNotification(files[i].getName()); if(overwrite == false){ return PublisherUtil.FILE_EXISTS; } } } String DEFAULT_PUBLISH_URL = biServerConnection.getUrl()+"RepositoryFilePublisher"; //$NON-NLS-1$ int result = PublisherUtil.publish(DEFAULT_PUBLISH_URL, repositoryPath, files, biServerConnection.getPublishPassword(), biServerConnection.getUserId(), biServerConnection.getPassword(), true, true); if( showFeedback ) { showFeedback( result ); } return result; } /** * Publishes a datasource to the current BI server * @param databaseMeta * @param update * @return * @throws KettleDatabaseException */ private boolean publishDataSource( DatabaseMeta databaseMeta, boolean update ) throws KettleDatabaseException, ConnectionServiceException { // Create a connection service client and give it the connection for the current BI server ConnectionServiceClient serviceClient = new ConnectionServiceClient(); serviceClient.setHost(biServerConnection.getUrl()); serviceClient.setUserId(biServerConnection.getUserId()); serviceClient.setPassword(biServerConnection.getPassword()); // create a new connection object and populate it from the databaseMeta Connection connection = new Connection(); connection.setDriverClass(databaseMeta.getDriverClass()); connection.setName(databaseMeta.getName()); connection.setPassword(databaseMeta.getPassword()); connection.setUrl(databaseMeta.getURL()); connection.setUsername(databaseMeta.getUsername()); // call updateConnection or addConnection boolean result = false; if( update ) { result = serviceClient.updateConnection(connection); } else { result = serviceClient.addConnection(connection); } // serviceClientStatus = serviceClient.getStatus(); return result; } /** * Publishes a file to the current BI server * @param publishPath * @param publishFile * @param jndiName * @param modelId * @param enableXmla * @return * @throws Exception * @throws UnsupportedEncodingException */ public int publish( String publishPath, File publishFile, String jndiName, String modelId, boolean enableXmla) throws Exception, UnsupportedEncodingException { String url = biServerConnection.getUrl(); StringBuilder sb = new StringBuilder(); sb.append(url); if( url.charAt( url.length()-1) != ISolutionRepository.SEPARATOR ) { sb.append( ISolutionRepository.SEPARATOR ); } sb.append( "MondrianCatalogPublisher?publishPath=" ) //$NON-NLS-1$ .append( URLEncoder.encode(publishPath, "UTF-8") ) //$NON-NLS-1$ .append( "&publishKey=" ).append( getPasswordKey(new String(biServerConnection.getPublishPassword()))) //$NON-NLS-1$ .append( "&overwrite=true&mkdirs=true" ) //$NON-NLS-1$ .append( "&jndiName=" ).append( jndiName ) //$NON-NLS-1$ .append( "&enableXmla=" ).append( enableXmla ) //$NON-NLS-1$ .append( "&userid=" ).append( biServerConnection.getUserId() ) //$NON-NLS-1$ .append( "&password=" ).append( biServerConnection.getPassword() ); //$NON-NLS-1$ String fullUrl = sb.toString(); PostMethod filePost = new PostMethod(fullUrl); ArrayList<Part> parts = new ArrayList<Part>(); try { parts.add(new FilePart(publishFile.getName(), publishFile)); } catch (FileNotFoundException e) { // file is not existing or not readable, this should not happen e.printStackTrace(); } filePost.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), filePost.getParams())); HttpClient client = getClient(biServerConnection.getUserId(), biServerConnection.getPassword()); try { serviceClientStatus = client.executeMethod(filePost); } catch (IOException e) { throw new Exception(e.getMessage(), e); } // if (serviceClientStatus != HttpStatus.SC_OK) { // if (serviceClientStatus == HttpStatus.SC_MOVED_TEMPORARILY) { // throw new Exception(BaseMessages.getString(this.getClass(), "ModelServerPublish.Errors.InvalidUser")); //$NON-NLS-1$ // } else { // throw new Exception(BaseMessages.getString(this.getClass(), "ModelServerPublish.Errors.UnknownError", Integer.toString(serviceClientStatus)) ); //$NON-NLS-1$ // } else { try { String postResult = filePost.getResponseBodyAsString(); int publishResult = Integer.parseInt(postResult.trim()); return publishResult; } catch (IOException e) { e.printStackTrace(); return ModelServerPublish.PUBLISH_UNKNOWN_PROBLEM; } catch(NumberFormatException e){ e.printStackTrace(); return ModelServerPublish.PUBLISH_UNKNOWN_PROBLEM; } } private HttpClient getClient( String serverUserId, String serverPassword) { HttpClient client = new HttpClient(); // If server userid/password was supplied, use basic authentication to // authenticate with the server. if (serverUserId.length() > 0 && serverPassword.length() > 0) { Credentials creds = new UsernamePasswordCredentials(serverUserId, serverPassword); client.getState().setCredentials(AuthScope.ANY, creds); client.getParams().setAuthenticationPreemptive(true); } return client; } private String getPasswordKey(String passWord) { try { MessageDigest md = MessageDigest.getInstance("MD5"); //$NON-NLS-1$ md.reset(); md.update(passWord.getBytes("UTF-8")); //$NON-NLS-1$ byte[] digest = md.digest("P3ntah0Publ1shPa55w0rd".getBytes("UTF-8")); //$NON-NLS-1$//$NON-NLS-2$ StringBuilder buf = new StringBuilder(digest.length + 1); String s; for (byte aDigest : digest) { s = Integer.toHexString(0xFF & aDigest); buf.append((s.length() == 1) ? "0" : "").append(s); //$NON-NLS-1$ //$NON-NLS-2$ } return buf.toString(); } catch (Exception ex) { ex.printStackTrace(); } return null; } /** * Publishes the specified model, schema, and connection to the current BI server * @param schemaName * @param jndiName * @param modelName * @param showFeedback * @throws Exception */ public void publishToServer( String schemaName, String jndiName, String modelName, String repositoryPath, String selectedPath, boolean publishDatasource, boolean showFeedback, boolean isExistentDatasource, String fileName) throws Exception { File files[] = { new File(fileName) }; publishFile(selectedPath, files, false); if( publishDatasource ) { // DatabaseMeta databaseMeta = model.getModelSource().getDatabaseMeta(); // publishDataSource(databaseMeta, isExistentDatasource); } publishOlapSchemaToServer( schemaName, jndiName , modelName, repositoryPath, true ); } public void publishPrptToServer(String theXmiPublishingPath, String thePrptPublishingPath, boolean publishDatasource, boolean isExistentDatasource, boolean publishXmi, String xmi, String prpt) throws Exception { File thePrpt[] = { new File(prpt) }; int result = publishFile(thePrptPublishingPath, thePrpt, !publishXmi /*show feedback here if not publishing xmi*/); if(result != PublisherUtil.FILE_ADD_SUCCESSFUL){ return; } if(publishXmi){ File theXmi[] = { new File(xmi) }; publishFile(theXmiPublishingPath, theXmi, true); } if( publishDatasource ) { // DatabaseMeta databaseMeta = model.getModelSource().getDatabaseMeta(); // publishDataSource(databaseMeta, isExistentDatasource); } } public boolean checkForExistingFile(String path, String name){ try { if(path == null || name == null){ return false; } List<String> folders = new ArrayList(Arrays.asList(path.split(""+ISolutionRepository.SEPARATOR))); int idx = 0; CmisObject folder = null; while(folders.size() > 0){ folder = findFolder(folders.get(idx), folder); if(folder == null){ return false; } folders.remove(idx); } List<CmisObject> files = getNavigationService().getDescendants(BiPlatformRepositoryClient.PLATFORMORIG, folder.findIdProperty( PropertiesBase.OBJECTID, null ), new TypesOfFileableObjects( TypesOfFileableObjects.ANY), 1, null, false, false); for(CmisObject f : files){ if(f.findStringProperty( CmisObject.NAME, null ).equals(name)){ return true; } } } catch (Exception e) { e.printStackTrace(); } return false; } private CmisObject findFolder(String folder, CmisObject parent) throws Exception{ List<CmisObject> solutions = getNavigationService().getDescendants(BiPlatformRepositoryClient.PLATFORMORIG, (parent != null)? parent.findIdProperty( PropertiesBase.OBJECTID, null ) : "", new TypesOfFileableObjects( TypesOfFileableObjects.FOLDERS ), 1, null, false, false); for(CmisObject obj : solutions){ if(obj.findStringProperty( CmisObject.NAME, null ).equals(folder)){ return obj; } } return null; } public boolean checkDataSource( boolean autoMode ) throws KettleDatabaseException, ConnectionServiceException { // check the data source // DatabaseMeta databaseMeta = model.getModelSource().getDatabaseMeta(); int compare = 0;//compareDataSourceWithRemoteConnection(databaseMeta); String serverName = biServerConnection.getName(); boolean nonJndi = (compare & ModelServerPublish.REMOTE_CONNECTION_MUST_BE_JNDI) > 0; boolean missing = (compare & ModelServerPublish.REMOTE_CONNECTION_MISSING) > 0; boolean different = (compare & ModelServerPublish.REMOTE_CONNECTION_DIFFERENT) > 0; // boolean same = (compare | ModelServerPublish.REMOTE_CONNECTION_SAME) > 0; if(missing && !nonJndi) { if( !autoMode && !SpoonFactory.getInstance().messageBox( BaseMessages.getString(this.getClass(), "ModelServerPublish.Datasource.OkToPublish" ), //$NON-NLS-1$ BaseMessages.getString(this.getClass(), "ModelServerPublish.MessageBox.Title", serverName), true, Const.INFO) ) { //$NON-NLS-1$ SpoonFactory.getInstance().messageBox( BaseMessages.getString(this.getClass(), "ModelServerPublish.Datasource.PublishCancelled" ), //$NON-NLS-1$ BaseMessages.getString(this.getClass(), "ModelServerPublish.MessageBox.Title", serverName), false, Const.ERROR); //$NON-NLS-1$ return false; } boolean ok = true;//publishDataSource(databaseMeta, false); if( !autoMode && ok ) { SpoonFactory.getInstance().messageBox( BaseMessages.getString(this.getClass(), "ModelServerPublish.Datasource.Added" ), //$NON-NLS-1$ BaseMessages.getString(this.getClass(), "ModelServerPublish.MessageBox.Title", serverName), false, Const.INFO); //$NON-NLS-1$ } return ok; } else if(missing && nonJndi) { if( !autoMode ) { SpoonFactory.getInstance().messageBox( BaseMessages.getString(this.getClass(), "ModelServerPublish.Datasource.NonJNDI" ), //$NON-NLS-1$ BaseMessages.getString(this.getClass(), "ModelServerPublish.MessageBox.Title", serverName), false, Const.ERROR); //$NON-NLS-1$ } return false; } else if( different && !nonJndi ) { if( !autoMode && !SpoonFactory.getInstance().messageBox( BaseMessages.getString(this.getClass(), "ModelServerPublish.Datasource.IsDifferent" ), //$NON-NLS-1$ BaseMessages.getString(this.getClass(), "ModelServerPublish.MessageBox.Title", serverName), true, Const.INFO) ) { //$NON-NLS-1$ return false; } // replace the data source boolean ok = true;//publishDataSource(databaseMeta, true); if( !autoMode && ok ) { SpoonFactory.getInstance().messageBox( BaseMessages.getString(this.getClass(), "ModelServerPublish.Datasource.Updated" ), //$NON-NLS-1$ BaseMessages.getString(this.getClass(), "ModelServerPublish.MessageBox.Title", serverName), false, Const.ERROR); //$NON-NLS-1$ } return ok; } else if(different && nonJndi) { if( !autoMode ) { SpoonFactory.getInstance().messageBox( BaseMessages.getString(this.getClass(), "ModelServerPublish.Datasource.CannotUpdate" ), //$NON-NLS-1$ BaseMessages.getString(this.getClass(), "ModelServerPublish.MessageBox.Title", serverName), false, Const.ERROR); //$NON-NLS-1$ } return false; } return false; } protected void showFeedback( int result ) { String serverName = biServerConnection.getName(); switch (result) { case ModelServerPublish.PUBLISH_CATALOG_EXISTS: { SpoonFactory.getInstance().messageBox( BaseMessages.getString(this.getClass(), "ModelServerPublish.Publish.CatalogExists" ), //$NON-NLS-1$ BaseMessages.getString(this.getClass(), "ModelServerPublish.MessageBox.Title", serverName), false, Const.ERROR); //$NON-NLS-1$ break; } case ModelServerPublish.PUBLISH_DATASOURCE_PROBLEM: { SpoonFactory.getInstance().messageBox( BaseMessages.getString(this.getClass(), "ModelServerPublish.Publish.DataSourceProblem" ), //$NON-NLS-1$ BaseMessages.getString(this.getClass(), "ModelServerPublish.MessageBox.Title", serverName), false, Const.ERROR); //$NON-NLS-1$ break; } case ModelServerPublish.PUBLISH_FAILED: { SpoonFactory.getInstance().messageBox( BaseMessages.getString(this.getClass(), "ModelServerPublish.Publish.Failed" ), //$NON-NLS-1$ BaseMessages.getString(this.getClass(), "ModelServerPublish.MessageBox.Title", serverName), false, Const.ERROR); //$NON-NLS-1$ break; } case ModelServerPublish.PUBLISH_FILE_EXISTS: { SpoonFactory.getInstance().messageBox( BaseMessages.getString(this.getClass(), "ModelServerPublish.Publish.FileExists" ), //$NON-NLS-1$ BaseMessages.getString(this.getClass(), "ModelServerPublish.MessageBox.Title", serverName), false, Const.ERROR); //$NON-NLS-1$ break; } case ModelServerPublish.PUBLISH_INVALID_PASSWORD: { SpoonFactory.getInstance().messageBox( BaseMessages.getString(this.getClass(), "ModelServerPublish.Publish.BadPassword" ), //$NON-NLS-1$ BaseMessages.getString(this.getClass(), "ModelServerPublish.MessageBox.Title", serverName), false, Const.ERROR); //$NON-NLS-1$ break; } case ModelServerPublish.PUBLISH_INVALID_USER_OR_PASSWORD: { SpoonFactory.getInstance().messageBox( BaseMessages.getString(this.getClass(), "ModelServerPublish.Errors.InvalidUser" ), //$NON-NLS-1$ BaseMessages.getString(this.getClass(), "ModelServerPublish.MessageBox.Title", serverName), false, Const.ERROR); //$NON-NLS-1$ break; } case ModelServerPublish.PUBLISH_SUCCESS: { SpoonFactory.getInstance().messageBox( BaseMessages.getString(this.getClass(), "ModelServerPublish.Publish.Success" ), //$NON-NLS-1$ BaseMessages.getString(this.getClass(), "ModelServerPublish.MessageBox.Title", serverName), false, Const.INFO); //$NON-NLS-1$ break; } case ModelServerPublish.PUBLISH_UNKNOWN_PROBLEM: { SpoonFactory.getInstance().messageBox( BaseMessages.getString(this.getClass(), "ModelServerPublish.Publish.UnknownProblem" ), //$NON-NLS-1$ BaseMessages.getString(this.getClass(), "ModelServerPublish.MessageBox.Title", serverName), false, Const.ERROR); //$NON-NLS-1$ break; } } } private void publishOlapSchemaToServer( String schemaFilePath, String jndiName, String modelName, String repositoryPath, boolean showFeedback ) throws Exception { File modelsDir = new File("models"); //$NON-NLS-1$ if(!modelsDir.exists()) { modelsDir.mkdir(); } File publishFile = new File(modelsDir, schemaFilePath); publishFile.createNewFile(); LogicalModel lModel = this.model.getDomain().getLogicalModels().get(0); String catName = lModel.getName(Locale.getDefault().toString()); lModel.setProperty("MondrianCatalogRef", catName); //$NON-NLS-1$ MondrianModelExporter exporter = new MondrianModelExporter(lModel, Locale.getDefault().toString()); String mondrianSchema = exporter.createMondrianModelXML(); org.dom4j.Document schemaDoc = DocumentHelper.parseText(mondrianSchema); byte schemaBytes[] = schemaDoc.asXML().getBytes(); if(!publishFile.exists()) { throw new ModelerException("Schema file does not exist"); //$NON-NLS-1$ } OutputStream out = new FileOutputStream(publishFile); out.write(schemaBytes); out.flush(); out.close(); int result = publish(repositoryPath, publishFile, jndiName, modelName, false); if( showFeedback ) { showFeedback( result ); } } /** * Sets the current BI server connection * @param biServerConnection */ public void setBiServerConnection(BiServerConnection biServerConnection) { this.biServerConnection = biServerConnection; } /** * Sets the metadata model * @param model */ public void setModel( ModelerWorkspace model) { this.model = model; } public int getServerConnectionStatus() { return serviceClientStatus; } public BiPlatformRepositoryClientNavigationService getNavigationService() { if(navigationService == null){ BiPlatformRepositoryClient client = new BiPlatformRepositoryClient(); client.setServerUri( biServerConnection.getUrl() ); client.setUserId(biServerConnection.getUserId()); client.setPassword( biServerConnection.getPassword() ); try { client.connect(); } catch (ServiceException e) { e.printStackTrace(); return null; } navigationService = client.getNavigationService(); } return navigationService; } }