answer
stringlengths
17
10.2M
package net.sf.jaer.graphics; import java.awt.Font; import java.awt.geom.Rectangle2D; import java.nio.ByteOrder; import java.nio.FloatBuffer; import net.sf.jaer.chip.*; import net.sf.jaer.eventprocessing.*; import com.sun.opengl.util.*; import com.sun.opengl.util.j2d.TextRenderer; import java.awt.BasicStroke; import java.awt.BufferCapabilities; import java.awt.Canvas; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import java.nio.ByteBuffer; import java.util.*; import java.util.logging.Logger; import java.util.prefs.Preferences; import javax.media.opengl.*; import javax.media.opengl.glu.GLU; import javax.media.opengl.glu.GLUquadric; import javax.swing.*; /** * Superclass for classes that paint rendered AE data to graphics devices. *<p> * This is Canvas (AWT component) for rendering retina events. * Note this is a heavyweight componnent and doesn't understand Swing layering. Thus care must be *taken to ensure Swing components show over it. This component also * uses a page-flipping BufferStrategy to eliminate tearing by flipping pages on *monitor refresh. * <p> * The graphics context is obtained here in the component and its * origin is the UL corner of the component when using Java2D rendering, or LL corner * if using OpenGL rendering. The context is translated *to center the rendering in the Canvas. * This canvas can either use Java2D or OpenGL to render, and it can either actively or passively render. *<p> *If 3-d event rendering is enabled, the raw events are painted out in space-time, with time axis defined by duration from first to last event *in the packet. *<p> *If 3-d histogramming is enabled, then the image frame from the ChipRenderer is rendered as a 3-d surface that the user can rotate as desired. * * @author tobi */ public class ChipCanvas implements GLEventListener, Observer { protected Preferences prefs = Preferences.userNodeForPackage(ChipCanvas.class); /** Default scaling from chip pixel to screen pixels */ protected static final float SCALE_DEFAULT = 4f; protected AEViewer aeViewer; protected float anglex = prefs.getFloat("ChipCanvas.anglex", 5); protected float angley = prefs.getFloat("ChipCanvas.angley", 10); private Chip2D chip; protected final int colorScale = 255; protected GLCanvas drawable; /** fr is the rendered event data that we draw. X is the first dimenion, Y is the second dimension, RGB 3 vector is the last dimension */ protected float[][][] fr; // this is legacy data that we render here to the screen protected RenderingFrame frameData; // this is new form of pixel data to render protected GLU glu; // instance this if we need glu calls on context protected GLUT glut = null; protected Logger log = Logger.getLogger("Graphics"); protected boolean openGLEnabled = prefs.getBoolean("ChipCanvas.openGLEnabled", false); private float origin3dx = prefs.getInt("ChipCanvas.origin3dx", 0); private float origin3dy = prefs.getInt("ChipCanvas.origin3dy", 0); protected int pheight = prefs.getInt("ChipCanvas.pheight", 512); protected int[] pixels; /** defines the minimum canvas size in pixels; used when chip size has not been set to non zero value */ public static final int MIN_DIMENSION = 70; /** width and height of pixel array in canvas in screen pixels. these are different than the actual canvas size */ protected int pwidth = prefs.getInt("ChipCanvas.pwidth", 512); // the number of screen pixels for one retina pixel protected float j2dScale = prefs.getFloat("ChipCanvas.j2dScale", 3f); protected static final Color selectedPixelColor = Color.blue; protected GLUquadric selectedQuad; public BufferStrategy strategy; /** the translation of the actual chip drawing area in the canvas, in screen pixels */ protected int xt, yt; private ChipCanvas.Zoom zoom = new Zoom(); protected boolean zoomMode = false; // true while user is dragging zoom box // reused imageOpenGL for OpenGL image grab private BufferedImage imageOpenGL; // reused by canvas to hold bytes of image when writing java Image ByteBuffer byteBuffer = null; // boolean to flag that present opengl display call should write imageOpenGL volatile boolean grabNextImageEnabled = false; /** border around drawn pixel array in screen pixels */ private int borderSpacePixels = 20; /** border in screen pixels when in 3d space-time rendering mode */ protected final int BORDER3D = 70; /** Insets of the drawn chip canvas in the window */ protected Insets insets = new Insets(borderSpacePixels, borderSpacePixels, borderSpacePixels, borderSpacePixels); private boolean fillsHorizontally = false, fillsVertically = false; // filled in in the reshape method to show how chip fills drawable space private double ZCLIP = 1; private TextRenderer renderer=null; /** Creates a new instance of ChipCanvas */ public ChipCanvas(Chip2D chip) { this.chip = chip; try{ glut=new GLUT(); }catch(NoClassDefFoundError err){ log.warning("Could not construct GLUT object as the OpenGL utilities helper. There is some problem with your JOGL libraries." + "It could be that you are trying to run a 64-bit JVM under linux. Try using a 32-bit Java Virtual Machine (JVM) instead, because" + "the jAER JOGL native libraries are built for 32-bit JVMs."); throw err; } // design capabilities of opengl canvas GLCapabilities caps = new GLCapabilities(); caps.setDoubleBuffered(true); caps.setHardwareAccelerated(true); caps.setAlphaBits(8); caps.setRedBits(8); caps.setGreenBits(8); caps.setBlueBits(8); glu = new GLU(); // make the canvas try { drawable = new GLCanvas(caps); } catch (UnsatisfiedLinkError e) { e.printStackTrace(); System.err.println("java.libary.path=" + System.getProperty("java.library.path")); System.err.println("user.dir=" + System.getProperty("user.dir")); System.exit(1); } drawable.setLocale(Locale.US); // to avoid problems with other language support in JOGL // will always getString invalid operation here // checkGLError(drawable.getGL(),glu,"before add event listener"); // add us as listeners for the canvas. then when the display wants to redraw display() will be called. or we can call drawable.display(); drawable.addGLEventListener(this); // same here, canvas not yet valid // checkGLError(drawable.getGL(),glu,"after add event listener"); // Dimension ss=Toolkit.getDefaultToolkit().getScreenSize(); j2dScale = prefs.getFloat(scalePrefsKey(), 4); // if j2dScale comes from prefs, then j2dScale gets smaller and smaller with each window that is opened setScale(getScale()); drawable.setSize(200, 200); // set a size explicitly here initComponents(); chip.addObserver(this); // if this canvas was constructed from a chip, then fill the display methods from that chip's ChipCanvas, if it exists and has them if (displayMethods.isEmpty() && chip.getCanvas() != null && chip.getCanvas().getDisplayMethod() != null) { displayMethods.add(chip.getCanvas().getDisplayMethod()); } } /** call this method so that next open gl rendering by display(GLAutoDrawable) writes imageOpenGL */ public void grabNextImage() { grabNextImageEnabled = true; } // here are methods for toggling display method and building menu for AEViewer private JMenu displayMethodMenu = new JMenu("Display method"); private ButtonGroup menuButtonGroup = new ButtonGroup(); public JMenu getDisplayMethodMenu() { return displayMethodMenu; } /** the list of display methods for this canvas*/ private ArrayList<DisplayMethod> displayMethods = new ArrayList<DisplayMethod>(); /** adds a display method to this canvas @param m the method */ public void addDisplayMethod(DisplayMethod m) { if (getDisplayMethods().contains(m)) { return; } getDisplayMethods().add(m); displayMethodMenu.getPopupMenu().setLightWeightPopupEnabled(false); // canvas is heavyweight so we need this to make menu popup show JRadioButtonMenuItem mi = new JRadioButtonMenuItem(m.getDescription()); m.setMenuItem(mi); mi.setActionCommand(m.getDescription()); mi.putClientProperty("displayMethod", m); // add display method as client property mi.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { DisplayMethod m = (DisplayMethod) (((JComponent) e.getSource()).getClientProperty("displayMethod")); if (chip != null) { chip.setPreferredDisplayMethod(m.getClass()); // only set preference on user selection via GUI } setDisplayMethod(m); } }); displayMethodMenu.add(mi); menuButtonGroup.add(mi); // if there is no default method yet, set one to be sure that a method is set, to avoid null pointer exceptions if (displayMethod == null) { setDisplayMethod(m); } } /** Removes a DisplayMethod for this ChipCanvas * * @param m the method. If null or not in list, warning is logged. */ public void removeDisplayMethod(DisplayMethod m) { if (m == null || !getDisplayMethods().contains(m)) { log.warning("Cannot remove DisplayMethod "+m+": no such DisplayMethod " + m + " in the getDisplayMethods() list"); return; } displayMethods.remove(m); displayMethodMenu.remove(m.getMenuItem()); } protected DisplayMethod displayMethod; int currentDisplayMethodIndex = 0; /** returns the current display method @return the current display method */ public DisplayMethod getDisplayMethod() { return displayMethod; } /** cycle to the next display method */ public void cycleDisplayMethod() { if (++currentDisplayMethodIndex >= getDisplayMethods().size()) { currentDisplayMethodIndex = 0; } setDisplayMethod(currentDisplayMethodIndex); } /** sets the display method @param m the method to use */ public void setDisplayMethod(DisplayMethod m) { // System.out.println("set display method="+m); // Thread.currentThread().dumpStack(); this.displayMethod = m; if (m != null) { if (m.getMenuItem() == null) { // TODO comes here when preferred display method is constructed, which is not yet assigned a menu item like the others // which are constructed by default log.info("no menu item for display method " + m + " cannot set it as the selected display method in the menu"); } else { // log.info("setting display method to " + m.getDescription()); m.getMenuItem().setSelected(true); } } repaint(); } /** sets the display method using the menu name @param description the name, fully qualified class name or simple class name; only the last part is used, after the final ".". */ public void setDisplayMethod(String description) { for (DisplayMethod method : getDisplayMethods()) { String s = description; int ind = s.lastIndexOf('.'); s = s.substring(ind + 1); if (method.getDescription().equals(s)) { // log.info("setting display method=" + m); setDisplayMethod(method); return; } } StringBuilder sb = new StringBuilder("couldn't set display method to " + description + ", not in list of methods which are as follows:\n"); for (DisplayMethod method : getDisplayMethods()) { sb.append(method.getDescription() + "\n"); } log.warning(sb.toString()); } /** sets the current display method to a particular item @param index the index of the method in the list of methods */ protected void setDisplayMethod(int index) { setDisplayMethod(getDisplayMethods().get(index)); } /** opengl calls this when it wants to redraw, and we call it when we actively render. * @param drawable the surface from which we can getString the context with getGL @see net.sf.jaer.graphics.DisplayMethod#setupGL which sets up GL context for display methods */ public synchronized void display(GLAutoDrawable drawable) { if (!isOpenGLEnabled()) { paint(null); } else { // if(drawable.getContext().makeCurrent()!=GLContext.CONTEXT_CURRENT){ // log.warning("current drawing context not current, skipping"); // return; GL gl = drawable.getGL(); gl.glMatrixMode(GL.GL_MODELVIEW); gl.glLoadIdentity(); // log.info("display"); checkGLError(gl, glu, "before setting projection"); // gl.glPushMatrix(); // don't push so that mouse selection has correct matrices { if (getZoom().isZoomEnabled()) { getZoom().setProjection(gl); } else { setDefaultProjection(gl, drawable); } checkGLError(gl, glu, "after setting projection, before displayMethod"); DisplayMethod m = getDisplayMethod(); if (m == null) { log.warning("null display method for chip " + getChip()); } else { m.display(drawable); } // checkGLError(gl, glu, "after " + getDisplayMethod() + ".display()"); checkGLError(gl, glu, "after DisplayMethod.display()"); showSpike(gl); annotate(drawable); checkGLError(gl, glu, "after FrameAnnotator (EventFilter) annotations"); } if(getChip() instanceof AEChip && ((AEChip)chip).getFilterChain()!=null && ((AEChip)chip).getFilterChain().getProcessingMode()==FilterChain.ProcessingMode.ACQUISITION){ if ( renderer == null ){ renderer = new TextRenderer(new Font("SansSerif",Font.PLAIN,10),true,true); } renderer.begin3DRendering(); renderer.setColor(0,0,1,0.8f); final String s = "Real-time mode - raw data shown here"; Rectangle2D r = renderer.getBounds(s); renderer.draw3D(s,1f,1f,0f,(float)(chip.getSizeX() / r.getWidth())); renderer.end3DRendering(); } gl.glFlush(); // gl.glPopMatrix(); checkGLError(gl, glu, "after display"); // drawable.swapBuffers(); // don't use, very slow and autoswapbuffers is set // zoom.drawZoomBox(gl); if (grabNextImageEnabled) { grabImage(drawable); grabNextImageEnabled = false; } } } float[] rgbVec = new float[3]; public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) { // log.info("display changed"); // should be empty according to jogl user guide. // System.out.println("displayChanged"); } // TODO javadoc public float getAnglex() { return anglex; } public float getAngley() { return angley; } /** The actual drawing surface is a Canvas and this method returns a reference to it. * * @return the actual drawing Canvas. */ public Canvas getCanvas() { return drawable; } /** Pixel drawing j2dScale. 1 pixel is rendered to getScale screen pixels. * * @return j2dScale in screen pixels/chip pixel. */ public float getScale() { return this.j2dScale; } /** A utility method that returns an AWT Color from float rgb values */ protected final Color getPixelColor(float red, float green, float blue) { int r = (int) (colorScale * red); int g = (int) (colorScale * green); int b = (int) (colorScale * blue); int value = ((r & 0xFF) << 16) | ((g & 0xFF) << 8) | ((b & 0xFF) << 0); return new Color(value); } private boolean mouseWasInsideChipBounds=true; public Point getPixelFromPoint(Point mp) { // this method depends on current GL context being the one that is used for rendering. // the display method should not push/pop the matrix stacks!! if (mp == null) { // log.warning("null Point (outside entire canvas?), returning center pixel"); return new Point(chip.getSizeX() / 2, chip.getSizeY() / 2); } try { int ret = drawable.getContext().makeCurrent(); if (ret != GLContext.CONTEXT_CURRENT) { throw new GLException("couldn't make context current"); } } catch (GLException e) { log.warning("couldn't make GL context current, mouse position meaningless: " + e.toString()); } int viewport[] = new int[4]; double mvmatrix[] = new double[16]; double projmatrix[] = new double[16]; int realy = 0;// GL y coord pos double wcoord[] = new double[4];// wx, wy, wz;// returned xyz coords //set up a floatbuffer to getString the depth buffer value of the mouse position FloatBuffer fb = ByteBuffer.allocateDirect(4).order(ByteOrder.nativeOrder()).asFloatBuffer(); GL gl = drawable.getContext().getGL(); gl.glGetIntegerv(GL.GL_VIEWPORT, viewport, 0); gl.glGetDoublev(GL.GL_MODELVIEW_MATRIX, mvmatrix, 0); gl.glGetDoublev(GL.GL_PROJECTION_MATRIX, projmatrix, 0); /* note viewport[3] is height of window in pixels */ realy = viewport[3] - (int) mp.getY() - 1; //Get the depth buffer value at the mouse position. have to do height-mouseY, as GL puts 0,0 in the bottom left, not top left. gl.glReadPixels(mp.x, realy, 1, 1, GL.GL_DEPTH_COMPONENT, GL.GL_FLOAT, fb); float z = 0; //fb.getString(0); glu.gluUnProject((double) mp.getX(), (double) realy, z, mvmatrix, 0, projmatrix, 0, viewport, 0, wcoord, 0); Point p = new Point(); p.x = (int) Math.round(wcoord[0]); p.y = (int) Math.round(wcoord[1]); if(p.x<0 || p.x>chip.getSizeX()-1 || p.y<0|p.y>chip.getSizeY()-1) mouseWasInsideChipBounds=false; else mouseWasInsideChipBounds=true; clipPoint(p); // log.info("Mouse xyz=" + mp.getX() + "," + realy + "," + z + " Pixel x,y=" + p.x + "," + p.y); return p; } /** Finds the current AEChip pixel mouse position, or center of array if not inside. * * @return the AEChip pixel, clipped to the bounds of the AEChip */ public Point getMousePixel() { Point mp = getCanvas().getMousePosition(); return getPixelFromPoint(mp); } /** Returns state of mouse from last call to getPixelFromPoint; true if mouse inside bounds of chip drawing area. * * @return true if was inside, false otherwise. */ public boolean wasMousePixelInsideChipBounds (){ return mouseWasInsideChipBounds; } /** Takes a MouseEvent and returns the AEChip pixel. * @return pixel x,y location (integer point) from MouseEvent. Accounts for scaling and borders of chip display area */ public Point getPixelFromMouseEvent(MouseEvent evt) { Point mp = evt.getPoint(); return getPixelFromPoint(mp); } protected final int getPixelRGB(float red, float green, float blue) { int r = (int) (colorScale * red); int g = (int) (colorScale * green); int b = (int) (colorScale * blue); int value = ((r & 0xFF) << 16) | ((g & 0xFF) << 8) | ((b & 0xFF) << 0); return value; } public void init(GLAutoDrawable drawable) { // drawable.setGL(new DebugGL(drawable.getGL())); drawable.setAutoSwapBufferMode(true); GL gl = drawable.getGL(); log.info( "OpenGL implementation is: " + gl.getClass().getName() + "\nGL_VENDOR: " + gl.glGetString(GL.GL_VENDOR) + "\nGL_RENDERER: " + gl.glGetString(GL.GL_RENDERER) + "\nGL_VERSION: " + gl.glGetString(GL.GL_VERSION) // + "\nGL_EXTENSIONS: " + gl.glGetString(GL.GL_EXTENSIONS) ); float glVersion = Float.parseFloat(gl.glGetString(GL.GL_VERSION).substring(0, 3)); if (glVersion < 1.3f) { log.warning("\n\n*******************\nOpenGL version " + glVersion + " < 1.3, some features may not work and program may crash\nTry switching from 16 to 32 bit color if you have decent graphics card\n\n"); } // System.out.println("GLU_EXTENSIONS: "+glu.gluGetString(GLU.GLU_EXTENSIONS)); gl.setSwapInterval(1); gl.glShadeModel(GL.GL_FLAT); gl.glClearColor(0, 0, 0, 0f); gl.glClear(GL.GL_COLOR_BUFFER_BIT); gl.glLoadIdentity(); gl.glRasterPos3f(0, 0, 0); gl.glColor3f(1, 1, 1); glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, "Initialized display"); checkGLError(gl, glu, "after init"); } protected void initComponents() { unzoom(); if (getRenderer() != null) { drawable.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent evt) { Point p = getPixelFromMouseEvent(evt); // if (!isZoomMode()) { // System.out.println("evt="+evt); if (evt.getButton() == 1) { getRenderer().setXsel((short) -1); getRenderer().setYsel((short) -1); // System.out.println("cleared pixel selection"); } else if (evt.getButton() == 3) { // we want mouse click location in chip pixel location // don't forget that there is a borderSpacePixels on the orthographic viewport projection // this border means that the pixels are actually drawn on the screen in a viewport that has a borderSpacePixels sized edge on all sides // for simplicity because i can't figure this out, i have set the borderSpacePixels to zero // log.info(" width=" + drawable.getWidth() + " height=" + drawable.getHeight() + " mouseX=" + evt.getX() + " mouseY=" + evt.getY() + " xt=" + xt + " yt=" + yt); // renderer.setXsel((short)((0+((evt.x-xt-borderSpacePixels)/j2dScale)))); // renderer.setYsel((short)(0+((getPheight()-evt.y+yt-borderSpacePixels)/j2dScale))); getRenderer().setXsel((short) p.x); getRenderer().setYsel((short) p.y); log.info("Selected pixel x,y=" + getRenderer().getXsel() + "," + getRenderer().getYsel()); } // } else if (isZoomMode()) { // zoom startZoom // zoom.startZoom(p); } public void mouseReleased(MouseEvent e) { if (is3DEnabled()) { log.info("3d rotation: angley=" + angley + " anglex=" + anglex + " 3d origin: x=" + getOrigin3dx() + " y=" + getOrigin3dy()); } //else // if (isZoomMode()) { // Point p = getPixelFromMouseEvent(e); // zoom.endZoom(p); //// zoom.endX=p.x; //// zoom.endY=p.y; //// setZoomMode(false); } }); } // renderer!=null drawable.addMouseMotionListener(new MouseMotionListener() { public void mouseDragged(MouseEvent e) { int x = e.getX(); int y = e.getY(); int but1mask = InputEvent.BUTTON1_DOWN_MASK, but3mask = InputEvent.BUTTON3_DOWN_MASK; if ((e.getModifiersEx() & but1mask) == but1mask) { if (is3DEnabled()) { final float maxAngle = 180f; setAngley(maxAngle * (x - drawable.getWidth() / 2) / (float) drawable.getWidth()); setAnglex(maxAngle * (y - drawable.getHeight() / 2) / (float) drawable.getHeight()); } else if (isZoomMode()) { // System.out.print("z"); } } else if ((e.getModifiersEx() & but3mask) == but3mask) { if (is3DEnabled()) { // mouse position x,y is in pixel coordinates in window canvas, but later on, the events will be drawn in // chip coordinates (transformation applied). therefore here we set origin in pixel coordinates based on mouse // position in window. set3dOrigin(Math.round(getChip().getMaxSize() * ((float) x - drawable.getWidth() / 2) / drawable.getWidth()), Math.round(getChip().getMaxSize() * (drawable.getHeight() / 2 - (float) y) / drawable.getHeight())); } } repaint(100); // log.info("repaint called for"); } public void mouseMoved(MouseEvent e) { } }); } public boolean is3DEnabled() { return displayMethod instanceof DisplayMethod3D; } public boolean isOpenGLEnabled() { return openGLEnabled; } public boolean isZoomMode() { return zoomMode; } /** use to paint with Java2D using BufferStrategy */ protected void paint() { paint(null); } public synchronized void paint(Graphics g) { // log.info("paint with graphics="+g); Graphics2D g2 = null; if (strategy == null) { try { drawable.createBufferStrategy(2); strategy = drawable.getBufferStrategy(); BufferCapabilities cap = strategy.getCapabilities(); // ImageCapabilities imCapFront = cap.getFrontBufferCapabilities(); // ImageCapabilities imCapBack = cap.getBackBufferCapabilities(); boolean isPageFlip = cap.isPageFlipping(); boolean isMultiBufferAvailable = cap.isMultiBufferAvailable(); log.info("isPageFlipping=" + isPageFlip + " isMultiBufferAvailable=" + isMultiBufferAvailable); } catch (Exception e) { log.warning("couldn't create BufferStrategy yet: " + e.getMessage()); } } if (g == null) { if (strategy == null) { return; } g2 = (Graphics2D) strategy.getDrawGraphics(); } else { g2 = (Graphics2D) g; } try { g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED); g2.setColor(Color.black); g2.fill(drawable.getBounds()); // translate to center view; depends on how chip fills display if (isFillsHorizontally()) { // translate vertically downwards by (height-sizeY*j2dScale)/2 g2.translate(0, (getCanvas().getHeight() - j2dScale * chip.getSizeY()) / 2); } else { // fills canvas vertically, translate right by (width-sizeX*j2dScale)/2 g2.translate((getCanvas().getWidth() - j2dScale * chip.getSizeX()) / 2, 0); } g2.scale(j2dScale, j2dScale);// AffineTransform.getScaleInstance(j2dScale,j2dScale)); g2.setFont(g2.getFont().deriveFont(8f)); // g2.translate(.5,-.5); // g2.transform(new AffineTransform(1,0,0,-1,0,0)); // flip y float gray = (float) getRenderer().getGrayValue(); g2.setColor(new Color(gray, gray, gray)); g2.fill(new Rectangle(0, 0, chip.getSizeX(), chip.getSizeY())); int sizex = chip.getSizeX(), sizey = chip.getSizeY(); float[] fr = getRenderer().getPixmapArray(); if (fr == null) { return; } int ind = 0; for (int y = 0; y < sizey; y++) { for (int x = 0; x < sizex; x++) { if (fr[ind] != gray || fr[ind + 1] != gray || fr[ind + 2] != gray) { g2.setColor(getPixelColor(fr[ind], fr[ind + 1], fr[ind + 2])); g2.fillRect(x, sizey - y - 1, 1, 1); } ind += 3; } } int xsel = getRenderer().getXsel(), ysel = getRenderer().getYsel(); if (xsel != -1 && ysel != -1) { g2.setColor(selectedPixelColor); // g2.fillRect(j2dScale*renderer.xsel,pheight-j2dScale*(renderer.ysel+1),j2dScale, j2dScale); int radius = 1 + getRenderer().getSelectedPixelEventCount(); g2.setStroke(new BasicStroke(.2f / getScale())); int xs = xsel - radius, ys = sizey - (ysel + radius); g2.drawOval(xs, ys, 2 * radius, 2 * radius); g2.drawString(xsel + "," + ysel, xsel, sizey - ysel); } // call all the annotators that have registered themselves. these are java2d annotators // annotate(g2); strategy.show(); } catch (Exception e) { log.warning("ChipCanvas.display(): Graphics context error " + e); e.printStackTrace(); } } /** Used for active rendering. * You call this when you want to actively render the frame. * Internally, this calls the display() method of the drawable, which by callback to display(GLAutoDrawable). * If openGL is disabled, then it calls paint() directly. */ public void paintFrame (){ if ( isOpenGLEnabled() ){ try{ drawable.display(); // we call the drawable's display method that ends up calling us back via our local display(GLAutoDrawable)!! very important to getString this right } catch ( GLException e ){ if ( !( e.getCause() instanceof InterruptedException ) ){ log.warning(e.toString()); } } } else{ paint(); } } public void removeGLEventListener(GLEventListener listener) { } /** calls repaint on the drawable */ public synchronized void repaint() { drawable.repaint(); } /** calls repaint on the drawable */ public synchronized void repaint(long tm) { drawable.repaint(tm); } /** Called on reshape of canvas. Determines which way the chip fits into the display area optimally and calls * for a new orthographic projection to achieve this filling. Finally sets the viewport to the entire drawable area. */ public synchronized void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { GL gl = drawable.getGL(); gl.glLoadIdentity(); final int chipSizeX = chip.getSizeX(); final int chipSizeY = chip.getSizeY(); float newscale; final float border = 0; // getBorderSpacePixels()*(float)height/width; if (chipSizeY > chipSizeX) { // chip is tall and skinny, so set j2dScale by frame height/chip height newscale = (float) (height - border) / chipSizeY; fillsVertically = true; fillsHorizontally = false; if (newscale * chipSizeX > width) { // unless it runs into left/right, then set to fill width newscale = (float) (width - border) / chipSizeX; fillsHorizontally = true; fillsVertically = false; } } else { // chip is square or squat, so set j2dScale by frame width / chip width newscale = (float) (width - border) / chipSizeX; fillsHorizontally = true; fillsVertically = false; if (newscale * chipSizeY > height) {// unless it runs into top/bottom, then set to fill height newscale = (float) (height - border) / chipSizeY; fillsVertically = true; fillsHorizontally = false; } } setScale(newscale); // TODO j2dScale meaningless now for opengl but not for java2d rendering setDefaultProjection(gl, drawable); // this sets orthographic projection so that chip pixels are scaled to the drawable area gl.glViewport(0, 0, width, height); repaint(); } protected String scalePrefsKey() { if (chip == null) { return "ChipCanvas.j2dScale"; } else { return "ChipCanvas.j2dScale" + chip.getClass().getSimpleName(); } } protected void set3dOrigin(int x, int y) { setOrigin3dy(y); setOrigin3dx(x); prefs.putInt("ChipCanvas.origin3dx", x); prefs.putInt("ChipCanvas.origin3dy", y); } public void setAnglex(float anglex) { this.anglex = anglex; prefs.putFloat("ChipCanvas.anglex", anglex); } public void setAngley(float angley) { this.angley = angley; prefs.putFloat("ChipCanvas.angley", angley); } public void setOpenGLEnabled(boolean openGLEnabled) { this.openGLEnabled = openGLEnabled; prefs.putBoolean("ChipCanvas.openGLEnabled", openGLEnabled); } /** Orthographic projection clipping area. */ private class ClipArea { float left = 0, right = 0, bottom = 0, top = 0; ClipArea(float l, float r, float b, float t) { left = l; right = r; bottom = b; top = t; } } /** The actual clipping box bounds for the default orthographic projection. */ private ClipArea clipArea = new ClipArea(0, 0, 0, 0); /** Border around chip in clipping area. */ private class Borders { float leftRight = 0, bottomTop = 0; }; /** The actual borders in model space around the chip area. */ private Borders borders = new Borders(); /** Sets the projection matrix so that we getString an orthographic projection that is the size of the canvas with z volume -ZCLIP to ZCLIP padded with extra space around the sides. @param g the GL context @param d the GLAutoDrawable canvas */ protected void setDefaultProjection(GL g, GLAutoDrawable d) { /* void glOrtho(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble near, GLdouble far) */ final int w = drawable.getWidth(), h = drawable.getHeight(); // w,h of screen final int sx = chip.getSizeX(), sy = chip.getSizeY(); // chip size final float border = getBorderSpacePixels(); // desired smallest border in screen pixels float glScale; checkGLError(g, glu, "before setDefaultProjection"); g.glMatrixMode(GL.GL_PROJECTION); g.glLoadIdentity(); // very important to load identity matrix here so this works after first resize!!! // now we set the clipping volume so that the volume is clipped according to whether the window is tall (ar>1) or wide (ar<1). if (isFillsHorizontally()) { //tall glScale = (float) (w - 2 * border) / sx; // chip pix to screen pix scaling in horizontal&vert direction float b = border / glScale; // l,r border in model coordinates if (b <= 0) { b = 1; } float bb = (h / glScale - sy) / 2; // leftover y in model coordinates that makes up vertical border if (bb <= 0) { bb = 1; } clipArea.left = -b; clipArea.right = sx + b; clipArea.bottom = -bb; clipArea.top = sy + bb; borders.leftRight = b; borders.bottomTop = bb; g.glOrtho(-b, sx + b, -bb, (sy + bb), ZCLIP, -ZCLIP); // clip area has same ar as screen! } else { glScale = (float) (h - 2 * border) / sy; float b = border / glScale; if (b <= .5f) { b = 1; } float bb = (w / glScale - sx) / 2; // leftover y in model coordinates that makes up vertical border if (bb <= 0) { bb = 1; } clipArea.left = -bb; clipArea.right = sx + bb; clipArea.bottom = -b; clipArea.top = sy + b; borders.leftRight = bb; borders.bottomTop = b; g.glOrtho(-bb, (sx + bb), -b, sy + b, ZCLIP, -ZCLIP); } g.glMatrixMode(GL.GL_MODELVIEW); } /** This method sets the pixel drawing j2dScale so that * e.g. s=2 means a chip pixel occupies 2 screen pixels. * Only used for java2d rendering now. * @param s size of chip pixel in screen pixels. */ public void setScale(float s) { prefs.putFloat(scalePrefsKey(), (float) Math.round(s)); // if we don't round, window gets smaller each time we open a new one... this.j2dScale = s; } /** Shows selected pixel spike count by drawn circle */ protected void showSpike(GL gl) { // show selected pixel that user can hear if (getRenderer() != null && getRenderer().getXsel() != -1 && getRenderer().getYsel() != -1) { showSpike(gl, getRenderer().getXsel(), getRenderer().getYsel(), getRenderer().getSelectedPixelEventCount()); } } /** draws a circle at pixel x,y of size+.5 radius. size is used to indicate number of spikes in this 'frame' */ protected void showSpike(GL gl, int x, int y, int size) { // circle gl.glPushMatrix(); gl.glColor4f(0, 0, 1f, 0f); if (size > chip.getMinSize() / 3) { size = chip.getMinSize() / 3; } gl.glTranslatef(x, y, -1); selectedQuad = glu.gluNewQuadric(); glu.gluQuadricDrawStyle(selectedQuad, GLU.GLU_FILL); glu.gluDisk(selectedQuad, size, size + 1, 16, 1); glu.gluDeleteQuadric(selectedQuad); gl.glPopMatrix(); int font = GLUT.BITMAP_HELVETICA_18; gl.glPushMatrix(); final int FS = 1; // distance in pixels of text from selected pixel gl.glRasterPos3f(x + FS, y + FS, 0); glut.glutBitmapString(font, x + "," + y); gl.glPopMatrix(); checkGLError(gl, glu, "showSpike"); } public void zoomIn() { getZoom().zoomin(); } public void zoomOut() { getZoom().zoomout(); } public void unzoom() { getZoom().unzoom(); } public void update(Observable o, Object arg) { // if observable is a chip object and arg is a string size property then set a new j2dScale if (o == chip && arg instanceof String) { if (arg.equals(Chip2D.EVENT_SIZEX) || arg.equals(Chip2D.EVENT_SIZEY)) { setScale(prefs.getFloat(scalePrefsKey(), SCALE_DEFAULT)); ZCLIP = chip.getMaxSize(); unzoom(); } } if (o instanceof Chip2D) { Chip2D c = (Chip2D) o; setRenderer(c.getRenderer()); } } public Chip2DRenderer getRenderer() { return chip.getRenderer(); } public void setRenderer(Chip2DRenderer renderer) { chip.setRenderer(renderer); } public ArrayList<DisplayMethod> getDisplayMethods() { return displayMethods; } public void setDisplayMethods(ArrayList<DisplayMethod> displayMethods) { this.displayMethods = displayMethods; } /** Returns minimum space around pixel array in screen pixels * * @return screen pixel size border */ public int getBorderSpacePixels() { if (!is3DEnabled()) { return borderSpacePixels; } else { return BORDER3D; } } /** Sets the border around the drawn pixel canvas. * * @param borderSpacePixels in screen pixels. */ public void setBorderSpacePixels(int borderSpacePixels) { this.borderSpacePixels = borderSpacePixels; insets.bottom = borderSpacePixels; insets.top = borderSpacePixels; insets.left = borderSpacePixels; insets.right = borderSpacePixels; } /** Clips a Point to within the chip size. The point is modified to fit within the size of the Chip2D. * * @param p a Point */ void clipPoint(Point p) { if (p.x < 0) { p.x = 0; } else if (p.x > getChip().getSizeX() - 1) { p.x = getChip().getSizeX() - 1; } if (p.y < 0) { p.y = 0; } else if (p.y > getChip().getSizeY() - 1) { p.y = getChip().getSizeY() - 1; } } void zoomCenter() { getZoom().zoomcenter(); } public ChipCanvas.Zoom getZoom() { return zoom; } public void setZoom(ChipCanvas.Zoom zoom) { this.zoom = zoom; } /** Chip fills drawable horizontally. * @return the fillsHorizontally */ public boolean isFillsHorizontally() { return fillsHorizontally; } /** Chip fills drawable vertically. * @return the fillsVertically */ public boolean isFillsVertically() { return fillsVertically; } /** Encapsulates zooming the view */ public class Zoom { final float zoomStepRatio = 1.3f; private Point startPoint = new Point(); private Point endPoint = new Point(); private Point centerPoint = new Point(); float zoomFactor = 1; private boolean zoomEnabled = false; Point tmpPoint = new Point(); double projectionLeft, projectionRight, projectionBottom, projectionTop; // projection rect points, computed on zoom private void setProjection(GL gl) { float glScale; // define a new projection matrix so that the clipping volume is centered on the centerPoint // and the size of the rectangle zooms up by a factor of zoomFactor on the original j2dScale gl.glMatrixMode(GL.GL_PROJECTION); gl.glLoadIdentity(); final int w = drawable.getWidth(), h = drawable.getHeight(); // w,h of screen final int sx = chip.getSizeX(), sy = chip.getSizeY(); // chip size if (isFillsHorizontally()) { //tall glScale = (float) (w * zoomFactor) / sx; // chip pix to screen pix scaling in horizontal&vert direction final float wx2 = sx / zoomFactor / 2; clipArea.left = centerPoint.x - wx2; clipArea.right = centerPoint.x + wx2; final float wy2 = wx2 * h / w; clipArea.bottom = centerPoint.y - wy2; clipArea.top = centerPoint.y + wy2; borders.leftRight = 0; borders.bottomTop = 0; gl.glOrtho(clipArea.left, clipArea.right, clipArea.bottom, clipArea.top, ZCLIP, -ZCLIP); // clip area has same ar as screen! } else { glScale = (float) (h * zoomFactor) / sy; // chip pix to screen pix scaling in horizontal&vert direction final float wy2 = sy / zoomFactor / 2; clipArea.bottom = centerPoint.y - wy2; clipArea.top = centerPoint.y + wy2; final float wx2 = wy2 * w / h; clipArea.left = centerPoint.x - wx2; clipArea.right = centerPoint.x + wx2; borders.leftRight = 0; borders.bottomTop = 0; gl.glOrtho(clipArea.left, clipArea.right, clipArea.bottom, clipArea.top, ZCLIP, -ZCLIP); // clip area has same ar as screen! } } public Point getStartPoint() { return startPoint; } public void setStartPoint(Point startPoint) { this.startPoint = startPoint; } public Point getEndPoint() { return endPoint; } public void setEndPoint(Point endPoint) { this.endPoint = endPoint; } private void unzoom() { setZoomEnabled(false); zoomFactor = 1; getZoom().setStartPoint(new Point(0, 0)); getZoom().setEndPoint(new Point(getChip().getSizeX(), getChip().getSizeY())); if (!System.getProperty("os.name").contains("Mac")) {//crashes on mac os x 10.5 GL g = drawable.getGL(); g.glMatrixMode(GL.GL_PROJECTION); g.glLoadIdentity(); // very important to load identity matrix here so this works after first resize!!! g.glOrtho(-getBorderSpacePixels(), drawable.getWidth() + getBorderSpacePixels(), -getBorderSpacePixels(), drawable.getHeight() + getBorderSpacePixels(), ZCLIP, -ZCLIP); g.glMatrixMode(GL.GL_MODELVIEW); } } private void zoomcenter() { centerPoint = getMousePixel(); setZoomEnabled(true); } private void zoomin() { if (!isOpenGLEnabled()) { JOptionPane.showMessageDialog(getCanvas(), "<html>You are using Java2D rendering.<br>To enabling zooming, enable OpenGL graphics (View/Graphics options)", "Can't zoom", JOptionPane.INFORMATION_MESSAGE); return; } centerPoint = getMousePixel(); zoomFactor *= zoomStepRatio; setZoomEnabled(true); } private void zoomout() { centerPoint = getMousePixel(); zoomFactor /= zoomStepRatio; setZoomEnabled(true); } public boolean isZoomEnabled() { return zoomEnabled; } public void setZoomEnabled(boolean zoomEnabled) { this.zoomEnabled = zoomEnabled; } } public void addGLEventListener(GLEventListener listener) { // System.out.println("addGLEventListener("+listener+")"); } /** Draws the annotations for a filter including the annotations for enclosed filters @param f the filter to annotate @param a the corresponding annotator (usually the same filter) @param drawable the drawing context */ private void drawAnnotationsIncludingEnclosed(EventFilter f, FrameAnnotater a, GLAutoDrawable drawable) { try{ a.annotate(drawable); }catch(RuntimeException e){ log.warning("caught "+e+" when annotating with "+a); } if (f.getEnclosedFilter() != null && f.getEnclosedFilter() instanceof FrameAnnotater) { EventFilter f2 = f.getEnclosedFilter(); FrameAnnotater a2 = (FrameAnnotater) f2; if (a2.isAnnotationEnabled()) { drawAnnotationsIncludingEnclosed(f2, (FrameAnnotater) f2, drawable); } } if (f.getEnclosedFilterChain() != null) { for (EventFilter f2 : f.getEnclosedFilterChain()) { if (f2 != null && f2 instanceof FrameAnnotater) { FrameAnnotater a2 = (FrameAnnotater) f2; if (a2.isAnnotationEnabled()) { drawAnnotationsIncludingEnclosed(f2, a2, drawable); } } } } } /**First, calls annotate(GLAutoDrawable) for all FrameAnnotators that have been added explicitly to the current DisplayMethod. * Then it calls annotate on all FilterChain filters with that implement FrameAnnotator and that are enabled for the Chip2D. * @param drawable the context */ protected void annotate(GLAutoDrawable drawable) { if (getDisplayMethod() == null) { return; } if (getDisplayMethod().getAnnotators() == null) { return; } for (FrameAnnotater a : getDisplayMethod().getAnnotators()) { a.annotate(drawable); } if (chip instanceof AEChip) { FilterChain chain = ((AEChip) chip).getFilterChain(); if (chain != null) { for (EventFilter f : chain) { if (!f.isAnnotationEnabled()) { continue; } FrameAnnotater a = (FrameAnnotater) f; drawAnnotationsIncludingEnclosed(f, a, drawable); } } } } // /** Iterates through the FilterChain associated with the AEChip to call all the enabled filter annotations // @param g2 the graphics context passed to the EventFilter annotators // */ // protected void annotate(Graphics2D g2) { // FilterChain fc = null; // if (chip instanceof AEChip) { // fc = ((AEChip) chip).getFilterChain(); // if (fc != null) { // for (EventFilter f : fc) { // if (f instanceof FrameAnnotater && f.isAnnotationEnabled()) { // FrameAnnotater fa = (FrameAnnotater) f; // fa.annotate(g2); //// if (annotators == null)return; //// // System.out.println("ChipCanvas annotating graphics"); //// for(FrameAnnotater a : annotators){ //// a.annotate(g2); /** Utility method to check for GL errors. Prints stacked up errors up to a limit. @param g the GL context @param glu the GLU used to obtain the error strings @param msg an error message to log to e.g., show the context */ public void checkGLError(GL g, GLU glu, String msg) { int error = g.glGetError(); int nerrors = 3; while (error != GL.GL_NO_ERROR && nerrors StackTraceElement[] trace = Thread.currentThread().getStackTrace(); if (trace.length > 1) { String className = trace[2].getClassName(); String methodName = trace[2].getMethodName(); int lineNumber = trace[2].getLineNumber(); log.warning("GL error number " + error + " " + glu.gluErrorString(error) + " : " + msg + " at " + className + "." + methodName + " (line " + lineNumber + ")"); } else { log.warning("GL error number " + error + " " + glu.gluErrorString(error) + " : " + msg); } // Thread.dumpStack(); error = g.glGetError(); } } public float getOrigin3dx() { return origin3dx; } public void setOrigin3dx(float origin3dx) { this.origin3dx = origin3dx; } public float getOrigin3dy() { return origin3dy; } public void setOrigin3dy(float origin3dy) { this.origin3dy = origin3dy; } /* * Copy the frame buffer into the BufferedImage. The data needs to * be flipped top to bottom because the origin is the lower left in * OpenGL, but is the upper right in Java's BufferedImage format. This method should be called inside the rendering display method. @param d the drawable we are drawing in. */ void grabImage(GLAutoDrawable d) { GL gl = d.getGL(); int width = d.getWidth(); int height = d.getHeight(); // Allocate a buffer for the pixels ByteBuffer rgbData = BufferUtil.newByteBuffer(width * height * 3); // Set up the OpenGL state. gl.glReadBuffer(GL.GL_FRONT); gl.glPixelStorei(GL.GL_PACK_ALIGNMENT, 1); // Read the pixels into the ByteBuffer gl.glReadPixels(0, 0, width, height, GL.GL_RGB, GL.GL_UNSIGNED_BYTE, rgbData); // Allocate space for the converted pixels int[] pixelInts = new int[width * height]; // Convert RGB bytes to ARGB ints with no transparency. Flip // imageOpenGL vertically by reading the rows of pixels in the byte // buffer in reverse - (0,0) is at bottom left in OpenGL. int p = width * height * 3; // Points to first byte (red) in each row. int q; // Index into ByteBuffer int i = 0; // Index into target int[] int bytesPerRow = width * 3; // Number of bytes in each row for (int row = height - 1; row >= 0; row p = row * bytesPerRow; q = p; for (int col = 0; col < width; col++) { int iR = rgbData.get(q++); int iG = rgbData.get(q++); int iB = rgbData.get(q++); pixelInts[i++] = ((0xFF000000) | ((iR & 0xFF) << 16) | ((iG & 0xFF) << 8) | (iB & 0xFF)); } } // Set the data for the BufferedImage if (getImageOpenGL() == null || getImageOpenGL().getWidth() != width || getImageOpenGL().getHeight() != height) { imageOpenGL = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); } getImageOpenGL().setRGB(0, 0, width, height, pixelInts, 0, width); } public BufferedImage getImageOpenGL() { return imageOpenGL; } public GLUT getGlut() { return glut; } /** gets the chip we are rendering for. Subclasses or display methods can use this to access the chip object. @return the chip */ public Chip2D getChip() { return chip; } public void setChip(Chip2D chip) { this.chip = chip; } }
package com.aemreunal.config; import java.beans.PropertyVetoException; import java.util.Properties; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.PropertySources; import org.springframework.orm.jpa.vendor.Database; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import com.mchange.v2.c3p0.ComboPooledDataSource; import com.mysql.jdbc.Driver; @Configuration //@PropertySource("file:db.properties") @PropertySources(value = { @PropertySource(value = "file:db.properties", ignoreResourceNotFound = true), @PropertySource(value = "file:/root/iBeaconServer/db.properties", ignoreResourceNotFound = true) }) public class DatabaseSettings { @Value("${db.username}") private String dbUsername; @Value("${db.password}") private String dbPassword; @Value("${db.ip}") private String dbIp; @Value("${db.port}") private String dbPort; @Value("${db.name}") private String dbName; @Bean public HibernateJpaVendorAdapter vendorAdapter() { HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); vendorAdapter.setDatabase(Database.MYSQL); vendorAdapter.setGenerateDdl(true); return vendorAdapter; } // TODO better configure data source: // http://www.mchange.com/projects/c3p0/#configuration @Bean public DataSource dataSource() { ComboPooledDataSource dataSource = new ComboPooledDataSource(); try { dataSource.setDriverClass(Driver.class.getName()); } catch (PropertyVetoException e) { System.err.println("Unable to set data source driver class!\nWill exit now."); System.exit(-1); } dataSource.setJdbcUrl(getJdbcUrl()); dataSource.setUser(dbUsername); dataSource.setPassword(dbPassword); return dataSource; } @Bean public Properties jpaProperties() { Properties properties = new Properties(); properties.put(GlobalSettings.DB_DIALECT_KEY, GlobalSettings.DB_DIALECT_PROPERTY); properties.put(GlobalSettings.SHOW_SQL_KEY, GlobalSettings.SHOW_SQL_PROPERTY); properties.put(GlobalSettings.FORMAT_SQL_KEY, GlobalSettings.FORMAT_SQL_PROPERTY); properties.put(GlobalSettings.HBM2DDL_KEY, GlobalSettings.HBM2DDL_PROPERTY); return properties; } // We need to call this dynamically and can't make it a field, // as the other fields this depends on are assigned dynamically // during runtime via '@Value' private String getJdbcUrl() { return "jdbc:mysql://" + dbIp + ":" + dbPort + "/" + dbName + "?useUnicode=true&characterEncoding=UTF-8"; } }
package net.sf.mzmine.main; import java.util.Iterator; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.SwingUtilities; import net.sf.mzmine.io.impl.IOControllerImpl; import net.sf.mzmine.project.impl.MZmineProjectImpl; import net.sf.mzmine.taskcontrol.impl.TaskControllerImpl; import net.sf.mzmine.userinterface.mainwindow.MainWindow; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; /** * Main client class */ public class MZmineClient extends MZmineCore implements Runnable { private Logger logger = Logger.getLogger(this.getClass().getName()); private Vector<MZmineModule> moduleSet; /** * Main method */ public static void main(String args[]) { // create the GUI in the event-dispatching thread MZmineClient client = new MZmineClient(); SwingUtilities.invokeLater(client); } /** * @see java.lang.Runnable#run() */ public void run() { // load configuration from XML Document configuration = null; MainWindow desktop = null; try { SAXReader reader = new SAXReader(); configuration = reader.read(CONFIG_FILE); Element configRoot = configuration.getRootElement(); // get the configured number of computation nodes int numberOfNodes; Element nodes = configRoot.element(NODES_ELEMENT_NAME); String numberOfNodesConfigEntry = nodes.attributeValue(LOCAL_ATTRIBUTE_NAME); if (numberOfNodesConfigEntry != null) { numberOfNodes = Integer.parseInt(numberOfNodesConfigEntry); } else numberOfNodes = Runtime.getRuntime().availableProcessors(); logger.info("MZmine starting with " + numberOfNodes + " computation nodes"); logger.finer("Loading core classes"); // create instances of core modules TaskControllerImpl taskController = new TaskControllerImpl( numberOfNodes); IOControllerImpl ioController = new IOControllerImpl(); desktop = new MainWindow(); MZmineProjectImpl project = new MZmineProjectImpl(); // save static references to MZmineCore MZmineCore.taskController = taskController; MZmineCore.ioController = ioController; MZmineCore.desktop = desktop; MZmineCore.currentProject = project; logger.finer("Initializing core classes"); taskController.initModule(); ioController.initModule(); desktop.initModule(); project.initModule(); logger.finer("Loading modules"); moduleSet = new Vector<MZmineModule>(); Iterator modIter = configRoot.element(MODULES_ELEMENT_NAME).elementIterator( MODULE_ELEMENT_NAME); while (modIter.hasNext()) { Element moduleElement = (Element) modIter.next(); String className = moduleElement.attributeValue(CLASS_ATTRIBUTE_NAME); loadModule(className); } MZmineCore.initializedModules = moduleSet.toArray(new MZmineModule[0]); // load module configuration loadConfiguration(CONFIG_FILE); } catch (Exception e) { logger.log(Level.SEVERE, "Could not parse configuration file " + CONFIG_FILE, e); System.exit(1); } // register the shutdown hook ShutDownHook shutDownHook = new ShutDownHook(); Runtime.getRuntime().addShutdownHook(shutDownHook); // show the GUI logger.finest("Showing main window"); desktop.setVisible(true); // show the welcome message desktop.setStatusBarText("Welcome to MZmine!"); } public MZmineModule loadModule(String moduleClassName) { try { logger.finest("Loading module " + moduleClassName); // load the module class Class moduleClass = Class.forName(moduleClassName); // create instance MZmineModule moduleInstance = (MZmineModule) moduleClass.newInstance(); // init module moduleInstance.initModule(); // add to the module set moduleSet.add(moduleInstance); return moduleInstance; } catch (Exception e) { logger.log(Level.SEVERE, "Could not load module " + moduleClassName, e); return null; } } /** * Shutdown hook - invoked on JRE shutdown. This method saves current * configuration to XML. * */ private class ShutDownHook extends Thread { public void start() { saveConfiguration(CONFIG_FILE); } } }
package com.airbnb.chancery; import lombok.extern.slf4j.Slf4j; import org.apache.commons.codec.binary.Hex; import javax.annotation.Nullable; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import javax.validation.constraints.NotNull; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; @Slf4j public class GithubAuthChecker { static final String HMAC_SHA1 = "HmacSHA1"; final Mac mac; public GithubAuthChecker(String secret) throws NoSuchAlgorithmException, InvalidKeyException { mac = Mac.getInstance(HMAC_SHA1); final SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), HMAC_SHA1); mac.init(signingKey); } /** * Checks a github signature against its payload * @param signature A X-Hub-Signature header value ("sha1=[...]") * @param payload The signed HTTP request body * @return Whether the signature is correct for the checker's secret */ boolean checkSignature(@Nullable String signature, @NotNull String payload) { if (signature == null || signature.length() != 45) return false; final char[] hash = Hex.encodeHex(this.mac.doFinal(payload.getBytes())); final StringBuilder builder = new StringBuilder("sha1="); builder.append(hash); final String expected = builder.toString(); log.debug("Comparing {} and {}", expected, signature); return expected.equals(signature); } }
package org.jaudiotagger.tag.id3.framebody; import org.jaudiotagger.tag.InvalidTagException; import org.jaudiotagger.tag.datatype.DataTypes; import org.jaudiotagger.tag.id3.ID3v23Frames; import org.jaudiotagger.tag.id3.ID3v24Frames; import org.jaudiotagger.tag.id3.valuepair.TextEncoding; import java.nio.ByteBuffer; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.logging.Level; public class FrameBodyTDRC extends AbstractFrameBodyTextInfo implements ID3v24FrameBody { /** * Used when converting from v3 tags */ private String originalID; private String year = ""; private String time = ""; private String date = ""; private String reco = ""; private static SimpleDateFormat formatYearIn, formatYearOut; private static SimpleDateFormat formatDateIn, formatDateOut; private static SimpleDateFormat formatTimeIn, formatTimeOut; private static final List<SimpleDateFormat> formatters = new ArrayList<SimpleDateFormat>(); private static final int PRECISION_SECOND = 0; private static final int PRECISION_MINUTE = 1; private static final int PRECISION_HOUR = 2; private static final int PRECISION_DAY = 3; private static final int PRECISION_MONTH = 4; private static final int PRECISION_YEAR = 5; static { //This is allowable v24 format , we use UK Locale not because we are restricting to UK //but because these formats are fixed in ID3 spec, and could possibly get unexpected results if library //used with a default locale that has Date Format Symbols that intefere with the pattern formatters.add(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.UK)); formatters.add(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm", Locale.UK)); formatters.add(new SimpleDateFormat("yyyy-MM-dd'T'HH", Locale.UK)); formatters.add(new SimpleDateFormat("yyyy-MM-dd", Locale.UK)); formatters.add(new SimpleDateFormat("yyyy-MM", Locale.UK)); formatters.add(new SimpleDateFormat("yyyy", Locale.UK)); //These are formats used by v23 Frames formatYearIn = new SimpleDateFormat("yyyy", Locale.UK); formatYearOut = new SimpleDateFormat("yyyy", Locale.UK); formatDateIn = new SimpleDateFormat("ddMM", Locale.UK); formatDateOut = new SimpleDateFormat("-MM-dd", Locale.UK); formatTimeIn = new SimpleDateFormat("HHmm", Locale.UK); formatTimeOut = new SimpleDateFormat("'T'HH:mm", Locale.UK); } /** * Creates a new FrameBodyTDRC datatype. */ public FrameBodyTDRC() { super(); } public FrameBodyTDRC(FrameBodyTDRC body) { super(body); } /** * Retrieve the original identifier */ public String getOriginalID() { return originalID; } /** * When this has been generated as an amalgamation of v3 frames assumes * the v3 frames match the the format in specification and convert them * to their equivalent v4 format and return the generated String. * i.e if the v3 frames contain a valid value this will return a valid * v4 value, if not this won't. */ /** * Synchronized because SimpleDatFormat arent thread safe * * @param formatDate * @param parseDate * @param text * @return */ private static synchronized String formatAndParse(SimpleDateFormat formatDate,SimpleDateFormat parseDate,String text) { try { return formatDate.format(parseDate.parse(text)); } catch (ParseException e) { logger.warning("Unable to parse:" + text); } return ""; } public String getFormattedText() { StringBuffer sb = new StringBuffer(); if (originalID == null) { return this.getText(); } else { if (year != null && !(year.equals(""))) { sb.append(formatAndParse(formatYearOut,formatYearIn,year)); } if (!date.equals("")) { sb.append(formatAndParse(formatDateOut,formatDateIn,date)); } if (!time.equals("")) { sb.append(formatAndParse(formatTimeOut,formatTimeIn,time)); } return sb.toString(); } } public void setYear(String year) { logger.finest("Setting year to" + year); this.year = year; } public void setTime(String time) { logger.finest("Setting time to:" + time); this.time = time; } public void setDate(String date) { logger.finest("Setting date to:" + date); this.date = date; } public void setReco(String reco) { this.reco = reco; } public String getYear() { return year; } public String getTime() { return time; } public String getDate() { return date; } public String getReco() { return reco; } /** * When converting v3 YEAR to v4 TDRC frame */ public FrameBodyTDRC(FrameBodyTYER body) { originalID = ID3v23Frames.FRAME_ID_V3_TYER; year = body.getText(); setObjectValue(DataTypes.OBJ_TEXT_ENCODING, TextEncoding.ISO_8859_1); setObjectValue(DataTypes.OBJ_TEXT, body.getText()); } /** * When converting v3 TIME to v4 TDRC frame */ public FrameBodyTDRC(FrameBodyTIME body) { originalID = ID3v23Frames.FRAME_ID_V3_TIME; time = body.getText(); setObjectValue(DataTypes.OBJ_TEXT_ENCODING, TextEncoding.ISO_8859_1); setObjectValue(DataTypes.OBJ_TEXT, body.getText()); } /** * When converting v3 TDAT to v4 TDRC frame */ public FrameBodyTDRC(FrameBodyTDAT body) { originalID = ID3v23Frames.FRAME_ID_V3_TDAT; date = body.getText(); setObjectValue(DataTypes.OBJ_TEXT_ENCODING, TextEncoding.ISO_8859_1); setObjectValue(DataTypes.OBJ_TEXT, body.getText()); } /** * When converting v3 TRDA to v4 TDRC frame */ public FrameBodyTDRC(FrameBodyTRDA body) { originalID = ID3v23Frames.FRAME_ID_V3_TRDA; reco = body.getText(); setObjectValue(DataTypes.OBJ_TEXT_ENCODING, TextEncoding.ISO_8859_1); setObjectValue(DataTypes.OBJ_TEXT, body.getText()); } /** * Creates a new FrameBodyTDRC datatype. * * @param textEncoding * @param text */ public FrameBodyTDRC(byte textEncoding, String text) { super(textEncoding, text); //Find the date format of the text for (int i = 0; i < formatters.size(); i++) { try { Date d; synchronized(formatters.get(i)) { d = formatters.get(i).parse(getText()); } //If able to parse a date from the text if (d != null) { extractID3v23Formats(d, i); break; } } //Dont display will occur for each failed format catch (ParseException e) { //Do nothing; } catch(NumberFormatException nfe) { //Do nothing except log warning because not really expecting this to happen logger.log(Level.WARNING,"Date Formatter:"+formatters.get(i).toPattern() + "failed to parse:"+getText()+ "with "+nfe.getMessage(),nfe); } } } /** * Creates a new FrameBodyTDRC datatype from File * * @throws InvalidTagException */ public FrameBodyTDRC(ByteBuffer byteBuffer, int frameSize) throws InvalidTagException { super(byteBuffer, frameSize); //Store the equivalent ID3v23 values in case convert //Find the date format of the v24Frame for (int i = 0; i < formatters.size(); i++) { try { Date d; synchronized(formatters.get(i)) { d = formatters.get(i).parse(getText()); } if (d != null) { extractID3v23Formats(d, i); break; } } //Dont display will occur for each failed format catch (ParseException e) { //Do nothing; } catch(NumberFormatException nfe) { //Do nothing except log warning because not really expecting this to happen (but it does !) logger.log(Level.WARNING,"Date Formatter:"+formatters.get(i).toPattern() + "failed to parse:"+getText()+ "with "+nfe.getMessage(),nfe); } } } /** * Format Date * * Synchronized because SimpleDateFormat is invalid * * @param d * @return */ private static synchronized String formatDateAsYear(Date d) { return formatYearOut.format(d); } /** * Format Date * * Synchronized because SimpleDateFormat is invalid * * @param d * @return */ private static synchronized String formatDateAsDate(Date d) { return formatDateOut.format(d); } /** * Format Date * * Synchronized because SimpleDateFormat is invalid * * @param d * @return */ private static synchronized String formatDateAsTime(Date d) { return formatTimeOut.format(d); } /** * Extract Format * * @param dateRecord * @param precision */ private void extractID3v23Formats(final Date dateRecord, final int precision) { Date d = dateRecord; //Precision Year if (precision == PRECISION_YEAR) { setYear(formatDateAsYear(d)); } //Precision Month else if (precision == PRECISION_MONTH) { setYear(formatDateAsYear(d)); } //Precision Day else if (precision == PRECISION_DAY) { setYear(formatDateAsYear(d)); setDate(formatDateAsDate(d)); } //Precision Hour else if (precision == PRECISION_HOUR) { setYear(formatDateAsYear(d)); setDate(formatDateAsDate(d)); } //Precision Minute else if (precision == PRECISION_MINUTE) { setYear(formatDateAsYear(d)); setDate(formatDateAsDate(d)); setTime(formatDateAsTime(d)); } //Precision Minute else if (precision == PRECISION_SECOND) { setYear(formatDateAsYear(d)); setDate(formatDateAsDate(d)); setTime(formatDateAsTime(d)); } } /** * The ID3v2 frame identifier * * @return the ID3v2 frame identifier for this frame type */ public String getIdentifier() { return ID3v24Frames.FRAME_ID_YEAR; } }
package com.antsoft.yecai.model; import org.hibernate.validator.constraints.NotBlank; import javax.validation.constraints.Size; public class UserLoginInfo { @NotBlank @Size(min = 3, max = 16) private String loginName; @NotBlank @Size(min = 3, max = 20) private String password; private String sign; public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } }
package com.j2trp.core; import java.io.BufferedReader; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.Principal; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import javax.servlet.RequestDispatcher; import javax.servlet.ServletInputStream; import javax.servlet.ServletRequest; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpSession; public class ModifiableHttpRequest extends HttpServletRequestWrapper { private String authType; private Cookie[] cookies; private Map<String, List<String>> headers = new HashMap<String, List<String>>(); private String method; private String pathInfo; private String pathTranslated; private String contextPath; private String queryString; private String remoteUser; private Set<String> userInRole = new HashSet<String>(); private Principal principal; private String protocol; private String scheme; private Integer port; private String serverName; private String characterEncoding; private int contentLength; private ServletInputStream is; private String localAddr; private Locale locale; private String localName; private int localPort; private Map<String, String[]> parameterMap; private BufferedReader reader; private String realPath; private String remoteAddr; private String remoteHost; private int remotePort; private ServletRequest servletRequest; private RequestDispatcher requestDispatcher; private String requestedSessionId; private String requestURI; private StringBuffer requestURL; private int serverPort; private String servletPath; private HttpSession session; private boolean secure; private boolean requestedSessionIdValue; private boolean requestedSessionIdFromCookie; private boolean requestedSessionIdFromCookieUrl; private boolean requestedSessionIdFromCookieURL; private Map<String, Object> attributes = new HashMap<String, Object>(); private String contentType; public ModifiableHttpRequest(HttpServletRequest request) { super(request); } @Override public String getAuthType() { return Toolbox.getValue(super.getAuthType(), authType, String.class); } @Override public Cookie[] getCookies() { return Toolbox.merge(super.getCookies(), cookies, Cookie[].class); } @Override public long getDateHeader(String name) { return Toolbox.getValue(super.getDateHeader(name), Long.parseLong(headers.get(name).get(0)), -1L, Long.class); } @Override public String getHeader(String name) { return Toolbox.getValue(super.getHeader(name), headers.get(name), String.class); } @Override @SuppressWarnings("unchecked") public Enumeration<String> getHeaders(String name) { return Toolbox.mergeCollection(super.getHeaders(name), Toolbox.safeEnumerator(headers.get(name))); } @Override @SuppressWarnings("unchecked") public Enumeration<String> getHeaderNames() { return Toolbox.mergeCollection(super.getHeaderNames(), Toolbox.safeEnumerator(headers.keySet())); } @Override public int getIntHeader(String name) { return Toolbox.getValue(super.getIntHeader(name), Integer.parseInt(headers.get(name).get(0)), -1, Integer.class); } @Override public String getMethod() { return Toolbox.getValue(super.getMethod(), method, String.class); } @Override public String getPathInfo() { return Toolbox.getValue(super.getPathInfo(), pathInfo, String.class); } @Override public String getPathTranslated() { return Toolbox.getValue(super.getPathTranslated(), pathTranslated, String.class); } @Override public String getContextPath() { return Toolbox.getValue(super.getContextPath(), contextPath, String.class); } @Override public String getQueryString() { return Toolbox.getValue(super.getQueryString(), queryString, String.class); } @Override public String getRemoteUser() { return Toolbox.getValue(super.getRemoteUser(), remoteUser, String.class); } @Override public boolean isUserInRole(String role) { return Toolbox.getValue(super.isUserInRole(role), userInRole.contains(role), Boolean.class); } @Override public Principal getUserPrincipal() { return Toolbox.getValue(super.getUserPrincipal(), principal, Principal.class); } @Override public String getRequestedSessionId() { return Toolbox.getValue(super.getRequestedSessionId(), requestedSessionId, String.class); } @Override public String getRequestURI() { return Toolbox.getValue(super.getRequestURI(), requestURI, String.class); } @Override public StringBuffer getRequestURL() { return Toolbox.getValue(super.getRequestURL(), requestURL, StringBuffer.class); } @Override public String getServletPath() { return Toolbox.getValue(super.getServletPath(), servletPath, String.class); } @Override public HttpSession getSession(boolean create) { if (session != null) { return session; } return super.getSession(create); } @Override public HttpSession getSession() { return Toolbox.getValue(super.getSession(), session, HttpSession.class); } @Override public boolean isRequestedSessionIdValid() { return Toolbox.getValue(super.isRequestedSessionIdValid(), requestedSessionIdValue, Boolean.class); } @Override public boolean isRequestedSessionIdFromCookie() { return Toolbox.getValue(super.isRequestedSessionIdFromCookie(), requestedSessionIdFromCookie, Boolean.class); } @Override public boolean isRequestedSessionIdFromURL() { return Toolbox.getValue(super.isRequestedSessionIdFromURL(), requestedSessionIdFromCookieURL, Boolean.class); } @Override public boolean isRequestedSessionIdFromUrl() { return Toolbox.getValue(super.isRequestedSessionIdFromUrl(), requestedSessionIdFromCookieUrl, Boolean.class); } @Override public ServletRequest getRequest() { return Toolbox.getValue(super.getRequest(), servletRequest, ServletRequest.class); } @Override public void setRequest(ServletRequest request) { servletRequest = request; } @Override public Object getAttribute(String name) { return Toolbox.getValue(super.getAttribute(name), attributes.get(name), Object.class); } @Override @SuppressWarnings("unchecked") public Enumeration<String> getAttributeNames() { return Toolbox.mergeCollection(super.getAttributeNames(), Collections.enumeration(attributes.keySet())); } @Override public String getCharacterEncoding() { return Toolbox.getValue(super.getCharacterEncoding(), characterEncoding, String.class); } @Override public void setCharacterEncoding(String enc) throws UnsupportedEncodingException { characterEncoding = enc; } @Override public int getContentLength() { return Toolbox.getValue(super.getContentLength(), contentLength, -1, Integer.class); } @Override public String getContentType() { return Toolbox.getValue(super.getContentType(), contentType, String.class); } @Override public ServletInputStream getInputStream() throws IOException { return super.getInputStream(); } @Override public String getParameter(String name) { return Toolbox.getValue(super.getParameter(name), parameterMap.get(name), String.class); } @Override public Map getParameterMap() { return super.getParameterMap(); } @Override public Enumeration<String> getParameterNames() { return Toolbox.mergeCollection(super.getParameterNames(), Collections.enumeration(parameterMap.keySet())); } @Override public String[] getParameterValues(String name) { return Toolbox.merge(super.getParameterValues(name), parameterMap.get(name), String[].class); } @Override public String getProtocol() { return Toolbox.getValue(super.getProtocol(), protocol, String.class); } @Override public String getScheme() { return Toolbox.getValue(super.getScheme(), scheme, String.class); } @Override public String getServerName() { return Toolbox.getValue(super.getServerName(), serverName, String.class); } @Override public int getServerPort() { return Toolbox.getValue(super.getServerPort(), serverPort, Integer.class); } @Override public BufferedReader getReader() throws IOException { return super.getReader(); } @Override public String getRemoteAddr() { return Toolbox.getValue(super.getRemoteAddr(), remoteAddr, String.class); } @Override public String getRemoteHost() { return Toolbox.getValue(super.getRemoteHost(), remoteHost, String.class); } @Override public void setAttribute(String name, Object o) { attributes.put(name, o); } @Override public void removeAttribute(String name) { super.removeAttribute(name); } @Override public Locale getLocale() { return Toolbox.getValue(super.getLocale(), locale, Locale.class); } @Override @SuppressWarnings("unchecked") public Enumeration<Locale> getLocales() { return Toolbox.mergeCollection(super.getLocales(), new SingleValueEnumeration<Locale>(locale)); } @Override public boolean isSecure() { return Toolbox.getValue(super.isSecure(), secure, Boolean.class); } @Override public RequestDispatcher getRequestDispatcher(String path) { return Toolbox.getValue(super.getRequestDispatcher(path), requestDispatcher, RequestDispatcher.class); } @Override public String getRealPath(String path) { return Toolbox.getValue(super.getRealPath(path), realPath, String.class); } @Override public int getRemotePort() { return Toolbox.getValue(super.getRemotePort(), remotePort, Integer.class); } @Override public String getLocalName() { return Toolbox.getValue(super.getLocalName(), localName, String.class); } @Override public String getLocalAddr() { return Toolbox.getValue(super.getLocalAddr(), localAddr, String.class); } @Override public int getLocalPort() { return Toolbox.getValue(super.getLocalPort(), localPort, Integer.class); } public void setAuthType(String authType) { this.authType = authType; } public void setCookies(Cookie[] cookies) { if (cookies == null) { this.cookies = null; return; } this.cookies = new Cookie[cookies.length]; System.arraycopy(cookies, 0, this.cookies, 0, this.cookies.length); } public void addHeader(String header, String value) { List<String> values = headers.get(header); if (values == null) { values = new ArrayList<String>(); headers.put(header, values); } values.add(value); } public void setMethod(String method) { this.method = method; } public void setPathInfo(String pathInfo) { this.pathInfo = pathInfo; } public void setPathTranslated(String pathTranslated) { this.pathTranslated = pathTranslated; } public void setContextPath(String contextPath) { this.contextPath = contextPath; } public void setQueryString(String queryString) { this.queryString = queryString; } public void setRemoteUser(String remoteUser) { this.remoteUser = remoteUser; } public void setPrincipal(Principal principal) { this.principal = principal; } public void setProtocol(String protocol) { this.protocol = protocol; } public void setScheme(String scheme) { this.scheme = scheme; } public void setPort(Integer port) { this.port = port; } public void setServerName(String serverName) { this.serverName = serverName; } public void setContentLength(int contentLength) { this.contentLength = contentLength; } public void setIs(ServletInputStream is) { this.is = is; } public void setLocalAddr(String localAddr) { this.localAddr = localAddr; } public void setLocale(Locale locale) { this.locale = locale; } public void setLocalName(String localName) { this.localName = localName; } public void setLocalPort(int localPort) { this.localPort = localPort; } public void setParameterMap(Map<String, String[]> parameterMap) { this.parameterMap = parameterMap; } public void setReader(BufferedReader reader) { this.reader = reader; } public void setRealPath(String realPath) { this.realPath = realPath; } public void setRemoteAddr(String remoteAddr) { this.remoteAddr = remoteAddr; } public void setRemoteHost(String remoteHost) { this.remoteHost = remoteHost; } public void setRemotePort(int remotePort) { this.remotePort = remotePort; } public void setServletRequest(ServletRequest servletRequest) { this.servletRequest = servletRequest; } public void setRequestDispatcher(RequestDispatcher requestDispatcher) { this.requestDispatcher = requestDispatcher; } public void setRequestedSessionId(String requestedSessionId) { this.requestedSessionId = requestedSessionId; } public void setRequestURI(String requestURI) { this.requestURI = requestURI; } public void setRequestURL(StringBuffer requestURL) { this.requestURL = requestURL; } public void setServerPort(int serverPort) { this.serverPort = serverPort; } public void setServletPath(String servletPath) { this.servletPath = servletPath; } public void setSession(HttpSession session) { this.session = session; } public void setSecure(boolean secure) { this.secure = secure; } public void setRequestedSessionIdValue(boolean requestedSessionIdValue) { this.requestedSessionIdValue = requestedSessionIdValue; } public void setRequestedSessionIdFromCookie(boolean requestedSessionIdFromCookie) { this.requestedSessionIdFromCookie = requestedSessionIdFromCookie; } public void setRequestedSessionIdFromCookieUrl( boolean requestedSessionIdFromCookieUrl) { this.requestedSessionIdFromCookieUrl = requestedSessionIdFromCookieUrl; } public void setRequestedSessionIdFromCookieURL( boolean requestedSessionIdFromCookieURL) { this.requestedSessionIdFromCookieURL = requestedSessionIdFromCookieURL; } public void setAttributes(Map<String, Object> attributes) { this.attributes = attributes; } public void setContentType(String contentType) { this.contentType = contentType; } }
package org.kwstudios.play.ragemode.gameLogic; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.kwstudios.play.ragemode.items.CombatAxe; import org.kwstudios.play.ragemode.items.RageArrow; import org.kwstudios.play.ragemode.items.RageBow; import org.kwstudios.play.ragemode.items.RageKnife; import org.kwstudios.play.ragemode.scoreboard.ScoreBoard; import org.kwstudios.play.ragemode.tabsGuiListOverlay.TabAPI; import org.kwstudios.play.ragemode.toolbox.ConstantHolder; import org.kwstudios.play.ragemode.toolbox.GameBroadcast; public class GameLoader { private String gameName; private FileConfiguration fileConfiguration; private List<Location> gameSpawns = new ArrayList<Location>(); public GameLoader(String gameName, FileConfiguration fileConfiguration) { this.gameName = gameName; this.fileConfiguration = fileConfiguration; PlayerList.setGameRunning(gameName); checkTeleport(); setInventories(); List<String> players = Arrays.asList(PlayerList.getPlayersInGame(gameName)); // TabGuiUpdater.setTabGui(players); TabAPI.setTabGuiListOverLayForPlayers(players); ScoreBoard gameBoard = new ScoreBoard(players, true); new GameTimer(this.gameName, this.fileConfiguration); } private void checkTeleport(){ GameSpawnGetter gameSpawnGetter = new GameSpawnGetter(gameName, fileConfiguration); if (gameSpawnGetter.isGameReady()) { gameSpawns = gameSpawnGetter.getSpawnLocations(); teleportPlayersToGameSpawns(); } else { String message = ConstantHolder.RAGEMODE_PREFIX + ChatColor.DARK_RED + "The game is not set up correctly. Please contact an Admin."; GameBroadcast.broadcastToGame(gameName, message); String[] players = PlayerList.getPlayersInGame(gameName); for(String player : players){ Player thisPlayer = Bukkit.getPlayer(UUID.fromString(player)); PlayerList.removePlayer(thisPlayer); } } } private void teleportPlayersToGameSpawns() { String[] players = PlayerList.getPlayersInGame(gameName); for (int i = 0; i < players.length; i++) { Player player = Bukkit.getPlayer(UUID.fromString(players[i])); Location location = gameSpawns.get(i); player.teleport(location); } } private void setInventories(){ String[] players = PlayerList.getPlayersInGame(gameName); for (String playerUUID : players) { Player player = Bukkit.getPlayer(UUID.fromString(playerUUID)); player.getInventory().setItem(0, RageBow.getRageBow()); player.getInventory().setItem(1, RageKnife.getRageKnife()); player.getInventory().setItem(2, CombatAxe.getCombatAxe()); player.getInventory().setItem(9, RageArrow.getRageArrow()); } } }
package com.areen.jlib.gui.fcb; import com.areen.jlib.gui.ColorArrowUI; import com.areen.jlib.tuple.Pair; import com.areen.jlib.util.Sise; import java.awt.event.*; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.*; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.JTextComponent; import javax.swing.text.PlainDocument; public class ComboBoxFilter extends PlainDocument { private JComboBox comboBox; private JTextComponent comboBoxEditor; private FilteredComboBoxModel comboBoxModel; /** * Every call to setSelectedItem() in the combo-box will provoke another * call to the insertString, with the newly selected item. We prevent this * by seting "selecting" to true before we call setPattern(). Subsequent * calls to remove/insertString should be ignored. */ boolean selecting = false; boolean hidePopupOnFocusLoss; private boolean arrowKeyPressed = false; private boolean keyPressed = false; private boolean finish = false; private boolean inPreparation; private int selectedIndex; private Object pickedItem; private Object pickedKey; /** * This value is set by cell-editors to inform ComboBoxFilter whether to * execute pick value or not during the preparation phase (prepare() * method). */ private boolean triggeredByKeyPress = false; private int previousItemCount; /** * We have to store the popup menu's dimension so we can fix incorrect popup * size during the filtering process. */ private int popupMenuWidth; private int popupMenuHeight; static final Logger LOGGER = Logger.getLogger(ComboBoxFilter.class.getCanonicalName()); /** * This constructor adds filtering capability to the given JComboBox object * argComboBox. It will also assign appropriate model to the combo-box, one * that has setPattern() method. It will also set the argComboBox to be * editable. * * @param argComboBox * @param argComboBoxModel */ public ComboBoxFilter(final JComboBox argComboBox, FilteredComboBoxModel argComboBoxModel) { comboBox = argComboBox; comboBox.setEditable(true); fixComboBoxArrowUI(); comboBoxModel = argComboBoxModel; comboBox.setModel(comboBoxModel); // If initially an item is selected, we will assume that item is a picked item. comboBox.putClientProperty("item-picked", Boolean.TRUE); /* if (comboBox.getSelectedItem() == null) { comboBox.putClientProperty("item-picked", Boolean.TRUE); } else { comboBox.putClientProperty("item-picked", Boolean.TRUE); } * */ comboBoxEditor = (JTextComponent) comboBox.getEditor().getEditorComponent(); comboBoxEditor.setDocument(this); KeyAdapter keyAdapter = new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); /* * In the case user presses SHIFT, CTRL, ALT keys, or <ANY>+TAB, * we return imediately. */ //int modifiers = e.getModifiersEx(); if (keyCode == KeyEvent.VK_SHIFT || (keyCode == KeyEvent.VK_ALT) || (keyCode == KeyEvent.VK_CONTROL) || (keyCode == KeyEvent.VK_WINDOWS) || (keyCode == KeyEvent.VK_CONTEXT_MENU) || (keyCode == KeyEvent.VK_TAB && e.isShiftDown())) { keyPressed = false; return; } keyPressed = true; boolean isTableCellEditor = false; Object tmp = comboBox.getClientProperty("JComboBox.isTableCellEditor"); if (tmp != null) { isTableCellEditor = tmp.equals(Boolean.TRUE); } if (comboBox.isDisplayable()) { comboBox.setPopupVisible(true); } arrowKeyPressed = false; finish = false; int currentIndex = comboBox.getSelectedIndex(); switch (keyCode) { case KeyEvent.VK_TAB: finish = true; comboBoxModel.setReadyToFinish(false); if (!isTableCellEditor()) { String txt = updateFcbEditor(); boolean pa = comboBoxModel.isAnyPatternAllowed(); boolean ma = comboBoxModel.isMultiSelectionAllowed(); if (pa || ma) { // TODO } else { if (txt == null) { // After all events are processed, alert the user SwingUtilities.invokeLater(new Runnable() { @Override public void run() { String eol = System.getProperty("line.separator"); JOptionPane.showMessageDialog(comboBox, "Invalid option. Old value restored."); comboBox.requestFocusInWindow(); } // run() method }); // Runnable (anonymous) implementation } } // else } if ((comboBox.getSelectedItem() == null)) { /* * If TAB is pressed, but nothing is selected, and * the picked item is not null * that means the user * pressed tab when there was an empty list of * items. * (Typically when user typed something * that does not exist in the list of * items). In * this case we cancel the editing. */ comboBoxModel.setCancelled(true); } if (comboBox.getSelectedItem() != null) { if (pickedItem == comboBox.getSelectedItem()) { /* * We cancel the editing when the picked item is * the same as the item that * is currently * selected in the combo-box, because we do not * want to * trigger database change (there is * no need to update to the same value). */ comboBoxModel.setCancelled(true); } else { pickedItem = comboBox.getSelectedItem(); pickedKey = comboBoxModel.getKeyOfTheSelectedItem().toString(); } // else } break; case KeyEvent.VK_ESCAPE: if (isTableCellEditor()) { comboBoxModel.setCancelled(true); comboBox.setSelectedItem(pickedItem); } else { if (pickedKey == null) { ComboBoxFilter.this.setText(""); } else { ComboBoxFilter.this.setText(pickedKey.toString()); } // else } // else break; case KeyEvent.VK_ENTER: finish = true; comboBoxModel.setReadyToFinish(false); // we expect cell editor String txt = updateFcbEditor(); boolean pa = comboBoxModel.isAnyPatternAllowed(); boolean ma = comboBoxModel.isMultiSelectionAllowed(); if ((pa || ma)) { if (txt == null) { // do nothing } else { // we have to update the text here because updateFcbEditor won't setText(txt); pickedItem = comboBox.getSelectedItem(); pickedKey = txt; comboBoxModel.setPickedItem(pickedItem); comboBoxModel.setPickedKey(txt); } //else } else { if (txt == null) { // if user types a string that has no match, we select the last picked item. comboBox.setSelectedItem(pickedItem); // After all events are processed, alert the user SwingUtilities.invokeLater(new Runnable() { @Override public void run() { String eol = System.getProperty("line.separator"); JOptionPane.showMessageDialog(comboBox, "Invalid option."); } // run() method }); // Runnable (anonymous) implementation } else { // setText(txt); // No need because updateFcbEditor will do it in this case pickedItem = comboBox.getSelectedItem(); pickedKey = txt; comboBoxModel.setPickedItem(pickedItem); comboBoxModel.setPickedKey(txt); } // else } // else break; case KeyEvent.VK_UP: arrowKeyPressed = true; if (isTableCellEditor) { /* * For some reason, the JTable is stealing keyboard * events and preventing us * from moving up/down, * so we have to select proper values manually. * * * If selection did not move, we will manually * select appropriate item. */ if ((selectedIndex == currentIndex) && (currentIndex > 0)) { comboBox.setSelectedIndex(currentIndex - 1); selectedIndex = currentIndex - 1; } else { selectedIndex = currentIndex; } // else // we set this to false ONLY if the combo box is a cell editor! arrowKeyPressed = false; } break; case KeyEvent.VK_DOWN: arrowKeyPressed = true; if (isTableCellEditor && comboBox.isPopupVisible()) { /* * For some reason, the JTable is stealing keyboard * events and preventing us * from moving up/down, * so we have to select proper values manually. * * * If selection did not move, we will manually * select appropriate item. */ if ((selectedIndex == currentIndex) && (currentIndex < comboBox.getItemCount() - 1)) { comboBox.setSelectedIndex(currentIndex + 1); selectedIndex = currentIndex + 1; } else { selectedIndex = currentIndex; } // else // we set this to false ONLY if the combo box is a cell editor! arrowKeyPressed = false; } break; default: selectedIndex = currentIndex; } // switch keyPressed = false; } // keyPressed() method }; // KeyAdapter subclass (anonymous) // add the keyAdapter as *the first* KeyListener registered in the comboBoxEditor addAsTheFirstKeyListener(keyAdapter); // Bug 5100422 on Java 1.5: Editable JComboBox won't hide popup when tabbing out hidePopupOnFocusLoss = System.getProperty("java.version").startsWith("1.5"); // Highlight whole text when focus gets lost comboBoxEditor.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { boolean pa = comboBoxModel.isAnyPatternAllowed(); boolean ma = comboBoxModel.isMultiSelectionAllowed(); if (pickedKey != null && !(pa || ma)) { // When combo-box loses focus, we need to set the text to the selected setText(pickedKey.toString()); } else { if (!(pa || ma)) { setText(""); } } // else // Workaround for Bug 5100422 - Hide Popup on focus loss if (hidePopupOnFocusLoss) { ComboBoxFilter.this.comboBox.setPopupVisible(false); } comboBoxModel.setReadyToFinish(false); } // focusLost() method @Override public void focusGained(FocusEvent fe) { if (!isTableCellEditor()) { super.focusGained(fe); comboBoxEditor.selectAll(); } } // focusGained() method }); /* * The following PopupMenuListener is needed to store the inidial * Dimension of the combobox popup. */ comboBox.addPopupMenuListener(new PopupMenuListener() { @Override public void popupMenuWillBecomeVisible(PopupMenuEvent pme) { /* * NOTE: Dimension returned by getSize() method is actually the * dimension of the combo-box popup menu! It is not the size of * the JTextComponent object! :) */ JComboBox box = (JComboBox) pme.getSource(); popupMenuWidth = box.getSize().width; popupMenuHeight = box.getSize().height; } // popupMenuWillBecomeVisible() method @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent pme) { comboBox.putClientProperty("item-picked", Boolean.FALSE); } // popupMenuWillBecomeInvisible() method @Override public void popupMenuCanceled(PopupMenuEvent pme) { // do nothing } // popupMenuCanceled() method }); if (!isTableCellEditor()) { comboBoxEditor.setFocusTraversalKeysEnabled(false); Action myAction = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { // Nothing is needed here - all we want is to skip focusLost() call when user presses TAB comboBoxEditor.transferFocus(); } // actionPerformed() method }; comboBoxEditor.getActionMap().put("tab-action", myAction); comboBoxEditor.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) .put(KeyStroke.getKeyStroke("TAB"), "tab-action"); } Object selected = comboBox.getSelectedItem(); pickedItem = selected; Object tmp = comboBoxModel.getKeyOfTheSelectedItem(); if (tmp instanceof String) { pickedKey = tmp.toString(); } else { pickedKey = tmp; } // else selectedIndex = comboBox.getSelectedIndex(); if (selected != null) { setText(comboBoxModel.getKeyOfTheSelectedItem().toString()); } } // ComboBoxFilter() method /** * User typically will call this method from a table cell editor when we * want to "inform" filtered combo-box that we want to re-filter before we * actually start editing. The reason for this is when user goes to another * cell, the filtered set of entries from the previous cell will not apply. * * @param argPattern */ public void prepare(Object argPattern) { if (argPattern == null) { // If the previous value is null, we simply exit this method. pickedItem = null; pickedKey = null; comboBox.setSelectedItem(null); return; } inPreparation = true; selecting = true; comboBoxModel.setCancelled(false); if (isTableCellEditor()) { comboBoxModel.setReadyToFinish(false); } String pat = (String) argPattern.toString(); /* * If the editing is triggered by a key-press in a JTable, then the * argPattern contains a string in SISE format, so we have to extract * they key pressed and the previous value. */ String key = ""; if (isTriggeredByKeyPress()) { String[] strs = Sise.units(pat); /* * In the case the cell's value was a NULL, then strs will have only * one element. In that case we set pat to be a null, and do not set * the pickedItem. */ if (strs.length == 2) { pat = strs[1]; } else { pat = null; } // else key = strs[0]; } try { if (argPattern == null) { setText(""); } else { if (pat != null) { setText(pat.trim()); } } // else if (pat == null) { pickedItem = null; pickedKey = null; } else { // Cell's value was not a null, so we can execute filter so the combo-box updates the // selected item to be what was previously selected. filterTheModel(); pickedItem = comboBox.getSelectedItem(); pickedKey = comboBoxModel.getKeyOfTheSelectedItem(); } // else // Finally, when we have selected the item that was previously selected, now we can insert // the character user typed inside a JTable if (isTriggeredByKeyPress()) { setText(key); filterTheModel(); } } catch (BadLocationException ex) { Logger.getLogger(ComboBoxFilter.class.getName()).log(Level.SEVERE, null, ex); } // catch if (isTableCellEditor()) { comboBoxModel.setReadyToFinish(false); } inPreparation = false; } // prepare() method private void clearTextSelection() { if (comboBoxEditor.getSelectedText() != null) { // we have a selected text, removing the selection. On Windows text may become selected by default int pos = comboBoxEditor.getCaretPosition(); comboBoxEditor.select(0, 0); // return caret position to the original place comboBoxEditor.setCaretPosition(pos); } } // clearTextSelection() method private void setText(String text) { try { // remove all text and insert the completed string super.remove(0, getLength()); super.insertString(0, text, null); } catch (BadLocationException e) { throw new RuntimeException(e.toString()); } // catch } // setText() method /** * This method is a leftover from the previous version of the * ComboBoxFilter. Should be removed after the testing phase. */ private void highlightCompletedText(int start) { comboBoxEditor.setCaretPosition(getLength()); comboBoxEditor.moveCaretPosition(start); } // highlightCompletedText() method @Override public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { // return immediately when selecting an item if (selecting) { return; } if (arrowKeyPressed) { arrowKeyPressed = false; comboBox.putClientProperty("item-picked", Boolean.FALSE); return; } boolean itemPicked = false; // we need this value because item-picked may change due to chain // of events // inform action-performed listeners that the item has been picked so they may update // some other components if (keyPressed) { itemPicked = false; } else { itemPicked = true; } // else boolean isPicked = (Boolean) comboBox.getClientProperty("item-picked"); comboBox.putClientProperty("item-picked", itemPicked || isPicked); // insert the string into the document if (str.contains(Sise.UNIT_SEPARATOR_STRING)) { System.out.println(str); // we got a string in the Sise format, that must be because user picked an item with a mouse // in that case, we will take the key component (SISE unit) and put that instead. String[] strs = Sise.units(str); int idx = comboBoxModel.getKeyIndex(); if (isTableCellEditor()) { comboBoxModel.setReadyToFinish(true); } // This is an ArrayOutOfBounds exception "fix". When user presses SPACE + ENTER sometimes we get // an error, because strs is an empty array! if (strs.length > 0) { super.insertString(offs, strs[idx], a); } else { super.insertString(offs, "", a); } // else // We have to filter after the user selects an item with the mouse. // WARNING: here we rely on the FilteredComboBoxModel's setPattern() method to select the // exact match - ie the item that user picked with the mouse. filterTheModel(); if (itemPicked) { pickedItem = comboBox.getSelectedItem(); Object tmp = comboBoxModel.getKeyOfTheSelectedItem(); if (tmp instanceof String) { pickedKey = tmp.toString(); } else { pickedKey = tmp; } // else } comboBox.putClientProperty("item-picked", Boolean.TRUE); comboBoxModel.setPickedItem(pickedItem); comboBoxModel.setPickedKey(pickedKey); return; } else { // otherwise, insert the whole string super.insertString(offs, str, a); Object obj = comboBoxModel.getSelectedItem(); if (obj != null) { if (itemPicked && !(obj instanceof Pair) && !(obj instanceof Object[])) { comboBoxModel.setPickedItem(obj); comboBoxModel.setPickedKey(obj); } } } // else if (finish) { return; } filterTheModel(); } // insertString() method @Override public void remove(int offs, int len) throws BadLocationException { // return immediately when selecting an item if (selecting) { // remove() is called whenever setSelectedItem() or setSelectedIndex() are called. They may be // called during the filtering process, so we do not want to remove while in the middle. return; } if (arrowKeyPressed) { if (isTableCellEditor()) { // if the remove() has been called while user navigates through the combobox list, we do not // filter. when user navigates via arrow keys, remove() is always called first, followed by // the insertString. However, sometimes table steals the event, and causes trouble. // As remove() is called first, here we check if correct value has been selected after user // presses UP/DOWN int currentIndex = comboBox.getSelectedIndex(); if (selectedIndex != currentIndex) { // they are not equal, fix it comboBox.setSelectedIndex(selectedIndex); } } return; } // remove the string from the document super.remove(offs, len); if (finish) { // user pressed ENTER so in the case remove is called we do not filter the model. return; } // finally, do the filter filterTheModel(); } // remove() method /** * Use this method when you need to programmatically pick an item. * @param argItem */ public void pickItem(Object argItem) { Object obj = comboBoxModel.getKeyOfAnItem(argItem); if ((argItem == null) && (obj == null)) { return; } pickedItem = argItem; pickedKey = obj.toString(); } // pickItem() method /** * This method calls the setPatter() method, and starts the filtering. * * It also sets the previousItemCount variable to hold the previous number * of filtered items. */ private void filterTheModel() throws BadLocationException { // we have to "guard" the call to comboBoxModel.setPattern() with selecting set to true, then false selecting = true; boolean oldValue = comboBoxModel.isReadyToFinish(); comboBoxModel.setReadyToFinish(false); // we must set this to false during the filtering previousItemCount = comboBox.getItemCount(); /// store the number of items before filtering String pattern = getText(0, getLength()); comboBoxModel.setPattern(pattern); clearTextSelection(); fixPopupSize(); comboBoxModel.setReadyToFinish(oldValue); // restore the value selecting = false; selectedIndex = comboBox.getSelectedIndex(); } // filterTheModel() method /** * Use this method whenever you need to determine if the comboBox is used as * a cell editor or not. * * @return boolean Value indicating whether comboBox is a cell editor (TRUE) * or not (FALSE). */ private boolean isTableCellEditor() { boolean isTableCellEditor = false; Object tmp = comboBox.getClientProperty("JComboBox.isTableCellEditor"); if (tmp != null) { isTableCellEditor = tmp.equals(Boolean.TRUE); } return isTableCellEditor; } // isTableCellEditor() method /** * This method is used internally to fix the popup-menu size. Apparently * JComboBox has a bug and does not calculate the proper height of the * popup. * * The first time popup menu is shown, ComboBoxFilter stores the dimension, * and re-adjusts the width to the original value all the time. Reason for * this is that we do not want to have different widths while user types * something. */ private void fixPopupSize() { if (inPreparation) { return; } int maxRows = comboBox.getMaximumRowCount(); if ((previousItemCount < maxRows) || (comboBox.getItemCount() < maxRows)) { // do this only when we have less than maxRows items, to prevent the flickering. // this is a hack and is actually the easiest solution to the JComboBox's popup resizing problem. if (comboBox.isPopupVisible()) { comboBox.setPopupVisible(false); comboBox.setPopupVisible(true); } } } // fixPopupSize() method /** * If the l&f is system, and OS is Windows, we have to fix the arrow UI of * the combo box, when editing is enabled. This method is responsible for * doing that. */ private void fixComboBoxArrowUI() { String scn = UIManager.getSystemLookAndFeelClassName(); if (System.getProperty("os.name").startsWith("Windows") && UIManager.getLookAndFeel().getClass().getCanonicalName().equals(scn)) { System.err.println("DEBUG: fixing the combo-box's arrow"); comboBox.setUI(ColorArrowUI.createUI(comboBox)); } } // fixComboBoxArrowUI() method private String updateFcbEditor() { Object obj = comboBoxModel.getKeyOfTheSelectedItem(); String txt = null; if (obj != null) { txt = obj.toString(); } if (txt != null) { if (!comboBoxModel.isAnyPatternAllowed() || !comboBoxModel.isMultiSelectionAllowed()) { /* In the case when *any* pattern is allowed, or all we want is to get a * * list of items that match, then we do not update the comboBox editor * * component with the newly selected item's key. */ if (!isTableCellEditor()) { setText(txt); } } } return txt; } // updateFcbEditor() method /** * This method is used internally to insert the ComboBoxFilter's internal KeyAdapter object as * *the first* key listener of the combo box editor component. * Other key listeners will come after. * When ComboBoxFilter is instantiated some key listeners may already be installed in the comboBoxEditor. * This method fixes that. * @param argKeyAdapter */ private void addAsTheFirstKeyListener(KeyAdapter argKeyAdapter) { // get old key listeners KeyListener[] keyListeners = comboBoxEditor.getKeyListeners(); if (keyListeners.length == 0) { // if there are no other key listeners installed, install the internal one and return. comboBoxEditor.addKeyListener(argKeyAdapter); } else { // if there were some key listeners do the following: // remove all for (KeyListener kl : keyListeners) { comboBoxEditor.removeKeyListener(kl); } // now add ComboBoxFilter's KeyAdapter as the first: comboBoxEditor.addKeyListener(argKeyAdapter); // now add all old key listeners for (KeyListener kl : keyListeners) { comboBoxEditor.addKeyListener(kl); } } // else } // makeFirstKeyListener() method /** * * @return */ public boolean isTriggeredByKeyPress() { return triggeredByKeyPress; } // isTriggeredByKeyPress() method /** * * @param argTriggeredByKeyPress */ public void setTriggeredByKeyPress(boolean argTriggeredByKeyPress) { triggeredByKeyPress = argTriggeredByKeyPress; } // setTriggeredByKeyPress() method /** * * @return */ public Object getPickedItem() { return pickedItem; } // getPickedItem() method /** * * @return */ public Object getPickedKey() { return pickedKey; } // getPickedKey() method } // ComboBoxFilter class
package org.pentaho.agilebi.pdi.modeler; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Locale; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.metadata.model.Domain; import org.pentaho.metadata.model.LogicalColumn; import org.pentaho.metadata.model.LogicalModel; import org.pentaho.metadata.model.LogicalTable; import org.pentaho.metadata.model.SqlPhysicalModel; import org.pentaho.metadata.model.olap.OlapCube; import org.pentaho.metadata.model.olap.OlapDimension; import org.pentaho.metadata.model.olap.OlapHierarchy; import org.pentaho.metadata.model.olap.OlapHierarchyLevel; import org.pentaho.metadata.model.olap.OlapMeasure; import org.pentaho.metadata.util.ThinModelConverter; import org.pentaho.ui.xul.XulEventSourceAdapter; import org.pentaho.agilebi.pdi.publish.BiServerConfig; /** * UI model behind the XUL-based interface. This class contains a reference from the context in * which the modeling was initiated through an IModelerSource which also provides model generation. * * @author nbaker * */ @SuppressWarnings("unchecked") public class ModelerWorkspace extends XulEventSourceAdapter{ private AvailableFieldCollection availableFields = new AvailableFieldCollection(); private MainModelNode model; private String sourceName; private IModelerSource source; private String selectedServer; private String selectedVisualization; private String schemaName; private Domain domain; private boolean dirty; // full path to file private String fileName; private boolean modelIsChanging; private boolean autoModel; private boolean isTemporary; private AbstractMetaDataModelNode selectedNode; public ModelerWorkspace() { this.autoModel = true; this.isTemporary = true; setModel(new MainModelNode()); BiServerConfig biServerConfig = BiServerConfig.getInstance(); List<String> serverNames = biServerConfig.getServerNames(); if( serverNames.size() > 0 ) { selectedServer = serverNames.get(0); } } public MainModelNode getModel() { return model; } public void setModel(MainModelNode model) { this.model = model; model.addPropertyChangeListener("children", new PropertyChangeListener() { //$NON-NLS-1$ public void propertyChange(PropertyChangeEvent arg0) { if(!modelIsChanging){ fireModelChanged(); } } }); } public void setFileName(String fileName) { String prevVal = this.fileName; String prevFriendly = getShortFileName(); this.fileName = fileName; firePropertyChange("fileName", prevVal, fileName); //$NON-NLS-1$ firePropertyChange("shortFileName", prevFriendly, getShortFileName()); //$NON-NLS-1$ } public String getShortFileName() { if( fileName == null ) { return null; } int extensionPos = fileName.lastIndexOf('.'); if( extensionPos == -1 ) { extensionPos = fileName.length(); } int sepPos = fileName.replace('\\', '/').lastIndexOf('/'); if( sepPos == -1 ) { sepPos = 0; } else { sepPos++; } return fileName.substring(sepPos, extensionPos); } public String getFileName() { return fileName; } //transMeta.getFilename() public String getSourceName() { return sourceName; } public void setSourceName(String sourceName) { this.sourceName = sourceName; } public String getModelName() { return model.getName(); } public void setModelName(String modelName) { String prevVal = model.getName(); model.setName(modelName); setDirty(true); this.firePropertyChange("modelName", prevVal, modelName); //$NON-NLS-1$ } public boolean isDirty() { return dirty; } public boolean isValid(){ model.validateTree(); return this.model.isValid(); } public List<String> getValidationMessages(){ return model.getValidationMessages(); } public void setDirty(boolean dirty) { boolean prevVal = this.dirty; this.dirty = dirty; this.firePropertyChange("dirty", prevVal, this.dirty); //$NON-NLS-1$ } public AvailableFieldCollection getAvailableFields() { return availableFields; } public void setSelectedVisualization(String aVisualization) { this.selectedVisualization = aVisualization; } public String getSelectedVisualization() { return this.selectedVisualization; } public DimensionMetaData createDimensionFromNode(ColumnBackedNode obj) { DimensionMetaData dimension = new DimensionMetaData(obj.getName()); dimension.setExpanded(true); HierarchyMetaData hierarchy = createHierarchyForParentWithNode(dimension, obj); hierarchy.setParent(dimension); hierarchy.setExpanded(true); dimension.add(hierarchy); return dimension; } public DimensionMetaData createDimensionWithName(String dimName) { DimensionMetaData dimension = new DimensionMetaData(dimName); dimension.setExpanded(true); HierarchyMetaData hierarchy = createHierarchyForParentWithNode(dimension, null); hierarchy.setParent(dimension); hierarchy.setExpanded(true); dimension.add(hierarchy); return dimension; } public void addDimensionFromNode(ColumnBackedNode obj) { addDimension(createDimensionFromNode(obj)); } public void addDimension(DimensionMetaData dim) { boolean prevChangeState = this.modelIsChanging; this.setModelIsChanging(true); this.model.getDimensions().add(dim); this.setModelIsChanging(prevChangeState); } public LevelMetaData createLevelForParentWithNode(HierarchyMetaData parent, ColumnBackedNode obj) { LevelMetaData level = new LevelMetaData(parent, obj.getName()); level.setParent(parent); level.setLogicalColumn(obj.getLogicalColumn()); return level; } public LevelMetaData createLevelForParentWithNode(HierarchyMetaData parent, String name) { LevelMetaData level = new LevelMetaData(parent, name); level.setParent(parent); level.setLogicalColumn(findLogicalColumn(name)); return level; } public HierarchyMetaData createHierarchyForParentWithNode(DimensionMetaData parent, ColumnBackedNode obj) { HierarchyMetaData hier = new HierarchyMetaData(obj.getName()); hier.setParent(parent); hier.setExpanded(true); if(obj != null){ LevelMetaData level = createLevelForParentWithNode(hier, obj); hier.add(level); } return hier; } private void fireFieldsChanged() { firePropertyChange("availableFields", null, this.availableFields); //$NON-NLS-1$ } private void fireModelChanged() { firePropertyChange("model", null, model); //$NON-NLS-1$ setDirty(true); } public MeasureMetaData createMeasureForNode(AvailableField selectedField) { MeasureMetaData meta = new MeasureMetaData(selectedField.getName(), "", selectedField.getDisplayName()); //$NON-NLS-1$ meta.setLogicalColumn(selectedField.getLogicalColumn()); return meta; } public void addMeasure(MeasureMetaData measure) { boolean prevChangeState = isModelChanging(); this.setModelIsChanging(true); this.model.getMeasures().add(measure); this.setModelIsChanging(prevChangeState); } public LogicalColumn findLogicalColumn(String id) { LogicalColumn col = null; for(LogicalColumn c : domain.getLogicalModels().get(0).getLogicalTables().get(0).getLogicalColumns()){ if(c.getName(Locale.getDefault().toString()).equals(id)){ col = c; break; } } return col; } public void setModelSource(IModelerSource source) { this.source = source; } public IModelerSource getModelSource() { return source; } public void setFields(List<MeasureMetaData> fields) { this.model.getMeasures().clear(); this.model.getMeasures().addAll(fields); } public void refresh() throws ModelerException { if(source == null) { return; } Domain newDomain = source.generateDomain(); // Add in new logicalColumns for(LogicalColumn lc : newDomain.getLogicalModels().get(0).getLogicalTables().get(0).getLogicalColumns()){ boolean exists = false; inner: for(AvailableField fmd : this.availableFields){ if(fmd.getLogicalColumn().getId().equals(lc.getId())){ fmd.setLogicalColumn(lc); exists = true; break inner; } } if(!exists){ AvailableField fm = new AvailableField(); fm.setLogicalColumn(lc); fm.setName(lc.getName(Locale.getDefault().toString())); fm.setDisplayName(lc.getName(Locale.getDefault().toString())); availableFields.add(fm); Collections.sort(availableFields, new Comparator<AvailableField>(){ public int compare(AvailableField arg0, AvailableField arg1) { return arg0.getLogicalColumn().getId().compareTo(arg1.getLogicalColumn().getId()); } }); } } // Remove logicalColumns that no longer exist. List<AvailableField> toRemove = new ArrayList<AvailableField>(); for(AvailableField fm : availableFields){ boolean exists = false; LogicalColumn fmlc = fm.getLogicalColumn(); inner: for(LogicalColumn lc : newDomain.getLogicalModels().get(0).getLogicalTables().get(0).getLogicalColumns()){ if(lc.getId().equals(fmlc.getId())){ exists = true; break inner; } } if(!exists){ toRemove.add(fm); } } availableFields.removeAll(toRemove); sortFields(); fireFieldsChanged(); for(MeasureMetaData measure : model.getMeasures()) { boolean found = false; if(measure.getLogicalColumn() != null){ for(AvailableField fm : availableFields){ if(fm.getLogicalColumn().getId().equals(measure.getLogicalColumn().getId())){ found = true; } } } if(!found){ measure.setLogicalColumn(null); } } for(DimensionMetaData dm : model.getDimensions()) { for(HierarchyMetaData hm : dm){ for(LevelMetaData lm : hm){ boolean found = false; if(lm.getLogicalColumn() != null){ inner: for(AvailableField fm : availableFields){ if(fm.getLogicalColumn().getId().equals(lm.getLogicalColumn().getId())){ found = true; break inner; } } } if(!found){ lm.setLogicalColumn(null); } } } } // replace the domain with the new domain, which // makes sure the physical and logical columns are accurate domain = newDomain; model.validateTree(); } public String getDatabaseName() { return source.getDatabaseName(); } public String getSchemaName() { return schemaName; } public void setSchemaName(String schemaName) { this.schemaName = schemaName; } private void sortFields() { Collections.sort(availableFields, new Comparator() { public int compare(Object o1, Object o2) { if( o1 == null && o2 == null ) { return 0; } else if( o1 == null ) { return -1; } else if( o2 == null ) { return 1; } String name1 = ((AvailableField) o1).getDisplayName(); String name2 = ((AvailableField) o2).getDisplayName(); if( name1 == null && name2 == null ) { return 0; } else if( name1 == null ) { return -1; } else if( name2 == null ) { return 1; } return name1.compareToIgnoreCase(name2); } }); } public void setDomain(Domain d) { this.domain = d; this.model.getDimensions().clear(); this.model.getMeasures().clear(); this.availableFields.clear(); LogicalTable table = domain.getLogicalModels().get(0).getLogicalTables().get(0); for(LogicalColumn c : table.getLogicalColumns()){ AvailableField fm = new AvailableField(); fm.setLogicalColumn(c); fm.setName(c.getPhysicalColumn().getName(Locale.getDefault().toString())); fm.setDisplayName(c.getName(Locale.getDefault().toString())); fm.setAggTypeDesc(c.getAggregationType().toString()); availableFields.add(fm); } sortFields(); firePropertyChange("availableFields", null, getAvailableFields()); //$NON-NLS-1$ LogicalModel lModel = domain.getLogicalModels().get(0); if(lModel.getCategories().size() > 0){ setModelName(lModel.getCategories().get(0).getId()); } List<OlapDimension> theDimensions = (List) lModel.getProperty("olap_dimensions"); //$NON-NLS-1$ if(theDimensions != null) { Iterator<OlapDimension> theDimensionItr = theDimensions.iterator(); while(theDimensionItr.hasNext()) { OlapDimension theDimension = theDimensionItr.next(); DimensionMetaData theDimensionMD = new DimensionMetaData(theDimension.getName()); List<OlapHierarchy> theHierarchies = (List) theDimension.getHierarchies(); Iterator<OlapHierarchy> theHierarchiesItr = theHierarchies.iterator(); while(theHierarchiesItr.hasNext()) { OlapHierarchy theHierarchy = theHierarchiesItr.next(); HierarchyMetaData theHierarchyMD = new HierarchyMetaData(theHierarchy.getName()); List<OlapHierarchyLevel> theLevels = theHierarchy.getHierarchyLevels(); Iterator<OlapHierarchyLevel> theLevelsItr = theLevels.iterator(); while(theLevelsItr.hasNext()) { OlapHierarchyLevel theLevel = theLevelsItr.next(); LevelMetaData theLevelMD = new LevelMetaData(theHierarchyMD, theLevel.getName()); theLevelMD.setParent(theHierarchyMD); theLevelMD.setLogicalColumn(theLevel.getReferenceColumn()); theHierarchyMD.add(theLevelMD); } theHierarchyMD.setParent(theDimensionMD); theDimensionMD.add(theHierarchyMD); } this.model.getDimensions().add(theDimensionMD); } } List<OlapCube> theCubes = (List) lModel.getProperty("olap_cubes"); //$NON-NLS-1$ if(theCubes != null) { Iterator<OlapCube> theCubeItr = theCubes.iterator(); while(theCubeItr.hasNext()) { OlapCube theCube = theCubeItr.next(); List<OlapMeasure> theMeasures = theCube.getOlapMeasures(); Iterator<OlapMeasure> theMeasuresItr = theMeasures.iterator(); while(theMeasuresItr.hasNext()) { OlapMeasure theMeasure = theMeasuresItr.next(); MeasureMetaData theMeasureMD = new MeasureMetaData(); theMeasureMD.setName(theMeasure.getLogicalColumn().getName(Locale.getDefault().toString())); theMeasureMD.setFormat((String)theMeasure.getLogicalColumn().getProperty("mask")); //$NON-NLS-1$ theMeasureMD.setAggTypeDesc(theMeasure.getLogicalColumn().getAggregationType().toString()); theMeasureMD.setLogicalColumn(theMeasure.getLogicalColumn()); this.model.getMeasures().add(theMeasureMD); } } } model.validateTree(); } public void resolveConnectionFromDomain() { // set up the datasource if( domain != null && source != null ) { SqlPhysicalModel physicalModel = (SqlPhysicalModel)domain.getPhysicalModels().get(0); DatabaseMeta databaseMeta = ThinModelConverter.convertToLegacy(physicalModel.getId(), physicalModel.getDatasource()); source.setDatabaseMeta(databaseMeta); } } public Domain getDomain() { return updateDomain(); } private Domain updateDomain() { // TODO: update domain with changes return domain; } public void setModelIsChanging(boolean changing){ setModelIsChanging(changing, true); } public void setModelIsChanging(boolean changing, boolean fireChanged){ this.modelIsChanging = changing; if(!changing && fireChanged){ fireFieldsChanged(); model.validateTree(); fireModelChanged(); } model.setSupressEvents(changing); } public boolean isModelChanging(){ return modelIsChanging; } public boolean isAutoModel() { return this.autoModel; } public void setAutoModel(boolean isAutomodel) { this.autoModel = isAutomodel; } public void setTemporary(boolean isTempoarary) { this.isTemporary = isTempoarary; } public boolean isTemporary() { return this.isTemporary; } public AbstractMetaDataModelNode getSelectedNode(){ return selectedNode; } public void setSelectedNode(AbstractMetaDataModelNode node){ AbstractMetaDataModelNode prevVal = this.selectedNode; this.selectedNode = node; firePropertyChange("selectedNode", prevVal, node); //$NON-NLS-1$ } }
package com.ciandt.techgallery.ofy; import com.googlecode.objectify.Objectify; import com.googlecode.objectify.ObjectifyFactory; import com.googlecode.objectify.ObjectifyService; import com.ciandt.techgallery.persistence.model.Endorsement; import com.ciandt.techgallery.persistence.model.Skill; import com.ciandt.techgallery.persistence.model.TechGalleryUser; import com.ciandt.techgallery.persistence.model.Technology; import com.ciandt.techgallery.persistence.model.TechnologyComment; import com.ciandt.techgallery.persistence.model.TechnologyRecommendation; import com.ciandt.techgallery.sample.persistence.model.Card; import com.ciandt.techgallery.sample.persistence.model.RecommendationSample; import com.ciandt.techgallery.sample.persistence.model.Sample; import com.ciandt.techgallery.sample.persistence.model.TechnologySample; import com.ciandt.techgallery.sample.persistence.model.UserGroup; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; /** * Service class for Objectify settings. * * @author felipers * */ public class OfyService implements ServletContextListener { /** Define all entities first. */ static { ObjectifyService.register(Technology.class); ObjectifyService.register(Endorsement.class); ObjectifyService.register(TechGalleryUser.class); ObjectifyService.register(Skill.class); // @TODO improve how to separate the samples' registers from the production's registers // Samples of registers ObjectifyService.register(UserGroup.class); ObjectifyService.register(Card.class); ObjectifyService.register(TechnologySample.class); ObjectifyService.register(RecommendationSample.class); ObjectifyService.register(Sample.class); ObjectifyService.register(TechnologyComment.class); ObjectifyService.register(TechnologyRecommendation.class); } /** * Method that returns the objectify service reference. * * @return Objectify. */ public static Objectify ofy() { return ObjectifyService.ofy(); // prior to v.4.0 use .begin() , // since v.4.0 use ObjectifyService.ofy(); } /** * Method that returns the objectify factory reference. * * @return Objectify. */ public static ObjectifyFactory factory() { return ObjectifyService.factory(); } /** * Context destroyed for http servlet. */ @Override public void contextDestroyed(ServletContextEvent arg0) { // TODO Auto-generated method stub } /** * Context initialized for http servlet. */ @Override public void contextInitialized(ServletContextEvent arg0) { // Register entities = done with static block } }
package org.pentaho.di.trans.steps.excelinput; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.TimeZone; import org.apache.commons.vfs.FileObject; import org.pentaho.di.core.Const; import org.pentaho.di.core.ResultFile; import org.pentaho.di.core.RowSet; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleFileException; import org.pentaho.di.core.fileinput.FileInputList; import org.pentaho.di.core.playlist.FilePlayListAll; import org.pentaho.di.core.playlist.FilePlayListReplay; import org.pentaho.di.core.row.RowMeta; import org.pentaho.di.core.row.ValueMeta; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.spreadsheet.KCell; import org.pentaho.di.core.spreadsheet.KCellType; import org.pentaho.di.core.spreadsheet.KSheet; import org.pentaho.di.core.vfs.KettleVFS; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; import org.pentaho.di.trans.step.errorhandling.CompositeFileErrorHandler; import org.pentaho.di.trans.step.errorhandling.FileErrorHandler; import org.pentaho.di.trans.step.errorhandling.FileErrorHandlerContentLineNumber; import org.pentaho.di.trans.step.errorhandling.FileErrorHandlerMissingFiles; /** * This class reads data from one or more Microsoft Excel files. * * @author Matt * @author timh * @since 19-NOV-2003 */ public class ExcelInput extends BaseStep implements StepInterface { private static Class<?> PKG = ExcelInputMeta.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$ private ExcelInputMeta meta; private ExcelInputData data; public ExcelInput(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { super(stepMeta, stepDataInterface, copyNr, transMeta, trans); } /** * Build an empty row based on the meta-data... * * @return */ private Object[] fillRow(int startcolumn, ExcelInputRow excelInputRow) throws KettleException { Object[] r = new Object[data.outputRowMeta.size()]; // Keep track whether or not we handled an error for this line yet. boolean errorHandled = false; // Set values in the row... KCell cell = null; for (int i = startcolumn; i < excelInputRow.cells.length && i - startcolumn < meta.getField().length; i++) { cell = excelInputRow.cells[i]; int rowcolumn = i - startcolumn; ValueMetaInterface targetMeta = data.outputRowMeta.getValueMeta(rowcolumn); ValueMetaInterface sourceMeta = null; try { checkType(cell, targetMeta); } catch (KettleException ex) { if (!meta.isErrorIgnored()) { ex = new KettleCellValueException(ex, this.data.sheetnr, this.data.rownr, i, ""); throw ex; } if(log.isBasic()) logBasic(BaseMessages.getString(PKG, "ExcelInput.Log.WarningProcessingExcelFile",""+targetMeta,""+data.filename, ex.getMessage())); if (!errorHandled) { data.errorHandler.handleLineError(excelInputRow.rownr, excelInputRow.sheetName); errorHandled = true; } if (meta.isErrorLineSkipped()) { return null; } } KCellType cellType = cell.getType(); if (KCellType.BOOLEAN == cellType || KCellType.BOOLEAN_FORMULA==cellType) { r[rowcolumn] = (Boolean)cell.getValue(); sourceMeta = data.valueMetaBoolean; } else { if (KCellType.DATE.equals(cellType) || KCellType.DATE_FORMULA.equals(cellType) ) { Date date = (Date) cell.getValue(); long time = date.getTime(); int offset = TimeZone.getDefault().getOffset(time); r[rowcolumn] = new Date(time - offset); sourceMeta = data.valueMetaDate; } else { if (KCellType.LABEL==cellType || KCellType.STRING_FORMULA==cellType) { String string = (String) cell.getValue(); switch (meta.getField()[rowcolumn].getTrimType()) { case ExcelInputMeta.TYPE_TRIM_LEFT: string = Const.ltrim(string); break; case ExcelInputMeta.TYPE_TRIM_RIGHT: string = Const.rtrim(string); break; case ExcelInputMeta.TYPE_TRIM_BOTH: string = Const.trim(string); break; default: break; } r[rowcolumn] = string; sourceMeta = data.valueMetaString; } else { if (KCellType.NUMBER == cellType || KCellType.NUMBER_FORMULA == cellType) { r[rowcolumn] = (Double) cell.getValue(); sourceMeta = data.valueMetaNumber; } else { if (log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "ExcelInput.Log.UnknownType", cell.getType().toString(),cell.getContents())); r[rowcolumn] = null; } } } } ExcelInputField field = meta.getField()[rowcolumn]; // Change to the appropriate type if needed... try { // Null stays null folks. if (sourceMeta!=null && sourceMeta.getType() != targetMeta.getType() && r[rowcolumn]!=null) { ValueMetaInterface sourceMetaCopy = sourceMeta.clone(); sourceMetaCopy.setConversionMask(field.getFormat()); sourceMetaCopy.setGroupingSymbol(field.getGroupSymbol()); sourceMetaCopy.setDecimalSymbol(field.getDecimalSymbol()); sourceMetaCopy.setCurrencySymbol(field.getCurrencySymbol()); switch (targetMeta.getType()) { // Use case: we find a numeric value: convert it using the supplied format to the desired data type... case ValueMetaInterface.TYPE_NUMBER: case ValueMetaInterface.TYPE_INTEGER: switch (field.getType()) { case ValueMetaInterface.TYPE_DATE: // number to string conversion (20070522.00 --> "20070522") ValueMetaInterface valueMetaNumber = new ValueMeta("num", ValueMetaInterface.TYPE_NUMBER); valueMetaNumber.setConversionMask(" Object string = sourceMetaCopy.convertData(valueMetaNumber, r[rowcolumn]); // String to date with mask... r[rowcolumn] = targetMeta.convertData(sourceMetaCopy, string); break; default: r[rowcolumn] = targetMeta.convertData(sourceMetaCopy, r[rowcolumn]); break; } break; default: r[rowcolumn] = targetMeta.convertData(sourceMetaCopy, r[rowcolumn]); } } } catch (KettleException ex) { if (!meta.isErrorIgnored()) { ex = new KettleCellValueException(ex, this.data.sheetnr, cell.getRow(), i, field.getName()); throw ex; } if(log.isBasic()) logBasic(BaseMessages.getString(PKG, "ExcelInput.Log.WarningProcessingExcelFile",""+targetMeta,""+data.filename, ex.toString())); if (!errorHandled) // check if we didn't log an error already for this one. { data.errorHandler.handleLineError(excelInputRow.rownr, excelInputRow.sheetName); errorHandled=true; } if (meta.isErrorLineSkipped()) { return null; } else { r[rowcolumn] = null; } } } int rowIndex = meta.getField().length; // Do we need to include the filename? if (!Const.isEmpty(meta.getFileField())) { r[rowIndex] = data.filename; rowIndex++; } // Do we need to include the sheetname? if (!Const.isEmpty(meta.getSheetField())) { r[rowIndex] = excelInputRow.sheetName; rowIndex++; } // Do we need to include the sheet rownumber? if (!Const.isEmpty(meta.getSheetRowNumberField())) { r[rowIndex] = new Long(data.rownr); rowIndex++; } // Do we need to include the rownumber? if (!Const.isEmpty(meta.getRowNumberField())) { r[rowIndex] = new Long(getLinesWritten() + 1); rowIndex++; } // Possibly add short filename... if (meta.getShortFileNameField()!=null && meta.getShortFileNameField().length()>0) { r[rowIndex] = data.shortFilename; rowIndex++; } // Add Extension if (meta.getExtensionField()!=null && meta.getExtensionField().length()>0) { r[rowIndex] = data.extension; rowIndex++; } // add path if (meta.getPathField()!=null && meta.getPathField().length()>0) { r[rowIndex] = data.path; rowIndex++; } // Add Size if (meta.getSizeField()!=null && meta.getSizeField().length()>0) { r[rowIndex] = new Long(data.size); rowIndex++; } // add Hidden if (meta.isHiddenField()!=null && meta.isHiddenField().length()>0) { r[rowIndex] = new Boolean(data.hidden); rowIndex++; } // Add modification date if (meta.getLastModificationDateField()!=null && meta.getLastModificationDateField().length()>0) { r[rowIndex] = data.lastModificationDateTime; rowIndex++; } // Add Uri if (meta.getUriField()!=null && meta.getUriField().length()>0) { r[rowIndex] = data.uriName; rowIndex++; } // Add RootUri if (meta.getRootUriField()!=null && meta.getRootUriField().length()>0) { r[rowIndex] = data.rootUriName; rowIndex++; } return r; } private void checkType(KCell cell, ValueMetaInterface v) throws KettleException { if (!meta.isStrictTypes()) return; switch(cell.getType()) { case BOOLEAN: { if (!(v.getType() == ValueMetaInterface.TYPE_STRING || v.getType() == ValueMetaInterface.TYPE_NONE || v.getType() == ValueMetaInterface.TYPE_BOOLEAN)) throw new KettleException(BaseMessages.getString(PKG, "ExcelInput.Exception.InvalidTypeBoolean",v.getTypeDesc())); } break; case DATE: { if (!(v.getType() == ValueMetaInterface.TYPE_STRING || v.getType() == ValueMetaInterface.TYPE_NONE || v.getType() == ValueMetaInterface.TYPE_DATE)) throw new KettleException(BaseMessages.getString(PKG, "ExcelInput.Exception.InvalidTypeDate", cell.getContents(),v.getTypeDesc())); } break; case LABEL: { if (v.getType() == ValueMetaInterface.TYPE_BOOLEAN || v.getType() == ValueMetaInterface.TYPE_DATE || v.getType() == ValueMetaInterface.TYPE_INTEGER || v.getType() == ValueMetaInterface.TYPE_NUMBER) throw new KettleException(BaseMessages.getString(PKG, "ExcelInput.Exception.InvalidTypeLabel", cell.getContents(),v.getTypeDesc())); } break; case EMPTY: { } break; case NUMBER: { if (!(v.getType() == ValueMetaInterface.TYPE_STRING || v.getType() == ValueMetaInterface.TYPE_NONE || v.getType() == ValueMetaInterface.TYPE_INTEGER || v.getType() == ValueMetaInterface.TYPE_BIGNUMBER || v.getType() == ValueMetaInterface.TYPE_NUMBER)) throw new KettleException(BaseMessages.getString(PKG, "ExcelInput.Exception.InvalidTypeNumber", cell.getContents(),v.getTypeDesc())); } break; default: throw new KettleException(BaseMessages.getString(PKG, "ExcelInput.Exception.UnsupportedType", cell.getType().getDescription(), cell.getContents())); } } public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta = (ExcelInputMeta) smi; data = (ExcelInputData) sdi; if (first) { first = false; data.outputRowMeta = new RowMeta(); // start from scratch! meta.getFields(data.outputRowMeta, getStepname(), null, null, this); if (meta.isAcceptingFilenames()) { // Read the files from the specified input stream... data.files.getFiles().clear(); int idx = -1; RowSet rowSet = findInputRowSet(meta.getAcceptingStepName()); Object[] fileRow = getRowFrom(rowSet); while (fileRow!=null) { if (idx<0) { idx = rowSet.getRowMeta().indexOfValue(meta.getAcceptingField()); if (idx<0) { logError(BaseMessages.getString(PKG, "ExcelInput.Error.FilenameFieldNotFound",""+meta.getAcceptingField())); setErrors(1); stopAll(); return false; } } String fileValue = rowSet.getRowMeta().getString(fileRow, idx); try { data.files.addFile(KettleVFS.getFileObject(fileValue, getTransMeta())); } catch(KettleFileException e) { throw new KettleException(BaseMessages.getString(PKG, "ExcelInput.Exception.CanNotCreateFileObject",fileValue), e); } // Grab another row fileRow = getRowFrom(rowSet); } } handleMissingFiles(); } // See if we're not done processing... // We are done processing if the filenr >= number of files. if (data.filenr >= data.files.nrOfFiles()) { if (log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "ExcelInput.Log.NoMoreFiles",""+data.filenr)); setOutputDone(); // signal end to receiver(s) return false; // end of data or error. } // also handle the case if we have a startRow == 0 and no headers and a row limit > 0 // in this case we have to stop a row "earlier", since we start a row number 0 !!! if ((meta.getRowLimit() > 0 && data.rownr > meta.getRowLimit()) || (meta.getRowLimit() > 0 && data.startRow[data.sheetnr] == 0 && data.rownr > meta.getRowLimit()-1)) { // The close of the openFile is in dispose() if (log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "ExcelInput.Log.RowLimitReached",""+meta.getRowLimit())); setOutputDone(); // signal end to receiver(s) return false; // end of data or error. } Object[] r = getRowFromWorkbooks(); if (r != null) { incrementLinesInput(); // OK, see if we need to repeat values. if (data.previousRow != null) { for (int i = 0; i < meta.getField().length; i++) { ValueMetaInterface valueMeta = data.outputRowMeta.getValueMeta(i); Object valueData = r[i]; if (valueMeta.isNull(valueData) && meta.getField()[i].isRepeated()) { // Take the value from the previous row. r[i] = data.previousRow[i]; } } } // Remember this row for the next time around! data.previousRow = data.outputRowMeta.cloneRow(r); // Send out the good news: we found a row of data! putRow(data.outputRowMeta, r); return true; } else { // This row is ignored / eaten // We continue though. return true; } } private void handleMissingFiles() throws KettleException { List<FileObject> nonExistantFiles = data.files.getNonExistantFiles(); if (nonExistantFiles.size() != 0) { String message = FileInputList.getRequiredFilesDescription(nonExistantFiles); if(log.isBasic()) logBasic(BaseMessages.getString(PKG, "ExcelInput.Log.RequiredFilesTitle"), BaseMessages.getString(PKG, "ExcelInput.Warning.MissingFiles", message)); if (meta.isErrorIgnored()) for (FileObject fileObject : nonExistantFiles) { data.errorHandler.handleNonExistantFile( fileObject ); } else throw new KettleException(BaseMessages.getString(PKG, "ExcelInput.Exception.MissingRequiredFiles", message)); } List<FileObject> nonAccessibleFiles = data.files.getNonAccessibleFiles(); if (nonAccessibleFiles.size() != 0) { String message = FileInputList.getRequiredFilesDescription(nonAccessibleFiles); if(log.isBasic()) logBasic(BaseMessages.getString(PKG, "ExcelInput.Log.RequiredFilesTitle"), BaseMessages.getString(PKG, "ExcelInput.Log.RequiredFilesMsgNotAccessible",message)); if (meta.isErrorIgnored()) for (FileObject fileObject : nonAccessibleFiles) { data.errorHandler.handleNonAccessibleFile(fileObject); } else throw new KettleException(BaseMessages.getString(PKG, "ExcelInput.Exception.RequiredFilesNotAccessible",message)); } } public Object[] getRowFromWorkbooks() { // This procedure outputs a single Excel data row on the destination // rowsets... Object[] retval = null; try { // First, see if a file has been opened? if (data.workbook == null) { // Open a new openFile.. data.file = data.files.getFile(data.filenr); data.filename = KettleVFS.getFilename( data.file ); // Add additional fields? if (meta.getShortFileNameField()!=null && meta.getShortFileNameField().length()>0) { data.shortFilename = data.file.getName().getBaseName(); } if (meta.getPathField()!=null && meta.getPathField().length()>0) { data.path = KettleVFS.getFilename(data.file.getParent()); } if (meta.isHiddenField()!=null && meta.isHiddenField().length()>0) { data.hidden = data.file.isHidden(); } if (meta.getExtensionField()!=null && meta.getExtensionField().length()>0) { data.extension = data.file.getName().getExtension(); } if (meta.getLastModificationDateField()!=null && meta.getLastModificationDateField().length()>0) { data.lastModificationDateTime = new Date(data.file.getContent().getLastModifiedTime()); } if (meta.getUriField()!=null && meta.getUriField().length()>0) { data.uriName = data.file.getName().getURI(); } if (meta.getRootUriField()!=null && meta.getRootUriField().length()>0) { data.rootUriName = data.file.getName().getRootURI(); } if (meta.getSizeField()!=null && meta.getSizeField().length()>0) { data.size = new Long( data.file.getContent().getSize()); } if(meta.isAddResultFile()) { ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, data.file, getTransMeta().getName(), toString()); resultFile.setComment(BaseMessages.getString(PKG, "ExcelInput.Log.FileReadByStep")); addResultFile(resultFile); } if (log.isDetailed()) logDetailed(BaseMessages.getString(PKG, "ExcelInput.Log.OpeningFile",""+data.filenr + " : " + data.filename)); data.workbook = WorkbookFactory.getWorkbook(meta.getSpreadSheetType(), data.filename, meta.getEncoding()); data.errorHandler.handleFile(data.file); // Start at the first sheet again... data.sheetnr = 0; // See if we have sheet names to retrieve, otherwise we'll have to get all sheets... if (meta.readAllSheets()) { data.sheetNames = data.workbook.getSheetNames(); data.startColumn = new int[data.sheetNames.length]; data.startRow = new int[data.sheetNames.length]; for (int i=0;i<data.sheetNames.length;i++) { data.startColumn[i] = data.defaultStartColumn; data.startRow[i] = data.defaultStartRow; } } } boolean nextsheet = false; // What sheet were we handling? if (log.isDebug()) logDetailed(BaseMessages.getString(PKG, "ExcelInput.Log.GetSheet",""+data.filenr + "." + data.sheetnr)); String sheetName = data.sheetNames[data.sheetnr]; KSheet sheet = data.workbook.getSheet(sheetName); if (sheet != null) { // at what row do we continue reading? if (data.rownr < 0) { data.rownr = data.startRow[data.sheetnr]; // Add an extra row if we have a header row to skip... if (meta.startsWithHeader()) { data.rownr++; } } // Start at the specified column data.colnr = data.startColumn[data.sheetnr]; // Build a new row and fill in the data from the sheet... try { KCell line[] = sheet.getRow(data.rownr); // Already increase cursor 1 row int lineNr = ++data.rownr; // Excel starts counting at 0 if (!data.filePlayList.isProcessingNeeded(data.file, lineNr, sheetName)) { retval = null; // placeholder, was already null } else { if (log.isRowLevel()) logRowlevel(BaseMessages.getString(PKG, "ExcelInput.Log.GetLine",""+lineNr,data.filenr + "." + data.sheetnr)); if (log.isRowLevel()) logRowlevel(BaseMessages.getString(PKG, "ExcelInput.Log.ReadLineWith",""+line.length)); ExcelInputRow excelInputRow = new ExcelInputRow(sheet.getName(), lineNr, line); Object[] r = fillRow(data.colnr, excelInputRow); if (log.isRowLevel()) logRowlevel(BaseMessages.getString(PKG, "ExcelInput.Log.ConvertedLinToRow",""+lineNr,data.outputRowMeta.getString(r))); boolean isEmpty = isLineEmpty(line); if (!isEmpty || !meta.ignoreEmptyRows()) { // Put the row retval = r; } else { if (data.rownr>sheet.getRows()) { nextsheet=true; } } if (isEmpty && meta.stopOnEmpty()) { nextsheet = true; } } } catch (ArrayIndexOutOfBoundsException e) { if (log.isRowLevel()) logRowlevel(BaseMessages.getString(PKG, "ExcelInput.Log.OutOfIndex")); // We tried to read below the last line in the sheet. // Go to the next sheet... nextsheet = true; } } else { nextsheet = true; } if (nextsheet) { // Go to the next sheet data.sheetnr++; // Reset the start-row: data.rownr = -1; // no previous row yet, don't take it from the previous sheet! // (that whould be plain wrong!) data.previousRow = null; // Perhaps it was the last sheet? if (data.sheetnr >= data.sheetNames.length) { jumpToNextFile(); } } } catch (Exception e) { logError(BaseMessages.getString(PKG, "ExcelInput.Error.ProcessRowFromExcel",data.filename+"", e.toString()), e); setErrors(1); stopAll(); return null; } return retval; } private boolean isLineEmpty(KCell[] line) { if (line.length == 0) return true; boolean isEmpty = true; for (int i=0;i<line.length && isEmpty;i++) { if ( line[i]!=null && !Const.isEmpty(line[i].getContents()) ) isEmpty=false; } return isEmpty; } private void jumpToNextFile() throws KettleException { data.sheetnr = 0; // Reset the start-row: data.rownr = -1; // no previous row yet, don't take it from the previous sheet! (that // whould be plain wrong!) data.previousRow = null; // Close the openFile! data.workbook.close(); data.workbook = null; // marker to open again. data.errorHandler.close(); // advance to the next file! data.filenr++; } private void initErrorHandling() { List<FileErrorHandler> errorHandlers = new ArrayList<FileErrorHandler>(2); if (meta.getLineNumberFilesDestinationDirectory() != null) errorHandlers.add(new FileErrorHandlerContentLineNumber(getTrans().getCurrentDate(), environmentSubstitute(meta.getLineNumberFilesDestinationDirectory()), meta.getLineNumberFilesExtension(), "Latin1", this)); if (meta.getErrorFilesDestinationDirectory() != null) errorHandlers.add(new FileErrorHandlerMissingFiles(getTrans().getCurrentDate(), environmentSubstitute(meta.getErrorFilesDestinationDirectory()), meta.getErrorFilesExtension(), "Latin1", this)); data.errorHandler = new CompositeFileErrorHandler(errorHandlers); } private void initReplayFactory() { Date replayDate = getTrans().getReplayDate(); if (replayDate == null) data.filePlayList = FilePlayListAll.INSTANCE; else data.filePlayList = new FilePlayListReplay(replayDate, environmentSubstitute(meta.getLineNumberFilesDestinationDirectory()), meta.getLineNumberFilesExtension(), environmentSubstitute(meta.getErrorFilesDestinationDirectory()), meta .getErrorFilesExtension(), "Latin1"); } public boolean init(StepMetaInterface smi, StepDataInterface sdi) { meta = (ExcelInputMeta) smi; data = (ExcelInputData) sdi; if (super.init(smi, sdi)) { initErrorHandling(); initReplayFactory(); data.files = meta.getFileList(this); if (data.files.nrOfFiles() == 0 && data.files.nrOfMissingFiles() == 0 && !meta.isAcceptingFilenames()) { logError(BaseMessages.getString(PKG, "ExcelInput.Error.NoFileSpecified")); return false; } if (meta.getEmptyFields().size() > 0) { // Determine the maximum filename length... data.maxfilelength = -1; for (FileObject file : data.files.getFiles()) { String name = KettleVFS.getFilename(file); if (name.length() > data.maxfilelength) data.maxfilelength = name.length(); } // Determine the maximum sheet name length... data.maxsheetlength = -1; if (!meta.readAllSheets()) { data.sheetNames = new String[meta.getSheetName().length]; data.startColumn = new int[meta.getSheetName().length]; data.startRow = new int[meta.getSheetName().length]; for (int i = 0; i < meta.getSheetName().length; i++) { data.sheetNames[i] = meta.getSheetName()[i]; data.startColumn[i] = meta.getStartColumn()[i]; data.startRow[i] = meta.getStartRow()[i]; if (meta.getSheetName()[i].length() > data.maxsheetlength) { data.maxsheetlength = meta.getSheetName()[i].length(); } } } else { // Allocated at open file time: we want ALL sheets. if (meta.getStartRow().length==1) { data.defaultStartRow = meta.getStartRow()[0]; } else { data.defaultStartRow = 0; } if (meta.getStartColumn().length==1) { data.defaultStartColumn = meta.getStartColumn()[0]; } else { data.defaultStartColumn = 0; } } return true; } else { logError(BaseMessages.getString(PKG, "ExcelInput.Error.NotInputFieldsDefined")); } } return false; } public void dispose(StepMetaInterface smi, StepDataInterface sdi) { meta = (ExcelInputMeta) smi; data = (ExcelInputData) sdi; if (data.workbook != null) data.workbook.close(); if(data.file!=null) { try{ data.file.close(); }catch (Exception e){} } try { data.errorHandler.close(); } catch (KettleException e) { if (log.isDebug()) { logDebug(BaseMessages.getString(PKG, "ExcelInput.Error.CouldNotCloseErrorHandler",e.toString())); logDebug(Const.getStackTracker(e)); } } super.dispose(smi, sdi); } }
package org.uct.cs.simplify.simplifier; import org.uct.cs.simplify.util.OSDetect; import org.uct.cs.simplify.util.TempFileManager; import java.io.*; public class SimplifierWrapper { private static final String PATH_TO_EXECUTABLE = "./simplifier/" + (OSDetect.isWindows ? "tridecimator_win.exe" : "tridecimator_unix"); public static File simplify(File input, long numFaces, boolean preserveBoundary) throws IOException, InterruptedException { File tt = TempFileManager.provide("simp", ".ply"); System.out.printf("Simplifying %s to %s...%n", input.getPath(), tt.getPath()); Runtime r = Runtime.getRuntime(); String flags = " -P"; if (preserveBoundary) flags += " -By"; Process proc = r.exec( String.format( "%s %s %s %d" + flags, PATH_TO_EXECUTABLE, input.getAbsolutePath(), tt.getAbsolutePath(), numFaces ) ); StreamGobbler stdOutGobble = new StreamGobbler(proc.getInputStream()); StreamGobbler errorGobble = new StreamGobbler(proc.getErrorStream()); stdOutGobble.run(); errorGobble.run(); int code = proc.waitFor(); stdOutGobble.join(); errorGobble.join(); if (code != 0) { throw new UnknownError("Simplify failed! : " + stdOutGobble + errorGobble); } return tt; } private static class StreamGobbler extends Thread { private final StringBuilder sb; private final InputStream stream; public StreamGobbler(InputStream in) { this.sb = new StringBuilder(1000); this.stream = in; } public void run() { try { InputStreamReader reader = new InputStreamReader(this.stream); BufferedReader br = new BufferedReader(reader); String line ; while ((line = br.readLine()) != null) { this.sb.append(line); this.sb.append('\n'); } } catch (IOException ioe) { ioe.printStackTrace(); } } public String toString() { return this.sb.toString(); } } }
// This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc1073.robot16.commands; import edu.wpi.first.wpilibj.command.Command; import org.usfirst.frc1073.robot16.Robot; public class LowerCheval extends Command { double chevalAngle = 20.0; // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_DECLARATIONS // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_DECLARATIONS // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR public LowerCheval() { // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_SETTING // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_SETTING // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES requires(Robot.defense); requires(Robot.driveTrain); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES } // Called just before this Command runs the first time protected void initialize() { } // Called repeatedly when this Command is scheduled to run protected void execute() { Robot.defense.setAngle(chevalAngle); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return true; } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { end(); } }
package com.davidbracewell.io; import com.davidbracewell.io.resource.Resource; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import lombok.NonNull; import java.io.IOException; import java.io.Serializable; import java.io.Writer; import java.util.concurrent.atomic.AtomicInteger; /** * <p>A writer that will write content to different files using a round robin strategy. It is important that the full * content is written using one call to the write method to ensure the content goes to the same file. </p> * * @author David B. Bracewell */ public class MultiFileWriter extends Writer implements Serializable, AutoCloseable { private static final long serialVersionUID = 1L; private final Writer[] writers; private final AtomicInteger lockId = new AtomicInteger(); private final int numberOfFiles; /** * Instantiates a new Multi file writer. * * @param baseDirectory the base directory which will contain the files * @param filePrefix the file prefix (each file have XXXXX appended on where XX is the file number) * @param numberOfFiles the number of files * @throws IOException Something went wrong initializing the files */ public MultiFileWriter(@NonNull Resource baseDirectory, @NonNull String filePrefix, int numberOfFiles) throws IOException { Preconditions.checkArgument(!baseDirectory.exists() || baseDirectory.isDirectory(), "Resource base must not exist or be a directory"); Preconditions.checkArgument(numberOfFiles > 0, "Must specify at least one file"); baseDirectory.mkdirs(); this.writers = new Writer[numberOfFiles]; this.numberOfFiles = numberOfFiles; for (int i = 0; i < numberOfFiles; i++) { String name = filePrefix + Strings.padStart(Integer.toString(i), 5, '0'); this.writers[i] = new AsyncWriter(baseDirectory.getChild(name).writer()); } } @Override public void write(char[] cbuf, int off, int len) throws IOException { int lock = lockId.accumulateAndGet(1, (x1, x2) -> { if (x1 + x2 >= numberOfFiles) { return 0; } return x1 + x2; }); this.writers[lock].write(cbuf, off, len); } @Override public void flush() throws IOException { IOException ioe = null; for (int i = 0; i < numberOfFiles; i++) { try { this.writers[i].flush(); } catch (IOException e) { ioe = e; } } if (ioe != null) { throw ioe; } } @Override public void close() throws IOException { IOException ioe = null; for (int i = 0; i < numberOfFiles; i++) { try { this.writers[i].close(); } catch (IOException e) { ioe = e; } } if (ioe != null) { throw ioe; } } }//END OF MultiFileWriter
package com.dslplatform.compiler.client; import com.dslplatform.compiler.client.json.JsonObject; import org.w3c.dom.Document; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.*; import java.net.URL; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class Utils { public static String read(final InputStream stream) throws IOException { final BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); final StringBuilder sb = new StringBuilder(); final char[] buffer = new char[8192]; int len; while ((len = reader.read(buffer)) != -1) { sb.append(buffer, 0, len); } reader.close(); return sb.toString(); } public static Either<String> readFile(final File file) { try { FileInputStream stream = new FileInputStream(file); final String content = read(stream); stream.close(); return Either.success(content); } catch (IOException ex) { return Either.fail(ex); } } public static void saveFile(final File file, final String content) throws IOException { FileOutputStream fos = new FileOutputStream(file); final Writer writer = new OutputStreamWriter(fos, "UTF-8"); writer.write(content); writer.close(); fos.close(); } public static JsonObject toJson(final Map<String, String> map) { final JsonObject json = new JsonObject(); for (final Map.Entry<String, String> kv : map.entrySet()) { json.add(kv.getKey(), kv.getValue()); } return json; } public static List<File> findFiles(final File path, final List<String> extensions) { final List<File> foundFiles = new LinkedList<File>(); findFiles(path, foundFiles, extensions); return foundFiles; } private static void findFiles(final File path, final List<File> foundFiles, final List<String> extensions) { for (final String fn : path.list()) { final File f = new File(path, fn); if (f.isDirectory()) { findFiles(f, foundFiles, extensions); } else { for (final String e : extensions) { if (f.getName().endsWith(e)) { foundFiles.add(f); break; } } } } } public static void unpackZip(final Context context, final File path, final URL remoteUrl) throws IOException { unpackZip(context, path, remoteUrl, 3); } private static void unpackZip(final Context context, final File path, final URL remoteUrl, final int retry) throws IOException { try { InputStream response = remoteUrl.openConnection().getInputStream(); final ZipInputStream zip = new ZipInputStream(new BufferedInputStream(response)); ZipEntry entry; final byte[] buffer = new byte[8192]; while ((entry = zip.getNextEntry()) != null) { long size = 0; final File file = new File(path.getAbsolutePath(), entry.getName()); final FileOutputStream fos = new FileOutputStream(file); int len; while ((len = zip.read(buffer)) != -1) { fos.write(buffer, 0, len); size += len; } fos.close(); context.log("Unpacked: " + entry.getName() + ". Size: " + (size / 1024) + "kB"); zip.closeEntry(); } zip.close(); } catch (IOException io) { context.error(io); if (retry > 0) { context.log("Retrying download... from " + remoteUrl); unpackZip(context, path, remoteUrl, retry - 1); } else throw io; } } public static void downloadFile(final File file, final URL url) throws IOException { downloadFileAndRetry(file, url, 3); } private static void downloadFileAndRetry(final File file, final URL url, final int retry) throws IOException { final FileOutputStream fos = new FileOutputStream(file); try { final byte[] buffer = new byte[8192]; final InputStream stream = new BufferedInputStream(url.openConnection().getInputStream()); int len; while ((len = stream.read(buffer)) != -1) { fos.write(buffer, 0, len); } stream.close(); } catch (IOException io) { if (retry > 0) { downloadFileAndRetry(file, url, retry - 1); } else throw io; } finally { fos.close(); } } public static synchronized Either<Document> readXml(final InputStream stream) { try { final DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); final DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); return Either.success(dBuilder.parse(stream)); } catch (IOException ex) { return Either.fail(ex); } catch (ParserConfigurationException ex) { return Either.fail(ex); } catch (SAXException ex) { return Either.fail(ex); } } public static boolean isWindows() { return System.getProperty("os.name").toLowerCase().contains("windows"); } public static class CommandResult { public final String output; public final String error; public CommandResult(final String output, final String error) { this.output = output; this.error = error; } } private static class ConsumeStream extends Thread { private final BufferedReader reader; private final Context context; private final StringBuilder output = new StringBuilder(); private IOException exception; private ConsumeStream(final InputStream stream, final Context context) { this.reader = new BufferedReader(new InputStreamReader(stream)); this.context = context; } private ConsumeStream() { this.reader = null; this.context = null; } public static ConsumeStream start(final InputStream stream, final Context context) { if (stream == null) { return new ConsumeStream(); } final ConsumeStream cs = new ConsumeStream(stream, context); cs.start(); return cs; } @Override public void run() { if (reader == null) { return; } final char[] buffer = new char[8192]; int len; try { while ((len = reader.read(buffer)) != -1) { output.append(buffer, 0, len); if (context != null) { context.log(buffer, len); } } reader.close(); } catch (IOException ex) { exception = ex; } } } public static boolean testCommand(final Context context, final String command, final String contains) { return testCommand(context, command, contains, new ArrayList<String>()); } public static boolean testCommand(final Context context, final String command, final String contains, final List<String> arguments) { try { final List<String> commandAndArgs = new ArrayList<String>(); commandAndArgs.add(command); commandAndArgs.addAll(arguments); final ProcessBuilder pb = new ProcessBuilder(commandAndArgs); final Process compilation = pb.start(); final ConsumeStream result = ConsumeStream.start(compilation.getInputStream(), null); final ConsumeStream error = ConsumeStream.start(compilation.getErrorStream(), null); compilation.waitFor(); result.join(); error.join(); return error.output.toString().contains(contains) || result.output.toString().contains(contains); } catch (IOException ex) { context.log(ex.getMessage()); return false; } catch (InterruptedException ex) { context.log(ex.getMessage()); return false; } } public static Either<CommandResult> runCommand(final Context context, final String command, final File path, final List<String> arguments) { try { final List<String> commandAndArgs = new ArrayList<String>(); commandAndArgs.add(command); commandAndArgs.addAll(arguments); final ProcessBuilder pb = new ProcessBuilder(commandAndArgs); if (path != null) { pb.directory(path); } final Process compilation = pb.start(); final ConsumeStream result = ConsumeStream.start(compilation.getInputStream(), context); final ConsumeStream error = ConsumeStream.start(compilation.getErrorStream(), context); compilation.waitFor(); result.join(); error.join(); if (result.exception != null) { return Either.fail(result.exception); } if (error.exception != null) { return Either.fail(error.exception); } return Either.success(new CommandResult(result.output.toString(), error.output.toString())); } catch (IOException ex) { return Either.fail(ex); } catch (InterruptedException ex) { return Either.fail(ex); } } public static void deletePath(final File path) throws IOException { deletePathAndRetry(path, 3); } private static void deletePathAndRetry(final File path, final int retry) throws IOException { try { for (final String fn : path.list()) { final File f = new File(path, fn); if (f.isDirectory()) { deletePath(f); } if (!f.delete()) { throw new IOException("Error cleaning up temporary resource. Failed to delete: " + f.getAbsolutePath()); } } } catch (IOException io) { if (retry > 0) { deletePathAndRetry(path, retry - 1); } else throw io; } } public static List<File> findNonEmptyDirs(final File path, final String extension) { final List<File> foundDirs = new LinkedList<File>(); findNonEmptyDirs(path, foundDirs, extension); return foundDirs; } private static void findNonEmptyDirs(final File path, final List<File> foundFiles, final String extension) { if (path.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(extension); } }).length > 0) { foundFiles.add(path); } for (final String fn : path.list()) { final File f = new File(path, fn); if (f.isDirectory()) { findNonEmptyDirs(f, foundFiles, extension); } } } }
package com.ecbeta.common.core; import static com.ecbeta.common.constants.Constants.AA_REFRESH_ZONES_NAME; import static com.ecbeta.common.constants.Constants.ACTION_NAME; import static com.ecbeta.common.constants.Constants.BTN_OPTION; import static com.ecbeta.common.constants.Constants.JSON_REFRESH_TYPE; import static com.ecbeta.common.constants.Constants.PROGRESS_PAGE_POSTBACK; import static com.ecbeta.common.constants.Constants.REFRESH_TYPE; import static com.ecbeta.common.constants.Constants.UNDER_LINE; import static com.ecbeta.common.core.reflect.BingReflectUtils.automaticBindingJsonParams; import static com.ecbeta.common.core.reflect.BingReflectUtils.automaticBindingParams; import static com.ecbeta.common.core.reflect.BingReflectUtils.findAction; import static com.ecbeta.common.core.reflect.BingReflectUtils.findActionMethod; import java.io.IOException; import java.lang.reflect.Method; import java.util.Arrays; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import net.sf.json.JSONObject; import com.ecbeta.common.constants.Constants; import com.ecbeta.common.core.annotation.Action; import com.ecbeta.common.core.annotation.Actions; import com.ecbeta.common.core.servlet.CoreServlet; import com.ecbeta.common.core.viewer.BaseViewer; import com.ecbeta.common.core.viewer.JsonModel; import com.ecbeta.common.core.viewer.bean.ExportInformationBean; import com.ecbeta.common.core.viewer.bean.NavigationBean; import com.ecbeta.common.core.viewer.bean.PanelTab; import java.io.BufferedReader; import java.lang.reflect.InvocationTargetException; import java.util.logging.Level; import java.util.logging.Logger; public abstract class AbstractWorker { public static boolean debug = false; public static final boolean _SHOW_EXCEPTION = true; private static final int _PROCESS_STATUS_IGNORE = 0, _PROCESS_STATUS_SUCCESS = 1, _PROCESS_STATUS_NOMETHOD = 2, _PROCESS_STATUS_FAIL = 3; private final static Class<?> [][] PARAMETER_TYPES_ARRAY = new Class[][]{null, new Class[] { String.class }, new Class[] {HttpServletRequest.class, String.class }, new Class[] { String.class , HttpServletRequest.class } }; private static final Logger logger = Logger.getLogger(AbstractWorker.class.getName()) ; public static void main (String[] rags) { } private HttpServletRequest request; private HttpServletResponse response; private ServletContext servletContext; private NavigationBean navigationBean; private String jspPath; public String btnClicked; public boolean needForwordToJsp = true; // private static Map<String, Boolean> autoBindingFlagCache = new // HashMap<String, Boolean>(); public void addRefreshZone (String zones) { if (zones == null || zones.trim().equals("")) return; String s = (String) this.getRequest().getAttribute(AA_REFRESH_ZONES_NAME); if (s == null) { this.setRefreshZones(zones); return; } if (s.endsWith(",")) { this.setRefreshZones(s + zones); } else { this.setRefreshZones(s + "," + zones); } } public String allRefreshZone () { return "result,sourcePanelZone,topNavigationZone"; } protected void bindJsonParams (HttpServletRequest request, String btnClicked, String actionMethod) { automaticBindingJsonParams(request, btnClicked, actionMethod, this.getServicer()); automaticBindingJsonParams(request, btnClicked, actionMethod, this.getOtherServicers()); } protected void bindParams (HttpServletRequest request, String btnClicked, String actionMethod) { if (this.getServicer() != null) { this.getServicer().beforeBinding(btnClicked); } automaticBindingParams(request, btnClicked, actionMethod, this.getServicer()); automaticBindingParams(request, btnClicked, actionMethod, this.getOtherServicers()); // TODO; } /* public void bindParamsDisplayAndSort (HttpServletRequest request) { // this.getServicer().getBaseServicerParameterBean().bindTopBart(request, this.getServicer().getBaseServicerParameterBean().getTopBarID("TopBar")); } public void changeDecimalAction () { this.setRefreshZones("result"); this.getServicer().setReportDecimalControlList(TopBar2StateBean.parseOnlyDecimal(this.getRequest(), this.getServicer().getBaseServicerParameterBean().getTopBarID("TopBar")).getValue()); } public void changePaginatorAction () { PaginatorStateBean stateBean = this.getServicer().getPaginatorStateBean(); stateBean.parse(this.getRequest()); this.getServicer().handlePaginator(this.getServicer().getPanelIndex()); this.setRefreshZones("panelZone,result"); }*/ /* public void changePanelAction () { this.setRefreshZones("result,topNavigationZone,sortDialogZone,filterDialogZone,displayDialogZone"); } public void changeSortDisplayModeAction () { this.setRefreshZones("result,sourcePanelZone"); }*/ /* public void changeTimeAction () { }*/ public void clearResultAction () { this.getServicer().destory(); this.getServicer().getBaseServicerParameterBean().setDisplayStage(false); this.setRefreshZones(this.allRefreshZone()); } /** * this method only dispatch btnClicked action, don't write another * logic in this method. all method should be use Action as suffix w/o * or with btnClick as parameter as neccersy. * * @param btnClicked * @return */ public String createAction (String btnClicked) { if (btnClicked == null || btnClicked.trim().equals("")) return null; String methodName; if ("resetDialog".equals(btnClicked)) { methodName = "resetDialog" + ACTION_NAME; } else if (btnClicked.endsWith("Dialog")) { methodName = "popupDialog" + ACTION_NAME; } else if (btnClicked.startsWith("rspModule")) { methodName = "changeRSPModule" + ACTION_NAME; } else { methodName = btnClicked.replaceAll(UNDER_LINE, ""); if (methodName.endsWith(ACTION_NAME)) {} else { methodName = methodName + ACTION_NAME; } } if (btnClicked.startsWith("refresh")) { String s = btnClicked.replace("refresh", ""); if (s.length() >= 1) { s = s.substring(0, 1).toLowerCase() + s.substring(1); this.addRefreshZone(s + "Zone"); } } if (methodName.charAt(1) >= 'A' && methodName.charAt(1) <= 'Z') { return methodName; } return methodName.substring(0, 1).toLowerCase() + methodName.substring(1); } public void dispatchAction (String btnClicked) { } /* @SuppressWarnings("unchecked") public void displayRefreshAction () { this.getServicer().updateDisplay(this.btnClicked); this.setRefreshZones("result"); } */ private void doActionAnnotation (Action annotation) { if (StringUtils.isNotEmpty(annotation.refreshZones())) { this.addRefreshZone(annotation.refreshZones()); } this.needForwordToJsp = annotation.needForwordToJsp(); if (annotation.clearResult()) { this.clearResultAction(); } } private void doActionAnnotation (Method method, String action) { if (method == null) return; if (method.isAnnotationPresent(Action.class)) { Action annotation = (Action) method.getAnnotation(Action.class); this.doActionAnnotation(annotation); } else if (method.isAnnotationPresent(Actions.class)) { Actions actions = (Actions) method.getAnnotation(Actions.class); Action act = findAction(actions, action); if (act != null) { this.doActionAnnotation(act); } } } protected boolean enableActionAnnotation () { return false; } /* public void exportExcelAction () { }*/ /* public void exportPDFAction () { this.needForwordToJsp = false; }*/ /* public void filterRefreshAction () { this.getServicer().processFilter(); this.setRefreshZones("result"); // } */ private boolean findAnnotationInClassLevel ( Class<?> ownerClass, String action) { if (ownerClass.isAnnotationPresent(Actions.class)) { Actions actions = (Actions) ownerClass.getAnnotation(Actions.class); Action act = findAction(actions, action); if (act != null) { this.doActionAnnotation(act); return true; } } return false; } /* public void downloadExcelAction(){ }*/ protected void forwardToJsp(String jsp) throws IOException, ServletException{ this.getServletContext().getRequestDispatcher(jspPath+jsp).forward(getRequest(), getResponse()); } public String getAppName () { String workerName = this.getWORKER_NAME(); return workerName.substring(0, workerName.length() - "Worker".length()); } private Object[][] getArgs(HttpServletRequest request, String btnClicked){ return new Object[][]{ null, new Object[]{btnClicked}, new Object[]{request, btnClicked}, new Object[]{btnClicked, request}, }; } /** * @return the btnClicked */ public String getBtnClicked () { return btnClicked; } public String getClearResultActions () { return ""; } public ExportInformationBean getExportInformationBean(){ return null; } /** * @return the fORM_NAME */ public abstract String getFORM_NAME (); /** * @return the jSP_TOGO */ public String getJSP_TOGO(){ return this.getJSP_TOGO_PERIX()+".jsp"; } public abstract String getJSP_TOGO_PERIX (); public String getJspGoto () { return getJSP_TOGO(); } /** * @return the navigationBean */ public NavigationBean getNavigationBean () { return navigationBean; } public String getNavTier(){ if(this.navigationBean != null){ return this.navigationBean.getNavTier("_"); } return ""; } public Object[] getOtherServicers () { return null; } public PanelTab[] getPanels(){ return this.getServicer().getPanels(); } public String getRenderHTML () { BaseViewer viewer = this.getViewer(true); if (viewer != null) { if (!this.hasData()) { return ""; } try { viewer.export(new org.apache.commons.io.output.NullOutputStream(), this.getJSP_TOGO_PERIX() + ".html"); String s = viewer.toHTML(); return s; } catch (Exception e) { logger.log(Level.WARNING, "Render HTML", e); } } return ""; } public HttpServletRequest getRequest () { return request; } public HttpServletResponse getResponse () { return response; } /** * This is main servicer * @return */ public abstract AbstractServicer getServicer (); public ServletContext getServletContext () { return servletContext; } public String getUrl () { StringBuilder url = new StringBuilder(); if(this.navigationBean == null){ this.navigationBean = new NavigationBean(); } url.append(this.navigationBean.getUrl(this.request.getContextPath())); url.append("&"); url.append(Constants.SRC_JSP).append("=").append(this.getJSP_TOGO()).append("&"); url.append(REFRESH_TYPE).append("=").append(JSON_REFRESH_TYPE).append("&"); url.append(Constants.BTN_OPTION).append("="); return url.toString(); } public String getUrl (String type, String action) { StringBuilder url = new StringBuilder(); if(this.navigationBean == null){ this.navigationBean = new NavigationBean(); } url.append(this.navigationBean.getUrl(this.request.getContextPath())); url.append("&"); url.append(Constants.SRC_JSP).append("=").append(this.getJSP_TOGO()).append("&"); url.append(REFRESH_TYPE).append("=").append(type).append("&"); url.append(Constants.BTN_OPTION).append("=").append(action); return url.toString(); } public BaseViewer getViewer (boolean isHTML) { return null; } /** * @return the wORKER_NAME */ public String getWORKER_NAME () { return this.getClass().getSimpleName(); } public boolean hasData (){ return true; } public void init (HttpServletRequest request, HttpServletResponse response, String jspPath, CoreServlet servlet, ServletContext servletContext) { this.request = request; this.response = response; this.servletContext = servletContext; String navTier = request.getParameter(Constants.NAV_TIERS); if(StringUtils.isEmpty(navTier)){ navTier = "0_0_0_0"; } this.navigationBean = servlet.find(navTier.split("_"), this.getClass().getName()); this.btnClicked = request.getParameter(BTN_OPTION); this.jspPath = jspPath; } public boolean isDebug () { return debug; } public boolean isUseActionFromServicer () { return true; } public void otherClickedAction () { this.setRefreshZones("result"); } /* public void popupDialogAction () { this.setRefreshZones(this.btnClicked + "Zone," + this.btnClicked + "BottomZone"); }*/ public void processButtonClickedAction (String action) { try{ Object[] _instance = this.isUseActionFromServicer() ? new Object[]{this, this.getServicer()} : new Object[]{this}; int []_processStatus = new int[_instance.length]; Arrays.fill(_processStatus, _PROCESS_STATUS_IGNORE); Object[][] args = this.getArgs(this.getRequest(), btnClicked); outer: for(int c = 0; c < _instance.length; c++){ for(int i = 0 ; i < PARAMETER_TYPES_ARRAY.length && i < args.length; i++){ _processStatus[c] = this.processButtonClickedAction(action, _instance[c].getClass() , _instance[c], PARAMETER_TYPES_ARRAY[i], args[i]); if( _processStatus[c] != _PROCESS_STATUS_NOMETHOD){ break outer; } } } if(_processStatus[0] != _PROCESS_STATUS_SUCCESS && _processStatus[0] != _PROCESS_STATUS_IGNORE){ this.otherClickedAction(); this.dispatchAction(this.btnClicked); } if ( !"clearResultAction".equals(action) && StringUtils.isNotEmpty(this.getClearResultActions()) && (this.getClearResultActions().contains(this.btnClicked) || this.getClearResultActions().contains(action) )) { this.clearResultAction(); } }catch(Exception e){ logger.log(Level.WARNING, null, e); } } protected void setJsonContentType() { this.getResponse().setContentType("application/json; charset=UTF-8"); this.getResponse().setHeader("Cache-Control", "no-store, max-age=0, no-cache, must-revalidate"); this.getResponse().addHeader("Cache-Control", "post-check=0, pre-check=0"); this.getResponse().setHeader("Pragma", "no-cache"); } protected void returnJSON(Object o) { this.setJsonContentType(); try{ if(o instanceof JsonModel){ this.getResponse().getWriter().write( ((JsonModel)o).toJson()); } // this.getResponse().getWriter().write( new Gson.toJson(o).toString()); }catch(Exception e){ logger.log(Level.WARNING, null, e); //this.getResponse().getWriter().write(JSONArray.fromObject(o).toString()); } } private transient Object result; private int processButtonClickedAction (String action, Class<?> ownerClass, Object instance , Class<?>[] _classTypes, Object[] args) { if (action == null) return _PROCESS_STATUS_IGNORE; if (enableActionAnnotation() && findAnnotationInClassLevel(ownerClass, action)) { return _PROCESS_STATUS_SUCCESS; } String key = ownerClass.getName() + "_" + action; Method method = null; try { if (enableActionAnnotation() && method == null) { method = findActionMethod(ownerClass, action); } boolean withBtnPara = false; if (null == method) { method = ownerClass.getMethod(action, _classTypes); withBtnPara = true; } this.result = withBtnPara ? method.invoke(instance, args) : method.invoke(instance); logger.log(Level.INFO, action+" " + method.getName(), method); this.doActionAnnotation(method, action); return _PROCESS_STATUS_SUCCESS; } catch (SecurityException e) { this.showException(key + " " + (method == null ? "": method.toString() ) , e, true); } catch (NoSuchMethodException e) { this.showException(key + " " + (method == null ? "": method.toString() ) , e, false); return _PROCESS_STATUS_NOMETHOD; } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { this.showException(key + " " + (method == null ? "": method.toString() ) , e, false); } return _PROCESS_STATUS_FAIL; } public void processRequest () { this.getResponse().setContentType("text/html"); this.needForwordToJsp = true; this.result = null; this.setRefreshZones(""); //HttpServletRequest request = this.getRequest(); try { if (this.getServicer().getExportInformationBean() == null) { this.getServicer().setExportInformationBean(this.getExportInformationBean()); } } catch (Exception e) { logger.log(Level.WARNING, "", e); } String refresh = request.getParameter(REFRESH_TYPE); boolean isJson = (refresh != null && refresh.equals(JSON_REFRESH_TYPE) ); try{ try { this.btnClicked = request.getParameter(BTN_OPTION); if(StringUtils.isEmpty(this.btnClicked)){ this.btnClicked = ""; } this.needForwordToJsp = !(refresh != null && refresh.equals(JSON_REFRESH_TYPE) ); String action = this.createAction(btnClicked); if (this.btnClicked.equals(PROGRESS_PAGE_POSTBACK)) { } else if (isJson) { this.setJsonContentType(); this.bindJsonParams(request, btnClicked, action); } else { this.bindParams(request, btnClicked, action); } if (this.btnClicked != null && !"".equals(this.btnClicked) && (!this.btnClicked.equals("") && (!this.btnClicked.equals(PROGRESS_PAGE_POSTBACK) ) )) { this.processButtonClickedAction(action); } } catch (Exception e) { logger.log(Level.WARNING, "", e); } String zones = request.getParameter(AA_REFRESH_ZONES_NAME); if (StringUtils.isNotEmpty(zones)) { this.addRefreshZone(zones); } if (StringUtils.isEmpty(request.getAttribute(AA_REFRESH_ZONES_NAME) + "")) { this.addRefreshZone("result"); } this.addRefreshZone("excludeDateTimeZone,footerZone,alwaysRefreshZone"); if (isJson) { this.needForwordToJsp = false; } if(isJson && this.result != null && StringUtils.isNotEmpty(this.result.toString())){ returnJSON(this.result); }else if (this.needForwordToJsp && (!getResponse().isCommitted() )) { try { forwardToJsp(getJSP_TOGO()); } catch (IOException e) { logger.log(Level.WARNING, "", e); } } }finally{ } } /* public void reloadFromSnapshotAction(){ this.clearResultAction(); }*/ public void resetDialogAction () { this.setRefreshZones("sourcePanelZone,topNavigationZone,sortDialogZone,filterDialogZone,displayDialogZone"); } public void setDebug (boolean debug) { AbstractWorker.debug = debug; } public void setRefreshZones (String zones) { this.getRequest().setAttribute(AA_REFRESH_ZONES_NAME, zones); } public void setRequest (HttpServletRequest request) { this.request = request; } public void setResponse (HttpServletResponse response) { this.response = response; } public void setServletContext (ServletContext servletContext) { this.servletContext = servletContext; } private void showException(String acc, Exception e, boolean forceOut){ if (_SHOW_EXCEPTION || forceOut) { logger.log(Level.WARNING, "", e); } } /* public void sortRefreshAction () { } */ public void submitAction () { submitAction(false, false); } public void submitAction (boolean withOutSort, boolean withOutDisplay) { final AbstractServicer servicer = this.getServicer(); servicer.destory(); try { this.getServicer().retrieveData(); } catch (Exception e) { logger.log(Level.WARNING, "", e); } if(!withOutSort){ servicer.sort(); } if(!withOutDisplay){ servicer.updateDisplay(this.btnClicked); } servicer.getBaseServicerParameterBean().setDisplayStage(true); servicer.getBaseServicerParameterBean().setSelectionPanelStatusOpen(false); this.setRefreshZones(""); } public void updateExportInformationBean () { this.getServicer().updateExportInformationBean(); } public JSONObject getJSONObject() { StringBuilder jb = new StringBuilder(); String line; try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { jb.append(line); } } catch (IOException e) { logger.log(Level.SEVERE, "", e); } try { JSONObject jsonObject = JSONObject.fromObject(jb.toString()); return jsonObject; } catch (Exception e) { logger.log(Level.SEVERE, "", e); } return null; } }
package com.ezardlabs.lostsector.ai; import com.ezardlabs.dethsquare.Mathf; import com.ezardlabs.dethsquare.Physics; import com.ezardlabs.dethsquare.Physics.RaycastHit; import com.ezardlabs.dethsquare.Transform; import com.ezardlabs.dethsquare.Vector2; import com.ezardlabs.lostsector.Game.DamageType; import com.ezardlabs.lostsector.NavMesh; import com.ezardlabs.lostsector.NavMesh.NavPoint; public abstract class Behaviour { private float moveSpeed; private final boolean willPatrol; private final float visionRange; private State state = State.IDLE; private CombatState combatState = CombatState.IDLE; private Transform target = null; private NavPoint[] path = null; private int pathIndex = 0; private NavPoint currentNavPoint = null; private NavPoint currentTargetNavPoint = null; private long freezeTime = 5000; private long freezeStart; private float[] freezeTint = {0, 0.3f, 0.6f}; private long thawTime = 1000; private long thawStart; private int directionToLook = 0; public enum State { IDLE, MOVING, JUMPING, FALLING, LANDING, FROZEN, THAWING, ATTACKING } protected enum CombatState { IDLE, PATROLLING, TRACKING, SEARCHING, ATTACKING } Behaviour(float moveSpeed, boolean willPatrol, float visionRange) { this.moveSpeed = moveSpeed; this.willPatrol = willPatrol; this.visionRange = visionRange; } public final void update(Transform transform) { if (state == State.FROZEN) { transform.gameObject.renderer.setTint(freezeTint[0], freezeTint[1], freezeTint[2]); if (System.currentTimeMillis() - freezeStart > freezeTime) { state = State.THAWING; thawStart = System.currentTimeMillis(); } return; } if (state == State.THAWING) { long diff = System.currentTimeMillis() - thawStart; if (diff < thawTime) { float ratio = (float) diff / (float) thawTime; transform.gameObject.renderer.setTint(freezeTint[0] - ratio * freezeTint[0], freezeTint[1] - ratio * freezeTint[1], freezeTint[2] - ratio * freezeTint[2]); } else { transform.gameObject.renderer.setTint(0, 0, 0); transform.gameObject.animator.shouldUpdate = true; state = State.IDLE; } return; } if (directionToLook != 0) { transform.scale.x = directionToLook; directionToLook = 0; } Transform sightedEnemy = visionCheck(transform); if (sightedEnemy != null) { combatState = onEnemySighted(transform, sightedEnemy); switch (combatState) { case IDLE: case PATROLLING: target = null; break; case TRACKING: case SEARCHING: case ATTACKING: target = sightedEnemy; break; } } switch (combatState) { case IDLE: break; case PATROLLING: // TODO implement patrolling break; case TRACKING: NavPoint self = NavMesh.getNavPoint(transform.position.x, transform.position.y); NavPoint targetNavPoint = NavMesh.getNavPoint(target.position); if ((!self.equals(currentNavPoint) || !targetNavPoint.equals(currentTargetNavPoint)) && !self.links.isEmpty()) { currentNavPoint = self; currentTargetNavPoint = targetNavPoint; path = NavMesh.getPath(currentNavPoint, currentTargetNavPoint); } pathIndex = 0; break; case SEARCHING: break; case ATTACKING: combatState = attack(transform, target); break; } switch (combatState) { case IDLE: state = State.IDLE; break; case PATROLLING: case TRACKING: case SEARCHING: state = move(transform); break; case ATTACKING: state = State.ATTACKING; break; } } private State move(Transform transform) { if (path != null && path.length > 0) { if (pathIndex < path.length - 1) { float direction = Mathf.clamp(path[pathIndex + 1].position.x - path[pathIndex].position.x, -1, 1); transform.translate(moveSpeed * direction, 0); transform.scale.x = direction; if (transform.gameObject.rigidbody.velocity.y > transform.gameObject.rigidbody.gravity) { return State.FALLING; } else if (path[pathIndex + 1].position.y < path[pathIndex].position.y) { if (state != State.JUMPING) { jump(transform, Math.abs(path[pathIndex + 1].position.y - path[pathIndex].position.y)); } return State.JUMPING; } else if (direction == 0) { return State.IDLE; } else { return State.MOVING; } } } return State.IDLE; } private void jump(Transform transform, float distance) { transform.gameObject.rigidbody.velocity.y = (float) -Math.sqrt(2.5 * distance) - 2; } public State getState() { return state; } protected abstract CombatState onEnemySighted(Transform self, Transform enemy); protected abstract CombatState attack(Transform self, Transform target); private Transform visionCheck(Transform transform) { RaycastHit hit = Physics.raycast(transform.position.offset(transform.scale.x > 0 ? 200 : 0, 100), new Vector2(transform.scale.x, 0), visionRange, "player", "cryopod"); if (hit == null) { return null; } else { return hit.transform; } } public void onDamageReceived(DamageType damageType, Transform self, Vector2 attackOrigin) { switch (damageType) { case NORMAL: break; case SLASH: break; case COLD: state = State.FROZEN; freezeStart = System.currentTimeMillis(); self.gameObject.animator.shouldUpdate = false; break; case KUBROW: break; } if (attackOrigin.x > self.position.x) { directionToLook = 1; } else if (attackOrigin.x < self.position.x) { directionToLook = -1; } } public void die() { System.out.println("died"); } @SuppressWarnings("unchecked") protected abstract static class Builder<T extends Builder> { float moveSpeed = 10; float visionRange = 2000; boolean willPatrol = false; public T setMoveSpeed(float moveSpeed) { this.moveSpeed = moveSpeed; return (T) this; } public T setWillPatrol(boolean willPatrol) { this.willPatrol = willPatrol; return (T) this; } public T setVisionRange(float visionRange) { this.visionRange = visionRange; return (T) this; } public abstract Behaviour create(); } }
package nu.validator.xml; import java.net.URI; import java.util.LinkedList; import org.relaxng.datatype.DatatypeException; import org.whattf.datatype.Language; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; import com.hp.hpl.jena.iri.IRI; import com.hp.hpl.jena.iri.IRIFactory; public class BaseUriTracker implements ContentHandler, UriLangContext { private enum Direction { LTR, RTL, INHERIT } private class Node { public URI currentAbsolute; // not null public String originalRelative; // null if no xml:base public String lang; // null if no xml:lang private boolean langSpeficied; private boolean rtl; /** * @param currentAbsolute * @param originalRelative */ public Node(URI currentAbsolute, String originalRelative, String lang, boolean langSpecified, boolean rtl) { this.currentAbsolute = currentAbsolute; this.originalRelative = originalRelative; this.lang = lang; this.langSpeficied = langSpecified; this.rtl = rtl; } } private LinkedList<Node> stack = new LinkedList<Node>(); private final IRIFactory iriFactory; private boolean baseSeen = false; private boolean contentLanguageSeen = false; /** * -1 at start * 0 in html * >=1 in head * -2 situation over */ private int inHeadDepth = -1; private int inCruftDepth = 0; private boolean equalsIgnoreAsciiCase(CharSequence one, CharSequence other) { if (other == null && one == null) { return true; } if (other == null || one == null) { return false; } if (one.length() != other.length()) { return false; } for (int i = 0; i < other.length(); i++) { char c0 = one.charAt(i); if (c0 >= 'A' && c0 <= 'Z') { c0 += 0x20; } char c1 = other.charAt(i); if (c1 >= 'A' && c1 <= 'Z') { c1 += 0x20; } if (c0 != c1) { return false; } } return true; } public BaseUriTracker(String systemId, String contentLanguage) { this.iriFactory = new IRIFactory(); this.iriFactory.shouldViolation(false, false); this.iriFactory.securityViolation(false, false); this.iriFactory.dnsViolation(false, false); this.iriFactory.mintingViolation(false, false); this.iriFactory.useSpecificationIRI(false); this.iriFactory.useSchemeSpecificRules("http", false); this.iriFactory.useSchemeSpecificRules("https", false); this.iriFactory.useSchemeSpecificRules("ftp", false); this.iriFactory.useSchemeSpecificRules("data", false); URI uri = null; try { IRI iri = iriFactory.construct(systemId); uri = new URI(iri.toASCIIString()); if (!uri.isAbsolute()) { uri = null; } } catch (Exception e) { uri = null; } String lang = ""; boolean langSpecified = false; if (contentLanguage != null) { try { if (!"".equals(contentLanguage)) { Language.THE_INSTANCE.checkValid(contentLanguage); } lang = contentLanguage; langSpecified = true; } catch (DatatypeException e) { } } stack.add(new Node(uri, null, lang, langSpecified, false)); stack.add(new Node(uri, null, lang, false, false)); // base/content-language placeholder } private Node peek() { return stack.getLast(); } private void pop() { stack.removeLast(); } private void push(String relative, String language, Direction dir) { String lang = ""; boolean langSpecified = false; if (language != null) { try { if (!"".equals(language)) { Language.THE_INSTANCE.checkValid(language); } lang = language; langSpecified = true; } catch (DatatypeException e) { } } Node curr = peek(); URI base = curr.currentAbsolute; if (!langSpecified) { lang = curr.lang; } boolean rtl; switch (dir) { case RTL: rtl = true; break; case LTR: rtl = false; break; default: rtl = curr.rtl; break; } if (relative == null) { stack.addLast(new Node(base, null, lang, langSpecified, rtl)); } else { URI newBase; String ascii = null; try { IRI relIri = iriFactory.construct(relative); ascii = relIri.toASCIIString(); if (base != null) { newBase = base.resolve(ascii); if (!newBase.isAbsolute()) { newBase = base; } } else { newBase = new URI(ascii); if (!newBase.isAbsolute()) { newBase = null; } } } catch (Exception e) { newBase = base; } stack.addLast(new Node(newBase, ascii, lang, langSpecified, rtl)); } } private void installBase(String href) { if (baseSeen) { return; } baseSeen = true; LinkedList<Node> oldStack = stack; stack = new LinkedList<Node>(); int i = 0; for (Node node : oldStack) { if (i == 0) { stack.addLast(node); // root } else if (i == 1) { push(href, node.langSpeficied ? node.lang : null, node.rtl ? Direction.RTL : Direction.LTR); } else { push(node.originalRelative, node.langSpeficied ? node.lang : null, node.rtl ? Direction.RTL : Direction.LTR); } i++; } } private void installContentLanguage(String language) { if (contentLanguageSeen) { return; } contentLanguageSeen = true; String lang = ""; boolean langSpecified = false; if (language != null) { try { if (!"".equals(language)) { Language.THE_INSTANCE.checkValid(language); } lang = language; langSpecified = true; } catch (DatatypeException e) { } } if (!langSpecified) { return; } int i = 0; for (Node node : stack) { if (i == 0) { // nop } else if (i == 1) { node.lang = lang; node.langSpeficied = true; // probably unnecessary... } else { if (node.langSpeficied) { return; } else { node.lang = lang; } } i++; } } /** * @see nu.validator.xml.UriLangContext#currentLanguage() */ public String currentLanguage() { return stack.getLast().lang; } /** * @see nu.validator.xml.UriLangContext#isCurrentRtl() */ public boolean isCurrentRtl() { return stack.getLast().rtl; } /** * @see nu.validator.xml.UriLangContext#toAbsoluteUriWithCurrentBase(java.lang.String) */ public String toAbsoluteUriWithCurrentBase(String uri) { try { IRI relIri = iriFactory.construct(uri); String ascii; ascii = relIri.toASCIIString(); URI base = stack.getLast().currentAbsolute; URI rv; if (base == null) { rv = new URI(ascii); } else { rv = base.resolve(ascii); } if (rv.isAbsolute()) { return rv.toASCIIString(); } else { return null; } } catch (Exception e) { return null; } } public void characters(char[] ch, int start, int length) throws SAXException { } public void endDocument() throws SAXException { } public void endElement(String uri, String localName, String name) throws SAXException { if (inHeadDepth > 0) { inHeadDepth if (inHeadDepth == 0) { inHeadDepth = -2; } } if (inCruftDepth > 0) { inCruftDepth } pop(); } public void endPrefixMapping(String prefix) throws SAXException { } public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { } public void processingInstruction(String target, String data) throws SAXException { } public void setDocumentLocator(Locator locator) { } public void skippedEntity(String name) throws SAXException { } public void startDocument() throws SAXException { inHeadDepth = -1; inCruftDepth = 0; } public void startElement(String uri, String localName, String n, Attributes atts) throws SAXException { if (inHeadDepth >= 1) { inHeadDepth++; if ("http: if ("base" == localName) { String href = atts.getValue("", "href"); if (href != null) { installBase(href); } } else if ("meta" == localName) { String httpEquiv = atts.getValue("", "http-equiv"); if (equalsIgnoreAsciiCase("content-language", httpEquiv)) { String content = atts.getValue("", "content"); if (content == null) { content = ""; } installContentLanguage(content); } } } } else if (inHeadDepth == -1) { if ("html" == localName && "http: inHeadDepth = 0; } else { inHeadDepth = -2; } } else if (inHeadDepth == 0 && inCruftDepth == 0) { if ("head" == localName && "http: inHeadDepth = 1; } else { inCruftDepth = 1; } } String base = null; String lang = null; Direction dir = Direction.INHERIT; int len = atts.getLength(); for (int i = 0; i < len; i++) { String ns = atts.getURI(i); if ("http: String name = atts.getLocalName(i); if ("lang" == name) { lang = atts.getValue(i); } else if ("base" == name) { base = atts.getValue(i); } } else if ("" == ns) { String name = atts.getLocalName(i); if (("dir" == name && "http: || ("direction" == name && "http: String value = atts.getValue(i); if (equalsIgnoreAsciiCase("ltr", value)) { dir = Direction.LTR; } else if (equalsIgnoreAsciiCase("rtl", value)) { dir = Direction.RTL; } } } } push(base, lang, dir); } public void startPrefixMapping(String prefix, String uri) throws SAXException { } }
package com.farmaprom.helpers; import com.farmaprom.logger.LoggerWrapper; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; import org.apache.mesos.Protos; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import java.util.Objects; public class MesosTaskHelper { private Boolean tail = true; private Integer offset = 0; public void mesosTailStdOut(LoggerWrapper loggerWrapper) { try { while (loggerWrapper.mesosTailWait || loggerWrapper.task == null) { Thread.sleep(2000); } } catch (InterruptedException e) { System.out.println(""); } JSONParser parser = new JSONParser(); String frameworkID = this.getFrameworkId(loggerWrapper); String mesosMasterIP = this.getMesosMasterIp(loggerWrapper); Integer mesosMasterPort = this.getMesosMasterPort(loggerWrapper); String slaveID = this.getSalveId(loggerWrapper); String taskID = this.getTaskId(loggerWrapper); String slaveHostName = this.getSlaveHostName(parser, mesosMasterIP, mesosMasterPort, slaveID); String directory = ""; while (Objects.equals(directory, "")) { try { directory = this.getDirectoryTashRunning( parser, this.getSlaveHostName(parser, mesosMasterIP, mesosMasterPort, slaveID), frameworkID, slaveID, taskID ); if (Objects.equals(directory, "")) { directory = this.getDirectoryTashFinish( parser, this.getSlaveHostName(parser, mesosMasterIP, mesosMasterPort, slaveID), frameworkID, slaveID, taskID ); } Thread.sleep(2000); } catch (InterruptedException e) { System.out.println(""); } } String file = "stdout"; System.out.println("Output " + file + ":"); while (this.tail) { this.printLog(parser, slaveHostName, directory, file); if (loggerWrapper.taskStatus != null) { Protos.TaskState state = loggerWrapper.taskStatus.getState(); switch (state) { case TASK_FAILED: case TASK_FINISHED: case TASK_KILLED: case TASK_LOST: case TASK_ERROR: this.tail = false; break; } } } this.printLog(parser, slaveHostName, directory, file); } private void printLog(JSONParser parser, String slaveHostName, String directory, String file) { try { HttpResponse<JsonNode> jsonResponse; jsonResponse = Unirest.get(this.getMesosFileReadUrl(slaveHostName)) .header("accept", "application/json") .queryString("path", directory + "/" + file) .queryString("offset", this.offset) .asJson(); JSONObject fileRead = (JSONObject) parser.parse(jsonResponse.getBody().toString()); if (jsonResponse.getStatus() != 200 || fileRead.get("data") == null) { Thread.sleep(2000); } String data = fileRead.get("data").toString(); if (data == null || data.length() == 0) { Thread.sleep(1000); } else { this.offset += data.length(); System.out.print(data); } } catch (UnirestException | ParseException | InterruptedException e) { System.out.println(""); } } public void stopTail() { this.tail = false; } public void getMesosTaskOutput(LoggerWrapper loggerWrapper) { JSONParser parser = new JSONParser(); try { Thread.sleep(1000); String logs = getMesosTaskLogs( parser, loggerWrapper, this.getMesosMasterIp(loggerWrapper), this.getMesosMasterPort(loggerWrapper) ); System.out.println(""); System.out.println(logs); } catch (InterruptedException e) { System.out.println(""); } } private String getFrameworkId(LoggerWrapper loggerWrapper) { return loggerWrapper.frameworkID.getValue(); } private String getMesosMasterIp(LoggerWrapper loggerWrapper) { int ip = loggerWrapper.masterInfo.getIp(); return String.format("%d.%d.%d.%d", (ip & 0xff), (ip >> 8 & 0xff), (ip >> 16 & 0xff), (ip >> 24 & 0xff)); } private Integer getMesosMasterPort(LoggerWrapper loggerWrapper) { return loggerWrapper.masterInfo.getPort(); } private String getSalveId(LoggerWrapper loggerWrapper) { return loggerWrapper.task.getSlaveId().getValue(); } private String getTaskId(LoggerWrapper loggerWrapper) { return loggerWrapper.task.getTaskId().getValue(); } private String getMesosFileReadUrl(String slaveHostName) { return "http://" + slaveHostName + ":5051/files/read.json"; } private String getMesosFileDownloadUrl(String slaveHostName) { return "http://" + slaveHostName + ":5051/files/download"; } private String getMesosTaskLogs(JSONParser parser, LoggerWrapper loggerWrapper, String mesosMasterIP, Integer mesosMasterPort) { String frameworkID = this.getFrameworkId(loggerWrapper); String slaveID = this.getSalveId(loggerWrapper); String taskID = this.getTaskId(loggerWrapper); String slaveHostName = this.getSlaveHostName(parser, mesosMasterIP, mesosMasterPort, slaveID); String directory = this.getDirectoryTashFinish(parser, slaveHostName, frameworkID, slaveID, taskID); String stderr = getLogFileData(slaveHostName, directory, "stderr"); return "\r\n" + stderr; } private String getLogFileData(String slaveHostName, String directory, String file) { HttpResponse<String> response; int status, numAttempts = 0; try { do { response = Unirest.get(this.getMesosFileDownloadUrl(slaveHostName)) .queryString("path", directory + "/" + file) .asString(); numAttempts++; Thread.sleep(1000); status = response.getStatus(); if (status == 200) { break; } } while (numAttempts < 10); return "Output " + file + ":\r\n" + response.getBody() + "\r\n"; } catch (UnirestException e) { e.printStackTrace(); } catch (InterruptedException e) { System.out.println(""); } return ""; } private String getSlaveHostName(JSONParser parser, String mesosMasterIP, Integer mesosMasterPort, String slaveID) { String slaveHostName = ""; try { HttpResponse<String> masterSlavesResponse = Unirest.post("http://" + mesosMasterIP + ":" + mesosMasterPort + "/master/slaves") .asString(); JSONObject masterSlaveBody = (JSONObject) parser.parse(masterSlavesResponse.getBody()); JSONArray salves = (JSONArray) masterSlaveBody.get("slaves"); for (Object salve : salves) { JSONObject slave = (JSONObject) parser.parse(salve.toString()); if (Objects.equals(slaveID, slave.get("id").toString())) { slaveHostName = slave.get("hostname").toString(); } } } catch (UnirestException | ParseException e) { e.printStackTrace(); } return slaveHostName; } private String getDirectoryTashFinish(JSONParser parser, String slaveHostName, String executeFrameworkID, String slaveID, String taskID) { String directory = ""; try { HttpResponse<String> statsResponse = Unirest.post("http://" + slaveHostName + ":5051/state.json") .asString(); JSONObject jsonBody = (JSONObject) parser.parse(statsResponse.getBody()); JSONArray completedFrameworks = (JSONArray) jsonBody.get("completed_frameworks"); for (Object completedFramework : completedFrameworks) { JSONObject framework = (JSONObject) parser.parse(completedFramework.toString()); if (Objects.equals(executeFrameworkID, framework.get("id").toString())) { JSONArray completedExecutors = (JSONArray) framework.get("completed_executors"); for (Object completedExecutor : completedExecutors) { JSONObject executor = (JSONObject) parser.parse(completedExecutor.toString()); if (Objects.equals(taskID, executor.get("id").toString())) { JSONArray completedTasks = (JSONArray) executor.get("completed_tasks"); for (Object completedTask : completedTasks) { JSONObject task = (JSONObject) parser.parse(completedTask.toString()); if (Objects.equals(slaveID, task.get("slave_id").toString())) { directory = executor.get("directory").toString(); } } } } } } } catch (UnirestException | ParseException e) { e.printStackTrace(); } return directory; } private String getDirectoryTashRunning(JSONParser parser, String slaveHostName, String executeFrameworkID, String slaveID, String taskID) { String directory = ""; try { HttpResponse<String> statsResponse = Unirest.post("http://" + slaveHostName + ":5051/state.json") .asString(); JSONObject jsonBody = (JSONObject) parser.parse(statsResponse.getBody()); JSONArray completedFrameworks = (JSONArray) jsonBody.get("frameworks"); for (Object completedFramework : completedFrameworks) { JSONObject framework = (JSONObject) parser.parse(completedFramework.toString()); if (Objects.equals(executeFrameworkID, framework.get("id").toString())) { JSONArray completedExecutors = (JSONArray) framework.get("executors"); for (Object completedExecutor : completedExecutors) { JSONObject executor = (JSONObject) parser.parse(completedExecutor.toString()); if (Objects.equals(taskID, executor.get("id").toString())) { JSONArray completedTasks = (JSONArray) executor.get("tasks"); for (Object completedTask : completedTasks) { JSONObject task = (JSONObject) parser.parse(completedTask.toString()); if (Objects.equals(slaveID, task.get("slave_id").toString())) { directory = executor.get("directory").toString(); } } } } } } } catch (UnirestException | ParseException e) { e.printStackTrace(); } return directory; } }
package com.github.davidmoten.bigsort; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import rx.Notification; import rx.Observable; import rx.Scheduler; import rx.functions.Func0; import rx.functions.Func1; import rx.functions.Func2; import rx.functions.FuncN; public class BigSort { public static <T, Resource> Observable<T> sort(Observable<T> source, final Comparator<T> comparator, final Func2<Observable<T>, Resource, Observable<Resource>> writer, final Func1<Resource, Observable<T>> reader, final Func0<Resource> resourceFactory, int maxToSortInMemoryPerThread, final int maxTempResources, Scheduler scheduler) { return source // buffer into groups small enough to sort in memory .buffer(maxToSortInMemoryPerThread) // sort each buffer to a resource .flatMap( sortInMemoryAndWriteToAResource(comparator, writer, resourceFactory, scheduler)) // make each resource an Observable<Resource> .nest() // reduce by merging the resources to a single resource once the // resource count is maxTempResources .reduce(Observable.<Resource> empty(), mergeResources(comparator, writer, reader, resourceFactory, maxTempResources)) // flatten to a sequence of Resource .flatMap( com.github.davidmoten.rx.Functions .<Observable<Resource>> identity()) // accumulate to a list .toList() // merge remaining resources .flatMap(mergeResourceList(comparator, reader)); } private static <T, Resource> Func1<List<T>, Observable<Resource>> sortInMemoryAndWriteToAResource( final Comparator<T> comparator, final Func2<Observable<T>, Resource, Observable<Resource>> writer, final Func0<Resource> resourceFactory, final Scheduler scheduler) { return new Func1<List<T>, Observable<Resource>>() { @Override public Observable<Resource> call(List<T> list) { return Observable.just(list) // sort .map(sortList(comparator)) // write to resource .flatMap(writeToResource(writer, resourceFactory)) // subscribe on desired scheduler .subscribeOn(scheduler); } }; } private static <T, Resource> Func2<Observable<Resource>, Observable<Resource>, Observable<Resource>> mergeResources( final Comparator<T> comparator, final Func2<Observable<T>, Resource, Observable<Resource>> writer, final Func1<Resource, Observable<T>> reader, final Func0<Resource> resourceFactory, final int maxTempResources) { return new Func2<Observable<Resource>, Observable<Resource>, Observable<Resource>>() { @Override public Observable<Resource> call(Observable<Resource> resources, final Observable<Resource> f) { return resources .concatWith(f) .toList() .flatMap( mergeWhenSizeIsMaxTempResources(comparator, writer, reader, resourceFactory, maxTempResources)); } }; } private static <T, Resource> Func1<List<Resource>, Observable<T>> mergeResourceList( final Comparator<T> comparator, final Func1<Resource, Observable<T>> reader) { return new Func1<List<Resource>, Observable<T>>() { @Override public Observable<T> call(List<Resource> list) { return merge(list, comparator, reader); } }; } private static <T, Resource> Func1<List<Resource>, Observable<Resource>> mergeWhenSizeIsMaxTempResources( final Comparator<T> comparator, final Func2<Observable<T>, Resource, Observable<Resource>> writer, final Func1<Resource, Observable<T>> reader, final Func0<Resource> resourceFactory, final int maxTempResources) { return new Func1<List<Resource>, Observable<Resource>>() { @Override public Observable<Resource> call(List<Resource> list) { if (list.size() < maxTempResources) return Observable.from(list); else { Resource resource = resourceFactory.call(); Observable<T> items = merge(list, comparator, reader); return writer.call(items, resource); } } }; } private static <T, Resource> Func1<List<T>, Observable<Resource>> writeToResource( final Func2<Observable<T>, Resource, Observable<Resource>> writer, final Func0<Resource> resourceFactory) { return new Func1<List<T>, Observable<Resource>>() { @Override public Observable<Resource> call(List<T> a) { Resource resource = resourceFactory.call(); return writer.call(Observable.from(a), resource); } }; } private static <T, Resource> Func1<List<T>, List<T>> sortList( final Comparator<T> comparator) { return new Func1<List<T>, List<T>>() { @Override public List<T> call(List<T> list) { Collections.sort(list, comparator); return list; } }; } private static <T, Resource> Observable<T> merge(List<Resource> resources, final Comparator<T> comparator, Func1<Resource, Observable<T>> reader) { return Observable .zip(Observable.from(resources) // read .map(reader) // materialize and ensure each stream does not complete .map(BigSort .<T> materializeAndRepeatOnCompleteIndefinitely()), BigSort.<Notification<T>> toList()) // keep going till all observables complete .takeWhile(BigSort.<T> listHasOnNext()) // take miniumum .map(BigSort.<T> toMinimum(comparator)); } private static <T> Func1<List<Notification<T>>, T> toMinimum( final Comparator<T> comparator) { return new Func1<List<Notification<T>>, T>() { @Override public T call(List<Notification<T>> list) { T t = null; for (Notification<T> notification : list) { if (notification.isOnNext()) { T v = notification.getValue(); if (t == null || comparator.compare(v, t) < 0) t = v; } } throw new RuntimeException("unexpected"); } }; } private static <T> Func1<List<Notification<T>>, Boolean> listHasOnNext() { return new Func1<List<Notification<T>>, Boolean>() { @Override public Boolean call(List<Notification<T>> list) { for (Notification<T> notif : list) if (notif.isOnNext()) return true; return false; } }; } private static <T> Func1<Observable<T>, Observable<Notification<T>>> materializeAndRepeatOnCompleteIndefinitely() { return new Func1<Observable<T>, Observable<Notification<T>>>() { @Override public Observable<Notification<T>> call(Observable<T> o) { return o.materialize().concatWith( Observable.just(Notification.<T> createOnCompleted()) .repeat()); } }; } private static <T> FuncN<List<T>> toList() { return new FuncN<List<T>>() { @SuppressWarnings("unchecked") @Override public List<T> call(Object... items) { return Arrays.asList((T[]) items); } }; } }
package com.gkopevski.fuelcheck; import com.gkopevski.printer.PrintFuelEntry; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import java.net.URL; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; /** * * @author gkopevski */ public class FuelCheckForm extends javax.swing.JFrame { /** * Creates new form FuelCheckForm */ WebDriver driver; public FuelCheckForm() { initComponents(); System.setProperty("webdriver.chrome.driver", "drivers/chromedriver"); // AnnotationConfiguration config = new AnnotationConfiguration(); // config.addAnnotatedClass(FuelEntry.class ); // config.configure(); // new SchemaExport(config).create(true, true); //Configuration config = new Configuration(); //config.addAnnotatedClass(FuelEntry.class); //config.configure(); //config.buildMappings(); URL myurl = Thread.currentThread().getContextClassLoader().getResource("hibernate.cfg.xml"); SessionFactory sessionFactory = new Configuration() .configure(myurl) .buildSessionFactory(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); menuBar = new javax.swing.JMenuBar(); fileMenu = new javax.swing.JMenu(); openMenuItem = new javax.swing.JMenuItem(); saveMenuItem = new javax.swing.JMenuItem(); saveAsMenuItem = new javax.swing.JMenuItem(); exitMenuItem = new javax.swing.JMenuItem(); editMenu = new javax.swing.JMenu(); cutMenuItem = new javax.swing.JMenuItem(); copyMenuItem = new javax.swing.JMenuItem(); pasteMenuItem = new javax.swing.JMenuItem(); deleteMenuItem = new javax.swing.JMenuItem(); helpMenu = new javax.swing.JMenu(); contentsMenuItem = new javax.swing.JMenuItem(); aboutMenuItem = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jButton1.setText("CheckFuel"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("quit"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jButton3.setText("Print"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); fileMenu.setMnemonic('f'); fileMenu.setText("File"); openMenuItem.setMnemonic('o'); openMenuItem.setText("Open"); fileMenu.add(openMenuItem); saveMenuItem.setMnemonic('s'); saveMenuItem.setText("Save"); fileMenu.add(saveMenuItem); saveAsMenuItem.setMnemonic('a'); saveAsMenuItem.setText("Save As ..."); saveAsMenuItem.setDisplayedMnemonicIndex(5); fileMenu.add(saveAsMenuItem); exitMenuItem.setMnemonic('x'); exitMenuItem.setText("Exit"); exitMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exitMenuItemActionPerformed(evt); } }); fileMenu.add(exitMenuItem); menuBar.add(fileMenu); editMenu.setMnemonic('e'); editMenu.setText("Edit"); cutMenuItem.setMnemonic('t'); cutMenuItem.setText("Cut"); editMenu.add(cutMenuItem); copyMenuItem.setMnemonic('y'); copyMenuItem.setText("Copy"); editMenu.add(copyMenuItem); pasteMenuItem.setMnemonic('p'); pasteMenuItem.setText("Paste"); editMenu.add(pasteMenuItem); deleteMenuItem.setMnemonic('d'); deleteMenuItem.setText("Delete"); editMenu.add(deleteMenuItem); menuBar.add(editMenu); helpMenu.setMnemonic('h'); helpMenu.setText("Help"); contentsMenuItem.setMnemonic('c'); contentsMenuItem.setText("Contents"); helpMenu.add(contentsMenuItem); aboutMenuItem.setMnemonic('a'); aboutMenuItem.setText("About"); helpMenu.add(aboutMenuItem); menuBar.add(helpMenu); setJMenuBar(menuBar); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(24, 24, 24) .addComponent(jButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton2) .addGap(43, 43, 43) .addComponent(jButton3) .addContainerGap(462, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(21, 21, 21) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1) .addComponent(jButton2) .addComponent(jButton3)) .addContainerGap(408, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed System.exit(0); }//GEN-LAST:event_exitMenuItemActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed try { // Create a new instance of the html unit driver // Notice that the remainder of the code relies on the interface, // not the implementation. driver = new ChromeDriver(); // And now use this to visit Google driver.get("http: // Find the text input element by its name WebElement element = driver.findElement(By.name("q")); // Enter something to search for element.sendKeys("Cheese!"); // Now submit the form. WebDriver will find the form for us from the element element.submit(); // Check the title of the page System.out.println("Page title is: " + driver.getTitle()); } catch (Exception e) { e.printStackTrace(); } }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed driver.quit(); }//GEN-LAST:event_jButton2ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed try { PrintFuelEntry pfe = new PrintFuelEntry(); PrinterJob job = PrinterJob.getPrinterJob(); job.setPrintable(pfe); /** * Commented this in order to avoid wizard for printer selection */ // boolean ok = job.printDialog(); // if (ok) { try { job.print(); } catch (PrinterException ex) { /* The job did not successfully complete */ } } catch (Exception e) { e.printStackTrace(); } }//GEN-LAST:event_jButton3ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(FuelCheckForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(FuelCheckForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(FuelCheckForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FuelCheckForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new FuelCheckForm().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JMenuItem aboutMenuItem; private javax.swing.JMenuItem contentsMenuItem; private javax.swing.JMenuItem copyMenuItem; private javax.swing.JMenuItem cutMenuItem; private javax.swing.JMenuItem deleteMenuItem; private javax.swing.JMenu editMenu; private javax.swing.JMenuItem exitMenuItem; private javax.swing.JMenu fileMenu; private javax.swing.JMenu helpMenu; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JMenuBar menuBar; private javax.swing.JMenuItem openMenuItem; private javax.swing.JMenuItem pasteMenuItem; private javax.swing.JMenuItem saveAsMenuItem; private javax.swing.JMenuItem saveMenuItem; // End of variables declaration//GEN-END:variables }
package com.imcode.imcms.config; import com.imcode.imcms.domain.dto.AuditDTO; import com.imcode.imcms.domain.dto.DocumentDTO; import com.imcode.imcms.domain.dto.ImageCropRegionDTO; import com.imcode.imcms.domain.dto.ImageDTO; import com.imcode.imcms.domain.dto.ImageData; import com.imcode.imcms.domain.dto.ImageFileDTO; import com.imcode.imcms.domain.dto.ImageFolderDTO; import com.imcode.imcms.domain.dto.LoopEntryRefDTO; import com.imcode.imcms.domain.dto.MenuDTO; import com.imcode.imcms.domain.dto.MenuItemDTO; import com.imcode.imcms.domain.dto.TextHistoryDTO; import com.imcode.imcms.domain.dto.UserDTO; import com.imcode.imcms.domain.service.CategoryService; import com.imcode.imcms.domain.service.CommonContentService; import com.imcode.imcms.domain.service.DocumentMenuService; import com.imcode.imcms.domain.service.LanguageService; import com.imcode.imcms.domain.service.UserService; import com.imcode.imcms.domain.service.VersionService; import com.imcode.imcms.model.Category; import com.imcode.imcms.model.CommonContent; import com.imcode.imcms.model.Language; import com.imcode.imcms.persistence.entity.CategoryJPA; import com.imcode.imcms.persistence.entity.Image; import com.imcode.imcms.persistence.entity.ImageCropRegionJPA; import com.imcode.imcms.persistence.entity.LanguageJPA; import com.imcode.imcms.persistence.entity.LoopEntryRefJPA; import com.imcode.imcms.persistence.entity.Menu; import com.imcode.imcms.persistence.entity.MenuItem; import com.imcode.imcms.persistence.entity.Meta; import com.imcode.imcms.persistence.entity.RestrictedPermissionJPA; import com.imcode.imcms.persistence.entity.TextHistoryJPA; import com.imcode.imcms.persistence.entity.User; import com.imcode.imcms.persistence.entity.Version; import com.imcode.imcms.util.function.TernaryFunction; import imcode.server.Imcms; import imcode.server.user.UserDomainObject; import imcode.util.DateConstants; import imcode.util.ImcmsImageUtils; import imcode.util.image.Format; import imcode.util.image.Resize; import lombok.SneakyThrows; import org.apache.commons.io.FilenameUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.Resource; import java.io.File; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; import java.util.function.UnaryOperator; import java.util.stream.Collectors; import java.util.stream.IntStream; import static com.imcode.imcms.persistence.entity.Meta.DisabledLanguageShowMode.SHOW_IN_DEFAULT_LANGUAGE; import static imcode.server.document.DocumentDomainObject.DOCUMENT_PROPERTIES__IMCMS_DOCUMENT_ALIAS; /** * Configuration class for mapping DTO -> JPA and vice versa, but not only. */ @Configuration class MappingConfig { @Bean public BiFunction<MenuItem, Language, MenuItemDTO> menuItemToDTO(DocumentMenuService documentMenuService) { return new BiFunction<MenuItem, Language, MenuItemDTO>() { @Override public MenuItemDTO apply(MenuItem menuItem, Language language) { final MenuItemDTO menuItemDTO = documentMenuService.getMenuItemDTO(menuItem.getDocumentId(), language); final List<MenuItemDTO> children = menuItem.getChildren() .stream() .map(menuItemChild -> this.apply(menuItemChild, language)) .collect(Collectors.toList()); menuItemDTO.setChildren(children); return menuItemDTO; } }; } @Bean public UnaryOperator<MenuItem> toMenuItemsWithoutId() { return new UnaryOperator<MenuItem>() { @Override public MenuItem apply(MenuItem menuItem) { final MenuItem newMenuItem = new MenuItem(); newMenuItem.setDocumentId(menuItem.getDocumentId()); newMenuItem.setSortOrder(menuItem.getSortOrder()); final Set<MenuItem> newChildren = menuItem.getChildren() .stream() .map(this) .collect(Collectors.toCollection(LinkedHashSet::new)); newMenuItem.setChildren(newChildren); return newMenuItem; } }; } @Bean public BiFunction<MenuItem, Language, MenuItemDTO> menuItemToMenuItemDtoWithLang( CommonContentService commonContentService, BiFunction<MenuItem, Language, MenuItemDTO> menuItemToDTO, LanguageService languageService, VersionService versionService, DocumentMenuService documentMenuService ) { return new BiFunction<MenuItem, Language, MenuItemDTO>() { @Override public MenuItemDTO apply(final MenuItem menuItem, final Language language) { final Integer docId = menuItem.getDocumentId(); final Version latestVersion = versionService.getLatestVersion(docId); final List<CommonContent> enabledCommonContents = commonContentService.getByVersion(latestVersion) .stream() .filter(CommonContent::isEnabled) .collect(Collectors.toList()); if (enabledCommonContents.size() == 0) { return null; } final boolean isLanguageDisabled = enabledCommonContents.stream() .noneMatch(commonContent -> commonContent.getLanguage().getCode().equals(language.getCode())); final Language menuLanguage; if (isLanguageDisabled) { final boolean isShowInDefaultLanguage = documentMenuService.getDisabledLanguageShowMode(docId) .equals(SHOW_IN_DEFAULT_LANGUAGE); if (isShowInDefaultLanguage) { menuLanguage = languageService.findByCode(Imcms.getUser().getLanguage()); } else { return null; } } else { menuLanguage = language; } final MenuItemDTO menuItemDTO = menuItemToDTO.apply(menuItem, menuLanguage); final List<MenuItemDTO> children = menuItem.getChildren() .stream() .map(menuItem1 -> this.apply(menuItem1, language)) .filter(Objects::nonNull) .collect(Collectors.toList()); menuItemDTO.setChildren(children); return menuItemDTO; } }; } @Bean public BiFunction<Menu, Language, MenuDTO> menuToMenuDTO(BiFunction<MenuItem, Language, MenuItemDTO> menuItemToDTO) { return (menu, language) -> { final MenuDTO menuDTO = new MenuDTO(); menuDTO.setDocId(menu.getVersion().getDocId()); menuDTO.setMenuIndex(menu.getNo()); menuDTO.setMenuItems(menu.getMenuItems() .stream() .map(menuItem -> menuItemToDTO.apply(menuItem, language)).collect(Collectors.toList())); return menuDTO; }; } @Bean public Function<MenuItemDTO, MenuItem> menuItemDtoToMenuItem() { return new Function<MenuItemDTO, MenuItem>() { @Override public MenuItem apply(MenuItemDTO menuItemDTO) { final MenuItem menuItem = new MenuItem(); menuItem.setDocumentId(menuItemDTO.getDocumentId()); final Set<MenuItem> children = menuItemDtoListToMenuItemList(this).apply(menuItemDTO.getChildren()); menuItem.setChildren(children); return menuItem; } }; } @Bean public Function<List<MenuItemDTO>, Set<MenuItem>> menuItemDtoListToMenuItemList(Function<MenuItemDTO, MenuItem> menuItemDtoToMenuItem) { return menuItemDtoList -> IntStream.range(0, menuItemDtoList.size()) .mapToObj(i -> { final MenuItem menuItem = menuItemDtoToMenuItem.apply(menuItemDtoList.get(i)); menuItem.setSortOrder(i + 1); return menuItem; }) .collect(Collectors.toCollection(LinkedHashSet::new)); } @Bean public Function<Image, ImageDTO> imageToImageDTO(@Value("${ImageUrl}") String imagesPath) { return image -> { final ImageDTO dto = new ImageDTO(); dto.setIndex(image.getIndex()); dto.setName(image.getName()); dto.setDocId(image.getVersion().getDocId()); dto.setLangCode(image.getLanguage().getCode()); dto.setPath(image.getUrl()); dto.setAllLanguages(image.isAllLanguages()); dto.setExifInfo(ImcmsImageUtils.getExifInfo(image.getUrl())); final boolean filenameExists = (image.getGeneratedFilename() != null) && !image.getGeneratedFilename().equals(""); final String generatedFilePath = filenameExists ? (imagesPath + "generated/" + image.getGeneratedFilename()) : ""; dto.setGeneratedFilePath(generatedFilePath); dto.setGeneratedFilename(image.getGeneratedFilename()); dto.setFormat(image.getFormat()); dto.setHeight(image.getHeight()); dto.setWidth(image.getWidth()); Optional.ofNullable(image.getLoopEntryRef()).map(LoopEntryRefDTO::new).ifPresent(dto::setLoopEntryRef); dto.setCropRegion(new ImageCropRegionDTO(image.getCropRegion())); dto.setInText(image.isInText()); dto.setAlternateText(image.getAlternateText()); dto.setLinkUrl(image.getLinkUrl()); dto.setBorder(image.getBorder()); dto.setAlign(image.getAlign()); dto.setLowResolutionUrl(image.getLowResolutionUrl()); dto.setSpaceAround(image.getSpaceAround()); dto.setTarget(image.getTarget()); dto.setType(image.getType()); dto.setRotateAngle(image.getRotateAngle()); dto.setRotateDirection(ImageData.RotateDirection.fromAngle(image.getRotateAngle())); dto.setArchiveImageId(image.getArchiveImageId()); dto.setResize(Resize.getByOrdinal(image.getResize())); return dto; }; } @Bean public TernaryFunction<ImageDTO, Version, Language, Image> imageDtoToImage() { return (imageDTO, version, language) -> { final Image image = new Image(); final String path = imageDTO.getPath(); image.setUrl(!path.isEmpty() && path.startsWith("/") ? path.substring(1) : path); image.setIndex(imageDTO.getIndex()); image.setVersion(version); image.setLanguage(new LanguageJPA(language)); image.setHeight(imageDTO.getHeight()); image.setWidth(imageDTO.getWidth()); image.setName(imageDTO.getName()); image.setGeneratedFilename(imageDTO.getGeneratedFilename()); Optional.ofNullable(imageDTO.getLoopEntryRef()).map(LoopEntryRefJPA::new).ifPresent(image::setLoopEntryRef); image.setFormat(imageDTO.getFormat()); image.setCropRegion(new ImageCropRegionJPA(imageDTO.getCropRegion())); image.setAllLanguages(imageDTO.isAllLanguages()); image.setInText(imageDTO.isInText()); image.setAlternateText(imageDTO.getAlternateText()); image.setLinkUrl(imageDTO.getLinkUrl()); image.setBorder(imageDTO.getBorder()); image.setAlign(imageDTO.getAlign()); image.setLowResolutionUrl(imageDTO.getLowResolutionUrl()); image.setSpaceAround(imageDTO.getSpaceAround()); image.setTarget(imageDTO.getTarget()); image.setType(imageDTO.getName().isEmpty() ? imageDTO.getType() : 0); image.setRotateAngle(imageDTO.getRotateDirection().toAngle()); image.setArchiveImageId(imageDTO.getArchiveImageId()); image.setResize(imageDTO.getResize() == null ? 0 : imageDTO.getResize().getOrdinal()); return image; }; } @Bean public Function<DocumentDTO, Meta> documentDtoToMeta(CategoryService categoryService) { return documentDTO -> { final Meta meta = new Meta(); final Integer version = documentDTO.getCurrentVersion().getId(); meta.setId(documentDTO.getId()); meta.setDefaultVersionNo(version); // fixme: save or check version first meta.setPublicationStatus(documentDTO.getPublicationStatus()); meta.setTarget(documentDTO.getTarget()); meta.setDocumentType(documentDTO.getType()); meta.setKeywords(documentDTO.getKeywords()); // todo: check publication status and save here final AuditDTO publication = documentDTO.getPublished(); meta.setPublisherId(publication.getId()); meta.setPublicationStartDatetime(publication.getFormattedDate()); final AuditDTO publicationEnd = documentDTO.getPublicationEnd(); meta.setDepublisherId(publicationEnd.getId()); meta.setPublicationEndDatetime(publicationEnd.getFormattedDate()); final AuditDTO archivation = documentDTO.getArchived(); meta.setArchiverId(archivation.getId()); meta.setArchivedDatetime(archivation.getFormattedDate()); final UserDomainObject currentUser = Imcms.getUser(); // save creator to version too final AuditDTO creation = documentDTO.getCreated(); final Integer creatorId = Optional.ofNullable(creation.getId()).orElseGet(currentUser::getId); meta.setCreatorId(creatorId); final Date currentDateTime = new Date(); final Date createdDatetime = ((creation.getDate() == null) || (creation.getTime() == null)) ? currentDateTime : creation.getFormattedDate(); meta.setCreatedDatetime(createdDatetime); final AuditDTO modification = documentDTO.getModified(); final Integer modifierId = Optional.ofNullable(modification.getId()).orElseGet(currentUser::getId); meta.setModifierId(modifierId); final Date modifiedDatetime = ((modification.getDate() == null) || (modification.getTime() == null)) ? currentDateTime : modification.getFormattedDate(); meta.setModifiedDatetime(modifiedDatetime); meta.getProperties().put(DOCUMENT_PROPERTIES__IMCMS_DOCUMENT_ALIAS, documentDTO.getAlias()); meta.setDisabledLanguageShowMode(documentDTO.getDisabledLanguageShowMode()); meta.setSearchDisabled(documentDTO.isSearchDisabled()); final Set<Category> categories = documentDTO.getCategories() .stream() .map(categoryDTO -> categoryService.getById(categoryDTO.getId()).map(CategoryJPA::new)) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toSet()); meta.setCategories(categories); meta.setLinkableByOtherUsers(true); // fixme: not sure what to do with this meta.setLinkedForUnauthorizedUsers(true); // fixme: not sure what to do with this meta.setRoleIdToPermission(documentDTO.getRoleIdToPermission()); final Set<RestrictedPermissionJPA> restrictedPermissions = documentDTO.getRestrictedPermissions() .stream() .map(RestrictedPermissionJPA::new) .collect(Collectors.toSet()); meta.setRestrictedPermissions(restrictedPermissions); return meta; }; } @Bean public TernaryFunction<Meta, Version, List<CommonContent>, DocumentDTO> documentMapping(UserService userService) { final BiFunction<Supplier<Integer>, Supplier<Date>, AuditDTO> auditDtoCreator = (auditorIdSupplier, auditedDateSupplier) -> { final AuditDTO audit = new AuditDTO(); final Integer userId = auditorIdSupplier.get(); audit.setDateTime(auditedDateSupplier.get()); if (userId != null) { audit.setId(userId); audit.setBy(userService.getUser(userId).getLogin()); } return audit; }; return (meta, latestVersion, commonContents) -> { final DocumentDTO dto = new DocumentDTO(); final Integer metaId = meta.getId(); dto.setId(metaId); dto.setTarget(meta.getTarget()); dto.setAlias(meta.getProperties().get(DOCUMENT_PROPERTIES__IMCMS_DOCUMENT_ALIAS)); dto.setPublicationStatus(meta.getPublicationStatus()); dto.setCommonContents(commonContents); dto.setPublished(auditDtoCreator.apply(meta::getPublisherId, meta::getPublicationStartDatetime)); dto.setPublicationEnd(auditDtoCreator.apply(meta::getDepublisherId, meta::getPublicationEndDatetime)); dto.setArchived(auditDtoCreator.apply(meta::getArchiverId, meta::getArchivedDatetime)); dto.setCreated(auditDtoCreator.apply(meta::getCreatorId, meta::getCreatedDatetime)); dto.setModified(auditDtoCreator.apply(meta::getModifierId, meta::getModifiedDatetime)); dto.setDisabledLanguageShowMode(meta.getDisabledLanguageShowMode()); dto.setCurrentVersion(AuditDTO.fromVersion(latestVersion)); dto.setSearchDisabled(meta.isSearchDisabled()); dto.setKeywords(meta.getKeywords()); dto.setRoleIdToPermission(meta.getRoleIdToPermission()); dto.setCategories(meta.getCategories()); dto.setRestrictedPermissions(new HashSet<>(meta.getRestrictedPermissions())); dto.setProperties(meta.getProperties()); dto.setType(meta.getDocumentType()); return dto; }; } @Bean public Function<File, ImageFileDTO> fileToImageFileDTO(@Value("${ImagePath}") Resource imagesPath) { return new Function<File, ImageFileDTO>() { @Override @SneakyThrows public ImageFileDTO apply(File imageFile) { final ImageFileDTO imageFileDTO = new ImageFileDTO(); final String fileName = imageFile.getName(); imageFileDTO.setName(fileName); imageFileDTO.setFormat(Format.findFormat(FilenameUtils.getExtension(fileName))); final String relativePath = imageFile.getPath() .replace(imagesPath.getFile().getPath(), "") .replace("\\", "/"); imageFileDTO.setPath(relativePath); final Date lastModifiedDate = new Date(imageFile.lastModified()); final String formattedDate = DateConstants.DATETIME_DOC_FORMAT.format(lastModifiedDate); imageFileDTO.setUploaded(formattedDate); long fileSize = imageFile.length(); String suffix; final long k = 1000L; final long square = k * k; final long cube = square * k; if (fileSize >= cube) { suffix = "GB"; // I hope it's not the real case fileSize /= cube; } else if (fileSize >= square) { suffix = "MB"; fileSize /= square; } else if (fileSize >= k) { suffix = "kB"; fileSize /= k; } else { suffix = "B"; } imageFileDTO.setSize(String.valueOf(fileSize) + suffix); final java.awt.Dimension imageDimension = ImcmsImageUtils.getImageDimension(imageFile); if (imageDimension != null) { imageFileDTO.setWidth(imageDimension.width); imageFileDTO.setHeight(imageDimension.height); imageFileDTO.setResolution(String.valueOf(imageDimension.width) + "x" + imageDimension.height); } return imageFileDTO; } }; } @Bean public BiFunction<File, Boolean, ImageFolderDTO> fileToImageFolderDTO(Function<File, ImageFileDTO> fileToImageFileDTO, @Value("${ImagePath}") Resource imagesPath) { return new BiFunction<File, Boolean, ImageFolderDTO>() { @Override @SneakyThrows public ImageFolderDTO apply(File folderFile, Boolean isRoot) { final ImageFolderDTO imageFolderDTO = new ImageFolderDTO(); imageFolderDTO.setName(folderFile.getName()); final String relativePath = folderFile.getPath().replace(imagesPath.getFile().getPath(), ""); imageFolderDTO.setPath(relativePath); final ArrayList<ImageFolderDTO> subFolders = new ArrayList<>(); final ArrayList<ImageFileDTO> folderFiles = new ArrayList<>(); final File[] files = folderFile.listFiles(); if (files == null) { return imageFolderDTO; } for (File file : files) { if ((file.isDirectory())) { subFolders.add(this.apply(file, false)); } else if (isRoot && Format.isImage(FilenameUtils.getExtension(file.getName()))) { folderFiles.add(fileToImageFileDTO.apply(file)); } } imageFolderDTO.setFiles(folderFiles); imageFolderDTO.setFolders(subFolders); return imageFolderDTO; } }; } @Bean public Function<TextHistoryJPA, TextHistoryDTO> textHistoryJpaToTextHistoryDTO(final UserService userService) { return textHistoryJPA -> { final User modifierUser = userService.getUser(textHistoryJPA.getModifierId()); final TextHistoryDTO textHistoryDTO = new TextHistoryDTO(textHistoryJPA); textHistoryDTO.setLangCode(textHistoryJPA.getLangCode()); textHistoryDTO.setModifiedBy(new UserDTO(modifierUser)); return textHistoryDTO; }; } }
package com.jcabi.github.mock; import com.jcabi.aspects.Immutable; import com.jcabi.github.GitHubThread; import com.jcabi.github.Notification; import com.jcabi.github.Notifications; import org.apache.commons.lang3.NotImplementedException; @Immutable final class MkNotifications implements Notifications { @Override public Iterable<Notification> iterate() { throw new NotImplementedException("MkNotifications#iterate"); } @Override public Notification get(final int number) { throw new NotImplementedException("MkNotifications#get"); } @Override public void markAsRead() { // Will be implemented later } @Override public GitHubThread thread(final int number) { return null; } }
package com.lenis0012.bukkit.ls; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.command.CommandExecutor; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import com.lenis0012.bukkit.ls.commands.AdminCommand; import com.lenis0012.bukkit.ls.commands.ChangePassCommand; import com.lenis0012.bukkit.ls.commands.LoginCommand; import com.lenis0012.bukkit.ls.commands.LogoutCommand; import com.lenis0012.bukkit.ls.commands.RegisterCommand; import com.lenis0012.bukkit.ls.commands.RmPassCommand; import com.lenis0012.bukkit.ls.data.Converter; import com.lenis0012.bukkit.ls.data.Converter.FileType; import com.lenis0012.bukkit.ls.data.DataManager; import com.lenis0012.bukkit.ls.data.MySQL; import com.lenis0012.bukkit.ls.data.SQLite; import com.lenis0012.bukkit.ls.encryption.EncryptionType; import com.lenis0012.bukkit.ls.util.Metrics; import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; public class LoginSecurity extends JavaPlugin { public DataManager data; public static LoginSecurity instance; public Map<String, Boolean> AuthList = new HashMap<String, Boolean>(); public Map<String, Location> loginLocations = new HashMap<String, Location>(); public List<String> messaging = new ArrayList<String>(); public boolean required, blindness, sesUse, timeUse, messager, spawntp, godMode; public int sesDelay, timeDelay; public Logger log = Logger.getLogger("Minecraft"); public ThreadManager thread; public String prefix; public EncryptionType hasher; public Map<String, CommandExecutor> commandMap = new HashMap<String, CommandExecutor>(); public static int PHP_VERSION; public static String encoder; private static String metadataKey = "LS_oldGameMode"; @Override public void onEnable() { //setup quickcalls FileConfiguration config = this.getConfig(); PluginManager pm = this.getServer().getPluginManager(); //setup config config.addDefault("settings.password-required", false); config.addDefault("settings.encryption", "MD5"); config.addDefault("settings.encoder", "UTF-8"); config.addDefault("settings.PHP_VERSION", 4); config.addDefault("settings.messager-api", true); config.addDefault("settings.blindness", true); config.addDefault("settings.godMode", true); config.addDefault("settings.fake-location", false); config.addDefault("settings.session.use", true); config.addDefault("settings.session.timeout (sec)", 60); config.addDefault("settings.timeout.use", true); config.addDefault("settings.timeout.timeout (sec)", 60); config.addDefault("settings.table prefix", "ls_"); config.addDefault("MySQL.use", false); config.addDefault("MySQL.host", "localhost"); config.addDefault("MySQL.port", 3306); config.addDefault("MySQL.database", "LoginSecurity"); config.addDefault("MySQL.username", "root"); config.addDefault("MySQL.password", "password"); config.options().copyDefaults(true); saveConfig(); //intalize fields instance = (LoginSecurity)pm.getPlugin("LoginSecurity"); messager = config.getBoolean("settings.messager-api", false); prefix = config.getString("settings.table prefix"); data = this.getDataManager(config, "users.db"); data.openConnection(); thread = new ThreadManager(this); thread.startMsgTask(); required = config.getBoolean("settings.password-required"); blindness = config.getBoolean("settings.blindness"); godMode = config.getBoolean("settings.godMode"); spawntp = config.getBoolean("settings.fake-location"); sesUse = config.getBoolean("settings.session.use", true); sesDelay = config.getInt("settings.session.timeout (sec)", 60); timeUse = config.getBoolean("settings.timeout.use", true); timeDelay = config.getInt("settings.timeout.timeout (sec)", 60); PHP_VERSION = config.getInt("settings.PHP_VERSION", 4); this.hasher = EncryptionType.fromString(config.getString("settings.encryption")); String enc = config.getString("settings.encoder"); if(enc.equalsIgnoreCase("utf-16")) encoder = "UTF-16"; else encoder = "UTF-8"; if(sesUse) thread.startSessionTask(); if(timeUse) thread.startTimeoutTask(); thread.startMainTask(); thread.startMsgTask(); //convert everything this.checkConverter(); //register events if(messager) { Bukkit.getMessenger().registerIncomingPluginChannel(this, "LoginSecurity", new LoginMessager(this)); Bukkit.getMessenger().registerOutgoingPluginChannel(this, "LoginSecurity"); } pm.registerEvents(new LoginListener(this), this); this.registerCommands(); //clear old config if(config.contains("options")) { config.set("options", null); this.saveConfig(); } //metrics try { Metrics metrics = new Metrics(this); metrics.start(); if(config.getBoolean("settings.update-checker")) { //TODO: Recode update checker } } catch(Exception e) { log.info("[LoginSecurity] Failed sending stats to mcstats.org"); } } @Override public void onDisable() { if(data != null) data.closeConnection(); if(thread != null) { thread.stopMsgTask(); thread.stopSessionTask(); } // TODO: Fix reloads for connected but un-aunthenticated players } private DataManager getDataManager(FileConfiguration config, String fileName) { if(config.getBoolean("MySQL.use")) { return new MySQL(config, "users"); } else { return new SQLite(new File(this.getDataFolder(), fileName)); } } private void checkConverter() { PluginManager pm = this.getServer().getPluginManager(); File file; file = new File(this.getDataFolder(), "data.yml"); if(file.exists()) { Converter conv = new Converter(FileType.YAML, file); conv.convert(); } file = new File(this.getDataFolder(), "data.db"); if(file.exists() && data instanceof MySQL) { Converter conv = new Converter(FileType.SQLite, file); conv.convert(); } if(data instanceof MySQL) { MySQL mysql = (MySQL)data; if(mysql.tableExists("passwords")) { Converter conv = new Converter(FileType.OldToNewMySQL, null); conv.convert(); } } Plugin xAuth = pm.getPlugin("xAuth"); if(xAuth != null) { if(xAuth.isEnabled()) { Converter conv = new Converter(FileType.xAuth, null); conv.convert(); log.info("[LoginSecurity] Converted data from xAuth to LoginSecurity"); } } } public void registerCommands() { this.commandMap.clear(); this.commandMap.put("login", new LoginCommand()); this.commandMap.put("register", new RegisterCommand()); this.commandMap.put("changepass", new ChangePassCommand()); this.commandMap.put("rmpass", new RmPassCommand()); this.commandMap.put("logout", new LogoutCommand()); this.commandMap.put("lac", new AdminCommand()); for(Entry<String, CommandExecutor> entry : this.commandMap.entrySet()) { String cmd = entry.getKey(); CommandExecutor ex = entry.getValue(); this.getCommand(cmd).setExecutor(ex); } } public boolean checkLastIp(Player player) { String name = player.getName().toLowerCase(); if(data.isRegistered(name)) { String lastIp = data.getIp(name); String currentIp = player.getAddress().getAddress().toString(); return lastIp.equalsIgnoreCase(currentIp); } return false; } public void playerJoinPrompt(final Player player, final String name) { if(sesUse && thread.getSession().containsKey(name) && checkLastIp(player)) { player.sendMessage(ChatColor.GREEN+"Extended session from last login"); return; } else if(data.isRegistered(name)) { AuthList.put(name, false); if(!messager) player.sendMessage(ChatColor.RED+"Please login using /login <password>"); } else if(required) { AuthList.put(name, true); if(!messager) player.sendMessage(ChatColor.RED+"Please register using /register <password>"); } else return; //Send data to messager API if(messager) { messaging.add(name); Bukkit.getScheduler().runTaskLater(this, new Runnable() { @Override public void run() { if(messaging.contains(name)) { boolean register = AuthList.get(name); messaging.remove(name); if(register) player.sendMessage(ChatColor.RED+"Please register using /register <password>"); else player.sendMessage(ChatColor.RED+"Please login using /login <password>"); } else sendCustomPayload(player, "Q_LOGIN"); } }, 20); } debilitatePlayer(player, name, false); } public void debilitatePlayer(Player player, String name, boolean logout) { if (godMode && !logout) { player.setMetadata(metadataKey, new FixedMetadataValue(this, player.getGameMode().getValue())); player.setGameMode(GameMode.CREATIVE); } if (blindness) { player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 1728000, 15)); player.addPotionEffect(new PotionEffect(PotionEffectType.NIGHT_VISION, 178000, 15)); } if (spawntp && !logout) { loginLocations.put(name, player.getLocation().clone()); player.teleport(player.getWorld().getSpawnLocation()); } } public void rehabPlayer(Player player, String name) { player.setGameMode(GameMode.getByValue(player.getMetadata(metadataKey).get(0).asInt())); player.removePotionEffect(PotionEffectType.BLINDNESS); player.removePotionEffect(PotionEffectType.NIGHT_VISION); if (spawntp) { if(loginLocations.containsKey(name)) player.teleport(loginLocations.remove(name)); } } public void sendCustomPayload(Player player, String msg) { if(!player.getListeningPluginChannels().contains(this.getName())) return; player.sendPluginMessage(this, this.getName(), msg.getBytes()); } }
package com.lenis0012.bukkit.ls; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.command.CommandExecutor; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import com.lenis0012.bukkit.ls.commands.AdminCommand; import com.lenis0012.bukkit.ls.commands.ChangePassCommand; import com.lenis0012.bukkit.ls.commands.LoginCommand; import com.lenis0012.bukkit.ls.commands.LogoutCommand; import com.lenis0012.bukkit.ls.commands.RegisterCommand; import com.lenis0012.bukkit.ls.commands.RmPassCommand; import com.lenis0012.bukkit.ls.data.Converter; import com.lenis0012.bukkit.ls.data.Converter.FileType; import com.lenis0012.bukkit.ls.data.DataManager; import com.lenis0012.bukkit.ls.data.MySQL; import com.lenis0012.bukkit.ls.data.SQLite; import com.lenis0012.bukkit.ls.encryption.EncryptionType; import com.lenis0012.bukkit.ls.util.Metrics; import org.bukkit.ChatColor; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; public class LoginSecurity extends JavaPlugin { public DataManager data; public static LoginSecurity instance; public Map<String, Boolean> AuthList = new HashMap<String, Boolean>(); public Map<String, Location> loginLocations = new HashMap<String, Location>(); public List<String> messaging = new ArrayList<String>(); public boolean required, blindness, sesUse, timeUse, messager, spawntp; public int sesDelay, timeDelay; public Logger log = Logger.getLogger("Minecraft"); public ThreadManager thread; public String prefix; public EncryptionType hasher; public Map<String, CommandExecutor> commandMap = new HashMap<String, CommandExecutor>(); public static int PHP_VERSION; public static String encoder; private static String metadataKey = "LS_oldGameMode"; @Override public void onEnable() { //setup quickcalls FileConfiguration config = this.getConfig(); PluginManager pm = this.getServer().getPluginManager(); //setup config config.addDefault("settings.password-required", false); config.addDefault("settings.encryption", "MD5"); config.addDefault("settings.encoder", "UTF-8"); config.addDefault("settings.PHP_VERSION", 4); config.addDefault("settings.messager-api", true); config.addDefault("settings.blindness", true); config.addDefault("settings.fake-location", false); config.addDefault("settings.session.use", true); config.addDefault("settings.session.timeout (sec)", 60); config.addDefault("settings.timeout.use", true); config.addDefault("settings.timeout.timeout (sec)", 60); config.addDefault("settings.table prefix", "ls_"); config.addDefault("MySQL.use", false); config.addDefault("MySQL.host", "localhost"); config.addDefault("MySQL.port", 3306); config.addDefault("MySQL.database", "LoginSecurity"); config.addDefault("MySQL.username", "root"); config.addDefault("MySQL.password", "password"); config.options().copyDefaults(true); saveConfig(); //intalize fields instance = (LoginSecurity) pm.getPlugin("LoginSecurity"); messager = config.getBoolean("settings.messager-api", false); prefix = config.getString("settings.table prefix"); data = this.getDataManager(config, "users.db"); data.openConnection(); thread = new ThreadManager(this); thread.startMsgTask(); required = config.getBoolean("settings.password-required"); blindness = config.getBoolean("settings.blindness"); spawntp = config.getBoolean("settings.fake-location"); sesUse = config.getBoolean("settings.session.use", true); sesDelay = config.getInt("settings.session.timeout (sec)", 60); timeUse = config.getBoolean("settings.timeout.use", true); timeDelay = config.getInt("settings.timeout.timeout (sec)", 60); PHP_VERSION = config.getInt("settings.PHP_VERSION", 4); this.hasher = EncryptionType.fromString(config.getString("settings.encryption")); String enc = config.getString("settings.encoder"); if (enc.equalsIgnoreCase("utf-16")) { encoder = "UTF-16"; } else { encoder = "UTF-8"; } if (sesUse) { thread.startSessionTask(); } if (timeUse) { thread.startTimeoutTask(); } thread.startMainTask(); thread.startMsgTask(); //convert everything this.checkConverter(); //register events if (messager) { Bukkit.getMessenger().registerIncomingPluginChannel(this, "LoginSecurity", new LoginMessager(this)); Bukkit.getMessenger().registerOutgoingPluginChannel(this, "LoginSecurity"); } pm.registerEvents(new LoginListener(this), this); this.registerCommands(); //clear old config if (config.contains("options")) { config.set("options", null); this.saveConfig(); } //metrics try { Metrics metrics = new Metrics(this); metrics.start(); if (config.getBoolean("settings.update-checker")) { //TODO: Recode update checker } } catch (Exception e) { log.info("[LoginSecurity] Failed sending stats to mcstats.org"); } } @Override public void onDisable() { if (data != null) { data.closeConnection(); } if (thread != null) { thread.stopMsgTask(); thread.stopSessionTask(); } // TODO: Fix reloads for connected but un-aunthenticated players } private DataManager getDataManager(FileConfiguration config, String fileName) { if (config.getBoolean("MySQL.use")) { return new MySQL(config, "users"); } else { return new SQLite(new File(this.getDataFolder(), fileName)); } } private void checkConverter() { PluginManager pm = this.getServer().getPluginManager(); File file; file = new File(this.getDataFolder(), "data.yml"); if (file.exists()) { Converter conv = new Converter(FileType.YAML, file); conv.convert(); } file = new File(this.getDataFolder(), "data.db"); if (file.exists() && data instanceof MySQL) { Converter conv = new Converter(FileType.SQLite, file); conv.convert(); } if (data instanceof MySQL) { MySQL mysql = (MySQL) data; if (mysql.tableExists("passwords")) { Converter conv = new Converter(FileType.OldToNewMySQL, null); conv.convert(); } } Plugin xAuth = pm.getPlugin("xAuth"); if (xAuth != null) { if (xAuth.isEnabled()) { Converter conv = new Converter(FileType.xAuth, null); conv.convert(); log.info("[LoginSecurity] Converted data from xAuth to LoginSecurity"); } } } public void registerCommands() { this.commandMap.clear(); this.commandMap.put("login", new LoginCommand()); this.commandMap.put("register", new RegisterCommand()); this.commandMap.put("changepass", new ChangePassCommand()); this.commandMap.put("rmpass", new RmPassCommand()); this.commandMap.put("logout", new LogoutCommand()); this.commandMap.put("lac", new AdminCommand()); for (Entry<String, CommandExecutor> entry : this.commandMap.entrySet()) { String cmd = entry.getKey(); CommandExecutor ex = entry.getValue(); this.getCommand(cmd).setExecutor(ex); } } public boolean checkLastIp(Player player) { String name = player.getName().toLowerCase(); if (data.isRegistered(name)) { String lastIp = data.getIp(name); String currentIp = player.getAddress().getAddress().toString(); return lastIp.equalsIgnoreCase(currentIp); } return false; } public void playerJoinPrompt(final Player player, final String name) { if (sesUse && thread.getSession().containsKey(name) && checkLastIp(player)) { player.sendMessage(ChatColor.GREEN + "Extended session from last login"); return; } else if (data.isRegistered(name)) { AuthList.put(name, false); if (!messager) { player.sendMessage(ChatColor.RED + "Please login using /login <password>"); } } else if (required) { AuthList.put(name, true); if (!messager) { player.sendMessage(ChatColor.RED + "Please register using /register <password>"); } } else { return; } //Send data to messager API if (messager) { messaging.add(name); Bukkit.getScheduler().runTaskLater(this, new Runnable() { @Override public void run() { if (messaging.contains(name)) { boolean register = AuthList.get(name); messaging.remove(name); if (register) { player.sendMessage(ChatColor.RED + "Please register using /register <password>"); } else { player.sendMessage(ChatColor.RED + "Please login using /login <password>"); } } else { sendCustomPayload(player, "Q_LOGIN"); } } }, 20); } debilitatePlayer(player, name, false); } public void debilitatePlayer(Player player, String name, boolean logout) { if (blindness) { player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 1728000, 15)); } if (spawntp && !logout) { loginLocations.put(name, player.getLocation().clone()); player.teleport(player.getWorld().getSpawnLocation()); } } public void rehabPlayer(Player player, String name) { player.removePotionEffect(PotionEffectType.BLINDNESS); if (spawntp) { if (loginLocations.containsKey(name)) { Location fixedLocation = loginLocations.remove(name); fixedLocation.add(0, 0.2, 0); // fix for players falling into ground player.teleport(fixedLocation); } } // ensure that player does not drown after logging in player.setRemainingAir(player.getMaximumAir()); } public void sendCustomPayload(Player player, String msg) { if (!player.getListeningPluginChannels().contains(this.getName())) { return; } player.sendPluginMessage(this, this.getName(), msg.getBytes()); } }
package com.lingke.xvp.demo.utils; import org.springframework.web.context.request.RequestAttributes; import org.springframework.web.context.request.RequestContextHolder; import com.lingke.xvp.demo.XvpConstants; public class SessionUtil { public final static String SELLER_LOGIN_ID = "SELLER_LOGIN_ID"; public final static String USER_LOGIN_ID = "USER_LOGIN_ID"; public final static String SELLER_STORELOGIN_ID = "SELLER_STORELOGIN_ID"; public final static String USER_STORELOGIN_ID = "USER_STORELOGIN_ID"; public static void sellerLogin(Long value) { RequestContextHolder.getRequestAttributes().setAttribute( SELLER_LOGIN_ID, value, RequestAttributes.SCOPE_SESSION); } public static boolean checkSellerLogin() { return RequestContextHolder.getRequestAttributes().getAttribute( SELLER_LOGIN_ID, RequestAttributes.SCOPE_SESSION) != null; } public static void sellerSetStoreId(String value) { RequestContextHolder.getRequestAttributes().setAttribute( SELLER_STORELOGIN_ID, value, RequestAttributes.SCOPE_SESSION); } public static String sellerGetStoreId() { Object ob = RequestContextHolder.getRequestAttributes().getAttribute( SELLER_STORELOGIN_ID, RequestAttributes.SCOPE_SESSION); if (ob == null) { throw new RuntimeException(XvpConstants.ERROR_MESSAGE04); } return ob.toString(); } public static void userLogin(String value) { RequestContextHolder.getRequestAttributes().setAttribute(USER_LOGIN_ID, value, RequestAttributes.SCOPE_SESSION); } public static boolean checkUserLogin() { return RequestContextHolder.getRequestAttributes().getAttribute( USER_LOGIN_ID, RequestAttributes.SCOPE_SESSION) != null; } public static void userSetStoreId(String value) { RequestContextHolder.getRequestAttributes().setAttribute( USER_STORELOGIN_ID, value, RequestAttributes.SCOPE_SESSION); } public static String userGetStoreId() { Object ob = RequestContextHolder.getRequestAttributes().getAttribute( USER_STORELOGIN_ID, RequestAttributes.SCOPE_SESSION); if (ob == null) { throw new RuntimeException(XvpConstants.ERROR_MESSAGE04); } return ob.toString(); } }
package com.monkeyinabucket.forge.blink; import java.io.*; import java.util.ArrayList; import cpw.mods.fml.relauncher.Side; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.server.MinecraftServer; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.event.world.BlockEvent; import net.minecraftforge.event.world.WorldEvent; import com.monkeyinabucket.forge.blink.block.RuneCore; import com.monkeyinabucket.forge.blink.command.BlinkList; import com.monkeyinabucket.forge.blink.command.BlinkLoad; import com.monkeyinabucket.forge.blink.command.BlinkSave; import com.monkeyinabucket.forge.blink.rune.BlinkRune; import com.monkeyinabucket.forge.blink.rune.RuneManager; import com.monkeyinabucket.forge.world.Location; import com.monkeyinabucket.forge.world.SerializableLocation; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLServerStartedEvent; import cpw.mods.fml.common.event.FMLServerStartingEvent; import cpw.mods.fml.common.event.FMLServerStoppingEvent; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.registry.GameRegistry; /** * Main class for the Blink plugin. Handles the enabling and disabling process, * provides centralized logging features, and acts as the primary container for * all objects in the plugin. * * TODO: Handle events that may change or break a rune: ice melt, piston push, block placed in air signature slot, grass grow, etc. */ @Mod(modid = "Blink", name = "Blink", version = "3.0.0") public class Blink { /** Flag to track whether the runes save file has already been loaded */ private Boolean runeFileLoaded = false; /** The name of the rune save file. This will be stored in the world folder */ @SuppressWarnings("FieldCanBeLocal") private static String SAVE_FILE_NAME = "blink.sav"; /** The data file that will be used to save and load rune locations */ protected String saveFile; /** The primary object used to manage runes in the plugin */ protected final RuneManager runeManager = RuneManager.getInstance(); public static Block runecore; @Instance(value = "Blink") public static Blink instance; @EventHandler public void onServerLoadStart(FMLServerStartingEvent event) { event.registerServerCommand(new BlinkList()); event.registerServerCommand(new BlinkLoad()); event.registerServerCommand(new BlinkSave()); } @EventHandler public void preInit(FMLPreInitializationEvent event) { runecore = new RuneCore(Material.iron); runecore.setHarvestLevel("pickaxe", 3); } /** * Called when this Plugin is enabled. Initializes the plugin and loads all saved Runes. */ @EventHandler public void onInit(FMLInitializationEvent event) { GameRegistry.registerBlock(runecore, "runecore"); ItemStack ironStack = new ItemStack(Items.iron_ingot); ItemStack emeraldStack = new ItemStack(Items.emerald); ItemStack obsidianStack = new ItemStack(Blocks.obsidian); GameRegistry.addRecipe( new ItemStack(runecore), "xxx", "yzy", "xxx", 'x', ironStack, 'y', emeraldStack, 'z', obsidianStack ); } /** * Event handler for the Server Started Event. Sets up the various event * listeners for the mod. * * @param event The server started event. */ @EventHandler public void onServerStarted(FMLServerStartedEvent event) { MinecraftForge.EVENT_BUS.register(this); FMLCommonHandler.instance().bus().register(this); saveFile = "saves" + "/" + MinecraftServer.getServer().getFolderName() + '/' + SAVE_FILE_NAME; } /** * Called when this mod is disabled. Shuts down the mod, and saves all Runes. */ @EventHandler public void unload(FMLServerStoppingEvent event) { saveRunes(); } /** * Loads the runes that have been saved to disk. This should be called once * when the World is first loaded (Not the Dimension). Calling this a second * time would result in duplicate runes being registered. */ public void loadRunes() { runeManager.clearRunes(); ArrayList<SerializableLocation> locs; ObjectInputStream stream = null; try { File file = new File(saveFile); stream = new ObjectInputStream(new FileInputStream(saveFile)); locs = (ArrayList<SerializableLocation>) stream.readObject(); } catch (FileNotFoundException ex) { locs = new ArrayList<SerializableLocation>(); } catch (ClassNotFoundException ex) { Logger.severe(ex.getMessage()); return; } catch (IOException ex) { Logger.severe(ex.getMessage()); return; } finally { try { if (stream != null) { stream.close(); } } catch (IOException ex) { Logger.severe(ex.getMessage()); } } MinecraftServer server = MinecraftServer.getServer(); for (SerializableLocation savedLoc : locs) { Location loc = savedLoc.getLocation(server); BlinkRune rune = new BlinkRune(loc); runeManager.addRune(rune); } runeFileLoaded = true; } /** * Saves the currently registered runes to a save file in the world folder. */ public void saveRunes() { ArrayList<SerializableLocation> locs = runeManager.getLocationsForSave(); ObjectOutputStream os = null; try { os = new ObjectOutputStream(new FileOutputStream(saveFile)); os.writeObject(locs); os.flush(); os.close(); } catch (IOException ex) { Logger.severe(ex.getMessage()); } finally { try { if (os != null) { os.close(); } } catch (IOException ex) { Logger.severe(ex.getMessage()); } } } /** * Handles Dimension load events (Forge calls Dimensions Worlds). Checks to * ensure that the rune save file is loaded. * * The file will only be loaded if the world is not remote. If the world is * remote, then the server is responsible for saving and loading the runes. * * @param event The world load event. */ @SubscribeEvent public void onWorldLoad(WorldEvent.Load event) { if (runeFileLoaded) { return; } if (FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER) { return; } loadRunes(); } /** * Handles BlockBreakEvents. If the broken Block is part of a BlinkRune, this * method will invoke the BlinkRunes onDestroy event, and remove the BlinkRune * from the RuneManager. * * FIXME There's a bug where if the player is OP, and they attack a block that's part of a rune, the onBlockBreak event doesn't fire. * * @param event the event that describes the block break. */ @SubscribeEvent public void onBlockBreak(BlockEvent.BreakEvent event) { // The server will handle the event if the world is remote if (event.world.isRemote) { return; } if (event.isCanceled()) { return; } Location loc = new Location(event); BlinkRune rune = runeManager.getRuneByPart(loc); if (rune == null) { return; } rune.onDestroy(); } /** * Handles BlockDamageEvents. If the damaged Block is part of a BlinkRune, * this method will call the BlinkRune's onDamage method. * * @param event the event that describes the block damage. */ public void onBlockDamage(PlayerInteractEvent event) { if (event.isCanceled()) { return; } Location loc = new Location(event); BlinkRune rune = runeManager.getRuneByPart(loc); if (rune == null) { return; } rune.onDamage(); } /** * Handles PlayerInteractEvents. If the player right clicks on a block * (excluding placing a block), then this method will determine if a new * BlinkRune is being created, or an existing BlinkRune is being activated. * * @param event the PlayerInteractEvent */ @SubscribeEvent public void onPlayerInteract(PlayerInteractEvent event) { // The server will handle the event if the world is remote if (event.world.isRemote) { return; } if (event.action == PlayerInteractEvent.Action.LEFT_CLICK_BLOCK) { onBlockDamage(event); } } }
package com.paulhammant.ngwebdriver; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.NoSuchElementException; import java.util.List; public class ByAngular { protected final JavascriptExecutor jse; public ByAngular(JavascriptExecutor jse) { this.jse = jse; } public ByAngularRepeater repeater(String repeater) { return new ByAngularRepeater(jse, repeater); } public ByAngularBinding binding(String binding) { return new ByAngularBinding(jse, binding); } public ByAngularModel model(String model) { return new ByAngularModel(jse, model); } public abstract static class BaseBy extends By { protected final JavascriptExecutor jse; public BaseBy(JavascriptExecutor jse) { this.jse = jse; } protected final void errorIfNull(Object o) { if (o == null || o instanceof List && ((List) o).size() == 0) { throw new NoSuchElementException(this + " didn't have any matching elements at this place in the DOM"); } } } }
package com.relayrides.pushy.apns; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.util.concurrent.Future; import java.lang.Thread.UncaughtExceptionHandler; import java.security.KeyStore; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Vector; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p>A {@code PushManager} is the main public-facing point of interaction with APNs. {@code PushManager}s manage the * queue of outbound push notifications and manage connections to the various APNs servers. {@code PushManager}s should * always be created using the {@link PushManagerFactory} class.</p> * * @author <a href="mailto:jon@relayrides.com">Jon Chambers</a> * * @see PushManagerFactory */ public class PushManager<T extends ApnsPushNotification> { private final BlockingQueue<T> queue; private final LinkedBlockingQueue<T> retryQueue; private final ApnsEnvironment environment; private final KeyStore keyStore; private final char[] keyStorePassword; private final int concurrentConnectionCount; private final ArrayList<ApnsClientThread<T>> clientThreads; private final ThreadExceptionHandler<T> threadExceptionHandler; private final Vector<RejectedNotificationListener<? super T>> rejectedNotificationListeners; private final NioEventLoopGroup workerGroup; private final boolean shouldShutDownWorkerGroup; private final ExecutorService rejectedNotificationExecutorService; private boolean started = false; private boolean shutDown = false; private boolean shutDownFinished = false; private final Logger log = LoggerFactory.getLogger(PushManager.class); public static class ThreadExceptionHandler<T extends ApnsPushNotification> implements UncaughtExceptionHandler { private final Logger log = LoggerFactory.getLogger(ThreadExceptionHandler.class); final PushManager<T> manager; public ThreadExceptionHandler(final PushManager<T> manager) { this.manager = manager; } public void uncaughtException(final Thread t, final Throwable e) { assert t instanceof ApnsClientThread; log.error(String.format("%s died unexpectedly. Please file a bug with the exception details.", t.getName()), e); this.manager.replaceThread(t); } } protected PushManager(final ApnsEnvironment environment, final KeyStore keyStore, final char[] keyStorePassword, final int concurrentConnectionCount, final NioEventLoopGroup workerGroup, final BlockingQueue<T> queue) { if (environment.isTlsRequired() && keyStore == null) { throw new IllegalArgumentException("Must include a non-null KeyStore for environments that require TLS."); } this.queue = queue != null ? queue : new LinkedBlockingQueue<T>(); this.retryQueue = new LinkedBlockingQueue<T>(); this.rejectedNotificationListeners = new Vector<RejectedNotificationListener<? super T>>(); this.environment = environment; this.keyStore = keyStore; this.keyStorePassword = keyStorePassword; this.concurrentConnectionCount = concurrentConnectionCount; this.clientThreads = new ArrayList<ApnsClientThread<T>>(this.concurrentConnectionCount); this.threadExceptionHandler = new ThreadExceptionHandler<T>(this); this.rejectedNotificationExecutorService = Executors.newSingleThreadExecutor(); if (workerGroup != null) { this.workerGroup = workerGroup; this.shouldShutDownWorkerGroup = false; } else { this.workerGroup = new NioEventLoopGroup(); this.shouldShutDownWorkerGroup = true; } } /** * Returns the environment in which this {@code PushManager} is operating. * * @return the environment in which this {@code PushManager} is operating */ public ApnsEnvironment getEnvironment() { return this.environment; } /** * Returns the {@code KeyStore} containing the client certificate to be presented to TLS-enabled APNs servers. * * @return the {@code KeyStore} containing the client certificate to be presented to TLS-enabled APNs servers */ public KeyStore getKeyStore() { return this.keyStore; } /** * Returns the key to unlock the {@code KeyStore} for this {@code PushManager}. * * @return the key to unlock the {@code KeyStore} for this {@code PushManager} */ public char[] getKeyStorePassword() { return this.keyStorePassword; } public synchronized void start() { if (this.isStarted()) { throw new IllegalStateException("Push manager has already been started."); } if (this.isShutDown()) { throw new IllegalStateException("Push manager has already been shut down and may not be restarted."); } for (int i = 0; i < this.concurrentConnectionCount; i++) { this.createAndActivateClientThread(); } this.started = true; } /** * <p>Enqueues a push notification for re-transmission to the APNs service. Notifications may not be sent to APNs * immediately, and delivery is not guaranteed by APNs, but notifications rejected by APNs for specific reasons * will be passed to registered {@link RejectedNotificationListener}s. Notifications that are to be re-transmitted * are given priority over &quot;new&quot; notifications, but are otherwise treated identically.</p> * * @param notification the notification to enqueue for re-transmission * * @see PushManager#registerRejectedNotificationListener(RejectedNotificationListener) */ protected void enqueuePushNotificationForRetry(final T notification) { this.retryQueue.add(notification); } /** * <p>Enqueues a collection of push notifications for re-transmission to the APNs service. Notifications may not be * sent to APNs immediately, and delivery is not guaranteed by APNs, but notifications rejected by APNs for * specific reasons will be passed to registered {@link RejectedNotificationListener}s. Notifications that are to * be re-transmitted are given priority over &quot;new&quot; notifications, but are otherwise treated identically.</p> * * @param notifications the notifications to enqueue for re-transmission * * @see PushManager#registerRejectedNotificationListener(RejectedNotificationListener) */ protected void enqueueAllNotificationsForRetry(final Collection<T> notifications) { this.retryQueue.addAll(notifications); } /** * Indicates whether this push manager has been started and not yet shut down. * * @return {@code true} if this push manager has been started and has not yet been shut down or {@code false} * otherwise */ public boolean isStarted() { if (this.shutDown) { return false; } else { return this.started; } } /** * Indicates whether this push manager has been shut down (or is in the process of shutting down). * * @return {@code true} if this push manager has been shut down or is in the process of shutting down or * {@code false} otherwise */ public boolean isShutDown() { return this.shutDown; } public synchronized List<T> shutdown() throws InterruptedException { return this.shutdown(0); } public synchronized List<T> shutdown(long timeout) throws InterruptedException { if (this.shutDown) { log.warn("Push manager has already been shut down; shutting down multiple times is harmless, but may " + "indicate a problem elsewhere."); } if (this.shutDownFinished) { // the same result without harm. final ArrayList<T> unsentNotifications = new ArrayList<T>(); unsentNotifications.addAll(this.retryQueue); unsentNotifications.addAll(this.getQueue()); return unsentNotifications; } if (!this.isStarted()) { throw new IllegalStateException("Push manager has not yet been started and cannot be shut down."); } this.shutDown = true; for (final ApnsClientThread<T> clientThread : this.clientThreads) { clientThread.requestShutdown(); } if (timeout > 0) { final long deadline = System.currentTimeMillis() + timeout; for (final ApnsClientThread<T> clientThread : this.clientThreads) { final long remainingTimeout = deadline - System.currentTimeMillis(); if (remainingTimeout <= 0) { break; } clientThread.join(remainingTimeout); } for (final ApnsClientThread<T> clientThread : this.clientThreads) { if (clientThread.isAlive()) { clientThread.shutdownImmediately(); } } } for (final ApnsClientThread<T> clientThread : this.clientThreads) { clientThread.join(); } this.rejectedNotificationListeners.clear(); this.rejectedNotificationExecutorService.shutdown(); if (this.shouldShutDownWorkerGroup) { if (!this.workerGroup.isShutdown()) { final Future<?> workerShutdownFuture = this.workerGroup.shutdownGracefully(); workerShutdownFuture.await(); } } this.shutDownFinished = true; final ArrayList<T> unsentNotifications = new ArrayList<T>(); unsentNotifications.addAll(this.retryQueue); unsentNotifications.addAll(this.getQueue()); return unsentNotifications; } protected ApnsClientThread<T> createClientThread() { return new ApnsClientThread<T>(this); } private void createAndActivateClientThread() { final ApnsClientThread<T> thread = createClientThread(); thread.setUncaughtExceptionHandler(this.threadExceptionHandler); this.clientThreads.add(thread); thread.start(); } protected synchronized void replaceThread(Thread t) { if (!this.shutDown) { if (!this.clientThreads.remove(t)) { log.warn(String.format("Did not find thread %s in list of client threads.", t.getName())); } this.createAndActivateClientThread(); } else { log.debug("Thread died unexpectedly, but push manager is already shut down."); } } public void registerRejectedNotificationListener(final RejectedNotificationListener<? super T> listener) { if (this.shutDown) { throw new IllegalStateException("Rejected notification listeners may not be registered after a push manager has been shut down."); } this.rejectedNotificationListeners.add(listener); } /** * <p>Un-registers a rejected notification listener.</p> * * @param listener the listener to un-register * * @return {@code true} if the given listener was registered with this push manager and removed or {@code false} if * the listener was not already registered with this push manager */ public boolean unregisterRejectedNotificationListener(final RejectedNotificationListener<? super T> listener) { return this.rejectedNotificationListeners.remove(listener); } protected void notifyListenersOfRejectedNotification(final T notification, final RejectedNotificationReason reason) { for (final RejectedNotificationListener<? super T> listener : this.rejectedNotificationListeners) { // Handle the notifications in a separate thread in case a listener takes a long time to run this.rejectedNotificationExecutorService.submit(new Runnable() { public void run() { listener.handleRejectedNotification(notification, reason); } }); } } /** * <p>Returns the queue of messages to be sent to the APNs gateway. Callers should add notifications to this queue * directly to send notifications. Notifications will be removed from this queue by Pushy when a send attempt is * started, but no guarantees are made as to when the notification will actually be sent. Successful delivery is * neither guaranteed nor acknowledged by the APNs gateway. Notifications rejected by APNs for specific reasons * will be passed to registered {@link RejectedNotificationListener}s, and notifications that could not be sent due * to temporary I/O problems will be scheduled for re-transmission in a separate, internal queue.</p> * * <p>Notifications in this queue will only be consumed when the {@code PushManager} is running and has active * connections and when the internal &quot;retry queue&quot; is empty.</p> * * @return the queue of new notifications to send to the APNs gateway * * @see PushManager#registerRejectedNotificationListener(RejectedNotificationListener) */ public BlockingQueue<T> getQueue() { return this.queue; } protected LinkedBlockingQueue<T> getRetryQueue() { return this.retryQueue; } protected NioEventLoopGroup getWorkerGroup() { return this.workerGroup; } public List<ExpiredToken> getExpiredTokens() throws InterruptedException { return this.getExpiredTokens(1, TimeUnit.SECONDS); } public List<ExpiredToken> getExpiredTokens(final long timeout, final TimeUnit timeoutUnit) throws InterruptedException { if (!this.isStarted()) { throw new IllegalStateException("Push manager has not been started yet."); } if (this.isShutDown()) { throw new IllegalStateException("Push manager has already been shut down."); } return new FeedbackServiceClient(this).getExpiredTokens(timeout, timeoutUnit); } }
package com.sdl.selenium.web.utils; import com.google.common.base.Strings; import org.slf4j.Logger; import java.time.Duration; import java.util.List; import java.util.concurrent.Callable; public class RetryUtils { private static final Logger log = org.slf4j.LoggerFactory.getLogger(RetryUtils.class); public static <V> V retry(int maxRetries, Callable<V> call) { return retry(maxRetries, null, call, false); } /** * * @param duration example 20 seconds * @param call button.click() * @param <V> type of method * @return true or false, throw RuntimeException() * <pre>{@code * RetryUtils.retry(Duration.ofSeconds(10), ()-> button.click()); * }</pre> */ public static <V> V retry(Duration duration, Callable<V> call) { return retry(duration, null, call, false); } public static <V> V retry(int maxRetries, String prefixLog, Callable<V> call) { return retry(maxRetries, prefixLog, call, false); } /** * * @param duration example 20 seconds * @param prefixLog class name * @param call button.click() * @param <V> type of method * @return true or false, throw RuntimeException() * <pre>{@code * RetryUtils.retry(Duration.ofSeconds(10), "LoginButton", ()-> button.click()); * }</pre> */ public static <V> V retry(Duration duration, String prefixLog, Callable<V> call) { return retry(duration, prefixLog, call, false); } public static boolean retryRunnable(int maxRetries, Runnable r) { return retryRunnable(maxRetries, null, r, false); } public static boolean retryRunnable(int maxRetries, String prefixLog, Runnable r) { return retryRunnable(maxRetries, prefixLog, r, false); } public static boolean retryRunnableSafe(int maxRetries, Runnable r) { return retryRunnable(maxRetries, null, r, true); } public static boolean retryRunnableSafe(int maxRetries, String prefixLog, Runnable r) { return retryRunnable(maxRetries, prefixLog, r, true); } private static boolean retryRunnable(int maxRetries, String prefixLog, Runnable r, boolean safe) { int count = 0; int wait = 0; Fib fib = new Fib(); long startMs = System.currentTimeMillis(); do { count++; // wait = wait == 0 ? 5 : count < 9 ? wait * 2 : wait; wait = count < 9 ? fibonacci(wait, fib).getResult() : wait; Utils.sleep(wait); try { r.run(); return true; } catch (Exception | AssertionError e) { if (safe) { return false; } else { if (count >= maxRetries) { long duringMs = getDuringMillis(startMs); log.error((Strings.isNullOrEmpty(prefixLog) ? "" : prefixLog + ":") + "Retry {} and wait {} milliseconds ->{}", count, duringMs, e); throw new RuntimeException(e.getMessage(), e); } } } } while (count < maxRetries); if (count > 1) { long duringMs = getDuringMillis(startMs); log.info((Strings.isNullOrEmpty(prefixLog) ? "" : prefixLog + ":") + "Retry {} and wait {} milliseconds", count, duringMs); } return true; } private static <V> V retry(int maxRetries, String prefixLog, Callable<V> call, boolean safe) { int count = 0; int wait = 0; Fib fib = new Fib(); long startMs = System.currentTimeMillis(); V execute = null; do { count++; // wait = wait == 0 ? 5 : count < 9 ? wait * 2 : wait; wait = count < 9 ? fibonacci(wait, fib).getResult() : wait; Utils.sleep(wait); // log.info("Retry {} and wait {} ->!!!", count, wait); try { execute = call.call(); } catch (Exception | AssertionError e) { if (!safe) { if (count >= maxRetries) { long duringMs = getDuringMillis(startMs); log.error((Strings.isNullOrEmpty(prefixLog) ? "" : prefixLog + ":") + "Retry {} and wait {} milliseconds ->{}", count, duringMs, e); throw new RuntimeException(e.getMessage(), e); } } } } while ((execute == null || isNotExpected(execute)) && count < maxRetries); if (count > 1) { long duringMs = getDuringMillis(startMs); log.info((Strings.isNullOrEmpty(prefixLog) ? "" : prefixLog + ":") + "Retry {} and wait {} milliseconds", count, duringMs); } return execute; } private static <V> V retry(Duration duration, String prefixLog, Callable<V> call, boolean safe) { int count = 0; int wait = 0; int limit = (int) duration.getSeconds() / 5; Fib fib = new Fib(limit); long startMillis = System.currentTimeMillis(); V execute = null; do { count++; wait = fibonacciSinusoidal(wait, fib).getResult(); Utils.sleep(wait * 1000); try { execute = call.call(); } catch (Exception | AssertionError e) { if (!safe) { if (timeIsOver(startMillis, duration)) { long duringMillis = getDuringMillis(startMillis); log.error((Strings.isNullOrEmpty(prefixLog) ? "" : prefixLog + ":") + "Retry {} and wait {} milliseconds ->{}", count, duringMillis, e); throw new RuntimeException(e.getMessage(), e); } } } } while ((execute == null || isNotExpected(execute)) && !timeIsOver(startMillis, duration)); if (count > 1) { long duringMillis = getDuringMillis(startMillis); log.info((Strings.isNullOrEmpty(prefixLog) ? "" : prefixLog + ":") + "Retry {} and wait {} milliseconds", count, duringMillis); } return execute; } private static boolean timeIsOver(long startMillis, Duration duration) { long duringMillis = getDuringMillis(startMillis); long toMillis = duration.toMillis(); return toMillis <= duringMillis; } private static long getDuringMillis(long startMillis) { long endMillis = System.currentTimeMillis(); return endMillis - startMillis; } @Deprecated public static <V> V retryWithSuccess(int maxRetries, Callable<V> call) { return retry(maxRetries, call); } public static <V> V retrySafe(int maxRetries, Callable<V> call) { return retry(maxRetries, null, call, true); } public static <V> V retrySafe(Duration duration, Callable<V> call) { return retry(duration, null, call, true); } public static <V> V retrySafe(int maxRetries, String prefixLog, Callable<V> call) { return retry(maxRetries, prefixLog, call, true); } public static <V> V retrySafe(Duration duration, String prefixLog, Callable<V> call) { return retry(duration, prefixLog, call, true); } private static <V> boolean isNotExpected(V execute) { if (execute instanceof Boolean) { return !(Boolean) execute; } else if (execute instanceof String) { return Strings.isNullOrEmpty((String) execute); } else if (execute instanceof List) { return ((List) execute).isEmpty(); } return execute == null; } public static <V> V retryIfNotSame(int maxRetries, V expected, Callable<V> call) { V result = retry(maxRetries, () -> { V text = call.call(); if (text instanceof Integer) { return expected == text ? text : null; } else { return expected.equals(text) ? text : null; } }); return result == null ? retry(0, call) : result; } public static <V> V retryIfNotContains(int maxRetries, String expected, Callable<V> call) { V result = retry(maxRetries, () -> { V text = call.call(); return text instanceof String && ((String) text).contains(expected) ? text : null; }); return result == null ? retry(0, call) : result; } private static Fib fibonacci(int time, Fib fib) { int sum = time + fib.getLast(); fib.setLast(fib.getStart()); fib.setStart(sum); fib.setResult(sum); // log.info((Strings.isNullOrEmpty(prefixLog) ? "" : prefixLog + ":") + "time is {}", sum); return fib; } private static Fib fibonacciSinusoidal(int time, Fib fib) { int sum = 0; if (fib.isPositive() && time >= fib.getLimit()) { sum = fib.getLast(); fib.setStart(fib.getStart() - fib.getLast()); fib.setLast(sum); fib.setPositive(false); } else if (!fib.isPositive() && time < fib.getLimit()) { sum = fib.getStart(); fib.setStart(fib.getLast() - fib.getStart()); fib.setLast(sum); } else if (fib.isPositive() && time >= 0) { sum = time + fib.getLast(); fib.setLast(fib.getStart()); fib.setStart(sum); } else { log.info("This value is not covered!"); Utils.sleep(1); } if (sum <= 0) { fib.setPositive(true); } fib.setResult(sum); // log.info("result is: {}", sum); return fib; } public static void main(String[] args) { int t = 0; for (int i = 0; i < 10; i++) { t = RetryUtils.fibonacci(t, new Fib()).getResult(); // log.info("time is {}", t); Utils.sleep(t); } } private static class Fib { private int start = 0; private int last = 1; private int result; private int limit = 60; private boolean positive = true; public Fib() { } public Fib(int limit) { this.limit = limit; } public void setStart(int start) { this.start = start; } public int getStart() { return start; } public void setLast(int last) { this.last = last; } public int getLast() { return last; } public void setResult(int result) { this.result = result; } public int getResult() { return result; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } public boolean isPositive() { return positive; } public void setPositive(boolean positive) { this.positive = positive; } @Override public String toString() { return "Fib{" + "start=" + start + ", last=" + last + ", result=" + result + ", limit=" + limit + ", positive=" + positive + '}'; } } }
package com.suse.salt.netapi.calls; import static com.suse.salt.netapi.utils.ClientUtils.parameterizedType; import com.suse.salt.netapi.AuthModule; import com.suse.salt.netapi.client.SaltClient; import com.suse.salt.netapi.exception.SaltException; import com.suse.salt.netapi.results.Result; import com.suse.salt.netapi.results.Return; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; /** * Class representing a function call of a salt runner module. * * @param <R> the return type of the called function */ public class RunnerCall<R> implements Call<R> { private final String functionName; private final Optional<Map<String, ?>> kwargs; private final TypeToken<R> returnType; public RunnerCall(String functionName, Optional<Map<String, ?>> kwargs, TypeToken<R> returnType) { this.functionName = functionName; this.kwargs = kwargs; this.returnType = returnType; } public TypeToken<R> getReturnType() { return returnType; } /** * {@inheritDoc} */ @Override public Map<String, Object> getPayload() { HashMap<String, Object> payload = new HashMap<>(); payload.put("fun", functionName); kwargs.ifPresent(kwargs -> payload.put("kwarg", kwargs)); return payload; } /** * Calls a runner module function on the master asynchronously and * returns information about the scheduled job that can be used to query the result. * Authentication is done with the token therefore you have to login prior * to using this function. * * @param client SaltClient instance * @return information about the scheduled job * @throws SaltException if anything goes wrong */ public RunnerAsyncResult<R> callAsync(final SaltClient client) throws SaltException { Return<List<RunnerAsyncResult<R>>> wrapper = client.call( this, Client.RUNNER_ASYNC, "/", new TypeToken<Return<List<RunnerAsyncResult<R>>>>(){}); RunnerAsyncResult<R> result = wrapper.getResult().get(0); result.setType(getReturnType()); return result; } /** * Calls a runner module function on the master asynchronously and * returns information about the scheduled job that can be used to query the result. * Authentication is done with the given credentials no session token is created. * * @param client SaltClient instance * @param username username for authentication * @param password password for authentication * @param authModule authentication module to use * @return information about the scheduled job * @throws SaltException if anything goes wrong */ public RunnerAsyncResult<R> callAsync(final SaltClient client, String username, String password, AuthModule authModule) throws SaltException { Map<String, Object> customArgs = new HashMap<>(); customArgs.putAll(getPayload()); customArgs.put("username", username); customArgs.put("password", password); customArgs.put("eauth", authModule.getValue()); Return<List<RunnerAsyncResult<R>>> wrapper = client.call( this, Client.RUNNER_ASYNC, "/run", Optional.of(customArgs), new TypeToken<Return<List<RunnerAsyncResult<R>>>>(){}); RunnerAsyncResult<R> result = wrapper.getResult().get(0); result.setType(getReturnType()); return result; } /** * Calls a runner module function on the master and synchronously * waits for the result. Authentication is done with the given credentials * no session token is created. * * @param client SaltClient instance * @param username username for authentication * @param password password for authentication * @param authModule authentication module to use * @return the result of the called function * @throws SaltException if anything goes wrong */ public Result<R> callSync(final SaltClient client, String username, String password, AuthModule authModule) throws SaltException { Map<String, Object> customArgs = new HashMap<>(); customArgs.putAll(getPayload()); customArgs.put("username", username); customArgs.put("password", password); customArgs.put("eauth", authModule.getValue()); Type xor = parameterizedType(null, Result.class, getReturnType().getType()); Type listType = parameterizedType(null, List.class, xor); Type wrapperType = parameterizedType(null, Return.class, listType); @SuppressWarnings("unchecked") Return<List<Result<R>>> wrapper = client.call( this, Client.RUNNER, "/run", Optional.of(customArgs), (TypeToken<Return<List<Result<R>>>>) TypeToken.get(wrapperType)); return wrapper.getResult().get(0); } /** * Calls a runner module function on the master and synchronously * waits for the result. Authentication is done with the token therefore you * have to login prior to using this function. * * @param client SaltClient instance * @return the result of the called function * @throws SaltException if anything goes wrong */ public Result<R> callSync(final SaltClient client) throws SaltException { Type xor = parameterizedType(null, Result.class, getReturnType().getType()); Type listType = parameterizedType(null, List.class, xor); Type wrapperType = parameterizedType(null, Return.class, listType); @SuppressWarnings("unchecked") Return<List<Result<R>>> wrapper = client.call(this, Client.RUNNER, "/", (TypeToken<Return<List<Result<R>>>>) TypeToken.get(wrapperType)); return wrapper.getResult().get(0); } }
package com.tinkerpop.rexster; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; public class ShutdownManager { protected final Logger logger = Logger.getLogger(this.getClass()); private final CountDownLatch shutdownLatch = new CountDownLatch(1); private final AtomicBoolean shutdownRequested = new AtomicBoolean(false); private final AtomicBoolean shutdownComplete = new AtomicBoolean(false); protected final Collection<ShutdownListener> internalShutdownListeners = new ArrayList<ShutdownListener>(); protected Collection<ShutdownListener> shutdownListeners = null; public static final String COMMAND_SHUTDOWN_WAIT = "sw"; public static final String COMMAND_SHUTDOWN_NO_WAIT = "s"; public static final String COMMAND_STATUS = "status"; private int port = 8184; private String host = "127.0.0.1"; static { PropertyConfigurator.configure(RexsterApplication.class.getResource("log4j.properties")); } public ShutdownManager(String host, int port) { this.port = port; this.host = host; } public void registerShutdownListener(ShutdownListener shutdownListener) { if (this.shutdownListeners == null) { this.shutdownListeners = new ArrayList<ShutdownListener>(); } this.shutdownListeners.add(shutdownListener); } public final void start() throws Exception { final ShutdownSocketListener shutdownSocketListener = new ShutdownSocketListener(this.host, this.port); final Thread shutdownSocketThread = new Thread(shutdownSocketListener, "ShutdownListener-" + this.host + ":" + this.port); shutdownSocketThread.setDaemon(true); shutdownSocketThread.start(); //Add the listener to the shutdown list this.internalShutdownListeners.add(shutdownSocketListener); //Register a shutdown handler final Thread shutdownHook = new Thread(new ShutdownHookHandler(), "JVM Shutdown Hook"); Runtime.getRuntime().addShutdownHook(shutdownHook); this.logger.debug("Registered JVM shutdown hook"); this.internalShutdownListeners.add(new ShutdownListener() { public void shutdown() { Runtime.getRuntime().removeShutdownHook(shutdownHook); logger.debug("Removed JVM shutdown hook"); } @Override public String toString() { return "JVM Shutdown Hook Remover"; } }); } /** * If shutdown isn't complete will wait on the shutdown lock for shutdown to complete. * DOES NOT TRIGGER SHUTDOWN */ public final void waitForShutdown() { if (this.shutdownComplete.get()) { return; } try { this.shutdownLatch.await(); } catch (InterruptedException e) { this.logger.warn("Interrupted waiting for shutdown condition", e); } } /** * Calls shutdown hooks and cleans up shutdown listener code, notifies all waiting threads on completion */ public final void shutdown() { final boolean shuttingDown = this.shutdownRequested.getAndSet(true); if (shuttingDown) { if (this.shutdownComplete.get()) { logger.info("Already shut down, ignoring duplicate request"); } else { logger.info("Already shutting down, ignoring duplicate request"); } return; } this.preShutdownListeners(); //Run external shutdown tasks this.runShutdownHandlers(this.shutdownListeners); //Run internal shutdown tasks this.runShutdownHandlers(this.internalShutdownListeners); this.postShutdownListeners(); this.shutdownComplete.set(true); this.shutdownLatch.countDown(); } /** * Called before the shutdown listeners */ protected void preShutdownListeners() { } /** * Called after the shutdown listeners, before threads waiting on {@link #waitForShutdown()} are released */ protected void postShutdownListeners() { } /** * Sort a {@link List} of {@link com.tinkerpop.rexster.ShutdownManager.ShutdownSocketListener} before {@link #runShutdownHandlers(Collection)} iterates over them. * Default implementation does nothing */ protected void sortShutdownListeners(List<ShutdownListener> shutdownListeners) { } protected final void runShutdownHandlers(Collection<ShutdownListener> shutdownListeners) { final List<ShutdownListener> shutdownListenersClone = new ArrayList<ShutdownListener>(shutdownListeners); this.sortShutdownListeners(shutdownListenersClone); for (final ShutdownListener shutdownListener : shutdownListenersClone) { try { this.logger.info("Calling ShutdownListener: " + shutdownListener); shutdownListener.shutdown(); this.logger.info("ShutdownListener " + shutdownListener + " complete"); } catch (Exception e) { this.logger.warn("ShutdownListener " + shutdownListener + " threw an exception, continuing with shutdown"); } } } /** * Runnable for waiting on connections to the shutdown socket and handling them */ private class ShutdownSocketListener implements Runnable, ShutdownListener { private final ServerSocket shutdownSocket; private final InetAddress bindHost; private final int port; private ShutdownSocketListener(String host, int port) { this.port = port; try { this.bindHost = InetAddress.getByName(host); } catch (UnknownHostException uhe) { throw new RuntimeException("Failed to create InetAddress for host '" + host + "'", uhe); } try { this.shutdownSocket = new ServerSocket(this.port, 10, this.bindHost); } catch (IOException ioe) { throw new RuntimeException("Failed to create shutdown socket on '" + this.bindHost + "' and " + this.port, ioe); } logger.info("Bound shutdown socket to " + this.bindHost + ":" + this.port + ". Starting listener thread for shutdown requests."); } /* (non-Javadoc) * @see java.lang.Runnable#run() */ public void run() { try { while (!shutdownSocket.isClosed()) { try { final Socket connection = shutdownSocket.accept(); final ShutdownSocketHandler shutdownSocketHandler = new ShutdownSocketHandler(connection); final Thread shutdownRequestThread = new Thread(shutdownSocketHandler, "ShutdownManager-" + connection.getInetAddress() + ":" + connection.getPort()); shutdownRequestThread.setDaemon(true); shutdownRequestThread.start(); } catch (SocketException se) { if (shutdownSocket.isClosed()) { logger.info("Caught SocketException on shutdownSocket, assuming close() was called: " + se); } else { logger.warn("Exception while handling connection to shutdown socket, ignoring", se); } } catch (IOException ioe) { logger.warn("Exception while handling connection to shutdown socket, ignoring", ioe); } } } finally { this.shutdown(); } } public void shutdown() { if (!shutdownSocket.isClosed()) { try { shutdownSocket.close(); logger.debug("Closed shutdown socket " + this.bindHost + ":" + this.port); } catch (IOException ioe) { //Ignore } } } @Override public String toString() { return "ShutdownListener [bindHost=" + bindHost + ", port=" + port + "]"; } } /** * Runnable to handle connections to the shutdown socket */ private class ShutdownSocketHandler implements Runnable { private final Socket shutdownConnection; public ShutdownSocketHandler(Socket shutdownConnection) { this.shutdownConnection = shutdownConnection; } public void run() { boolean shutdownNoWait = false; try { final BufferedReader reader = new BufferedReader(new InputStreamReader(shutdownConnection.getInputStream())); final PrintWriter writer = new PrintWriter(this.shutdownConnection.getOutputStream()); try { final String receivedCommand = reader.readLine(); if (ShutdownManager.COMMAND_SHUTDOWN_WAIT.equals(receivedCommand)) { logger.info("Received request for shutdown"); writer.println(new Date() + ": Starting Shutdown and waiting"); writer.flush(); shutdown(); writer.println(new Date() + ": Shutdown Complete"); } else if (ShutdownManager.COMMAND_SHUTDOWN_NO_WAIT.equals(receivedCommand)) { logger.info("Received request for shutdown"); writer.println(new Date() + ": Starting Shutdown and disconnecting shutdown socket"); shutdownNoWait = true; } else if (ShutdownManager.COMMAND_STATUS.equals(receivedCommand)) { logger.debug("Received request for status"); if (shutdownRequested.get()) { writer.println(new Date() + ": Shutting down"); } else { writer.println(new Date() + ": Running"); } } else { writer.println(new Date() + ": Unknown command '" + receivedCommand + "'"); } } finally { writer.flush(); IOUtils.closeQuietly(reader); IOUtils.closeQuietly(writer); } } catch (IOException e) { logger.warn("Exception while handling connection to shutdown socket, ignoring", e); } finally { if (this.shutdownConnection != null) { try { this.shutdownConnection.close(); } catch (IOException ioe) { //Ignore } } //To handle shutdown-no-wait calls if (shutdownNoWait) { shutdown(); } } } } public interface ShutdownListener { /** * Called when the application is shutting down, should block until the class is completely shut down */ public void shutdown(); } /** * Runnable that calls shutdown, used for JVM shutdown hook */ private class ShutdownHookHandler implements Runnable { /* (non-Javadoc) * @see java.lang.Runnable#run() */ public void run() { logger.info("JVM shutdown hook called"); shutdown(); } } }
package com.whammich.sstow.item; import com.google.common.base.Strings; import com.whammich.repack.tehnut.lib.annot.Handler; import com.whammich.repack.tehnut.lib.annot.ModItem; import com.whammich.repack.tehnut.lib.annot.Used; import com.whammich.repack.tehnut.lib.iface.IMeshProvider; import com.whammich.repack.tehnut.lib.util.BlockStack; import com.whammich.repack.tehnut.lib.util.TextHelper; import com.whammich.sstow.ConfigHandler; import com.whammich.sstow.SoulShardsTOW; import com.whammich.sstow.api.ISoulShard; import com.whammich.sstow.api.ISoulWeapon; import com.whammich.sstow.api.ShardHelper; import com.whammich.sstow.api.SoulShardsAPI; import com.whammich.sstow.registry.ModEnchantments; import com.whammich.sstow.registry.ModItems; import com.whammich.sstow.util.EntityMapper; import com.whammich.sstow.util.PosWithStack; import com.whammich.sstow.util.TierHandler; import com.whammich.sstow.util.Utils; import net.minecraft.client.renderer.ItemMeshDefinition; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.monster.EntitySkeleton; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.MobSpawnerBaseLogic; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityMobSpawner; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.common.util.FakePlayer; import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.fml.common.ObfuscationReflectionHelper; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import java.util.ArrayList; import java.util.List; @ModItem(name = "ItemSoulShard") @Used @Handler public class ItemSoulShard extends Item implements ISoulShard, IMeshProvider { public static List<PosWithStack> multiblock = new ArrayList<PosWithStack>(); public static BlockStack originBlock = null; public ItemSoulShard() { super(); setUnlocalizedName(SoulShardsTOW.MODID + ".shard"); setCreativeTab(SoulShardsTOW.soulShardsTab); setMaxStackSize(1); setHasSubtypes(true); } @Override public EnumActionResult onItemUse(ItemStack stack, EntityPlayer player, World world, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { if (!Utils.hasMaxedKills(stack) && ConfigHandler.allowSpawnerAbsorption) { TileEntity tile = world.getTileEntity(pos); if (tile instanceof TileEntityMobSpawner) { String name = ObfuscationReflectionHelper.getPrivateValue(MobSpawnerBaseLogic.class, ((TileEntityMobSpawner) tile).getSpawnerBaseLogic(), "mobID", "field_98288_a"); EntityLiving ent = EntityMapper.getNewEntityInstance(world, name, pos); if (ent == null) return EnumActionResult.FAIL; if (!EntityMapper.isEntityValid(name) || SoulShardsAPI.isEntityBlacklisted(ent)) return EnumActionResult.FAIL; if (ent instanceof EntitySkeleton && ((EntitySkeleton) ent).getSkeletonType() == 1) name = "Wither Skeleton"; if (ShardHelper.isBound(stack) && ShardHelper.getBoundEntity(stack).equals(name)) { if (!world.isRemote) Utils.increaseShardKillCount(stack, ConfigHandler.spawnerAbsorptionBonus); world.destroyBlock(pos, false); return EnumActionResult.SUCCESS; } } } return EnumActionResult.FAIL; } @Override public boolean showDurabilityBar(ItemStack stack) { return ConfigHandler.displayDurabilityBar && ShardHelper.getKillsFromShard(stack) < TierHandler.getMaxKills(TierHandler.tiers.size() - 1); } @Override public double getDurabilityForDisplay(ItemStack stack) { return 1.0D - ((double) ShardHelper.getKillsFromShard(stack) / (double) TierHandler.getTier(TierHandler.tiers.size() - 1).getMinKills()); } @Override public String getUnlocalizedName(ItemStack stack) { return super.getUnlocalizedName(stack) + (ShardHelper.isBound(stack) ? "" : ".unbound"); } @Override @SideOnly(Side.CLIENT) public boolean hasEffect(ItemStack stack) { return Utils.hasMaxedKills(stack); } @Override @SideOnly(Side.CLIENT) public void getSubItems(Item item, CreativeTabs tabs, List<ItemStack> list) { for (int i = 0; i <= TierHandler.tiers.size() - 1; i++) { ItemStack stack = new ItemStack(item, 1); ShardHelper.setKillsForShard(stack, TierHandler.getMinKills(i)); ShardHelper.setTierForShard(stack, i); list.add(stack); } } @Override @SideOnly(Side.CLIENT) public void addInformation(ItemStack stack, EntityPlayer player, List<String> list, boolean bool) { if (ShardHelper.isBound(stack)) list.add(TextHelper.localizeEffect("tooltip.soulshardstow.bound", Utils.getEntityNameTranslated(ShardHelper.getBoundEntity(stack)))); if (ShardHelper.getKillsFromShard(stack) >= 0) list.add(TextHelper.localizeEffect("tooltip.soulshardstow.kills", ShardHelper.getKillsFromShard(stack))); list.add(TextHelper.localizeEffect("tooltip.soulshardstow.tier", ShardHelper.getTierFromShard(stack))); } @Override @SideOnly(Side.CLIENT) public ItemMeshDefinition getMeshDefinition() { return new ItemMeshDefinition() { @Override public ModelResourceLocation getModelLocation(ItemStack stack) { if (ShardHelper.isBound(stack)) return new ModelResourceLocation(new ResourceLocation("soulshardstow:item/ItemSoulShard"), "tier=" + ShardHelper.getTierFromShard(stack)); return new ModelResourceLocation(new ResourceLocation("soulshardstow:item/ItemSoulShard"), "tier=unbound"); } }; } @Override public List<String> getVariants() { List<String> ret = new ArrayList<String>(); ret.add("tier=unbound"); for (int i = 0; i < TierHandler.tiers.size(); i++) ret.add("tier=" + i); return ret; } public static void buildMultiblock() { originBlock = new BlockStack(Blocks.glowstone); multiblock.clear(); multiblock.add(new PosWithStack(new BlockPos(0, 0, 0), new BlockStack(Blocks.glowstone))); multiblock.add(new PosWithStack(new BlockPos(1, 0, 0), new BlockStack(Blocks.end_stone))); multiblock.add(new PosWithStack(new BlockPos(-1, 0, 0), new BlockStack(Blocks.end_stone))); multiblock.add(new PosWithStack(new BlockPos(0, 0, 1), new BlockStack(Blocks.end_stone))); multiblock.add(new PosWithStack(new BlockPos(0, 0, -1), new BlockStack(Blocks.end_stone))); multiblock.add(new PosWithStack(new BlockPos(1, 0, 1), new BlockStack(Blocks.obsidian))); multiblock.add(new PosWithStack(new BlockPos(1, 0, -1), new BlockStack(Blocks.obsidian))); multiblock.add(new PosWithStack(new BlockPos(-1, 0, 1), new BlockStack(Blocks.obsidian))); multiblock.add(new PosWithStack(new BlockPos(-1, 0, -1), new BlockStack(Blocks.obsidian))); } @SubscribeEvent @Used public void onEntityKill(LivingDeathEvent event) { World world = event.entity.worldObj; if (world.isRemote || !(event.entity instanceof EntityLiving) || !(event.source.getEntity() instanceof EntityPlayer) || event.source.getEntity() instanceof FakePlayer) return; EntityLiving dead = (EntityLiving) event.entity; EntityPlayer player = (EntityPlayer) event.source.getEntity(); String entName = EntityList.getEntityString(dead); if (Strings.isNullOrEmpty(entName)) { SoulShardsTOW.instance.getLogHelper().severe("Player killed an entity with no mapped name: {}", dead); return; } if (dead instanceof EntitySkeleton && ((EntitySkeleton) dead).getSkeletonType() == 1) entName = "Wither Skeleton"; ItemStack shard = Utils.getShardFromInv(player, entName); if (shard == null) return; if (!ConfigHandler.entityList.contains(entName) || SoulShardsAPI.isEntityBlacklisted(dead)) return; if (!EntityMapper.isEntityValid(entName)) return; if (!ConfigHandler.countCageBornForShard && Utils.isCageBorn(dead)) return; if (!ShardHelper.isBound(shard)) ShardHelper.setBoundEntity(shard, entName); int soulStealer = EnchantmentHelper.getEnchantmentLevel(ModEnchantments.soulStealer, player.getHeldItemMainhand()); soulStealer *= ConfigHandler.soulStealerBonus; if (player.getHeldItemMainhand() != null && player.getHeldItemMainhand().getItem() instanceof ISoulWeapon) soulStealer += ((ISoulWeapon) player.getHeldItemMainhand().getItem()).getBonusSouls(player.getHeldItemMainhand()); Utils.increaseShardKillCount(shard, 1 + soulStealer); } @SubscribeEvent @Used public void onInteract(PlayerInteractEvent event) { if (multiblock.isEmpty()) buildMultiblock(); // TODO - Change back to `PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK` when Forge re-implements if (event.action != PlayerInteractEvent.Action.LEFT_CLICK_BLOCK) return; if (event.entityPlayer.getHeldItemMainhand() != null && event.entityPlayer.getHeldItemMainhand().getItem() == Items.diamond && originBlock.equals(BlockStack.getStackFromPos(event.world, event.pos))) { for (PosWithStack posWithStack : multiblock) { BlockStack worldStack = BlockStack.getStackFromPos(event.world, event.pos.add(posWithStack.getPos())); if (!posWithStack.getBlock().equals(worldStack)) return; } for (PosWithStack posWithStack : multiblock) event.world.destroyBlock(event.pos.add(posWithStack.getPos()), false); if (!event.world.isRemote) { EntityItem invItem = new EntityItem(event.world, event.entityPlayer.posX, event.entityPlayer.posY + 0.25, event.entityPlayer.posZ, new ItemStack(ModItems.getItem(getClass()), 1, 0)); event.world.spawnEntityInWorld(invItem); } if (!event.entityPlayer.capabilities.isCreativeMode) event.entityPlayer.getHeldItemMainhand().stackSize event.entityPlayer.swingArm(EnumHand.MAIN_HAND); } } }
package eu.thog92.isbrh.coremod; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Label; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.JumpInsnNode; import org.objectweb.asm.tree.LabelNode; import org.objectweb.asm.tree.LocalVariableNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.TypeInsnNode; import org.objectweb.asm.tree.VarInsnNode; public class RITransformer implements ITransformHandler { @Override public byte[] transform(String className, byte[] buffer) { ClassNode classNode = new ClassNode(); ClassReader classReader = new ClassReader(buffer); classReader.accept(classNode, 0); List<MethodNode> methods = classNode.methods; Iterator<MethodNode> iterator = methods.iterator(); MethodNode newMethod = null; String methodDesc = "(Lnet/minecraft/item/ItemStack;Lnet/minecraft/client/resources/model/IBakedModel;Lnet/minecraft/client/renderer/block/model/ItemCameraTransforms$TransformType;)V"; String transformType = "net/minecraft/client/renderer/block/model/ItemCameraTransforms$TransformType"; String desc = "(Lnet/minecraft/item/ItemStack;Lnet/minecraft/client/renderer/block/model/ItemCameraTransforms$TransformType;)V"; String itemStackClass = "net/minecraft/item/ItemStack"; String itemBlockClass = "net/minecraft/item/ItemBlock"; String getItemName = "getItem"; String getItemDesc = "()Lnet/minecraft/item/Item;"; String getBlockName = "getBlock"; String blockClass = "net/minecraft/block/Block"; String getRenderTypeName = "getRenderType"; String getRenderTypeDesc = "()I"; String glStateManagerClass = "net/minecraft/client/renderer/GlStateManager"; String pushMatrixName = "pushMatrix"; String popMatrixName = "popMatrix"; boolean ob; while (iterator.hasNext()) { MethodNode method = iterator.next(); if ((method.name.equals("renderItem") && method.desc .equals("(Lnet/minecraft/item/ItemStack;Lnet/minecraft/client/resources/model/IBakedModel;)V")) || (method.name.equals("a") && method.desc .equals("(Lamj;Lcxe;)V"))) { ob = method.name.equals("a"); if (ob) { transformType = "cmz"; desc = "(Lamj;Lcmz;)V"; itemStackClass = "amj"; itemBlockClass = "aju"; getItemName = "b"; getItemDesc = "()Lalq;"; getBlockName = "d"; getRenderTypeName = "b"; blockClass = "atr"; methodDesc = "(Lamj;Lcxe;Lcmz;)V"; glStateManagerClass = "cjm"; pushMatrixName = "E"; popMatrixName = "F"; } newMethod = new MethodNode(Opcodes.ACC_PUBLIC, "renderItem", methodDesc, null, null); LabelNode label = new LabelNode(); LabelNode label2 = new LabelNode(); InsnList toInject = new InsnList(); toInject.add(new VarInsnNode(Opcodes.ALOAD, 1)); toInject.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, itemStackClass, getItemName, getItemDesc, false)); toInject.add(new TypeInsnNode(Opcodes.INSTANCEOF, itemBlockClass)); toInject.add(new JumpInsnNode(Opcodes.IFEQ, label)); toInject.add(new VarInsnNode(Opcodes.ALOAD, 1)); toInject.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, itemStackClass, getItemName, getItemDesc, false)); toInject.add(new TypeInsnNode(Opcodes.CHECKCAST, itemBlockClass)); toInject.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, itemBlockClass, getBlockName, "()L" + blockClass + ";", false)); toInject.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, blockClass, getRenderTypeName, getRenderTypeDesc, false)); toInject.add(new InsnNode(Opcodes.ICONST_4)); toInject.add(new JumpInsnNode(Opcodes.IF_ICMPLE, label)); toInject.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "eu/thog92/isbrh/registry/RenderRegistry", "instance", "()Leu/thog92/isbrh/registry/RenderRegistry;", false)); toInject.add(new VarInsnNode(Opcodes.ALOAD, 1)); toInject.add(new VarInsnNode(Opcodes.ALOAD, 3)); toInject.add(new MethodInsnNode( Opcodes.INVOKEVIRTUAL, "eu/thog92/isbrh/registry/RenderRegistry", "renderInventoryBlock", desc, false)); toInject.add(new JumpInsnNode(Opcodes.GOTO, label2)); toInject.add(label); toInject.add(new VarInsnNode(Opcodes.ALOAD, 0)); toInject.add(new VarInsnNode(Opcodes.ALOAD, 1)); toInject.add(new VarInsnNode(Opcodes.ALOAD, 2)); toInject.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, classNode.name, method.name, method.desc, false)); toInject.add(label2); toInject.add(new InsnNode(Opcodes.RETURN)); newMethod.instructions.insert(toInject); System.out.println("Adding renderItem new method"); } else if ((method.name.equals("renderItemModelTransform") && method.desc .equals("(Lnet/minecraft/item/ItemStack;Lnet/minecraft/client/resources/model/IBakedModel;Lnet/minecraft/client/renderer/block/model/ItemCameraTransforms$TransformType;)V")) || (method.name.equals("a") && method.desc .equals("(Lamj;Lcxe;Lcmz;)V"))) { ob = method.name.equals("a"); InsnList newInstruction = new InsnList(); for (int i = 0; i < method.instructions.size(); i++) { AbstractInsnNode abstractInsnNode = method.instructions .get(i); if (abstractInsnNode instanceof MethodInsnNode) { MethodInsnNode methodInsnNode = (MethodInsnNode) abstractInsnNode; if ((methodInsnNode.name.equals("renderItem") && methodInsnNode.desc .equals("(Lnet/minecraft/item/ItemStack;Lnet/minecraft/client/resources/model/IBakedModel;)V")) || (methodInsnNode.name.equals("a") && methodInsnNode.desc .equals("(Lamj;Lcxe;)V"))) { newInstruction .add(new VarInsnNode(Opcodes.ALOAD, 3)); newInstruction.add(new MethodInsnNode( Opcodes.INVOKEVIRTUAL, methodInsnNode.owner, newMethod.name, methodDesc, false)); } else newInstruction.add(abstractInsnNode); } else { newInstruction.add(abstractInsnNode); } } method.instructions = newInstruction; } else if ((method.name.equals("shouldRenderItemIn3D") && method.desc .equals("(Lnet/minecraft/item/ItemStack;)Z")) || (method.name.equals("a") && method.desc .equals("(Lamj;)Z"))) { ob = method.name.equals("a"); String shouldRenderItemIn3DBodyDesc = "(Lnet/minecraft/client/renderer/entity/RenderItem;Lnet/minecraft/item/ItemStack;)Z"; if (ob) shouldRenderItemIn3DBodyDesc = "(Lcqh;Lamj;)Z"; method.instructions.clear(); method.localVariables = new ArrayList<LocalVariableNode>(); method.instructions.add(new VarInsnNode(Opcodes.ALOAD, 0)); method.instructions.add(new VarInsnNode(Opcodes.ALOAD, 1)); method.instructions.add(new MethodInsnNode( Opcodes.INVOKESTATIC, "eu/thog92/isbrh/coremod/RenderAccessHook", "shouldRenderItemIn3DBody", shouldRenderItemIn3DBodyDesc, false)); method.instructions.add(new InsnNode(Opcodes.IRETURN)); } } classNode.methods.add(newMethod); ClassWriter writer = new ClassWriter(0); classNode.accept(writer); byte[] patched = writer.toByteArray(); try { FileOutputStream out = new FileOutputStream("RenderItem.class"); out.write(patched); out.close(); } catch (IOException ex) { ex.printStackTrace(); } return patched; } }
package fi.solita.utils.functional; import static fi.solita.utils.functional.Collections.emptyList; import static fi.solita.utils.functional.Collections.newMap; import static fi.solita.utils.functional.Collections.newSet; import static fi.solita.utils.functional.Option.None; import static fi.solita.utils.functional.Option.Some; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import fi.solita.utils.functional.Iterables.*; public abstract class Functional { /** * Returns a new iterable <code>a - b</code>, i.e. one that contains all elements of <code>a</code> that * don't exist in <code>b</code>. */ @SuppressWarnings("unchecked") public static <T> Iterable<T> subtract(Iterable<? extends T> a, final Collection<? extends T> b) { return (Iterable<T>) filter(a, new Predicate<T>() { @Override public boolean accept(T object) { return !b.contains(object); } }); } public static <T> Iterable<T> subtract(T[] a, final Collection<T> b) { return subtract(Arrays.asList(a), b); } public static <T> Iterable<T> subtract(Iterable<T> a, final T[] b) { return subtract(a, newSet(b)); } public static <T> Iterable<T> subtract(T[] a, final T[] b) { return subtract(Arrays.asList(a), newSet(b)); } public static <K, V> Option<V> find(Map<? extends K, V> map, K key) { return Option.of(map.get(key)); } public static <T> Option<T> find(T[] elements, Apply<? super T, Boolean> filter) { return find(Arrays.asList(elements), filter); } public static <T> Option<T> find(Iterable<T> elements, Apply<? super T, Boolean> filter) { return headOption(filter(elements, filter)); } public static <T> Iterable<T> filter(T[] elements, Apply<? super T, Boolean> filter) { return filter(Arrays.asList(elements), filter); } public static <T> Iterable<T> filter(Iterable<T> elements, Apply<? super T, Boolean> filter) { return new FilteringIterable<T>(elements, filter); } public static <T, E> Map<T, E> filter(Map<T, E> map, Apply<Map.Entry<T, E>, Boolean> filter) { return Collections.newMap(filter(map.entrySet(), filter)); } public static <S, T> Iterable<T> map(S[] elements, Apply<? super S, ? extends T> transformer) { return map(Arrays.asList(elements), transformer); } public static <S, T1, T2> Iterable<Tuple2<T1,T2>> map(S[] elements, final Apply<? super S, T1> f1, final Apply<? super S, T2> f2) { return map(Arrays.asList(elements), f1, f2); } public static <S, T1, T2, T3> Iterable<Tuple3<T1,T2,T3>> map(S[] elements, final Apply<? super S, T1> f1, final Apply<? super S, T2> f2, final Apply<? super S, T3> f3) { return map(Arrays.asList(elements), f1, f2, f3); } public static <S, T1, T2, T3, T4> Iterable<Tuple4<T1,T2,T3,T4>> map(S[] elements, final Apply<? super S, T1> f1, final Apply<? super S, T2> f2, final Apply<? super S, T3> f3, final Apply<? super S, T4> f4) { return map(Arrays.asList(elements), f1, f2, f3, f4); } public static <S, T> Iterable<T> map(Iterable<S> elements, Apply<? super S, ? extends T> transformer) { return new TransformingIterable<S,T>(elements, transformer); } public static <S, T1, T2> Iterable<Tuple2<T1,T2>> map(Iterable<S> elements, final Apply<? super S, T1> f1, final Apply<? super S, T2> f2) { return new TransformingIterable<S,Tuple2<T1,T2>>(elements, new Transformer<S, Tuple2<T1,T2>>() { @Override public Tuple2<T1,T2> transform(S source) { return Tuple.of(f1.apply(source), f2.apply(source)); } }); } public static <S, T1, T2, T3> Iterable<Tuple3<T1,T2,T3>> map(Iterable<S> elements, final Apply<? super S, T1> f1, final Apply<? super S, T2> f2, final Apply<? super S, T3> f3) { return new TransformingIterable<S,Tuple3<T1,T2,T3>>(elements, new Transformer<S, Tuple3<T1,T2,T3>>() { @Override public Tuple3<T1,T2,T3> transform(S source) { return Tuple.of(f1.apply(source), f2.apply(source), f3.apply(source)); } }); } public static <S, T1, T2, T3, T4> Iterable<Tuple4<T1,T2,T3,T4>> map(Iterable<S> elements, final Apply<? super S, T1> f1, final Apply<? super S, T2> f2, final Apply<? super S, T3> f3, final Apply<? super S, T4> f4) { return new TransformingIterable<S,Tuple4<T1,T2,T3,T4>>(elements, new Transformer<S, Tuple4<T1,T2,T3,T4>>() { @Override public Tuple4<T1,T2,T3,T4> transform(S source) { return Tuple.of(f1.apply(source), f2.apply(source), f3.apply(source), f4.apply(source)); } }); } public static <K1, V1, K2, V2> Map<K2, V2> map(Map<K1, V1> source, Apply<Map.Entry<K1, V1>, Map.Entry<K2, V2>> transformer) { return Collections.newMap(map(source.entrySet(), transformer)); } public static <S, T> Iterable<T> flatMap(S[] elements, Apply<? super S, ? extends Iterable<T>> transformer) { return flatMap(Arrays.asList(elements), transformer); } public static <S, T> Iterable<T> flatMap(Iterable<S> elements, Apply<? super S, ? extends Iterable<? extends T>> transformer) { return flatten(map(elements, transformer)); } public static <T> Iterable<T> flatten(T[][] elements) { return flatten(map(elements, new Transformer<T[], Iterable<T>>() { @Override public Iterable<T> transform(T[] source) { return Arrays.asList(source); } })); } public static <T> Iterable<T> flatten(Iterable<? extends T>[] elements) { return flatten(Arrays.asList(elements)); } public static <T> Iterable<T> flatten(Iterable<? extends Iterable<? extends T>> elements) { return new FlatteningIterable<T>(elements); } public static <T> void foreach(T[] elements, Apply<? super T, Void> procedure) { foreach(Arrays.asList(elements), procedure); } public static <T> void foreach(Iterable<T> elements, Apply<? super T, Void> procedure) { for (T t: elements) { procedure.apply(t); } } /** * Non-lazy */ public static <T> Iterable<List<T>> grouped(T[] elements, int size) { return grouped(Arrays.asList(elements), size); } /** * Non-lazy */ public static <T> Iterable<List<T>> grouped(Iterable<T> elements, int size) { if (size <= 0) { throw new IllegalArgumentException("size must be positive"); } Option<Integer> estimatedSize = Iterables.resolveSize.apply(elements); List<List<T>> target = estimatedSize.isDefined() ? Collections.<List<T>>newListOfSize(estimatedSize.get() / size) : Collections.<List<T>>newList(); Iterator<T> it = elements.iterator(); while (it.hasNext()) { List<T> group = Collections.newListOfSize(size); for (int i = 0; i < size; ++i) { if (it.hasNext()) { group.add(it.next()); } } if (!group.isEmpty()) { target.add(group); } } return target; } /** * Non-lazy */ public static <G, T> Map<G, List<T>> groupBy(T[] elements, Apply<? super T,G> f) { return groupBy(Arrays.asList(elements), f); } /** * Non-lazy */ public static <G, T> Map<G, List<T>> groupBy(Iterable<T> elements, Apply<? super T,G> f) { Map<G, List<T>> target = newMap(); for (T t: elements) { G g = f.apply(t); Option<List<T>> groupOption = find(target, g); List<T> group; if (groupOption.isDefined()) { group = groupOption.get(); } else { group = Collections.newList(); target.put(g, group); } group.add(t); } return target; } public static <T> T head(T[] elements) { return elements[0]; } public static <T> T head(Iterable<T> elements) { return elements.iterator().next(); } public static <T> Option<T> headOption(T[] elements) { return elements.length == 0 ? Option.<T>None() : Some(elements[0]); } public static <T> Option<T> headOption(Iterable<T> elements) { Iterator<T> it = elements.iterator(); if (it.hasNext()) { return Some(it.next()); } else { return None(); } } public static <T> Iterable<T> tail(T[] elements) { return tail(Arrays.asList(elements)); } public static <T> Iterable<T> tail(Iterable<T> elements) { return drop(elements, 1); } public static <T> T last(T[] elements) { return elements[elements.length-1]; } public static <T> T last(Iterable<T> elements) { return lastOption(elements).get(); } public static <T> Option<T> lastOption(T[] elements) { return elements.length == 0 ? Option.<T>None() : Some(elements[elements.length-1]); } public static <T> Option<T> lastOption(Iterable<T> elements) { if (elements instanceof List) { if (((List<T>) elements).isEmpty()) { return None(); } return Some(((List<T>) elements).get(((List<T>) elements).size()-1)); } else { Iterator<T> it = elements.iterator(); if (it.hasNext()) { T ret = it.next(); while (it.hasNext()) { ret = it.next(); } return Some(ret); } else { return None(); } } } public static <T> Iterable<T> init(T[] elements) { return init(Arrays.asList(elements)); } public static <T> Iterable<T> init(Iterable<T> elements) { return take(elements, size(elements)-1); } public static <T> Iterable<T> take(T[] elements, int amount) { return take(Arrays.asList(elements), amount); } public static <T> Iterable<T> take(final Iterable<T> elements, final int amount) { return new Iterables.TakingIterable<T>(elements, amount); } public static <T> Iterable<T> drop(T[] elements, int amount) { return drop(Arrays.asList(elements), amount); } public static <T> Iterable<T> drop(final Iterable<T> elements, final int amount) { return new Iterables.DroppingIterable<T>(elements, amount); } public static <T> Iterable<T> takeWhile(T[] elements, Apply<? super T, Boolean> predicate) { return takeWhile(Arrays.asList(elements), predicate); } public static <T> Iterable<T> takeWhile(final Iterable<T> elements, final Apply<? super T, Boolean> predicate) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return new Iterator<T>() { private Option<T> next; private final Iterator<T> source = elements.iterator(); { readNext(); } @Override public boolean hasNext() { return next.isDefined(); } private void readNext() { if (!source.hasNext()) { next = None(); } else { T n = source.next(); if (predicate.apply(n)) { next = Some(n); } else { next = None(); } } } @Override public T next() { if (!next.isDefined()) { throw new NoSuchElementException(); } T ret = next.get(); readNext(); return ret; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; } public static <T> Iterable<T> dropWhile(T[] elements, Apply<? super T, Boolean> predicate) { return dropWhile(Arrays.asList(elements), predicate); } public static <T> Iterable<T> dropWhile(final Iterable<T> elements, final Apply<? super T, Boolean> predicate) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return new Iterator<T>() { private boolean dropping = true; private final Iterator<T> source = elements.iterator(); private Option<T> next; { readNext(); } @Override public boolean hasNext() { return next.isDefined(); } private void readNext() { next = source.hasNext() ? Some(source.next()) : Option.<T>None(); while (dropping && next.isDefined() && predicate.apply(next.get())) { next = source.hasNext() ? Some(source.next()) : Option.<T>None(); } dropping = false; } @Override public T next() { if (!next.isDefined()) { throw new NoSuchElementException(); } T ret = next.get(); readNext(); return ret; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; } public static <T> Pair<Iterable<T>, Iterable<T>> span(final Iterable<T> elements, final Apply<? super T, Boolean> predicate) { // TODO: a more efficient implementation return Pair.of(takeWhile(elements, predicate), dropWhile(elements, predicate)); } public static boolean isEmpty(Iterable<?> elements) { return !elements.iterator().hasNext(); } public static int size(Iterable<?> elements) { if (elements instanceof Collection) { return ((Collection<?>) elements).size(); } else { int s = 0; Iterator<?> it = elements.iterator(); while (it.hasNext()) { s++; it.next(); } return s; } } public static <T> boolean contains(T[] elements, T element) { return contains(Arrays.asList(elements), element); } public static <T,E> boolean contains(Iterable<T> elements, final T element) { return exists(elements, new Predicate<T>() { @Override public boolean accept(T candidate) { return candidate.equals(element); } }); } public static <T> boolean exists(T[] elements, Apply<T, Boolean> filter) { return exists(Arrays.asList(elements), filter); } public static <T> boolean exists(Iterable<T> elements, Apply<? super T, Boolean> filter) { return !isEmpty(filter(elements, filter)); } public static <T> boolean forAll(T[] elements, Apply<? super T, Boolean> filter) { return forAll(Arrays.asList(elements), filter); } public static <T> boolean forAll(Iterable<T> elements, Apply<? super T, Boolean> filter) { return !exists(elements, Predicates.not(filter)); } @SuppressWarnings("unchecked") public static <T> Iterable<T> cons(T element, Iterable<? extends T> elements) { return concat(Arrays.asList(element), elements); } @SuppressWarnings("unchecked") public static <T> Iterable<T> cons(T element, T[] elements) { return concat(Arrays.asList(element), elements); } public static <T> Iterable<T> concat(T[] elements1, Iterable<? extends T> elements2) { return concat(Arrays.asList(elements1), elements2); } public static <T> Iterable<T> concat(Iterable<? extends T> elements1, T[] elements2) { return concat(elements1, Arrays.asList(elements2)); } public static <T> Iterable<T> concat(T[] elements1, T[] elements2) { return concat(Arrays.asList(elements1), Arrays.asList(elements2)); } @SuppressWarnings("unchecked") public static <T> Iterable<T> concat(Iterable<? extends T> elements1, Iterable<? extends T> elements2) { return new ConcatenatingIterable<T>(Arrays.asList(elements1, elements2)); } @SuppressWarnings("unchecked") public static <T> Iterable<T> concat(Iterable<? extends T> elements1, Iterable<? extends T> elements2, Iterable<? extends T> elements3) { return new ConcatenatingIterable<T>(Arrays.asList(elements1, elements2, elements3)); } @SuppressWarnings("unchecked") public static <T> Iterable<T> concat(Iterable<? extends T> elements1, Iterable<? extends T> elements2, Iterable<? extends T> elements3, Iterable<? extends T> elements4) { return new ConcatenatingIterable<T>(Arrays.asList(elements1, elements2, elements3, elements4)); } @SuppressWarnings("unchecked") public static <T> Iterable<T> concat(Iterable<? extends T> elements1, final Iterable<? extends T> elements2, Iterable<? extends T> elements3, Iterable<? extends T> elements4, Iterable<? extends T> elements5, Iterable<? extends T>... rest) { return new ConcatenatingIterable<T>(concat(Arrays.asList(elements1, elements2, elements3, elements4, elements5), rest)); } public static <T extends Comparable<T>> Iterable<T> sort(T[] elements) { return sort(Arrays.asList(elements)); } public static <T extends Comparable<T>> Iterable<T> sort(Iterable<T> elements) { return sort(elements, Ordering.Natural()); } public static <T> Iterable<T> sort(T[] elements, Comparator<? super T> comparator) { return sort(Arrays.asList(elements), comparator); } public static <T> Iterable<T> sort(Iterable<T> elements, Comparator<? super T> comparator) { if (isEmpty(elements)) { return emptyList(); } return new Iterables.SortingIterable<T>(elements, comparator); } public static <T extends SemiGroup<T>> T reduce(T e1) { return e1; } @SuppressWarnings("unchecked") public static <T extends SemiGroup<T>> T reduce(T e1, T e2) { return reduce(Arrays.asList(e1, e2)).get(); } @SuppressWarnings("unchecked") public static <T extends SemiGroup<T>> T reduce(T e1, T e2, T e3) { return reduce(Arrays.asList(e1, e2, e3)).get(); } @SuppressWarnings("unchecked") public static <T extends SemiGroup<T>> T reduce(T e1, T e2, T e3, T e4) { return reduce(Arrays.asList(e1, e2, e3, e4)).get(); } @SuppressWarnings("unchecked") public static <T extends SemiGroup<T>> T reduce(T e1, T e2, T e3, T e4, T... elements) { return reduce(concat(Arrays.asList(e1, e2, e3, e4), elements)).get(); } public static <T extends SemiGroup<T>> Option<T> reduce(T[] elements) { return reduce(Arrays.asList(elements)); } public static <T extends SemiGroup<T>> Option<T> reduce(Iterable<? extends T> elements) { if (isEmpty(elements)) { return None(); } return fold(elements, head(elements)); } public static <T> T reduce(T[] elements, Monoid<T> m) { return reduce(Arrays.asList(elements), m); } public static <T> T reduce(Iterable<? extends T> elements, Monoid<T> m) { return fold(cons(m.zero(), elements), m).get(); } /** * @return <i>None</i> if <i>elements</i> is empty */ public static <T> Option<T> fold(T[] elements, Apply<Tuple2<T,T>, T> f) { return fold(Arrays.asList(elements), f); } /** * @return <i>None</i> if <i>elements</i> is empty */ public static <T> Option<T> fold(Iterable<? extends T> elements, Apply<Tuple2<T,T>, T> f) { Option<? extends T> h = headOption(elements); if (h.isDefined()) { T ret = h.get(); for (T t : drop(elements, 1)) { ret = f.apply(Tuple.of(ret, t)); } return Some(ret); } return None(); } public static long sum(Integer... elements) { return sum(Arrays.asList(elements)); } public static long sum(Iterable<Integer> elements) { return reduce(map(elements, int2long), Monoids.longSum); } public static long product(Integer... elements) { return product(Arrays.asList(elements)); } public static long product(Iterable<Integer> elements) { return reduce(map(elements, int2long), Monoids.longProduct); } public static <T extends Comparable<T>> T min(T e1, T... elements) { return min(cons(e1, elements)).get(); } public static <T extends Comparable<T>> Option<T> min(T[] elements) { return min(Arrays.asList(elements)); } public static <T extends Comparable<T>> Option<T> min(Iterable<T> elements) { return headOption(sort(elements)); } public static <T extends Comparable<T>> T max(T e1, T... elements) { return max(cons(e1, elements)).get(); } public static <T extends Comparable<T>> Option<T> max(T[] elements) { return max(Arrays.asList(elements)); } public static <T extends Comparable<T>> Option<T> max(Iterable<T> elements) { return headOption(sort(elements, Ordering.Natural().reverse())); } public static <A,B> Iterable<Tuple2<A, B>> zip(A[] a, B[] b) { return zip(Arrays.asList(a), Arrays.asList(b)); } public static <A,B> Iterable<Tuple2<A, B>> zip(A[] a, Iterable<B> b) { return zip(Arrays.asList(a), b); } public static <A,B> Iterable<Tuple2<A, B>> zip(Iterable<A> a, B[] b) { return zip(a, Arrays.asList(b)); } public static <A,B> Iterable<Tuple2<A, B>> zip(Iterable<A> a, Iterable<B> b) { return new ZippingIterable<A,B>(a, b); } public static <A,B,C> Iterable<Tuple3<A, B, C>> zip(A[] a, B[] b, C[] c) { return zip(Arrays.asList(a), Arrays.asList(b), Arrays.asList(c)); } public static <A,B,C> Iterable<Tuple3<A, B, C>> zip(A[] a, Iterable<B> b, Iterable<C> c) { return zip(Arrays.asList(a), b, c); } public static <A,B,C> Iterable<Tuple3<A, B, C>> zip(Iterable<A> a, B[] b, Iterable<C> c) { return zip(a, Arrays.asList(b), c); } public static <A,B,C> Iterable<Tuple3<A, B, C>> zip(Iterable<A> a, Iterable<B> b, C[] c) { return zip(a, b, Arrays.asList(c)); } public static <A,B,C> Iterable<Tuple3<A, B, C>> zip(A[] a, B[] b, Iterable<C> c) { return zip(Arrays.asList(a), Arrays.asList(b), c); } public static <A,B,C> Iterable<Tuple3<A, B, C>> zip(Iterable<A> a, B[] b, C[] c) { return zip(a, Arrays.asList(b), Arrays.asList(c)); } public static <A,B,C> Iterable<Tuple3<A, B, C>> zip(A[] a, Iterable<B> b, C[] c) { return zip(Arrays.asList(a), b, Arrays.asList(c)); } @SuppressWarnings("unchecked") public static <A,B,C> Iterable<Tuple3<A, B, C>> zip(Iterable<A> a, Iterable<B> b, Iterable<C> c) { return map(zip(zip(a, b), c), ( Transformer<Tuple2<Tuple2<A, B>, C>, Tuple3<A, B, C>>)(Object)zip3Transformer); } private static final Transformer<Tuple2<Tuple2<Object,Object>,Object>,Tuple3<Object,Object,Object>> zip3Transformer = new Transformer<Tuple2<Tuple2<Object, Object>, Object>, Tuple3<Object, Object, Object>>() { @Override public Tuple3<Object, Object, Object> transform(Tuple2<Tuple2<Object, Object>, Object> source) { return source._1.append(source._2); } }; public static <A> Iterable<Tuple2<Integer, A>> zipWithIndex(Iterable<A> a) { return new ZippingIterable<Integer,A>(range(0), a); } public static <A> Iterable<Tuple2<Integer, A>> zipWithIndex(A[] a) { return new ZippingIterable<Integer,A>(range(0), Arrays.asList(a)); } public static Iterable<Integer> range(int from) { return range(Enumerables.ints, from); } public static Iterable<Integer> range(int from, int toInclusive) { return new RangeIterable<Integer>(Enumerables.ints, from, toInclusive, toInclusive - from + 1); } public static <T, S extends Enumerable<T> & Bounded<T>> Iterable<T> range(S enumeration) { return range(enumeration, enumeration.minBound()); } public static <T> Iterable<T> range(Enumerable<T> enumeration, T from) { return new RangeIterable<T>(enumeration, from, Option.<T>None()); } public static <T> Iterable<T> range(Enumerable<T> enumeration, T from, T toInclusive) { return new RangeIterable<T>(enumeration, from, Some(toInclusive)); } public static <T> Iterable<T> repeat(T value) { return new RepeatingIterable<T>(value); } public static <T> Iterable<T> repeat(T value, int amount) { return new RepeatingIterable<T>(value, amount); } public static String mkString(Iterable<Character> elements) { StringBuilder sb = new StringBuilder(); for (char c: elements) { sb.append(c); } return sb.toString(); } public static String mkString(CharSequence delim, CharSequence[] elements) { return mkString(delim, Arrays.asList(elements)); } public static String mkString(CharSequence delim, Iterable<? extends CharSequence> elements) { StringBuilder sb = new StringBuilder(); for (CharSequence s: elements) { if (sb.length() > 0) { sb.append(delim); } sb.append(s); } return sb.toString(); } public static <T> Iterable<T> reverse(Iterable<T> elements) { return new Iterables.ReversingIterable<T>(elements); } public static <T,R> Iterable<R> sequence(Iterable<? extends Apply<? super T,? extends R>> elements, final T t) { return map(elements, new Transformer<Apply<? super T,? extends R>, R>() { @Override public R transform(Apply<? super T,? extends R> source) { return source.apply(t); } }); } public static <T> Iterable<Iterable<T>> transpose(Iterable<? extends Iterable<T>> elements) { return new TransposingIterable<T>(elements); } @SuppressWarnings("unchecked") public static <T> Iterable<Iterable<T>> transpose2(Iterable<T[]> elements) { return transpose(map(elements, (Transformer<T[], Iterable<T>>)(Object)arrayToIterable)); } private static final Transformer<Object[], Iterable<Object>> arrayToIterable = new Transformer<Object[], Iterable<Object>>() { @Override public Iterable<Object> transform(Object[] source) { return Arrays.asList(source); } }; private static final Transformer<Integer,Long> int2long = new Transformer<Integer,Long>() { @Override public Long transform(Integer source) { return (long)source; } }; private static final String LINE_SEP = System.getProperty("line.separator"); public static final String unlines(Iterable<? extends CharSequence> elements) { return mkString(LINE_SEP, elements); } @SuppressWarnings("unchecked") public static <T> Set<T> union(Set<T> e1, Set<T> e2) { return reduce(Arrays.asList(e1, e2), Monoids.<T>setUnion()); } @SuppressWarnings("unchecked") public static <T> Set<T> union(Set<T> e1, Set<T> e2, Set<T>... e) { return reduce(concat(Arrays.asList(e1, e2), e), Monoids.<T>setUnion()); } @SuppressWarnings("unchecked") public static <T> Set<T> intersection(Set<T> e1, Set<T> e2) { return reduce(Arrays.asList(e1, e2), Monoids.<T>setIntersection()); } @SuppressWarnings("unchecked") public static <T> Set<T> intersection(Set<T> e1, Set<T> e2, Set<T>... e) { return reduce(concat(Arrays.asList(e1, e2), e), Monoids.<T>setIntersection()); } }
package fr.jeci.alfresco.saod; import javax.servlet.MultipartConfigElement; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration; import org.springframework.boot.autoconfigure.security.SecurityProperties; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.embedded.MultipartConfigFactory; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.web.SpringBootServletInitializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.authentication.configurers.GlobalAuthenticationConfigurerAdapter; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import com.jolbox.bonecp.BoneCPDataSource; import fr.jeci.alfresco.saod.sql.SqlQueries; @Configuration @EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class }) @ComponentScan @EnableGlobalMethodSecurity(securedEnabled = true) public class SaodApplication extends SpringBootServletInitializer { @Bean MultipartConfigElement multipartConfigElement() { MultipartConfigFactory factory = new MultipartConfigFactory(); factory.setMaxFileSize("51200KB"); // 50MB factory.setMaxRequestSize("256000KB"); return factory.createMultipartConfig(); } public static void main(String[] args) throws Exception { new SpringApplicationBuilder(SaodApplication.class).run(args); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(SaodApplication.class); } @Bean @ConfigurationProperties(prefix = "alfresco.datasource") public DataSource alfrescoDataSource() { return DataSourceBuilder.create().type(BoneCPDataSource.class).build(); } @Bean @ConfigurationProperties(prefix = "local.datasource") public DataSource localDataSource() { return DataSourceBuilder.create().type(BoneCPDataSource.class).build(); } @Value("${sql.local.base_path}") private String sqlLocalBasePath = "sql/hsqldb"; @Bean public SqlQueries localSqlQueries() { SqlQueries sqlQueries = new SqlQueries(); sqlQueries.setSqlBasePath(sqlLocalBasePath); return sqlQueries; } @Value("${sql.alfresco.base_path}") private String sqlAlfrescoBAsePath = "sql/hsqldb"; @Bean public SqlQueries alfrescoSqlQueries() { SqlQueries sqlQueries = new SqlQueries(); sqlQueries.setSqlBasePath(sqlAlfrescoBAsePath); return sqlQueries; } @Bean public ApplicationSecurity applicationSecurity() { return new ApplicationSecurity(); } @Order(Ordered.HIGHEST_PRECEDENCE) @Configuration protected static class AuthenticationSecurity extends GlobalAuthenticationConfigurerAdapter { @Override public void init(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN", "USER").and() .withUser("user").password("user").roles("USER"); } } @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) protected static class ApplicationSecurity extends WebSecurityConfigurerAdapter { // @formatter:off @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/login").permitAll() .anyRequest().fullyAuthenticated() .and() .formLogin().loginPage("/login") .failureUrl("/login?error") .and() .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")) .and() .exceptionHandling().accessDeniedPage("/access?error"); } // @formatter:on } }
package hu.akarnokd.theplanetcrafter; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; public class BuildMap { public static void main(String[] args) throws Exception { buildMapOf("barren"); buildMapOf("lush"); } static void buildMapOf(String mode) throws Exception { int step = 200; int maxZ = 3000; int minZ = -1400; int maxX = 2400; int minX = -1000; int nHorizontal = (maxZ - minZ) / step; int nVertical = (maxX - minX) / step; int w = 80; int h = 60; BufferedImage bimg = new BufferedImage(w * nHorizontal, h * nVertical, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = bimg.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); int outx = 0; for (int z = maxZ; z >= minZ; z-= step) { int outy = 0; for (int x = maxX; x >= minX; x -= step) { //System.out.println(mode + " - " + z + " : " + x); BufferedImage image = ImageIO.read(new File("c:\\temp\\" + mode + "\\map_" + z + "_" + x + ".png")); g2.drawImage(image, outx - w / 2, outy - h / 2, outx + w / 2, outy + h / 2, 0, 0, image.getWidth(), image.getHeight(), null); outy += h; } outx += w; } ImageIO.write(bimg, "png", new File("c:\\temp\\" + mode + "\\map_" + mode + ".png")); System.out.println(mode + " Done"); System.out.printf("CenterX: %d, CenterZ: %d%n", minX + (maxX - minX) / 2, minZ + (maxZ - minZ) / 2); } }
package io.bitsquare.app; import io.bitsquare.BitsquareException; import io.bitsquare.btc.UserAgent; import io.bitsquare.btc.WalletService; import io.bitsquare.gui.ViewCB; import io.bitsquare.persistence.Persistence; import io.bitsquare.util.spring.JOptCommandLinePropertySource; import java.nio.file.Paths; import java.util.Properties; import joptsimple.OptionSet; import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertiesPropertySource; import org.springframework.core.env.PropertySource; import org.springframework.core.env.StandardEnvironment; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.ResourcePropertySource; import static com.google.common.base.Preconditions.checkNotNull; public class BitsquareEnvironment extends StandardEnvironment { public static final String APP_VERSION_KEY = "app.version"; public static final String USER_DATA_DIR_KEY = "user.data.dir"; public static final String DEFAULT_USER_DATA_DIR = defaultUserDataDir(); public static final String APP_NAME_KEY = "app.name"; public static final String DEFAULT_APP_NAME = "Bitsquare"; public static final String APP_DATA_DIR_KEY = "app.data.dir"; public static final String DEFAULT_APP_DATA_DIR = appDataDir(DEFAULT_USER_DATA_DIR, DEFAULT_APP_NAME); static final String BITSQUARE_DEFAULT_PROPERTY_SOURCE_NAME = "bitsquareDefaultProperties"; static final String BITSQUARE_CLASSPATH_PROPERTY_SOURCE_NAME = "bitsquareClasspathProperties"; static final String BITSQUARE_FILESYSTEM_PROPERTY_SOURCE_NAME = "bitsquareFilesystemProperties"; static final String BITSQUARE_COMMANDLINE_PROPERTY_SOURCE_NAME = "bitsquareCommandLineProperties"; private final ResourceLoader resourceLoader = new DefaultResourceLoader(); private final String appName; private final String appDataDir; public BitsquareEnvironment(OptionSet options) { this(new JOptCommandLinePropertySource(BITSQUARE_COMMANDLINE_PROPERTY_SOURCE_NAME, checkNotNull(options))); } BitsquareEnvironment(PropertySource commandLineProperties) { String userDataDir = commandLineProperties.containsProperty(USER_DATA_DIR_KEY) ? (String) commandLineProperties.getProperty(USER_DATA_DIR_KEY) : DEFAULT_USER_DATA_DIR; this.appName = commandLineProperties.containsProperty(APP_NAME_KEY) ? (String) commandLineProperties.getProperty(APP_NAME_KEY) : DEFAULT_APP_NAME; this.appDataDir = commandLineProperties.containsProperty(APP_DATA_DIR_KEY) ? (String) commandLineProperties.getProperty(APP_DATA_DIR_KEY) : appDataDir(userDataDir, appName); MutablePropertySources propertySources = this.getPropertySources(); propertySources.addFirst(commandLineProperties); try { propertySources.addLast(filesystemProperties()); propertySources.addLast(classpathProperties()); propertySources.addLast(defaultProperties()); } catch (Exception ex) { throw new BitsquareException(ex); } } PropertySource<?> filesystemProperties() throws Exception { String location = String.format("file:%s/bitsquare.properties", appDataDir); Resource resource = resourceLoader.getResource(location); if (!resource.exists()) return new PropertySource.StubPropertySource(BITSQUARE_FILESYSTEM_PROPERTY_SOURCE_NAME); return new ResourcePropertySource(BITSQUARE_FILESYSTEM_PROPERTY_SOURCE_NAME, resource); } PropertySource<?> classpathProperties() throws Exception { Resource resource = resourceLoader.getResource("classpath:bitsquare.properties"); return new ResourcePropertySource(BITSQUARE_CLASSPATH_PROPERTY_SOURCE_NAME, resource); } PropertySource<?> defaultProperties() throws Exception { return new PropertiesPropertySource(BITSQUARE_DEFAULT_PROPERTY_SOURCE_NAME, new Properties() {{ setProperty(APP_DATA_DIR_KEY, appDataDir); setProperty(APP_NAME_KEY, appName); setProperty(UserAgent.NAME_KEY, appName); setProperty(UserAgent.VERSION_KEY, BitsquareEnvironment.this.getRequiredProperty(APP_VERSION_KEY)); setProperty(WalletService.DIR_KEY, appDataDir); setProperty(WalletService.PREFIX_KEY, appName); setProperty(Persistence.DIR_KEY, appDataDir); setProperty(Persistence.PREFIX_KEY, appName + "_pref"); setProperty(ViewCB.TITLE_KEY, appName); }}); } private static String defaultUserDataDir() { String os = System.getProperty("os.name").toLowerCase(); if (os.contains("win")) return System.getenv("APPDATA"); if (os.contains("mac")) return Paths.get(System.getProperty("user.home"), "Library", "Application Support").toString(); // *nix return Paths.get(System.getProperty("user.home"), ".local", "share").toString(); } private static String appDataDir(String userDataDir, String appName) { return Paths.get(userDataDir, appName).toString(); } }
package io.github.classgraph; import java.io.File; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; import io.github.classgraph.Scanner.ClasspathEntryWorkUnit; import nonapi.io.github.classgraph.concurrency.WorkQueue; import nonapi.io.github.classgraph.scanspec.ScanSpec; import nonapi.io.github.classgraph.scanspec.ScanSpec.ScanSpecPathMatch; import nonapi.io.github.classgraph.utils.FileUtils; import nonapi.io.github.classgraph.utils.JarUtils; import nonapi.io.github.classgraph.utils.LogNode; /** A classpath element (a directory or jarfile on the classpath). */ abstract class ClasspathElement { /** * If non-null, contains a list of resolved paths for any classpath element roots nested inside this classpath * element. (Scanning should stop at a nested classpath element root, otherwise that subtree will be scanned * more than once.) N.B. contains only the nested part of the resolved path (the common prefix is removed). Also * includes a trailing '/', since only nested directory classpath elements need to be caught (nested jars do not * need to be caught, because we don't scan jars-within-jars unless the inner jar is explicitly listed on the * classpath). */ List<String> nestedClasspathRootPrefixes; /** * True if there was an exception when trying to open this classpath element (e.g. a corrupt ZipFile). */ boolean skipClasspathElement; /** True if classpath element contains a specifically-whitelisted resource path. */ boolean containsSpecificallyWhitelistedClasspathElementResourcePath; /** * The child classpath elements, keyed by the order of the child classpath element within the Class-Path entry * of the manifest file the child classpath element was listed in (or the position of the file within the sorted * entries of a lib directory). */ final Queue<Entry<Integer, ClasspathElement>> childClasspathElementsIndexed = new ConcurrentLinkedQueue<>(); /** * The child classpath elements, ordered by order within the parent classpath element. */ List<ClasspathElement> childClasspathElementsOrdered; /** The list of all resources found within this classpath element that were whitelisted and not blacklisted. */ protected final Collection<Resource> whitelistedResources = new ConcurrentLinkedQueue<>(); /** The list of all classfiles found within this classpath element that were whitelisted and not blacklisted. */ protected Collection<Resource> whitelistedClassfileResources = new ConcurrentLinkedQueue<>(); /** The map from File to last modified timestamp, if scanFiles is true. */ protected final Map<File, Long> fileToLastModified = new ConcurrentHashMap<>(); /** Flag to ensure classpath element is only scanned once. */ protected final AtomicBoolean scanned = new AtomicBoolean(false); /** The classloader that this classpath element was obtained from. */ protected ClassLoader classLoader; /** * The name of the module from the {@code module-info.class} module descriptor, if one is present in the root of * the classpath element. */ String moduleNameFromModuleDescriptor; /** The scan spec. */ final ScanSpec scanSpec; /** * A classpath element. * * @param classLoader * the classloader * @param scanSpec * the scan spec */ ClasspathElement(final ClassLoader classLoader, final ScanSpec scanSpec) { this.classLoader = classLoader; this.scanSpec = scanSpec; } /** * Get the ClassLoader the classpath element was obtained from. * * @return the classloader */ ClassLoader getClassLoader() { return classLoader; } /** * Get the number of classfile matches. * * @return the num classfile matches */ int getNumClassfileMatches() { return whitelistedClassfileResources == null ? 0 : whitelistedClassfileResources.size(); } /** * Check relativePath against classpathElementResourcePathWhiteBlackList. * * @param relativePath * the relative path * @param log * the log */ protected void checkResourcePathWhiteBlackList(final String relativePath, final LogNode log) { // Whitelist/blacklist classpath elements based on file resource paths if (!scanSpec.classpathElementResourcePathWhiteBlackList.whitelistAndBlacklistAreEmpty()) { if (scanSpec.classpathElementResourcePathWhiteBlackList.isBlacklisted(relativePath)) { if (log != null) { log.log("Reached blacklisted classpath element resource path, stopping scanning: " + relativePath); } skipClasspathElement = true; return; } if (scanSpec.classpathElementResourcePathWhiteBlackList.isSpecificallyWhitelisted(relativePath)) { if (log != null) { log.log("Reached specifically whitelisted classpath element resource path: " + relativePath); } containsSpecificallyWhitelistedClasspathElementResourcePath = true; } } } /** * Apply relative path masking within this classpath resource -- remove relative paths that were found in an * earlier classpath element. * * @param classpathIdx * the classpath index * @param classpathRelativePathsFound * the classpath relative paths found * @param log * the log */ void maskClassfiles(final int classpathIdx, final Set<String> classpathRelativePathsFound, final LogNode log) { if (!scanSpec.performScan) { // Should not happen throw new IllegalArgumentException("performScan is false"); } // Find relative paths that occur more than once in the classpath / module path. // Usually duplicate relative paths occur only between classpath / module path elements, not within, // but actually there is no restriction for paths within a zipfile to be unique, and in fact // zipfiles in the wild do contain the same classfiles multiple times with the same exact path, // e.g.: xmlbeans-2.6.0.jar!org/apache/xmlbeans/xml/stream/Location.class final List<Resource> whitelistedClassfileResourcesFiltered = new ArrayList<>( whitelistedClassfileResources.size()); boolean foundMasked = false; for (final Resource res : whitelistedClassfileResources) { final String pathRelativeToPackageRoot = res.getPath(); // Don't mask module-info.class or package-info.class, these are read for every module/package, // and they don't result in a ClassInfo object, so there will be no duplicate ClassInfo objects // created, even if they are encountered multiple times. Instead, any annotations on modules or // packages are merged into the appropriate ModuleInfo / PackageInfo object. if (!pathRelativeToPackageRoot.equals("module-info.class") && !pathRelativeToPackageRoot.equals("package-info.class") && !pathRelativeToPackageRoot.endsWith("/package-info.class") // Check if pathRelativeToPackageRoot has been seen before && !classpathRelativePathsFound.add(pathRelativeToPackageRoot)) { // This relative path has been encountered more than once; // mask the second and subsequent occurrences of the path foundMasked = true; if (log != null) { log.log(String.format("%06d-1", classpathIdx), "Ignoring duplicate (masked) class " + JarUtils.classfilePathToClassName(pathRelativeToPackageRoot) + " found at " + res); } } else { whitelistedClassfileResourcesFiltered.add(res); } } if (foundMasked) { // Remove masked (duplicated) paths. N.B. this replaces the concurrent collection with a non-concurrent // collection, but this is the last time the collection is changed during a scan, and this method is // run from a single thread. whitelistedClassfileResources = whitelistedClassfileResourcesFiltered; } } /** * Add a resource discovered during the scan. * * @param resource * the resource * @param parentMatchStatus * the parent match status * @param isClassfileOnly * if true, only add the resource to the list of classfile resources, not to the list of * non-classfile resources * @param log * the log */ protected void addWhitelistedResource(final Resource resource, final ScanSpecPathMatch parentMatchStatus, final boolean isClassfileOnly, final LogNode log) { final String path = resource.getPath(); final boolean isClassFile = FileUtils.isClassfile(path); boolean isWhitelisted = false; if (isClassFile) { // Check classfile scanning is enabled, and classfile is not specifically blacklisted if (scanSpec.enableClassInfo && !scanSpec.classfilePathWhiteBlackList.isBlacklisted(path)) { // ClassInfo is enabled, and found a whitelisted classfile whitelistedClassfileResources.add(resource); isWhitelisted = true; } } else { // Resources are always whitelisted if found in whitelisted directories isWhitelisted = true; } if (!isClassfileOnly) { // Add resource to whitelistedResources, whether for a classfile or non-classfile resource whitelistedResources.add(resource); } // Write to log if enabled, and as long as classfile scanning is not disabled, and this is not // a blacklisted classfile if (log != null && isWhitelisted) { final String type = isClassFile ? "classfile" : "resource"; String logStr; switch (parentMatchStatus) { case HAS_WHITELISTED_PATH_PREFIX: logStr = "Found " + type + " within subpackage of whitelisted package: "; break; case AT_WHITELISTED_PATH: logStr = "Found " + type + " within whitelisted package: "; break; case AT_WHITELISTED_CLASS_PACKAGE: logStr = "Found specifically-whitelisted " + type + ": "; break; default: logStr = "Found whitelisted " + type + ": "; break; } // Precede log entry sort key with "0:file:" so that file entries come before dir entries for // ClasspathElementDir classpath elements resource.scanLog = log.log("0:" + path, logStr + path + (path.equals(resource.getPathRelativeToClasspathElement()) ? "" : " ; full path: " + resource.getPathRelativeToClasspathElement())); } } /** * Called by scanPaths() after scan completion. * * @param log * the log */ protected void finishScanPaths(final LogNode log) { if (log != null) { if (whitelistedResources.isEmpty() && whitelistedClassfileResources.isEmpty()) { log.log(scanSpec.enableClassInfo ? "No whitelisted classfiles or resources found" : "Classfile scanning is disabled, and no whitelisted resources found"); } else if (whitelistedResources.isEmpty()) { log.log("No whitelisted resources found"); } else if (whitelistedClassfileResources.isEmpty()) { log.log(scanSpec.enableClassInfo ? "No whitelisted classfiles found" : "Classfile scanning is disabled"); } } if (log != null) { log.addElapsedTime(); } } /** * Write entries to log in classpath / module path order. * * @param classpathElementIdx * the classpath element idx * @param msg * the log message * @param log * the log * @return the new {@link LogNode} */ protected LogNode log(final int classpathElementIdx, final String msg, final LogNode log) { return log.log(String.format("%07d", classpathElementIdx), msg); } /** * Determine if this classpath element is valid. If it is not valid, sets skipClasspathElement. For * {@link ClasspathElementZip}, may also open or extract inner jars, and also causes jarfile manifests to be * read to look for Class-Path entries. If nested jars or Class-Path entries are found, they are added to the * work queue. This method is only run once per classpath element, from a single thread. * * @param workQueue * the work queue * @param classpathElementIdx * the index of the classpath element within the classpath or module path. * @param log * the log * @throws InterruptedException * if the thread was interrupted while trying to open the classpath element. */ abstract void open(final WorkQueue<ClasspathEntryWorkUnit> workQueue, final int classpathElementIdx, final LogNode log) throws InterruptedException; /** * Scan paths in the classpath element for whitelist/blacklist criteria, creating Resource objects for * whitelisted and non-blacklisted resources and classfiles. * * @param classpathElementIdx * the index of the classpath element within the classpath or module path. * @param log * the log */ abstract void scanPaths(final int classpathElementIdx, final LogNode log); /** * Get the {@link Resource} for a given relative path. * * @param relativePath * The relative path of the {@link Resource} to return. Path should have already be sanitized by * calling {@link FileUtils#sanitizeEntryPath(String, boolean)}, or by providing a path that is * already sanitized (i.e. doesn't start or end with "/", doesn't contain "/../" or "/./", etc.). * @return The {@link Resource} for the given relative path, or null if relativePath does not exist in this * classpath element. */ abstract Resource getResource(final String relativePath); /** * Get the URI for this classpath element. * * @return the URI for the classpath element. */ abstract URI getURI(); /** * Get the file for this classpath element, or null if this is a module with a "jrt:" URI. * * @return the file for the classpath element. */ abstract File getFile(); /** * Get the name of this classpath element's module, or null if there is no module name. * * @return the module name */ abstract String getModuleName(); }
package io.github.kkysen.quicktrip.app; import io.github.kkysen.quicktrip.apis.hotels.scrape.ScrapedHotelsHotel; import io.github.kkysen.quicktrip.optimization.simulatedAnnealing.AnnealingState; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.stream.IntStream; public class Hotels implements AnnealingState { private static final double RATING_SCALE_FACTOR = 0.1; private static final Random random = new Random(); // these never change, so not cloned private final int size; private final List<List<Hotel>> pools; private final List<Integer> numDays; private final List<Double> avgRatings; private final double maxRating; private final int budget; private final List<Hotel> hotels; private Hotel prevHotel; private int prevIndex; public Hotels(final List<Destination> dests, final int budget) { this.budget = budget; size = dests.size(); pools = new ArrayList<>(size); numDays = new ArrayList<>(size); // getPossibleHotels takes a while, so did it parallel // b/c parallel, order won't be defined it use dests::add // therefore must make IntStream of indices and use pools.set(i, hotels) for (int i = 0; i < size; i++) { pools.add(null); avgRatings.add(null); } IntStream.range(0, dests.size()) .parallel() .forEach(i -> { final Destination dest = dests.get(i); dest.addHotelsHotelsScrapeRequest(); List<Hotel> possibleHotels = dest.getPossibleHotels(); pools.set(i, possibleHotels); double totalRating = 0; for (Hotel hotel : possibleHotels) { totalRating += hotel.getRating(); } double avgRating = totalRating / possibleHotels.size(); avgRatings.set(i, avgRating); }); // FIXME idk why this is happening // check for empty pools for (int i = 0; i < size; i++) { final List<Hotel> pool = pools.get(i); if (pool.size() == 0) { System.err.println("no hotels found for " + dests.get(i)); pool.add(ScrapedHotelsHotel.DUMMY); } } int totalDays = 0; for (final Destination dest : dests) { final int singleNumDays = dest.getNumDays(); numDays.add(singleNumDays); totalDays += singleNumDays; } maxRating = totalDays * 5; hotels = new ArrayList<>(size); for (final List<Hotel> pool : pools) { hotels.add(pool.get(random.nextInt(pool.size()))); } } private Hotels(final Hotels other) { size = other.size; pools = other.pools; numDays = other.numDays; maxRating = other.maxRating; budget = other.budget; hotels = new ArrayList<>(other.hotels); prevHotel = other.prevHotel; prevIndex = other.prevIndex; } @Override public void perturb() { prevIndex = random.nextInt(size); final List<Hotel> randPool = pools.get(prevIndex); prevHotel = hotels.set(prevIndex, randPool.get(random.nextInt(randPool.size()))); } @Override public void undo() { hotels.set(prevIndex, prevHotel); prevHotel = null; // free mem } public int totalPrice() { int totalPrice = 0; for (int i = 0; i < size; i++) { totalPrice += hotels.get(i).getPrice() * numDays.get(i); } return totalPrice; } private double priceEnergy() { double priceDiff = totalPrice() - budget; if (priceDiff > 0) { priceDiff = Math.exp(priceDiff); } return priceDiff; } public double totalRating() { int totalRating = 0; for (int i = 0; i < size; i++) { totalRating += hotels.get(i).getRating() * numDays.get(i); } return totalRating; } private double ratingEnergy() { //final double ratingDiff = totalRating() - maxRating; //return -Math.exp(-ratingDiff); int totalRatingDiff = 0; for (int i = 0; i < size; i++) { double ratingDiff = hotels.get(i).getRating() * numDays.get(i); totalRatingDiff = avgRatings.get(i) - ratingDiff; } return Math.pow(totalRatingDiff / maxRating, 3) * RATING_SCALE_FACTOR; } @Override public double energy() { return priceEnergy() * ratingEnergy(); // FIXME I have no idea if this is good } @Override public AnnealingState clone() { return new Hotels(this); } public List<Hotel> getHotels() { return new ArrayList<>(hotels); } }
package isomorphly.reflect; import isomorphly.IsomorphlyValidationException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; public class IsomorphlyRegistry { private Map<String, Map<String, Method>> methods; private Map<String, Object> instances; public IsomorphlyRegistry(Map<String, Map<String, Method>> map) throws IsomorphlyValidationException { this.methods = new HashMap<>(); this.instances = new HashMap<>(); for (String className : map.keySet()) { try { Class<?> cls = Class.forName(className); Object obj = cls.newInstance(); instances.put(className, obj); } catch (ClassNotFoundException e) { throw new IsomorphlyValidationException(e.getMessage()); } catch (InstantiationException e) { throw new IsomorphlyValidationException(e.getMessage()); } catch (IllegalAccessException e) { throw new IsomorphlyValidationException(e.getMessage()); } Map<String, Method> annotatedMethods = map.get(className); // methods currently registered Map<String, Method> registeredMethods = methods.get(className); if (registeredMethods == null) { registeredMethods = new HashMap<>(); } for (String methodName : annotatedMethods.keySet()) { registeredMethods.put(methodName, annotatedMethods.get(methodName)); } methods.put(className, registeredMethods); } } }
package it.richkmeli.RMC.swing; import it.richkmeli.RMC.controller.App; import it.richkmeli.RMC.controller.network.NetworkException; import it.richkmeli.RMC.model.Device; import it.richkmeli.RMC.model.ModelException; import it.richkmeli.RMC.utils.Logger; import it.richkmeli.RMC.utils.ResponseParser; import it.richkmeli.RMC.view.View; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Base64; import java.util.List; public class RichkwarePanel implements View { private JFrame MainFrame; private JPanel LoginPanel; private JPasswordField passwordField; private JTextField emailField; private JTextField protocoloField; private JTextField serverField; private JTextField serviceField; private JTextField portField; private JButton loginButton; private JLabel errorField; private JPanel FIRST_BLOCK; private JPanel MainPanel; private JPanel StartSkipPanel; private JButton SkipButton; private JPanel AFTER_LOGIN; private JPanel ServerInfoPanel; private JPanel ButtonsPanel; private JButton Disconnect; private JButton refresh; private JCheckBox encryptionCheckBox; private JProgressBar progressBar1; private JScrollPane TableScrollPanel; private JTable InfoTable; private JPanel SendCommandsPanel; private JPanel ConnectToDevicePanel; private JCheckBox directCheckBox; private JButton ConnectDevice; private JButton DisconnectDevice; private JTextField addressOfDeviceTextField; private JCheckBox forceEncryptionCommandCheckBox; private JScrollPane DeviceResponseScrollPanel; private JPanel DeviceResponsePanel; private JTextArea DeviceResponseTextArea; private JButton SendCommandButton; private JTextField commandToSendTextField; private JPanel DIRECT_CONNECT; private JPanel ConnectToDevicePanelDirect; private JPanel CommandsPanelDirect; private JCheckBox directCheckBoxDirect; private JButton ConnectDeviceDirect; private JButton DisconnectDeviceDirect; private JTextField addressOfDeviceTextFieldDirect; private JCheckBox forceEncryptionCommandCheckBoxDirect; private JScrollPane DeviceResponseScrollPanelDirect; private JPanel DeviceResponsePanelDirect; private JTextArea DeviceResponseTextAreaDirect; private JButton SendCommandButtonDirect; private JTextField commandToSendTextFieldDirect; private JButton loginDirect; private JPanel SendCommandPanelDirect; private JTabbedPane tabbedPane1; private JButton ConnectDeviceReverse; private JButton DisconnectDeviceReverse; private JCheckBox forceEncryptionCommandCheckBoxReverse; private JButton SendCommandButtonReverse; private JTextArea CommandsTextAreaReverse; private JPanel ReverseCmmandsPanel; private JButton ReceiveResponseButtonReverse; private JPanel DirectConnectPanel; private App app; private List<Device> deviceList; private Device device; private List<Device> devices; @Override public void initialize() { MainFrame = new JFrame(); MainFrame.setTitle("Richkware-Manager-Client"); MainFrame.setContentPane(MainPanel); MainFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); MainFrame.pack(); MainFrame.setVisible(true); } public RichkwarePanel(App app) { this.app = app; initialize(); loadLoginPanel(); } private void loadLoginPanel() { FIRST_BLOCK.setVisible(true); DIRECT_CONNECT.setVisible(false); AFTER_LOGIN.setVisible(false); MainFrame.pack(); if (loginButton.getActionListeners().length == 0) { loginButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { String email = emailField.getText(); String password = passwordField.getText(); try { app.getController().getNetwork().setURL(protocoloField.getText(), serverField.getText(), portField.getText(), serviceField.getText()); } catch (NetworkException e) { errorField.setText(e.getMessage()); } app.getController().login(email, password, false, new RichkwareCallback() { @Override public void onSuccess(String response) { errorField.setText(" "); loadDevicesPanel(); } @Override public void onFailure(String response) { errorField.setText(ResponseParser.parseMessage(response)); errorField.setVisible(true); } }); } }); } if (SkipButton.getActionListeners().length == 0) { SkipButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { loadDirectConnectPanel(); } }); } } private void loadDevicesPanel() { FIRST_BLOCK.setVisible(false); DIRECT_CONNECT.setVisible(false); AFTER_LOGIN.setVisible(true); MainFrame.pack(); deviceList = new ArrayList<>(); // jtable InfoTable initialisation try { InfoTable.setModel(new DeviceTableModel(deviceList)); } catch (NullPointerException npe) { System.err.println(npe.getMessage()); } refreshTable(); if (refresh.getActionListeners().length == 0) { refresh.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { refreshTable(); } }); } if (Disconnect.getActionListeners().length == 0) { Disconnect.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // deviceList = new ArrayList<Device>(); // InfoTable.setModel(new DeviceTableModel(deviceList)); app.getController().logout(false, new RichkwareCallback() { @Override public void onSuccess(String response) { deviceList.clear(); InfoTable.setModel(new DeviceTableModel(deviceList)); loadLoginPanel(); } @Override public void onFailure(String response) { errorPanel(response); } }); } }); } loadConnectPanel(); } private void loadConnectPanel() { Logger.i("loading openSocket panel"); connectPanel(SendCommandButton, commandToSendTextField, DeviceResponseTextArea, ConnectDevice, directCheckBox, addressOfDeviceTextField, forceEncryptionCommandCheckBox, DisconnectDevice, Connect.DEFAULT); Logger.i("loaded openSocket panel"); if (SendCommandButtonReverse.getActionListeners().length == 0) { SendCommandButtonReverse.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String command = CommandsTextAreaReverse.getText(); if (command.compareTo("") == 0 || command.compareTo("Command to send") == 0) { Logger.e("Write the command to execute on device"); } else { app.getController().reverseCommand(command, false, new RichkwareCallback() { @Override public void onSuccess(String s) { //TODO COMMANDS SEND } @Override public void onFailure(String response) { errorPanel(response + ": " + response); } }); } } }); } if (ConnectDeviceReverse.getActionListeners().length == 0) { ConnectDeviceReverse.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int devicesCount = getSelectedDeviceCount(); Logger.i("connect"); if (devicesCount == 1) { clearTable(); app.getController().connectDevice(getSelectedDevice()); } else if (devicesCount > 1) { clearTable(); app.getController().connectDevice(getSelectedDevices()); } else { errorPanel("Select a device"); } } }); } if (ReceiveResponseButtonReverse.getActionListeners().length == 0) { ReceiveResponseButtonReverse.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { app.getController().reverseCommandResponse(device, new RichkwareCallback() { @Override public void onSuccess(String response) { response = new String(Base64.getDecoder().decode(ResponseParser.parseMessage(response))); CommandsTextAreaReverse.setText(response); } @Override public void onFailure(String response) { errorPanel(response); } }); } }); } if (DisconnectDeviceReverse.getActionListeners().length == 0) { DisconnectDeviceReverse.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { clearTable(); } }); } } private void loadDirectConnectPanel() { FIRST_BLOCK.setVisible(false); DIRECT_CONNECT.setVisible(true); AFTER_LOGIN.setVisible(false); MainFrame.pack(); if (loginDirect.getActionListeners().length == 0) { loginDirect.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { loadLoginPanel(); } }); } connectPanel(SendCommandButtonDirect, commandToSendTextFieldDirect, DeviceResponseTextAreaDirect, ConnectDeviceDirect, directCheckBoxDirect, addressOfDeviceTextFieldDirect, forceEncryptionCommandCheckBoxDirect, DisconnectDeviceDirect, Connect.DIRECT); } private void errorPanel(String err) { JOptionPane.showMessageDialog(MainFrame, err, "Error", JOptionPane.ERROR_MESSAGE); } private void connectPanel(JButton SendCommandButton, JTextField commandToSendTextField, JTextArea DeviceResponseTextArea, JButton ConnectDevice, JCheckBox directCheckBox, JTextField addressOfDeviceTextField, JCheckBox forceEncryptionCommandCheckBox, JButton DisconnectDevice, Connect connetionType) { devices = new ArrayList<>(); disableInput(connetionType); if (SendCommandButton.getActionListeners().length == 0) { SendCommandButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String command = commandToSendTextField.getText(); if (command.compareTo("") == 0 || command.compareTo("Command to send") == 0) { Logger.e("Write the command to execute on device"); } else { app.getController().sendCommand(command, new RichkwareCallback() { @Override public void onSuccess(String response) { Logger.i("Response: " + response); DeviceResponseTextArea.append(response); DeviceResponseTextArea.setLineWrap(true); } @Override public void onFailure(String error) { Logger.e("Error: " + error); } }); } } }); } if (ConnectDevice.getActionListeners().length == 0) { ConnectDevice.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (directCheckBox.isSelected()) { //Direct command to selected devices from table String ipport = addressOfDeviceTextField.getText(); device = new Device("", ipport.substring(0, ipport.indexOf(":")), ipport.substring(ipport.indexOf(":") + 1, ipport.length()), "", "", ""); app.getController().openSocket(device, forceEncryptionCommandCheckBox.isSelected(), new RichkwareCallback() { @Override public void onSuccess(String response) { enableInput(); } @Override public void onFailure(String response) { errorPanel(response); } }); } else { int devicesCount = getSelectedDeviceCount(); if (devicesCount == 1) { clearTable(); device = getSelectedDevice(); if (device.getServerPort().compareTo("none") == 0) { clearTable(); errorPanel("ServerPort of this device is closed"); } else { app.getController().openSocket(device, forceEncryptionCommandCheckBox.isSelected(), new RichkwareCallback() { @Override public void onSuccess(String response) { addressOfDeviceTextField.setText(device.getIp() + ":" + device.getServerPort()); enableInput(); } @Override public void onFailure(String response) { errorPanel(response); } }); } } else if (devicesCount > 1) { clearTable(); devices = getSelectedDevices(); //TODO check device ip and port app.getController().openSocket(devices, forceEncryptionCommandCheckBox.isSelected(), new RichkwareCallback() { @Override public void onSuccess(String response) { addressOfDeviceTextField.setText("Multiple devies"); enableInput(); } @Override public void onFailure(String response) { errorPanel(response); } }); } else { errorPanel("Select a device"); } } } }); } if (DisconnectDevice.getActionListeners().length == 0) { DisconnectDevice.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { clearTable(); disableInput(connetionType); } }); } if (directCheckBox.getActionListeners().length == 0) { directCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (directCheckBox.isSelected()) { addressOfDeviceTextField.setText(""); addressOfDeviceTextField.setEnabled(true); } else { addressOfDeviceTextField.setText("Address of device"); commandToSendTextField.setEnabled(false); } } }); } if (addressOfDeviceTextField.getActionListeners().length == 0) { addressOfDeviceTextField.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { super.mouseClicked(e); // addressOfDeviceTextField.setText(""); } }); } if (addressOfDeviceTextField.getActionListeners().length == 0) { commandToSendTextField.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { super.mouseClicked(e); // commandToSendTextField.setText(""); } }); } } private void refreshTable() { Thread t = new Thread(new Runnable() { @Override public void run() { try { progressBar1.setValue(0); // if encryption check box is selected, RMC uses encryption to refresh the list of devices app.getController().devicesList(encryptionCheckBox.isSelected(), new ListCallback() { @Override public void onSuccess(List<Device> response) { deviceList = (List<Device>) response; progressBar1.setValue(20); InfoTable.setModel(new DeviceTableModel(deviceList)); progressBar1.setValue(40); updateRowHeights(InfoTable); } @Override public void onFailure(String response) { } }); //InfoTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); } catch (ModelException e1) { errorPanel(e1.toString()); e1.printStackTrace(); } } }); t.start(); } private void clearTable() { device = null; devices.clear(); } private void updateRowHeights(JTable jTable) { Component comp; double singleStep = 50.0 / jTable.getRowCount(); progressBar1.setValue(50); double count = 50.0; for (int row = 0; row < jTable.getRowCount(); row++) { int rowHeight = jTable.getRowHeight(); for (int column = 0; column < jTable.getColumnCount(); column++) { comp = jTable.prepareRenderer(jTable.getCellRenderer(row, column), row, column); rowHeight = Math.max(rowHeight, comp.getPreferredSize().height); } count += singleStep; progressBar1.setValue((int) Math.round(count)); jTable.setRowHeight(row, rowHeight); } progressBar1.setValue(100); } private int getSelectedDeviceCount() { // InfoTable.setDefaultRenderer(Object.class, new DefaultTableCellRenderer(){ // @Override // public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) { // super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col); // if (devices.contains(deviceList.get(row)) || device == deviceList.get(row)) { // setBackground(Color.GREEN); // setForeground(Color.WHITE); // } else { // setBackground(table.getBackground()); // setForeground(table.getForeground()); // return this; return InfoTable.getSelectedRowCount(); } private Device getSelectedDevice() { return deviceList.get(InfoTable.getSelectedRow()); } private List<Device> getSelectedDevices() { List<Device> list = new ArrayList<>(); for (int i : InfoTable.getSelectedRows()) list.add(deviceList.get(i)); return list; } private void disableInput(Connect connectionType) { Logger.i("disable"); commandToSendTextField.setEnabled(false); commandToSendTextFieldDirect.setEnabled(false); directCheckBox.setEnabled(true); directCheckBoxDirect.setEnabled(true); if (connectionType == Connect.DIRECT) { directCheckBox.setEnabled(false); directCheckBoxDirect.setEnabled(false); directCheckBox.setSelected(true); directCheckBoxDirect.setSelected(true); } if (directCheckBox.isSelected() || directCheckBoxDirect.isSelected()) { addressOfDeviceTextField.setEnabled(true); addressOfDeviceTextFieldDirect.setEnabled(true); } else { addressOfDeviceTextField.setText("Address of device"); addressOfDeviceTextFieldDirect.setText("Address of device"); addressOfDeviceTextField.setEnabled(false); addressOfDeviceTextFieldDirect.setEnabled(false); } SendCommandButton.setEnabled(false); SendCommandButtonDirect.setEnabled(false); DisconnectDevice.setEnabled(false); DisconnectDeviceDirect.setEnabled(false); ConnectDevice.setEnabled(true); ConnectDeviceDirect.setEnabled(true); } private void enableInput() { Logger.i("enable"); commandToSendTextField.setEnabled(true); commandToSendTextFieldDirect.setEnabled(true); directCheckBox.setEnabled(false); directCheckBoxDirect.setEnabled(false); addressOfDeviceTextField.setEnabled(false); addressOfDeviceTextFieldDirect.setEnabled(false); SendCommandButton.setEnabled(true); SendCommandButtonDirect.setEnabled(true); DisconnectDevice.setEnabled(true); DisconnectDeviceDirect.setEnabled(true); ConnectDevice.setEnabled(false); ConnectDeviceDirect.setEnabled(false); } private enum Connect { DEFAULT(0), DIRECT(1), REVERSE(2); private int code; Connect(int code) { this.code = code; } } }
package javax.validation.constraints; import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.CONSTRUCTOR; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE_USE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; import javax.validation.constraints.NotBlank.List; /** * The annotated element must not be {@code null} and must contain at least one non-whitespace character. Accepts * {@code CharSequence}. * * @author Hardy Ferentschik * @since 2.0 * * @see Character#isWhitespace(char) */ @Documented @Constraint(validatedBy = { }) @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE }) @Retention(RUNTIME) @Repeatable(List.class) public @interface NotBlank { String message() default "{javax.validation.constraints.NotBlank.message}"; Class<?>[] groups() default { }; Class<? extends Payload>[] payload() default { }; /** * Defines several {@code @NotBlank} constraints on the same element. * * @see NotBlank */ @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE }) @Retention(RUNTIME) @Documented public @interface List { NotBlank[] value(); } }
package me.hugmanrique.pokedata.tiles; import lombok.Getter; import me.hugmanrique.pokedata.Data; import me.hugmanrique.pokedata.compression.Lz77; import me.hugmanrique.pokedata.graphics.ImageType; import me.hugmanrique.pokedata.graphics.Palette; import me.hugmanrique.pokedata.graphics.ROMImage; import me.hugmanrique.pokedata.roms.ROM; import me.hugmanrique.pokedata.utils.BitConverter; import me.hugmanrique.pokedata.utils.ImageUtils; import java.awt.image.BufferedImage; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * @author Hugmanrique * @since 02/07/2017 */ @Getter public class Tileset extends Data { public static final int MAX_TIME = 4; public static final int MAIN_PAL_COUNT = 6; private static final int MAIN_HEIGHT = 0x100; private static final int LOCAL_HEIGHT = 0x100; public static final int MAIN_SIZE = 0x200; public static final int LOCAL_SIZE = 0x200; public static final int MAIN_BLOCKS = 0x200; public static int LOCAL_BLOCKS = 0xFE; // Cache last primary as it's used a lot private static Tileset lastPrimary; private TilesetHeader header; private ROMImage image; private BufferedImage[][] images; private Palette[][] palettes; private Map<Integer, BufferedImage>[] renderedTiles; private int blockCount; public Tileset(ROM rom) { header = new TilesetHeader(rom); blockCount = header.isPrimary() ? MAIN_BLOCKS : LOCAL_BLOCKS; render(rom); } public static Tileset load(ROM rom, int offset) { rom.seek(offset); return new Tileset(rom); } public void render(ROM rom) { renderPalettes(rom); renderGraphics(rom); } private void renderPalettes(ROM rom) { palettes = new Palette[MAX_TIME][16]; images = new BufferedImage[MAX_TIME][16]; for (int i = 0; i < MAX_TIME; i++) { for (int j = 0; j < 16; j++) { int offset = (int) header.getPalettesPtr() + (32 * j) + (i * 0x200); byte[] data = rom.readBytes(offset, 32); palettes[i][j] = new Palette(ImageType.C16, data); } } } private void renderGraphics(ROM rom) { int imgDataPtr = (int) header.getTilesetImgPtr(); if (header.isPrimary()) { lastPrimary = this; } int[] data; final int height = getHeight(); if (header.isCompressed()) { data = Lz77.decompress(rom, imgDataPtr); } else { // Pull uncompressed data int size = height * 128 / 2; data = BitConverter.toInts(rom.readBytes(imgDataPtr, size)); } renderedTiles = new HashMap[16 * 4]; for (int i = 0; i < 16 * MAX_TIME; i++) { renderedTiles[i] = new HashMap<>(); } image = new ROMImage(palettes[0][0], data, 128, height); } public void startTileLoaders() { for (int i = 0; i < (header.isPrimary() ? MAIN_PAL_COUNT : 13); i++) { new TileLoader(this, renderedTiles, i).start(); } } public BufferedImage getTile(int tileIndex, int palette, boolean flipX, boolean flipY, int time) { if (palette < MAIN_PAL_COUNT) { // Check if tile is cached Map<Integer, BufferedImage> tiles = renderedTiles[palette + (time * 16)]; if (tiles.containsKey(tileIndex)) { BufferedImage image = tiles.get(tileIndex); return applyTransforms(image, flipX, flipY); } } else if (palette >= 13) { String error = String.format( "[WARN] Attempted to read tile %s of palette %s in %s tileset", tileIndex, palette, header.isPrimary() ? "global" : "local" ); System.out.println(error); // Return empty image return new BufferedImage(8, 8, BufferedImage.TYPE_INT_ARGB); } // Tile isn't cached int x = (tileIndex % (128 / 8)) * 8; int y = (tileIndex / (128 / 8)) * 8; BufferedImage image; try { image = images[time][palette].getSubimage(x, y, 8, 8); } catch (Exception ignored) { // Out of bounds // TODO Print warning image = new BufferedImage(8, 8, BufferedImage.TYPE_INT_ARGB); } if (palette < MAIN_PAL_COUNT || renderedTiles.length > MAIN_PAL_COUNT) { renderedTiles[palette + (time * 16)].put(tileIndex, image); } return applyTransforms(image, flipX, flipY); } private BufferedImage applyTransforms(BufferedImage image, boolean flipX, boolean flipY) { return ImageUtils.applyTransforms(image, flipX, flipY); } public void renderPalettedTiles() { for (int j = 0; j < MAX_TIME; j++) { for (int i = 0; i < 16; i++) { rerenderTileSet(j, i); } } } private void rerenderTileSet(int time, int palette) { images[time][palette] = image.getImage(palettes[time][palette]); } public Palette[] getPalette(int time) { return palettes[time]; } public void setPalettes(int time, Palette[] palettes) { this.palettes[time] = palettes; } private int getHeight() { return header.isPrimary() ? MAIN_HEIGHT : LOCAL_HEIGHT; } }
package me.nallar.javapatcher.patcher; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import com.google.common.collect.MultimapBuilder; import com.google.common.io.Files; import javassist.*; import lombok.val; import me.nallar.javapatcher.PatcherLog; import me.nallar.javapatcher.mappings.*; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.SAXException; import java.io.*; import java.lang.annotation.*; import java.lang.reflect.*; import java.util.*; /** * Patcher which uses javassist, a config file and a patcher class to patch arbitrary classes. */ public class Patcher { private static final String debugPatchedOutput = System.getProperty("patcher.debug", ""); private static final Splitter idSplitter = Splitter.on(" ").trimResults().omitEmptyStrings(); private final ClassPool classPool; private final Mappings mappings; private final Map<String, PatchMethodDescriptor> patchMethods = new HashMap<>(); private final Multimap<String, ClassPatchDescriptor> patches = MultimapBuilder.hashKeys().arrayListValues().build(); private final Map<String, byte[]> patchedBytes = new HashMap<>(); private Object patchClassInstance; /** * Creates a patcher instance * * @param classPool Javassist classpool set up with correct classpath containing needed classes */ public Patcher(ClassPool classPool) { this(classPool, Patches.class); } /** * Creates a patcher instance * * @param classPool Javassist classpool set up with correct classpath containing needed classes * @param patchesClass Class to instantiate containing @Patch annotated methods */ public Patcher(ClassPool classPool, Class<?> patchesClass) { this(classPool, patchesClass, new DefaultMappings()); } /** * Creates a patcher instance * * @param classPool Javassist classpool set up with correct classpath containing needed classes * @param patchesClass Class to instantiate containing @Patch annotated methods * @param mappings Mappings instance */ public Patcher(ClassPool classPool, Class<?> patchesClass, Mappings mappings) { for (Method method : patchesClass.getDeclaredMethods()) { for (Annotation annotation : method.getDeclaredAnnotations()) { if (annotation instanceof Patch) { PatchMethodDescriptor patchMethodDescriptor = new PatchMethodDescriptor(method, (Patch) annotation); if (patchMethods.put(patchMethodDescriptor.name, patchMethodDescriptor) != null) { PatcherLog.warn("Duplicate @Patch method with name " + patchMethodDescriptor.name); } } } } this.classPool = classPool; this.mappings = mappings; try { patchClassInstance = patchesClass.getDeclaredConstructors()[0].newInstance(classPool, mappings); } catch (Exception e) { PatcherLog.error("Failed to instantiate patch class", e); } } /** * Convenience method which reads an XML document from the input stream and passes it to readPatchesFromXMLDocument * * @param inputStream input stream to read from */ public void readPatchesFromXmlInputStream(InputStream inputStream) { readPatchesFromXmlString(DomUtil.readInputStreamToString(inputStream)); } /** * Convenience method which reads an XML document from the input stream and passes it to readPatchesFromXMLDocument * * @param inputStream input stream to read from */ public void readPatchesFromJsonInputStream(InputStream inputStream) { readPatchesFromJsonString(DomUtil.readInputStreamToString(inputStream)); } public void readPatchesFromJsonString(String json) { readPatchesFromXmlString(DomUtil.makePatchXmlFromJson(json)); } /** * Reads patches from the given XML Document * * @param document XML document */ public void readPatchesFromXmlString(String document) { try { readPatchesFromXmlDocument(DomUtil.readDocumentFromString(document)); } catch (IOException | SAXException e) { throw new RuntimeException(e); } } public void readPatchesFromXmlDocument(Document document) { List<Element> patchGroupElements = DomUtil.children(document.getDocumentElement()); for (Element patchGroupElement : patchGroupElements) { // TODO - rework this. Side-effect of object creation makes this look redundant when it isn't loadPatchGroup(patchGroupElement); } } /** * @return The Mappings */ public Mappings getMappings() { return mappings; } /** * @return The ClassPool */ public ClassPool getClassPool() { return classPool; } /** * Returns whether the given class will be patched * * @param className Name of the class to check * @return Whether a patch exists for that class */ public boolean willPatch(String className) { return !patches.get(className).isEmpty(); } /** * Patch the class with the given name, if it has a patch associated with it. * * @param className Name of the class * @return Returns patched class if needed, else returns null */ public byte[] patch(String className) { return patch(className, null); } /** * Patch the class with the given name, if it has a patch associated with it. * * @param className Name of the class * @param originalBytes original class bytes * @return Returns patched class if needed, else returns original class */ public synchronized byte[] patch(String className, byte[] originalBytes) { byte[] bytes = patchedBytes.get(className); if (bytes != null) { return bytes; } val patches = this.patches.get(className); if (patches.isEmpty()) { return originalBytes; } try { CtClass ctClass = classPool.get(className); for (val classPatchDescriptor : patches) { ctClass = classPatchDescriptor.runPatches(ctClass); } bytes = ctClass.toBytecode(); patchedBytes.put(className, bytes); saveByteCode(bytes, className); return bytes; } catch (Throwable t) { PatcherLog.error("Failed to patch " + className + " in patch group " + className + '.', t); return originalBytes; } } /** * Writes debug info about this patcher to the debug logger */ public void logDebugInfo() { PatcherLog.info("Logging Patcher debug info of " + patches.size() + " class patches"); for (ClassPatchDescriptor classPatch : patches.values()) { PatcherLog.info(classPatch.toString()); } } private static void saveByteCode(byte[] bytes, String name) { if (!debugPatchedOutput.isEmpty()) { name = name.replace('.', '/') + ".class"; File file = new File(debugPatchedOutput + '/' + name); //noinspection ResultOfMethodCallIgnored file.getParentFile().mkdirs(); try { Files.write(bytes, file); } catch (IOException e) { PatcherLog.error("Failed to save patched bytes for " + name, e); } } } private static class PatchDescriptor { private final Map<String, String> attributes; private final String patch; private String methods; PatchDescriptor(Element element) { attributes = DomUtil.getAttributes(element); methods = element.getTextContent().trim(); patch = element.getTagName(); } public String set(String name, String value) { return attributes.put(name, value); } public String get(String name) { return attributes.get(name); } public Map<String, String> getAttributes() { return attributes; } public String getMethods() { return methods; } public void setMethods(String methods) { this.methods = methods; } public String getPatch() { return patch; } } private static class PatchMethodDescriptor { public final String name; public final List<String> requiredAttributes; public final Method patchMethod; public final boolean isClassPatch; public final boolean emptyConstructor; private PatchMethodDescriptor(Method method, Patch patch) { String name = patch.name(); if (Arrays.asList(method.getParameterTypes()).contains(Map.class)) { this.requiredAttributes = Lists.newArrayList(Splitter.on(",").trimResults().omitEmptyStrings().split(patch.requiredAttributes())); } else { this.requiredAttributes = null; } if (name == null || name.isEmpty()) { name = method.getName(); } this.name = name; emptyConstructor = patch.emptyConstructor(); isClassPatch = method.getParameterTypes()[0].equals(CtClass.class); patchMethod = method; } public Object run(PatchDescriptor patchDescriptor, CtClass ctClass, Object patchClassInstance) { String methods = patchDescriptor.getMethods(); Map<String, String> attributes = patchDescriptor.getAttributes(); Map<String, String> attributesClean = new HashMap<>(attributes); attributesClean.remove("code"); PatcherLog.trace("Patching " + ctClass.getName() + " with " + this.name + '(' + CollectionsUtil.mapToString(attributesClean) + ')' + (methods.isEmpty() ? "" : " {" + methods + '}')); if (requiredAttributes != null && !requiredAttributes.isEmpty() && !attributes.keySet().containsAll(requiredAttributes)) { PatcherLog.error("Missing required attributes " + requiredAttributes.toString() + " when patching " + ctClass.getName()); return null; } if ("^all^".equals(methods)) { patchDescriptor.set("silent", "true"); List<CtBehavior> ctBehaviors = new ArrayList<>(); Collections.addAll(ctBehaviors, ctClass.getDeclaredMethods()); Collections.addAll(ctBehaviors, ctClass.getDeclaredConstructors()); CtBehavior initializer = ctClass.getClassInitializer(); if (initializer != null) { ctBehaviors.add(initializer); } for (CtBehavior ctBehavior : ctBehaviors) { run(ctBehavior, attributes, patchClassInstance); } } else if (isClassPatch || (!emptyConstructor && methods.isEmpty())) { return run(ctClass, attributes, patchClassInstance); } else if (methods.isEmpty()) { for (CtConstructor ctConstructor : ctClass.getDeclaredConstructors()) { run(ctConstructor, attributes, patchClassInstance); } } else if ("^static^".equals(methods)) { CtConstructor ctBehavior = ctClass.getClassInitializer(); if (ctBehavior == null) { PatcherLog.error("No static initializer found patching " + ctClass.getName() + " with " + toString()); } else { run(ctBehavior, attributes, patchClassInstance); } } else { List<MethodDescription> methodDescriptions = MethodDescription.fromListString(ctClass.getName(), methods); for (MethodDescription methodDescription : methodDescriptions) { CtMethod ctMethod; try { ctMethod = methodDescription.inClass(ctClass); } catch (Throwable t) { if (!attributes.containsKey("allowMissing")) { PatcherLog.warn("", t); } continue; } run(ctMethod, attributes, patchClassInstance); } } return null; } private Object run(CtClass ctClass, Map<String, String> attributes, Object patchClassInstance) { try { if (requiredAttributes == null) { return patchMethod.invoke(patchClassInstance, ctClass); } else { return patchMethod.invoke(patchClassInstance, ctClass, attributes); } } catch (Throwable t) { if (t instanceof InvocationTargetException) { t = t.getCause(); } if (t instanceof CannotCompileException && attributes.containsKey("code")) { PatcherLog.error("Code: " + attributes.get("code")); } PatcherLog.error("Error patching " + ctClass.getName() + " with " + toString(), t); return null; } } private Object run(CtBehavior ctBehavior, Map<String, String> attributes, Object patchClassInstance) { try { if (requiredAttributes == null) { return patchMethod.invoke(patchClassInstance, ctBehavior); } else { return patchMethod.invoke(patchClassInstance, ctBehavior, attributes); } } catch (Throwable t) { if (t instanceof InvocationTargetException) { t = t.getCause(); } if (t instanceof CannotCompileException && attributes.containsKey("code")) { PatcherLog.error("Code: " + attributes.get("code")); } PatcherLog.error("Error patching " + ctBehavior.getName() + " in " + ctBehavior.getDeclaringClass().getName() + " with " + toString(), t); return null; } } @Override public String toString() { return name; } } private void obfuscateAttributesAndTextContent(Element root) { // TODO - reimplement environments? /* for (Element classElement : DomUtil.children(root.getChildNodes())) { String env = classElement.getAttribute("env"); if (env != null && !env.isEmpty()) { if (!env.equals(getEnv())) { root.removeChild(classElement); } } } */ for (Element element : DomUtil.children(root)) { if (!DomUtil.children(element).isEmpty()) { obfuscateAttributesAndTextContent(element); } else if (element.getTextContent() != null && !element.getTextContent().isEmpty()) { element.setTextContent(mappings.obfuscate(element.getTextContent())); } Map<String, String> attributes = DomUtil.getAttributes(element); for (Map.Entry<String, String> attributeEntry : attributes.entrySet()) { element.setAttribute(attributeEntry.getKey(), mappings.obfuscate(attributeEntry.getValue())); } } for (Element element : DomUtil.children(root)) { String id = element.getAttribute("id"); ArrayList<String> list = Lists.newArrayList(idSplitter.split(id)); if (list.size() > 1) { for (String className : list) { Element newClassElement = (Element) element.cloneNode(true); newClassElement.setAttribute("id", className.trim()); element.getParentNode().insertBefore(newClassElement, element); } element.getParentNode().removeChild(element); } } } private void loadPatchGroup(Element e) { Map<String, String> attributes = DomUtil.getAttributes(e); String requiredProperty = attributes.get("requireProperty"); if (requiredProperty != null && !requiredProperty.isEmpty() && !Boolean.getBoolean(requiredProperty)) { // Required property attribute isn't set as system property return; } obfuscateAttributesAndTextContent(e); val patchElements = DomUtil.children(e); for (Element classElement : patchElements) { ClassPatchDescriptor classPatchDescriptor; try { classPatchDescriptor = new ClassPatchDescriptor(classElement); } catch (Throwable t) { throw new RuntimeException("Failed to create class patch for " + classElement.getAttribute("id"), t); } patches.put(classPatchDescriptor.name, classPatchDescriptor); } } public class ClassPatchDescriptor { public final String name; public final List<PatchDescriptor> patches = new ArrayList<>(); private final Map<String, String> attributes; private ClassPatchDescriptor(Element element) { attributes = DomUtil.getAttributes(element); ClassDescription deobfuscatedClass = new ClassDescription(attributes.get("id")); ClassDescription obfuscatedClass = mappings.map(deobfuscatedClass); name = obfuscatedClass == null ? deobfuscatedClass.name : obfuscatedClass.name; for (Element patchElement : DomUtil.children(element)) { PatchDescriptor patchDescriptor = new PatchDescriptor(patchElement); patches.add(patchDescriptor); List<MethodDescription> methodDescriptionList = MethodDescription.fromListString(deobfuscatedClass.name, patchDescriptor.getMethods()); if (!patchDescriptor.getMethods().isEmpty()) { patchDescriptor.set("deobf", methodDescriptionList.get(0).getShortName()); patchDescriptor.setMethods(MethodDescription.toListString(mappings.map(methodDescriptionList))); } String field = patchDescriptor.get("field"), prefix = ""; if (field != null && !field.isEmpty()) { if (field.startsWith("this.")) { field = field.substring("this.".length()); prefix = "this."; } String after = "", type = name; if (field.indexOf('.') != -1) { after = field.substring(field.indexOf('.')); field = field.substring(0, field.indexOf('.')); if (!field.isEmpty() && (field.charAt(0) == '$') && prefix.isEmpty()) { ArrayList<String> parameterList = new ArrayList<>(); for (MethodDescription methodDescriptionOriginal : methodDescriptionList) { MethodDescription methodDescription = mappings.unmap(mappings.map(methodDescriptionOriginal)); methodDescription = methodDescription == null ? methodDescriptionOriginal : methodDescription; int i = 0; for (String parameter : methodDescription.getParameterList()) { if (parameterList.size() <= i) { parameterList.add(parameter); } else if (!parameterList.get(i).equals(parameter)) { parameterList.set(i, null); } i++; } } int parameterIndex = Integer.valueOf(field.substring(1)) - 1; if (parameterIndex >= parameterList.size()) { if (!parameterList.isEmpty()) { PatcherLog.error("Can not obfuscate parameter field " + patchDescriptor.get("field") + ", index: " + parameterIndex + " but parameter list is: " + Joiner.on(',').join(parameterList)); } break; } type = parameterList.get(parameterIndex); if (type == null) { PatcherLog.error("Can not obfuscate parameter field " + patchDescriptor.get("field") + " automatically as this parameter does not have a single type across the methods used in this patch."); break; } prefix = field + '.'; field = after.substring(1); after = ""; } } FieldDescription obfuscatedField = mappings.map(new FieldDescription(type, field)); if (obfuscatedField != null) { patchDescriptor.set("field", prefix + obfuscatedField.name + after); } } } } public CtClass runPatches(CtClass ctClass) throws NotFoundException { for (PatchDescriptor patchDescriptor : patches) { PatchMethodDescriptor patchMethodDescriptor = patchMethods.get(patchDescriptor.getPatch()); if (patchMethodDescriptor == null) { PatcherLog.error("Couldn't find patch with name " + patchDescriptor.getPatch() + " when patching " + ctClass.getName()); return ctClass; } Object result = patchMethodDescriptor.run(patchDescriptor, ctClass, patchClassInstance); if (result instanceof CtClass) { ctClass = (CtClass) result; } } return ctClass; } } }
package me.xorgon.connect4.util; import com.google.common.base.Preconditions; import com.supaham.commons.bukkit.players.Players; import com.supaham.commons.bukkit.utils.BlockFaceUtils; import com.supaham.commons.utils.WeakSet; import me.xorgon.connect4.C4Properties; import me.xorgon.connect4.Connect4Plugin; import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.entity.FallingBlock; import org.bukkit.entity.Player; import org.bukkit.material.MaterialData; import org.bukkit.scheduler.BukkitTask; import org.bukkit.util.Vector; import java.util.*; public class PhysicalBoard { private Map<Integer, Block> slots = new HashMap<>(); private List<Block> spaces = new ArrayList<>(); private Map<Block, Integer> buttons = new HashMap<>(); private Block joinButton; private Player redPlayer; private Player bluePlayer; private VirtualBoard board; private String tag; private BlockFace face; private final C4Properties.Board config; private final World world; private boolean canInteract = true; private boolean started = false; private boolean redTurn = true; private boolean finished = false; private Vector center; private BukkitTask initTimer; private BukkitTask finTimer; private WeakSet<FallingBlock> fallingBlocks = new WeakSet<>(); public PhysicalBoard(World world, C4Properties.Board serialized) { Preconditions.checkArgument(BlockFaceUtils.isHorizontal(serialized.getFace()), "Block face must be horizontal."); this.world = world; config = serialized; board = new VirtualBoard(); loadBoard(world); center = config.getRegion().getMaximumPoint().clone().midpoint(config.getRegion().getMinimumPoint()); } public void resetBoard() { for (Vector space : config.getRegion()) { space.toLocation(world).getBlock().setType(Material.AIR); } board.initialize(); finished = false; canInteract = true; if (initTimer != null){ initTimer.cancel(); } if (finTimer != null){ finTimer.cancel(); } } public void resetPlayers() { redPlayer = null; bluePlayer = null; started = false; redTurn = true; } public void placePiece(Player player, int column) { if ((player == redPlayer && redTurn) || (player == bluePlayer && !redTurn)) { MaterialData material; //Virtual Board VirtualBoard.SpaceType piece; if (player == redPlayer) { piece = VirtualBoard.SpaceType.RED; material = config.getRedBlock(); } else { piece = VirtualBoard.SpaceType.BLUE; material = config.getBlueBlock(); } if (board.placePiece(column, piece)) { //Physical Board Block slot = slots.get(column); FallingBlock block = (FallingBlock) slot.getWorld().spawnFallingBlock(slot.getLocation().add(0, 1, 0), material.getItemType(), material.getData()); fallingBlocks.add(block); canInteract = false; initTimer.cancel(); finTimer.cancel(); } else { player.sendMessage(ChatColor.RED + "You can't place a piece there."); } } else { player.sendMessage(ChatColor.RED + "It is not your turn."); } } public void handleFallingBlock(FallingBlock block) { VirtualBoard.WinStatus winStatus = board.testWin(); if (winStatus != VirtualBoard.WinStatus.NONE && winStatus != VirtualBoard.WinStatus.DRAW) { boolean redWin = winStatus == VirtualBoard.WinStatus.RED; String winString = (redWin ? ChatColor.RED + redPlayer.getName() : ChatColor.BLUE + bluePlayer.getName()) + ChatColor.YELLOW + " wins!"; String announce = (redWin ? ChatColor.RED + redPlayer.getName() : ChatColor.BLUE + bluePlayer.getName()) + ChatColor.YELLOW + " beat " + (!redWin ? ChatColor.RED + redPlayer.getName() : ChatColor.BLUE + bluePlayer.getName()) + ChatColor.YELLOW + " at Connect 4!"; Collection<? extends Player> players = Players.playersByRadius(Players.worldPlayers(block.getWorld()), 20).get(block.getLocation()); for (Player player : players) { player.sendMessage(announce); } TitleUtil.sendTitle(redPlayer, winString, redWin ? ChatColor.YELLOW + "Congratulations!" : ChatColor.YELLOW + "Better luck next time."); TitleUtil.sendTitle(bluePlayer, winString, !redWin ? ChatColor.YELLOW + "Congratulations!" : ChatColor.YELLOW + "Better luck next time."); finished = true; Bukkit.getScheduler().runTaskLater(Connect4Plugin.getInstance(), new Runnable() { @Override public void run() { resetBoard(); resetPlayers(); } }, 10 * 20); } else if (winStatus == VirtualBoard.WinStatus.DRAW){ TitleUtil.sendTitle(redPlayer, ChatColor.YELLOW + "It's a draw!",""); TitleUtil.sendTitle(bluePlayer, ChatColor.YELLOW + "It's a draw!",""); finished = true; Bukkit.getScheduler().runTaskLater(Connect4Plugin.getInstance(), new Runnable() { @Override public void run() { resetBoard(); resetPlayers(); } }, 10 * 20); } else { canInteract = true; if (redTurn) { redTurn = false; TitleUtil.sendTitle(bluePlayer, ChatColor.YELLOW + "Your turn!"); } else { redTurn = true; TitleUtil.sendTitle(redPlayer, ChatColor.YELLOW + "Your turn!"); } resetTimers(); } fallingBlocks.remove(block); } public void loadBoard(World world) { Location min = config.getRegion().getMinimumPoint().toLocation(world); Location max = config.getRegion().getMaximumPoint().toLocation(world); int width = 0; int offX = 0; int offZ = 0; if (min.getBlockX() == max.getBlockX()) { width = max.getBlockZ() - min.getBlockZ(); offZ = 1; } else { width = max.getBlockX() - min.getBlockX(); offX = 1; } for (int i = 0; i < width + 1; i++) { Block button = min.clone().add(offX * i, -1, offZ * i).getBlock().getRelative(config.getFace().getOppositeFace()); buttons.put(button, i); int height = max.getBlockY() - min.getBlockY() - 1; Block slot = min.clone().add(offX * i, height, offZ * i).getBlock(); slots.put(i, slot); } resetBoard(); } public void resetTimers(){ initTimer = Bukkit.getScheduler().runTaskLater(Connect4Plugin.getInstance(), new Runnable() { @Override public void run() { if (redTurn) { TitleUtil.sendTitle(redPlayer, ChatColor.RED + "10 Seconds"); } else { TitleUtil.sendTitle(bluePlayer, ChatColor.RED + "10 Seconds"); } } }, 50 * 20); finTimer = Bukkit.getScheduler().runTaskLater(Connect4Plugin.getInstance(), new Runnable() { @Override public void run() { if (redTurn) { TitleUtil.sendTitle(redPlayer, ChatColor.RED + "You forfeit the game.", ChatColor.YELLOW + "You ran out of time."); TitleUtil.sendTitle(bluePlayer, ChatColor.RED + redPlayer.getName() + ChatColor.YELLOW + " forfeit.", ChatColor.YELLOW + "They ran out of time."); } else { TitleUtil.sendTitle(bluePlayer, ChatColor.RED + "You forfeit the game.", ChatColor.YELLOW + "You ran out of time."); TitleUtil.sendTitle(redPlayer, ChatColor.BLUE + bluePlayer.getName() + ChatColor.YELLOW + " forfeit.", ChatColor.YELLOW + "They ran out of time."); } resetBoard(); resetPlayers(); } }, 60 * 20); } public WeakSet<FallingBlock> getFallingBlocks() { return fallingBlocks; } public Player getRedPlayer() { return redPlayer; } public Player getBluePlayer() { return bluePlayer; } public Vector getCenter() { return center; } public boolean isFinished() { return finished; } public void setRedPlayer(Player redPlayer) { this.redPlayer = redPlayer; } public void setBluePlayer(Player bluePlayer) { this.bluePlayer = bluePlayer; } public boolean isStarted() { return started; } public boolean isCanInteract() { return canInteract; } public Map<Block, Integer> getButtons() { return buttons; } public void setStarted(boolean started) { this.started = started; } public VirtualBoard getBoard() { return board; } }
package me.zero.client.api.event; import me.zero.client.api.event.type.EventPriority; import me.zero.client.api.exception.UnexpectedOutcomeException; import me.zero.client.api.util.ReflectionUtils; import java.lang.reflect.Field; import java.util.*; import java.util.stream.Collectors; public final class EventManager { /** * HashMap containing all Listeners for various Events */ private static final Map<Class<?>, List<Listener>> SUBSCRIPTION_MAP = new HashMap<>(); /** * Buffer used while making modifications to {@code SUBSCRIPTION_MAP} * * @see #subscribe(Object) * @see #unsubscribe(Object) */ private static final List<Listener> eventBuffer = new ArrayList<>(); /** * Discovers all valid methods from the Object * specified and then registers them in the * form of {@code Listeners} * * @see me.zero.client.api.event.Listener * @see #subscribe(Object, Field) * * @since 1.0 * * @param object The object containing possible Event Methods */ public static void subscribe(Object object) { Arrays.stream(object.getClass().getDeclaredFields()) .filter(EventManager::isValidField) .forEach(field -> subscribe(object, field)); } /** * Creates a listener from the specified object and method. * After the listener is created, it is passed to the listener * subscription method. * * @see #subscribe(Listener) * * @since 1.0 * * @param object Parent object * @param field Listener field */ private static void subscribe(Object object, Field field) { Listener listener = (Listener) ReflectionUtils.getField(object, field); if (listener.getPriority() > EventPriority.LOWEST || listener.getPriority() < EventPriority.HIGHEST) throw new UnexpectedOutcomeException("Event Priority out of bounds! %s"); subscribe(listener); } /** * Subscribes a Listener to the Subscription Map * * @since 1.0 * * @param listener The listener being registered */ private static void subscribe(Listener listener) { eventBuffer.clear(); List<Listener> listeners = SUBSCRIPTION_MAP.get(listener.getTarget()); if (listeners != null && listeners.size() > 0) eventBuffer.addAll(listeners); int index = 0; if (!eventBuffer.isEmpty()) { for (; index < eventBuffer.size(); index++) { if (listener.getPriority() < eventBuffer.get(index).getPriority()) { break; } } } eventBuffer.add(index, listener); SUBSCRIPTION_MAP.put(listener.getTarget(), new ArrayList<>(eventBuffer)); } /** * Unregisters the Event Listeners from * the specified object * * @see #subscribe(Object) * * @since 1.0 * * @param object The object being unsubscribed */ public static void unsubscribe(Object object) { List<Listener> objectListeners = Arrays.stream(object.getClass().getDeclaredFields()) .filter(EventManager::isValidField) .map(field -> (Listener) ReflectionUtils.getField(object, field)).collect(Collectors.toList()); SUBSCRIPTION_MAP.keySet().forEach(eventClass -> SUBSCRIPTION_MAP.put(eventClass, SUBSCRIPTION_MAP.get(eventClass).stream() .filter(listener -> !objectListeners.contains(listener)) .collect(Collectors.toList()) )); } /** * Checks if a Field is a valid Event Handler field. * Done by checking the field type and presence * of the {@code EventHandler} annotation; * * @see me.zero.client.api.event.EventHandler * * @since 1.0 * * @param field Field being checked * @return Whether or not the Field is valid */ private static boolean isValidField(Field field) { return field.isAnnotationPresent(EventHandler.class) && field.getType() == Listener.class; } /** * Posts an event to all registered {@code Listeners}. * Done via Reflection Method Invokation * * @see me.zero.client.api.event.Listener#invoke(Object) * * @since 1.0 * * @param event Event being called */ public static void post(Object event) { List<Listener> listeners = SUBSCRIPTION_MAP.get(event.getClass()); if (listeners != null) listeners.forEach(listener -> listener.invoke(event)); } }
package mil.dds.anet.beans.lists; import io.leangen.graphql.annotations.GraphQLInputField; import io.leangen.graphql.annotations.GraphQLQuery; import java.util.List; import org.jdbi.v3.core.mapper.RowMapper; import org.jdbi.v3.core.statement.Query; public class AnetBeanList<T> { @GraphQLQuery @GraphQLInputField List<T> list; @GraphQLQuery @GraphQLInputField Integer pageNum; @GraphQLQuery @GraphQLInputField Integer pageSize; @GraphQLQuery @GraphQLInputField Integer totalCount; public AnetBeanList() { /* Serialization Constructor */ } public AnetBeanList(List<T> list) { this(null, null, list); this.totalCount = list.size(); } public AnetBeanList(Integer pageNum, Integer pageSize, List<T> list) { this.pageNum = pageNum; this.pageSize = pageSize; this.list = list; } public AnetBeanList(Query query, int pageNum, int pageSize, RowMapper<T> mapper) { this(pageNum, pageSize, query.map(mapper).list()); final Integer foundCount = (Integer) query.getContext().getAttribute("totalCount"); if (foundCount != null) { // Total count was found in the query results, use it setTotalCount(foundCount); } else { // Get the number of results actually retrieved int resultSize = getList().size(); // Check if that is zero if (resultSize == 0) { // We may have a pagination overshoot, so set the size to the last item on the previous page resultSize = pageNum * pageSize; } // Make sure size is always non-negative setTotalCount(Math.max(0, resultSize)); } } public List<T> getList() { return list; } public void setList(List<T> list) { this.list = list; } public Integer getPageNum() { return pageNum; } public void setPageNum(Integer pageNum) { this.pageNum = pageNum; } public Integer getPageSize() { return pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } public Integer getTotalCount() { return totalCount; } public void setTotalCount(Integer totalCount) { this.totalCount = totalCount; } }
package models.bipartite_matching; import javafx.util.Pair; import logic.FordFulkersonAlgorithm; import logic.MaximumProfitAlgorithm; import org.apache.logging.log4j.Logger; import servers.LocalServer; import java.util.*; public class FlowNetwork { private Map<Vertex, Map<Vertex, Boolean>> mapFromSource = new HashMap<>(); private Map<Vertex, Map<Vertex, Boolean>> mapToSink = new HashMap<>(); private int maximumFlow; private int totalTaskMatches = 0; private int totalEmployeeMatches = 0; private BipartiteGraph bipartiteGraph; private Class strategyClass; private Logger logger; private static final Integer SOURCE_ID = -1; private static final Integer SINK_ID = -2; public static final Vertex SOURCE_VERTEX = new Vertex(SOURCE_ID, VertexType.SOURCE); public static final Vertex SINK_VERTEX = new Vertex(SINK_ID, VertexType.SINK); private final Pair<Vertex, Map<Vertex, Boolean>> SOURCE = new Pair(SOURCE_VERTEX, new HashMap<>()); private final Pair<Vertex, Map<Vertex, Boolean>> SINK = new Pair(SINK_VERTEX, new HashMap<>()); public FlowNetwork() { } public FlowNetwork(BipartiteGraph bipartiteGraph) { strategyClass = bipartiteGraph.strategyClass; if (strategyClass.equals(MaximumProfitAlgorithm.class)) { logger = LocalServer.mpLogger; } else if (strategyClass.equals(FordFulkersonAlgorithm.class)) { logger = LocalServer.ffLogger; } mapToSink = new HashMap<>(); this.bipartiteGraph = bipartiteGraph; //initialises mapFromSource for Network flow mapFromSource = bipartiteGraph.getTaskMap(); //initialises mapToSink for Network flow mapToSink = new HashMap<>(); bipartiteGraph.getEmployeeMap().keySet().forEach(employeeVertex -> { Map<Vertex, Boolean> adjacentVertices = new HashMap(); adjacentVertices.put(SINK_VERTEX, false); mapToSink.put(employeeVertex, adjacentVertices); //LocalServer.ffLogger.trace("employee "+ employeeId); }); //initialises source mapFromSource.keySet().forEach(taskVertex -> SOURCE.getValue().put(taskVertex, false)); } public Map<Vertex, Map<Vertex, Boolean>> getMapFromSource() { return mapFromSource; } public Map<Vertex, Map<Vertex, Boolean>> getMapToSink() { return mapToSink; } public Pair<Vertex, Map<Vertex, Boolean>> getSink() { return SINK; } public Pair<Vertex, Map<Vertex, Boolean>> getSource() { return SOURCE; } public void printGraph() { logger.trace("\n==========================NETWORK START=============="); logger.trace(" Map<Vertex, Boolean> sourceEdges = SOURCE.getValue(); sourceEdges.forEach((vertex, isVisited) -> logger.trace("\tsource: {}", vertex.toString())); logger.trace(" mapFromSource.keySet().forEach( vertex -> { logger.trace("\t{} : ", vertex.toString()); Map<Vertex, Boolean> edges = mapFromSource.get(vertex); edges.forEach( (adjacentVertex, isVisited)-> { if (adjacentVertex.equals(SOURCE_VERTEX)) { logger.trace("\t\t\tsource, "); } else { logger.trace("\t\t\t{}, ", adjacentVertex.toString()); } }); }); logger.trace(" mapToSink.keySet().forEach( vertex -> { logger.trace("\t{} :",vertex.toString()); Map<Vertex, Boolean> edges = mapToSink.get(vertex); edges.forEach( (adjacentVertex, isVisited) -> { if (adjacentVertex.equals(SINK_VERTEX)) { LocalServer.mpLogger.trace("\t\t\tsink, "); } else { logger.trace("\t\t\t{}, ", adjacentVertex.toString()); } }); }); logger.trace(" Map<Vertex, Boolean> sinkEdges = SINK.getValue(); if (sinkEdges !=null){ sinkEdges.forEach((vertex, isVisited) -> logger.trace("\tsink: {}, ", vertex.toString())); } logger.trace("===========================NETWORK END==============\n"); } }
package net.dean.jraw.managers; import com.fasterxml.jackson.databind.JsonNode; import com.google.common.collect.ImmutableList; import net.dean.jraw.AccountPreferencesEditor; import net.dean.jraw.ApiException; import net.dean.jraw.EndpointImplementation; import net.dean.jraw.Endpoints; import net.dean.jraw.JrawUtils; import net.dean.jraw.RedditClient; import net.dean.jraw.http.MediaTypes; import net.dean.jraw.http.NetworkException; import net.dean.jraw.http.RequestBody; import net.dean.jraw.http.RestResponse; import net.dean.jraw.models.AccountPreferences; import net.dean.jraw.models.Captcha; import net.dean.jraw.models.Contribution; import net.dean.jraw.models.FlairTemplate; import net.dean.jraw.models.KarmaBreakdown; import net.dean.jraw.models.PublicContribution; import net.dean.jraw.models.Submission; import net.dean.jraw.models.Subreddit; import net.dean.jraw.models.Thing; import net.dean.jraw.models.UserRecord; import net.dean.jraw.models.VoteDirection; import net.dean.jraw.models.attr.Votable; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; /** * This class manages common user actions, such as voting, commenting, saving, etc. */ public class AccountManager extends AbstractManager { /** * Instantiates a new AccountManager * @param client The RedditClient to use */ public AccountManager(RedditClient client) { super(client); } /** * Submits a new link * * @param b The SubmissionBuilder to gather data from * @return A representation of the newly submitted Submission * @throws NetworkException If the request was not successful * @throws net.dean.jraw.ApiException If the Reddit API returned an error */ public Submission submit(SubmissionBuilder b) throws NetworkException, ApiException { return submit(b, null, null); } /** * Submits a new link with a given captcha. Only really needed if the user has less than 10 link karma. * * @param b The SubmissionBuilder to gather data from * @param captcha The Captcha the user is attempting * @param captchaAttempt The user's guess at the captcha * @return A representation of the newly submitted Submission * @throws NetworkException If the request was not successful * @throws ApiException If the API returned an error */ @EndpointImplementation(Endpoints.SUBMIT) public Submission submit(SubmissionBuilder b, Captcha captcha, String captchaAttempt) throws NetworkException, ApiException { Map<String, String> args = JrawUtils.mapOf( "api_type", "json", "extension", "json", "kind", b.selfPost ? "self" : "link", "resubmit", b.resubmit, "save", b.saveAfter, "sendreplies", b.sendRepliesToInbox, "sr", b.subreddit, "then", "comments", "title", b.title ); if (b.selfPost) { args.put("text", b.selfText); } else { args.put("url", b.url.toExternalForm()); } if (captcha != null) { if (captchaAttempt == null) { throw new IllegalArgumentException("Captcha present but the attempt is not"); } args.put("iden", captcha.getId()); args.put("captcha", captchaAttempt); } RestResponse response = genericPost(reddit.request() .endpoint(Endpoints.SUBMIT) .post(args) .build()); return reddit.getSubmission(response.getJson().get("json").get("data").get("id").asText()); } /** * Votes on a comment or submission. Please note that "API clients proxying a human's action one-for-one are OK, but * bots deciding how to vote on content or amplifying a human's vote are not". * * @param s The submission to vote on * @param voteDirection How to vote * @param <T> The Votable Thing to vote on * @throws NetworkException If the request was not successful * @throws ApiException If the API returned an error */ @EndpointImplementation(Endpoints.VOTE) public <T extends Thing & Votable> void vote(T s, VoteDirection voteDirection) throws NetworkException, ApiException { genericPost(reddit.request() .endpoint(Endpoints.VOTE) .post(JrawUtils.mapOf( "api_type", "json", "dir", voteDirection.getValue(), "id", s.getFullName()) ).build()); } /** * Saves a given submission * @param s The submission to save * @throws NetworkException If the request was not successful * @throws ApiException If the API returned an error */ public void save(PublicContribution s) throws NetworkException, ApiException { setSaved(s, true); } /** * Unsaves a given submission * @param s The submission to unsave * @throws NetworkException If the request was not successful * @throws ApiException If the API returned an error */ public void unsave(PublicContribution s) throws NetworkException, ApiException { setSaved(s, false); } /** * Saves or unsaves a submission. * * @param s The submission to save or unsave * @param save Whether or not to save the submission * @throws NetworkException If the request was not successful * @throws ApiException If the API returned an error */ @EndpointImplementation({Endpoints.SAVE, Endpoints.UNSAVE}) private void setSaved(PublicContribution s, boolean save) throws NetworkException, ApiException { // Send it to "/api/save" if save == true, "/api/unsave" if save == false genericPost(reddit.request() .endpoint(save ? Endpoints.SAVE : Endpoints.UNSAVE) .post(JrawUtils.mapOf( "id", s.getFullName() )).build()); } /** * Sets whether or not replies to this submission should be sent to your inbox. You must own this Submission. * * @param s The submission to modify * @param send Whether or not to send replies to your inbox * @throws NetworkException If the request was not successful * @throws ApiException If the API returned an error */ @EndpointImplementation(Endpoints.SENDREPLIES) public void sendRepliesToInbox(Submission s, boolean send) throws NetworkException, ApiException { genericPost(reddit.request() .endpoint(Endpoints.SENDREPLIES) .post(JrawUtils.mapOf( "id", s.getFullName(), "state", send )).build()); } /** * Sets whether or not a submission is hidden * * @param s The submission to hide or unhide * @param hide If the submission is to be hidden * @throws NetworkException If the request was not successful * @throws ApiException If the API returned an error */ @EndpointImplementation({Endpoints.HIDE, Endpoints.UNHIDE}) public void hide(Submission s, boolean hide) throws NetworkException, ApiException { genericPost(reddit.request() .endpoint(hide ? Endpoints.HIDE : Endpoints.UNHIDE) .post(JrawUtils.mapOf( "id", s.getFullName() )).build()); } /** * Changes the text of your * * @param submission The submission that that you would like to edit the text for * @param text The new text that you want the post to have * @throws NetworkException If the request was not successful * @throws ApiException If the API returned an error */ @EndpointImplementation(Endpoints.EDITUSERTEXT) public void updateSelfpost(Submission submission, String text) throws NetworkException, ApiException { genericPost(reddit.request().endpoint(Endpoints.EDITUSERTEXT) .post(JrawUtils.mapOf( "api_type", "json", "text", text, "thing_id", submission.getFullName() )).build()); } /** * Sends a reply to a Comment, Submission, or Message. * * @param contribution The contribution to reply to * @param text The body of the message, formatted in Markdown * @return The ID of the newly created reply * @throws NetworkException If the request was not successful * @throws ApiException If the Reddit API returned an error */ @EndpointImplementation(Endpoints.COMMENT) public <T extends Contribution> String reply(T contribution, String text) throws NetworkException, ApiException { RestResponse response = genericPost(reddit.request() .endpoint(Endpoints.COMMENT) .post(JrawUtils.mapOf( "api_type", "json", "text", text, "thing_id", contribution.getFullName() )).build()); return response.getJson().get("json").get("data").get("things").get(0).get("data").get("id").asText(); } /** * Subscribes to a subreddit * @param subreddit The subreddit to subscribe to * @throws NetworkException If the request was not successful * @see #unsubscribe(Subreddit) */ @EndpointImplementation(Endpoints.SUBSCRIBE) public void subscribe(Subreddit subreddit) throws NetworkException { setSubscribed(subreddit, true); } /** * Unsubscribes from a subreddit * @param subreddit The subreddit to unsubscribe to * @throws NetworkException If the request was not successful * @see #subscribe(Subreddit) */ public void unsubscribe(Subreddit subreddit) throws NetworkException { setSubscribed(subreddit, false); } /** * Subscribe or unsubscribe to a subreddit * * @param subreddit The subreddit to (un)subscribe to * @param sub Whether to subscribe (true) or unsubscribe (false) * @throws NetworkException If the request was not successful */ private void setSubscribed(Subreddit subreddit, boolean sub) throws NetworkException { reddit.execute(reddit.request() .endpoint(Endpoints.SUBSCRIBE) .post(JrawUtils.mapOf( "sr", subreddit.getFullName(), "action", sub ? "sub" : "unsub" // JSON is returned on subscribe, HTML is returned on unsubscribe )).build()); } /** * Gets a list of possible flair templates for this subreddit. See also: {@link #getFlairChoices(Submission)}, * {@link #getCurrentFlair(String)}, {@link #getCurrentFlair(Submission)} * * @param subreddit The subreddit to look up * @return A list of flair templates * @throws NetworkException If the request was not successful * @throws ApiException If the Reddit API returned an error */ @EndpointImplementation(Endpoints.FLAIRSELECTOR) public List<FlairTemplate> getFlairChoices(String subreddit) throws NetworkException, ApiException { ImmutableList.Builder<FlairTemplate> templates = ImmutableList.builder(); for (JsonNode choiceNode : getFlairChoicesRootNode(subreddit, null).get("choices")) { templates.add(new FlairTemplate(choiceNode)); } return templates.build(); } /** * Gets a list of possible flair templates for this submission * @param link The submission to look up * @return A list of flair templates * @throws NetworkException If the request was not successful * @throws ApiException If the Reddit API returned an error */ public List<FlairTemplate> getFlairChoices(Submission link) throws NetworkException, ApiException { ImmutableList.Builder<FlairTemplate> templates = ImmutableList.builder(); for (JsonNode choiceNode : getFlairChoicesRootNode(link.getSubredditName(), link).get("choices")) { templates.add(new FlairTemplate(choiceNode)); } return templates.build(); } /** * Gets the current user flair for this subreddit * @param subreddit The subreddit to look up * @return The flair template that is being used by the authenticated user * @throws NetworkException If the request was not successful * @throws ApiException If the Reddit API returned an error */ public FlairTemplate getCurrentFlair(String subreddit) throws NetworkException, ApiException { return new FlairTemplate(getFlairChoicesRootNode(subreddit, null).get("current")); } /** * Gets the current user flair for this subreddit * @param link The submission to look up * @return The given submission's current flair * @throws NetworkException If the request was not successful * @throws ApiException If the Reddit API returned an error */ public FlairTemplate getCurrentFlair(Submission link) throws NetworkException, ApiException { return new FlairTemplate(getFlairChoicesRootNode(link.getSubredditName(), link).get("current")); } /** * Enables or disables user flair on a subreddit * @param subreddit The subreddit to enable or disable flair on * @param enabled If user flair is enabled * @throws NetworkException If the request was not successful * @throws ApiException If the API returned an error */ @EndpointImplementation(Endpoints.SETFLAIRENABLED) public void setFlairEnabled(String subreddit, boolean enabled) throws NetworkException, ApiException { RestResponse response = reddit.execute(reddit.request() .path("/r/" + subreddit + Endpoints.SETFLAIRENABLED.getEndpoint().getUri()) .post(JrawUtils.mapOf( "api_type", "json", "enabled", enabled )) .build()); if (response.hasErrors()) { throw response.getError(); } } /** Gives gold to a comment or submission */ @EndpointImplementation(Endpoints.OAUTH_GOLD_GILD_FULLNAME) public void giveGold(PublicContribution target) throws NetworkException, ApiException { genericPost(reddit.request() .endpoint(Endpoints.OAUTH_GOLD_GILD_FULLNAME, target.getFullName()) .post() .build()); } /** Gives creddits to a user */ @EndpointImplementation(Endpoints.OAUTH_GOLD_GIVE_USERNAME) public void giveGold(String username, int months) throws NetworkException, ApiException { genericPost(reddit.request() .endpoint(Endpoints.OAUTH_GOLD_GIVE_USERNAME, username) .post(JrawUtils.mapOf("months", months)) .build()); } @EndpointImplementation(Endpoints.OAUTH_ME_PREFS_GET) public AccountPreferences getPreferences(String... names) throws NetworkException { Map<String, String> query = new HashMap<>(); if (names.length > 0) { query.put("fields", JrawUtils.join(',', names)); } RestResponse response = reddit.execute(reddit.request() .endpoint(Endpoints.OAUTH_ME_PREFS_GET) .query(query) .build()); return new AccountPreferences(response.getJson()); } /** * Updates the preferences for this account * @param prefs The preferences * @return The preferences after they were updated * @throws NetworkException If the request was not successful */ @EndpointImplementation(Endpoints.OAUTH_ME_PREFS_PATCH) public AccountPreferences updatePreferences(AccountPreferencesEditor prefs) throws NetworkException { RestResponse response = reddit.execute(reddit.request() .endpoint(Endpoints.OAUTH_ME_PREFS_PATCH) .patch(RequestBody.create(MediaTypes.JSON.type(), JrawUtils.toJson(prefs.getArgs()))) .build()); return new AccountPreferences(response.getJson()); } /** * Gets a breakdown of link and comment karma by subreddit * @return A KarmaBreakdown for this account * @throws NetworkException If the request was not successful */ @EndpointImplementation(Endpoints.OAUTH_ME_KARMA) public KarmaBreakdown getKarmaBreakdown() throws NetworkException { RestResponse response = reddit.execute(reddit.request() .endpoint(Endpoints.OAUTH_ME_KARMA) .build()); return new KarmaBreakdown(response.getJson().get("data")); } /** * Removes a friend * @param friend The username of the friend * @throws NetworkException If the request was not successful */ @EndpointImplementation(Endpoints.OAUTH_ME_FRIENDS_USERNAME_DELETE) public void deleteFriend(String friend) throws NetworkException { reddit.execute(reddit.request() .delete() .endpoint(Endpoints.OAUTH_ME_FRIENDS_USERNAME_DELETE, friend) .build()); } /** * Gets a user record pertaining to a particular relationship * @param name The name of the user * @return A UserRecord representing the relationship * @throws NetworkException If the request was not successful */ @EndpointImplementation(Endpoints.OAUTH_ME_FRIENDS_USERNAME_GET) public UserRecord getFriend(String name) throws NetworkException { RestResponse response = reddit.execute(reddit.request() .endpoint(Endpoints.OAUTH_ME_FRIENDS_USERNAME_GET, name) .build()); return new UserRecord(response.getJson()); } /** * Adds of updates a friend * @param name The name of the user * @throws NetworkException If the request was not successful * @return A UserRecord representing the new or updated relationship */ @EndpointImplementation(Endpoints.OAUTH_ME_FRIENDS_USERNAME_PUT) public UserRecord updateFriend(String name) throws NetworkException { RestResponse response = reddit.execute(reddit.request() .put(RequestBody.create(MediaTypes.JSON.type(), JrawUtils.toJson(new FriendModel(name)))) .endpoint(Endpoints.OAUTH_ME_FRIENDS_USERNAME_PUT, name) .build()); return new UserRecord(response.getJson()); } private static final class FriendModel { private final String name; private FriendModel(String name) { this.name = name == null ? "" : name; } public String getName() { return name; } } private JsonNode getFlairChoicesRootNode(String subreddit, Submission link) throws NetworkException, ApiException { String linkFullname = link != null ? link.getFullName() : null; Map<String, String> formArgs = new HashMap<>(); if (linkFullname != null) { formArgs.put("link", linkFullname); } RestResponse response = genericPost(reddit.request() .path("/r/" + subreddit + Endpoints.FLAIRSELECTOR.getEndpoint().getUri()) .post(formArgs.isEmpty() ? null : formArgs) .build()); return response.getJson(); } /** * This class provides a way to configure posting parameters of a new submission */ public static class SubmissionBuilder { private final boolean selfPost; private final String selfText; private final URL url; private final String subreddit; private final String title; private boolean saveAfter; // = false; private boolean sendRepliesToInbox; // = false; private boolean resubmit = true; /** * Instantiates a new SubmissionBuilder that will result in a self post. * @param selfText The body text of the submission, formatted in Markdown * @param subreddit The subreddit to submit the link to (e.g. "funny", "pics", etc.) * @param title The title of the submission */ public SubmissionBuilder(String selfText, String subreddit, String title) { this.selfPost = true; this.selfText = selfText; this.url = null; this.subreddit = subreddit; this.title = title; } /** * Instantiates a new SubmissionBuilder that will result in a link post. * @param url The URL that this submission will link to * @param subreddit The subreddit to submit the link to (e.g. "funny", "pics", etc.) * @param title The title of the submission */ public SubmissionBuilder(URL url, String subreddit, String title) { this.selfPost = false; this.url = url; this.selfText = null; this.subreddit = subreddit; this.title = title; } /** * Whether to save after right after posting * @param flag To save or not to save, that is the question * @return This builder */ public SubmissionBuilder saveAfter(boolean flag) { this.saveAfter = flag; return this; } /** * Whether to send top-level replies to your inbox * @param flag Send replies to your inbox? * @return This builder */ public SubmissionBuilder sendRepliesToInbox(boolean flag) { this.sendRepliesToInbox = flag; return this; } /** * Set whether or not the Reddit API will return an error if the link's URL has already been posted * @param flag If there should be an exception if there is already a post like this * @return This builder */ public SubmissionBuilder resubmit(boolean flag) { this.resubmit = flag; return this; } } }
package net.dongliu.apk.parser.io; import net.dongliu.apk.parser.bean.Locale; import net.dongliu.apk.parser.exception.ParserException; import net.dongliu.apk.parser.struct.*; import net.dongliu.apk.parser.struct.resource.*; import java.io.IOException; import java.util.List; /** * @author dongliu */ public class StreamUtils { /** * read string from input stream. if get EOF before read enough data, throw IOException. */ public static String readString(TellableInputStream in, StringEncoding encoding) throws IOException { if (encoding == StringEncoding.UTF8) { // The lengths are encoded in the same way as for the 16-bit format // but using 8-bit rather than 16-bit integers. int strLen = readLen(in); int bytesLen = readLen(in); byte[] bytes = in.readBytes(bytesLen); String str = new String(bytes, "UTF-8"); // zero int trailling = in.readUByte(); return str; } else { // The length is encoded as either one or two 16-bit integers as per the commentRef... int strLen = readLen16(in); String str = in.readStringUTF16(strLen); // zero int trailling = in.readUShort(); return str; } } /** * read utf-16 encoding str, use zero char to end str. * * @param in * @param strLen * @return * @throws IOException */ public static String readStringUTF16(TellableInputStream in, int strLen) throws IOException { String str = in.readStringUTF16(strLen); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (c == 0) { return str.substring(0, i); } } return str; } /** * read encoding len. * see Stringpool.cpp ENCODE_LENGTH * * @param in * @return * @throws IOException */ private static int readLen(TellableInputStream in) throws IOException { int len = 0; int i = in.read(); if ((i & 0x80) != 0) { //read one more byte. len |= (i & 0x7f) << 7; len += in.read(); } else { len = i; } return len; } /** * read encoding len. * see Stringpool.cpp ENCODE_LENGTH * * @param in * @return * @throws IOException */ private static int readLen16(TellableInputStream in) throws IOException { int len = 0; int i = in.readUShort(); if ((i & 0x8000) != 0) { len |= (i & 0x7fff) << 15; len += in.readUShort(); } else { len = i; } return len; } /** * read String pool * * @param in * @param stringPoolHeader * @return * @throws IOException */ public static StringPool readStringPool(TellableInputStream in, StringPoolHeader stringPoolHeader) throws IOException { long beginPos = in.tell(); long[] offsets = new long[(int) stringPoolHeader.stringCount]; // read strings offset if (stringPoolHeader.stringCount > 0) { for (int idx = 0; idx < stringPoolHeader.stringCount; idx++) { offsets[idx] = in.readUInt(); } } // read flag boolean sorted = (stringPoolHeader.flags & StringPoolHeader.SORTED_FLAG) != 0; StringEncoding stringEncoding = (stringPoolHeader.flags & StringPoolHeader.UTF8_FLAG) != 0 ? StringEncoding.UTF8 : StringEncoding.UTF16; // read strings. the head and metas have 28 bytes long stringPos = beginPos + stringPoolHeader.stringsStart - stringPoolHeader.headerSize; in.advanceIfNotRearch(stringPos); StringPool stringPool = new StringPool((int) stringPoolHeader.stringCount); for (int idx = 0; idx < offsets.length; idx++) { in.advanceIfNotRearch(stringPos + offsets[idx]); String str = StreamUtils.readString(in, stringEncoding); stringPool.set(idx, str); } // read styles if (stringPoolHeader.styleCount > 0) { // now we just skip it } in.advanceIfNotRearch(beginPos + stringPoolHeader.chunkSize - stringPoolHeader.headerSize); return stringPool; } /** * method to read resource value RGB/ARGB type. * * @return */ public static String readRGBs(TellableInputStream in, int strLen) throws IOException { long l = in.readUInt(); StringBuilder sb = new StringBuilder(); for (int i = strLen / 2 - 1; i >= 0; i sb.append(Integer.toHexString((int) ((l >> i * 8) & 0xff))); } return sb.toString(); } /** * read res value, convert from different types to string. * * @param in * @param stringPool * @return * @throws IOException */ public static ResValue readResValue(TellableInputStream in, StringPool stringPool, ResourceTable resourceTable, boolean isStyle, Locale locale) throws IOException { ResValue resValue = new ResValue(); resValue.size = in.readUShort(); resValue.res0 = in.readUByte(); resValue.dataType = in.readUByte(); switch (resValue.dataType) { case ResValue.ResType.INT_DEC: case ResValue.ResType.INT_HEX: resValue.data = String.valueOf(in.readInt()); break; case ResValue.ResType.STRING: int strRef = in.readInt(); if (strRef > 0) { resValue.data = stringPool.get(strRef); } break; case ResValue.ResType.REFERENCE: long resourceId = in.readUInt(); resValue.data = getResourceByid(resourceId, isStyle, resourceTable, locale); break; case ResValue.ResType.INT_BOOLEAN: resValue.data = String.valueOf(in.readInt() != 0); break; case ResValue.ResType.NULL: resValue.data = ""; break; case ResValue.ResType.INT_COLOR_RGB8: case ResValue.ResType.INT_COLOR_RGB4: resValue.data = readRGBs(in, 6); break; case ResValue.ResType.INT_COLOR_ARGB8: case ResValue.ResType.INT_COLOR_ARGB4: resValue.data = readRGBs(in, 8); break; case ResValue.ResType.DIMENSION: resValue.data = getDemension(in); break; case ResValue.ResType.FRACTION: resValue.data = getFraction(in); break; default: resValue.data = "{" + resValue.dataType + ":" + in.readUInt() + "}"; } return resValue; } private static String getDemension(TellableInputStream in) throws IOException { long l = in.readUInt(); short unit = (short) (l & 0xff); String unitStr; switch (unit) { case ResValue.ResDataCOMPLEX.UNIT_MM: unitStr = "mm"; break; case ResValue.ResDataCOMPLEX.UNIT_PX: unitStr = "px"; break; case ResValue.ResDataCOMPLEX.UNIT_DIP: unitStr = "dp"; break; case ResValue.ResDataCOMPLEX.UNIT_SP: unitStr = "sp"; break; case ResValue.ResDataCOMPLEX.UNIT_PT: unitStr = "pt"; break; case ResValue.ResDataCOMPLEX.UNIT_IN: unitStr = "in"; break; default: unitStr = "unknow unit:0x" + Integer.toHexString(unit); } return (l >> 8) + unitStr; } private static String getFraction(TellableInputStream in) throws IOException { long l = in.readUInt(); // The low-order 4 bits of the data value specify the type of the fraction short type = (short) (l & 0xf); String pstr; switch (type) { case ResValue.ResDataCOMPLEX.UNIT_FRACTION: pstr = "%"; break; case ResValue.ResDataCOMPLEX.UNIT_FRACTION_PARENT: pstr = "%p"; break; default: pstr = "unknow type:0x" + Integer.toHexString(type); } float value = Float.intBitsToFloat((int) (l >> 4)); return value + pstr; } public static void checkChunkType(int expected, int real) { if (expected != real) { throw new ParserException("Excepct chunk type:" + Integer.toHexString(expected) + ", but got:" + Integer.toHexString(real)); } } /** * get resource value by string-format via resourceId. * * @param resourceId * @param resourceTable * @param locale * @return */ public static String getResourceByid(long resourceId, boolean isStyle, ResourceTable resourceTable, Locale locale) { // An Android Resource id is a 32-bit integer. It comprises // an 8-bit Package id [bits 24-31] // an 8-bit Type id [bits 16-23] // a 16-bit Entry index [bits 0-15] // android system styles. if (isStyle && (resourceId & AndroidConstants.STYLE_ID_START) == AndroidConstants.STYLE_ID_START) { return "@android:style/" + ResourceTable.styleMap.get((int) resourceId); } String str = "resourceId:0x" + Long.toHexString(resourceId); if (resourceTable == null) { return str; } short packageId = (short) (resourceId >> 24 & 0xff); short typeId = (short) ((resourceId >> 16) & 0xff); int entryIndex = (int) (resourceId & 0xffff); ResourcePackage resourcePackage = resourceTable.getPackage(packageId); if (resourcePackage == null) { return str; } TypeSpec typeSpec = resourcePackage.getTypeSpec(typeId); List<Type> types = resourcePackage.getTypes(typeId); if (typeSpec == null || types == null) { return str; } if (!typeSpec.exists(entryIndex)) { return str; } // read from type resource String result = null; String ref = null; int currentLevel = -1; for (Type type : types) { ResourceEntry resource = type.getResourceEntry(entryIndex); if (resource == null) { continue; } int level = locale.match(type.locale); if (level == 2) { ref = resource.key; result = resource.toString(); break; } else if (level > currentLevel) { ref = resource.key; result = resource.toString(); } } if (result == null) { result = "@" + typeSpec.name + "/" + ref; } return result; } /** * read res value. for resource table parser * @param in * @param stringPool * @return */ public static ResValue readResValue(TellableInputStream in, StringPool stringPool) throws IOException { return readResValue(in, stringPool, null, false, null); } }
package net.fortuna.ical4j.vcard; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.URISyntaxException; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.fortuna.ical4j.data.ParserException; import net.fortuna.ical4j.data.UnfoldingReader; public final class VCardBuilder { private static final Pattern VCARD_BEGIN = Pattern.compile("^BEGIN:VCARD$"); private static final Pattern VCARD_END = Pattern.compile("^END:VCARD$"); private static final Pattern PROPERTY_NAME_PATTERN = Pattern.compile("^\\w*\\.?\\w*(?=[;:])"); private static final Pattern PROPERTY_VALUE_PATTERN = Pattern.compile("(?<=[:]).*$"); private static final Pattern PARAMETERS_PATTERN = Pattern.compile("(?<=[;])[^:]*(?=[:])"); private static final int BUFFER_SIZE = 1024; private final BufferedReader reader; private final GroupRegistry groupRegistry; private final PropertyFactoryRegistry propertyFactoryRegistry; private final ParameterFactoryRegistry parameterFactoryRegistry; /** * @param in */ public VCardBuilder(InputStream in) { this(new InputStreamReader(in)); } /** * @param in */ public VCardBuilder(Reader in) { this(in, new GroupRegistry(), new PropertyFactoryRegistry(), new ParameterFactoryRegistry()); } /** * @param in */ public VCardBuilder(Reader in, GroupRegistry registry, PropertyFactoryRegistry propertyFactoryRegistry, ParameterFactoryRegistry parameterFactoryRegistry) { this.reader = new BufferedReader(new UnfoldingReader(in, BUFFER_SIZE), BUFFER_SIZE); this.groupRegistry = registry; this.propertyFactoryRegistry = propertyFactoryRegistry; this.parameterFactoryRegistry = parameterFactoryRegistry; } /** * @return * @throws IOException * @throws ParserException */ public VCard build() throws IOException, ParserException { final VCard vcard = new VCard(); String line = null; String lastLine = null; int lineNo = 0; while ((line = reader.readLine()) != null) { lineNo++; if (lineNo == 1) { if (!VCARD_BEGIN.matcher(line).matches()) { throw new ParserException(lineNo); } } else if (!VCARD_END.matcher(line).matches()) { Property property; try { property = parseProperty(line); } catch (URISyntaxException e) { throw new ParserException("Error parsing line", lineNo, e); } catch (ParseException e) { throw new ParserException("Error parsing line", lineNo, e); } final List<Parameter> params = parseParameters(line); if (!params.isEmpty()) { property.getParameters().addAll(params); } vcard.getProperties().add(property); } lastLine = line; } if (lineNo <= 1 || !VCARD_END.matcher(lastLine).matches()) { throw new ParserException(lineNo); } return vcard; } /** * @param line * @return * @throws ParseException * @throws URISyntaxException */ private Property parseProperty(final String line) throws URISyntaxException, ParseException { Matcher matcher = PROPERTY_NAME_PATTERN.matcher(line); if (matcher.find()) { PropertyFactory<?> factory = null; Group group = null; final String propertyName = matcher.group(); if (propertyName.indexOf('.') >= 0) { final String[] groupProperty = propertyName.split("\\."); group = groupRegistry.getGroup(groupProperty[0]); factory = propertyFactoryRegistry.getFactory(groupProperty[1]); } else { factory = propertyFactoryRegistry.getFactory(propertyName); } matcher = PROPERTY_VALUE_PATTERN.matcher(line); if (matcher.find()) { final String propertyValue = matcher.group(0); if (group != null) { return factory.createProperty(group, propertyValue); } else { return factory.createProperty(propertyValue); } } } return null; } /** * @param line * @return */ private List<Parameter> parseParameters(final String line) { final List<Parameter> parameters = new ArrayList<Parameter>(); final Matcher matcher = PARAMETERS_PATTERN.matcher(line); if (matcher.find()) { final String[] params = matcher.group().split(";"); for (String param : params) { final String[] vals = param.split("="); final ParameterFactory<? extends Parameter> factory = parameterFactoryRegistry.getFactory(vals[0]); if (vals.length > 1) { parameters.add(factory.createParameter(vals[1])); } else { parameters.add(factory.createParameter(null)); } } } return parameters; } }
package net.royawesome.jlibnoise.model; import net.royawesome.jlibnoise.Utils; import net.royawesome.jlibnoise.exception.NoModuleException; import net.royawesome.jlibnoise.module.Module; /** * Model that defines the surface of a sphere. * * @image html modelsphere.png * * This model returns an output value from a noise module given the * coordinates of an input value located on the surface of a sphere. * * To generate an output value, pass the (latitude, longitude) * coordinates of an input value to the GetValue() method. * * This model is useful for creating: - seamless textures that can be * mapped onto a sphere - terrain height maps for entire planets * * This sphere has a radius of 1.0 unit and its center is located at the * origin. */ public class Sphere { Module module; /** * Constructor * * @param module The noise module that is used to generate the output * values. */ public Sphere(Module module) { if (module == null) throw new IllegalArgumentException("module cannot be null"); this.module = module; } /** * Returns the noise module that is used to generate the output values. * * @returns A reference to the noise module. * @pre A noise module was passed to the SetModule() method. */ public Module getModule() { return module; } /** * Sets the noise module that is used to generate the output values. * * @param module The noise module that is used to generate the output * values. * * This noise module must exist for the lifetime of this object, * until you pass a new noise module to this method. */ public void setModule(Module module) { if (module == null) throw new IllegalArgumentException("module cannot be null"); this.module = module; } /** * Returns the output value from the noise module given the (latitude, * longitude) coordinates of the specified input value located on the * surface of the sphere. * * @param lat The latitude of the input value, in degrees. * @param lon The longitude of the input value, in degrees. * @return The output value from the noise module. * @pre A noise module was passed to the SetModule() method. * * This output value is generated by the noise module passed to the * SetModule() method. * * Use a negative latitude if the input value is located on the * southern hemisphere. * * Use a negative longitude if the input value is located on the * western hemisphere. */ public double getValue(double lat, double log) { if (module == null) throw new NoModuleException(); double[] vec = Utils.LatLonToXYZ(lat, log); return module.GetValue(vec[0], vec[1], vec[2]); } }
package net.sf.jabb.util.test; import java.text.DecimalFormat; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.LongConsumer; import java.util.function.LongUnaryOperator; /** * @author James Hu * */ public class RateTestUtility { public static LongConsumer emptyLoop = endTime -> { while(System.currentTimeMillis() < endTime){} }; public static void doRateTest(ExecutorService threadPool, int numThreads, int warmUpPeriod, TimeUnit warmUpPeriodUnit, LongConsumer warmUpConsumer, int testPeriod, TimeUnit testPeriodUnit, LongUnaryOperator testFunction ) throws Exception{ doRateTest(null, threadPool, numThreads, warmUpPeriod, warmUpPeriodUnit, warmUpConsumer, testPeriod, testPeriodUnit, testFunction); } public static void doRateTest(int numThreads, int warmUpPeriod, TimeUnit warmUpPeriodUnit, LongConsumer warmUpConsumer, int testPeriod, TimeUnit testPeriodUnit, LongUnaryOperator testFunction ) throws Exception{ ThreadPoolExecutor threadPool = new ThreadPoolExecutor(numThreads, numThreads, 1L, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>()); threadPool.allowCoreThreadTimeOut(true); doRateTest(null, threadPool, numThreads, warmUpPeriod, warmUpPeriodUnit, warmUpConsumer, testPeriod, testPeriodUnit, testFunction); threadPool.shutdown(); threadPool.awaitTermination(1, TimeUnit.MINUTES); threadPool.shutdownNow(); } public static double doRateTest(String title, int numThreads, int warmUpPeriod, TimeUnit warmUpPeriodUnit, LongConsumer warmUpConsumer, int testPeriod, TimeUnit testPeriodUnit, LongUnaryOperator testFunction ) throws Exception{ ThreadPoolExecutor threadPool = new ThreadPoolExecutor(numThreads, numThreads, 1L, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>()); threadPool.allowCoreThreadTimeOut(true); double result = doRateTest(title, threadPool, numThreads, warmUpPeriod, warmUpPeriodUnit, warmUpConsumer, testPeriod, testPeriodUnit, testFunction); threadPool.shutdown(); threadPool.awaitTermination(1, TimeUnit.MINUTES); threadPool.shutdownNow(); return result; } public static double doRateTest(String title, ExecutorService threadPool, int numThreads, int warmUpPeriod, TimeUnit warmUpPeriodUnit, LongConsumer warmUpConsumer, int testPeriod, TimeUnit testPeriodUnit, LongUnaryOperator testFunction ) throws Exception{ LongConsumer warmUpFunction = warmUpConsumer != null? warmUpConsumer : endTime -> testFunction.applyAsLong(endTime); long start = System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(warmUpPeriod, warmUpPeriodUnit); long end = start + TimeUnit.MILLISECONDS.convert(testPeriod, testPeriodUnit); List<Future<Long>> futures = new LinkedList<>(); for (int i = 0; i < numThreads; i ++){ futures.add(threadPool.submit(()->{ long total = 0; for (long now = System.currentTimeMillis(); now < end; now = System.currentTimeMillis()){ if (now < start){ // warm up period warmUpFunction.accept(start); }else{ total += testFunction.applyAsLong(end); } } return total; })); } final AtomicBoolean errorHappened = new AtomicBoolean(false); long total = futures.stream().mapToLong(f -> { try{ return f.get(); }catch(Exception e){ e.printStackTrace(); errorHappened.set(true); return 0; } }).sum(); double rate = (double)total/TimeUnit.SECONDS.convert(testPeriod, testPeriodUnit); if (title != null){ System.out.println("Rate of " + title + " is " + formatDouble(" } if (errorHappened.get()){ System.out.println("Error happened during the test."); } return rate; } static public String formatDouble(String pattern, double value) { DecimalFormat myFormatter = new DecimalFormat(pattern); String output = myFormatter.format(value); return output; } }
package net.sf.jabref.external; import java.net.URL; import java.net.MalformedURLException; import java.io.IOException; /** * FullTextFinder implementation that attempts to find PDF url from a ACS DOI. */ public class ACSPdfDownload implements FullTextFinder { private static final String BASE_URL = "http://pubs.acs.org/doi/pdf/"; public ACSPdfDownload() { } public boolean supportsSite(URL url) { return url.getHost().toLowerCase().contains("acs.org"); } public URL findFullTextURL(URL url) throws IOException { try { return new URL(BASE_URL+url.getPath().substring("/doi/abs/".length())); } catch (MalformedURLException e) { return null; } } }
package no.cantara.csdb.health; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.IOException; import java.net.URL; import java.util.Properties; import static no.cantara.csdb.health.HealthResource.HEALTH_PATH; @Controller @Path(HEALTH_PATH) @Produces(MediaType.APPLICATION_JSON) public class HealthResource { public static final String HEALTH_PATH = "/health"; private static final Logger log = LoggerFactory.getLogger(HealthResource.class); @Autowired public HealthResource() { } @GET public Response healthCheck() { log.trace("healthCheck"); return Response.ok(getHealthTextJson()).build(); } public String getHealthTextJson() { return "{\n" + " \"Status\": \"OK\",\n" + " \"Version\": \"" + getVersion() + "\"\n" + "}\n"; } public String getVersion() { Properties mavenProperties = new Properties(); String resourcePath = "/META-INF/maven/no.cantara.csdb/ConfigService-Dashboard/pom.properties"; URL mavenVersionResource = this.getClass().getResource(resourcePath); if (mavenVersionResource != null) { try { mavenProperties.load(mavenVersionResource.openStream()); return mavenProperties.getProperty("version", "missing version info in " + resourcePath); } catch (IOException e) { log.warn("Problem reading version resource from classpath: ", e); } } return "(DEV VERSION)"; } }
package org.alienlabs.amazon; import java.io.UnsupportedEncodingException; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormSubmitBehavior; import org.apache.wicket.extensions.ajax.markup.html.IndicatingAjaxButton; import org.apache.wicket.injection.Injector; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.Button; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.TextField; import org.apache.wicket.markup.html.form.upload.FileUpload; import org.apache.wicket.markup.html.form.upload.FileUploadField; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.Model; import org.apache.wicket.spring.injection.annot.SpringBean; import org.apache.wicket.util.lang.Bytes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Required; import com.xuggle.mediatool.IMediaReader; import com.xuggle.mediatool.IMediaWriter; import com.xuggle.mediatool.ToolFactory; import com.xuggle.mediatool.IMediaViewer; import com.xuggle.xuggler.ICodec; @edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value = { "SE_INNER_CLASS", "SIC_INNER_SHOULD_BE_STATIC_ANON" }, justification = "In Wicket, serializable inner classes are common. And as the parent Page is serialized as well, this is no concern. This is no bad practice in Wicket") public class ImportVideoPanel extends Panel { private static final Logger LOGGER = LoggerFactory.getLogger(ImportVideoPanel.class); private static final long serialVersionUID = 1L; final FileUploadField file; public ImportVideoPanel(final String id) { super(id); Injector.get().inject(this); final Form<Void> form = new Form<>("form"); this.file = new FileUploadField("videoFile"); form.setMarkupId("inputForm").setOutputMarkupId(true); form.setMaxSize(Bytes.kilobytes(5)); form.setMultiPart(true); form.add(this.file); this.add(form); final Button upload = new Button("upload") { @Override public void onSubmit() { ImportVideoPanel.LOGGER.info("trying to upload something"); //final FileUpload fupload = ImportDeckDialog.this.file.getFileUpload(); //if (fupload == null) // No file was provided // ImportDeckDialog.LOGGER.info("Please provide a valid file"); // return; //else if (fupload.getSize() == 0) // ImportDeckDialog.LOGGER.info("Please provide a non-empty file"); // return; //else if ((fupload.getClientFileName() == null) // || ("".equals(fupload.getClientFileName().trim())) // || (fupload.getClientFileName().endsWith(".txt"))) // ImportDeckDialog.LOGGER.info("Please provide a valid file"); // return; //ImportDeckDialog.LOGGER.info("uploading file: " // + ImportDeckDialog.this.file.getFileUpload().getClientFileName()); //try // new String(fupload.getBytes(), "UTF-8"); ImportVideoPanel.convert("/home/nostromo/test.avi", "/home/nostromo/test.wav"); //catch (final UnsupportedEncodingException e) // ImportDeckDialog.LOGGER.info("Please provide a file encoded with UTF-8 charset"); // return; //ImportDeckDialog.LOGGER.info("successfully added deck: " // + fupload.getClientFileName()); ImportVideoPanel.LOGGER.info("Your file has been successfully uploaded"); } }; form.add(upload); } public static void convert(String from, final String to) { // create a media reader IMediaReader mediaReader = ToolFactory.makeReader(from); // create a media writer IMediaWriter mediaWriter = ToolFactory.makeWriter(to, mediaReader); // add a writer to the reader, to create the output file mediaReader.addListener(mediaWriter); // create a media viewer with stats enabled IMediaViewer mediaViewer = ToolFactory.makeViewer(true); // add a viewer to the reader, to see the decoded media mediaReader.addListener(mediaViewer); // read and decode packets from the source file // and dispatch decoded audio and video to the writer while (mediaReader.readPacket() == null) ; } }
package org.cejug.yougi.business; import org.cejug.yougi.entity.Timezone; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.List; @Stateless public class TimezoneBean { @PersistenceContext private EntityManager em; public Timezone findTimezone(String id) { if(id != null) { return em.find(Timezone.class, id); } else { return null; } } public Timezone findDefaultTimezone() { return em.createQuery("select tz from Timezone tz where tz.defaultTz = true", Timezone.class).getSingleResult(); } public List<Timezone> findTimezones() { return em.createQuery("select tz from Timezone tz order by tz.label", Timezone.class) .getResultList(); } public void save(Timezone timezone) { if(timezone.getDefaultTz()) { Timezone defaultTimezone = findDefaultTimezone(); if(!timezone.equals(defaultTimezone)) { defaultTimezone.setDefaultTz(Boolean.FALSE); } } Timezone existingTimezone = em.find(Timezone.class, timezone.getId()); if(existingTimezone == null) { em.persist(timezone); } else { em.merge(timezone); } } public void remove(String id) { Timezone timezone = em.find(Timezone.class, id); if(timezone != null) { em.remove(timezone); } } }
package org.csanchez.aws.glacier.domain; import static org.apache.commons.io.FileUtils.byteCountToDisplaySize; import org.csanchez.aws.glacier.utils.Check; public final class Vault { public final String name; public final Long numberOfArchives; public final Long sizeInBytes; private final String arn; public Vault( String arn, String name, Long numberOfArchives, Long sizeInBytes ) { this.arn = Check.notBlank( arn ); this.name = Check.notBlank( name ); this.numberOfArchives = numberOfArchives; this.sizeInBytes = sizeInBytes; } @Override public String toString() { return "Vault[name=" + name + ", numberOfArchives=" + numberOfArchives + ", size=" + byteCountToDisplaySize( sizeInBytes ) + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((arn == null) ? 0 : arn.hashCode()); return result; } @Override public boolean equals( Object obj ) { if ( this == obj ) return true; if ( obj == null ) return false; if ( getClass() != obj.getClass() ) return false; Vault other = (Vault) obj; if ( arn == null ) { if ( other.arn != null ) return false; } else if ( !arn.equals( other.arn ) ) return false; return true; } }
package org.ferris.riviera.console.io; import java.io.PrintWriter; import javax.inject.Inject; /** * A wrapper around {@code System.out} and {@code System.in} for the application * * @author Michael Remijan mjremijan@yahoo.com @mjremijan */ public class Console { @Inject protected PrintWriter writer; /** * Print the string as title * * @param str The string to print */ public void title(String str) { writer.println("************************************************************"); writer.println("* *"); writer.printf("* %-57s*%n", str); writer.println("* *"); writer.println("************************************************************"); writer.flush(); } /** * Print the string as heading1 * * @param str The string to print */ public void h1(String str) { writer.printf("%n%s%n", str); for (int i=0; i<str.length(); i++) { writer.print("-"); } writer.println(); writer.println(); writer.flush(); } /** * Print the string as a paragraph * * @param str The string to print */ public void p(String str) { p(str, null); } /** * Formats the string with the given args then * print the string as a paragraph * * @param str The format of the string to print * @param args The arguemnts for the format */ public void p(String format, String...args) { writer.printf(" %s%n", String.format(format, args)); writer.flush(); } /** * Print the throwable stack trace as a paragraph * * @param e The throwable to print */ public void p(Throwable e) { writer.println(); e.printStackTrace(writer); writer.flush(); } }
package org.ftcTeam; import com.qualcomm.robotcore.eventloop.opmode.OpModeRegister; import org.ftcTeam.opmodes.*; import org.firstinspires.ftc.robotcontroller.internal.FtcRobotControllerActivity; public class FTCTeamControllerActivity extends FtcRobotControllerActivity { // testing from daniel // testing on android studio @Override protected OpModeRegister createOpModeRegister() { return new Registrar1(); //return new Registrar2(); } }
package org.janelia.saalfeldlab.n5; import java.io.IOException; import java.nio.channels.Channels; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.stream.Stream; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; /** * Filesystem {@link N5Writer} implementation with version compatibility check. * * @author Stephan Saalfeld */ public class N5FSWriter extends N5FSReader implements N5Writer { /** * Opens an {@link N5FSWriter} at a given base path with a custom * {@link GsonBuilder} to support custom attributes. * * If the base path does not exist, it will be created. * * If the base path exists and if the N5 version of the container is * compatible with this implementation, the N5 version of this container * will be set to the current N5 version of this implementation. * * @param basePath n5 base path * @param gsonBuilder * @throws IOException * if the base path cannot be written to or cannot be created, * if the N5 version of the container is not compatible with this * implementation. */ public N5FSWriter(final String basePath, final GsonBuilder gsonBuilder) throws IOException { super(basePath, gsonBuilder); Files.createDirectories(Paths.get(basePath)); if (!VERSION.equals(getVersion())) setAttribute("/", VERSION_KEY, VERSION.toString()); } /** * Opens an {@link N5FSWriter} at a given base path. * * If the base path does not exist, it will be created. * * If the base path exists and if the N5 version of the container is * compatible with this implementation, the N5 version of this container * will be set to the current N5 version of this implementation. * * @param basePath n5 base path * @param gsonBuilder * @throws IOException * if the base path cannot be written to or cannot be created, * if the N5 version of the container is not compatible with this * implementation. */ public N5FSWriter(final String basePath) throws IOException { this(basePath, new GsonBuilder()); } @Override public void createGroup(final String pathName) throws IOException { final Path path = Paths.get(basePath, pathName); Files.createDirectories(path); } @Override public void setAttributes( final String pathName, final Map<String, ?> attributes) throws IOException { final Path path = Paths.get(basePath, getAttributesPath(pathName).toString()); final HashMap<String, JsonElement> map = new HashMap<>(); try (final LockedFileChannel lockedFileChannel = LockedFileChannel.openForWriting(path)) { map.putAll(GsonAttributesParser.readAttributes(Channels.newReader(lockedFileChannel.getFileChannel(), StandardCharsets.UTF_8.name()), getGson())); GsonAttributesParser.insertAttributes(map, attributes, gson); lockedFileChannel.getFileChannel().truncate(0); GsonAttributesParser.writeAttributes(Channels.newWriter(lockedFileChannel.getFileChannel(), StandardCharsets.UTF_8.name()), map, getGson()); } } @Override public <T> void writeBlock( final String pathName, final DatasetAttributes datasetAttributes, final DataBlock<T> dataBlock) throws IOException { final Path path = Paths.get(basePath, getDataBlockPath(pathName, dataBlock.getGridPosition()).toString()); Files.createDirectories(path.getParent()); try (final LockedFileChannel lockedChannel = LockedFileChannel.openForWriting(path)) { lockedChannel.getFileChannel().truncate(0); DefaultBlockWriter.writeBlock(Channels.newOutputStream(lockedChannel.getFileChannel()), datasetAttributes, dataBlock); } } @Override public boolean remove() throws IOException { return remove(""); } @Override public boolean remove(final String pathName) throws IOException { final Path path = Paths.get(basePath, pathName); if (Files.exists(path)) try (final Stream<Path> pathStream = Files.walk(path)) { pathStream.sorted(Comparator.reverseOrder()).forEach( childPath -> { if (Files.isRegularFile(childPath)) { try (final LockedFileChannel channel = LockedFileChannel.openForWriting(childPath)) { Files.delete(childPath); } catch (final IOException e) { e.printStackTrace(); } } else try { Files.delete(childPath); } catch (final IOException e) { e.printStackTrace(); } }); } return !Files.exists(path); } }
package org.lightmare.libraries; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.apache.log4j.Logger; import org.lightmare.libraries.loaders.EjbClassLoader; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.fs.FileUtils; import org.lightmare.utils.reflect.MetaUtils; /** * Class for load jar or class files from specified path * * @author levan * @since 0.0.15-SNAPSHOT */ public class LibraryLoader { // Method name to add URL to class loader private static final String ADD_URL_METHOD_NAME = "addURL"; private static final String CLOSE_METHOD_NAME = "close"; // Caches if class URLClassLoader has close method private static Boolean hasCloseMethod; // Name of class loader isolated thread private static final String LOADER_THREAD_NAME = "library-class-loader-thread"; // Inaccessible method to add URL to existing class loader private static Method addURLMethod; // Lock to synchronize class loading private static final Lock LOCK = new ReentrantLock(); private static final Logger LOG = Logger.getLogger(LibraryLoader.class); /** * implementation of {@link Callable}<ClassLoader> interface to initialize * {@link ClassLoader} in separate thread * * @author levan * @since 0.0.15-SNAPSHOT */ private static class LibraryLoaderInit implements Callable<ClassLoader> { // Classes URL array private URL[] urls; // Parent class loader private ClassLoader parent; public LibraryLoaderInit(final URL[] urls, final ClassLoader parent) { this.urls = urls; this.parent = parent; } @Override public ClassLoader call() throws Exception { ClassLoader loader = cloneContextClassLoader(urls, parent); return loader; } } /** * Gets {@link URLClassLoader} class addURL method * * @return Method * @throws IOException */ private static Method getURLMethod() throws IOException { if (addURLMethod == null) { ObjectUtils.lock(LOCK); try { if (addURLMethod == null && MetaUtils.hasMethod(URLClassLoader.class, ADD_URL_METHOD_NAME)) { addURLMethod = MetaUtils.getDeclaredMethod( URLClassLoader.class, ADD_URL_METHOD_NAME, URL.class); } } finally { ObjectUtils.unlock(LOCK); } } return addURLMethod; } /** * If passed {@link ClassLoader} is instance of {@link URLClassLoader} then * gets {@link URL}[] of this {@link ClassLoader} calling * {@link URLClassLoader#getURLs()} method * * @param loader * @return {@link URL}[] */ private static URL[] getURLs(ClassLoader loader) { URL[] urls; if (loader instanceof URLClassLoader) { urls = ((URLClassLoader) loader).getURLs(); } else { urls = CollectionUtils.emptyArray(URL.class); } return urls; } /** * Initializes and returns enriched {@link ClassLoader} in separated * {@link Thread} to load bean and library classes * * @param urls * @return {@link ClassLoader} * @throws IOException */ public static ClassLoader initializeLoader(final URL[] urls) throws IOException { ClassLoader ejbLoader; ClassLoader parent = getContextClassLoader(); LibraryLoaderInit initializer = new LibraryLoaderInit(urls, parent); FutureTask<ClassLoader> task = new FutureTask<ClassLoader>(initializer); Thread thread = new Thread(task); thread.setName(LOADER_THREAD_NAME); thread.setPriority(Thread.MAX_PRIORITY); thread.start(); try { ejbLoader = task.get(); } catch (InterruptedException ex) { throw new IOException(ex); } catch (ExecutionException ex) { throw new IOException(ex); } return ejbLoader; } /** * Gets current {@link Thread}'s context {@link ClassLoader} object * * @return {@link ClassLoader} */ public static ClassLoader getContextClassLoader() { PrivilegedAction<ClassLoader> action = new PrivilegedAction<ClassLoader>() { public ClassLoader run() { Thread currentThread = Thread.currentThread(); ClassLoader classLoader = currentThread.getContextClassLoader(); return classLoader; } }; ClassLoader loader = AccessController.doPrivileged(action); return loader; } /** * Gets new {@link ClassLoader} enriched with passed {@link URL} array and * parent {@link ClassLoader} classes * * @param urls * @param parent * @return {@link ClassLoader} * @throws IOException */ public static ClassLoader getEnrichedLoader(URL[] urls, ClassLoader parent) { ClassLoader enrichedLoader; if (CollectionUtils.valid(urls)) { if (parent == null) { parent = getContextClassLoader(); } enrichedLoader = EjbClassLoader.newInstance(urls, parent); } else { enrichedLoader = null; } return enrichedLoader; } /** * Gets new {@link ClassLoader} enriched with passed {@link File} and it's * sub files {@link URL}s and parent {@link ClassLoader} classes * * @param file * @param urls * @return {@link ClassLoader} * @throws IOException */ public static ClassLoader getEnrichedLoader(File file, Set<URL> urls) throws IOException { FileUtils.getSubfiles(file, urls); URL[] paths = CollectionUtils.toArray(urls, URL.class); ClassLoader parent = getContextClassLoader(); ClassLoader enrichedLoader = getEnrichedLoader(paths, parent); return enrichedLoader; } /** * Initializes new {@link ClassLoader} from loaded {@link URL}'s from * enriched {@link ClassLoader} for beans and libraries * * @param urls * @return {@link ClassLoader} * @throws IOException */ public static ClassLoader cloneContextClassLoader(final URL[] urls, ClassLoader parent) throws IOException { URLClassLoader loader = (URLClassLoader) getEnrichedLoader(urls, parent); try { // get all resources for cloning URL[] urlArray = loader.getURLs(); URL[] urlClone = urlArray.clone(); if (parent == null) { parent = getContextClassLoader(); } ClassLoader clone = EjbClassLoader.newInstance(urlClone, parent); return clone; } finally { closeClassLoader(loader); // dereference cloned class loader instance loader = null; } } /** * Merges two {@link ClassLoader}s in one * * @param newLoader * @param oldLoader * @return {@link ClassLoader} */ public static ClassLoader createCommon(ClassLoader newLoader, ClassLoader oldLoader) { URL[] urls = getURLs(oldLoader); ClassLoader commonLoader = URLClassLoader.newInstance(urls, oldLoader); urls = getURLs(newLoader); commonLoader = getEnrichedLoader(urls, newLoader); return commonLoader; } /** * Sets passed {@link Thread}'s context class loader appropriated * {@link ClassLoader} instance * * @param thread * @param loader */ public static void loadCurrentLibraries(Thread thread, ClassLoader loader) { if (ObjectUtils.notNull(loader)) { thread.setContextClassLoader(loader); } } /** * Sets passed {@link ClassLoader} instance as current {@link Thread}'s * context class loader * * @param loader */ public static void loadCurrentLibraries(ClassLoader loader) { Thread thread = Thread.currentThread(); loadCurrentLibraries(thread, loader); } /** * Adds {@link URL} array to system {@link ClassLoader} instance * * @param urls * @param method * @param urlLoader * @throws IOException */ public static void loadURLToSystem(URL[] urls, Method method, URLClassLoader urlLoader) throws IOException { for (URL url : urls) { MetaUtils.invokePrivate(method, urlLoader, url); } } /** * Loads all files and sub files {@link URL}s to system class loader * * @param libraryPath * @throws IOException */ private static void loadLibraryFromPath(String libraryPath) throws IOException { File file = new File(libraryPath); if (file.exists()) { Set<URL> urls = new HashSet<URL>(); FileUtils.getSubfiles(file, urls); URL[] paths = CollectionUtils.toArray(urls, URL.class); ClassLoader systemLoader = ClassLoader.getSystemClassLoader(); if (systemLoader instanceof URLClassLoader) { URLClassLoader urlLoader = (URLClassLoader) systemLoader; Method method = getURLMethod(); if (ObjectUtils.notNull(method)) { loadURLToSystem(paths, method, urlLoader); } } } } /** * Loads jar or <code>.class</code> files to the current thread from * libraryPaths recursively * * @param libraryPaths * @throws IOException */ public static void loadLibraries(String... libraryPaths) throws IOException { if (CollectionUtils.valid(libraryPaths)) { for (String libraryPath : libraryPaths) { loadLibraryFromPath(libraryPath); } } } /** * Loads passed classes to specified {@link ClassLoader} instance * * @param classes * @param loader */ public static void loadClasses(Collection<String> classes, ClassLoader loader) throws IOException { if (CollectionUtils.valid(classes) && ObjectUtils.notNull(loader)) { for (String className : classes) { try { loader.loadClass(className); } catch (ClassNotFoundException ex) { throw new IOException(ex); } } } } /** * Loads passed classes to specified current {@link Thread}'s context class * loader * * @param classes */ public static void loadClasses(Collection<String> classes) throws IOException { ClassLoader loader = getContextClassLoader(); loadClasses(classes, loader); } /** * Checks and caches if passed {@link ClassLoader} implementation or it's * parent class has close method * * @param loader * @throws IOException */ private static void checkOnClose(ClassLoader loader) throws IOException { // Finds if loader associated class or superclass has "close" // method Class<? extends ClassLoader> loaderClass = loader.getClass(); if (hasCloseMethod == null) { synchronized (LibraryLoader.class) { if (hasCloseMethod == null) { boolean hasMethod = MetaUtils.hasPublicMethod(loaderClass, CLOSE_METHOD_NAME); hasCloseMethod = hasMethod; } } } } /** * Closes passed {@link ClassLoader} if it is instance of * {@link URLClassLoader} class * * @param loader * @throws IOException */ public static void closeClassLoader(ClassLoader loader) throws IOException { if (ObjectUtils.notNull(loader) && loader instanceof URLClassLoader) { try { URLClassLoader urlClassLoader = ObjectUtils.cast(loader, URLClassLoader.class); urlClassLoader.clearAssertionStatus(); // Finds if loader associated class or superclass has "close" // method checkOnClose(loader); if (hasCloseMethod) { urlClassLoader.close(); } } catch (Throwable th) { LOG.error(th.getMessage(), th); } } } }
package org.lightmare.libraries; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.apache.log4j.Logger; import org.lightmare.libraries.loaders.EjbClassLoader; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.fs.FileUtils; import org.lightmare.utils.reflect.MetaUtils; /** * Class for load jar or class files from specified path * * @author levan * @since 0.0.15-SNAPSHOT */ public class LibraryLoader { // Method name to add URL to class loader private static final String ADD_URL_METHOD_NAME = "addURL"; private static final String CLOSE_METHOD_NAME = "close"; // Caches if class URLClassLoader has close method private static Boolean hasCloseMethod; // Name of class loader isolated thread private static final String LOADER_THREAD_NAME = "library-class-loader-thread"; // Inaccessible method to add URL to existing class loader private static Method addURLMethod; // Lock to synchronize class loading private static final Lock LOCK = new ReentrantLock(); private static final Logger LOG = Logger.getLogger(LibraryLoader.class); /** * implementation of {@link Callable}<ClassLoader> interface to initialize * {@link ClassLoader} in separate thread * * @author levan * @since 0.0.15-SNAPSHOT */ private static class LibraryLoaderInit implements Callable<ClassLoader> { // Classes URL array private URL[] urls; // Parent class loader private ClassLoader parent; public LibraryLoaderInit(final URL[] urls, final ClassLoader parent) { this.urls = urls; this.parent = parent; } @Override public ClassLoader call() throws Exception { ClassLoader loader = cloneContextClassLoader(urls, parent); return loader; } } /** * Caches specific "addURL" method for {@link URLClassLoader} class * * @throws IOException */ private static void initURLMethod() throws IOException { if (addURLMethod == null && MetaUtils.hasMethod(URLClassLoader.class, ADD_URL_METHOD_NAME)) { addURLMethod = MetaUtils.getDeclaredMethod(URLClassLoader.class, ADD_URL_METHOD_NAME, URL.class); } } /** * Gets {@link URLClassLoader} class addURL method * * @return Method * @throws IOException */ private static Method getURLMethod() throws IOException { if (addURLMethod == null) { ObjectUtils.lock(LOCK); try { initURLMethod(); } finally { ObjectUtils.unlock(LOCK); } } return addURLMethod; } /** * If passed {@link ClassLoader} is instance of {@link URLClassLoader} then * gets {@link URL}[] of this {@link ClassLoader} calling * {@link URLClassLoader#getURLs()} method * * @param loader * @return {@link URL}[] */ private static URL[] getURLs(ClassLoader loader) { URL[] urls; if (loader instanceof URLClassLoader) { urls = ((URLClassLoader) loader).getURLs(); } else { urls = CollectionUtils.emptyArray(URL.class); } return urls; } /** * Initializes and returns enriched {@link ClassLoader} in separated * {@link Thread} to load bean and library classes * * @param urls * @return {@link ClassLoader} * @throws IOException */ public static ClassLoader initializeLoader(final URL[] urls) throws IOException { ClassLoader ejbLoader; ClassLoader parent = getContextClassLoader(); LibraryLoaderInit initializer = new LibraryLoaderInit(urls, parent); FutureTask<ClassLoader> task = new FutureTask<ClassLoader>(initializer); Thread thread = new Thread(task); thread.setName(LOADER_THREAD_NAME); thread.setPriority(Thread.MAX_PRIORITY); thread.start(); try { ejbLoader = task.get(); } catch (InterruptedException ex) { throw new IOException(ex); } catch (ExecutionException ex) { throw new IOException(ex); } return ejbLoader; } /** * Gets current {@link Thread}'s context {@link ClassLoader} object * * @return {@link ClassLoader} */ public static ClassLoader getContextClassLoader() { PrivilegedAction<ClassLoader> action = new PrivilegedAction<ClassLoader>() { @Override public ClassLoader run() { Thread currentThread = Thread.currentThread(); ClassLoader classLoader = currentThread.getContextClassLoader(); return classLoader; } }; ClassLoader loader = AccessController.doPrivileged(action); return loader; } /** * Gets new {@link ClassLoader} enriched with passed {@link URL} array and * parent {@link ClassLoader} classes * * @param urls * @param parent * @return {@link ClassLoader} * @throws IOException */ public static ClassLoader getEnrichedLoader(URL[] urls, ClassLoader parent) { ClassLoader enrichedLoader; if (CollectionUtils.valid(urls)) { if (parent == null) { parent = getContextClassLoader(); } enrichedLoader = EjbClassLoader.newInstance(urls, parent); } else { enrichedLoader = null; } return enrichedLoader; } /** * Gets new {@link ClassLoader} enriched with passed {@link File} and it's * sub files {@link URL}s and parent {@link ClassLoader} classes * * @param file * @param urls * @return {@link ClassLoader} * @throws IOException */ public static ClassLoader getEnrichedLoader(File file, Set<URL> urls) throws IOException { ClassLoader enrichedLoader; FileUtils.getSubfiles(file, urls); URL[] paths = CollectionUtils.toArray(urls, URL.class); ClassLoader parent = getContextClassLoader(); enrichedLoader = getEnrichedLoader(paths, parent); return enrichedLoader; } /** * Initializes new {@link ClassLoader} from loaded {@link URL}'s from * enriched {@link ClassLoader} for beans and libraries * * @param urls * @return {@link ClassLoader} * @throws IOException */ public static ClassLoader cloneContextClassLoader(final URL[] urls, ClassLoader parent) throws IOException { ClassLoader clone; URLClassLoader loader = (URLClassLoader) getEnrichedLoader(urls, parent); try { // get all resources for cloning URL[] urlArray = loader.getURLs(); URL[] urlClone = urlArray.clone(); if (parent == null) { parent = getContextClassLoader(); } clone = EjbClassLoader.newInstance(urlClone, parent); } finally { closeClassLoader(loader); // dereference cloned class loader instance loader = null; } return clone; } /** * Merges two {@link ClassLoader}s in one * * @param newLoader * @param oldLoader * @return {@link ClassLoader} */ public static ClassLoader createCommon(ClassLoader newLoader, ClassLoader oldLoader) { ClassLoader commonLoader; URL[] urls = getURLs(oldLoader); commonLoader = URLClassLoader.newInstance(urls, oldLoader); urls = getURLs(newLoader); commonLoader = getEnrichedLoader(urls, newLoader); return commonLoader; } /** * Sets passed {@link Thread}'s context class loader appropriated * {@link ClassLoader} instance * * @param thread * @param loader */ public static void loadCurrentLibraries(Thread thread, ClassLoader loader) { if (ObjectUtils.notNull(loader)) { thread.setContextClassLoader(loader); } } /** * Sets passed {@link ClassLoader} instance as current {@link Thread}'s * context class loader * * @param loader */ public static void loadCurrentLibraries(ClassLoader loader) { Thread thread = Thread.currentThread(); loadCurrentLibraries(thread, loader); } /** * Adds {@link URL} array to system {@link ClassLoader} instance * * @param urls * @param method * @param urlLoader * @throws IOException */ public static void loadURLToSystem(URL[] urls, Method method, URLClassLoader urlLoader) throws IOException { for (URL url : urls) { MetaUtils.invokePrivate(method, urlLoader, url); } } /** * Loads all files and sub files {@link URL}s to system class loader * * @param libraryPath * @throws IOException */ private static void loadLibraryFromPath(String libraryPath) throws IOException { File file = new File(libraryPath); if (file.exists()) { Set<URL> urls = new HashSet<URL>(); FileUtils.getSubfiles(file, urls); URL[] paths = CollectionUtils.toArray(urls, URL.class); ClassLoader systemLoader = ClassLoader.getSystemClassLoader(); if (systemLoader instanceof URLClassLoader) { URLClassLoader urlLoader = (URLClassLoader) systemLoader; Method method = getURLMethod(); if (ObjectUtils.notNull(method)) { loadURLToSystem(paths, method, urlLoader); } } } } /** * Loads jar or <code>.class</code> files to the current thread from * libraryPaths recursively * * @param libraryPaths * @throws IOException */ public static void loadLibraries(String... libraryPaths) throws IOException { if (CollectionUtils.valid(libraryPaths)) { for (String libraryPath : libraryPaths) { loadLibraryFromPath(libraryPath); } } } /** * Loads passed classes to specified {@link ClassLoader} instance * * @param classes * @param loader */ public static void loadClasses(Collection<String> classes, ClassLoader loader) throws IOException { if (CollectionUtils.valid(classes) && ObjectUtils.notNull(loader)) { for (String className : classes) { try { loader.loadClass(className); } catch (ClassNotFoundException ex) { throw new IOException(ex); } } } } /** * Loads passed classes to specified current {@link Thread}'s context class * loader * * @param classes */ public static void loadClasses(Collection<String> classes) throws IOException { ClassLoader loader = getContextClassLoader(); loadClasses(classes, loader); } /** * Checks and caches if passed {@link ClassLoader} implementation or it's * parent class has close method * * @param loader * @throws IOException */ private static void hasCloseMethod(Class<URLClassLoader> loaderClass) throws IOException { if (hasCloseMethod == null) { // Finds if loader associated class or superclass has // "close" // method boolean hasMethod = MetaUtils.hasPublicMethod(loaderClass, CLOSE_METHOD_NAME); hasCloseMethod = hasMethod; } } /** * Checks and caches if passed {@link ClassLoader} implementation or it's * parent class has close method * * @param loader * @throws IOException */ private static void checkOnClose(Class<URLClassLoader> loaderClass) throws IOException { if (hasCloseMethod == null) { synchronized (LibraryLoader.class) { // Finds if loader associated class or superclass has // "close" // method hasCloseMethod(loaderClass); } } } /** * Closes passed {@link ClassLoader} if it is instance of * {@link URLClassLoader} class * * @param loader * @throws IOException */ public static void closeClassLoader(ClassLoader loader) throws IOException { if (ObjectUtils.notNull(loader) && loader instanceof URLClassLoader) { try { URLClassLoader urlClassLoader = ObjectUtils.cast(loader, URLClassLoader.class); urlClassLoader.clearAssertionStatus(); // Finds if loader associated class or superclass has "close" // method checkOnClose(URLClassLoader.class); if (hasCloseMethod) { urlClassLoader.close(); } } catch (Throwable th) { LOG.error(th.getMessage(), th); } } } }
package org.mifmi.commons4j.io.file; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributeView; import java.nio.file.attribute.FileTime; import java.util.Date; import org.mifmi.commons4j.util.StringUtilz; public final class FileUtilz { private static final char[] FILE_NAME_SEPATATORS = {'/', '\\', File.separatorChar}; private static final char FILE_EXTENTION_SEPARATOR = '.'; private FileUtilz() { } public static char getFileNameSeparator(String path) { return getFileNameSeparator(path, File.separatorChar); } public static char getFileNameSeparator(String path, char defaultSeparator) { int idx = StringUtilz.indexOf(path, FILE_NAME_SEPATATORS); char fileNameSeparator; if (idx == -1) { fileNameSeparator = defaultSeparator; } else { fileNameSeparator = path.charAt(idx); } return fileNameSeparator; } public static String getFileName(String path) { if (path == null) { return null; } int idx = StringUtilz.lastIndexOf(path, FILE_NAME_SEPATATORS); if (idx == -1) { return path; } else { return path.substring(idx + 1); } } public static String getBasePath(String path) { if (path == null) { return null; } int idx = path.lastIndexOf(FILE_EXTENTION_SEPARATOR); if (idx <= 0) { return path; } else { return path.substring(0, idx); } } public static String getBaseName(String path) { if (path == null) { return null; } String fileName = getFileName(path); int idx = fileName.lastIndexOf(FILE_EXTENTION_SEPARATOR); if (idx <= 0) { return fileName; } else { return path.substring(0, idx); } } public static String getExt(String path) { if (path == null) { return null; } int idx = path.lastIndexOf(FILE_EXTENTION_SEPARATOR); if (idx <= 0) { return ""; } else { idx++; if (path.length() <= idx) { return ""; } else { return path.substring(idx); } } } public static String addSuffix(String path, String suffix) { if (path == null) { return null; } if (path.indexOf(FILE_EXTENTION_SEPARATOR) == -1) { return path + suffix; } return getBasePath(path) + suffix + FILE_EXTENTION_SEPARATOR + getExt(path); } public static String getParentFolderPath(String path) { if (path == null) { return null; } int idx = StringUtilz.lastIndexOf(path, FILE_NAME_SEPATATORS); if (idx <= 0) { return ""; } if (path.length() == idx + 1) { idx = StringUtilz.lastIndexOf(path, FILE_NAME_SEPATATORS, idx - 1); if (idx <= 0) { return ""; } } return path.substring(0, idx); } public static String getPath(String basePath, String subPath) { return getPath(basePath, subPath, File.separatorChar); } public static String getPath(String basePath, String subPath, char separator) { if (basePath == null) { basePath = ""; } if (subPath == null) { subPath = ""; } String strSep = String.valueOf(separator); String path; if (basePath.endsWith(strSep)) { if (subPath.startsWith(strSep)) { path = basePath + subPath.substring(1); } else { path = basePath + subPath; } } else { if (subPath.startsWith(strSep)) { path = basePath + subPath; } else { path = basePath + separator + subPath; } } return path; } public static String getCanonicalPath(String path, char separator) { StringBuilder pathSb = new StringBuilder(path); int prevSepIdx = -1; int sepIdx = -1; boolean o = true; int d = 0; for (int i = 0; i < pathSb.length(); i++) { char ch = pathSb.charAt(i); if (o && ch == '.') { d++; } else if (ch == separator) { if (o) { if (d == 0) { prevSepIdx = sepIdx; sepIdx = i; } else if (d == 1) { pathSb.delete(sepIdx + 1, i + 1); i = sepIdx; } else if (d == 2) { pathSb.delete(prevSepIdx + 1, i + 1); i = prevSepIdx; sepIdx = prevSepIdx; prevSepIdx = StringUtilz.lastIndexOf(pathSb, separator, prevSepIdx - 1); } else { throw new RuntimeException(); } } else { prevSepIdx = sepIdx; sepIdx = i; } o = true; d = 0; } else { o = false; d = 0; } } if (o) { if (d == 1) { pathSb.setLength(sepIdx + 1); } else if (d == 2) { pathSb.setLength(prevSepIdx + 1); } } return pathSb.toString(); } public static void setTimes(Path path, Date time) throws IOException { FileTime fileTime = FileTime.fromMillis(time.getTime()); BasicFileAttributeView attrs = Files.getFileAttributeView(path, BasicFileAttributeView.class); attrs.setTimes(fileTime, fileTime, fileTime); } public static void setTimes(Path path, long time) throws IOException { FileTime fileTime = FileTime.fromMillis(time); BasicFileAttributeView attrs = Files.getFileAttributeView(path, BasicFileAttributeView.class); attrs.setTimes(fileTime, fileTime, fileTime); } public static void setTimes(Path path, Date lastModifiedTime, Date lastAccessTime, Date creationTIme) throws IOException { BasicFileAttributeView attrs = Files.getFileAttributeView(path, BasicFileAttributeView.class); attrs.setTimes( (lastModifiedTime == null) ? null : FileTime.fromMillis(lastModifiedTime.getTime()), (lastAccessTime == null) ? null : FileTime.fromMillis(lastAccessTime.getTime()), (creationTIme == null) ? null : FileTime.fromMillis(creationTIme.getTime()) ); } public static void setTimes(Path path, long lastModifiedTime, long lastAccessTime, long creationTIme) throws IOException { BasicFileAttributeView attrs = Files.getFileAttributeView(path, BasicFileAttributeView.class); attrs.setTimes( FileTime.fromMillis(lastModifiedTime), FileTime.fromMillis(lastAccessTime), FileTime.fromMillis(creationTIme) ); } }
package org.camsrobotics.frc2016; import edu.wpi.first.wpilibj.networktables.NetworkTable; /** * NetworkTables Vision Adapter * * @author Michael * */ public class Vision { private NetworkTable table; private double[] m_defaultVal = new double[0]; private int m_max; private int m_maxKey = 0; private static Vision m_instance = null; /** * Constructs a network table given a key. (For instance 'GRIP/myContourReport') * @param key */ private Vision() { table = NetworkTable.getTable("GRIP/myContourReport"); } /** * Get one instance of vision object. (Since we will never need more than one.) * @Vision Instance */ public static Vision getInstance() { if (m_instance == null) { m_instance = new Vision(); } return m_instance; } /** * Returns max value in a given array. * @param array * @throws Exception */ private int getMax(double[] array) throws Exception { if (array != null && array != m_defaultVal) { m_max = 0; for (int i = 0; i < array.length; i++) { m_max = array[i] > m_max ? i : m_max; } return m_max; } else { throw new Exception("There is nothing in the array."); } } /** * Returns width of largest contour. Only works with contour reports. * @throws Exception */ public double getWidth() throws Exception { double[] m_areas = table.getNumberArray("area", m_defaultVal); double[] m_widths = table.getNumberArray("width", m_defaultVal); m_maxKey = getMax(m_areas); return m_widths[m_maxKey]; } /** * Returns height of largest contour, or the length of the longest line. * @throws Exception */ public double getHeight() throws Exception { double[] m_areas = table.getNumberArray("area", m_defaultVal); double[] m_heights = table.getNumberArray("height", m_defaultVal); m_maxKey = getMax(m_areas); return m_heights[m_maxKey]; } /** * Returns largest measured area. Only works for contour reports. * @throws Exception */ public double getArea() throws Exception { double[] m_areas = table.getNumberArray("area", m_defaultVal); m_maxKey = getMax(m_areas); return m_areas[m_maxKey]; } /** * Returns centerX of the largest contour or longest line. * @throws Exception */ public double getCenterX() throws Exception { double[] m_areas = table.getNumberArray("area", m_defaultVal); double[] m_centerxs = table.getNumberArray("centerX", m_defaultVal); m_maxKey = getMax(m_areas); return m_centerxs[m_maxKey]; } /** * Returns centerY of the largest contour. * @throws Exception */ public double getCenterY() throws Exception { double[] m_areas = table.getNumberArray("area", m_defaultVal); double[] m_centerys = table.getNumberArray("centerY", m_defaultVal); m_maxKey = getMax(m_areas); return m_centerys[m_maxKey]; } //TODO Distance method, clean this code up }
package edu.columbia.cs.psl.phosphor; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.lang.instrument.Instrumentation; import java.security.ProtectionDomain; import com.sun.xml.internal.ws.org.objectweb.asm.Type; import edu.columbia.cs.psl.phosphor.instrumenter.TaintTrackingClassVisitor; import edu.columbia.cs.psl.phosphor.org.objectweb.asm.AnnotationVisitor; import edu.columbia.cs.psl.phosphor.org.objectweb.asm.ClassReader; import edu.columbia.cs.psl.phosphor.org.objectweb.asm.ClassVisitor; import edu.columbia.cs.psl.phosphor.org.objectweb.asm.ClassWriter; import edu.columbia.cs.psl.phosphor.org.objectweb.asm.MethodVisitor; import edu.columbia.cs.psl.phosphor.org.objectweb.asm.Opcodes; import edu.columbia.cs.psl.phosphor.org.objectweb.asm.commons.JSRInlinerAdapter; import edu.columbia.cs.psl.phosphor.org.objectweb.asm.commons.SerialVersionUIDAdder; import edu.columbia.cs.psl.phosphor.org.objectweb.asm.util.CheckClassAdapter; import edu.columbia.cs.psl.phosphor.org.objectweb.asm.util.TraceClassVisitor; import edu.columbia.cs.psl.phosphor.runtime.TaintInstrumented; import edu.columbia.cs.psl.phosphor.struct.TaintedByteArray; public class PreMain { private static Instrumentation instrumentation; static boolean DEBUG = true; public static ClassLoader bigLoader = PreMain.class.getClassLoader(); public static final class PCLoggingTransformer implements ClassFileTransformer { private final class HackyClassWriter extends ClassWriter { private HackyClassWriter(ClassReader classReader, int flags) { super(classReader, flags); } private Class<?> getClass(String name) throws ClassNotFoundException { try { return Class.forName(name.replace("/", "."),false,bigLoader); } catch (SecurityException e) { throw new ClassNotFoundException("Security exception when loading class"); } catch(NoClassDefFoundError e) { throw new ClassNotFoundException(); } catch(Throwable e) { throw new ClassNotFoundException(); } } protected String getCommonSuperClass(String type1, String type2) { Class<?> c, d; try { c = getClass(type1); d = getClass(type2); } catch (ClassNotFoundException e) { // System.err.println("Can not do superclass for " + type1 + " and " + type2); // logger.debug("Error while finding common super class for " + type1 +"; " + type2,e); return "java/lang/Object"; // throw new RuntimeException(e); } catch (ClassCircularityError e) { return "java/lang/Object"; } if (c.isAssignableFrom(d)) { return type1; } if (d.isAssignableFrom(c)) { return type2; } if (c.isInterface() || d.isInterface()) { return "java/lang/Object"; } else { do { c = c.getSuperclass(); } while (!c.isAssignableFrom(d)); // System.out.println("Returning " + c.getName()); return c.getName().replace('.', '/'); } } } private void upgradeToForceFrames(ClassReader cr, ClassWriter cw) throws Throwable { // System.out.println("upgrading: " + cr.getClassName()); ClassWriter cw2 = new HackyClassWriter(cr,ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); cr.accept(new ClassVisitor(Opcodes.ASM5,cw2) { @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { // System.out.println("old was " + version); version = 50; access = access & ~Opcodes.ACC_SUPER; if((access & Opcodes.ACC_INTERFACE) != 0) access |= Opcodes.ACC_ABSTRACT; super.visit(version, access, name, signature, superName, interfaces); } @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { return new JSRInlinerAdapter(super.visitMethod(access, name, desc, signature, exceptions), access, name, desc, signature, exceptions); } }, ClassReader.EXPAND_FRAMES); byte[] newClass = cw2.toByteArray(); cr = new ClassReader(newClass); try{ cr.accept( // new CheckClassAdapter( new SerialVersionUIDAdder(new TaintTrackingClassVisitor(cw)) , ClassReader.EXPAND_FRAMES); } catch(Throwable ex) { PrintWriter pw = null; try { pw = new PrintWriter(new FileWriter("lastClass.txt")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } TraceClassVisitor cv= new TraceClassVisitor(null,pw); try{ ex.printStackTrace(); System.err.println("running again to trace it"); cr = new ClassReader(cw2.toByteArray()); cr.accept( new CheckClassAdapter( new SerialVersionUIDAdder(new TaintTrackingClassVisitor(cv)) ) , ClassReader.EXPAND_FRAMES); } catch(Throwable ex2) { innerException = true; System.err.println("writing out to " + cr.getClassName()); cv.p.print(pw); pw.flush(); pw.close(); System.err.println("written"); File f = new File("debug/" + cr.getClassName().replace("/", ".") + ".class"); try { FileOutputStream fos = new FileOutputStream(f); fos.write(cr.b); fos.close(); } catch (Exception ex5) { ex5.printStackTrace(); } System.err.println("ex2"); ex2.printStackTrace(); System.out.println("exiting"); System.exit(-1); System.out.println("ASDHFASKJFALDSFJALSDFJADSLKFJADSF STUPID"); } System.err.println("ex1"); ex.printStackTrace(); throw ex; } } static boolean innerException = false; public TaintedByteArray transform$$INVIVO_PC(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, int[] classtaint, byte[] classfileBuffer, TaintedByteArray ret) throws IllegalClassFormatException { bigLoader = loader; Instrumenter.loader = bigLoader; if(className.startsWith("sun")) //there are dynamically generated accessors for reflection, we don't want to instrument those. ret.val = classfileBuffer; else ret.val = transform(loader, className, classBeingRedefined, protectionDomain, classfileBuffer); ret.taint = new int[ret.val.length]; return ret; } public byte[] transform(ClassLoader loader, final String className2, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException { ClassReader cr = new ClassReader(classfileBuffer); String className = cr.getClassName(); innerException = false; if(Instrumenter.isIgnoredClass(className)) { // System.out.println("Premain.java ignore: " + className); return classfileBuffer; } // if(className.equals("java/lang/Integer")) // System.out.println(className); final boolean[] shouldBeDoneBetter = new boolean[1]; shouldBeDoneBetter[0]=false; cr.accept(new ClassVisitor(Opcodes.ASM5) { @Override public AnnotationVisitor visitAnnotation(String desc, boolean visible) { if(desc.equals(Type.getDescriptor(TaintInstrumented.class))) { shouldBeDoneBetter[0] = true; } return super.visitAnnotation(desc, visible); } }, ClassReader.SKIP_CODE); if(shouldBeDoneBetter[0]) return classfileBuffer; // System.out.println("Instrumenting: " + className); // System.out.println(classBeingRedefined); TraceClassVisitor cv =null; try { ClassWriter cw = new HackyClassWriter(cr, ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); try{ cr.accept( // new CheckClassAdapter( new SerialVersionUIDAdder(new TaintTrackingClassVisitor(cw)) , ClassReader.EXPAND_FRAMES); } catch(ClassFormatError ex) { upgradeToForceFrames(cr, cw); } catch(ArrayIndexOutOfBoundsException ex) { } if (DEBUG) { File debugDir = new File("debug"); if (!debugDir.exists()) debugDir.mkdir(); File f = new File("debug/" + className.replace("/", ".") + ".class"); FileOutputStream fos = new FileOutputStream(f); fos.write(cw.toByteArray()); fos.close(); } { // if(TaintUtils.DEBUG_FRAMES) // System.out.println("NOW IN CHECKCLASSADAPTOR"); if (TaintUtils.VERIFY_CLASS_GENERATION && !className.endsWith("org/codehaus/janino/UnitCompiler")) { cr = new ClassReader(cw.toByteArray()); cr.accept(new CheckClassAdapter(new ClassWriter(0)), 0); } } // System.out.println("Succeeded w " + className); return cw.toByteArray(); } catch (Throwable ex) { cv= new TraceClassVisitor(null,null); try{ cr.accept( // new CheckClassAdapter( new SerialVersionUIDAdder(new TaintTrackingClassVisitor(cv)) , ClassReader.EXPAND_FRAMES); } catch(Throwable ex2) { } ex.printStackTrace(); System.err.println("method so far:"); if (!innerException) { PrintWriter pw = null; try { pw = new PrintWriter(new FileWriter("lastClass.txt")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } cv.p.print(pw); pw.flush(); } System.out.println("Saving " + className); File f = new File("debug/"+className.replace("/", ".")+".class"); try{ FileOutputStream fos = new FileOutputStream(f); fos.write(classfileBuffer); fos.close(); } catch(Exception ex2) { ex.printStackTrace(); } System.exit(-1); return new byte[0]; } } } public static void premain(String args, Instrumentation inst) { instrumentation = inst; if(Instrumenter.loader == null) Instrumenter.loader = bigLoader; ClassFileTransformer transformer = new PCLoggingTransformer(); inst.addTransformer(transformer); } }
package org.ensembl.healthcheck; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.logging.Logger; public final class Species { /** Specific type of species */ public static final Species HOMO_SAPIENS = new Species("homo_sapiens"); /** Specific type of species */ public static final Species ANOPHELES_GAMBIAE = new Species("anopheles_gambiae"); /** Specific type of species */ public static final Species CAENORHABDITIS_ELEGANS = new Species("caenorhabditis_elegans"); /** Specific type of species */ public static final Species CAENORHABDITIS_BRIGGSAE = new Species("caenorhabditis_briggsae"); /** Specific type of species */ public static final Species CIONA_INTESTINALIS = new Species("ciona_intestinalis"); /** Specific type of species */ public static final Species DANIO_RERIO = new Species("danio_rerio"); /** Specific type of species */ public static final Species DROSOPHILA_MELANOGASTER = new Species("drosophila_melanogaster"); /** Specific type of species */ public static final Species TAKIFUGU_RUBRIPES = new Species("takifugu_rubripes"); /** Specific type of species */ public static final Species MUS_MUSCULUS = new Species("mus_musculus"); /** Specific type of species */ public static final Species RATTUS_NORVEGICUS = new Species("rattus_norvegicus"); /** Specific type of species */ public static final Species PAN_TROGLODYTES = new Species("pan_troglodytes"); /** Specific type of species */ public static final Species GALLUS_GALLUS = new Species("gallus_gallus"); /** Specific type of species */ public static final Species TETRAODON_NIGROVIRIDIS = new Species("tetraodon_nigroviridis"); /** Specific type of species */ public static final Species APIS_MELLIFERA = new Species("apis_mellifera"); /** Specific type of species */ public static final Species BOS_TAURUS = new Species("bos_taurus"); /** Specific type of species */ public static final Species CANIS_FAMILIARIS = new Species("canis_familiaris"); /** Specific type of species */ public static final Species XENOPUS_TROPICALIS = new Species("xenopus_tropicalis"); /** Specific type of species */ public static final Species MONODELPHIS_DOMESTICA = new Species("monodelphis_domestica"); /** Specific type of species */ public static final Species SACCHAROMYCES_CEREVISIAE = new Species("saccharomyces_cerevisiae"); /** Specific type of species */ public static final Species MACACA_MULATTA = new Species("macaca_mulatta"); /** Specific type of species */ public static final Species LOXODONTA_AFRICANA = new Species("loxodonta_africana"); /** Specific type of species */ public static final Species DASYPUS_NOVEMCINCTUS = new Species("dasypus_novemcinctus"); /** Specific type of species */ public static final Species ORYZIAS_LATIPES = new Species("oryzias_latipes"); /** Specific type of species */ public static final Species SUS_SCROFA = new Species("sus_scrofa"); /** Specific type of species */ public static final Species ECHINOPS_TELFAIRI = new Species("echinops_telfairi"); /** Specific type of species */ public static final Species ORYCTOLAGUS_CUNICULUS = new Species("oryctolagus_cuniculus"); /** Specific type of species */ public static final Species CIONA_SAVIGNYI = new Species("ciona_savignyi"); /** Specific type of species */ public static final Species GASTEROSTEUS_ACULEATUS = new Species("gasterosteus_aculeatus"); /** Specific type of species */ public static final Species AEDES_AEGYPTI = new Species("aedes_aegypti"); /** Specific type of species */ public static final Species ORNITHORHYNCHUS_ANATINUS = new Species("ornithorhynchus_anatinus"); /** Specific type of species */ public static final Species FELIS_CATUS = new Species("felis_catus"); /** Specific type of species */ public static final Species OTOLEMUR_GARNETTII = new Species("otolemur_garnettii"); /** Specific type of species */ public static final Species MYOTIS_LUCIFUGUS = new Species("myotis_lucifugus"); /** Specific type of species */ public static final Species SOREX_ARANEUS = new Species("sorex_araneus"); /** Specific type of species */ public static final Species OCHOTONA_PRINCEPS = new Species("ochotona_princeps"); /** Specific type of species */ public static final Species ERINACEUS_EUROPAEUS = new Species("erinaceus_europaeus"); /** Specific type of species */ public static final Species CAVIA_PORCELLUS = new Species("cavia_porcellus"); /** Specific type of species */ public static final Species TUPAIA_BELANGERI = new Species("tupaia_belangeri"); /** Specific type of species */ public static final Species SPERMOPHILUS_TRIDECEMLINEATUS = new Species("spermophilus_tridecemlineatus"); /** Specific type of species */ public static final Species EQUUS_CABALLUS = new Species("equus_caballus"); /** Non-ensembl database */ public static final Species SYSTEM = new Species("system"); /** Help database */ public static final Species HELP = new Species("help"); /** A taxonomy database */ public static final Species NCBI_TAXONOMY = new Species("ncbi_taxonomy"); /** An ensembl_website database */ public static final Species ENSEMBL_WEBSITE = new Species("ensembl_website"); /** An healthcheck database */ public static final Species HEALTHCHECK = new Species("healthcheck"); /** Unknown species */ public static final Species UNKNOWN = new Species("unknown"); private final String name; private static Logger logger = Logger.getLogger("HealthCheckLogger"); private Species(String name) { this.name = name; } /** * @return The string representation of this species. */ public String toString() { return this.name; } // Taxonomy IDs - see ensembl-compara/sql/taxon.txt private static Map taxonIDToSpecies = new HashMap(); private static Map speciesToTaxonID = new HashMap(); private static Map assemblyPrefixToSpecies = new HashMap(); private static Map speciesToAssemblyPrefix = new HashMap(); private static Map ensemblStableIDPrefix = new HashMap(); private static Map vegaStableIDPrefix = new HashMap(); static { taxonIDToSpecies.put("9606", HOMO_SAPIENS); taxonIDToSpecies.put("10090", MUS_MUSCULUS); taxonIDToSpecies.put("10116", RATTUS_NORVEGICUS); taxonIDToSpecies.put("31033", TAKIFUGU_RUBRIPES); taxonIDToSpecies.put("7165", ANOPHELES_GAMBIAE); taxonIDToSpecies.put("7227", DROSOPHILA_MELANOGASTER); taxonIDToSpecies.put("6239", CAENORHABDITIS_ELEGANS); taxonIDToSpecies.put("6238", CAENORHABDITIS_BRIGGSAE); taxonIDToSpecies.put("7719", CIONA_INTESTINALIS); taxonIDToSpecies.put("7955", DANIO_RERIO); taxonIDToSpecies.put("9598", PAN_TROGLODYTES); taxonIDToSpecies.put("9031", GALLUS_GALLUS); taxonIDToSpecies.put("99883", TETRAODON_NIGROVIRIDIS); taxonIDToSpecies.put("7460", APIS_MELLIFERA); taxonIDToSpecies.put("9913", BOS_TAURUS); taxonIDToSpecies.put("9615", CANIS_FAMILIARIS); taxonIDToSpecies.put("8364", XENOPUS_TROPICALIS); taxonIDToSpecies.put("13616", MONODELPHIS_DOMESTICA); taxonIDToSpecies.put("4932", SACCHAROMYCES_CEREVISIAE); taxonIDToSpecies.put("9544", MACACA_MULATTA); taxonIDToSpecies.put("9785", LOXODONTA_AFRICANA); taxonIDToSpecies.put("9361", DASYPUS_NOVEMCINCTUS); taxonIDToSpecies.put("8090", ORYZIAS_LATIPES); taxonIDToSpecies.put("9371", ECHINOPS_TELFAIRI); taxonIDToSpecies.put("9986", ORYCTOLAGUS_CUNICULUS); taxonIDToSpecies.put("9823", SUS_SCROFA); taxonIDToSpecies.put("51511", CIONA_SAVIGNYI); taxonIDToSpecies.put("69293", GASTEROSTEUS_ACULEATUS); taxonIDToSpecies.put("7159", AEDES_AEGYPTI); taxonIDToSpecies.put("9685", FELIS_CATUS); taxonIDToSpecies.put("30611", OTOLEMUR_GARNETTII); taxonIDToSpecies.put("59463", MYOTIS_LUCIFUGUS); taxonIDToSpecies.put("42254", SOREX_ARANEUS); taxonIDToSpecies.put("9978", OCHOTONA_PRINCEPS); taxonIDToSpecies.put("9258", ORNITHORHYNCHUS_ANATINUS); taxonIDToSpecies.put("9365", ERINACEUS_EUROPAEUS); taxonIDToSpecies.put("10141", CAVIA_PORCELLUS); taxonIDToSpecies.put("37347", TUPAIA_BELANGERI); taxonIDToSpecies.put("43179", SPERMOPHILUS_TRIDECEMLINEATUS); taxonIDToSpecies.put("9796", EQUUS_CABALLUS); // and the other way around Iterator it = taxonIDToSpecies.keySet().iterator(); while (it.hasNext()) { String taxonID = (String) it.next(); Species species = (Species) taxonIDToSpecies.get(taxonID); speciesToTaxonID.put(species, taxonID); } assemblyPrefixToSpecies.put("RGSC", RATTUS_NORVEGICUS); assemblyPrefixToSpecies.put("BDGP", DROSOPHILA_MELANOGASTER); assemblyPrefixToSpecies.put("ZFISH", DANIO_RERIO); assemblyPrefixToSpecies.put("FUGU", TAKIFUGU_RUBRIPES); assemblyPrefixToSpecies.put("AgamP", ANOPHELES_GAMBIAE); assemblyPrefixToSpecies.put("WB", CAENORHABDITIS_ELEGANS); assemblyPrefixToSpecies.put("CBR", CAENORHABDITIS_BRIGGSAE); assemblyPrefixToSpecies.put("JGI", CIONA_INTESTINALIS); assemblyPrefixToSpecies.put("NCBI", HOMO_SAPIENS); assemblyPrefixToSpecies.put("NCBIM", MUS_MUSCULUS); assemblyPrefixToSpecies.put("TETRAODON", TETRAODON_NIGROVIRIDIS); assemblyPrefixToSpecies.put("AMEL", APIS_MELLIFERA); assemblyPrefixToSpecies.put("CHIMP", PAN_TROGLODYTES); assemblyPrefixToSpecies.put("WASHUC", GALLUS_GALLUS); assemblyPrefixToSpecies.put("BTAU", BOS_TAURUS); assemblyPrefixToSpecies.put("BROADD", CANIS_FAMILIARIS); assemblyPrefixToSpecies.put("JGI", XENOPUS_TROPICALIS); assemblyPrefixToSpecies.put("BROADO", MONODELPHIS_DOMESTICA); assemblyPrefixToSpecies.put("SGD", SACCHAROMYCES_CEREVISIAE); assemblyPrefixToSpecies.put("MM", MACACA_MULATTA); assemblyPrefixToSpecies.put("BROADE", LOXODONTA_AFRICANA); assemblyPrefixToSpecies.put("ARMA", DASYPUS_NOVEMCINCTUS); assemblyPrefixToSpecies.put("MEDAKA", ORYZIAS_LATIPES); assemblyPrefixToSpecies.put("TENREC", ECHINOPS_TELFAIRI); assemblyPrefixToSpecies.put("RABBIT", ORYCTOLAGUS_CUNICULUS); assemblyPrefixToSpecies.put("PIG", SUS_SCROFA); assemblyPrefixToSpecies.put("CSAV", CIONA_SAVIGNYI); assemblyPrefixToSpecies.put("BROADS", GASTEROSTEUS_ACULEATUS); assemblyPrefixToSpecies.put("CAT", FELIS_CATUS); assemblyPrefixToSpecies.put("BUSHBABY", OTOLEMUR_GARNETTII); assemblyPrefixToSpecies.put("MICROBAT", MYOTIS_LUCIFUGUS); assemblyPrefixToSpecies.put("COMMON_SHREW", SOREX_ARANEUS); assemblyPrefixToSpecies.put("PIKA", OCHOTONA_PRINCEPS); assemblyPrefixToSpecies.put("OANA", ORNITHORHYNCHUS_ANATINUS); assemblyPrefixToSpecies.put("HEDGEHOG", ERINACEUS_EUROPAEUS); assemblyPrefixToSpecies.put("GUINEAPIG", CAVIA_PORCELLUS); assemblyPrefixToSpecies.put("TREESHREW", TUPAIA_BELANGERI); assemblyPrefixToSpecies.put("SQUIRREL", SPERMOPHILUS_TRIDECEMLINEATUS); assemblyPrefixToSpecies.put("EQUUS", EQUUS_CABALLUS); // and the other way around it = assemblyPrefixToSpecies.keySet().iterator(); while (it.hasNext()) { String ap = (String) it.next(); Species species = (Species) assemblyPrefixToSpecies.get(ap); speciesToAssemblyPrefix.put(species, ap); } // stable ID prefixes - ensembl databases ensemblStableIDPrefix.put(AEDES_AEGYPTI, "IGNORE"); ensemblStableIDPrefix.put(ANOPHELES_GAMBIAE, "ENSANG"); ensemblStableIDPrefix.put(BOS_TAURUS, "ENSBTA"); ensemblStableIDPrefix.put(CAENORHABDITIS_ELEGANS, "IGNORE"); ensemblStableIDPrefix.put(CANIS_FAMILIARIS, "ENSCAF"); ensemblStableIDPrefix.put(CAVIA_PORCELLUS, "ENSCPO"); ensemblStableIDPrefix.put(CIONA_INTESTINALIS, "ENSCIN"); ensemblStableIDPrefix.put(CIONA_SAVIGNYI, "ENSCSAV"); ensemblStableIDPrefix.put(DANIO_RERIO, "ENSDAR"); ensemblStableIDPrefix.put(DASYPUS_NOVEMCINCTUS, "ENSDNO"); ensemblStableIDPrefix.put(DROSOPHILA_MELANOGASTER, "IGNORE"); ensemblStableIDPrefix.put(ECHINOPS_TELFAIRI, "ENSETE"); ensemblStableIDPrefix.put(ERINACEUS_EUROPAEUS, "ENSEEU"); ensemblStableIDPrefix.put(FELIS_CATUS, "ENSFCA"); ensemblStableIDPrefix.put(GALLUS_GALLUS, "ENSGAL"); ensemblStableIDPrefix.put(GASTEROSTEUS_ACULEATUS, "ENSGAC"); ensemblStableIDPrefix.put(HOMO_SAPIENS, "ENS"); ensemblStableIDPrefix.put(LOXODONTA_AFRICANA, "ENSLAF"); ensemblStableIDPrefix.put(MACACA_MULATTA, "ENSMMU"); ensemblStableIDPrefix.put(MONODELPHIS_DOMESTICA, "ENSMOD"); ensemblStableIDPrefix.put(MUS_MUSCULUS, "ENSMUS"); ensemblStableIDPrefix.put(MYOTIS_LUCIFUGUS, "ENSMLU"); ensemblStableIDPrefix.put(OCHOTONA_PRINCEPS, "ENSOPR"); ensemblStableIDPrefix.put(ORNITHORHYNCHUS_ANATINUS, "ENSOAN"); ensemblStableIDPrefix.put(ORYCTOLAGUS_CUNICULUS, "ENSOCU"); ensemblStableIDPrefix.put(ORYZIAS_LATIPES, "ENSORL"); ensemblStableIDPrefix.put(OTOLEMUR_GARNETTII, "ENSOGA"); ensemblStableIDPrefix.put(PAN_TROGLODYTES, "ENSPTR"); ensemblStableIDPrefix.put(SOREX_ARANEUS, "ENSSAR"); ensemblStableIDPrefix.put(RATTUS_NORVEGICUS, "ENSRNO"); ensemblStableIDPrefix.put(SACCHAROMYCES_CEREVISIAE, "IGNORE"); ensemblStableIDPrefix.put(TAKIFUGU_RUBRIPES, "SINFRU"); ensemblStableIDPrefix.put(TETRAODON_NIGROVIRIDIS, "IGNORE"); ensemblStableIDPrefix.put(TUPAIA_BELANGERI, "ENSTBE"); ensemblStableIDPrefix.put(XENOPUS_TROPICALIS, "ENSXET"); ensemblStableIDPrefix.put(SPERMOPHILUS_TRIDECEMLINEATUS, "ENSSTO"); // stable ID prefixes - Vega databases vegaStableIDPrefix.put(HOMO_SAPIENS, "OTTHUM"); vegaStableIDPrefix.put(MUS_MUSCULUS, "OTTMUS"); vegaStableIDPrefix.put(CANIS_FAMILIARIS, "OTTCAN"); vegaStableIDPrefix.put(DANIO_RERIO, "OTTDAR"); } /** * Resolve an alias to a Species object. * * @param speciesAlias * The alias (e.g. human, homosapiens, hsapiens) * @return The species object corresponding to alias, or Species.UNKNOWN if it * cannot be resolved. */ public static Species resolveAlias(String speciesAlias) { String alias = speciesAlias.toLowerCase(); if (in(alias, "human,hsapiens,homosapiens,homo_sapiens")) { return HOMO_SAPIENS; } if (in(alias, "mosquito,anopheles,agambiae,anophelesgambiae,anopheles_gambiae")) { return ANOPHELES_GAMBIAE; } if (in(alias, "elegans,celegans,caenorhabditiselegans,caenorhabditis_elegans")) { return CAENORHABDITIS_ELEGANS; } if (in(alias, "briggsae,cbriggsae,caenorhabditisbriggsae,caenorhabditis_briggsae")) { return CAENORHABDITIS_BRIGGSAE; } if (in(alias, "zebrafish,danio,drerio,daniorerio,danio_rerio")) { return DANIO_RERIO; } if (in(alias, "pufferfish,fugu,frubripes,fugurubripes,fugu_rubripes,takifugu,trubripes,takifugurubripes,takifugu_rubripes")) { return TAKIFUGU_RUBRIPES; } if (in(alias, "drosophila,dmelongaster,drosophilamelanogaster,drosophila_melanogaster")) { return DROSOPHILA_MELANOGASTER; } if (in(alias, "mouse,mmusculus,musmusculus,mus_musculus")) { return MUS_MUSCULUS; } if (in(alias, "rat,rnovegicus,rattusnorvegicus,rattus_norvegicus")) { return RATTUS_NORVEGICUS; } if (in(alias, "chimp,chimpanzee,ptroglodytes,pantroglodytes,pan_troglodytes")) { return PAN_TROGLODYTES; } if (in(alias, "chicken,chick,ggallus,gallusgallus,gallus_gallus")) { return GALLUS_GALLUS; } if (in(alias, "tetraodon,tnigroviridis,tetraodonnigroviridis,tetraodon_nigroviridis")) { return TETRAODON_NIGROVIRIDIS; } if (in(alias, "honeybee,honey_bee,apis,amellifera,apismellifera,apis_mellifera")) { return APIS_MELLIFERA; } if (in(alias, "cow,btaurus,bostaurus,bos_taurus")) { return BOS_TAURUS; } if (in(alias, "dog,doggy,cfamiliaris,canisfamiliaris,canis_familiaris")) { return CANIS_FAMILIARIS; } if (in(alias, "pipid,pipidfrog,xenopus,xtropicalis,xenopustropicalis,xenopus_tropicalis")) { return XENOPUS_TROPICALIS; } if (in( alias, "opossum,monodelphis,mdomestica,mdomesticus,monodelphisdomestica,monodelphisdomesticus,monodelphis_domestica,monodelphis_domesticus")) { return MONODELPHIS_DOMESTICA; } if (in(alias, "yeast,saccharomyces,scerevisiae,saccharomycescerevisiae,saccharomyces_cerevisiae")) { return SACCHAROMYCES_CEREVISIAE; } if (in(alias, "cionaintestinalis,ciona_intestinalis,ciona_int")) { return CIONA_INTESTINALIS; } if (in(alias, "macacamulatta,macaca_mulatta,rhesusmacaque,rhesus_macaque,macaque")) { return MACACA_MULATTA; } if (in(alias, "elephant,loxodonta_africana,nelly,loxodonta,african_elephant,african_savannah_elephant,african_bush_elephant")) { return LOXODONTA_AFRICANA; } if (in(alias, "armadillo,dasypus_novemcinctus,daisy,dasypus,nine_banded_armadillo,nine-banded_armadillo,texas_armadillo")) { return DASYPUS_NOVEMCINCTUS; } if (in(alias, "medaka,oryzias_latipes,oryzias,japanese_medaka,japanese_rice_fish,japanese_ricefish,japanese_killifish")) { return ORYZIAS_LATIPES; } if (in(alias, "tenrec,echinops_telfairi,echinops,small_madagascar_hedgehog,lesser_hedgehog_tenrec")) { return ECHINOPS_TELFAIRI; } if (in(alias, "rabbit,oryctolagus_cuniculus,oryctolagus,domestic_rabbit,bunny,japanese_white_rabbit,european_rabbit")) { return ORYCTOLAGUS_CUNICULUS; } if (in(alias, "cat,felis_catus,fcatus,felis,domestic_cat")) { return FELIS_CATUS; } if (in(alias, "bushbaby,bush_baby,galago,small_eared_galago,ogarnettii,otolemur_garnettii,otolemur")) { return OTOLEMUR_GARNETTII; } if (in(alias, "microbat,little_brown_bat,mlucifugus,myotis_lucifugus,myotis")) { return MYOTIS_LUCIFUGUS; } if (in(alias, "shrew,common_shrew,commonShrew,european_shrew,sorex_araneus,saraneus,sorex")) { return SOREX_ARANEUS; } if (in(alias, "pika,Americanpika,American_pika,ochotona_princeps,oprinceps,ochotona")) { return OCHOTONA_PRINCEPS; } if (in(alias, "hedgehog,erinaceus_europaeus,european_hedgehog,eeuropaeus")) { return ERINACEUS_EUROPAEUS; } if (in(alias, "guineapig,guinea_pig,cavia_porcellus,cporcellus")) { return CAVIA_PORCELLUS; } if (in(alias, "treeshrew,tbelangeri,tupaia_belangeri,northern_tree_shrew,common_tree_shrew")) { return TUPAIA_BELANGERI; } if (in(alias, "squirrel,stridecemlineatus,thirteen-lined_ground_squirrel,spermophilus_tridecemlineatus,spermophilus_tridecemlineatus_arenicola")) { return SPERMOPHILUS_TRIDECEMLINEATUS; } if (in(alias, "pig,boar,wildboar,wild_boar,susscrofa,sus_scrofa")) { return SUS_SCROFA; } if (in(alias, "savignyi,ciona_savignyi,csavignyi,cionasavignyi")) { return CIONA_SAVIGNYI; } if (in(alias, "stickleback,gas_aculeatus,gasaculeatus,gasterosteus_aculeatus,gasterosteusaculeatus")) { return GASTEROSTEUS_ACULEATUS; } if (in(alias, "aedes,aedes_aegypti,aedesaegypti")) { return AEDES_AEGYPTI; } if (in(alias, "platypus,ornithorhynchus_anatinus,oanatius")) { return ORNITHORHYNCHUS_ANATINUS; } if (in(alias, "horse,equus_caballus,equus,mr_ed,ecaballus")) { return EQUUS_CABALLUS; } // default // logger.warning("Cannot resolve species alias " + alias + " to a // species - returning Species.UNKNOWN"); return Species.UNKNOWN; } /** * Get the taxonomy ID associated with a particular species. * * @param s * The species to look up. * @return The taxonomy ID associated with s, or "" if none is found. */ public static String getTaxonomyID(Species s) { String result = ""; if (speciesToTaxonID.containsKey(s)) { result = (String) speciesToTaxonID.get(s); } else { logger.warning("Cannot get taxonomy ID for species " + s); } return result; } /** * Get the species associated with a particular taxonomy ID. * * @param t * The taxonomy ID to look up. * @return The species associated with t, or Species.UNKNOWN if none is found. */ public static Species getSpeciesFromTaxonomyID(String t) { Species result = UNKNOWN; if (taxonIDToSpecies.containsKey(t)) { result = (Species) taxonIDToSpecies.get(t); } else { logger.warning("Cannot get species for taxonomy ID " + t + " returning Species.UNKNOWN"); } return result; } /** * Return true if alias appears somewhere in a string. */ private static boolean in(String alias, String list) { String[] aliases = list.split(","); for (int i = 0; i < aliases.length; i++) { if (alias.equals(aliases[i])) { return true; } } return false; } /** * Return a Species object corresponding to a particular assembly prefix. * * @param prefix * The assembly prefix. * * @return The Species corresponding to prefix, or Species.UNKNOWN. */ public static Species getSpeciesForAssemblyPrefix(String prefix) { Species result = Species.UNKNOWN; if (assemblyPrefixToSpecies.containsKey(prefix)) { result = (Species) assemblyPrefixToSpecies.get(prefix); } else { result = Species.UNKNOWN; } return result; } /** * Get the assembly prefix for a species. * * @param s * The species. * @return The assembly prefix for s. */ public static String getAssemblyPrefixForSpecies(Species s) { return (String) speciesToAssemblyPrefix.get(s); } /** * Get the stable ID prefix for a species. * * @param s * The species. * @param t The type of database. * @return The stable ID prefix for s. Note "IGNORE" is used for imported species. */ public static String getStableIDPrefixForSpecies(Species s, DatabaseType t) { String result = ""; if (t.equals(DatabaseType.CORE)) { result = (String) ensemblStableIDPrefix.get(s); } else if (t.equals(DatabaseType.VEGA)) { result = (String) vegaStableIDPrefix.get(s); } if (result == null || result.equals("")) { logger.warning("Can't get stable ID prefix for " +s.toString() + " " + t.toString() + " database"); } return result; } }
package ru.pinkponies.app; import java.util.logging.Logger; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; /** * An activity with login form. * */ public class LoginActivity extends Activity { /** * The class wide logger. */ private static final Logger LOGGER = Logger.getLogger(LoginActivity.class.getName()); /** * The login edit box. */ private EditText loginEditBox; /** * The password edit box. */ private EditText passwordEditBox; @Override protected void onCreate(final Bundle savedInstanceState) { LOGGER.info("LoginActivity::Initializing..."); super.onCreate(savedInstanceState); this.setContentView(R.layout.activity_login); this.loginEditBox = (EditText) this.findViewById(R.id.login); this.passwordEditBox = (EditText) this.findViewById(R.id.password); LOGGER.info("LoginActivity::Initialized!"); } /** * Called when login button is clicked. * * @param view * the view that was clicked. */ public void onLoginClick(final View view) { final String login = this.loginEditBox.getText().toString(); final String password = this.passwordEditBox.getText().toString(); this.goToMainActivity(login, password); } /** * Opens up a new main activity, passing it login and password. * * @param login * the login * @param password * the password */ public void goToMainActivity(final String login, final String password) { final Intent intent = new Intent(LoginActivity.this, MainActivity.class); intent.putExtra("login", login); intent.putExtra("password", password); this.startActivity(intent); LoginActivity.this.finish(); }; @Override protected void onResume() { super.onResume(); } @Override protected void onPause() { super.onPause(); } @Override protected void onDestroy() { super.onDestroy(); } @Override public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case 0: // do whatever return true; default: return super.onOptionsItemSelected(item); } } @Override public boolean onCreateOptionsMenu(final Menu menu) { this.getMenuInflater().inflate(R.menu.main, menu); return true; } }
package org.jgroups.jmx; import org.jgroups.JChannel; import org.jgroups.JChannelFactory; import org.jgroups.logging.Log; import org.jgroups.logging.LogFactory; import org.jgroups.annotations.MBean; import org.jgroups.stack.Protocol; import org.jgroups.stack.ProtocolStack; import javax.management.*; import java.util.Vector; import java.util.Set; import java.util.Iterator; /** * @author Bela Ban, Vladimir Blagojevic * @version $Id: JmxConfigurator.java,v 1.16 2009/09/23 15:37:42 vlada Exp $ */ public class JmxConfigurator { static final Log log = LogFactory.getLog(JmxConfigurator.class); /** * Registers an already created channel with the given MBeanServer. Wraps instance of JChannel * with DynamicMBean and delegates all calls to the actual JChannel wrapped. * <p> * Optionally, this method will also wrap each protocol in the given channel with DynamicMBean * and register it as well. * * @param channel * @param server * @param domain * Has to be a JMX ObjectName of the domain, e.g. DefaultDomain:name=JGroups * @param register_protocols */ public static void registerChannel(JChannel channel, MBeanServer server, String domain, String cluster_name, boolean register_protocols) throws Exception { if (cluster_name == null) cluster_name = channel != null ? channel.getClusterName() : null; if (cluster_name == null) cluster_name = "null"; if (register_protocols) { ProtocolStack stack = channel.getProtocolStack(); Vector<Protocol> protocols = stack.getProtocols(); for (Protocol p : protocols) { register(p, server, getProtocolRegistrationName(cluster_name, domain, p)); } } register(channel, server, getChannelRegistrationName(channel, domain, cluster_name)); } /** * Registers an already created channel with the given MBeanServer. Wraps instance of JChannel * with DynamicMBean and delegates all calls to the actual JChannel wrapped. * <p> * This method will also wrap each protocol in the given channel with DynamicMBean and register * it as well. * * @param channel * @param server * @param domain * Has to be a JMX ObjectName of the domain, e.g. DefaultDomain:name=JGroups */ public static void registerChannel(JChannel channel, MBeanServer server, String name) throws Exception { registerChannel(channel, server, "jgroups", name, true); } public static void unregisterChannel(MBeanServer server, ObjectName name) throws Exception { if (server != null) server.unregisterMBean(name); } public static void unregisterChannel(MBeanServer server, String name) throws Exception { if (server != null) server.unregisterMBean(new ObjectName(name)); } public static void unregisterChannel(JChannel c, MBeanServer server, String clusterName) throws Exception { ProtocolStack stack = c.getProtocolStack(); Vector<Protocol> protocols = stack.getProtocols(); for (Protocol p : protocols) { if (p.getClass().isAnnotationPresent(MBean.class)) { try { unregister(p, server, getProtocolRegistrationName(clusterName, "jgroups", p)); } catch (MBeanRegistrationException e) { if (log.isWarnEnabled()) { log.warn("MBean unregistration failed " + e); } } } } unregister(c, server, getChannelRegistrationName(clusterName)); } public static void registerChannelFactory(JChannelFactory factory, MBeanServer server, String name) throws Exception { register(factory, server, name); } public static void unRegisterChannelFactory(JChannelFactory factory, MBeanServer server, String name) throws Exception { unregister(factory, server, name); } public static void register(Object obj, MBeanServer server, String name) throws MBeanRegistrationException, MalformedObjectNameException { internalRegister(obj, server, name); } public static void unregister(Object obj, MBeanServer server, String name) throws MBeanRegistrationException, MalformedObjectNameException { internalUnregister(obj, server, name); } public DynamicMBean asDynamicMBean(JChannel ch) { return new ResourceDMBean(ch); } public DynamicMBean asDynamicMBean(Protocol p) { return new ResourceDMBean(p); } private static void internalRegister(Object obj, MBeanServer server, String name) throws MalformedObjectNameException, MBeanRegistrationException { if (obj == null) throw new IllegalArgumentException("Object being registered cannot be null"); if (server == null) throw new IllegalArgumentException("MBean server used for registeration cannot be null"); try { ObjectName objName = getObjectName(obj, name); ResourceDMBean res = new ResourceDMBean(obj); server.registerMBean(res, objName); if (log.isDebugEnabled()) { log.debug("register MBean " + objName + " completed"); } } catch (InstanceAlreadyExistsException e) { if (log.isErrorEnabled()) { log.error("register MBean failed " + e.getMessage()); } throw new MBeanRegistrationException(e, "The @MBean objectName is not unique"); } catch (NotCompliantMBeanException e) { if (log.isErrorEnabled()) { log.error("register MBean failed " + e.getMessage()); } throw new MBeanRegistrationException(e); } } private static void internalUnregister(Object obj, MBeanServer server, String name) throws MBeanRegistrationException { try { if (name != null && name.length() > 0) { server.unregisterMBean(new ObjectName(name)); } else if (obj != null) { server.unregisterMBean(getObjectName(obj, null)); } else { throw new MBeanRegistrationException(null, "Cannot find MBean name from @MBean or passed in value"); } if (log.isDebugEnabled()) { log.debug("unregister MBean" + name + " completed"); } } catch (InstanceNotFoundException infe) { if (log.isErrorEnabled()) { log.error("unregister MBean failed " + infe.getMessage()); } throw new MBeanRegistrationException(infe); } catch (MalformedObjectNameException e) { if (log.isErrorEnabled()) { log.error("unregister MBean failed " + e.getMessage()); } throw new MBeanRegistrationException(e); } } private static ObjectName getObjectName(Object obj, String name) throws MalformedObjectNameException { MBean resource = obj.getClass().getAnnotation(MBean.class); if (name != null && name.length() > 0) { return new ObjectName(name); } else if (resource.objectName() != null && resource.objectName().length() > 0) { return new ObjectName(resource.objectName()); } else { throw new MalformedObjectNameException("Instance " + obj + " of a class " + obj.getClass() + " does not have a valid object name"); } } /** * Unregisters object_name and everything under it * * @param object_name */ public static void unregister(MBeanServer server, String object_name) throws Exception { Set<ObjectName> mbeans = server.queryNames(new ObjectName(object_name), null); if (mbeans != null) { for (Iterator<ObjectName> it = mbeans.iterator(); it.hasNext();) { server.unregisterMBean(it.next()); } } } private static String getChannelRegistrationName(JChannel c, String domain, String clusterName) { return domain + ":type=channel,cluster=" + clusterName; } private static String getProtocolRegistrationName(String clusterName, String domain, Protocol p) { return domain + ":type=protocol,cluster=" + clusterName + ",protocol=" + p.getName(); } private static String getChannelRegistrationName(String clusterName) { return "jgroups:type=channel,cluster=" + clusterName; } }
package org.oucs.gaboto.entities; import java.lang.reflect.Method; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.oucs.gaboto.entities.pool.EntityExistsCallback; import org.oucs.gaboto.entities.pool.GabotoEntityPool; import org.oucs.gaboto.entities.pool.PassiveEntitiesRequest; import org.oucs.gaboto.entities.time.GabotoTimeBasedEntity; import org.oucs.gaboto.entities.utils.GabotoEntityUtils; import org.oucs.gaboto.entities.utils.SimpleLiteralProperty; import org.oucs.gaboto.entities.utils.SimpleURIProperty; import org.oucs.gaboto.exceptions.GabotoRuntimeException; import org.oucs.gaboto.exceptions.IllegalAnnotationException; import org.oucs.gaboto.model.Gaboto; import org.oucs.gaboto.model.GabotoSnapshot; import org.oucs.gaboto.reflection.RDFContainer; import org.oucs.gaboto.reflection.RDFContainerTripleGeneratorImpl; import org.oucs.gaboto.timedim.TimeSpan; import org.oucs.gaboto.vocabulary.OxPointsVocab; import com.hp.hpl.jena.graph.Graph; import com.hp.hpl.jena.graph.Node; import com.hp.hpl.jena.graph.Triple; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.Resource; abstract public class GabotoEntity implements RDFContainer { private static Logger logger = Logger.getLogger(GabotoEntity.class.getName()); /** * Stores the timespan in which this entity is valid. If it is null, then the entity is valid indefinitely. */ private TimeSpan timespan = TimeSpan.EXISTENCE; /** * stores the entity's URI. */ private String uri; /** * Stores the pool, this entity was created from */ private GabotoEntityPool createFromPool = null; /** * Tells whether or not passive entities were loaded */ private boolean passiveEntitiesLoaded = false; protected Map<String, Resource> missingEntityReferences = new HashMap<String, Resource>(); protected Map<String, Collection<EntityExistsCallback>> missingEntityReferenceCallbacks = new HashMap<String, Collection<EntityExistsCallback>>(); /** * Instantiate the GabotoEntity. * * <p> * OxPointsEntities should always use the default constructor and provide * methods for all their fields in order for Gaboto to be able to automatically * load and serialize them. * </p> */ public GabotoEntity(){ } final static public <T extends GabotoEntity> T createNew(Gaboto gaboto, T newEntity){ newEntity.setUri(gaboto.generateID()); return newEntity; } final public void setCreatedFromPool(GabotoEntityPool pool){ this.createFromPool = pool; } final protected void addMissingReference(Resource res, EntityExistsCallback callback){ missingEntityReferences.put(res.getURI(), res); if(! missingEntityReferenceCallbacks.containsKey(res.getURI())){ missingEntityReferenceCallbacks.put(res.getURI(), new HashSet<EntityExistsCallback>()); } missingEntityReferenceCallbacks.get(res.getURI()).add(callback); } final protected void removeMissingReference(String uriToRemove){ missingEntityReferences.remove(uriToRemove); //missingEntityReferenceCallbacks.remove(uri); } /** * Returns the entity's URI. * * @see #setUri(String) * @return the entity's URI. */ final public String getUri() { return uri; } /** * Sets the entity's URI. * * @see #getUri() * @param uri this entity's new URI. */ final public void setUri(String uri) { this.uri = uri; } /** * Stores the lifespan of this GabotoEntity. * * <p> * The lifespan does not necessary correspond to when the entity came into * being and was destroyed. It is the span in which the entity is valid in the * form at it is represented by this object. * </p> * * @see #getTimeSpan() * * @param ts The lifespan */ final public void setTimeSpan(TimeSpan ts){ if(ts == null) this.timespan = TimeSpan.EXISTENCE; else this.timespan = ts.canonicalize(); } /** * Returns the entity's lifespan. * * @see #setTimeSpan(TimeSpan) * @return Returns the entity's lifespan. */ final public TimeSpan getTimeSpan(){ return this.timespan; } /** * Every entity has a defined type. * * @see OxPointsVocab * * @return The entity's type (ontology class). */ abstract public String getType(); /** * @param propertyURI unused, overridden */ protected List<Method> getIndirectMethodsForProperty(String propertyURI){ return null; } /** * Tells whether direct references have been resolved for this entity. * * @return true if direct references have been resolved. */ public boolean isDirectReferencesResolved() { return missingEntityReferences.isEmpty(); } /** * Tries to resolve the direct references from the entity's pool (the pool it was last added to). */ public void resolveDirectReferences(){ resolveDirectReferences(createFromPool); } /** * Tries to resolve the entity's direct references from the passed pool. * @param pool The pool to load the direct references from. */ public void resolveDirectReferences(GabotoEntityPool pool) { if(isDirectReferencesResolved()) return; if(pool == null) throw new IllegalStateException("The GabotoEntity was not provided with a pool object to resolve its references from."); // add missing references pool.addMissingReferencesForEntity(missingEntityReferences.values(), missingEntityReferenceCallbacks); } /** * Tells the entity that all passive properties were loaded. */ public void setPassiveEntitiesLoaded(){ this.passiveEntitiesLoaded = true; } /** * * @return true if passive entities were loaded. */ public boolean isPassiveEntitiesLoaded(){ return passiveEntitiesLoaded; } /** * Tries to load passive entities from the entity's pool. */ public void loadPassiveEntities(){ loadPassiveEntities(createFromPool); } /** * Tries to load passive entities from the passed pool. * @param pool The pool to load the passive entities from. */ public void loadPassiveEntities(GabotoEntityPool pool){ if(passiveEntitiesLoaded) return; if(pool == null) throw new IllegalStateException("The GabotoEntity was not provided with a pool object to load the passive properties from."); pool.addPassiveEntitiesFor(this); } /** * Is called by subclasses to ask for passive entities that they claim belong to them. * * @return null */ public Collection<PassiveEntitiesRequest> getPassiveEntitiesRequest(){ return null; } /** * The entity adds itself to the supplied Jena Model. * * @param model the JenaModel */ public void addToModel(Model model) { Graph g = model.getGraph(); List<Triple> triples = getTriplesFor(); for(Triple t : triples) g.add(t); } /** * Returns the value of a property via reflection (searching in direct and indirect properties, but not in passive properties) * * @param prop The property * @return The property's value (or null). */ public Object getPropertyValue(Property prop){ return getPropertyValue(prop.getURI(), false, true); } /** * Returns the value of a property via reflection * * @param prop The property * @param searchInPassiveProperties Search in passive properties * @param searchInIndirectProperties Search in indirect properties */ public Object getPropertyValue(Property prop, boolean searchInPassiveProperties, boolean searchInIndirectProperties){ return getPropertyValue(prop.getURI(), searchInPassiveProperties, searchInIndirectProperties); } /** * Returns the value of a property via reflection (searching in direct and indirect properties, but not in passive properties) * * @param propURI The property's URI */ public Object getPropertyValue(String propURI){ return getPropertyValue(propURI, false, true); } /** * Returns the value of a property. * * @param propURI The property's URI. * @param searchInPassiveProperties True to search in passive properties. * @param searchInIndirectProperties True to search in indirect properties. */ @SuppressWarnings("unchecked") public Object getPropertyValue(String propURI, boolean searchInPassiveProperties, boolean searchInIndirectProperties){ Method directMethod = GabotoEntityUtils.getGetMethodFor(this, propURI); if(directMethod != null){ try { Object value = directMethod.invoke(this, (Object[])null); if(value != null) return value; } catch (Exception e) { throw new GabotoRuntimeException(e); } } // search in passive if(searchInPassiveProperties){ Object value = getPassivePropertyValue(propURI); if(value != null) return value; } // search in indirect properties? if(! searchInIndirectProperties) return null; // look for indirect Method List<Method> indirectMethods = getIndirectMethodsForProperty(propURI); if(indirectMethods == null) return null; for(Method indirectMethod : indirectMethods){ try { Object obj = indirectMethod.invoke(this, (Object[])null); if(obj != null){ if(! (obj instanceof GabotoEntity) && !(obj instanceof Collection)) throw new IllegalAnnotationException(getClass()); if(obj instanceof GabotoEntity){ // cast GabotoEntity entity = (GabotoEntity) obj; // try to find answer at entity Object value = entity.getPropertyValue(propURI, searchInPassiveProperties, searchInIndirectProperties); if(value != null) return value; } else if(obj instanceof Collection){ // try to cast try{ Collection<GabotoEntity> entityCollection = (Collection<GabotoEntity>) obj; for(GabotoEntity entityInCollection : entityCollection){ // try to find answer at entity Object value = entityInCollection.getPropertyValue(propURI, searchInPassiveProperties, searchInIndirectProperties); if(null != value) return value; } } catch(ClassCastException e){ IllegalAnnotationException iae = new IllegalAnnotationException(getClass()); iae.initCause(e); throw iae; } } } } catch (Exception e) { throw new GabotoRuntimeException(e); } } return null; } /** * Returns the value of a passive property. * @param prop The passive property. * @return The property's value */ public Object getPassivePropertyValue(Property prop){ return getPassivePropertyValue(prop.getURI()); } /** * Returns the value of a passive property. * @param propURI The URI of the passive property. * @return The property's value */ public Object getPassivePropertyValue(String propURI){ Method m = GabotoEntityUtils.getPassiveGetMethodFor(this.getClass(), propURI); if(m != null){ try { //System.err.println("For class " + this.getClass() + // " found passive method " + m.getName() + ":" + m.invoke(this, (Object[])null)); return m.invoke(this, (Object[])null); } catch (Exception e) { throw new GabotoRuntimeException(e); } } return null; } /** * Creates a map with all properties: direct (including static and unstored), indirect and passive */ public Map<String, Object> getAllProperties(){ Map<String, Object> properties = getAllDirectProperties(); properties.putAll(getAllPassiveProperties()); properties.putAll(getAllIndirectProperties()); return properties; } /** * Creates a map with property value pairs for all direct properties (including static and unstored). * @return a map with property value pairs */ public Map<String, Object> getAllDirectProperties(){ Map<String, Object> properties = new HashMap<String, Object>(); for(String prop : GabotoEntityUtils.getAllDirectProperties(this.getClass())){ properties.put(prop, getPropertyValue(prop)); } return properties; } /** * Creates a map with property value pairs for all passive properties. * @return a map with property value pairs. */ public Map<String, Object> getAllPassiveProperties(){ Map<String, Object> properties = new HashMap<String, Object>(); for(String prop : GabotoEntityUtils.getAllPassiveProperties(this.getClass())){ Object value = getPassivePropertyValue(prop); properties.put(prop, value); //System.err.println("Adding " + prop + " : (" + value.getClass() + ") " + value); } return properties; } /** * Creates a map with property value pairs for all indirect properties. * @return a map with property value pairs. */ public Map<String, Object> getAllIndirectProperties(){ Map<String, Object> properties = new HashMap<String, Object>(); for(String prop : GabotoEntityUtils.getAllIndirectProperties(this.getClass())){ properties.put(prop, getPropertyValue(prop, false, true)); } return properties; } /** * Creates the java representation from an GabotoSnapshot and a resource object.. * * <p> * The method uses reflection mechanisms to find appropriate setter methods. * </p> * * @param res An RDF Resource. * @param snapshot The GabotoSnapshot containing all the data. * @param pool The entity pool that is currently created (used for references to other entities). * */ public void loadFromSnapshot(Resource res, GabotoSnapshot snapshot, GabotoEntityPool pool) { // set uri this.setUri(res.getURI()); // log logger.debug("Load entity " + this.getUri() + " from Snapshot."); // try to set time span this.setTimeSpan(snapshot.getTimeSpanForEntity(res)); // load entity //RDFContainerLoaderImpl.getInstance().loadFromSnapshot(this, res, snapshot, pool); } public List<Triple> getTriplesFor() throws IllegalAnnotationException{ return getTriplesFor(true); } public List<Triple> getTriplesFor(boolean includeType) throws IllegalAnnotationException{ // if no uri if(this.getUri() == null) throw new IllegalArgumentException("Entities need to have a defined uri"); List<Triple> triples = RDFContainerTripleGeneratorImpl.getInstance().getTriplesFor(this, Node.createURI(getUri()), includeType); return triples; } @Override public String toString(){ TimeSpan ts = getTimeSpan(); if(ts == null) ts = TimeSpan.EXISTENCE; return getUri() + " " + this.getClass().getSimpleName() + " : " + ts + ""; } @Override public boolean equals(Object obj) { if(! (obj instanceof GabotoEntity)) return false; GabotoEntity entity = (GabotoEntity) obj; if(getTimeSpan() != null && getUri() != null && entity.getTimeSpan() != null && entity.getUri() != null) return getTimeSpan().equals(entity.getTimeSpan()) && getUri().equals(entity.getUri()) && getClass().equals(entity.getClass()); if(getUri() != null && entity.getUri() != null) return getUri().equals(entity.getUri()) && getClass().equals(entity.getClass()); return super.equals(obj); } @Override public int hashCode(){ return toString().hashCode(); } }
// $Id: TCPGOSSIP.java,v 1.28 2008/02/29 08:22:13 belaban Exp $ package org.jgroups.protocols; import org.jgroups.Address; import org.jgroups.Event; import org.jgroups.Message; import org.jgroups.stack.GossipClient; import org.jgroups.stack.IpAddress; import java.util.*; import java.net.UnknownHostException; /** * The TCPGOSSIP protocol layer retrieves the initial membership (used by the GMS when started * by sending event FIND_INITIAL_MBRS down the stack). * We do this by contacting one or more GossipRouters, which must be running at well-known * addresses:ports. The responses should allow us to determine the coordinator whom we have to * contact, e.g. in case we want to join the group. When we are a server (after having * received the BECOME_SERVER event), we'll respond to TCPGOSSIP requests with a TCPGOSSIP * response.<p> The FIND_INITIAL_MBRS event will eventually be answered with a * FIND_INITIAL_MBRS_OK event up the stack. * * @author Bela Ban */ public class TCPGOSSIP extends Discovery { Vector initial_hosts=null; // (list of IpAddresses) hosts to be contacted for the initial membership GossipClient gossip_client=null; // accesses the GossipRouter(s) to find initial mbrship // we need to refresh the registration with the GossipRouter(s) periodically, // so that our entries are not purged from the cache long gossip_refresh_rate=20000; int sock_conn_timeout=1000; // max time in millis for a socket creation final static String name="TCPGOSSIP"; public String getName() { return name; } public boolean setProperties(Properties props) { String str; str=props.getProperty("gossip_refresh_rate"); // wait for at most n members if(str != null) { gossip_refresh_rate=Integer.parseInt(str); props.remove("gossip_refresh_rate"); } str=props.getProperty("sock_conn_timeout"); // wait for at most n members if(str != null) { sock_conn_timeout=Integer.parseInt(str); props.remove("sock_conn_timeout"); } str=props.getProperty("initial_hosts"); if(str != null) { props.remove("initial_hosts"); try { initial_hosts=createInitialHosts(str); } catch(UnknownHostException ex) { if(log.isErrorEnabled()) log.error("failed creating initial hosts", ex); return false; } } if(initial_hosts == null || initial_hosts.isEmpty()) { if(log.isErrorEnabled()) log.error("initial_hosts must contain the address of at least one GossipRouter"); return false; } if(timeout <= sock_conn_timeout) { log.warn("timeout should be greater than sock_conn_timeout"); } return super.setProperties(props); } public void start() throws Exception { super.start(); if(gossip_client == null) gossip_client=new GossipClient(initial_hosts, gossip_refresh_rate, sock_conn_timeout); } public void stop() { super.stop(); if(gossip_client != null) { gossip_client.stop(); gossip_client=null; } } public void destroy() { if(gossip_client != null) { gossip_client.destroy(); gossip_client=null; } } public void handleConnect() { if(group_addr == null || local_addr == null) { if(log.isErrorEnabled()) log.error("group_addr or local_addr is null, cannot register with GossipRouter(s)"); } else { if(log.isTraceEnabled()) log.trace("registering " + local_addr + " under " + group_addr + " with GossipRouter"); gossip_client.register(group_addr, local_addr); } } public void sendGetMembersRequest(String cluster_name) { Message msg, copy; PingHeader hdr; List tmp_mbrs; Address mbr_addr; if(group_addr == null) { if(log.isErrorEnabled()) log.error("[FIND_INITIAL_MBRS]: group_addr is null, cannot get mbrship"); return; } if(log.isTraceEnabled()) log.trace("fetching members from GossipRouter(s)"); tmp_mbrs=gossip_client.getMembers(group_addr); if(tmp_mbrs == null || tmp_mbrs.isEmpty()) { if(log.isErrorEnabled()) log.error("[FIND_INITIAL_MBRS]: gossip client found no members"); return; } if(log.isTraceEnabled()) log.trace("consolidated mbrs from GossipRouter(s) are " + tmp_mbrs); // 1. 'Mcast' GET_MBRS_REQ message hdr=new PingHeader(PingHeader.GET_MBRS_REQ, cluster_name); msg=new Message(null); msg.setFlag(Message.OOB); msg.putHeader(name, hdr); for(Iterator it=tmp_mbrs.iterator(); it.hasNext();) { mbr_addr=(Address)it.next(); copy=msg.copy(); copy.setDest(mbr_addr); if(log.isTraceEnabled()) log.trace("[FIND_INITIAL_MBRS] sending PING request to " + copy.getDest()); down_prot.down(new Event(Event.MSG, copy)); } } /** * Input is "daddy[8880],sindhu[8880],camille[5555]. Return list of IpAddresses */ private Vector<Address> createInitialHosts(String l) throws UnknownHostException { Vector<Address> tmp=new Vector<Address>(); String host; int port; IpAddress addr; StringTokenizer tok=new StringTokenizer(l, ","); String t; while(tok.hasMoreTokens()) { try { t=tok.nextToken(); host=t.substring(0, t.indexOf('[')); port=Integer.parseInt(t.substring(t.indexOf('[') + 1, t.indexOf(']'))); addr=new IpAddress(host, port); tmp.addElement(addr); } catch(NumberFormatException e) { if(log.isErrorEnabled()) log.error("exeption is " + e); } } return tmp; } }
package org.lff.plugin.dupfinder; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.roots.OrderRootType; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.VerticalFlowLayout; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.JBSplitter; import com.intellij.ui.ScrollPaneFactory; import com.intellij.ui.components.JBLabel; import com.intellij.ui.components.JBList; import com.intellij.ui.components.JBTextField; import com.intellij.ui.table.JBTable; import com.intellij.util.Processor; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.UIUtil; import org.jdesktop.swingx.HorizontalLayout; import org.jetbrains.jps.model.java.JavaSourceRootType; import org.lff.plugin.dupfinder.vo.DuplicateClass; import org.lff.plugin.dupfinder.vo.SourceVO; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.logging.Logger; public class Dialog extends DialogWrapper implements ProgressListener { private static final Logger logger = Logger.getLogger(Dialog.class.getName()); private final Project project; private Finder finder; private ProjectRootManager rootManager = null; public Dialog(Project project, ProjectRootManager rootManager) { super(false); this.rootManager = rootManager; this.project = project; listModal = new ClassListModel(); tableModel = new DuplicatesTableModel(); } public void init() { super.init(); setTitle("Find Duplicate classes in classpath"); getWindow().addWindowListener(new WindowListener() { @Override public void windowOpened(WindowEvent e) { getWindow().setCursor(new Cursor(Cursor.WAIT_CURSOR)); javax.swing.SwingUtilities.invokeLater(() -> process()); } @Override public void windowClosing(WindowEvent e) { } @Override public void windowClosed(WindowEvent e) { fireStop(); } @Override public void windowIconified(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { } @Override public void windowActivated(WindowEvent e) { } @Override public void windowDeactivated(WindowEvent e) { } }); } protected Action[] createActions() { return new Action[]{this.getOKAction()}; } private JProgressBar bar; private JBLabel label; private JBList myList; private ClassListModel listModal; private DuplicatesTableModel tableModel; private JBTextField filter; private JButton btnOK; private JButton btnClear; private JBLabel filterLabel; protected JComponent createCenterPanel() { final JPanel panel = new JPanel(new BorderLayout(UIUtil.DEFAULT_HGAP, UIUtil.DEFAULT_VGAP)); myList = new JBList(listModal); JPanel north = new JPanel(new VerticalFlowLayout()); bar = new JProgressBar(0, 100); final JBSplitter mainPanel = new JBSplitter(true, 2f / 5); mainPanel.setFirstComponent(ScrollPaneFactory.createScrollPane(myList)); mainPanel.setSecondComponent(ScrollPaneFactory.createScrollPane(new JBTable(tableModel))); myList.addMouseListener(new ClassMouseListener(this.listModal, this.tableModel)); north.add(label = new JBLabel("Duplicate classes found")); north.add(bar); JPanel panelSearch = new JPanel(new HorizontalLayout(12)); filter = new JBTextField("", 32); btnOK = new JButton("Filter"); btnClear = new JButton("Clear"); panelSearch.add(filter); panelSearch.add(btnOK); panelSearch.add(btnClear); filterLabel = new JBLabel("0 classes filtered."); panelSearch.add(filterLabel); btnOK.setEnabled(false); btnClear.setEnabled(false); north.add(panelSearch); panel.add(north, BorderLayout.NORTH); panel.add(mainPanel, BorderLayout.CENTER); panel.setPreferredSize(new Dimension(800, 600)); btnOK.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { applyFilter(); } }); btnClear.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { clearFilter(); } }); return panel; } public void process() { java.util.List<VirtualFile> result = (rootManager.getModuleSourceRoots(ContainerUtil.set(JavaSourceRootType.SOURCE))); List<SourceVO> dependents = new ArrayList<>(); for (VirtualFile file : result) { logger.info("Module Root " + file); Module module = ModuleUtil.findModuleForFile(file, project); ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module); ModuleRootManager.getInstance(module).orderEntries().forEachLibrary(new Processor<Library>() { @Override public boolean process(Library library) { String libraryName = library.getName() == null ? "<JAR>" : library.getName(); String[] urls = library.getRootProvider().getUrls(OrderRootType.CLASSES); for (String url : urls) { dependents.add(new SourceVO(libraryName, url)); } return true; } }); } label.setText("Total " + dependents.size() + " found."); process(dependents); } private void setFinder(Finder finder) { this.finder = finder; } private void fireStop() { if (this.finder != null) { this.finder.stop(); } } private void process(List<SourceVO> dependents) { new Thread(()-> { Finder finder = new Finder(); setFinder(finder); List<DuplicateClass> clz = finder.process(this, dependents); Collections.sort(clz); SwingUtilities.invokeLater(() -> { this.listModal.clear(); clz.forEach(c -> { this.listModal.add(c.getFullName()); tableModel.setDependents(c.getFullName(), c.getDependents()); }); getWindow().setCursor(Cursor.getDefaultCursor()); btnOK.setEnabled(true); btnClear.setEnabled(true); this.finder = null; }); }).start(); } @Override public void onProgress(int percent, String message) { SwingUtilities.invokeLater(() -> { this.bar.setValue(percent); this.label.setText(message); }); } private void applyFilter() { String filter = this.filter.getText(); if (filter.equals("") || filter.trim().equals("")) { Messages.showMessageDialog(project, "Filter is empty", "Error", Messages.getErrorIcon()); } this.listModal.saveList(); List<String> result = new ArrayList<>(); for (String clz : this.listModal.getList()) { if (clz.contains(filter)) { result.add(clz); } } this.listModal.clear(); this.listModal.addAll(result); filterLabel.setText(String.valueOf(result.size() + " classes filtered.")); } private void clearFilter() { this.filter.setText(""); this.listModal.clear(); this.listModal.restore(); filterLabel.setText("0 classes filtered."); } }
package org.psjava.ds.graph; import org.psjava.ds.Collection; import org.psjava.javautil.DataFilter; import org.psjava.javautil.FilteredIterable; public class EdgeFilteredGraph { // TODO introduce SubGraph and replace this public static <V, E> Graph<V, E> wrap(final Graph<V, E> original, final DataFilter<E> filter) { return new Graph<V, E>() { @Override public Collection<V> getVertices() { return original.getVertices(); } @Override public Iterable<E> getEdges() { return FilteredIterable.create(original.getEdges(), filter); } @Override public String toString() { return GraphToString.toString(this); } }; } }
/* * $Id: ConfigManager.java,v 1.12 2003-11-14 02:08:36 tlipkis Exp $ */ package org.lockss.daemon; import java.util.*; import java.io.*; import java.net.*; import java.text.*; import org.mortbay.tools.*; import org.lockss.app.*; import org.lockss.util.*; import org.lockss.servlet.*; import org.lockss.proxy.*; import org.lockss.hasher.*; import org.lockss.protocol.*; import org.lockss.repository.*; import org.lockss.state.*; /** ConfigManager loads and periodically reloads the LOCKSS configuration * parameters, and provides services for updating locally changeable * configuration. */ public class ConfigManager implements LockssManager { /** The common prefix string of all LOCKSS configuration parameters. */ public static final String PREFIX = Configuration.PREFIX; static final String MYPREFIX = PREFIX + "config."; static final String PARAM_RELOAD_INTERVAL = MYPREFIX + "reloadInterval"; static final long DEFAULT_RELOAD_INTERVAL = 30 * Constants.MINUTE; static final String PARAM_CONFIG_PATH = MYPREFIX + "configFilePath"; static final String DEFAULT_CONFIG_PATH = "config"; /** Config param written to local config files to indicate file version */ static final String PARAM_CONFIG_FILE_VERSION = MYPREFIX + "fileVersion.<filename>"; /** Temporary param to enable new scheduler */ static final String PARAM_NEW_SCHEDULER = HashService.PREFIX + "use.scheduler"; static final boolean DEFAULT_NEW_SCHEDULER = false; /** Common prefix of platform config params */ static final String PLATFORM = Configuration.PLATFORM; /** Local (routable) IP address, for lcap identity */ public static final String PARAM_PLATFORM_IP_ADDRESS = PLATFORM + "localIPAddress"; public static final String PARAM_PLATFORM_FQDN = PLATFORM + "fqdn"; /** Local subnet set during config */ public static final String PARAM_PLATFORM_ACCESS_SUBNET = PLATFORM + "accesssubnet"; static final String PARAM_PLATFORM_DISK_SPACE_LIST = PLATFORM + "diskSpacePaths"; static final String PARAM_PLATFORM_VERSION = PLATFORM + "version"; static final String PARAM_PLATFORM_ADMIN_EMAIL = PLATFORM + "sysadminemail"; static final String PARAM_PLATFORM_LOG_DIR = PLATFORM + "logdirectory"; static final String PARAM_PLATFORM_LOG_FILE = PLATFORM + "logfile"; static final String PARAM_PLATFORM_SMTP_HOST = PLATFORM + "smtphost"; static final String PARAM_PLATFORM_SMTP_PORT = PLATFORM + "smtpport"; static final String PARAM_PLATFORM_PIDFILE = PLATFORM + "pidfile"; public static String CONFIG_FILE_UI_IP_ACCESS = "ui_ip_access.txt"; public static String CONFIG_FILE_PROXY_IP_ACCESS = "proxy_ip_access.txt"; public static String CONFIG_FILE_AU_CONFIG = "au.txt"; /** array of local cache config file names */ static String cacheConfigFiles[] = { CONFIG_FILE_UI_IP_ACCESS, CONFIG_FILE_PROXY_IP_ACCESS, CONFIG_FILE_AU_CONFIG, }; // MUST pass in explicit log level to avoid recursive call back to // Configuration to get Config log level. (Others should NOT do this.) protected static Logger log = Logger.getLogger("Config", Logger.getInitialDefaultLevel()); protected LockssDaemon theDaemon = null; private List configChangedCallbacks = new ArrayList(); private List configUrlList; // list of urls /** A constant empty Configuration object */ public static Configuration EMPTY_CONFIGURATION = newConfiguration(); static { EMPTY_CONFIGURATION.seal(); } // Current configuration instance. // Start with an empty one to avoid errors in the static accessors. private static Configuration currentConfig = EMPTY_CONFIGURATION; private OneShotSemaphore haveConfig = new OneShotSemaphore(); private HandlerThread handlerThread; // reload handler thread private long reloadInterval = 10 * Constants.MINUTE; public ConfigManager() { this(null); } public ConfigManager(List urls) { if (urls != null) { configUrlList = new ArrayList(urls); } registerConfigurationCallback(Logger.getConfigCallback()); } public void initService(LockssDaemon daemon) throws LockssDaemonException { theDaemon = daemon; } /** Called to start each service in turn, after all services have been * initialized. Service should extend this to perform any startup * necessary. */ public void startService() { startHandler(); } /** Reset to unconfigured state. See LockssTestCase.tearDown(), where * this is called.) */ public void stopService() { currentConfig = newConfiguration(); // this currently runs afoul of Logger, which registers itself once // only, on first use. configChangedCallbacks = new ArrayList(); configUrlList = null; stopHandler(); haveConfig = new OneShotSemaphore(); } private static ConfigManager theMgr; public static ConfigManager makeConfigManager() { theMgr = new ConfigManager(); return theMgr; } public static ConfigManager makeConfigManager(List urls) { theMgr = new ConfigManager(urls); return theMgr; } public static ConfigManager getConfigManager() { return theMgr; } /** Factory to create instance of appropriate class */ public static Configuration newConfiguration() { return new ConfigurationPropTreeImpl(); } /** Return current configuration */ public static Configuration getCurrentConfig() { return currentConfig; } void setCurrentConfig(Configuration newConfig) { if (newConfig == null) { log.warning("attempt to install null Configuration"); } currentConfig = newConfig; } /** Create a Configuration object from a Properties */ public static Configuration fromProperties(Properties props) { Configuration config = new ConfigurationPropTreeImpl(); for (Iterator iter = props.keySet().iterator(); iter.hasNext(); ) { String key = (String)iter.next(); config.put(key, props.getProperty(key)); } config.seal(); return config; } /** Wait until the system is configured. (<i>Ie</i>, until the first * time a configuration has been loaded.) * @param timer limits the time to wait. If null, returns immediately. * @return true if configured, false if timer expired. */ public boolean waitConfig(Deadline timer) { while (!haveConfig.isFull() && !timer.expired()) { try { haveConfig.waitFull(timer); } catch (InterruptedException e) { // no action - check timer } } return haveConfig.isFull(); } /** Wait until the system is configured. (<i>Ie</i>, until the first * time a configuration has been loaded.) */ public boolean waitConfig() { return waitConfig(Deadline.MAX); } void runCallback(Configuration.Callback cb, Configuration newConfig, Configuration oldConfig, Set diffs) { try { cb.configurationChanged(newConfig, oldConfig, diffs); } catch (Exception e) { log.error("callback threw", e); } } void runCallback(Configuration.Callback cb, Configuration newConfig, Configuration oldConfig) { runCallback(cb, newConfig, oldConfig, newConfig.differentKeys(oldConfig)); } void runCallbacks(Configuration newConfig, Configuration oldConfig) { Set diffs = newConfig.differentKeys(oldConfig); // copy the list of callbacks as it could change during the loop. List cblist = new ArrayList(configChangedCallbacks); for (Iterator iter = cblist.iterator(); iter.hasNext();) { try { Configuration.Callback cb = (Configuration.Callback)iter.next(); runCallback(cb, newConfig, oldConfig, diffs); } catch (RuntimeException e) { throw e; } } } /** * Return a new <code>Configuration</code> instance loaded from the * url list */ public Configuration readConfig(List urlList) { if (urlList == null) { return null; } Configuration newConfig = newConfiguration(); // newConfig.setConfigUrls(urlList); boolean gotIt = newConfig.loadList(urlList); return gotIt ? newConfig : null; } boolean updateConfig() { Configuration newConfig = readConfig(configUrlList); return installConfig(newConfig); } boolean installConfig(Configuration newConfig) { if (newConfig == null) { return false; } initCacheConfig(newConfig); List loadedCacheFiles = loadCacheConfigInto(newConfig); copyPlatformParams(newConfig); newConfig.seal(); Configuration oldConfig = currentConfig; if (!oldConfig.isEmpty() && newConfig.equals(oldConfig)) { if (reloadInterval >= 10 * Constants.MINUTE) { log.info("Config unchanged, not updated"); } return false; } setCurrentConfig(newConfig); String cmsg = ((loadedCacheFiles != null) ? "; " + StringUtil.separatedString(loadedCacheFiles, ", ") : ""); log.info("Config updated from " + StringUtil.separatedString(configUrlList, ", ") + cmsg); if (log.isDebug()) { logConfig(newConfig); } runCallbacks(newConfig, oldConfig); haveConfig.fill(); return true; } private void copyPlatformParams(Configuration config) { // hack to make hash use new scheduler without directly setting // org.lockss.manager.HashService, which would break old daemons. if (config.getBoolean(PARAM_NEW_SCHEDULER, DEFAULT_NEW_SCHEDULER)) { config.put("org.lockss.manager.HashService", "org.lockss.hasher.HashSvcSchedImpl"); } String logdir = config.get(PARAM_PLATFORM_LOG_DIR); String logfile = config.get(PARAM_PLATFORM_LOG_FILE); if (logdir != null && logfile != null) { platformOverride(config, FileTarget.PARAM_FILE, new File(logdir, logfile).toString()); } conditionalPlatformOverride(config, PARAM_PLATFORM_IP_ADDRESS, IdentityManager.PARAM_LOCAL_IP); conditionalPlatformOverride(config, PARAM_PLATFORM_SMTP_PORT, MailTarget.PARAM_SMTPPORT); conditionalPlatformOverride(config, PARAM_PLATFORM_SMTP_HOST, MailTarget.PARAM_SMTPHOST); String platformSubnet = config.get(PARAM_PLATFORM_ACCESS_SUBNET); appendPlatformAccess(config, ServletManager.PARAM_IP_INCLUDE, platformSubnet); appendPlatformAccess(config, ProxyManager.PARAM_IP_INCLUDE, platformSubnet); String space = config.get(PARAM_PLATFORM_DISK_SPACE_LIST); if (!StringUtil.isNullString(space)) { String firstSpace = ((String)StringUtil.breakAt(space, ';', 1).elementAt(0)); platformOverride(config, LockssRepositoryImpl.PARAM_CACHE_LOCATION, firstSpace); platformOverride(config, HistoryRepositoryImpl.PARAM_HISTORY_LOCATION, firstSpace); platformOverride(config, IdentityManager.PARAM_IDDB_DIR, new File(firstSpace, "iddb").toString()); } } private void platformOverride(Configuration config, String key, String val) { if (config.get(key) != null) { log.warning("Overriding param: " + key + "= " + config.get(key)); log.warning("with platform-derived value: " + val); } config.put(key, val); } private void conditionalPlatformOverride(Configuration config, String platformKey, String key) { String value = config.get(platformKey); if (value != null) { platformOverride(config, key, value); } } private void appendPlatformAccess(Configuration config, String accessParam, String platformAccess) { if (StringUtil.isNullString(platformAccess)) { return; } String includeIps = config.get(accessParam); if (StringUtil.isNullString(includeIps)) { includeIps = platformAccess; } else { includeIps = platformAccess + ";" + includeIps; } config.put(accessParam, includeIps); } private void logConfig(Configuration config) { SortedSet keys = new TreeSet(); for (Iterator iter = config.keyIterator(); iter.hasNext(); ) { keys.add((String)iter.next()); } for (Iterator iter = keys.iterator(); iter.hasNext(); ) { String key = (String)iter.next(); log.debug(key + " = " + (String)config.get(key)); } } /** * Register a {@link Configuration.Callback}, which will be called * whenever the current configuration has changed. If a configuration is * present when a callback is registered, the callback will be called * immediately. * @param c <code>Configuration.Callback</code> to add. */ public void registerConfigurationCallback(Configuration.Callback c) { log.debug3("registering " + c); if (!configChangedCallbacks.contains(c)) { configChangedCallbacks.add(c); if (!currentConfig.isEmpty()) { runCallback(c, currentConfig, EMPTY_CONFIGURATION); } } } /** * Unregister a <code>Configuration.Callback</code>. * @param c <code>Configuration.Callback</code> to remove. */ public void unregisterConfigurationCallback(Configuration.Callback c) { log.debug3("unregistering " + c); configChangedCallbacks.remove(c); } static void resetForTesting() { cacheConfigInited = false; cacheConfigDir = null; } static boolean cacheConfigInited = false; static String cacheConfigDir = null; boolean isUnitTesting() { return Boolean.getBoolean("org.lockss.unitTesting"); } private void initCacheConfig(Configuration newConfig) { if (cacheConfigInited) return; String dspace = newConfig.get(PARAM_PLATFORM_DISK_SPACE_LIST); String relConfigPath = newConfig.get(PARAM_CONFIG_PATH, DEFAULT_CONFIG_PATH); Vector v = StringUtil.breakAt(dspace, ';'); if (!isUnitTesting() && v.size() == 0) { log.error(PARAM_PLATFORM_DISK_SPACE_LIST + " not specified, not configuring local cache config dir"); return; } for (Iterator iter = v.iterator(); iter.hasNext(); ) { String path = (String)iter.next(); File configDir = new File(path, relConfigPath); if (configDir.exists()) { cacheConfigDir = configDir.toString(); break; } } if (cacheConfigDir == null) { if (v.size() >= 1) { String path = (String)v.get(0); File dir = new File(path, relConfigPath); if (dir.mkdirs()) { cacheConfigDir = dir.toString(); } } } cacheConfigInited = true; } List loadCacheConfigInto(Configuration config) { if (cacheConfigDir == null) { return null; } List res = new ArrayList(); for (int ix = 0; ix < cacheConfigFiles.length; ix++) { File cfile = new File(cacheConfigDir, cacheConfigFiles[ix]); log.debug2("Loading cache config from " + cfile); boolean gotIt = config.loadList(ListUtil.list(cfile.toString()), true); if (gotIt) { res.add(cfile.toString()); } } return res; } /** Read the named local cache config file from the previously determined * cache config directory. * @param cacheConfigFileName filename, no path * @return Configuration with parameters from file */ public Configuration readCacheConfigFile(String cacheConfigFileName) throws IOException { if (cacheConfigDir == null) { log.warning("Attempting to read cache config file: " + cacheConfigFileName + ", but no cache config dir exists"); throw new RuntimeException("No cache config dir"); } File cfile = new File(cacheConfigDir, cacheConfigFileName); log.debug2("Reading cache config file: " + cfile.toString()); InputStream is = new FileInputStream(cfile); Configuration res = newConfiguration(); res.load(is); is.close(); return res; } /** Return the contents of the local AU config file. * @return the Configuration from the AU config file, or an empty config * if no config file found */ public Configuration readAuConfigFile() { Configuration auConfig; try { auConfig = readCacheConfigFile(CONFIG_FILE_AU_CONFIG); } catch (IOException e) { log.warning("Couldn't read AU config file: " + e.getMessage()); auConfig = newConfiguration(); } return auConfig; } /** Write the named local cache config file into the previously determined * cache config directory. * @param props properties to write * @param cacheConfigFileName filename, no path * @param header file header string */ public void writeCacheConfigFile(Properties props, String cacheConfigFileName, String header) throws IOException { writeCacheConfigFile(fromProperties(props), cacheConfigFileName, header); } /** Write the named local cache config file into the previously determined * cache config directory. * @param config Configuration with properties to write * @param cacheConfigFileName filename, no path * @param header file header string */ public void writeCacheConfigFile(Configuration config, String cacheConfigFileName, String header) throws IOException { if (cacheConfigDir == null) { log.warning("Attempting to write cache config file: " + cacheConfigFileName + ", but no cache config dir exists"); throw new RuntimeException("No cache config dir"); } File cfile = new File(cacheConfigDir, cacheConfigFileName); OutputStream os = new FileOutputStream(cfile); // make a copy and add the config file version number, write the copy Configuration tmpConfig = config.copy(); tmpConfig.put(configVersionProp(cacheConfigFileName), "1"); tmpConfig.store(os, header); os.close(); log.debug2("Wrote cache config file: " + cfile.toString()); if (handlerThread != null) { handlerThread.forceReload(); } } /** Return the config version prop key for the named config file */ static String configVersionProp(String cacheConfigFileName) { String noExt = StringUtil.upToFinal(cacheConfigFileName, "."); return StringUtil.replaceString(PARAM_CONFIG_FILE_VERSION, "<filename>", noExt); } /** Replace one AU's config keys in the local AU config file. * @param auProps new properties for AU * @param auPropKey the common initial part of all keys in the AU's config */ public void updateAuConfigFile(Properties auProps, String auPropKey) throws IOException { updateAuConfigFile(fromProperties(auProps), auPropKey); } /** Replace one AU's config keys in the local AU config file. * @param auConfig new config for AU * @param auPropKey the common initial part of all keys in the AU's config */ public void updateAuConfigFile(Configuration auConfig, String auPropKey) throws IOException { Configuration fileConfig; try { fileConfig = readCacheConfigFile(CONFIG_FILE_AU_CONFIG); } catch (FileNotFoundException e) { fileConfig = newConfiguration(); } // first remove all existing values for the AU if (auPropKey != null) { fileConfig.removeConfigTree(auPropKey); } for (Iterator iter = auConfig.keySet().iterator(); iter.hasNext();) { String key = (String)iter.next(); fileConfig.put(key, auConfig.get(key)); } writeCacheConfigFile(fileConfig, CONFIG_FILE_AU_CONFIG, "AU Configuration"); } // static convenience methods /** Static convenience method to get param from current configuration. * Don't accidentally use this on a <code>Configuration</code> instance. */ public static String getParam(String key) { return currentConfig.get(key); } /** Static convenience method to get param from current configuration. * Don't accidentally use this on a <code>Configuration</code> instance. */ public static String getParam(String key, String dfault) { return currentConfig.get(key, dfault); } /** Static convenience method to get param from current configuration. * Don't accidentally use this on a <code>Configuration</code> instance. */ public static boolean getBooleanParam(String key) throws Configuration.InvalidParam { return currentConfig.getBoolean(key); } /** Static convenience method to get param from current configuration. * Don't accidentally use this on a <code>Configuration</code> instance. */ public static boolean getBooleanParam(String key, boolean dfault) { return currentConfig.getBoolean(key, dfault); } /** Static convenience method to get param from current configuration. * Don't accidentally use this on a <code>Configuration</code> instance. */ public static int getIntParam(String key) throws Configuration.InvalidParam { return currentConfig.getInt(key); } /** Static convenience method to get param from current configuration. * Don't accidentally use this on a <code>Configuration</code> instance. */ public static int getIntParam(String key, int dfault) { return currentConfig.getInt(key, dfault); } /** Static convenience method to get param from current configuration. * Don't accidentally use this on a <code>Configuration</code> instance. */ public static long getLongParam(String key) throws Configuration.InvalidParam { return currentConfig.getLong(key); } /** Static convenience method to get param from current configuration. * Don't accidentally use this on a <code>Configuration</code> instance. */ public static long getLongParam(String key, long dfault) { return currentConfig.getLong(key, dfault); } /** Static convenience method to get param from current configuration. * Don't accidentally use this on a <code>Configuration</code> instance. */ public static long getTimeIntervalParam(String key) throws Configuration.InvalidParam { return currentConfig.getTimeInterval(key); } /** Static convenience method to get param from current configuration. * Don't accidentally use this on a <code>Configuration</code> instance. */ public static long getTimeIntervalParam(String key, long dfault) { return currentConfig.getTimeInterval(key, dfault); } /** Static convenience method to get a <code>Configuration</code> * subtree from the current configuration. * Don't accidentally use this on a <code>Configuration</code> instance. */ public static Configuration paramConfigTree(String key) { return currentConfig.getConfigTree(key); } /** Static convenience method to get key iterator from the * current configuration. * Don't accidentally use this on a <code>Configuration</code> instance. */ public static Iterator paramKeyIterator() { return currentConfig.keyIterator(); } /** Static convenience method to get a node iterator from the * current configuration. * Don't accidentally use this on a <code>Configuration</code> instance. */ public static Iterator paramNodeIterator(String key) { return currentConfig.nodeIterator(key); } // Reload thread void startHandler() { if (handlerThread != null) { log.warning("Handler already running; stopping old one first"); stopHandler(); } else { log.info("Starting handler"); } handlerThread = new HandlerThread("ConfigHandler"); handlerThread.start(); } void stopHandler() { if (handlerThread != null) { log.info("Stopping handler"); handlerThread.stopHandler(); handlerThread = null; } else { // log.warning("Attempt to stop handler when it isn't running"); } } // Handler thread, periodicially reloads config private class HandlerThread extends Thread { private long lastReload = 0; private boolean goOn = false; private Deadline nextReload; private HandlerThread(String name) { super(name); } public void run() { Thread.currentThread().setPriority(Thread.NORM_PRIORITY + 1); goOn = true; // repeat every 10ish minutes until first successful load, then // according to org.lockss.parameterReloadInterval, or 30 minutes. while (goOn) { if (updateConfig()) { // true iff loaded config has changed if (!goOn) { break; } lastReload = TimeBase.nowMs(); // stopAndOrStartThings(true); reloadInterval = getTimeIntervalParam(PARAM_RELOAD_INTERVAL, DEFAULT_RELOAD_INTERVAL); } long reloadRange = reloadInterval/4; nextReload = Deadline.inRandomRange(reloadInterval - reloadRange, reloadInterval + reloadRange); log.debug2(nextReload.toString()); if (goOn) { try { nextReload.sleep(); } catch (InterruptedException e) { // just wakeup and check for exit } } } } private void stopHandler() { goOn = false; this.interrupt(); } void forceReload() { if (nextReload != null) { nextReload.expire(); } } } /** * The ConfigManager.Callback interface defines the callback registered * by clients of ConfigManager who want to know when the configuration * has changed. */ public interface xxCallback { /** * Callback used to inform clients that something in the configuration * has changed. It is called after the new config is installed as * current, as well as upon registration (if there is a current * configuration at the time). It is thus safe to rely solely on a * configuration callback to receive configuration information. * @param newConfig the new (just installed) <code>Configuration</code>. * @param oldConfig the previous <code>Configuration</code>, or null * if there was no previous config. * @param changedKeys the set of keys whose value has changed. * @see Configuration#registerConfigurationCallback */ public void configurationChanged(Configuration newConfig, Configuration oldConfig, Set changedKeys); } }
package org.redline_rpm.header; import org.redline_rpm.Util; import java.io.IOException; import java.lang.reflect.Array; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.nio.charset.Charset; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; public abstract class AbstractHeader { public interface Tag { int NULL_ENTRY = 0; int CHAR_ENTRY = 1; int INT8_ENTRY = 2; int INT16_ENTRY = 3; int INT32_ENTRY = 4; int INT64_ENTRY = 5; int STRING_ENTRY = 6; int BIN_ENTRY = 7; int STRING_ARRAY_ENTRY = 8; int I18NSTRING_ENTRY = 9; int ASN1_ENTRY = 10; int OPENPGP_ENTRY = 11; int getCode(); int getType(); String getName(); } protected static final int HEADER_HEADER_SIZE = 16; protected static final int ENTRY_SIZE = 16; protected static final int MAGIC_WORD = 0x8EADE801; protected final Map< Integer, Tag> tags = new HashMap< Integer, Tag>(); protected final Map< Integer, Entry< ?>> entries = new TreeMap< Integer, Entry< ?>>(); protected final Map< Entry< ?>, Integer> pending = new LinkedHashMap< Entry< ?>, Integer>(); protected int startPos; protected int endPos; protected abstract boolean pad(); /** * Reads the entire header contents for this channel and returns the number of entries * found. * @param in the ReadableByteChannel to read * @return the number read * @throws IOException there was an IO error */ public int read( ReadableByteChannel in) throws IOException { ByteBuffer header = Util.fill( in, HEADER_HEADER_SIZE); int magic = header.getInt(); // TODO: Determine if this hack to fix mangled headers for some RPMs is really needed. if ( magic == 0) { header.compact(); Util.fill( in, header); magic = header.getInt(); } Util.check( MAGIC_WORD, magic); header.getInt(); final ByteBuffer index = Util.fill( in, header.getInt() * ENTRY_SIZE); final int total = header.getInt(); final int pad = pad() ? Util.round( total, 7) - total : 0; final ByteBuffer data = Util.fill( in, total + pad); int count = 0; while ( index.remaining() >= ENTRY_SIZE) { readEntry( index.getInt(), index.getInt(), index.getInt(), index.getInt(), data); count++; } return count; } /** * Writes this header section to the provided file at the current position and returns the * required padding. The caller is responsible for adding the padding immediately after * this data. * @param out the WritableByteChannel to output to * @return the number written * @throws IOException there was an IO error */ public int write( WritableByteChannel out) throws IOException { final ByteBuffer header = getHeader(); final ByteBuffer index = getIndex(); final ByteBuffer data = getData( index); data.flip(); int pad = pad() ? Util.round( data.remaining(), 7) - data.remaining() : 0; header.putInt( data.remaining()); Util.empty( out, ( ByteBuffer) header.flip()); Util.empty( out, ( ByteBuffer) index.flip()); Util.empty( out, data); return pad; } public int count() { return entries.size(); } /** * Memory maps the portion of the destination file that will contain the header structure * header and advances the file channels position. The resulting buffer will be prefilled with * the necesssary magic data and the correct index count, but will require an integer value to * be written with the total data section size once data writing is complete. * This method must be invoked before mapping the index or data sections. * @return a buffer containing the header * @throws IOException there was an IO error */ protected ByteBuffer getHeader() throws IOException { ByteBuffer buffer = ByteBuffer.allocate( HEADER_HEADER_SIZE); buffer.putInt( MAGIC_WORD); buffer.putInt( 0); buffer.putInt( count()); return buffer; } /** * Memory maps the portion of the destination file that will contain the index structure * header and advances the file channels position. The resulting buffer will be ready for * writing of the entry indexes. * This method must be invoked before mapping the data section, but after mapping the header. * @return a buffer containing the header * @throws IOException there was an IO error */ protected ByteBuffer getIndex() throws IOException { return ByteBuffer.allocate( count() * ENTRY_SIZE); } /** * Writes the data section of the file, starting at the current position which must be immediately * after the header section. Each entry writes its corresponding index into the provided index buffer * and then writes its data to the file channel. * @param index ByteBuffer of the index * @return the total number of bytes written to the data section of the file. * @throws IOException there was an IO error */ protected ByteBuffer getData( final ByteBuffer index) throws IOException { int offset = 0; final List< ByteBuffer> buffers = new LinkedList< ByteBuffer>(); final Iterator< Integer> i = entries.keySet().iterator(); index.position( 16); final Entry< ?> first = entries.get( i.next()); Entry< ?> entry = null; try { while ( i.hasNext()) { entry = entries.get( i.next()); offset = writeData( buffers, index, entry, offset); } index.position( 0); offset = writeData( buffers, index, first, offset); index.position( index.limit()); } catch ( IllegalArgumentException e) { throw new RuntimeException( "Error while writing '" + entry + "'.", e); } ByteBuffer data = ByteBuffer.allocate( offset); for ( ByteBuffer buffer : buffers) data.put( buffer); return data; } protected int writeData( final Collection< ByteBuffer> buffers, final ByteBuffer index, final Entry< ?> entry, int offset) { final int shift = entry.getOffset( offset) - offset; if ( shift > 0) buffers.add( ByteBuffer.allocate( shift)); offset += shift; final int size = entry.size(); final ByteBuffer buffer = ByteBuffer.allocate( size); entry.index( index, offset); if ( entry.ready()) { entry.write( buffer); buffer.flip(); } else pending.put( entry, offset); buffers.add( buffer); return offset + size; } public void writePending( final FileChannel channel) { for ( Entry< ?> entry : pending.keySet()) { try { ByteBuffer data = ByteBuffer.allocate( entry.size()); entry.write( data); channel.position( Lead.LEAD_SIZE + HEADER_HEADER_SIZE + count() * ENTRY_SIZE + pending.get( entry)); Util.empty( channel, ( ByteBuffer) data.flip()); } catch ( Exception e) { throw new RuntimeException( "Error writing pending entry '" + entry.getTag() + "'.", e); } } } public Map< Entry< ?>, Integer> getPending() { return pending; } public void removeEntry( final Entry< ?> entry) { entries.remove( entry.getTag()); } public Entry< ?> getEntry( final Tag tag) { return getEntry( tag.getCode()); } public Entry< ?> getEntry( final int tag) { return entries.get( tag); } @SuppressWarnings( "unchecked") public Entry< String[]> createEntry( Tag tag, CharSequence value) { Entry< String[]> entry = ( Entry< String[]>) createEntry( tag.getCode(), tag.getType(), 1); entry.setValues( new String[] { value.toString()}); return entry; } @SuppressWarnings( "unchecked") public Entry< int[]> createEntry( Tag tag, int value) { Entry< int[]> entry = ( Entry< int[]>) createEntry( tag.getCode(), tag.getType(), 1); entry.setValues( new int[] { value}); return entry; } @SuppressWarnings( "unchecked") public < T> Entry< T> createEntry( Tag tag, T values) { Entry< T> entry = ( Entry< T>) createEntry( tag.getCode(), tag.getType(), values.getClass().isArray() ? Array.getLength( values) : 1); entry.setValues( values); return entry; } @SuppressWarnings( "unchecked") public < T> Entry< T> createEntry( Tag tag, int type, T values) { Entry< T> entry = ( Entry< T>) createEntry( tag.getCode(), type, values.getClass().isArray() ? Array.getLength( values) : 1); entry.setValues( values); return entry; } @SuppressWarnings( "unchecked") public < T> Entry< T> createEntry( int tag, int type, T values) { Entry< T> entry = ( Entry< T>) createEntry( tag, type, values.getClass().isArray() ? Array.getLength( values) : 1); entry.setValues( values); return entry; } /** * Adds a pending entry to this header. This entry will have the correctly sized buffer allocated, but * will not be written until the caller writes a value and then invokes {@link #writePending} on this * object. * @param tag the tag * @param count the count * @return the entry added */ public Entry< ?> addEntry( Tag tag, int count) { return createEntry( tag.getCode(), tag.getType(), count); } public Entry< ?> readEntry( final int tag, final int type, final int offset, final int count, final ByteBuffer data) { final Entry< ?> entry = createEntry( tag, type, count); final ByteBuffer buffer = data.duplicate(); buffer.position( offset); entry.read( buffer); entry.setOffset( offset); return entry; } public Entry< ?> createEntry( final int tag, final int type, final int count) { final Entry< ?> entry = createEntry( type); entry.setTag( tag); entry.setCount( count); entries.put( tag, entry); return entry; } protected Entry< ?> createEntry( int type) { switch ( type) { case Tag.NULL_ENTRY: return new NullEntry(); case Tag.CHAR_ENTRY: return new CharEntry(); case Tag.INT8_ENTRY: return new Int8Entry(); case Tag.INT16_ENTRY: return new Int16Entry(); case Tag.INT32_ENTRY: return new Int32Entry(); case Tag.INT64_ENTRY: return new Int64Entry(); case Tag.STRING_ENTRY: return new StringEntry(); case Tag.BIN_ENTRY: return new BinEntry(); case Tag.STRING_ARRAY_ENTRY: return new StringArrayEntry(); case Tag.I18NSTRING_ENTRY: return new I18NStringEntry(); default: throw new IllegalStateException( "Unknown entry type '" + type + "'."); } } public int getEndPos() { return endPos; } public void setEndPos(int endPos) { this.endPos = endPos; } public int getStartPos() { return startPos; } public void setStartPos(int startPos) { this.startPos = startPos; } public interface Entry< T> { void setTag( int tag); void setSize( int size); void setCount( int count); void setOffset( int offset); void setValues( T values); T getValues(); int getTag(); int getType(); int getOffset( int offset); int size(); boolean ready(); void read( ByteBuffer buffer); void write( ByteBuffer buffer); void index( ByteBuffer buffer, int position); } public abstract class AbstractEntry< T> implements Entry< T> { protected int size; protected int tag; protected int count; protected int offset; protected T values; public void setTag( Tag tag) { this.tag = tag.getCode(); } public void setTag( int tag) { this.tag = tag; } public void setSize( int size) { this.size = size; } public void setCount( int count) { this.count = count; } public void setOffset( int offset) { this.offset = offset; } public void setValues( T values) { this.values = values; } public T getValues() { return values; } public int getTag() { return tag; } public int getOffset( int offset) { return offset; } /** * Returns true if this entry is ready to write, indicated by the presence of * a set of values. * @return true if ready */ public boolean ready() { return values != null; } /** * Returns the data type of this entry. */ public abstract int getType(); /** * Returns the size this entry will need in the provided data buffer to write * it's contents, corrected for any trailing zeros to fill to a boundary. */ public abstract int size(); /** * Reads this entries value from the provided buffer using the set count. */ public abstract void read( final ByteBuffer buffer); /** * Writes this entries index to the index buffer and its values to the output * channel provided. */ public abstract void write( final ByteBuffer data); /** * Writes the index entry into the provided buffer at the current position. */ public void index( final ByteBuffer index, final int position) { index.putInt( tag).putInt( getType()).putInt( position).putInt( count); } public String toString() { StringBuilder builder = new StringBuilder(); if ( tags.containsKey( tag)) builder.append( tags.get( tag).getName()); else builder.append( super.toString()); builder.append( "[tag=").append( tag); builder.append( ",type=").append( getType()); builder.append( ",count=").append( count); builder.append( ",size=").append( size()); builder.append( ",offset=").append( offset); builder.append( "]"); return builder.toString(); } } class NullEntry extends AbstractEntry< Object> { public int getType() { return 0; } public int size() { return 0; } public void read( final ByteBuffer buffer) {} public void write( final ByteBuffer data) {} } class CharEntry extends AbstractEntry< byte[]> { public int getType() { return Tag.CHAR_ENTRY; } public int size() { return count ; } public void read( final ByteBuffer buffer) { byte[] values = new byte[ count]; for ( int x = 0; x < count; x++) values[ x] = buffer.get(); setValues( values); } public void write( final ByteBuffer data) { for ( byte c : values) data.put( c); } public String toString() { StringBuilder builder = new StringBuilder( super.toString()); for ( byte c : values) builder.append( c); builder.append( "\n\t"); return builder.toString(); } } class Int8Entry extends AbstractEntry< byte[]> { public int getType() { return Tag.INT8_ENTRY; } public int size() { return count; } public void read( final ByteBuffer buffer) { byte[] values = new byte[ count]; for ( int x = 0; x < count; x++) values[ x] = buffer.get(); setValues( values); } public void write( final ByteBuffer data) { for ( byte b : values) data.put( b); } public String toString() { StringBuilder builder = new StringBuilder( super.toString()); builder.append( "\n\t"); for ( byte b : values) builder.append( b).append( ", "); return builder.toString(); } } class Int16Entry extends AbstractEntry< short[]> { public int getOffset( int offset) { return Util.round( offset, 1); } public int getType() { return Tag.INT16_ENTRY; } public int size() { return count * ( Short.SIZE / 8); } public void read( final ByteBuffer buffer) { short[] values = new short[ count]; for ( int x = 0; x < count; x++) values[ x] = buffer.getShort(); setValues( values); } public void write( final ByteBuffer data) { for ( short s : values) data.putShort( s); } public String toString() { StringBuilder builder = new StringBuilder( super.toString()); builder.append( "\n\t"); for ( short s : values) builder.append( s & 0xFFFF).append( ", "); return builder.toString(); } } class Int32Entry extends AbstractEntry< int[]> { public int getOffset( int offset) { return Util.round( offset, 3); } public int getType() { return Tag.INT32_ENTRY; } public int size() { return count * ( Integer.SIZE / 8); } public void read( final ByteBuffer buffer) { int[] values = new int[ count]; for ( int x = 0; x < count; x++) values[ x] = buffer.getInt(); setValues( values); } public void write( final ByteBuffer data) { for ( int i : values) data.putInt( i); } public String toString() { StringBuilder builder = new StringBuilder( super.toString()); builder.append( "\n\t"); for ( int i : values) builder.append( i).append( ", "); return builder.toString(); } } class Int64Entry extends AbstractEntry< long[]> { public int getOffset( int offset) { return Util.round( offset, 7); } public int getType() { return Tag.INT64_ENTRY; } public int size() { return count * ( Long.SIZE / 8); } public void read( final ByteBuffer buffer) { long[] values = new long[ count]; for ( int x = 0; x < count; x++) values[ x] = buffer.getLong(); setValues( values); } public void write( final ByteBuffer data) { for ( long l : values) data.putLong( l); } public String toString() { StringBuilder builder = new StringBuilder( super.toString()); builder.append( "\n\t"); for ( long l : values) builder.append( l).append( ", "); return builder.toString(); } } class StringEntry extends AbstractEntry< String[]> { public int getType() { return Tag.STRING_ENTRY; } public int size() { if ( size != 0) return size; for ( String s : values) size += Charset.forName( "UTF-8").encode( s).remaining() + 1; return size; } public void read( final ByteBuffer buffer) { String[] values = new String[ count]; for ( int x = 0; x < count; x++) { int length = 0; while ( buffer.get( buffer.position() + length) != 0) length++; final ByteBuffer slice = buffer.slice(); buffer.position( buffer.position() + length + 1); slice.limit( length); values[ x] = Charset.forName( "UTF-8").decode( slice).toString(); } setValues( values); } public void write( final ByteBuffer data) { for ( String s : values) data.put( Charset.forName( "UTF-8").encode( s)).put(( byte) 0); } public String toString() { StringBuilder builder = new StringBuilder( super.toString()); if ( values != null) { for ( String s : values) { builder.append( "\n\t"); builder.append( s); } } return builder.toString(); } } class BinEntry extends AbstractEntry< byte[]> { public int getType() { return Tag.BIN_ENTRY; } public int size() { return count; } public void read( final ByteBuffer buffer) { byte[] values = new byte[ count]; buffer.get( values); setValues( values); } public void write( final ByteBuffer data) { data.put( values); } public String toString() { StringBuilder builder = new StringBuilder( super.toString()); if ( values != null) { builder.append( "\n"); Util.dump( values, builder); } return builder.toString(); } } class StringArrayEntry extends StringEntry { public int getType() { return Tag.STRING_ARRAY_ENTRY; } } class I18NStringEntry extends StringEntry { public int getType() { return Tag.I18NSTRING_ENTRY; } } public String toString() { StringBuilder builder = new StringBuilder(); builder.append( "Start Header ( ").append( getClass()).append( ")").append( "\n"); int count = 0; for ( int tag : entries.keySet()) { builder.append( count++).append( ": ").append( entries.get( tag)).append( "\n"); } return builder.toString(); } }
/* * $Id: HtmlTags.java,v 1.4 2008-10-30 08:29:30 tlipkis Exp $ */ package org.lockss.filter.html; import java.util.*; import org.htmlparser.tags.*; /** * Collection of additional simple HtmlParser tags. * @see HtmlFilterInputStream#makeParser() */ public class HtmlTags { /** * An IFRAME tag. Registered with PrototypicalNodeFactory to cause iframe * to be a CompositeTag. See code samples in org.htmlparser.tags. * @see HtmlFilterInputStream#makeParser() */ public static class Iframe extends CompositeTag { /** * The set of names handled by this tag. */ private static final String[] mIds = new String[] {"IFRAME"}; /** * Return the set of names handled by this tag. * @return The names to be matched that create tags of this type. */ public String[] getIds() { return mIds; } } /** * A NOSCRIPT tag. Registered with PrototypicalNodeFactory to cause iframe * to be a CompositeTag. See code samples in org.htmlparser.tags. * @see HtmlFilterInputStream#makeParser() */ public static class Noscript extends CompositeTag { /** * The set of names handled by this tag. */ private static final String[] mIds = new String[] {"NOSCRIPT"}; /** * Return the set of names handled by this tag. * @return The names to be matched that create tags of this type. */ public String[] getIds() { return mIds; } } }
/* * $Id: PluginManager.java,v 1.188 2008-04-18 18:00:34 edwardsb1 Exp $ */ package org.lockss.plugin; import java.io.*; import java.net.*; import java.security.KeyStore; import java.util.*; import java.util.jar.*; import org.apache.commons.collections.*; import org.apache.commons.collections.map.*; import org.apache.commons.collections.map.LRUMap; import org.lockss.app.*; import org.lockss.config.*; import org.lockss.crawler.*; import org.lockss.daemon.*; import org.lockss.plugin.definable.DefinablePlugin; import org.lockss.poller.PollSpec; import org.lockss.state.*; import org.lockss.util.*; /** * Plugin global functionality * * @author TAL * @version 0.0 */ public class PluginManager extends BaseLockssDaemonManager implements ConfigurableManager { public static final String PREFIX = Configuration.PREFIX + "plugin."; public static final String PARAM_AU_TREE = Configuration.PREFIX + "au"; /** The location on the platform to store downloaded plugins once they have been verified for loading. */ static final String PARAM_PLUGIN_LOCATION = Configuration.PLATFORM + "pluginDir"; static final String DEFAULT_PLUGIN_LOCATION = "plugins"; /** A list of plugins to load at startup. */ static final String PARAM_PLUGIN_REGISTRY = PREFIX + "registry"; /** List of plugins not to load, or to remove if already loaded. */ static final String PARAM_PLUGIN_RETRACT = PREFIX + "retract"; static final String PARAM_REMOVE_STOPPED_AUS = PREFIX + "removeStoppedAus"; static final boolean DEFAULT_REMOVE_STOPPED_AUS = true; /** Global list of plugin registry URLs. */ static final String PARAM_PLUGIN_REGISTRIES = PREFIX + "registries"; /** List of user-specified plugin registry URLs. */ public static final String PARAM_USER_PLUGIN_REGISTRIES = PREFIX + "userRegistries"; /** If true, default list of plugin registries from prop server is used * in addition to user-specified registries */ public static final String PARAM_USE_DEFAULT_PLUGIN_REGISTRIES = PREFIX + "useDefaultRegistries"; public static final boolean DEFAULT_USE_DEFAULT_PLUGIN_REGISTRIES = true; /** If true, default plugin signature keystore is used in addition to * user-specified keystore */ public static final String PARAM_USE_DEFAULT_KEYSTORE = PREFIX + "useDefaultKeystore"; public static final boolean DEFAULT_USE_DEFAULT_KEYSTORE = true; /** If true (the default), plugins that appear both in a loadable plugin * registry jar and on the local classpath will be loaded from the * downloaded registry jar. If false such plugins will be loaded from * the local classpath. This is useful in development, where * lockss-plugins.jar is on the classpath. Normal true setting simulates * production behavior, loading plugins from registry. Set false to test * plugins from the local build. */ static final String PARAM_PREFER_LOADABLE_PLUGIN = PREFIX + "preferLoadable"; static final boolean DEFAULT_PREFER_LOADABLE_PLUGIN = true; /** Common prefix of plugin keystore params */ static final String KEYSTORE_PREFIX = PREFIX + "keystore."; /** The location of a Java JKS keystore to use for verifying loadable plugins (optional). */ static final String PARAM_KEYSTORE_LOCATION = KEYSTORE_PREFIX + "location"; static final String DEFAULT_KEYSTORE_LOCATION = "org/lockss/plugin/lockss.keystore"; /** The password to use when opening the loadable plugin verification keystore (optional). */ static final String PARAM_KEYSTORE_PASSWORD = KEYSTORE_PREFIX + "password"; static final String DEFAULT_KEYSTORE_PASSWORD = "password"; /** Common prefix of user-specified plugin keystore params */ static final String USER_KEYSTORE_PREFIX = PREFIX + "userKeystore."; /** The location of a Java JKS keystore to use for verifying loadable plugins (optional). */ public static final String PARAM_USER_KEYSTORE_LOCATION = USER_KEYSTORE_PREFIX + "location"; /** The password to use when opening the loadable plugin verification keystore (optional). */ public static final String PARAM_USER_KEYSTORE_PASSWORD = USER_KEYSTORE_PREFIX + "password"; /** If true, accept plugins signed by otherwise-valid certificates that * are expired or not yet valid. */ static final String PARAM_ACCEPT_EXPIRED_CERTS = PREFIX + "acceptExpiredCertificates"; static final boolean DEFAULT_ACCEPT_EXPIRED_CERTS = true; /** The amount of time to wait when processing loadable plugins. This process delays the start of AUs, so the timeout should not be too long. */ public static final String PARAM_PLUGIN_LOAD_TIMEOUT = PREFIX + "load.timeout"; public static final long DEFAULT_PLUGIN_LOAD_TIMEOUT = Constants.MINUTE; /** The type of plugin we prefer to load, if both are present. Can be either "class" or "xml" (case insensitive) */ public static final String PARAM_PREFERRED_PLUGIN_TYPE = PREFIX + "preferredType"; public static final String DEFAULT_PREFERRED_PLUGIN_TYPE = "xml"; /** Root of TitleSet definitions. */ public static final String PARAM_TITLE_SETS = Configuration.PREFIX + "titleSet"; static final String TITLE_SET_PARAM_CLASS = "class"; static final String TITLE_SET_PARAM_NAME = "name"; static final String TITLE_SET_CLASS_XPATH = "xpath"; static final String TITLE_SET_XPATH_XPATH = "xpath"; static final String TITLE_SET_CLASS_ALL_TITLES = "AllTitles"; static final String TITLE_SET_CLASS_ACTIVE_AUS = "ActiveAus"; static final String TITLE_SET_CLASS_INACTIVE_AUS = "InactiveAus"; // prefix for non-plugin AU params public static final String AU_PARAM_RESERVED = "reserved"; // per AU params known to and processed by daemon, not plugin public static final String AU_PARAM_DISABLED = AU_PARAM_RESERVED + ".disabled"; public static final String AU_PARAM_REPOSITORY = AU_PARAM_RESERVED + ".repository"; public static final String AU_PARAM_DISPLAY_NAME = AU_PARAM_RESERVED + ".displayName"; public static final List NON_USER_SETTABLE_AU_PARAMS = Collections.unmodifiableList(new ArrayList()); static final String CONFIGURABLE_PLUGIN_NAME = DefinablePlugin.class.getName(); private static Logger log = Logger.getLogger("PluginMgr"); private boolean useDefaultPluginRegistries = DEFAULT_USE_DEFAULT_PLUGIN_REGISTRIES; private ConfigManager configMgr; private File pluginDir = null; private AuOrderComparator auComparator = new AuOrderComparator(); private final Attributes.Name LOADABLE_PLUGIN_ATTR = new Attributes.Name("Lockss-Plugin"); // List of names of plugins not to load List retract = null; // maps plugin key(not id) to plugin private Map pluginMap = Collections.synchronizedMap(new HashMap()); // maps auid to AU private Map auMap = Collections.synchronizedMap(new HashMap()); // A set of all aus sorted by title. The UI relies on this behavior. private Set auSet = new TreeSet(auComparator); private List<ArchivalUnit> auList = null; // maps host to collections of AUs. Used to quickly locate candidate AUs // for incoming URLs. Each collection is sorted in AU order (for proxy // manifest index display). private MultiMap hostAus = new HostAuMap(); private static class HostAuMap extends MultiValueMap { HostAuMap() { super(new HashMap(), new org.apache.commons.collections.Factory() { public Object create() { return new ArrayList(3); }}); } } private Set inactiveAuIds = Collections.synchronizedSet(new HashSet()); private List auEventHandlers = new ArrayList(); // Plugin registry processing private Map cuNodeVersionMap = Collections.synchronizedMap(new HashMap()); // Map of plugin key to PluginInfo private Map pluginfoMap = Collections.synchronizedMap(new HashMap()); private RegistryPlugin regPlugin; private KeyStore keystore; private JarValidator jarValidator; private boolean keystoreInited = false; private boolean loadablePluginsReady = false; private boolean preferLoadablePlugin = DEFAULT_PREFER_LOADABLE_PLUGIN; private long registryTimeout = DEFAULT_PLUGIN_LOAD_TIMEOUT; private boolean acceptExpiredCertificates = DEFAULT_ACCEPT_EXPIRED_CERTS; private Map titleMap = null; private List allTitles = null; private List allTitleConfigs = null; private Map titleSetMap; private TreeSet titleSets; private boolean explodedPluginLoaded = false; private Plugin explodedPlugin = null; public static final int PREFER_XML_PLUGIN = 0; public static final int PREFER_CLASS_PLUGIN = 1; public PluginManager() { } /** * start the plugin manager. * @see org.lockss.app.LockssManager#startService() */ public void startService() { super.startService(); configMgr = getDaemon().getConfigManager(); // Initialize the plugin directory. initPluginDir(); PluginStatus.register(getDaemon(), this); } /** * stop the plugin manager * @see org.lockss.app.LockssManager#stopService() */ public void stopService() { // tk - checkpoint if nec. for (Iterator iter = pluginMap.values().iterator(); iter.hasNext(); ) { Plugin plugin = (Plugin)iter.next(); plugin.stopPlugin(); } auEventHandlers = new ArrayList(); PluginStatus.unregister(getDaemon()); super.stopService(); } /** * Start loadable plugins, ensure that they are properly loaded, and * then start all configured AUs. This is called by LockssDaemon * after starting all the managers, and ensures everything happens * in the right order. */ public void startLoadablePlugins() { if (loadablePluginsReady) { return; } Configuration config = CurrentConfig.getCurrentConfig(); log.debug("Initializing loadable plugin registries before starting AUs"); initLoadablePluginRegistries(getPluginRegistryUrls(config)); initPluginRegistry(config); Class explodedPluginClass = null; String name = "org.lockss.plugin.exploded.ExplodedPlugin"; if (!explodedPluginLoaded) { explodedPluginLoaded = true; try { explodedPluginClass = Class.forName(name); } catch (ClassNotFoundException ex) { log.warning("No class " + name); } if (explodedPluginClass != null) { explodedPlugin = loadBuiltinPlugin(explodedPluginClass); } } configureAllPlugins(config); loadablePluginsReady = true; } public void setLoadablePluginsReady(boolean val) { loadablePluginsReady = val; } List getPluginRegistryUrls(Configuration config) { if (useDefaultPluginRegistries) { return ListUtil.append(config.getList(PARAM_PLUGIN_REGISTRIES), config.getList(PARAM_USER_PLUGIN_REGISTRIES)); } else { return config.getList(PARAM_USER_PLUGIN_REGISTRIES); } } public boolean areAusStarted() { return getDaemon().areAusStarted(); } Configuration currentAllPlugs = ConfigManager.EMPTY_CONFIGURATION; public void setConfig(Configuration config, Configuration oldConfig, Configuration.Differences changedKeys) { if (changedKeys.contains(PREFIX)) { registryTimeout = config.getTimeInterval(PARAM_PLUGIN_LOAD_TIMEOUT, DEFAULT_PLUGIN_LOAD_TIMEOUT); preferLoadablePlugin = config.getBoolean(PARAM_PREFER_LOADABLE_PLUGIN, DEFAULT_PREFER_LOADABLE_PLUGIN); acceptExpiredCertificates = config.getBoolean(PARAM_ACCEPT_EXPIRED_CERTS, DEFAULT_ACCEPT_EXPIRED_CERTS); // must set retract before loadablePluginsReady is true as // retrievePlugin() may be called before that if (changedKeys.contains(PARAM_PLUGIN_RETRACT)) { retract = config.getList(PARAM_PLUGIN_RETRACT); } // If the keystore or password has changed, update. if (changedKeys.contains(KEYSTORE_PREFIX) || changedKeys.contains(USER_KEYSTORE_PREFIX)) { keystoreInited = false; initKeystore(configMgr.getCurrentConfig()); } useDefaultPluginRegistries = config.getBoolean(PARAM_USE_DEFAULT_PLUGIN_REGISTRIES, DEFAULT_USE_DEFAULT_PLUGIN_REGISTRIES); } // Process any changed TitleSets if (changedKeys.contains(PARAM_TITLE_SETS)) { configureTitleSets(config); } // Don't load or start other plugins until the daemon is running. if (loadablePluginsReady) { // Process loadable plugin registries. if (changedKeys.contains(PARAM_PLUGIN_REGISTRIES) || changedKeys.contains(PARAM_USER_PLUGIN_REGISTRIES) || changedKeys.contains(PARAM_USE_DEFAULT_PLUGIN_REGISTRIES)) { initLoadablePluginRegistries(getPluginRegistryUrls(config)); } // Process the built-in plugin registry. if (changedKeys.contains(PARAM_PLUGIN_REGISTRY) || changedKeys.contains(PARAM_PLUGIN_RETRACT)) { initPluginRegistry(config); } // Process any changed AU config if (changedKeys.contains(PARAM_AU_TREE)) { configureAllPlugins(config); } } } private void configureAllPlugins(Configuration config) { Configuration allPlugs = config.getConfigTree(PARAM_AU_TREE); if (!allPlugs.equals(currentAllPlugs)) { List plugList = ListUtil.fromIterator(allPlugs.nodeIterator()); plugList = CollectionUtil.randomPermutation(plugList); for (Iterator iter = plugList.iterator(); iter.hasNext(); ) { String pluginKey = (String)iter.next(); log.debug2("Configuring plugin key: " + pluginKey); Configuration pluginConf = allPlugs.getConfigTree(pluginKey); Configuration prevPluginConf = currentAllPlugs.getConfigTree(pluginKey); configurePlugin(pluginKey, pluginConf, prevPluginConf); } currentAllPlugs = allPlugs; } } private void configureTitleSets(Configuration config) { Map map = new HashMap(); TreeSet list = new TreeSet(); Configuration allSets = config.getConfigTree(PARAM_TITLE_SETS); for (Iterator iter = allSets.nodeIterator(); iter.hasNext(); ) { String id = (String)iter.next(); Configuration setDef = allSets.getConfigTree(id); try { TitleSet ts = createTitleSet(setDef); if (ts != null) { if (log.isDebug2()) { log.debug2("Adding TitleSet: " + ts); } list.add(ts); } else { log.warning("Null TitleSet created from: " + setDef); } } catch (RuntimeException e) { log.warning("Error creating TitleSet from: " + setDef, e); } } for (Iterator iter = list.iterator(); iter.hasNext(); ) { TitleSet ts = (TitleSet)iter.next(); map.put(ts.getName(), ts); } titleSets = list; titleSetMap = map; } private TitleSet createTitleSet(Configuration config) { String cls = config.get(TITLE_SET_PARAM_CLASS); String name = config.get(TITLE_SET_PARAM_NAME); try { if (cls.equalsIgnoreCase(TITLE_SET_CLASS_XPATH)) { return new TitleSetXpath(getDaemon(), name, config.get(TITLE_SET_XPATH_XPATH)); } if (cls.equalsIgnoreCase(TITLE_SET_CLASS_ALL_TITLES)) { return new TitleSetAllTitles(getDaemon()); } if (cls.equalsIgnoreCase(TITLE_SET_CLASS_ACTIVE_AUS)) { return new TitleSetActiveAus(getDaemon()); } if (cls.equalsIgnoreCase(TITLE_SET_CLASS_INACTIVE_AUS)) { return new TitleSetInactiveAus(getDaemon()); } } catch (Exception e) { log.error("Error creating TitleSet", e); } return null; } /** Return the TitleSet name to {@link org.lockss.daemon.TitleSet} * mapping */ public Map getTitleSetMap() { return titleSetMap; } /** Return the TitleSets, in display order */ public Collection getTitleSets() { return titleSets; } /** * Convert plugin property key to plugin class name. * @param key the key * @return the plugin name */ public static String pluginNameFromKey(String key) { return StringUtil.replaceString(key, "|", "."); } /** * Convert plugin class name to key suitable for property file. * @param className the class name * @return the plugin key */ public static String pluginKeyFromName(String className) { return StringUtil.replaceString(className, ".", "|"); } /** * Convert plugin id to key suitable for property file. Plugin id is * currently the same as plugin class name, but that may change. * @param id the plugin id * @return String the plugin key */ public static String pluginKeyFromId(String id) { // tk - needs to do real mapping from IDs obtained from all available // plugins. return StringUtil.replaceString(id, ".", "|"); } /** * Return the plugin's key */ public static String getPluginKey(Plugin plugin) { return pluginKeyFromId(plugin.getPluginId()); } /** * Return a unique identifier for an au based on its plugin id and defining * properties. * @param pluginId plugin id (with . not escaped) * @param auDefProps Properties with values for all definitional AU params * @return a unique identifier for an au based on its plugin id and defining * properties. */ public static String generateAuId(String pluginId, Properties auDefProps) { return generateAuId(pluginId, PropUtil.propsToCanonicalEncodedString(auDefProps)); } public static String generateAuId(Plugin plugin, Configuration auConfig) { Properties props = new Properties(); for (Iterator iter = plugin.getAuConfigDescrs().iterator(); iter.hasNext();) { ConfigParamDescr descr = (ConfigParamDescr)iter.next(); if (descr.isDefinitional()) { String key = descr.getKey(); String val = auConfig.get(key); if (val == null) { throw new NullPointerException(key + " is null in: " + auConfig); } props.setProperty(key, val); } } return generateAuId(plugin.getPluginId(), props); } public static String generateAuId(String pluginId, String auKey) { return pluginKeyFromId(pluginId)+"&"+auKey; } public static String auKeyFromAuId(String auid) { int pos = auid.indexOf("&"); if (pos < 0) { throw new IllegalArgumentException("Illegal AuId: " + auid); } return auid.substring(pos + 1); } public static String pluginIdFromAuId(String auid) { int pos = auid.indexOf("&"); if (pos < 0) { throw new IllegalArgumentException("Illegal AuId: " + auid); } return auid.substring(0, pos); } public static String pluginNameFromAuId(String auid) { return pluginNameFromKey(pluginIdFromAuId(auid)); } public static String configKeyFromAuId(String auid) { return StringUtil.replaceFirst(auid, "&", "."); } /** * Return the plugin with the given key. * @param pluginKey the plugin key * @return the plugin or null */ public Plugin getPlugin(String pluginKey) { return (Plugin)pluginMap.get(pluginKey); } private void configurePlugin(String pluginKey, Configuration pluginConf, Configuration oldPluginConf) { List auList = ListUtil.fromIterator(pluginConf.nodeIterator()); auList = CollectionUtil.randomPermutation(auList); nextAU: for (Iterator iter = auList.iterator(); iter.hasNext(); ) { String auKey = (String)iter.next(); String auId = generateAuId(pluginKey, auKey); try { Configuration auConf = pluginConf.getConfigTree(auKey); Configuration oldAuConf = oldPluginConf.getConfigTree(auKey); if (auConf.getBoolean(AU_PARAM_DISABLED, false)) { // tk should actually remove AU? if (log.isDebug2()) log.debug("Not configuring disabled AU id: " + auKey); if (auMap.get(auId) == null) { // don't add to inactive if it's still running inactiveAuIds.add(auId); } } else if (auConf.equals(oldAuConf)) { if (log.isDebug3()) log.debug3("AU already configured, not reconfiguring: " + auKey); } else { log.debug("Configuring AU id: " + auKey); boolean pluginOk = ensurePluginLoaded(pluginKey); if (pluginOk) { Plugin plugin = getPlugin(pluginKey); try { String genAuid = generateAuId(plugin, auConf); if (!auId.equals(genAuid)) { log.warning("Generated AUID " + genAuid + " does not match stored AUID " + auId + ". Proceeding anyway."); } } catch (RuntimeException e) { log.warning("Not configuring probable non-AU. " + "Can't generate AUID from config: " + auConf); continue nextAU; } configureAu(plugin, auConf, auId); inactiveAuIds.remove(generateAuId(pluginKey, auKey)); } else { log.warning("Not configuring AU " + auKey); } } } catch (ArchivalUnit.ConfigurationException e) { log.error("Failed to configure AU " + auKey, e); } catch (Exception e) { log.error("Unexpected exception configuring AU " + auKey, e); } } } void configureAu(Plugin plugin, Configuration auConf, String auId) throws ArchivalUnit.ConfigurationException { Configuration oldConfig = null; try { ArchivalUnit oldAu = (ArchivalUnit)auMap.get(auId); if (oldAu != null) { oldConfig = oldAu.getConfiguration(); if (auConf.equals(oldConfig)) { // Don't bother if the config is the same. (This happens the // first time config is loaded after AU created via UI.) return; } } ArchivalUnit au = plugin.configureAu(auConf, oldAu); if (oldAu != null && oldAu != au) { String msg = "Plugin created new AU: " + au + ", should have reconfigured old AU: " + oldAu; throw new ArchivalUnit.ConfigurationException(msg); } if (!auId.equals(au.getAuId())) { String msg = "Configured AU has unexpected AUID: " + au.getAuId() + ", expected: "+ auId; throw new ArchivalUnit.ConfigurationException(msg); } try { getDaemon().startOrReconfigureAuManagers(au, auConf); } catch (Exception e) { throw new ArchivalUnit.ConfigurationException("Couldn't configure AU managers", e); } if (oldAu != null) { log.debug("Reconfigured AU " + au); signalAuEvent(au, AU_CHANGE_RECONFIG, oldConfig); } else { log.debug("Configured AU " + au); putAuInMap(au); signalAuEvent(au, AU_CHANGE_CREATED, null); } } catch (ArchivalUnit.ConfigurationException e) { throw e; } catch (Exception e) { log.error("Error configuring AU", e); throw new ArchivalUnit.ConfigurationException("Unexpected error creating AU", e); } } ArchivalUnit createAu(Plugin plugin, Configuration auConf) throws ArchivalUnit.ConfigurationException { String auid = null; ArchivalUnit oldAu = null; try { auid = generateAuId(plugin, auConf); oldAu = getAuFromId(auid); } catch (Exception e) { // no action. Bad/missing config value might cause getAuFromId() to // throw. It will be caught soon when creating the AU; for now we // can assume it means the AU doesn't already exist. } if (oldAu != null) { inactiveAuIds.remove(oldAu.getAuId()); throw new ArchivalUnit.ConfigurationException("Cannot create that AU because it already exists: " + oldAu.getName()); } try { ArchivalUnit au = plugin.createAu(auConf); inactiveAuIds.remove(au.getAuId()); log.debug("Created AU " + au); try { getDaemon().startOrReconfigureAuManagers(au, auConf); } catch (Exception e) { log.error("Couldn't start AU processes", e); throw new ArchivalUnit.ConfigurationException("Couldn't start AU processes", e); } putAuInMap(au); signalAuEvent(au, AU_CHANGE_CREATED, null); return au; } catch (ArchivalUnit.ConfigurationException e) { throw e; } catch (Exception e) { log.error("Error creating AU", e); throw new ArchivalUnit.ConfigurationException("Unexpected error creating AU", e); } } /** Stop the AU's activity and remove it, as though it had never been * configured. Does not affect the AU's current repository contents. * @return true if the AU was removed, false if it didn't exist or is * stale. */ public boolean stopAu(ArchivalUnit au) { String auid = au.getAuId(); ArchivalUnit mapAu = (ArchivalUnit)auMap.get(auid); if (mapAu == null) { log.warning("stopAu(" + au.getName() + "), wasn't in map"); return false; } if (mapAu != au) { log.warning("stopAu(" + au.getName() + "), but map contains " + mapAu); return false; } log.debug("Deactivating AU: " + au.getName()); // remove from map first, so no new activity can start (poll messages, // RemoteAPI, etc.) synchronized (auSet) { auMap.remove(auid); auSet.remove(au); auList = null; } delHostAus(au); signalAuEvent(au, AU_CHANGE_DELETED, null); try { Plugin plugin = au.getPlugin(); plugin.stopAu(au); getDaemon().stopAuManagers(au); } catch (Exception e) { log.warning("Unexpected stopping AU", e); // Shouldn't happen, as stopAuManagers() catches errors in // stopService(). Not clear what to do anyway, if some of the // managers don't stop cleanly. } return true; } static final int AU_CHANGE_CREATED = 1; static final int AU_CHANGE_DELETED = 2; static final int AU_CHANGE_RECONFIG = 3; /** * Register a handler for AU events: create, delete, reconfigure. May be * called after this manager's initService() (before startService()). * @param aueh AuEventHandler to add */ public void registerAuEventHandler(AuEventHandler aueh) { log.debug3("registering " + aueh); if (!auEventHandlers.contains(aueh)) { auEventHandlers.add(aueh); } } /** * Unregister an AuEventHandler * @param aueh AuEventHandler to remove */ public void unregisterAuEventHandler(AuEventHandler aueh) { log.debug3("unregistering " + aueh); auEventHandlers.remove(aueh); } void signalAuEvent(ArchivalUnit au, int how, Configuration oldAuConfig) { if (log.isDebug2()) log.debug2("AuEvent " + how + ": " + au); // copy the list of handler as it could change during the loop. List handlers = new ArrayList(auEventHandlers); for (Iterator iter = handlers.iterator(); iter.hasNext();) { try { AuEventHandler hand = (AuEventHandler)iter.next(); switch (how) { case AU_CHANGE_CREATED: hand.auCreated(au); break; case AU_CHANGE_DELETED: hand.auDeleted(au); break; case AU_CHANGE_RECONFIG: hand.auReconfigured(au, oldAuConfig); break; } } catch (Exception e) { log.error("AuEventHandler threw", e); } } } protected void putAuInMap(ArchivalUnit au) { log.debug2("putAuMap(" + au.getAuId() +", " + au); synchronized (auSet) { auMap.put(au.getAuId(), au); auSet.add(au); auList = null; } addHostAus(au); } public ArchivalUnit getAuFromId(String auId) { ArchivalUnit au = (ArchivalUnit)auMap.get(auId); if (log.isDebug3()) log.debug3("getAu(" + auId + ") = " + au); return au; } private void addHostAus(ArchivalUnit au) { try { Collection stems = au.getUrlStems(); if (stems != null) { synchronized (hostAus) { for (Iterator iter = stems.iterator(); iter.hasNext();) { String stem = (String)iter.next(); stem = UrlUtil.getUrlPrefix(UrlUtil.normalizeUrl(stem)); log.debug2("Adding stem: " + stem + ", " + au); hostAus.put(stem, au); } } } } catch (Exception e) { log.warning("addHostAus()", e); } } private void delHostAus(ArchivalUnit au) { try { Collection stems = au.getUrlStems(); if (stems != null) { synchronized (hostAus) { for (Iterator iter = stems.iterator(); iter.hasNext();) { String stem = (String)iter.next(); stem = UrlUtil.getUrlPrefix(UrlUtil.normalizeUrl(stem)); log.debug2("Removing stem: " + stem + ", " + au); hostAus.remove(stem, au); } } } } catch (Exception e) { log.warning("delHostAus()", e); } } // These don't belong here /** * Reconfigure an AU and save the new configuration in the local config * file. Need to find a better place for this. * @param au the AU * @param auProps the new AU configuration, using simple prop keys (not * prefixed with org.lockss.au.<i>auid</i>) * @throws ArchivalUnit.ConfigurationException * @throws IOException */ public void setAndSaveAuConfiguration(ArchivalUnit au, Properties auProps) throws ArchivalUnit.ConfigurationException, IOException { setAndSaveAuConfiguration(au, ConfigManager.fromPropertiesUnsealed(auProps)); } /** * Reconfigure an AU and save the new configuration in the local config * file. Need to find a better place for this. * @param au the AU * @param auConf the new AU configuration, using simple prop keys (not * prefixed with org.lockss.au.<i>auid</i>) * @throws ArchivalUnit.ConfigurationException * @throws IOException */ public void setAndSaveAuConfiguration(ArchivalUnit au, Configuration auConf) throws ArchivalUnit.ConfigurationException, IOException { log.debug("Reconfiguring AU " + au); au.setConfiguration(auConf); updateAuConfigFile(au, auConf); } private void updateAuConfigFile(ArchivalUnit au, Configuration auConf) throws IOException { if (!auConf.isEmpty()) { if (!auConf.isSealed()) { auConf.put(AU_PARAM_DISPLAY_NAME, au.getName()); } else if (StringUtil.isNullString(auConf.get(AU_PARAM_DISPLAY_NAME))) { log.debug("Can't add name to sealed AU config: " + auConf, new Throwable()); } } updateAuConfigFile(au.getAuId(), auConf); } public void updateAuConfigFile(String auid, Configuration auConf) throws IOException { String prefix = PARAM_AU_TREE + "." + configKeyFromAuId(auid); Configuration fqConfig = auConf.addPrefix(prefix); configMgr.updateAuConfigFile(fqConfig, prefix); } /** * Create an AU and save its configuration in the local config * file. Need to find a better place for this. * @param plugin the Plugin in which to create the AU * @param auProps the new AU configuration, using simple prop keys (not * prefixed with org.lockss.au.<i>auid</i>) * @return the new AU * @throws ArchivalUnit.ConfigurationException * @throws IOException */ public ArchivalUnit createAndSaveAuConfiguration(Plugin plugin, Properties auProps) throws ArchivalUnit.ConfigurationException, IOException { return createAndSaveAuConfiguration(plugin, ConfigManager.fromPropertiesUnsealed(auProps)); } /** * Create an AU and save its configuration in the local config * file. Need to find a better place for this. * @param plugin the Plugin in which to create the AU * @param auConf the new AU configuration, using simple prop keys (not * prefixed with org.lockss.au.<i>auid</i>) * @return the new AU * @throws ArchivalUnit.ConfigurationException * @throws IOException */ public ArchivalUnit createAndSaveAuConfiguration(Plugin plugin, Configuration auConf) throws ArchivalUnit.ConfigurationException, IOException { auConf.put(AU_PARAM_DISABLED, "false"); ArchivalUnit au = createAu(plugin, auConf); updateAuConfigFile(au, auConf); return au; } /** * Delete AU configuration from the local config file. Need to find a * better place for this. * @param au the ArchivalUnit to be unconfigured * @throws IOException */ public void deleteAuConfiguration(ArchivalUnit au) throws IOException { log.debug("Deleting AU config: " + au); updateAuConfigFile(au, ConfigManager.EMPTY_CONFIGURATION); } /** * Delete AU configuration from the local config file. Need to find a * better place for this. * @param auid the AuId * @throws IOException */ public void deleteAuConfiguration(String auid) throws IOException { log.debug("Deleting AU config: " + auid); updateAuConfigFile(auid, ConfigManager.EMPTY_CONFIGURATION); // might be deleting an inactive au inactiveAuIds.remove(auid); } /** * Deactivate an AU in the config file. Does not actually stop the AU. * @param au the ArchivalUnit to be deactivated * @throws IOException */ public void deactivateAuConfiguration(ArchivalUnit au) throws IOException { log.debug("Deactivating AU: " + au); Configuration config = getStoredAuConfiguration(au); if (config.isSealed()) { config = config.copy(); } config.put(AU_PARAM_DISABLED, "true"); updateAuConfigFile(au, config); } /** * Delete an AU * @param au the ArchivalUnit to be deleted * @throws IOException */ public void deleteAu(ArchivalUnit au) throws IOException { deleteAuConfiguration(au); if (isRemoveStoppedAus()) { stopAu(au); } } /** * Deactivate an AU * @param au the ArchivalUnit to be deactivated * @throws IOException */ public void deactivateAu(ArchivalUnit au) throws IOException { deactivateAuConfiguration(au); if (isRemoveStoppedAus()) { String auid = au.getAuId(); stopAu(au); inactiveAuIds.add(auid); } } public boolean isRemoveStoppedAus() { return CurrentConfig.getBooleanParam(PARAM_REMOVE_STOPPED_AUS, DEFAULT_REMOVE_STOPPED_AUS); } /** * Return true if the specified Archival Unit is used internally * by the LOCKSS daemon. Currently this is only registry AUs */ public boolean isInternalAu(ArchivalUnit au) { return au instanceof RegistryArchivalUnit; } /** * Return true if the specified Archival Unit is a plugin registry AU */ public boolean isRegistryAu(ArchivalUnit au) { return au instanceof RegistryArchivalUnit; } /** * Return true if the specified Plugin is used internally * by the LOCKSS daemon. */ public boolean isInternalPlugin(Plugin plugin) { return plugin instanceof RegistryPlugin; } /** * Return true if the specified Plugin is a Loadable plugin */ public boolean isLoadablePlugin(Plugin plugin) { PluginInfo info = (PluginInfo)pluginfoMap.get(getPluginKey(plugin)); if (info == null) { return false; } return info.isOnLoadablePath(); } /** * Return the stored config info for an AU (from config file, not from * AU instance). * @param au the ArchivalUnit * @return the AU's Configuration, with unprefixed keys. */ public Configuration getStoredAuConfiguration(ArchivalUnit au) { return getStoredAuConfiguration(au.getAuId()); } /** * Return the config tree for an AU id (from the local au config file, * not the au itself). * @param auid the AU's id. * @return the AU's Configuration, with unprefixed keys. */ public Configuration getStoredAuConfiguration(String auid) { String aukey = configKeyFromAuId(auid); Configuration config = configMgr.readAuConfigFile(); String prefix = PARAM_AU_TREE + "." + aukey; return config.getConfigTree(prefix); } /** * Return the current config info for an AU (from current configuration) * @param auid the AU's id. * @return the AU's Configuration, with unprefixed keys. */ public Configuration getCurrentAuConfiguration(String auid) { String aukey = configKeyFromAuId(auid); String prefix = PARAM_AU_TREE + "." + aukey; return ConfigManager.getCurrentConfig().getConfigTree(prefix); } // Loadable Plugin Support /** * Retrieve a plugin from the specified classloader. If the * clasloader is 'null', this method will use the default * classloader. */ PluginInfo retrievePlugin(String pluginKey, ClassLoader loader) throws Exception { if (pluginfoMap.containsKey(pluginKey)) { return (PluginInfo)pluginfoMap.get(pluginKey); } if (pluginMap.containsKey(pluginKey)) { return new PluginInfo((Plugin)pluginMap.get(pluginKey), loader, null); } String pluginName = pluginNameFromKey(pluginKey); if (retract != null && !retract.isEmpty()) { if (retract.contains(pluginName)) { log.debug3("Not loading " + pluginName + " because it's on the retract list"); return null; } } if (loader == null) { loader = this.getClass().getClassLoader(); } Plugin classPlugin = null; DefinablePlugin xmlPlugin = null; boolean foundClassPlugin = false; boolean foundXmlPlugin = false; // 1. Look for an ordinary Plugin object. try { // See if we can load the class by name. log.debug3(pluginName + ": Loading class."); Class c = Class.forName(pluginName, true, loader); classPlugin = (Plugin)c.newInstance(); classPlugin.initPlugin(getDaemon()); if (isCompatible(classPlugin)) { foundClassPlugin = true; } else { classPlugin.stopPlugin(); log.warning("Plugin " + pluginName + " not started because it requires daemon version " + classPlugin.getRequiredDaemonVersion()); } } catch (ClassNotFoundException ex) { log.debug3(pluginName + ": Class not found on classpath."); } catch (LinkageError e) { log.warning("Can't load plugin", e); } // 2. Look for a loadable plugin definition. try { log.debug3(pluginName + ": Loading XML definition."); Class c = Class.forName(getConfigurablePluginName(), true, loader); xmlPlugin = (DefinablePlugin)c.newInstance(); xmlPlugin.initPlugin(getDaemon(), pluginName, loader); if (isCompatible(xmlPlugin)) { foundXmlPlugin = true; } else { xmlPlugin.stopPlugin(); log.warning("Plugin " + pluginName + " not started because it requires daemon version " + xmlPlugin.getRequiredDaemonVersion()); } } catch (FileNotFoundException ex) { log.debug2("No XML plugin: " + pluginName + ": " + ex); } catch (Exception ex) { log.debug2("No XML plugin: " + pluginName, ex); } // If both are found, decide which one to favor. if (foundClassPlugin && foundXmlPlugin) { // Shouldn't have both. Log a warning, and use // the default (which is configurable) log.warning(pluginName + ": Both a definable plugin definition " + "and a plugin class file were found."); switch(getPreferredPluginType()) { case PREFER_XML_PLUGIN: log.debug(pluginName + ": Creating definable plugin."); foundClassPlugin = false; break; case PREFER_CLASS_PLUGIN: log.debug(pluginName + ": Instantiating plugin class."); foundXmlPlugin = false; break; default: log.warning(pluginName + ": Unable to determine which " + "to load! Plugin not loaded."); return null; } } // Now at most one version is true if (foundClassPlugin) { String path = pluginName.replace('.', '/').concat(".class"); URL url = loader.getResource(path); PluginInfo info = new PluginInfo(classPlugin, loader, url.toString()); return info; } else if (foundXmlPlugin) { String url = xmlPlugin.getLoadedFrom(); PluginInfo info = new PluginInfo(xmlPlugin, loader, url); return info; } else { // Error -- this plugin was not found. log.error(pluginName + " could not be loaded."); return null; } } boolean isCompatible(Plugin plug) { boolean res; DaemonVersion dver = getDaemonVersion(); if (dver == null) { res = true; // don't break things during testing } else { DaemonVersion preq = new DaemonVersion(plug.getRequiredDaemonVersion()); res = dver.compareTo(preq) >= 0; } if (log.isDebug3()) log.debug3("Plugin is " + (res ? "" : "not ") + "compatible with daemon " + dver); return res; } // overridable for testing protected DaemonVersion getDaemonVersion() { return ConfigManager.getDaemonVersion(); } /** * (package-level access for unit testing) */ int getPreferredPluginType() { String preferredPlugin = CurrentConfig.getCurrentConfig().get(PARAM_PREFERRED_PLUGIN_TYPE, DEFAULT_PREFERRED_PLUGIN_TYPE); if (StringUtil.equalStringsIgnoreCase(preferredPlugin.trim(), "xml")) { return PREFER_XML_PLUGIN; } else if (StringUtil.equalStringsIgnoreCase(preferredPlugin.trim(), "class")) { return PREFER_CLASS_PLUGIN; } else { // By default, if we can't parse the configuration return PREFER_XML_PLUGIN; } } /** * Load a plugin with the given class name from somewhere in our classpath. * @param pluginKey the key for this plugin * @return true if loaded */ public boolean ensurePluginLoaded(String pluginKey) { if (pluginMap.containsKey(pluginKey)) { return true; } ClassLoader loader = null; PluginInfo info = (PluginInfo)pluginfoMap.get(pluginKey); if (info != null) { loader = info.getClassLoader(); } if (loader == null) { loader = this.getClass().getClassLoader(); } String pluginName = ""; try { pluginName = pluginNameFromKey(pluginKey); log.debug3("Trying to retrieve "+pluginKey); info = retrievePlugin(pluginKey, loader); if (info != null) { setPlugin(pluginKey, info.getPlugin()); pluginfoMap.put(pluginKey, info); return true; } else { log.debug("Couldn't retrieve "+pluginKey); return false; } } catch (Exception e) { log.error("Error instantiating " + pluginName, e); return false; } } public Plugin loadBuiltinPlugin(Class pluginClass) { return loadBuiltinPlugin(pluginClass.getName()); } protected Plugin loadBuiltinPlugin(String pluginClassName) { String pluginKey = pluginKeyFromName(pluginClassName); if (ensurePluginLoaded(pluginKey)) { return (Plugin)pluginMap.get(pluginKey); } return null; } // separate method so can be called by test code protected void setPlugin(String pluginKey, Plugin plugin) { if (log.isDebug3()) { log.debug3("PluginManager.setPlugin(" + pluginKey + ", " + plugin.getPluginName() + ")"); } pluginMap.put(pluginKey, plugin); resetTitles(); } void removePlugin(String key) { log.debug("Removing plugin " + key); pluginMap.remove(key); pluginfoMap.remove(key); } protected String getConfigurablePluginName() { return CONFIGURABLE_PLUGIN_NAME; } /** * Find the CachedUrlSet from a PollSpec. * @param spec the PollSpec (from an incoming message) * @return a CachedUrlSet for the plugin, au and URL in the spec, or * null if au not present on this cache */ public CachedUrlSet findCachedUrlSet(PollSpec spec) { if (log.isDebug3()) log.debug3(this +".findCachedUrlSet2("+spec+")"); String auId = spec.getAuId(); ArchivalUnit au = getAuFromId(auId); if (log.isDebug3()) log.debug3("au: " + au); if (au == null) return null; String url = spec.getUrl(); CachedUrlSet cus; if (AuUrl.isAuUrl(url)) { cus = au.getAuCachedUrlSet(); } else if ((spec.getLwrBound() != null) && (spec.getLwrBound().equals(PollSpec.SINGLE_NODE_LWRBOUND))) { cus = au.makeCachedUrlSet(new SingleNodeCachedUrlSetSpec(url)); } else { RangeCachedUrlSetSpec rcuss = new RangeCachedUrlSetSpec(url, spec.getLwrBound(), spec.getUprBound()); cus = au.makeCachedUrlSet(rcuss); } if (log.isDebug3()) log.debug3("ret cus: " + cus); return cus; } /** * Find an AU's top level CachedUrlSet. * * @param auId * @return top level <code>CachedUrlSet</code> for the specified auId */ public CachedUrlSet findCachedUrlSet(String auId) { ArchivalUnit au = getAuFromId(auId); if (au == null) return null; return au.getAuCachedUrlSet(); } /** * Searches for an AU that contains the URL and returns the corresponding * CachedUrl. * @param url The URL to search for. * @return a CachedUrl, or null if URL not present in any AU */ public CachedUrl findCachedUrl(String url) { return findTheCachedUrl(url, true); } /** * Searches for an AU that contains the URL and returns the corresponding * CachedUrl. * @param url The URL to search for. * @param withContent true if the CachedUrl must have content * @return a CachedUrl, or null if URL not present in any AU */ public CachedUrl findCachedUrl(String url, boolean withContent) { return findTheCachedUrl(url, withContent); } /** Return a collection of all AUs that have content on the host of this * url, sorted in AU title order. */ // This method needs to copy the list anyway, to avoid CME, so this is as // good a place as any to sort it. // XXX Should do something about the redundant normalization involved in // calling more than one of these methods public Collection getCandidateAus(String url) throws MalformedURLException { String normStem = UrlUtil.getUrlPrefix(UrlUtil.normalizeUrl(url)); return getCandidateAusFromStem(normStem); } public Collection getCandidateAusFromStem(String normStem) { synchronized (hostAus) { Collection cand = (Collection)hostAus.get(normStem); if (cand != null) { Set res = new TreeSet(new AuOrderComparator()); res.addAll(cand); cand = res; } return cand; } } /** Return a collection of all AUs that have content on the host of this * url, sorted in AU title order. */ // This method needs to copy the list anyway, to avoid CME, so this is as // good a place as any to sort it. // XXX Should do something about the redundant normalization involved in // calling more than one of these methods public SortedSet getAllStems() { synchronized (hostAus) { return new TreeSet(hostAus.keySet()); } } // Return actual list of candiate AUs, used only for testing List getRawCandidateAus(String url) throws MalformedURLException { String normStem = UrlUtil.getUrlPrefix(UrlUtil.normalizeUrl(url)); synchronized (hostAus) { return (List)hostAus.get(normStem); } } private Map recentCuMap = Collections.synchronizedMap(new LRUMap(20)); /** Find a CachedUrl for the URL. */ private CachedUrl findTheCachedUrl(String url, boolean withContent) { // Maintain a small cache of URL -> CU. When ICP is in use, each URL // will likely be looked up twice in quick succession CachedUrl res = (CachedUrl)recentCuMap.get(url); if (log.isDebug3()) { if (res != null) { log.debug3("cache hit " + res.toString() + (res.hasContent() ? "with" : "without") + " content."); } else { log.debug3("cache miss for " + url); } } if (res == null || (withContent && !res.hasContent())) { res = findTheCachedUrl0(url, withContent); if (res != null) { recentCuMap.put(url, res); } } return res; } private CachedUrl findTheCachedUrl0(String url, boolean withContent) { // We don't know what AU it might be in, so can't do plugin-dependent // normalization yet. But only need to do generic normalization once. // XXX This is wrong, as plugin-specific normalization is normally done // first. // XXX There is a problem with this when used by *Exploder() classes. // In the CLOCKSS case, we expect huge numbers of AUs to share // that is exploded to include URLs for a large number of them. // The optimization that returns the most recent one if it matches // will help, but perhaps not enough. Ideally we want to search // for AUs on the basis of their base_url, which for // ExplodedArchiveUnits is their sole definitional parameter, so // is known unique. String normUrl; String normStem; try { normUrl = UrlUtil.normalizeUrl(url); normStem = UrlUtil.getUrlPrefix(normUrl); } catch (MalformedURLException e) { log.warning("findTheCachedUrl(" + url + ")", e); return null; } synchronized (hostAus) { ArrayList candidateAus = (ArrayList)hostAus.get(normStem); if (candidateAus == null) { log.debug3("findTheCachedUrl: No AUs for " + normStem); return null; } CachedUrl bestCu = null; int bestAuIx = -1; int bestScore = 8; int auIx = 0; for (Iterator iter = candidateAus.iterator(); iter.hasNext(); auIx++) { ArchivalUnit au = (ArchivalUnit)iter.next(); log.debug3("findTheCachedUrl: " + normUrl + " check " + au.toString()); if (au.shouldBeCached(normUrl)) { log.debug3("findTheCachedUrl: " + normUrl + " should be in " + au.getAuId()); try { String siteUrl = UrlUtil.normalizeUrl(normUrl, au); CachedUrl cu = au.makeCachedUrl(siteUrl); log.debug3("findTheCachedUrl: " + siteUrl + " got " + (cu == null ? "no cu" : cu.toString())); if (cu != null && (!withContent || cu.hasContent())) { int score = score(au, cu); if (score == 0) { makeFirstCandidate(candidateAus, auIx); log.debug3("findTheCachedUrl: " + siteUrl + " is it"); return cu; } if (score < bestScore) { AuUtil.safeRelease(bestCu); bestCu = cu; bestAuIx = auIx; bestScore = score; } else { cu.release(); } } } catch (MalformedURLException ignore) { // ignored } catch (PluginBehaviorException ignore) { // ignored } } } makeFirstCandidate(candidateAus, bestAuIx); log.debug3("bestCu was " + (bestCu == null ? "null" : bestCu.toString())); return bestCu; } } // Move the AU in which we found the CU to the head of the list, as it's // likely next request will be for the same AU. private void makeFirstCandidate(List lst, int ix) { if (ix > 0) { synchronized (hostAus) { Collections.swap(lst, ix, 0); } } } // Combine the various elements of desirability into a single score; // lower is better, zero is best. private int score(ArchivalUnit au, CachedUrl cu) { if (cu == null) return 4; int res = 0; if (isUnsubscribed(au)) res += 2; if (isDamaged(cu)) res += 1; return res; } private boolean isUnsubscribed(ArchivalUnit au) { return (getDaemon().isDetectClockssSubscription() && (AuUtil.getAuState(au).getClockssSubscriptionStatus() != AuState.CLOCKSS_SUB_YES)); } // XXX private boolean isDamaged(CachedUrl cu) { return false; } // // return true if cu1 is newer than cu2, or cu2 is null // // XXX - should compare last-modified times, or crawl times? // private boolean cuNewerThan(CachedUrl cu1, CachedUrl cu2) { // if (cu2 == null) return true; // return false; // // CIProperties p1 = cu1.getProperties(); // // CIProperties p2 = cu2.getProperties(); // // Long.parseLong(p1.getProperty(HttpFields.__LastModified, "-1")); /** * Return a list of all configured ArchivalUnits. The UI relies on * this being sorted by au title, and so we return a copy of auSet, * which is kept in the right order. * * @return the List of aus */ public List<ArchivalUnit> getAllAus() { synchronized (auSet) { if (auList == null) { auList = new ArrayList<ArchivalUnit>(auSet); } return auList; } } /** * Return a randomly ordered list of all AUs. */ // putting this here in PluginManager saves having to make an extra copy // of auSet public List getRandomizedAus() { synchronized (auSet) { return CollectionUtil.randomPermutation(auSet); } } public Collection getInactiveAuIds() { return inactiveAuIds; } /** Return a collection of all RegistryArchivalUnits. This is a subset * of getAllAus() */ public Collection<ArchivalUnit> getAllRegistryAus() { return getRegistryPlugin().getAllAus(); } Object titleMonitor = new Object(); /** Return all the known titles from the title db, sorted by title */ public List findAllTitles() { synchronized (titleMonitor) { if (allTitles == null) { allTitles = new ArrayList(getTitleMap().keySet()); Collections.sort(allTitles, CatalogueOrderComparator.SINGLETON); } return allTitles; } } /** Find all the plugins that support the given title */ public Collection getTitlePlugins(String title) { Collection res = (Collection)getTitleMap().get(title); if (res != null) { return res; } return Collections.EMPTY_LIST; } /** Return all known TitleConfigs */ public List findAllTitleConfigs() { synchronized (titleMonitor) { if (allTitleConfigs == null) { List titles = findAllTitles(); List res = new ArrayList(titles.size()); for (Iterator titer = titles.iterator(); titer.hasNext();) { String title = (String)titer.next(); for (Iterator piter = getTitlePlugins(title).iterator(); piter.hasNext();) { Plugin plugin = (Plugin)piter.next(); TitleConfig tc = plugin.getTitleConfig(title); if (tc != null) { res.add(tc); } else { log.warning("getTitleConfig(" + plugin + ", " + title + ") = null"); } } } allTitleConfigs = res; } return allTitleConfigs; } } public void resetTitles() { synchronized (titleMonitor) { titleMap = null; allTitles = null; allTitleConfigs = null; } } public Map getTitleMap() { synchronized (titleMonitor) { if (titleMap == null) { titleMap = buildTitleMap(); } return titleMap; } } Map buildTitleMap() { Map map = new MultiValueMap(); synchronized (pluginMap) { for (Iterator iter = getRegisteredPlugins().iterator(); iter.hasNext();) { Plugin p = (Plugin)iter.next(); Collection titles = p.getSupportedTitles(); for (Iterator iter2 = titles.iterator(); iter2.hasNext();) { String title = (String)iter2.next(); if (title != null) { map.put(title, p); } } } } return map; } /** Return a SortedMap mapping (human readable) plugin name to plugin * instance */ public SortedMap getPluginNameMap() { SortedMap pMap = new TreeMap(); synchronized (pluginMap) { for (Iterator iter = getRegisteredPlugins().iterator(); iter.hasNext(); ) { Plugin p = (Plugin)iter.next(); pMap.put(p.getPluginName(), p); } } return pMap; } /** @return All plugins that have been registered. <i>Ie</i>, that are * either listed in org.lockss.plugin.registry, or were loaded by a * configured AU */ public Collection getRegisteredPlugins() { return pluginMap.values(); } /** @return loadable PluginInfo for plugin, or null */ PluginInfo getLoadablePluginInfo(Plugin plugin) { return (PluginInfo)pluginfoMap.get(getPluginKey(plugin)); } /** * Load all plugin registry plugins. */ void initLoadablePluginRegistries(List urls) { // Load the keystore if necessary initKeystore(configMgr.getCurrentConfig()); if (urls.isEmpty()) { return; } BinarySemaphore bs = new BinarySemaphore(); InitialRegistryCallback regCallback = new InitialRegistryCallback(urls, bs); List loadAus = new ArrayList(); for (Iterator iter = urls.iterator(); iter.hasNext(); ) { String url = (String)iter.next(); Configuration auConf = ConfigManager.newConfiguration(); auConf.put(ConfigParamDescr.BASE_URL.getKey(), url); String auId = generateAuId(getRegistryPlugin(), auConf); String auKey = auKeyFromAuId(auId); // Only process this registry if it is new. if (!auMap.containsKey(auId)) { try { configureAu(getRegistryPlugin(), auConf, auId); } catch (ArchivalUnit.ConfigurationException ex) { log.error("Failed to configure AU " + auKey, ex); regCallback.crawlCompleted(url); continue; } ArchivalUnit registryAu = getAuFromId(auId); loadAus.add(registryAu); // Trigger a new content crawl if required. possiblyStartRegistryAuCrawl(registryAu, url, regCallback); } else { log.debug2("We already have this AU configured, notifying callback."); regCallback.crawlCompleted(url); } } // Wait for a while for the AU crawls to complete, then process all the // registries in the load list. log.debug("Waiting for loadable plugins to finish loading..."); try { if (!bs.take(Deadline.in(registryTimeout))) { log.warning("Timed out while waiting for registries to finish loading. " + "Remaining registry URL list: " + regCallback.getRegistryUrls()); } } catch (InterruptedException ex) { log.warning("Binary semaphore threw InterruptedException while waiting." + "Remaining registry URL list: " + regCallback.getRegistryUrls()); } processRegistryAus(loadAus); } private synchronized RegistryPlugin getRegistryPlugin() { if (regPlugin == null) { regPlugin = new RegistryPlugin(); String pluginKey = pluginKeyFromName("org.lockss.plugin.RegistryPlugin"); regPlugin.initPlugin(getDaemon()); setPlugin(pluginKey, regPlugin); } return regPlugin; } // Trigger a new content crawl on the registry AU if required. protected void possiblyStartRegistryAuCrawl(ArchivalUnit registryAu, String url, InitialRegistryCallback cb) { if (registryAu.shouldCrawlForNewContent(AuUtil.getAuState(registryAu))) { if (log.isDebug2()) log.debug2("Starting new crawl:: " + registryAu); getDaemon().getCrawlManager().startNewContentCrawl(registryAu, cb, url, null); } else { if (log.isDebug2()) log.debug2("No crawl needed: " + registryAu); // If we're not going to crawl this AU, let the callback know. cb.crawlCompleted(url); } } // Synch the plugin registry with the plugins listed in names void initPluginRegistry(Configuration config) { List nameList = config.getList(PARAM_PLUGIN_REGISTRY); Collection newKeys = new HashSet(); for (Iterator iter = nameList.iterator(); iter.hasNext(); ) { String name = (String)iter.next(); String key = pluginKeyFromName(name); ensurePluginLoaded(key); newKeys.add(key); } // remove plugins on retract list, unless they have one or more // configured AUs synchronized (pluginMap) { if (retract != null) { for (Iterator iter = retract.iterator(); iter.hasNext(); ) { String name = (String)iter.next(); String key = pluginKeyFromName(name); Plugin plug = getPlugin(key); if (plug != null && !isInternalPlugin(plug)) { Configuration tree = currentAllPlugs.getConfigTree(key); if (tree == null || tree.isEmpty()) { removePlugin(key); } } } } } } /** * Initialize the "blessed" loadable plugin directory. */ private void initPluginDir() { if (pluginDir != null) { return; } List dSpaceList = ConfigManager.getCurrentConfig().getList(ConfigManager.PARAM_PLATFORM_DISK_SPACE_LIST); String relPluginPath = ConfigManager.getCurrentConfig().get(PARAM_PLUGIN_LOCATION, DEFAULT_PLUGIN_LOCATION); if (dSpaceList == null || dSpaceList.size() == 0) { log.error(ConfigManager.PARAM_PLATFORM_DISK_SPACE_LIST + " not specified, not configuring plugin dir"); return; } String pluginDisk = (String)dSpaceList.get(0); File dir = new File(new File(pluginDisk), relPluginPath); if (dir.exists() && !dir.isDirectory()) { // This should (hopefully) never ever happen. Log an error and // return for now. log.error("Plugin directory " + dir + " cannot be created. A file " + "already exists with that name!"); return; } if (dir.exists() && dir.isDirectory()) { log.debug("Plugin directory " + dir + " already exists. Cleaning up..."); File[] dirList = dir.listFiles(); for (int ix = 0; ix < dirList.length; ix++) { if (!dirList[ix].delete()) { log.error("Unable to clean up plugin directory " + dir + ". Could not delete " + dirList[ix]); return; } } } else { if (!dir.mkdirs()) { log.error("Unable to create plugin directory " + dir); return; } } pluginDir = dir; } /* * Helper methods for handling loadable plugins. */ /** * Initialize and return the keystore. */ KeyStore initKeystore(String keystoreLoc, String keystorePass) { KeyStore ks = null; try { if (keystoreLoc == null || keystorePass == null) { log.error("Unable to load keystore! Loadable plugins will " + "not be available."); } else { log.debug("Loading keystore: " + keystoreLoc); ks = KeyStore.getInstance("JKS", "SUN"); if (keystoreLoc.startsWith(File.separator)) { InputStream kin = new FileInputStream(new File(keystoreLoc)); try { ks.load(kin, keystorePass.toCharArray()); } finally { IOUtil.safeClose(kin); } } else if (UrlUtil.isHttpUrl(keystoreLoc) || UrlUtil.isFileUrl(keystoreLoc)) { URL keystoreUrl = new URL(keystoreLoc); ks.load(keystoreUrl.openStream(), keystorePass.toCharArray()); } else { InputStream kin = getClass().getClassLoader().getResourceAsStream(keystoreLoc); if (kin == null) { throw new IOException("Keystore reousrce not found: " + keystoreLoc); } ks.load(kin, keystorePass.toCharArray()); } } } catch (Exception ex) { // ensure the keystore is null. log.error("Unable to load keystore from " + keystoreLoc, ex); return null; } log.debug("Keystore successfully initialized."); return ks; } private boolean isKeystoreInited() { return keystoreInited; } private void initKeystore(Configuration config) { String keystoreLoc; String keystorePass; if (!isKeystoreInited()) { keystoreLoc = config.get(PARAM_USER_KEYSTORE_LOCATION); if (!StringUtil.isNullString(keystoreLoc)) { keystorePass = config.get(PARAM_USER_KEYSTORE_PASSWORD, DEFAULT_KEYSTORE_PASSWORD); } else { keystoreLoc = config.get(PARAM_KEYSTORE_LOCATION, DEFAULT_KEYSTORE_LOCATION); keystorePass = config.get(PARAM_KEYSTORE_PASSWORD, DEFAULT_KEYSTORE_PASSWORD); } keystore = initKeystore(keystoreLoc, keystorePass); if (keystore != null) { keystoreInited = true; } } } // used by unit tests. public void setKeystoreInited(boolean val) { this.keystoreInited = val; } /** * Given a file representing a JAR, retrieve a list of available * plugin classes to load. */ private List getJarPluginClasses(File blessedJar) throws IOException { JarFile jar = new JarFile(blessedJar); Manifest manifest = jar.getManifest(); Map entries = manifest.getEntries(); List plugins = new ArrayList(); for (Iterator manIter = entries.keySet().iterator(); manIter.hasNext();) { String key = (String)manIter.next(); Attributes attrs = manifest.getAttributes(key); if (attrs.containsKey(LOADABLE_PLUGIN_ATTR)) { String s = StringUtil.replaceString(key, "/", "."); String pluginName = null; if (StringUtil.endsWithIgnoreCase(key, ".class")) { pluginName = StringUtil.replaceString(s, ".class", ""); log.debug2("Adding '" + pluginName + "' to plugin load list."); plugins.add(pluginName); } else if (StringUtil.endsWithIgnoreCase(key, ".xml")) { pluginName = StringUtil.replaceString(s, ".xml", ""); log.debug2("Adding '" + pluginName + "' to plugin load list."); plugins.add(pluginName); } } } jar.close(); return plugins; } /** * Run through the list of Registry AUs and verify and load any JARs * that need to be loaded. */ public synchronized void processRegistryAus(List registryAus) { if (jarValidator == null) { jarValidator = new JarValidator(keystore, pluginDir); } jarValidator.allowExpired(acceptExpiredCertificates); // Create temporary plugin and classloader maps HashMap tmpMap = new HashMap(); for (Iterator iter = registryAus.iterator(); iter.hasNext(); ) { ArchivalUnit au = (ArchivalUnit)iter.next(); try { processOneRegistryAu(au, tmpMap); } catch (RuntimeException e) { log.error("Error processing plugin registry AU: " + au, e); } } // After the temporary plugin map has been built, install it into // the global maps. List classloaders = new ArrayList(); for (Iterator pluginIter = tmpMap.entrySet().iterator(); pluginIter.hasNext(); ) { Map.Entry entry = (Map.Entry)pluginIter.next(); String key = (String)entry.getKey(); log.debug2("Adding to plugin map: " + key); PluginInfo info = (PluginInfo)entry.getValue(); pluginfoMap.put(key, info); classloaders.add(info.getClassLoader()); setPlugin(key, info.getPlugin()); } // Add the JAR's bundled titledb config (if any) to the ConfigManager. // Do this once at the end so as not to trigger more than one config // update & reload. configMgr.addTitleDbConfigFrom(classloaders); // Cleanup as a hint to GC. tmpMap.clear(); tmpMap = null; } protected void processOneRegistryAu(ArchivalUnit au, Map tmpMap) { CachedUrlSet cus = au.getAuCachedUrlSet(); for (Iterator cusIter = cus.contentHashIterator(); cusIter.hasNext(); ) { CachedUrlSetNode cusn = (CachedUrlSetNode)cusIter.next(); // TODO: Eventually this should be replaced with // "cusn.hasContent()", which will add another loop if it is a // CachedUrlSet. String url = cusn.getUrl(); if (StringUtil.endsWithIgnoreCase(url, ".jar") && cusn.isLeaf()) { // This CachedUrl represents a plugin JAR, validate it and // process the plugins it contains. CachedUrl cu = (CachedUrl)cusn; try { processOneRegistryJar(cu, url, au, tmpMap); } catch (RuntimeException e) { log.error("Error processing plugin jar: " + cu, e); } } } } protected void processOneRegistryJar(CachedUrl cu, String url, ArchivalUnit au, Map tmpMap) { Integer curVersion = new Integer(cu.getVersion()); if (cuNodeVersionMap.get(url) == null) { cuNodeVersionMap.put(url, new Integer(-1)); } // If we've already visited this CU, skip it unless the current // repository node is a different version (older OR newer) Integer oldVersion = (Integer)cuNodeVersionMap.get(url); if (oldVersion.equals(curVersion)) { log.debug2(url + ": JAR repository and map versions are identical. Skipping..."); return; } File blessedJar = null; if (cu.getContentSize() == 0) { log.debug("Empty plugin jar: " + cu); return; } else { try { // Validate and bless the JAR file from the CU. blessedJar = jarValidator.getBlessedJar(cu); } catch (IOException ex) { log.error("Error processing jar file: " + url, ex); return; } catch (JarValidator.JarValidationException ex) { log.error("CachedUrl did not validate: " + cu, ex); return; } } // Update the cuNodeVersion map now that we have the blessed Jar. cuNodeVersionMap.put(url, curVersion); if (blessedJar != null) { // Get the list of plugins to load from this jar. List loadPlugins = null; try { loadPlugins = getJarPluginClasses(blessedJar); } catch (IOException ex) { log.error("Error while getting list of plugins for " + blessedJar); return; // skip this CU. } // Although this -should- never happen, it's possible. if (loadPlugins.size() == 0) { log.warning("Jar " + blessedJar + " does not contain any plugins. Skipping..."); return; // skip this CU. } // Load the plugin classes ClassLoader pluginLoader = null; URL blessedUrl; try { blessedUrl = blessedJar.toURL(); URL[] urls = new URL[] { blessedUrl }; pluginLoader = preferLoadablePlugin ? new LoadablePluginClassLoader(urls) : new URLClassLoader(urls); } catch (MalformedURLException ex) { log.error("Malformed URL exception attempting to create " + "classloader for plugin JAR " + blessedJar); return; // skip this CU. } String pluginName = null; for (Iterator pluginIter = loadPlugins.iterator(); pluginIter.hasNext();) { pluginName = (String)pluginIter.next(); String key = pluginKeyFromName(pluginName); Plugin plugin; PluginInfo info; try { info = retrievePlugin(pluginName, pluginLoader); info.setCuUrl(url); info.setRegistryAu(au); String jar = info.getJarUrl(); if (jar != null) { // If the blessed jar path is a substring of the jar: // url from which the actual plugin resource or class // was loaded, then it is a loadable plugin. boolean isLoadable = jar.indexOf(blessedUrl.getFile()) > 0; info.setIsOnLoadablePath(isLoadable); } plugin = info.getPlugin(); } catch (Exception ex) { log.error("Unable to load plugin " + pluginName + ", skipping: " + ex.getMessage()); return; } PluginVersion version = null; try { version = new PluginVersion(plugin.getVersion()); info.setVersion(version); } catch (IllegalArgumentException ex) { // Don't let this runtime exception stop the daemon. Skip the plugin. log.error("Skipping plugin " + pluginName + ": " + ex.getMessage()); return; } if (pluginMap.containsKey(key)) { // Plugin already exists in the global plugin map. // Replace it with a new version if one is available. log.debug2("Plugin " + key + " is already in global pluginMap."); Plugin otherPlugin = getPlugin(key); PluginVersion otherVer = new PluginVersion(otherPlugin.getVersion()); if (version.toLong() > otherVer.toLong()) { if (log.isDebug2()) { log.debug2("Existing plugin " + plugin.getPluginId() + ": Newer version " + version + " found."); } tmpMap.put(key, info); } else { if (log.isDebug2()) { log.debug2("Existing plugin " + plugin.getPluginId() + ": No newer version found."); } } } else if (!tmpMap.containsKey(key)) { // Plugin doesn't yet exist in the temporary map, add it. tmpMap.put(key, info); if (log.isDebug2()) { log.debug2("Plugin " + plugin.getPluginId() + ": No previous version in temp map."); } } else { // Plugin already exists in the temporary map, use whichever // version is higher. PluginVersion otherVer = ((PluginInfo)tmpMap.get(key)).getVersion(); if (version.toLong() > otherVer.toLong()) { if (log.isDebug2()) { log.debug2("Plugin " + plugin.getPluginId() + ": version " + version + " is newer than version " + otherVer + " already in temp map, overwriting."); } // Overwrite old key in temp map tmpMap.put(key, info); } } } } } /** * CrawlManager callback that is responsible for handling Registry * AUs when they're finished with their initial crawls. */ static class InitialRegistryCallback implements CrawlManager.Callback { private BinarySemaphore bs; List registryUrls; /* * Set the initial size of the list of registry URLs to process. */ public InitialRegistryCallback(List registryUrls, BinarySemaphore bs) { this.registryUrls = Collections.synchronizedList(new ArrayList(registryUrls)); this.bs = bs; if (log.isDebug2()) log.debug2("InitialRegistryCallback: " + registryUrls); if (registryUrls.isEmpty()) { bs.give(); } } public void signalCrawlAttemptCompleted(boolean success, Object cookie, CrawlerStatus status) { String url = (String)cookie; crawlCompleted(url); } public void crawlCompleted(String url) { // Remove urls from registryUrls as they finish crawling (or it is // determine that they don't need to be crawled). When registryUrls // is empty signal the waiting process that it may proceed to load // plugins we're done running crawls on all the plugin registries, // and we can load the plugin classes. registryUrls.remove(url); if (log.isDebug2()) log.debug2("Registry crawl complete: " + url + ", " + registryUrls.size() + " left"); if (registryUrls.isEmpty()) { if (log.isDebug2()) log.debug2("Registry crawls complete"); bs.give(); } } /** * Used only in the case that our semaphore throws an Interrupted * exception -- we can print this list to see what was left. */ public List getRegistryUrls() { return registryUrls; } } /** * CrawlManager callback that causes a check for new plugins. Meant to * be used for asynchronous registry crawls */ public static class RegistryCallback implements CrawlManager.Callback { private PluginManager pluginMgr; private ArchivalUnit registryAu; public RegistryCallback(PluginManager pluginMgr, ArchivalUnit au) { this.pluginMgr = pluginMgr; this.registryAu = au; } public void signalCrawlAttemptCompleted(boolean success, Object cookie, CrawlerStatus status) { if (success) { log.debug2("Registry crawl completed successfully, checking for new plugins"); pluginMgr.processRegistryAus(ListUtil.list(registryAu)); } } } /** * A simple class that wraps information about a loadable plugin, * used during the loading process. */ static class PluginInfo { private Plugin plugin; private ArchivalUnit registryAu; private PluginVersion version; private ClassLoader classLoader; private String cuUrl; private String jarUrl; private boolean isOnLoadablePath = false; public PluginInfo(Plugin plugin, ClassLoader classLoader, String jarUrl) { this.plugin = plugin; this.classLoader = classLoader; this.jarUrl = jarUrl; } public Plugin getPlugin() { return plugin; } public PluginVersion getVersion() { return version; } public void setVersion(PluginVersion version) { this.version = version; } public ClassLoader getClassLoader() { return classLoader; } public String getCuUrl() { return cuUrl; } public void setCuUrl(String cuUrl) { this.cuUrl = cuUrl; } public ArchivalUnit getRegistryAu() { return registryAu; } public void setRegistryAu(ArchivalUnit registryAu) { this.registryAu = registryAu; } public String getJarUrl() { return jarUrl; } public boolean isOnLoadablePath() { return isOnLoadablePath; } public void setIsOnLoadablePath(boolean val) { this.isOnLoadablePath = val; } } }
package org.synchronoss.utils.cpo; import org.apache.log4j.Logger; import java.text.ParseException; import java.util.*; public class QueryParser { private Logger OUT = Logger.getLogger(this.getClass()); public QueryParser() { // do nothing } public List<String> parse(String query) throws ParseException { if (OUT.isDebugEnabled()) OUT.debug("Query: " + query); // query is empty, nothing we can do if (query.length() < 1) return null; // no question marks, nothing to do if (query.indexOf("?") == -1) return null; // upper case the query, to make things easier query = query.toUpperCase(); Vector<String> colList = new Vector<String>(); if (query.startsWith("INSERT")) { // query is in the format of: insert into table(col1, col2...) values(val1, val2...) // so we'll use the parens () to parse int colParenStart = query.indexOf("("); if (colParenStart == -1) throw new ParseException("Unable to locate starting parenthesis for the column names.", -1); int colParenEnd = query.indexOf(")", colParenStart); if (colParenEnd == -1) throw new ParseException("Unable to locate ending parenthesis for the column names.", -1); int valParenStart = query.indexOf("(", colParenEnd); if (valParenStart == -1) throw new ParseException("Unable to locate starting parenthesis for the column values.", -1); int valParenEnd = query.indexOf(")", valParenStart); if (valParenEnd == -1) throw new ParseException("Unable to locate ending parenthesis for the column values.", -1); String[] cols = query.substring(colParenStart + 1, colParenEnd).split(","); String[] vals = query.substring(valParenStart + 1, valParenEnd).split(","); // if cols or vals is null, it means we couldn't find any if (cols == null || vals == null) return null; if (OUT.isDebugEnabled()) { OUT.debug("Found cols: " + cols.length); OUT.debug("Found vals: " + vals.length); } if (cols.length != vals.length) throw new ParseException("You seem to have " + cols.length + " columns, and " + vals.length + " values.\n\nThose numbers should be equal.", -1); // filter out columns that we're not providing values for for (int i = 0; i < vals.length; i++) { String val = vals[i]; if (val.trim().equals("?")) { colList.add(cols[i].trim()); } } } else { // query is in the format of: ...col1 = ? , col2 = ?... // so we'll have to move left to right from the ? looking for the field name String[] chunks = query.split("\\?"); for (String chunk : chunks) { if (OUT.isDebugEnabled()) OUT.debug("Chunk: " + chunk); int idx = chunk.length() - 1; int fieldStartIdx = -1; int fieldEndIdx = -1; boolean found = false; while (!found && (idx >= 0)) { char c = chunk.charAt(idx); if (fieldEndIdx == -1) { // till we find the first char of the end of the field name, ignore spaces and equals if (!(c == ' ' || c == '=')) { // found a char, must be the end of the field name fieldEndIdx = idx; } } else { // if we find a space or a comma, we've reached the beginning of the field name if (c == ' ' || c == ',') { fieldStartIdx = idx + 1; found = true; } } idx } if (found) { String col = chunk.substring(fieldStartIdx, fieldEndIdx + 1); colList.add(col); } } } // at this point, the colList will only have columns that correspond to a ? if (OUT.isDebugEnabled()) { StringBuilder buf = new StringBuilder(); for (String s : colList) { OUT.debug("Column [" + s + "]"); } } return colList; } }
/* * $Id: ListHoldings.java,v 1.42 2012-08-06 11:42:48 easyonthemayo Exp $ */ package org.lockss.servlet; import java.io.IOException; import java.io.OutputStream; import java.util.*; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import org.apache.commons.lang.StringUtils; import org.lockss.config.*; import org.lockss.config.TdbUtil.ContentScope; import org.lockss.config.TdbUtil.ContentType; import org.lockss.daemon.AuHealthMetric; import org.lockss.daemon.MetadataDatabaseUtil; import org.lockss.exporter.biblio.BibliographicItem; import org.lockss.exporter.kbart.*; import org.lockss.exporter.kbart.KbartExporter.OutputFormat; import org.lockss.exporter.kbart.ReportFormat.ReportDataFormat; import org.lockss.exporter.kbart.CoverageNotesFormat; import org.lockss.exporter.kbart.KbartExportFilter.CustomFieldOrdering; import org.lockss.exporter.kbart.KbartExportFilter.FieldOrdering; import org.lockss.exporter.kbart.KbartExportFilter.CustomFieldOrdering.CustomFieldOrderingException; import org.lockss.exporter.kbart.KbartTitle.Field; import org.lockss.plugin.ArchivalUnit; import org.lockss.util.Logger; import org.lockss.util.StringUtil; import org.lockss.util.TimeBase; import org.mortbay.html.Form; import org.mortbay.html.Input; import org.mortbay.html.Table; import org.mortbay.html.Composite; import org.mortbay.html.TextArea; import org.mortbay.html.Heading; import org.mortbay.html.Link; import org.mortbay.html.Page; @SuppressWarnings("serial") public class ListHoldings extends LockssServlet { protected static Logger log = Logger.getLogger("ListHoldings"); static final String PREFIX = Configuration.PREFIX + "listHoldings."; private static final String BREAK = "<br/><br/>"; private static final String ENCODING = KbartExporter.DEFAULT_ENCODING; /** Create a footnote for platforms that don't support the health metric. */ private String notAvailFootnote; /** Enable ListHoldings in UI. Daemon restart required when set to true, * not when set false */ public static final String PARAM_ENABLE_HOLDINGS = PREFIX + "enabled"; public static final boolean DEFAULT_ENABLE_HOLDINGS = false; /** Enable "preserved" option when ListHoldings UI is enabled. */ public static final String PARAM_ENABLE_PRESERVED_HOLDINGS = PREFIX + "enablePreserved"; public static final boolean DEFAULT_ENABLE_PRESERVED_HOLDINGS = true; /** Enable "use metadata" option when "preserved" option is enabled. */ public static final String PARAM_USE_METATATA_FOR_PRESERVED_HOLDINGS = PREFIX + "useMetadataForPreserved"; public static final boolean DEFAULT_USE_METADATA_FOR_PRESERVED_HOLDINGS = false; // These keys are used in the URL for direct access to particular reports. // DO NOT CHANGE public static final String KEY_TITLE_SCOPE = "scope"; public static final String KEY_TITLE_TYPE = "type"; public static final String KEY_OUTPUT_FORMAT = "format"; public static final String KEY_REPORT_FORMAT = "report"; public static final String KEY_COVERAGE_NOTES_FORMAT = "coverageNotesFormat"; public static final String ACTION_EXPORT = "List Titles"; public static final String ACTION_CUSTOM = "Customise Fields"; public static final String ACTION_HIDE_CUSTOM_EXPORT = "Hide Customise Fields"; /** Apply the current customisation. */ public static final String ACTION_CUSTOM_OK = "List Titles"; /** Reset customisation to the defaults. */ public static final String ACTION_CUSTOM_RESET = "Reset"; /** Cancel the current customisation and show the output again. */ public static final String ACTION_CUSTOM_CANCEL = "Cancel"; /** Export the current report in some format. */ public static final String ACTION_CUSTOM_EXPORT = "Export"; public static final String I18N_ACTION_EXPORT = i18n.tr("List Titles"); public static final String I18N_ACTION_CUSTOM = i18n.tr("Customise Fields"); public static final String I18N_ACTION_HIDE_CUSTOM_EXPORT = i18n.tr("Hide Customise Fields"); public static final String I18N_ACTION_CUSTOM_OK = i18n.tr("List Titles"); public static final String I18N_ACTION_CUSTOM_RESET = i18n.tr("Reset"); public static final String I18N_ACTION_CUSTOM_CANCEL = i18n.tr("Cancel"); public static final String I18N_ACTION_CUSTOM_EXPORT = i18n.tr("Export"); public static final String KEY_COMPRESS = "compress"; public static final String KEY_OMIT_EMPTY_COLS = "omitEmptyCols"; public static final String KEY_OMIT_HEADER = "omitHeader"; public static final String KEY_SHOW_HEALTH = "showHealthRatings"; public static final String KEY_CUSTOM = "isCustom"; public static final String KEY_CUSTOM_ORDERING = "ordering"; public static final String KEY_CUSTOM_ORDERING_LIST = "ordering_list"; public static final String KEY_CUSTOM_ORDERING_PREVIOUS_MANUAL = "ordering_list_previous_manual"; /** Session key for storing custom options between customisation screens. */ static final String SESSION_KEY_CUSTOM_OPTS = "org.lockss.servlet.ListHoldings.customOpts"; // These are used in the state variables representing parameters of the export /** Default output format is HTML. */ static final OutputFormat OUTPUT_DEFAULT = OutputFormat.HTML; /** Default report format is KBART. */ static final ReportDataFormat REPORT_DEFAULT = ReportDataFormat.KBART; /** Default scope is the default in the scope enum. */ static final ContentScope SCOPE_DEFAULT = ContentScope.DEFAULT_SCOPE; /** Default type is the default in the type enum. */ static final ContentType TYPE_DEFAULT = ContentType.DEFAULT_TYPE; /** Default coverage notes format is year(volume) ranges. */ static final CoverageNotesFormat COVERAGE_NOTES_DEFAULT = CoverageNotesFormat.YEAR_VOLUME; /** Default field selection and ordering is KBART. */ static final FieldOrdering FIELD_ORDERING_DEFAULT = CustomFieldOrdering.getDefaultOrdering(); /** Default approach to omitting empty fields - inherited from the exporter base class. */ static final Boolean OMIT_EMPTY_COLUMNS_BY_DEFAULT = KbartExporter.omitEmptyFieldsByDefault; /** Default approach to omitting header row is false (do not omit). */ static final Boolean OMIT_HEADER_ROW_BY_DEFAULT = KbartExporter.omitHeaderRowByDefault; /** Default approach to showing health ratings - inherited from the exporter base class. */ static final Boolean SHOW_HEALTH_RATINGS_BY_DEFAULT = KbartExporter.showHealthRatingsByDefault; // Bits of state that must be reset to defaults in resetLocals() /** Holdings scope option. */ private ContentScope selectedScope = ContentScope.DEFAULT_SCOPE; private ContentType selectedType = ContentType.DEFAULT_TYPE; private OutputFormat outputFormat = OUTPUT_DEFAULT; private ReportDataFormat reportDataFormat = REPORT_DEFAULT; private CoverageNotesFormat coverageNotesFormat = COVERAGE_NOTES_DEFAULT; // Bits of state that must be reset in resetLocals() /** A record of the last manual ordering which was applied to an export; * maintained while the servlet is handling a request. */ private String lastManualOrdering; /** Manually specified custom field list. */ private FieldOrdering customFieldOrdering; /** Whether to do an export - set based on the submitted parameters. */ private boolean doExport = false; /** Get the current configuration and the TDB record. */ public void init(ServletConfig config) throws ServletException { super.init(config); } @Override /** Reset the transitory state. */ protected void resetLocals() { // Reset transitory state errMsg = null; statusMsg = null; lastManualOrdering = null; customFieldOrdering = null; doExport = false; // Reset export parameters to defaults selectedScope = ContentScope.DEFAULT_SCOPE; selectedType = ContentType.DEFAULT_TYPE; outputFormat = OUTPUT_DEFAULT; reportDataFormat = REPORT_DEFAULT; coverageNotesFormat = COVERAGE_NOTES_DEFAULT; // Finally reset super locals super.resetLocals(); } /** * Get an enum by name. Upper cases the name so lower case values * can be passed in URLs. * * @param enumClass the enum we want a value from * @param name a string representing the name of the format * @return an enum, of the type T, with the specified name, or null if none was found */ /*protected static <T extends Enum<T>> T byName(String name) { return byName(name, null); }*/ /** * Get an OutputFormat by name, or the default if the name cannot be parsed. * * @param name a string representing the name of the format * @param def the default to return if the name is invalid * @return an OutputFormat with the specified name, or the default */ /*protected static <T extends Enum<T>> T byName(String name, T def) { log.debug("XXX name "+name+" def "+def); try { if (def==null) return (T)T.valueOf(T.class, name.toUpperCase()); return (T)def.valueOf(def.getClass(), name.toUpperCase()); } catch (Exception e) { e.printStackTrace(); return def; } }*/ /** * Handle a request - if there is a format URL param, show the appropriate * default format; otherwise if it is a form submission show custom format; * otherwise show the page. The main page is shown if the params indicate so * or errors occur. Otherwise the relevant values are set and the code falls * through to the end of the method where the export is performed. * <p> * The bare minimum for an export to occur is the output format; all other * values can be set to defaults. If the output format is not set, then the * options are shown. If the export is customised, one of the custom submit * actions must have a value. * </p> */ public void lockssHandleRequest() throws IOException { errMsg = null; statusMsg = null; // Create a footnote if options are not available on this platform. if (!AuHealthMetric.isSupported()) { /*String fn = String.format("Not available on this platform (%s).", PlatformUtil.getInstance());*/ String fn = i18n.tr("Not available on this platform."); notAvailFootnote = addFootnote(fn); } // Get a set of custom opts, constructed with defaults if necessary KbartCustomOptions customOpts = getSessionCustomOpts(); Properties params = getParamsAsProps(); // Output format parameters (from URL) // Set the output format if specified (do not set a default as // this param indictates whether an export has been requested). outputFormat = OutputFormat.byName(params.getProperty(KEY_OUTPUT_FORMAT)); // Set other arguments to defaults unless specified reportDataFormat = ReportDataFormat.byName(params.getProperty(KEY_REPORT_FORMAT), REPORT_DEFAULT); coverageNotesFormat = CoverageNotesFormat.byName(params.getProperty(KEY_COVERAGE_NOTES_FORMAT), COVERAGE_NOTES_DEFAULT); selectedScope = ContentScope.byName(params.getProperty(KEY_TITLE_SCOPE), SCOPE_DEFAULT); selectedType = ContentType.byName(params.getProperty(KEY_TITLE_TYPE), TYPE_DEFAULT); // Set compression from the output format //if (outputFormat!=null) this.isCompress = outputFormat.isCompressible(); // Omit empty columns - use the option supplied from the form, or the // default if one of the other outputs was chosen boolean omitEmptyColumns = Boolean.valueOf( params.getProperty(KEY_OMIT_EMPTY_COLS, OMIT_EMPTY_COLUMNS_BY_DEFAULT.toString()) ); // Omit header - use the option supplied from the form, or the default boolean omitHeader = Boolean.valueOf( params.getProperty(KEY_OMIT_HEADER, OMIT_HEADER_ROW_BY_DEFAULT.toString()) ); // Show health ratings - use the option supplied from the form, or the // default if one of the other outputs was chosen boolean showHealthRatings = Boolean.valueOf( params.getProperty(KEY_SHOW_HEALTH, SHOW_HEALTH_RATINGS_BY_DEFAULT.toString()) ); // Custom HTML parameters (from custom form) String action = params.getProperty(ACTION_TAG, ""); // Manual custom ordering received from the text area String manualOrdering = params.getProperty(KEY_CUSTOM_ORDERING_LIST); // Last manual ordering (only received from customisation page, as ordering_list) // We set it if available, otherwise set it to the current ordering lastManualOrdering = params.getProperty(KEY_CUSTOM_ORDERING_PREVIOUS_MANUAL, manualOrdering); // Set lastManualOrdering unless a reset was requested, in which case we need the old value. //if (!action.equals(ACTION_CUSTOM_RESET)) lastManualOrdering = manualOrdering; // Set custom ordering to default this.customFieldOrdering = FIELD_ORDERING_DEFAULT; // Is this a custom output? Show custom options or apply to an export. // Set isCustom based on "customise" submit action // or "isCustom" flag in custom form; default false. boolean isCustom = (!StringUtil.isNullString(action) && action.equals(ACTION_CUSTOM)) || Boolean.valueOf(params.getProperty(KEY_CUSTOM, "false")); // Are we exporting? Export button pressed, or custom output and OK/cancel. // OR Minimal args (outputFormat) configured and no action. this.doExport = (outputFormat!=null && StringUtil.isNullString(action)) || action.equals(ACTION_EXPORT) || (isCustom && (action.equals(ACTION_CUSTOM_OK) || action.equals(ACTION_CUSTOM_CANCEL)) ); // If custom output, set the field ordering and omit flag if (isCustom) { // If custom export requested (from the output page) or a customisation was // okayed, set the custom ordering to the supplied manual ordering. If an // export is validated, set the last manual ordering. if (action.equals(ACTION_HIDE_CUSTOM_EXPORT)) { // hide custom form isCustom = false; } else if (action.equals(ACTION_CUSTOM) || action.equals(ACTION_CUSTOM_OK)) { // Try and parse the manual ordering into a list of valid field names setCustomFieldOrdering(manualOrdering); if (doExport) lastManualOrdering = manualOrdering; } // Cancel the customisation and set the ordering to the previously // applied value (from the session) else if (action.equals(ACTION_CUSTOM_CANCEL)) { setCustomFieldOrdering(manualOrdering); if (doExport) manualOrdering = lastManualOrdering; omitEmptyColumns = customOpts.isOmitEmptyColumns(); omitHeader = customOpts.isOmitHeader(); } // Reset the ordering customisation to the previous value else if (action.equals(ACTION_CUSTOM_RESET)) { //customFieldOrdering = FIELD_ORDERING_DEFAULT; setCustomFieldOrdering(lastManualOrdering); //omitEmptyColumns = OMIT_EMPTY_COLUMNS_BY_DEFAULT; } // Create an object encapsulating the custom HTML options, and store it // in the session. customOpts = new KbartCustomOptions(omitEmptyColumns, omitHeader, showHealthRatings, customFieldOrdering); putSessionCustomOpts(customOpts); } // If this is not a valid custom or one-per-line output, reset the // session customisation else resetSessionOptions(); // Just display the page if there is no export happening if (!doExport) { log.debug("No export requested; showing "+(isCustom?"custom":"main")+" options"); // Show the appropriate half of the page depending on whether we are customising displayPage(isCustom); return; } // Now we are doing an export - create the exporter KbartExporter kexp = createExporter(outputFormat, selectedScope, selectedType, reportDataFormat, coverageNotesFormat); // Make sure the exporter was properly instantiated if (kexp==null) { log.debug("No exporter; showing main options"); displayPage(); return; } // Do the export doExport(kexp); } /** * Attempt to set the custom field ordering using the given ordering string. If * the set fails, the errMsg is set and the doExport variable is set to false; * @param ordering * @return whether the set succeeded */ private boolean setCustomFieldOrdering(String ordering) { boolean success = false; try { this.customFieldOrdering = new CustomFieldOrdering(ordering); success = true; } catch (CustomFieldOrderingException e) { errMsg = e.getLocalizedMessage(); success = false; doExport = false; } return success; } /** * Make an exporter to be used in an export; this involves extracting and * converting titles from the TDB and passing to the exporter's constructor. * The exporter is configured with the basic settings; further configuration * may be necessary for custom exports. * * @param outputFormat the output format for the exporter * @param scope the scope of titles to export * @param reportDataFormat the format of the report * @param coverageNotesFormat the format of the coverage notes field * @return a usable exporter, or null if one could not be created */ private KbartExporter createExporter(OutputFormat outputFormat, ContentScope scope, ContentType type, ReportDataFormat reportDataFormat, CoverageNotesFormat coverageNotesFormat) { // The following counts the number of TdbTitles informing the export, by // processing the list of AUs in the given scope. It is provided as // information in the export, but is actually a little meaningless and // should probably be omitted. int numTdbTitles = TdbUtil.getNumberTdbTitles(scope, type); KbartCustomOptions opts = getSessionCustomOpts(false); // The list of KbartTitles to export; each title represents a TdbTitle // containing particular types of AU, over a particular range of coverage. List<KbartTitle> titles = getKbartTitlesForExport(scope, type); //KbartTitleIterator titles = getKbartTitlesForExport(scope); /*log.info(String.format("Creating exporter for %d titles in scope %s\n", titles.size(), scope));*/ log.info( i18n.tr("Creating exporter for titles of type {0} in scope {1}\n", type, scope) ); // Return if there are no titles errMsg = i18n.tr("No {0} titles of type {1} for export.", scope, type); if (titles.isEmpty()) { return null; } // Override the customisation options according to this ReportDataFormat's // preferences. reportDataFormat.overrideCustomOptions(opts); if (reportDataFormat.hasCoverageNotesFormat()) coverageNotesFormat = reportDataFormat.getCoverageNotesFormat(); if (reportDataFormat.hasOutputFormat()) outputFormat = reportDataFormat.getOutputFormat(); // Process the titles using a ReportFormat, to add supplementary data or // amalgamate records as required titles = ReportFormat.process(titles, coverageNotesFormat, reportDataFormat); // Create a filter KbartExportFilter filter; if (opts !=null) { filter = new KbartExportFilter(titles, opts.getFieldOrdering(), opts.isOmitEmptyColumns(), opts.isOmitHeader(), opts.isShowHealthRatings()); } else { filter = new KbartExportFilter(titles); } // Create and configure an exporter KbartExporter kexp = outputFormat.makeExporter(titles, filter); kexp.setTdbTitleTotal(numTdbTitles); kexp.setContentScope(scope); // Set an HTML form for the HTML output if necessary if (kexp.getOutputFormat().isHtml()) { kexp.setHtmlCustomForm(makeHtmlCustomForm()); } return kexp; } /** * Get the list of TdbTitles or AUs in the given scope, and turn them into * KbartTitles which represent the coverage ranges available for titles in * the scope. * * @param scope the scope of titles to create * @return an iterator over KbartTitles */ /*private KbartTitleIterator getKbartTitlesForExport(ContentScope scope) { // If we are exporting in a scope where ArchivalUnits are not available, // act on a list of TdbTitles, with their full AU ranges. if (!scope.areAusAvailable) { Collection<TdbTitle> tdbTitles = TdbUtil.getTdbTitles(scope); return KbartTitleIterator.getKbartTitleIterator(tdbTitles); //titles = KbartConverter.convertTitles(tdbTitles); } // Otherwise we need to look at the lists of individual AUs in order to // calculate ranges else { // Whether the output will include any range fields; if there is no custom // ordering, then the default will be used, which will include range fields boolean rangeFieldsIncluded = KbartExportFilter.includesRangeFields( getSessionCustomOpts().getFieldOrdering().getOrdering()); Collection<ArchivalUnit> aus = TdbUtil.getAus(scope); Map<TdbTitle, List<ArchivalUnit>> map = TdbUtil.mapTitlesToAus(aus); return KbartTitleIterator.getKbartTitleIterator(map.values().iterator(), getShowHealthRatings(), rangeFieldsIncluded); } }*/ /** * Get the list of TdbTitles or AUs in the given scope, and turn them into * KbartTitles which represent the coverage ranges available for titles in * the scope. It is also now possible to specify a ContentType in order to * filter the list on books or journals. * * @param scope the scope of titles to create * @param type the type of titles to include * @return a list of KbartTitles */ private List<KbartTitle> getKbartTitlesForExport(ContentScope scope, ContentType type) { List<KbartTitle> titles; Iterator<KbartTitle> titleIterator; // If we are exporting in a scope where ArchivalUnits are not available, // act on a list of TdbTitles, with their full AU ranges. if (!scope.areAusAvailable) { Collection<TdbTitle> tdbTitles = TdbUtil.getTdbTitles(scope, type); // TODO Sort the TdbTitles first if we are expecting an iterator back (??) titles = KbartConverter.convertTitles(tdbTitles); // TODO titleIterator = new KbartConverter.TdbTitleKbartTitleIterator(tdbTitles.iterator()); } // Otherwise we need to look at the lists of individual AUs in order to // calculate ranges else { // Whether the output will include any range fields; if there is no custom // ordering, then the default will be used, which will include range fields boolean rangeFieldsIncluded = KbartExportFilter.includesRangeFields( getSessionCustomOpts().getFieldOrdering().getOrdering()); if (scope == ContentScope.COLLECTED && useMetadataForPreserved()) { // try listing collected content from the metadata database first; // list of bibliographic items is assumed to be sorted by ISSN // TODO (PJG) note: should return AUs from DB and // show aggregate health of AU for each title List<? extends BibliographicItem> items = MetadataDatabaseUtil.getBibliographicItems(); if (items.size() > 0) { log.debug2("Found bibliographic items: " + items.size()); titles = new ArrayList<KbartTitle>(); int i = 0; if (i < items.size()) { for (int j = i+1; j <= items.size(); j++) { String issni = items.get(i).getIssn(); String issnj = items.get(j).getIssn(); // convert portion of bibliographic items list with same ISSN if ( (j == items.size()) || (issni!=null && !issni.equals(issnj))) { if (log.isDebug3()) { for (int k = i; k < j; k++) { log.debug3("printIssn: " + items.get(k).getPrintIssn() + " eissn: " + items.get(k).getEissn()); } } List<KbartTitle> currentTitles = KbartConverter.convertTitleToKbartTitles(items.subList(i, j)); titles.addAll(currentTitles); i = j; } } } if (log.isDebug3()) { for (KbartTitle title : titles) { log.debug3("printIssn: " + title.getField(KbartTitle.Field.PRINT_IDENTIFIER) + "eIssn: " + title.getField(KbartTitle.Field.ONLINE_IDENTIFIER)); } } return titles; } } // list content from the title database Collection<ArchivalUnit> aus = TdbUtil.getAus(scope, type); Map<TdbTitle, List<ArchivalUnit>> map = TdbUtil.mapTitlesToAus(aus); titles = KbartConverter.convertTitleAus(map.values(), getShowHealthRatings(), rangeFieldsIncluded); //TODO titleIterator = new KbartConverter.AuKbartTitleIterator( // map.values().iterator(), getShowHealthRatings(), rangeFieldsIncluded); } // TODO Sort here if not performed in KbartConverter return titles; } /** * Assign an HTML form of custom options to the exporter if necessary. * @param kexp the exporter */ /*private void assignHtmlCustomForm(KbartExporter kexp) { if (kexp.getOutputFormat().isHtml()) { kexp.setHtmlCustomForm(makeHtmlCustomForm()); } }*/ /** * Use the supplied exporter to export the data to the given output stream. * * @param kexp an exporter to use for export * @param out an output stream for the export * @throws IOException */ public void doExport(KbartExporter kexp, OutputStream out) throws IOException { long s = TimeBase.nowMs(); kexp.export(out); log.debug("Export took approximately " + StringUtil.timeIntervalToString(TimeBase.msSince(s))); out.flush(); out.close(); } /** * Perform an export of the data to the selected output stream. This * involves getting a TDB record from the system config, converting * the appropriate sections of it into KBART format, then emitting * that title by title. * * @param kexp an exporter to use for export * @throws IOException */ private void doExport(KbartExporter kexp) throws IOException { OutputFormat outputFormat = kexp.getOutputFormat(); // Set the content to be a downloadable file if appropriate if (outputFormat.asFile()) { String filename = kexp.getFilename(); String theFile = kexp.isCompress() ? filename+".zip" : filename; resp.setHeader( "Content-Disposition", "attachment; filename=" + theFile ); } // Set content headers based on the output format resp.setContentType( (kexp.isCompress() ? "application/zip" : outputFormat.getMimeType()) + ";charset="+ENCODING); resp.setCharacterEncoding(ENCODING); //resp.setContentLength( ); // Export to the response OutputStream doExport(kexp, resp.getOutputStream()); // Check errors (Note: the response has already been written by here, so // there is no point setting the err/status msgs) List<String> errs = kexp.getErrors(); log.debug("errs: " + errs); if (!errs.isEmpty()) { errMsg = StringUtil.separatedString(errs, "<br>"); } else { statusMsg = "File(s) written"; } } /** * Constructs a string representing the direct update URL of the default output. * * @return a string URL indicating the direct address for default output */ public String getDefaultUpdateUrl() { return srvAbsURL(myServletDescr(), "format=" + OUTPUT_DEFAULT.name()); } /** * Determine whether "preserved" option is enabled. * * @return <code>true</code> if "preserved" option is enabled. */ private boolean isEnablePreserved() { return CurrentConfig.getBooleanParam(PARAM_ENABLE_PRESERVED_HOLDINGS, DEFAULT_ENABLE_PRESERVED_HOLDINGS); } /** * Determine whether "metadata" option is enabled for preserved content. * * @return <code>true</code> if use metadata option is enabled */ private boolean useMetadataForPreserved() { return CurrentConfig.getBooleanParam( PARAM_USE_METATATA_FOR_PRESERVED_HOLDINGS, DEFAULT_USE_METADATA_FOR_PRESERVED_HOLDINGS); } /** * Generate a table with the page components and options. * * @param custom whether to show the customisation options * @return a Jetty table with all the page's options */ protected Table layoutTableOfOptions(boolean custom) { // Get the path to this servlet so we can postfix output format path // String thisPath = myServletDescr().path; Table tab = new Table(0, "align=\"center\" width=\"80%\""); //addBoxSummary(tab); tab.newRow(); tab.newCell("align=\"center\""); Tdb tdb = TdbUtil.getTdb(); if (tdb==null || tdb.isEmpty()) { tab.add(i18n.tr("No titlesets are defined.")); addBlankRow(tab); return tab; } // Create a form for whatever options we are showing Form form = ServletUtil.newForm(srvURL(myServletDescr())); form.add(new Input(Input.Hidden, "isForm", "true")); if (isEnablePreserved()) { form.add(i18n.tr("View or export a list of titles " + "that are available for collection, configured for collection, " + "or actually collected in your LOCKSS box." )); // Footnote for HealthMetric-based preserved option /*form.add(addFootnote("Titles in the 'ingested' output are " + "included based on a metric which assigns each configured volume " + "a health value. This health value is currently experimental and the " + "output of this option should not yet be considered authoritative." ));*/ /*form.add(addFootnote("Titles in the 'collected' output are " + "included based on whether each configured volume appears " + "to have 'substance', that is whether enough material has been " + "ingested." ));*/ } else { form.add(i18n.tr("View or export a list of titles " + "available for collection, or configured for collection in " + "your LOCKSS box." )); } form.add(BREAK); form.add(i18n.tr( "There are {0} titles available for collection, from {1} publishers.", tdb.getTdbTitleCount(), tdb.getTdbPublisherCount() )); form.add(BREAK); // Add an option to select the scope of exported holdings form.add(layoutScopeOptions()); // Add an option to select the type of exported holdings form.add(layoutTypeOptions()); // Add compress option (disabled as the CSV output is not very large) //tab.newRow(); //tab.newCell("align=\"center\""); //tab.add(ServletUtil.checkbox(this, KEY_COMPRESS, KEY_COMPRESS, "Compress the output", false)); // Create a sub table within the form Table subTab = new Table(0, "align=\"center\" width=\"80%\""); subTab.newRow(); subTab.newCell("align=\"center\""); addReportFormatOptions(subTab); subTab.newRow(); subTab.newCell("align=\"center\""); addOutputFormatOptions(subTab); subTab.newRow(); subTab.newCell("align=\"center\""); //addBlankRow(subTab); subTab.add(BREAK); subTab.newRow(); subTab.newCell("align=\"center\""); // Add the appropriate options to the sub table in the form if (custom) { // Add "hide custom" button at top ServletUtil.layoutSubmitButton(this, subTab, ACTION_TAG, ACTION_HIDE_CUSTOM_EXPORT, I18N_ACTION_HIDE_CUSTOM_EXPORT, false, true); // Add HTML customisation options subTab.add(new Heading(3, I18N_ACTION_CUSTOM)); layoutFormCustomOpts(subTab); subTab.add(BREAK); ServletUtil.layoutSubmitButton(this, subTab, ACTION_TAG, ACTION_CUSTOM_OK, I18N_ACTION_CUSTOM_OK, false, true); } else { // Show customise button and advice ServletUtil.layoutSubmitButton(this, subTab, ACTION_TAG, ACTION_CUSTOM, I18N_ACTION_CUSTOM, false, true); if (isEnablePreserved()) { subTab.add(BREAK + i18n.tr("By default, list is in the industry-standard KBART " + "format. Alternatively you can customise the list to define " + "which columns are visible and in what order they appear. ") + (AuHealthMetric.isSupported() ? i18n.tr("Use this option also to add health ratings to the output.") : "") + BREAK); } else { subTab.add(BREAK+ i18n.tr("By default, list is in the industry-standard KBART " + "format. Alternatively you can customise the list to define " + "which columns are visible and in what order they appear. ") + BREAK); } // Show the option to customise the export details, which are KBART by default: //form.add(new Input(Input.Hidden, KEY_TITLE_SCOPE, selectedScope.name())); form.add(new Input(Input.Hidden, KEY_COVERAGE_NOTES_FORMAT, COVERAGE_NOTES_DEFAULT.toString())); form.add(new Input(Input.Hidden, KEY_CUSTOM_ORDERING_LIST, getOrderingAsCustomFieldList(FIELD_ORDERING_DEFAULT))); form.add(new Input(Input.Hidden, KEY_OMIT_EMPTY_COLS, htmlInputTruthValue(false))); form.add(new Input(Input.Hidden, KEY_OMIT_HEADER, htmlInputTruthValue(false))); // Add the submit at the bottom ServletUtil.layoutSubmitButton(this, subTab, ACTION_TAG, ACTION_EXPORT, I18N_ACTION_EXPORT); } // Add some space addBlankRow(tab); addBlankRow(tab); // Add the sub table to the form, and the form to the main table form.add(subTab); tab.newRow(); tab.newCell("align=\"center\""); tab.add(form); return tab; } /** * Layout output data format options (CSV, TSV, screen). * @param tab */ private void addOutputFormatOptions(Table tab) { // Add default output formats //tab.add("Please choose one of the following actions.<br/>"); tab.newRow(); tab.newCell("align=\"center\" valign=\"middle\""); tab.add(i18n.tr("Output: ")); for (OutputFormat fmt : OutputFormat.values()) { boolean selected = outputFormat!=null ? fmt==outputFormat : fmt==OUTPUT_DEFAULT; tab.add(ServletUtil.radioButton(this, KEY_OUTPUT_FORMAT, fmt.name(), fmt.getLabel(), selected)); tab.add(addFootnote(fmt.getFootnote())); tab.add(" &nbsp; "); } } private void addReportFormatOptions(Table tab) { tab.newRow(); tab.newCell("align=\"center\" valign=\"middle\""); tab.add(i18n.tr("Format: ")); for (ReportDataFormat fmt : ReportDataFormat.values()) { boolean selected = reportDataFormat!=null ? fmt==reportDataFormat : fmt==REPORT_DEFAULT; tab.add(ServletUtil.radioButton(this, KEY_REPORT_FORMAT, fmt.name(), fmt.getLabel(), selected)); tab.add(addFootnote(fmt.getFootnote())); tab.add(" &nbsp; "); } } /** * Layout coverage note format options. * @param tab */ private void addCoverageNoteFormatOptions(Table tab) { tab.newRow(); tab.newCell("align=\"center\" valign=\"middle\""); //tab.add("Format: "); tab.add("<br/>"+i18n.tr("Choose a format for ranges in the coverage field:")+"<br/>"); int count = 0; for (CoverageNotesFormat fmt : CoverageNotesFormat.values()) { // Start a new row every 3 options if (count++%3==0) { tab.newRow(); tab.newCell("align=\"center\" valign=\"middle\""); } boolean selected = coverageNotesFormat!=null ? fmt==coverageNotesFormat : fmt==COVERAGE_NOTES_DEFAULT; tab.add(ServletUtil.radioButton(this, KEY_COVERAGE_NOTES_FORMAT, fmt.name(), fmt.label, selected)); tab.add(" &nbsp; "); } } /** * Create a table listing KBART field labels and descriptions. */ private static Table getKbartFieldLegend() { Table tab = new Table(); //tab.style("border: 1px solid black;"); for (Field f: Field.values()) { tab.newRow(); tab.newCell("align=\"center\""); //if (Field.idFields.contains(f)) tab.add(smallFont("ID")); String lab = f.getLabel(); if (Field.idFields.contains(f)) lab = "<b>"+lab+"</b>"; tab.addCell(smallFont(lab)); tab.addCell(smallFont(f.getDescription())); } return tab; } /** * Layout content scope options. */ private Table layoutScopeOptions() { Table tab = new Table(); tab.newRow(); tab.newCell("align=\"center\" valign=\"middle\""); tab.add(i18n.tr("Show: ")); for (ContentScope scope : ContentScope.values()) { //long s = System.currentTimeMillis(); boolean scopeEnabled = true; if (scope==ContentScope.COLLECTED) { if (!isEnablePreserved()) continue; scopeEnabled = AuHealthMetric.isSupported(); } // NOTE: getNumberTdbTitles() first has to produce a full list of titles; // this is expensive, in particular for the Preserved option, and so // should only be done when required. int total = TdbUtil.getNumberTdbTitles(scope, ContentType.ALL); /*log.debug(String.format("Title count %s took approximately %ss", scope, (System.currentTimeMillis()-s)/1000 ));*/ String label = String.format("%s (%d)", i18n.tr(scope.label), total); tab.add(ServletUtil.radioButton(this, KEY_TITLE_SCOPE, scope.name(), label, scope==selectedScope, scopeEnabled)); if (!scopeEnabled) tab.add(notAvailFootnote); tab.add(" &nbsp; "); } return tab; } /** * Layout content type options. */ private Table layoutTypeOptions() { Table tab = new Table(); tab.newRow(); tab.newCell("align=\"center\" valign=\"middle\""); tab.add(i18n.tr("Title type: ")); for (ContentType type : ContentType.values()) { boolean typeEnabled = true; tab.add(ServletUtil.radioButton(this, KEY_TITLE_TYPE, type.name(), type.label, type==selectedType, typeEnabled)); if (!typeEnabled) tab.add(notAvailFootnote); tab.add(" &nbsp; "); } return tab; } /** * Display top level export options, no custom options. * @throws IOException */ private void displayPage() throws IOException { displayPage(false); } /** * Display top level export options. * @param custom whether to show the HTML customisation options * @throws IOException */ private void displayPage(boolean custom) throws IOException { Page page = newPage(); layoutErrorBlock(page); page.add(layoutTableOfOptions(custom)); // Finish page endPage(page); } /** * Create a form of options for custom HTML output. This includes options to * use a custom field list or ordering, and to omit empty columns or the header. * * @return an HTML form */ private void layoutFormCustomOpts(Composite comp) { // Get the opts from the session KbartCustomOptions opts = getSessionCustomOpts(); // Add a format parameter //comp.add(new Input(Input.Hidden, KEY_FORMAT, OutputFormat.HTML.name())); // Add a hidden field listing the last manual ordering comp.add(new Input(Input.Hidden, KEY_CUSTOM_ORDERING_PREVIOUS_MANUAL, lastManualOrdering)); comp.add(new Input(Input.Hidden, KEY_CUSTOM, "true")); // Add one-per-line customisation opts Table covTab = new Table(); addCoverageNoteFormatOptions(covTab); covTab.add(BREAK); comp.add(covTab); /* form.add("<br/>Choose a field set:<br/>"); // Field ordering options (radio buttons) for (PredefinedFieldOrdering order: PredefinedFieldOrdering.values()) { form.add( ServletUtil.radioButton(this, KEY_CUSTOM_ORDERING, order.name(), order.displayName+" <span style=\"font-style:italic;font-size:small\">("+order.description+")</span><br/>", order==FIELD_ORDERING_DEFAULT) ); } */ comp.add( "<br/>"+i18n.tr("Use the box below to provide a custom ordering for the fields - one field per line.")+ "<br/>"+i18n.tr("Omit any fields you don't want, but include an identifying field for sensible results.")+ //"<br/>"+i18n.tr("(" + StringUtils.join(Field.getLabels(Field.idFields), LIST_COMMA) + ")")+ "<br/>"+i18n.tr("There is a description of the KBART fields next to the box; identifying fields are shown in bold.")+ "<br/><br/>" ); Table tab = new Table(); tab.newRow(); tab.newCell("align=\"center\" valign=\"middle\""); // Add a text area of an appropriate size int taCols = 25; // this should be the longest field width int taLines = Field.values().length+1; tab.add(i18n.tr("Field ordering")+"<br/>"); tab.add(new TextArea(KEY_CUSTOM_ORDERING_LIST, getOrderingAsCustomFieldList(opts.getFieldOrdering())).setSize(taCols, taLines)); // Omit empty columns option tab.add("<br/>"); tab.add(ServletUtil.checkbox(this, KEY_OMIT_EMPTY_COLS, Boolean.TRUE.toString(), i18n.tr("Omit empty columns")+"<br/>", opts.isOmitEmptyColumns())); // Omit header option tab.add("<br/>"); tab.add(ServletUtil.checkbox(this, KEY_OMIT_HEADER, Boolean.TRUE.toString(), i18n.tr("Omit header row")+"<br/>", opts.isOmitHeader())); // Show health option if available if (isEnablePreserved() && getShowHealthRatings()) { tab.add(ServletUtil.checkbox(this, KEY_SHOW_HEALTH, Boolean.TRUE.toString(), i18n.tr("Show health ratings"), opts.isShowHealthRatings(), AuHealthMetric.isSupported())); if (!AuHealthMetric.isSupported()) { tab.add(notAvailFootnote); } else { tab.add(addFootnote(i18n.tr("Health ratings will only be shown for titles which " + "you have configured on your box. The '{0}' export " + "will not show health ratings.", ContentScope.ALL))); } } // Add buttons tab.add("<br/><br/><center>"); ServletUtil.layoutSubmitButton(this, tab, ACTION_TAG, ACTION_CUSTOM_RESET, I18N_ACTION_CUSTOM_RESET, false, true); ServletUtil.layoutSubmitButton(this, tab, ACTION_TAG, ACTION_CUSTOM_CANCEL, I18N_ACTION_CUSTOM_CANCEL, false, true); tab.add("</center>"); // Add a legend for the fields tab.newCell("align=\"left\" padding=\"10\" valign=\"middle\""); tab.add("<br/>"+getKbartFieldLegend()); comp.add(tab); } /** * Turn the selected ordering into a string containing a separated list of fields. * @return */ private static String getOrderingAsCustomFieldList(FieldOrdering fo) { return StringUtils.join(fo.getOrderedLabels(), CustomFieldOrdering.CUSTOM_ORDERING_FIELD_SEPARATOR); /*return StringUtils.join(fo.getOrdering(), CustomFieldOrdering.CUSTOM_ORDERING_FIELD_SEPARATOR);*/ } /** * Construct an HTML form providing a link to customisation options for output. * This consists of a hidden list of ordered output fields, and a variety of * submit buttons, one for accessing the customisation options, and others * for directly exporting the current report in one of the non-HTML formats. * It is intended to be used on the output page. * * @return a Jetty composite element */ private Composite makeHtmlCustomForm() { String servletUrl = srvURL(myServletDescr()); Composite panel = new Composite(); panel.add( makeHtmlCustomExportFormSingleFormat(OutputFormat.HTML, I18N_ACTION_CUSTOM, ACTION_CUSTOM) ); panel.add(" &nbsp; "); // Provide selector for output options, and submit for (OutputFormat fmt : EnumSet.complementOf(EnumSet.of(OutputFormat.HTML))) { panel.add( makeHtmlCustomExportFormSingleFormat(fmt, i18n.tr("Export as {0}", fmt.getLabel()), ACTION_EXPORT) ); panel.add(" &nbsp; "); } panel.add("<p>"); panel.add(new Link(servletUrl, i18n.tr("Return to main title list page"))); panel.add("</p>"); return panel; } /** * Construct an HTML form for diaply on the HTML output page, encoding all * current options along with a single output format option. This * provides a way to directly export the current HTML report in a different * format, or to go to the customisation screen. All options are encoded as * hidden parameters. * * @return a Jetty form */ private Form makeHtmlCustomExportFormSingleFormat(OutputFormat outputFormat, String label, String key) { // Get the opts from the session KbartCustomOptions opts = getSessionCustomOpts(); String servletUrl = srvURL(myServletDescr()); Form form = ServletUtil.newForm(servletUrl); form.style("margin: 0; padding: 0; display: inline"); // Indicate that we are expecting custom out form.add(new Input(Input.Hidden, KEY_CUSTOM, "true")); form.add(new Input(Input.Hidden, KEY_TITLE_SCOPE, selectedScope.name())); form.add(new Input(Input.Hidden, KEY_TITLE_TYPE, selectedType.name())); form.add(new Input(Input.Hidden, KEY_CUSTOM_ORDERING_LIST, getOrderingAsCustomFieldList(opts.getFieldOrdering()))); form.add(new Input(Input.Hidden, KEY_OMIT_EMPTY_COLS, htmlInputTruthValue(opts.isOmitEmptyColumns()))); form.add(new Input(Input.Hidden, KEY_OMIT_HEADER, htmlInputTruthValue(opts.isOmitHeader()))); form.add(new Input(Input.Hidden, KEY_SHOW_HEALTH, htmlInputTruthValue(opts.isShowHealthRatings()))); form.add(new Input(Input.Hidden, KEY_REPORT_FORMAT, reportDataFormat.name())); form.add(new Input(Input.Hidden, KEY_COVERAGE_NOTES_FORMAT, coverageNotesFormat.name())); // The export format form.add(new Input(Input.Hidden, KEY_OUTPUT_FORMAT, outputFormat.name())); ServletUtil.layoutSubmitButton(this, form, ACTION_TAG, key, label, false, false); // TODO distinguish label/value! return form; } /** * Get the string representation of a boolean value, appropriate for use as * the value of a form input. * @param b a boolean value * @return a string which will yield the same value when interpreted as the value of a form input */ private static String htmlInputTruthValue(boolean b) { return b ? "true" : "false"; } /** * Add a blank row to a table or a line break to any other composite element. */ private static void addBlankRow(Composite comp) { if (comp instanceof Table) { Table tab = (Table)comp; tab.newRow(); tab.newCell(); tab.add("&nbsp;"); } else comp.add("<br/>"); } /** * Surround a string with small font tags. * @param s * @return */ private static String smallFont(String s) { return String.format("<font size=\"-1\">%s</font>", s); } /** * Add a summary of the LOCKSS box providing the data, to an HTML table. * @param tab the table to which to add the summary */ private void addBoxSummary(Table tab) { tab.newRow(); tab.newCell("align=\"center\""); tab.add(i18n.tr("This is the KBART Metadata Exporter for {0}", "<b>"+getMachineName()+"</b>.")); tab.newRow(); tab.newCell("align=\"center\""); tab.add(i18n.tr("The permanent KBART output URL for this server is:")+ "<br/><b><font color=\"navy\">"+getDefaultUpdateUrl()+"</font></b>"); addBlankRow(tab); } protected boolean getShowHealthRatings() { KbartCustomOptions opts = getSessionCustomOpts(); return opts == null ? SHOW_HEALTH_RATINGS_BY_DEFAULT : opts.isShowHealthRatings(); } /** * Get the current custom HTML options from the session. If the cookie is not * set, a new set of options is created and added to the session. This is a * convenience method which does not return null. * @return a CustomOptions object from the session */ protected KbartCustomOptions getSessionCustomOpts() { return getSessionCustomOpts(true); } /** * Get the current custom HTML options from the session. If the cookie is not * set, then either null is returned, or a new options object is added to the * session and returned, depending on the value of <code>createIfAbsent</code>. * This can be useful for testing whether custom options are available * * @param createIfAbsent whether to create a new CustomOptions in the session * @return a CustomOptions object from the session, or null */ protected KbartCustomOptions getSessionCustomOpts(boolean createIfAbsent) { Object o = getSession().getAttribute(SESSION_KEY_CUSTOM_OPTS); if (o==null && createIfAbsent) { KbartCustomOptions opts = KbartCustomOptions.getDefaultOptions(); putSessionCustomOpts(opts); return opts; } return o==null ? null : (KbartCustomOptions)o; } /** * Puts the supplied custom HTML options into the session. * @param opts a CustomOptions object */ protected void putSessionCustomOpts(KbartCustomOptions opts) { getSession().setAttribute(SESSION_KEY_CUSTOM_OPTS, opts); } /** * Put a default set of options in the session. */ protected void resetSessionOptions() { putSessionCustomOpts(KbartCustomOptions.getDefaultOptions()); } }
/* Open Source Software - may be modified and shared by FRC teams. The code */ /* the project. */ package org.mcmodding.team1482; import edu.wpi.first.wpilibj.Compressor; import edu.wpi.first.wpilibj.DriverStationLCD; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.Solenoid; import edu.wpi.first.wpilibj.Talon; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Team1482 extends IterativeRobot { /** * This function is run when the robot is first started up and should be * used for any initialization code. */ //timing ints int m_disabledPeriodicLoops; int m_autoPeriodicLoops; int m_telePeriodicLoops; int m_teleEnabledLoops; int m_dsPacketsReceivedInCurrentSecond; int cyclecount; boolean state = false; //Set up demo mode variables boolean m_demoMode = false; boolean m_shooterEnabled = true; double m_driveSpeedModifier = 100; //setup talons Talon drive_left_back = new Talon(1); Talon drive_right_back = new Talon(3); Talon drive_left_front = new Talon(2); Talon drive_right_front = new Talon(4); RobotDrive drive = new RobotDrive(drive_left_front, drive_left_back, drive_right_front, drive_right_back); //Joystick setup Joystick drivestick = new Joystick(1); Joystick shootstick = new Joystick(2); public static int NUM_JOYSTICK_BUTTONS = 16; //joystick buttons boolean[] m_driveStickButtonState = new boolean[(NUM_JOYSTICK_BUTTONS+1)]; boolean[] m_shootStickButtonState = new boolean[(NUM_JOYSTICK_BUTTONS+1)]; //Pressed or heald String[] driveButtons = new String[(NUM_JOYSTICK_BUTTONS+1)]; String[] shootButtons = new String[(NUM_JOYSTICK_BUTTONS+1)]; boolean m_button_1; //Setup compressor Compressor airCompressor = new Compressor(8,1); public Solenoid Shoot = new Solenoid(1); public Solenoid ShootReset = new Solenoid(2); public Solenoid Lift = new Solenoid(3); public Solenoid LiftReset = new Solenoid(4); public Team1482() { System.out.println("Starting constructor!"); for (int buttonNum = 1; buttonNum <= NUM_JOYSTICK_BUTTONS; buttonNum++) { //Set default vales for jpystick button arrays m_driveStickButtonState[buttonNum] = false; m_shootStickButtonState[buttonNum] = false; driveButtons[buttonNum] = null; shootButtons[buttonNum] = null; } } public void robotInit() { System.out.println("Starting RobotInit"); //get smartdashboard variables SmartDashboard.putBoolean("Lift State", false); SmartDashboard.getBoolean("Demo Mode", false); SmartDashboard.getBoolean("Enable shooter?" , true); /* Uncomment code to invert motor*/ // drive.setInvertedMotor(RobotDrive.MotorType.kFrontLeft, true); drive.setInvertedMotor(RobotDrive.MotorType.kFrontRight, true); // drive.setInvertedMotor(RobotDrive.MotorType.kRearLeft, true); drive.setInvertedMotor(RobotDrive.MotorType.kRearRight, true); System.out.println("RobotInit compleated!"); getWatchdog().setEnabled(false); } /** * This function is called at the start of autonomous */ public void autonomousInit() { System.out.println("There is no autonomous code!"); } public void teleopInit() { System.out.println("Starting Teleop!"); //Reset loop counters m_teleEnabledLoops = 0; m_telePeriodicLoops = 0; //set experation and enable watchdog getWatchdog().setEnabled(true); getWatchdog().setExpiration(0.5); airCompressor.start(); //Get smartdashboard variables //m_demoMode = SmartDashboard.getBoolean("Demo Mode"); //this.checkDemoMode(m_teleEnabledLoops, true); } /** * This function is called periodically during operator control */ public void disabledInit() { System.out.println("Dissabled!"); } public void disabledPeriodic() { getWatchdog().feed(); Timer.delay(0.05); } public void teleopPeriodic() { if (isEnabled()) { //double speedModifier; //Get joystick values double drivestick_x = drivestick.getRawAxis(1); double drivestick_y = drivestick.getRawAxis(2); // if (this.checkDemoMode(m_telePeriodicLoops, false)) { // //If is in demo mode apply speed modifier // speedModifier = m_driveSpeedModifier / 100; // drivestick_x = drivestick_x * speedModifier; // drivestick_y = drivestick_y * speedModifier; // //Put joystick values for debugging. // SmartDashboard.putNumber("drivestick_x", drivestick_x); // SmartDashboard.putNumber("drivestick_y", drivestick_y); // //If error in code was made stop the robot and print out error message! // if (drivestick_x > 1 || drivestick_y > 1) { // System.out.println("ERROR!!!!!!!! JOYSTICK VALUE IS GREATOR THAT 1 !!! BIG PROBLEM! DISSABLEING ROBOT "); // drive.stopMotor(); // return; drive.arcadeDrive(drivestick_x, drivestick_y); m_button_1 = drivestick.getRawButton(1); // if (m_button_1.equalsIgnoreCase("pressed")) { // System.out.println("Button 1 pressed!"); // //Reset cycle count // cyclecount = 0; // else if(m_button_1.equalsIgnoreCase("held")) // //Semi auto shooting // common.cycle(Shoot, ShootReset, cyclecount); // cyclecount++; //Increment cycle count //Button press and not pressed before if(m_button_1 && !m_driveStickButtonState[1]){ System.out.println("Pressed!"); //Set the sate of the button m_driveStickButtonState[1] = true; //Extend/Retract lifter state = common.liftSet(state, Lift, LiftReset); }else if(!m_button_1 && m_driveStickButtonState[1]){ System.out.println("Reseting button!"); m_driveStickButtonState[1] = false; } //feed the watchdog getWatchdog().feed(); Timer.delay(0.01); }else{ //Feed the watchdog when dissabled getWatchdog().feed(); Timer.delay(0.04); } } public boolean checkDemoMode(int loops, boolean force) { //See if robot is in dissabled mode every 40 loops if(loops % 40 == 0 || force){ m_demoMode = SmartDashboard.getBoolean("Demo Mode"); } if (m_demoMode) { //excute once every 40 calls if (loops % 40 == 0 || force) { //DEMO MODE CODE HERE! m_shooterEnabled = SmartDashboard.getBoolean("Enable shooter?"); if (!m_shooterEnabled) { System.out.println("Shooter dissabled!"); } m_driveSpeedModifier = (int) SmartDashboard.getNumber("Drive speed modifier"); } return true; } else { return false; } }
package org.webbitserver.netty; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.handler.codec.http.HttpChunkAggregator; import org.jboss.netty.handler.codec.http.HttpContentCompressor; import org.jboss.netty.handler.codec.http.HttpContentDecompressor; import org.jboss.netty.handler.codec.http.HttpRequestDecoder; import org.jboss.netty.handler.codec.http.HttpResponseEncoder; import org.jboss.netty.handler.ssl.SslHandler; import org.webbitserver.EventSourceHandler; import org.webbitserver.HttpHandler; import org.webbitserver.WebServer; import org.webbitserver.WebSocketHandler; import org.webbitserver.WebbitException; import org.webbitserver.handler.DateHeaderHandler; import org.webbitserver.handler.HttpToEventSourceHandler; import org.webbitserver.handler.HttpToWebSocketHandler; import org.webbitserver.handler.PathMatchHandler; import org.webbitserver.handler.ServerHeaderHandler; import org.webbitserver.handler.exceptions.PrintStackTraceExceptionHandler; import org.webbitserver.handler.exceptions.SilentExceptionHandler; import org.webbitserver.helpers.NamingThreadFactory; import org.webbitserver.helpers.SslFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import java.io.InputStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.URI; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import static org.jboss.netty.channel.Channels.pipeline; public class NettyWebServer implements WebServer { public static final long DEFAULT_STALE_CONNECTION_TIMEOUT = 42000; private final SocketAddress socketAddress; private final URI publicUri; protected List<HttpHandler> handlers = new ArrayList<HttpHandler>(); private final List<ExecutorService> executorServices = new ArrayList<ExecutorService>(); private final Executor executor; protected ServerBootstrap bootstrap; private Channel channel; private SSLContext sslContext; protected long nextId = 1; private Thread.UncaughtExceptionHandler exceptionHandler; private Thread.UncaughtExceptionHandler ioExceptionHandler; private ConnectionTrackingHandler connectionTrackingHandler; private StaleConnectionTrackingHandler staleConnectionTrackingHandler; private long staleConnectionTimeout = DEFAULT_STALE_CONNECTION_TIMEOUT; private int maxInitialLineLength = 4096; private int maxHeaderSize = 8192; private int maxChunkSize = 8192; private int maxContentLength = 65536; public NettyWebServer(int port) { this(Executors.newSingleThreadScheduledExecutor(new NamingThreadFactory("WEBBIT-HANDLER-THREAD")), port); } private NettyWebServer(ExecutorService executorService, int port) { this((Executor) executorService, port); // If we created the executor, we have to be responsible for tearing it down. executorServices.add(executorService); } public NettyWebServer(final Executor executor, int port) { this(executor, new InetSocketAddress(port), localUri(port)); } public NettyWebServer(final Executor executor, SocketAddress socketAddress, URI publicUri) { this.executor = executor; this.socketAddress = socketAddress; this.publicUri = publicUri; // Uncaught exceptions from handlers get dumped to console by default. // To change, call uncaughtExceptionHandler() uncaughtExceptionHandler(new PrintStackTraceExceptionHandler()); // Default behavior is to silently discard any exceptions caused // when reading/writing to the client. The Internet is flaky - it happens. connectionExceptionHandler(new SilentExceptionHandler()); //setupDefaultHandlers(); } public void setupDefaultHandlers() { add(new ServerHeaderHandler("nginx/1.5.10")); add(new DateHeaderHandler()); } @Override public NettyWebServer setupSsl(InputStream keyStore, String pass) throws WebbitException { return this.setupSsl(keyStore, pass, pass); } @Override public NettyWebServer setupSsl(InputStream keyStore, String storePass, String keyPass) throws WebbitException { this.sslContext = new SslFactory(keyStore, storePass).getServerContext(keyPass); return this; } @Override public URI getUri() { return publicUri; } @Override public int getPort() { if (publicUri.getPort() == -1) { return publicUri.getScheme().equalsIgnoreCase("https") ? 443 : 80; } return publicUri.getPort(); } @Override public Executor getExecutor() { return executor; } @Override public NettyWebServer staleConnectionTimeout(long millis) { staleConnectionTimeout = millis; return this; } @Override public NettyWebServer add(HttpHandler handler) { handlers.add(handler); return this; } @Override public NettyWebServer add(String path, HttpHandler handler) { return add(new PathMatchHandler(path, handler)); } @Override public NettyWebServer add(String path, WebSocketHandler handler) { return add(path, new HttpToWebSocketHandler(handler)); } @Override public NettyWebServer add(String path, EventSourceHandler handler) { return add(path, new HttpToEventSourceHandler(handler)); } @Override public Future<NettyWebServer> start() { FutureTask<NettyWebServer> future = new FutureTask<NettyWebServer>(new Callable<NettyWebServer>() { @Override public NettyWebServer call() throws Exception { if (isRunning()) { throw new IllegalStateException("Server already started."); } // Configure the server. bootstrap = new ServerBootstrap(); // Set up the event pipeline factory. bootstrap.setPipelineFactory(new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { long timestamp = timestamp(); Object id = nextId(); ChannelPipeline pipeline = pipeline(); if (sslContext != null) { SSLEngine sslEngine = sslContext.createSSLEngine(); sslEngine.setUseClientMode(false); SslHandler ssl = new SslHandler(sslEngine); ssl.setCloseOnSSLException(true); pipeline.addLast("ssl", ssl); } pipeline.addLast("staleconnectiontracker", staleConnectionTrackingHandler); pipeline.addLast("connectiontracker", connectionTrackingHandler); pipeline.addLast("flashpolicydecoder", new FlashPolicyFileDecoder(executor, exceptionHandler, ioExceptionHandler, getPort())); pipeline.addLast("decoder", new HttpRequestDecoder(maxInitialLineLength, maxHeaderSize, maxChunkSize)); pipeline.addLast("aggregator", new HttpChunkAggregator(maxContentLength)); pipeline.addLast("decompressor", new HttpContentDecompressor()); pipeline.addLast("encoder", new HttpResponseEncoder()); pipeline.addLast("compressor", new HttpContentCompressor()); pipeline.addLast("handler", new NettyHttpChannelHandler(executor, handlers, id, timestamp, exceptionHandler, ioExceptionHandler)); return pipeline; } }); staleConnectionTrackingHandler = new StaleConnectionTrackingHandler(staleConnectionTimeout, executor); ScheduledExecutorService staleCheckExecutor = Executors.newSingleThreadScheduledExecutor(new NamingThreadFactory("WEBBIT-STALE-CONNECTION-CHECK-THREAD")); staleCheckExecutor.scheduleWithFixedDelay(new Runnable() { @Override public void run() { staleConnectionTrackingHandler.closeStaleConnections(); } }, staleConnectionTimeout / 2, staleConnectionTimeout / 2, TimeUnit.MILLISECONDS); executorServices.add(staleCheckExecutor); connectionTrackingHandler = new ConnectionTrackingHandler(); ExecutorService bossExecutor = Executors.newSingleThreadExecutor(new NamingThreadFactory("WEBBIT-BOSS-THREAD")); executorServices.add(bossExecutor); ExecutorService workerExecutor = Executors.newSingleThreadExecutor(new NamingThreadFactory("WEBBIT-WORKER-THREAD")); executorServices.add(workerExecutor); bootstrap.setFactory(new NioServerSocketChannelFactory(bossExecutor, workerExecutor, 1)); channel = bootstrap.bind(socketAddress); return NettyWebServer.this; } }); // don't use Executor here - it's just another resource we need to manage - // thread creation on startup should be fine final Thread thread = new Thread(future, "WEBBIT-STARTUP-THREAD"); thread.start(); return future; } public boolean isRunning() { return channel != null && channel.isBound(); } @Override public Future<WebServer> stop() { FutureTask<WebServer> future = new FutureTask<WebServer>(new Callable<WebServer>() { @Override public WebServer call() throws Exception { if (channel != null) { channel.close(); } if (connectionTrackingHandler != null) { connectionTrackingHandler.closeAllConnections(); connectionTrackingHandler = null; } if (bootstrap != null) { bootstrap.releaseExternalResources(); } // shut down all services & give them a chance to terminate for (ExecutorService executorService : executorServices) { shutdownAndAwaitTermination(executorService); } bootstrap = null; if (channel != null) { channel.getCloseFuture().await(); } return NettyWebServer.this; } }); // don't use Executor here - it's just another resource we need to manage - // thread creation on shutdown should be fine final Thread thread = new Thread(future, "WEBBIT-SHUTDOW-THREAD"); thread.start(); return future; } // See JavaDoc for ExecutorService private void shutdownAndAwaitTermination(ExecutorService executorService) { executorService.shutdown(); // Disable new tasks from being submitted try { // Wait a while for existing tasks to terminate if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) { executorService.shutdownNow(); // Cancel currently executing tasks // Wait a while for tasks to respond to being cancelled if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) { System.err.println("ExecutorService did not terminate"); } } } catch (InterruptedException ie) { // (Re-)Cancel if current thread also interrupted executorService.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); } } @Override public NettyWebServer uncaughtExceptionHandler(Thread.UncaughtExceptionHandler exceptionHandler) { this.exceptionHandler = exceptionHandler; return this; } @Override public NettyWebServer connectionExceptionHandler(Thread.UncaughtExceptionHandler ioExceptionHandler) { this.ioExceptionHandler = ioExceptionHandler; return this; } /** * @see HttpRequestDecoder */ public NettyWebServer maxChunkSize(int maxChunkSize) { this.maxChunkSize = maxChunkSize; return this; } /** * @see HttpChunkAggregator */ public NettyWebServer maxContentLength(int maxContentLength) { this.maxContentLength = maxContentLength; return this; } /** * @see HttpRequestDecoder */ public NettyWebServer maxHeaderSize(int maxHeaderSize) { this.maxHeaderSize = maxHeaderSize; return this; } /** * @see HttpRequestDecoder */ public NettyWebServer maxInitialLineLength(int maxInitialLineLength) { this.maxInitialLineLength = maxInitialLineLength; return this; } private static URI localUri(int port) { try { return URI.create("http://" + InetAddress.getLocalHost() .getHostName() + (port == 80 ? "" : (":" + port)) + "/"); } catch (UnknownHostException e) { throw new RuntimeException("can not create URI from localhost hostname - use constructor to pass an explicit URI", e); } } protected long timestamp() { return System.currentTimeMillis(); } protected Object nextId() { return nextId++; } }
package org.mockito.exceptions; import static org.mockito.internal.util.StringJoiner.*; import org.mockito.exceptions.base.HasStackTrace; import org.mockito.exceptions.base.MockitoAssertionError; import org.mockito.exceptions.base.MockitoException; import org.mockito.exceptions.cause.TooLittleInvocations; import org.mockito.exceptions.cause.UndesiredInvocation; import org.mockito.exceptions.cause.WantedAnywhereAfterFollowingInteraction; import org.mockito.exceptions.misusing.InvalidUseOfMatchersException; import org.mockito.exceptions.misusing.MissingMethodInvocationException; import org.mockito.exceptions.misusing.NotAMockException; import org.mockito.exceptions.misusing.NullInsteadOfMockException; import org.mockito.exceptions.misusing.UnfinishedStubbingException; import org.mockito.exceptions.misusing.UnfinishedVerificationException; import org.mockito.exceptions.misusing.WrongTypeOfReturnValue; import org.mockito.exceptions.verification.ArgumentsAreDifferent; import org.mockito.exceptions.verification.NeverWantedButInvoked; import org.mockito.exceptions.verification.NoInteractionsWanted; import org.mockito.exceptions.verification.TooLittleActualInvocations; import org.mockito.exceptions.verification.TooManyActualInvocations; import org.mockito.exceptions.verification.VerifcationInOrderFailure; import org.mockito.exceptions.verification.WantedButNotInvoked; import org.mockito.exceptions.verification.junit.JUnitTool; import org.mockito.internal.debugging.Location; /** * Reports verification and misusing errors. * <p> * One of the key points of mocking library is proper verification/exception * messages. All messages in one place makes it easier to tune and amend them. * <p> * Reporter can be injected and therefore is easily testable. * <p> * Generally, exception messages are full of line breaks to make them easy to * read (xunit plugins take only fraction of screen on modern IDEs). */ public class Reporter { private String pluralize(int number) { return number == 1 ? "1 time" : number + " times"; } public void checkedExceptionInvalid(Throwable t) { throw new MockitoException(join( "Checked exception is invalid for this method!", "Invalid: " + t )); } public void cannotStubWithNullThrowable() { throw new MockitoException(join( "Cannot stub with null throwable!" )); } public void unfinishedStubbing() { throw new UnfinishedStubbingException(join( "Unfinished stubbing detected!", "E.g. thenReturn() may be missing.", "Examples of correct stubbing:", " when(mock.isOk()).thenReturn(true);", " when(mock.isOk()).thenThrow(exception);", " doThrow(exception).when(mock).someVoidMethod();", "Hints:", " 1. missing thenReturn() or mock call inside when()", " 2. stubbed method cannot be final.", " 3. although stubbed methods may return mocks, you cannot inline a mock() call inside a thenReturn method (see issue 53)" )); } public void missingMethodInvocation() { throw new MissingMethodInvocationException(join( "when() requires an argument which has to be a method call on a mock.", "For example:", " when(mock.getArticles()).thenReturn(articles);", "Also make sure the method is not final - you cannot stub final methods." )); } public void unfinishedVerificationException(Location location) { UnfinishedVerificationException exception = new UnfinishedVerificationException(join( "Missing method call for verify(mock) here:", "-> Located at " + location, "", "Example of correct verification:", " verify(mock).doSomething()", "Also make sure the method is not final - you cannot verify final methods.", "" )); throw exception; } public void notAMockPassedToVerify() { throw new NotAMockException(join( "Argument passed to verify() is not a mock!", "Examples of correct verifications:", " verify(mock).someMethod();", " verify(mock, times(10)).someMethod();", " verify(mock, atLeastOnce()).someMethod();" )); } public void nullPassedToVerify() { throw new NullInsteadOfMockException(join( "Argument passed to verify() is null!", "Examples of correct verifications:", " verify(mock).someMethod();", " verify(mock, times(10)).someMethod();", " verify(mock, atLeastOnce()).someMethod();", "Also, if you use @Mock annotation don't miss initMocks()" )); } public void notAMockPassedToWhenMethod() { throw new NotAMockException(join( "Argument passed to when() is not a mock!", "Example of correct stubbing:", " doThrow(new RuntimeException()).when(mock).someMethod();" )); } public void nullPassedToWhenMethod() { throw new NullInsteadOfMockException(join( "Argument passed to when() is null!", "Example of correct stubbing:", " doThrow(new RuntimeException()).when(mock).someMethod();", "Also, if you use @Mock annotation don't miss initMocks()" )); } public void mocksHaveToBePassedToVerifyNoMoreInteractions() { throw new MockitoException(join( "Method requires argument(s)!", "Pass mocks that should be verified, e.g:", " verifyNoMoreInteractions(mockOne, mockTwo);", " verifyZeroInteractions(mockOne, mockTwo);" )); } public void notAMockPassedToVerifyNoMoreInteractions() { throw new NotAMockException(join( "Argument(s) passed is not a mock!", "Examples of correct verifications:", " verifyNoMoreInteractions(mockOne, mockTwo);", " verifyZeroInteractions(mockOne, mockTwo);" )); } public void nullPassedToVerifyNoMoreInteractions() { throw new NullInsteadOfMockException(join( "Argument(s) passed is null!", "Examples of correct verifications:", " verifyNoMoreInteractions(mockOne, mockTwo);", " verifyZeroInteractions(mockOne, mockTwo);" )); } public void notAMockPassedWhenCreatingInOrder() { throw new NotAMockException(join( "Argument(s) passed is not a mock!", "Pass mocks that require verification in order.", "For example:", " InOrder inOrder = inOrder(mockOne, mockTwo);" )); } public void nullPassedWhenCreatingInOrder() { throw new NullInsteadOfMockException(join( "Argument(s) passed is null!", "Pass mocks that require verification in order.", "For example:", " InOrder inOrder = inOrder(mockOne, mockTwo);" )); } public void mocksHaveToBePassedWhenCreatingInOrder() { throw new MockitoException(join( "Method requires argument(s)!", "Pass mocks that require verification in order.", "For example:", " InOrder inOrder = inOrder(mockOne, mockTwo);" )); } public void inOrderRequiresFamiliarMock() { throw new MockitoException(join( "InOrder can only verify mocks that were passed in during creation of InOrder.", "For example:", " InOrder inOrder = inOrder(mockOne);", " inOrder.verify(mockOne).doStuff();" )); } public void invalidUseOfMatchers(int expectedMatchersCount, int recordedMatchersCount) { throw new InvalidUseOfMatchersException(join( "Invalid use of argument matchers!", expectedMatchersCount + " matchers expected, " + recordedMatchersCount + " recorded.", "This exception may occur if matchers are combined with raw values:", " //incorrect:", " someMethod(anyObject(), \"raw String\");", "When using matchers, all arguments have to be provided by matchers.", "For example:", " //correct:", " someMethod(anyObject(), eq(\"String by matcher\"));", "", "For more info see javadoc for Matchers class." )); } public void argumentsAreDifferent(PrintableInvocation wanted, PrintableInvocation actual, HasStackTrace actualStackTrace) { String message = join("Argument(s) are different! Wanted:", wanted.toString(), "-> at " + new Location(), "Actual invocation has different arguments:", actual.toString(), "-> at " + actualStackTrace.getStackTrace()[0], "" ); if (JUnitTool.hasJUnit()) { throw JUnitTool.createArgumentsAreDifferentException(message, wanted.toString(), actual.toString()); } else { throw new ArgumentsAreDifferent(message); } } public void wantedButNotInvoked(PrintableInvocation wanted) { throw new WantedButNotInvoked(join( "Wanted but not invoked:", wanted.toString() )); } public void wantedButNotInvokedInOrder(PrintableInvocation wanted, PrintableInvocation previous, HasStackTrace previousStackTrace) { WantedAnywhereAfterFollowingInteraction cause = new WantedAnywhereAfterFollowingInteraction(join( "Wanted anywhere AFTER following interaction:", previous.toString())); cause.setStackTrace(previousStackTrace.getStackTrace()); throw new VerifcationInOrderFailure(join( "Verification in order failure", "Wanted but not invoked:", wanted.toString() ), cause); } public void tooManyActualInvocations(int wantedCount, int actualCount, PrintableInvocation wanted, HasStackTrace firstUndesired) { throw new TooManyActualInvocations(join( wanted.toString(), "Wanted " + pluralize(wantedCount) + ":", "-> at " + new Location(), "but was " + pluralize(actualCount) + ". Undesired invocation:", "-> at " + firstUndesired.getStackTrace()[0], "" )); } public void neverWantedButInvoked(PrintableInvocation wanted, HasStackTrace firstUndesired) { UndesiredInvocation cause = createUndesiredInvocationCause(firstUndesired); throw new NeverWantedButInvoked(join( wanted.toString(), "Never wanted but invoked!" ), cause); } public void tooManyActualInvocationsInOrder(int wantedCount, int actualCount, PrintableInvocation wanted, HasStackTrace firstUndesired) { UndesiredInvocation cause = createUndesiredInvocationCause(firstUndesired); throw new VerifcationInOrderFailure(join( "Verification in order failure", wanted.toString(), "Wanted " + pluralize(wantedCount) + " but was " + actualCount ), cause); } private UndesiredInvocation createUndesiredInvocationCause(HasStackTrace firstUndesired) { UndesiredInvocation cause = new UndesiredInvocation(join("Undesired invocation:")); cause.setStackTrace(firstUndesired.getStackTrace()); return cause; } public void tooLittleActualInvocations(int wantedCount, int actualCount, PrintableInvocation wanted, HasStackTrace lastActualInvocationStackTrace) { String ending = (lastActualInvocationStackTrace != null)? "-> at " + lastActualInvocationStackTrace.getStackTrace()[0] + "\n" : "\n"; throw new TooLittleActualInvocations(join( wanted.toString(), "Wanted " + pluralize(wantedCount) + ":", "-> at " + new Location(), "But was " + pluralize(actualCount) + ":", ending )); } public void tooLittleActualInvocationsInOrder(int wantedCount, int actualCount, PrintableInvocation wanted, HasStackTrace lastActualStackTrace) { TooLittleInvocations cause = createTooLittleInvocationsCause(lastActualStackTrace); throw new VerifcationInOrderFailure(join( "Verification in order failure", wanted.toString(), "Wanted " + pluralize(wantedCount) + " but was " + actualCount ), cause); } private TooLittleInvocations createTooLittleInvocationsCause(HasStackTrace lastActualInvocationStackTrace) { TooLittleInvocations cause = null; if (lastActualInvocationStackTrace != null) { cause = new TooLittleInvocations(join("Too little invocations:")); cause.setStackTrace(lastActualInvocationStackTrace.getStackTrace()); } return cause; } public void noMoreInteractionsWanted(PrintableInvocation undesired, HasStackTrace actualInvocationStackTrace) { UndesiredInvocation cause = new UndesiredInvocation(join( "Undesired invocation:", undesired.toString() )); cause.setStackTrace(actualInvocationStackTrace.getStackTrace()); throw new NoInteractionsWanted(join("No interactions wanted"), cause); } public void cannotMockFinalClass(Class<?> clazz) { throw new MockitoException(join( "Cannot mock/spy " + clazz.toString(), "Mockito cannot mock/spy following:", " - final classes", " - anonymous classes", " - primitive types" )); } public void cannotStubVoidMethodWithAReturnValue() { throw new MockitoException(join( "Cannot stub a void method with a return value!", "Voids are usually stubbed with Throwables:", " doThrow(exception).when(mock).someVoidMethod();" )); } public void onlyVoidMethodsCanBeSetToDoNothing() { throw new MockitoException(join( "Only void methods can doNothing()!", "Example of correct use of doNothing():", " doNothing().", " doThrow(new RuntimeException())", " .when(mock).someVoidMethod();", "Above means:", "someVoidMethod() does nothing the 1st time but throws an exception the 2nd time is called" )); } public void tooLittleActualInvocationsInAtLeastMode(int wantedCount, int actualCount, PrintableInvocation wanted, HasStackTrace lastActualInvocationStackTrace) { TooLittleInvocations cause = createTooLittleInvocationsCause(lastActualInvocationStackTrace); throw new TooLittleActualInvocations(join( wanted.toString(), "Wanted at least " + pluralize(wantedCount) + " but was " + actualCount ), cause); } public void tooLittleActualInvocationsInOrderInAtLeastMode(int wantedCount, int actualCount, PrintableInvocation wanted, HasStackTrace lastActualStackTrace) { TooLittleInvocations cause = createTooLittleInvocationsCause(lastActualStackTrace); throw new VerifcationInOrderFailure(join( "Verification in order failure", wanted.toString(), "Wanted at least " + pluralize(wantedCount) + " but was " + actualCount ), cause); } public void wrongTypeOfReturnValue(String expectedType, String actualType, String method) { throw new WrongTypeOfReturnValue(join( actualType + " cannot be returned by " + method, method + " should return " + expectedType )); } public void wantedAtMostX(int maxNumberOfInvocations, int foundSize) { throw new MockitoAssertionError(join("Wanted at most " + pluralize(maxNumberOfInvocations) + " but was " + foundSize)); } public void misplacedArgumentMatcher() { throw new InvalidUseOfMatchersException(join( "Misplaced argument matcher detected!", "Somewhere before this line you probably misused Mockito argument matchers.", "For example you might have used anyObject() argument matcher outside of verification or stubbing.", "Here are examples of correct usage of argument matchers:", " when(mock.get(anyInt())).thenReturn(null);", " doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());", " verify(mock).someMethod(contains(\"foo\"))", "Also make sure you're *not* stubbing/verifying a final method with an argument matcher." )); } }
package parking.implementation.gui; import javafx.application.Application; import javafx.application.Platform; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; import javafx.scene.layout.VBox; import javafx.stage.Stage; import parking.api.business.concrete.Parking; import parking.api.business.concrete.ParkingManager; import parking.api.exceptions.ParkingExistsException; import parking.api.exceptions.ParkingNotPresentException; import parking.implementation.logic.Client; import parking.implementation.logic.FloorParkingSpotIdProvider; import parking.implementation.logic.ParkingSpotFactory; import java.util.ArrayList; import java.util.Collection; import java.util.Optional; import java.util.stream.Collectors; public class ParkingGui extends Application { private Stage stage; private GridPane gridPane; private int nbMaxLine = 10; private Collection<Collection<GridPane>> gridPaneParking = new ArrayList<>(); private Collection<Client> clients = new ArrayList<>(); private ParkingManager parkingManager = ParkingManager.getInstance(); private ParkingSpotFactory parkingSpotFactory; public static void main(String[] args) { launch(args); } private MenuBar createMenu() { Menu menuClient = createMenuClient(); Menu menuParking = createMenuParking(); Menu menuSelector = createMenuSelector(); Menu menuQuit = createMenuQuit(); MenuBar menuBar = new MenuBar(); menuBar.getMenus().addAll( menuClient, menuParking, menuSelector, menuQuit ); return menuBar; } private Menu createMenuClient() { Menu menuClient = new Menu("Client"); MenuItem list = new MenuItem("Selectionner"); list.setOnAction(event -> { ClientListStage clientListStage = new ClientListStage(stage, clients); clientListStage.showAndWait(); System.out.println(clients); }); MenuItem nouveau = new MenuItem("Nouveau"); nouveau.setOnAction(event -> { ClientStage clientStage = new ClientStage(stage); clientStage.showAndWait(); clients.add(clientStage.getClient()); }); menuClient.getItems().addAll( list, nouveau ); return menuClient; } private Menu createMenuParking() { Menu menuParking = new Menu("Parking"); MenuItem nouveau = new MenuItem("Nouveau"); nouveau.setOnAction(event -> { ParkingListStage parkingListStage = new ParkingListStage(stage); parkingListStage.showAndWait(); System.out.println(parkingListStage.getChoice()); }); menuParking.getItems().addAll( nouveau ); return menuParking; } private Menu createMenuSelector() { Menu menuSelector = new Menu("AutoSelector"); MenuItem find = new MenuItem("Find a place"); MenuItem undo = new MenuItem("Unselect place"); menuSelector.getItems().addAll( find, undo ); return menuSelector; } private Menu createMenuQuit() { Menu menuQuit = new Menu(); Label quitLabel = new Label("Quit"); quitLabel.setOnMouseClicked(event -> { Alert confirm = new Alert( Alert.AlertType.CONFIRMATION, "Êtes vous sûr de vouloir quitter ?" ); Optional<ButtonType> result = confirm.showAndWait(); if (result.get() == ButtonType.OK) stage.close(); }); menuQuit.setGraphic(quitLabel); return menuQuit; } public void updateGrid(Integer parking, Integer floor) { try { final int[] x = {0}; final int[] y = {0}; parkingManager.getParkingById(parking) .forEach(spot -> { if (y[0] == nbMaxLine) { y[0]++; x[0] = 0; } gridPane.add( new ButtonSpot( spot, spot.getClass().toString(), stage, clients ), x[0]++, y[0] ); }); } catch (ParkingNotPresentException e) { e.printStackTrace(); } } @Override public void start(Stage primaryStage) { this.stage = primaryStage; //add data clients.add(new Client("", "Anonyme", "")); try { ParkingSpotFactory parkingSpotFactory = new ParkingSpotFactory(); parkingSpotFactory.setIdProvider(new FloorParkingSpotIdProvider()); parkingSpotFactory.setNextVehicleType("Car"); ParkingManager.getInstance().newParking(1, "Parking 1").newParkingSpot(parkingSpotFactory, 10); } catch (ParkingExistsException e) { e.printStackTrace(); } updateGrid(0, 1); //create root BorderPane borderPane = new BorderPane(); //create top menu MenuBar menu = createMenu(); VBox vBox = new VBox(); vBox.getChildren().add(menu); vBox.setPrefHeight(menu.getHeight()); borderPane.setTop(vBox); borderPane.setPrefHeight(vBox.getHeight()); borderPane.setCenter(gridPane); Scene scene = new Scene( borderPane, 600, 400 ); primaryStage.setScene(scene); primaryStage.sizeToScene(); primaryStage.setTitle("SWAG Parking"); primaryStage.setOnCloseRequest(event -> Platform.exit()); primaryStage.show(); } }
package puck.parser.gen; import com.nativelibs4java.opencl.CLContext; import puck.package$; import puck.parser.*; import java.util.*; /** * TODO * * @author dlwh */ public abstract class SimpleGenRuleMultiply<C, L> extends JavaFriendlyGenRuleMultiply<C, L> { public static final int WARP_SIZE = 32; public static final int NUM_WARPS = 48; public static final int NUM_SM = 8; public RuleStructure<C, L> structure; private boolean writeDirectToChart; private boolean logSpaceSemiring; public SimpleGenRuleMultiply(RuleStructure<C, L> structure, boolean writeDirectToChart, boolean logSpace) { super(structure, writeDirectToChart); this.structure = structure; this.writeDirectToChart = writeDirectToChart; this.logSpaceSemiring = logSpace; } public abstract List<IndexedUnaryRule<C, L>>[] segmentUnaries(List<IndexedUnaryRule<C, L>> indexedUnaryRules); public abstract List<IndexedBinaryRule<C, L>>[][] segmentBinaries(List<IndexedBinaryRule<C, L>> indexedBinaryRules); public CLBinaryRuleUpdater javaBinaryRuleApplication(List<IndexedBinaryRule<C, L>> indexedBinaryRules, String name, CLContext context) { ArrayList<String> kernelTexts = new ArrayList<String>(); List<IndexedBinaryRule<C, L>>[][] segments = segmentBinaries(indexedBinaryRules); boolean supportsExtendedAtomics = supportsExtendedAtomics(context); for (int s=0; s<segments.length; s++) { kernelTexts.add(binaryKernelText(name+s, segments[s], supportsExtendedAtomics)); } List<RuleKernel> kernels = compileKernels(context, this.<IndexedBinaryRule<C, L>>flatten(segments), kernelTexts); int[] globalSize = {WARP_SIZE * NUM_WARPS, NUM_SM, 1}; int[] wgSize = {WARP_SIZE, 1, 1}; return new CLBinaryRuleUpdater(kernels, globalSize, wgSize, writeDirectToChart); } private String binaryKernelText(String name, List<IndexedBinaryRule<C, L>>[] subsegments, boolean supportsExtendedAtomics) { StringBuilder sb = new StringBuilder(); // determine duplicate parents Set<Integer> allParents = new HashSet<Integer>(); Set<Integer> dupParents = new HashSet<Integer>(); for(int m = 0; m < NUM_SM; ++m) { for(SymId<C, L> sym: getParents(subsegments[m])) { if(allParents.contains(sym.gpu())) { dupParents.add(sym.gpu()); } else { allParents.add(sym.gpu()); } } } if(!dupParents.isEmpty() && supportsExtendedAtomics) { sb.append("#pragma OPENCL EXTENSION cl_khr_global_int32_extended_atomics : enable\n"); } if (logSpaceSemiring) { sb.append(LOG_SPACE_SEMIRING_ADD); } else { sb.append(MAX_SEMIRING_ADD); } sb.append(WRITE_PARENT_ATOMIC); sb.append(CLMaskKernels.maskHeader(structure)); sb.append("\n\n"); // Sort so that LHS priority, then RHS for(List<IndexedBinaryRule<C, L>> rules : subsegments) { Collections.sort(rules, new Comparator<IndexedBinaryRule<C, L>>() { @Override public int compare(IndexedBinaryRule<C, L> o1, IndexedBinaryRule<C, L> o2) { int parent = Integer.compare(o1.rule().parent().gpu(), o2.rule().parent().gpu()); if(parent != 0) return parent; int lhs = Integer.compare(o1.rule().left().gpu(), o2.rule().left().gpu()); if(lhs != 0) return lhs; int rhs = Integer.compare(o1.rule().right().gpu(), o2.rule().right().gpu()); return rhs; } }); } for (int m=0; m<NUM_SM; ++m) { sb.append("static void subpart"+m+"(const mask_t mask, __global volatile float* parents, __global int* parentIndex, int row, __global float* left, __global float* right, int numRows) {\n"); // if (!subsegments[m].isEmpty()) sb.append(String.format("if (%s) return;\n", CLMaskKernels.genCheckIfMaskIsEmpty(structure, "mask", getParents(subsegments[m])))); Map<Integer,String> declaredParents = new HashMap<Integer, String>(); Map<Integer,String> declaredLeft = new HashMap<Integer, String>(); Map<Integer,String> declaredRight = new HashMap<Integer, String>(); if(writeDirectToChart) sb.append("int pi = parentIndex[row];"); Map<Integer,Integer> parentCounts = new HashMap<Integer,Integer>(); for(IndexedBinaryRule<C, L> rule : subsegments[m]) { int parentIndex = rule.rule().parent().gpu(); Integer count = parentCounts.get(parentIndex); if (count == null) { count = 0; } count++; parentCounts.put(parentIndex, count); } int cellSize = package$.MODULE$.roundUpToMultipleOf(Math.max(structure.numNonTerms(), structure.numTerms()), 32); for(IndexedBinaryRule<C, L> rule : subsegments[m]) { int parentIndex = rule.rule().parent().gpu(); String parent = declaredParents.get(parentIndex); if(parent == null) { parent = "parent_" + parentIndex; if(writeDirectToChart) sb.append(String.format("float parent_%d = parents[pi * "+cellSize+" + %d];\n", parentIndex, parentIndex)); else sb.append(String.format("float parent_%d = parents[%d * numRows + row];\n", parentIndex, parentIndex)); declaredParents.put(parentIndex, parent); } int leftIndex = rule.rule().left().gpu(); String left = declaredLeft.get(leftIndex); if(left == null) { left = "left_" + leftIndex; sb.append(String.format("float left_%d = left[%d * numRows + row];\n", leftIndex, leftIndex)); declaredLeft.put(leftIndex, left); } int rightIndex = rule.rule().right().gpu(); String right = declaredRight.get(rightIndex); if(right == null) { right = "right_" + rightIndex; sb.append(String.format("float right_%d = right[%d * numRows + row];\n", rightIndex, rightIndex)); declaredRight.put(rightIndex, right); } sb.append(String.format("%s = semiring_add(%s, %s + %s + %ff);\n", parent, parent, left, right, structure.scores()[rule.ruleId()])); parentCounts.put(parentIndex, parentCounts.get(parentIndex)-1); if (parentCounts.get(parentIndex) == 0) { if(writeDirectToChart) { String dest = String.format("parents[pi * "+cellSize+" + %d]", parentIndex); String src = parent; sb.append(genWriteSymbol(dest, src, false, supportsExtendedAtomics)); // force no atomics // sb.append(genWriteSymbol(dest, src, true, supportsExtendedAtomics)); } else { String dest = String.format("parents[%d * numRows + row]", parentIndex); String src = parent; sb.append(genWriteSymbol(dest, src, !dupParents.contains(parentIndex), supportsExtendedAtomics)); // force no atomics // sb.append(genWriteSymbol(dest, src, true, supportsExtendedAtomics)); } } } // sb.append("// write out\n"); // for(Map.Entry<Integer, String> e: declaredParents.entrySet()) { // sb.append(String.format("parents[%d * numRows + row] = %s;\n", e.getKey(), e.getValue())); // String dest = String.format("parents[%d * numRows + row]", e.getKey()); // String src = e.getValue(); // sb.append(genWriteSymbol(dest, src, !dupParents.contains(e.getKey()), supportsExtendedAtomics)); sb.append("}\n\n"); } sb.append(String.format( " __kernel void %s(__global volatile float* parents," + " __global int* parentIndex, " + " __global float* left," + " __global float* right," + " __global const mask_t* masks, int numRows, int cellsToDo) {\n" + " int numWorkers = get_global_size(0);\n" + " int grammarSubPartition = get_group_id(1);\n" + " for (int row = get_global_id(0); row < cellsToDo; row += numWorkers) {\n" + " const mask_t mask = masks[parentIndex[row]];\n", name)); sb.append("\n\n"); sb.append("switch (grammarSubPartition) {\n"); for (int m=0; m<NUM_SM; ++m) { sb.append("case "+m+": subpart"+m+"(mask, parents, parentIndex, row, left, right, numRows); continue;\n"); } sb.append("default: continue;\n"); sb.append("}\n"); sb.append("}\n"); sb.append("}\n"); return sb.toString(); } public CLUnaryRuleUpdater javaUnaryRuleApplication(List<IndexedUnaryRule<C, L>> indexedUnaryRules, String name, CLContext context) { ArrayList<String> kernelTexts = new ArrayList<String>(); List<IndexedUnaryRule<C, L>>[] segments = segmentUnaries(indexedUnaryRules); for (int s=0; s<segments.length; s++) { kernelTexts.add(unaryKernelText(name+s, segments[s])); } List<RuleKernel> kernels = compileKernels(context, Arrays.asList(segments), kernelTexts); return new CLUnaryRuleUpdater(kernels); } private String unaryKernelText(String name, List<IndexedUnaryRule<C, L>> segment) { StringBuilder sb = new StringBuilder(); if (logSpaceSemiring) { sb.append(LOG_SPACE_SEMIRING_ADD); } else { sb.append(MAX_SEMIRING_ADD); } sb.append("\n\n\n"); sb.append(String.format( " __kernel void %s(__global volatile float* parents, __global float* child, int numRows, int cellsToDo) {\n" + " int numWorkers = get_global_size(0);\n" + " int grammarSubPartition = get_group_id(1);\n" + " for (int row = get_global_id(0); row < cellsToDo; row += numWorkers) {\n", name)); sb.append("\n\n"); Map<Integer,String> declaredParents = new HashMap<Integer, String>(), declaredLeft = new HashMap<Integer, String>(); // todo: reorder to sensible groupings for(IndexedUnaryRule<C, L> rule : segment) { int parentIndex = rule.rule().parent().gpu(); String parent = declaredParents.get(parentIndex); if(parent == null) { parent = "parent_" + parentIndex; sb.append(String.format("float parent_%d = parents[%d * numRows + row];\n", parentIndex, parentIndex)); declaredParents.put(parentIndex, parent); } int childIndex = rule.rule().child().gpu(); String child = declaredLeft.get(childIndex); if(child == null) { child = "child_" + childIndex; sb.append(String.format("float child_%d = child[%d * numRows + row];\n", childIndex, childIndex)); declaredLeft.put(childIndex, child); } sb.append(String.format("%s = semiring_add(%s, %s + %ff);\n", parent, parent, child, structure.scores()[rule.ruleId()])); } sb.append("// write out\n"); for(Map.Entry<Integer, String> e: declaredParents.entrySet()) { sb.append(String.format("parents[%d * numRows + row] = %s;\n", e.getKey(), e.getValue())); } sb.append("}\n"); sb.append("}\n"); return sb.toString(); } public static boolean GRAMMAR_IS_GENERATIVE = true; public static boolean NVIDIA_IS_STILL_STUPID = true; public String genWriteSymbol(String dest, String src, boolean symIsUniqueToSubsegmentation, boolean supportsExtendedAtomics) { // return String.format("write_parent_atomic_nvidia_gen(&%s, %s);\n", dest, src); if(symIsUniqueToSubsegmentation) { return String.format("%s = %s;\n", dest, src); } else if(!logSpaceSemiring && GRAMMAR_IS_GENERATIVE && supportsExtendedAtomics && NVIDIA_IS_STILL_STUPID) { return String.format("write_parent_atomic_nvidia_gen(&%s, %s);\n", dest, src); } else if(!logSpaceSemiring && GRAMMAR_IS_GENERATIVE && supportsExtendedAtomics) { return String.format("write_parent_gen_atomic(&%s, %s);\n", dest, src); } else { return String.format("write_parent_atomic(&%s, %s);\n", dest, src); } } private static final String MAX_SEMIRING_ADD = "" + "inline float semiring_add(float x, float y) {\n"+ " return max(x, y);\n"+ "}\n\n\n"; private static final String LOG_SPACE_SEMIRING_ADD = "" + "inline float semiring_add(float x, float y) {\n"+ " float tmp = x;\n"+ " x = min(x, y);\n"+ " y = max(tmp, y);\n"+ " return y + native_log(1.0f + native_exp(x - y));\n"+ "}\n\n\n"; // floats < 0 are well ordered such that if max(float1, float2) = float1, then min(*(int*)&float1,*(int*)&float2) = *(int*)&float1 // note inversion of min and max // this is for write_atomic_min (because all floats are same sign) // there's a problem if one float is 0.0, but eh. private static final String WRITE_PARENT_ATOMIC = "" + " typedef union { int old; float oldf; } intbox;\n" + " \n" + " inline void write_parent_gen_atomic(volatile __global float* loc, float value) {\n" + " atomic_min((volatile __global int*)loc, *(int*)&value);\n" + " }\n"+ " #ifdef NVIDIA \n" + " inline void write_parent_atomic_nvidia_gen(volatile __global float* loc, float value) {\n" + " volatile __global int* d_ptr = (volatile __global int*)loc;\n" + " int z = *(int*)&value;\n" + " asm volatile(\"atom.global.min.s32 %0, [%1], %2;\" : \"=r\"(z), \"+l\"(d_ptr): \"r\"(z));\n" + " }\n"+ " \n" + " #endif \n" + " inline void write_parent_atomic(volatile __global float* loc, float value) {\n" + " intbox old;\n" + " value = max(*loc, value);\n" + " old.oldf = value;\n" + " \n" + " while((old.old = atomic_cmpxchg((volatile __global int*)loc, old.old, *(int*)&value)) != *(int*)&value) value = semiring_add(value, old.oldf);\n" + " }\n\n\n"; }
package seedu.taskitty.logic.commands; import seedu.taskitty.commons.core.EventsCenter; import seedu.taskitty.commons.core.Messages; import seedu.taskitty.commons.events.ui.IncorrectCommandAttemptedEvent; import seedu.taskitty.model.Model; /** * Represents a command with hidden internal logic and the ability to be * executed. */ public abstract class Command { public static final String[] ALL_COMMAND_WORDS = { AddCommand.COMMAND_WORD, ViewCommand.COMMAND_WORD, FindCommand.COMMAND_WORD, EditCommand.COMMAND_WORD, DeleteCommand.COMMAND_WORD, DoneCommand.COMMAND_WORD, PathCommand.COMMAND_WORD, UndoCommand.COMMAND_WORD, ClearCommand.COMMAND_WORD, RedoCommand.COMMAND_WORD, HelpCommand.COMMAND_WORD, ExitCommand.COMMAND_WORD }; public static final String[] ALL_COMMAND_MESSAGE_PARAMETER = { AddCommand.MESSAGE_PARAMETER, ViewCommand.MESSAGE_PARAMETER, FindCommand.MESSAGE_PARAMETER, EditCommand.MESSAGE_PARAMETER, DeleteCommand.MESSAGE_PARAMETER, DoneCommand.MESSAGE_PARAMETER, PathCommand.MESSAGE_PARAMETER, UndoCommand.MESSAGE_PARAMETER, ClearCommand.MESSAGE_PARAMETER, RedoCommand.MESSAGE_PARAMETER, HelpCommand.MESSAGE_PARAMETER, ExitCommand.MESSAGE_PARAMETER }; public static final String[] ALL_COMMAND_MESSAGE_USAGE = { AddCommand.MESSAGE_USAGE, ViewCommand.MESSAGE_USAGE, FindCommand.MESSAGE_USAGE, EditCommand.MESSAGE_USAGE, DeleteCommand.MESSAGE_USAGE, DoneCommand.MESSAGE_USAGE, PathCommand.MESSAGE_USAGE, UndoCommand.MESSAGE_USAGE, ClearCommand.MESSAGE_USAGE, RedoCommand.MESSAGE_USAGE, HelpCommand.MESSAGE_USAGE, ExitCommand.MESSAGE_USAGE }; public static final String MESSAGE_FORMAT = "Format: "; protected Model model; /** * Constructs a feedback message to summarise an operation that displayed a * listing of tasks. * * @param displaySize * used to generate summary * @return summary message for tasks displayed */ public static String getMessageForTaskListShownSummary(int displaySize) { return String.format(Messages.MESSAGE_PERSONS_LISTED_OVERVIEW, displaySize); } /** * Executes the command and returns the result message. * * @return feedback message of the operation result for display */ public abstract CommandResult execute(); /** * Provides any needed dependencies to the command. Commands making use of * any of these should override this method to gain access to the * dependencies. */ public void setData(Model model) { this.model = model; } /** * Raises an event to indicate an attempt to execute an incorrect command */ protected void indicateAttemptToExecuteIncorrectCommand() { EventsCenter.getInstance().post(new IncorrectCommandAttemptedEvent(this)); } }
package org.pentaho.di.www; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CarteServlet extends HttpServlet { private static final long serialVersionUID = 2434694833497859776L; private AddExportServlet addExportServlet = new AddExportServlet(); private AddJobServlet addJobServlet = new AddJobServlet(); private AddTransServlet addTransServlet = new AddTransServlet(); private AllocateServerSocketServlet allocateServerSocketServlet = new AllocateServerSocketServlet(); private CleanupTransServlet cleanupTransServlet = new CleanupTransServlet(); private GetJobStatusServlet getJobStatusServlet = new GetJobStatusServlet(); private GetSlavesServlet getSlavesServlet = new GetSlavesServlet(); private GetStatusServlet getStatusServlet = new GetStatusServlet(); private GetTransStatusServlet getTransStatusServlet = new GetTransStatusServlet(); private PauseTransServlet pauseTransServlet = new PauseTransServlet(); private PrepareExecutionTransServlet prepareExecutionTransServlet = new PrepareExecutionTransServlet(); private RegisterSlaveServlet registerSlaveServlet = new RegisterSlaveServlet(); private StartExecutionTransServlet startExecutionTransServlet = new StartExecutionTransServlet(); private StartJobServlet startJobServlet = new StartJobServlet(); private StartTransServlet startTransServlet = new StartTransServlet(); private StopJobServlet stopJobServlet = new StopJobServlet(); private StopTransServlet stopTransServlet = new StopTransServlet(); public CarteServlet() { } public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String uri = req.getRequestURI(); if (uri.contains(AddExportServlet.CONTEXT_PATH)) { addExportServlet.doGet(req, resp); } else if (uri.contains(AddJobServlet.CONTEXT_PATH)) { addJobServlet.doGet(req, resp); } else if (uri.contains(AddTransServlet.CONTEXT_PATH)) { addTransServlet.doGet(req, resp); } else if (uri.contains(AllocateServerSocketServlet.CONTEXT_PATH)) { allocateServerSocketServlet.doGet(req, resp); } else if (uri.contains(CleanupTransServlet.CONTEXT_PATH)) { cleanupTransServlet.doGet(req, resp); } else if (uri.contains(GetJobStatusServlet.CONTEXT_PATH)) { getJobStatusServlet.doGet(req, resp); } else if (uri.contains(GetSlavesServlet.CONTEXT_PATH)) { getSlavesServlet.doGet(req, resp); } else if (uri.contains(GetStatusServlet.CONTEXT_PATH)) { getStatusServlet.doGet(req, resp); } else if (uri.contains(GetTransStatusServlet.CONTEXT_PATH)) { getTransStatusServlet.doGet(req, resp); } else if (uri.contains(PauseTransServlet.CONTEXT_PATH)) { pauseTransServlet.doGet(req, resp); } else if (uri.contains(PrepareExecutionTransServlet.CONTEXT_PATH)) { prepareExecutionTransServlet.doGet(req, resp); } else if (uri.contains(RegisterSlaveServlet.CONTEXT_PATH)) { registerSlaveServlet.doGet(req, resp); } else if (uri.contains(StartExecutionTransServlet.CONTEXT_PATH)) { startExecutionTransServlet.doGet(req, resp); } else if (uri.contains(StartJobServlet.CONTEXT_PATH)) { startJobServlet.doGet(req, resp); } else if (uri.contains(StartTransServlet.CONTEXT_PATH)) { startTransServlet.doGet(req, resp); } else if (uri.contains(StopJobServlet.CONTEXT_PATH)) { stopJobServlet.doGet(req, resp); } else if (uri.contains(StopTransServlet.CONTEXT_PATH)) { stopTransServlet.doGet(req, resp); } } }
package src.enigma.calin.entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.projectile.*; import net.minecraft.init.Blocks; import net.minecraft.util.DamageSource; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; import src.enigma.calin.registry.CalinRegistry; import java.util.Random; public class EntityMolotov extends EntityThrowable { public EntityMolotov(World world) { super(world); } public EntityMolotov(World world, EntityLivingBase xBase) { super(world, xBase); } public EntityMolotov(World world, double x, double y, double z) { super(world, x, y, z); } protected void onImpact(MovingObjectPosition xPosition) { this.playSound("dig.glass", 1f, 0f); for (int a = 0; a < 20; a++) { Random x = new Random(); int ax = x.nextInt(6); int bx = x.nextInt(6); int cx = x.nextInt(6); if (this.worldObj.getBlock((int) this.posX + ax - 3, (int) this.posY + cx - 3, (int) this.posZ - bx + 3) == Blocks.air) { this.worldObj.setBlock((int) this.posX + ax - 3, (int) this.posY + cx - 3, (int) this.posZ - bx + 3, Blocks.fire, 0, 2); } } if (xPosition.entityHit != null) { byte b0 = 1; xPosition.entityHit.attackEntityFrom(DamageSource.causeThrownDamage(this, this.getThrower()), (float) b0); EntityLivingBase temp = this.getThrower(); if (temp instanceof EntityPlayer) { EntityPlayer temp2 = (EntityPlayer) temp; if (!temp2.capabilities.isCreativeMode) { temp2.inventory.consumeInventoryItem(CalinRegistry.itemMolotov); } } if (!this.worldObj.isRemote) { this.setDead(); } } for (int j = 0; j < 8; ++j) { this.worldObj.spawnParticle("snowballpoof", this.posX, this.posY, this.posZ, 0.0D, 0.0D, 0.0D); } if (!this.worldObj.isRemote) { this.setDead(); } } }
package org.phenoscape.view; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.Collection; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JCheckBoxMenuItem; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.KeyStroke; import org.apache.log4j.Logger; import org.bbop.framework.GUIManager; import org.bbop.framework.ViewMenu; import org.obo.app.controller.DocumentController.AutosaveChangeListener; import org.obo.app.swing.ResponderChainAction; import org.obo.app.util.CrossPlatform; import org.phenoscape.controller.PhenexController; import edu.stanford.ejalbert.BrowserLauncher; import edu.stanford.ejalbert.exception.BrowserLaunchingExecutionException; import edu.stanford.ejalbert.exception.BrowserLaunchingInitializingException; import edu.stanford.ejalbert.exception.UnsupportedOperatingSystemException; public class MenuFactory { private final PhenexController controller; public MenuFactory(PhenexController controller) { this.controller = controller; } public Collection<? extends JMenuItem> createMenus() { Collection<JMenuItem> menus = new ArrayList<JMenuItem>(); menus.add(this.createFileMenu()); menus.add(this.createEditMenu()); final ViewMenu bbopViewMenu = new ViewMenu(); final JMenuItem perspectivesMenu = bbopViewMenu.getItem(0); final JMenuItem viewMenu = bbopViewMenu.getItem(1); perspectivesMenu.setText("Window"); viewMenu.setText("View"); menus.add(viewMenu); menus.add(this.createORBMenu()); menus.add(perspectivesMenu); menus.add(this.createHelpMenu()); return menus; } private JMenuItem createFileMenu() { final JMenu menu = new JMenu("File"); final Action openAction = new AbstractAction("Open...") { @Override public void actionPerformed(ActionEvent e) { controller.open(); } }; openAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_O, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); menu.add(new JMenuItem(openAction)); final Action importPhenotypeProposals = new AbstractAction("Phenotype proposals...") { @Override public void actionPerformed(ActionEvent e) { controller.openImportPhenotypeProposals(); } }; final JMenu mergeMenu = new JMenu("Import"); mergeMenu.add(new JMenuItem(importPhenotypeProposals)); menu.add(mergeMenu); menu.addSeparator(); final Action saveAction = new AbstractAction("Save") { @Override public void actionPerformed(ActionEvent e) { controller.save(); } }; saveAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); menu.add(new JMenuItem(saveAction)); final Action saveAsAction = new AbstractAction("Save As...") { @Override public void actionPerformed(ActionEvent e) { controller.saveAs(); } }; saveAsAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() | InputEvent.SHIFT_MASK)); menu.add(new JMenuItem(saveAsAction)); final Action exportExcelAction = new AbstractAction("Export for Excel...") { @Override public void actionPerformed(ActionEvent e) { controller.exportToExcel(); } }; menu.add(new JMenuItem(exportExcelAction)); final Action exportBiocreativeAction = new AbstractAction("Export for BioCreative...") { @Override public void actionPerformed(ActionEvent e) { controller.exportForBioCreative(); } }; menu.add(new JMenuItem(exportBiocreativeAction)); if (CrossPlatform.shouldPutExitInFileMenu()) { menu.addSeparator(); final Action exitAction = new AbstractAction("Exit") { @Override public void actionPerformed(ActionEvent e) { GUIManager.exit(0); } }; menu.add(new JMenuItem(exitAction)); } menu.addSeparator(); final Action enableAutosaveAction = new AbstractAction("Enable Autosave") { @Override public void actionPerformed(ActionEvent e) { controller.toggleAutosave(); } }; final JCheckBoxMenuItem autosave = new JCheckBoxMenuItem(enableAutosaveAction); autosave.setSelected(controller.getShouldAutosave()); controller.addAutosaveChangeListener(new AutosaveChangeListener() { @Override public void autosaveSettingChanged(boolean shouldAutosave) { autosave.setSelected(shouldAutosave); } }); menu.add(autosave); return menu; } private JMenuItem createEditMenu() { final JMenu menu = new JMenu("Edit"); final Action undo = this.controller.getUndoController().getUndoAction(); undo.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); menu.add(new JMenuItem(undo)); final Action redo = this.controller.getUndoController().getRedoAction(); redo.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() | InputEvent.SHIFT_MASK)); menu.add(new JMenuItem(redo)); menu.addSeparator(); final Action cutAction = new ResponderChainAction("cut", "Cut"); cutAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_X, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); menu.add(new JMenuItem(cutAction)); final Action copyAction = new ResponderChainAction("copy", "Copy"); copyAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); menu.add(new JMenuItem(copyAction)); final Action pasteAction = new ResponderChainAction("paste", "Paste"); pasteAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_V, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); menu.add(new JMenuItem(pasteAction)); final Action selectAllAction = new ResponderChainAction("selectAll", "Select All"); selectAllAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_A, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); menu.add(new JMenuItem(selectAllAction)); return menu; } private JMenuItem createORBMenu() { final JMenu menu = new JMenu("ORB"); final Action termRequestAction = new AbstractAction("Request New Term...") { @Override public void actionPerformed(ActionEvent e) { controller.runORBTermRequest(); } }; menu.add(new JMenuItem(termRequestAction)); return menu; } private JMenuItem createHelpMenu() { final JMenu menu = new JMenu("Help"); final Action homepageAction = new AbstractAction("Phenex Homepage") { @Override public void actionPerformed(ActionEvent e) { try { (new BrowserLauncher(null)).openURLinBrowser("http: } catch (BrowserLaunchingInitializingException e1) { log().error("Unable to open URL in browser", e1); e1.printStackTrace(); } catch (UnsupportedOperatingSystemException e1) { log().error("Unable to open URL in browser", e1); } catch (BrowserLaunchingExecutionException e1) { log().error("Unable to open URL in browser", e1); } } }; final Action trackerAction = new AbstractAction("Submit Bug Report or Feature Request...") { @Override public void actionPerformed(ActionEvent e) { try { (new BrowserLauncher(null)).openURLinBrowser("https://sourceforge.net/tracker/?func=add&group_id=76834&atid=1116214"); } catch (BrowserLaunchingInitializingException e1) { log().error("Unable to open URL in browser", e1); e1.printStackTrace(); } catch (UnsupportedOperatingSystemException e1) { log().error("Unable to open URL in browser", e1); } catch (BrowserLaunchingExecutionException e1) { log().error("Unable to open URL in browser", e1); } } }; menu.add(homepageAction); menu.add(trackerAction); return menu; } private Logger log() { return Logger.getLogger(this.getClass()); } }
package teamrtg.passableleaves; import java.io.File; import java.util.List; import java.util.Set; import javax.annotation.ParametersAreNonnullByDefault; import net.minecraft.block.SoundType; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.resources.I18n; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommand; import net.minecraft.command.ICommandSender; import net.minecraft.command.NumberInvalidException; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.MobEffects; import net.minecraft.init.SoundEvents; import net.minecraft.potion.PotionEffect; import net.minecraft.server.MinecraftServer; import net.minecraft.util.DamageSource; import net.minecraft.util.IThreadListener; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.util.text.*; import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.config.ConfigElement; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Property; import net.minecraftforge.fml.client.IModGuiFactory; import net.minecraftforge.fml.client.config.GuiConfig; import net.minecraftforge.fml.client.config.IConfigElement; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.event.FMLServerStartingEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent; import net.minecraftforge.fml.common.network.FMLNetworkEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.server.command.CommandTreeBase; import com.google.common.collect.Lists; import mcp.MethodsReturnNonnullByDefault; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import teamrtg.passableleaves.asm.PassableLeavesCore; @SuppressWarnings("unused") @Mod( modid = PassableLeaves.MOD_ID, name = PassableLeaves.MOD_NAME, version = PassableLeaves.MOD_VERSION, dependencies = "required-after:" + PassableLeavesCore.MOD_ID +"@[1.0.0,)", guiFactory = "teamrtg.passableleaves.PassableLeaves$PLGuiConfigFactory" ) public class PassableLeaves { static final String MOD_ID = "passableleaves"; static final String MOD_NAME = "Passable Leaves"; static final String MOD_VERSION = "@MOD_VERSION@"; static final Logger LOGGER = LogManager.getLogger(MOD_ID); static boolean LOCAL_SERVER = true; @Mod.Instance(MOD_ID) private static PassableLeaves instance; @Mod.EventHandler public void initPre (FMLPreInitializationEvent event) { proxy.preInit(event); } @Mod.EventHandler public void init (FMLInitializationEvent event) { proxy.init(event); } @Mod.EventHandler public void initPost (FMLPostInitializationEvent event) { proxy.postInit(event); } @Mod.EventHandler public void addcommand(FMLServerStartingEvent event) { proxy.addCommand(event); } @SidedProxy private static CommonProxy proxy; private abstract static class CommonProxy { void preInit (FMLPreInitializationEvent event) { LOGGER.debug("Initialising configuration"); PLConfig.init(event); LOGGER.debug("Registering network messages"); NetworkDispatcher.init(); LOGGER.debug("Registering a new ConfigSyncHandler"); MinecraftForge.EVENT_BUS.register(new ConfigSyncHandler()); } void init (FMLInitializationEvent event) { } void postInit (FMLPostInitializationEvent event) { PLConfig.sync(); } void addCommand(FMLServerStartingEvent event) { LOGGER.debug("Registering /" + PLCommandTree.CMD_ROOT + " command"); event.registerServerCommand(new PLCommandTree()); } } public static final class ClientProxy extends CommonProxy { @Override public void preInit (FMLPreInitializationEvent event) { super.preInit(event); } @Override public void init (FMLInitializationEvent event) { super.init(event); } @Override public void postInit (FMLPostInitializationEvent event) { super.postInit(event); } @Override public void addCommand(FMLServerStartingEvent event) { super.addCommand(event);} } public static final class ServerProxy extends CommonProxy { @Override public void preInit (FMLPreInitializationEvent event) { super.preInit(event); } @Override public void init (FMLInitializationEvent event) { super.init(event); } @Override public void postInit (FMLPostInitializationEvent event) { super.postInit(event); } @Override public void addCommand(FMLServerStartingEvent event) { super.addCommand(event); } } @ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault static final class PLCommandTree extends CommandTreeBase { private static final int ACCESS_ALL = 0; // everyone private static final int ACCESS_OPS = 2; // only server Ops private static final int ACCESS_ADMIN = 4; // only admins private static final String LANG_KEY_BASE = MOD_ID+".command"; private static final String LANG_KEY_PREFIX_ERROR = LANG_KEY_BASE+".prefix.error"; private static final String LANG_KEY_SETTINGS_HEADER = LANG_KEY_BASE+".setting.header"; private static final String LANG_KEY_CURRENT_SETTING = LANG_KEY_BASE+".setting.current"; private static final String LANG_KEY_VALUE_INVALID = LANG_KEY_BASE+".setting.invalid"; private static final String LANG_KEY_VALUE_OUTOFRANGE = LANG_KEY_BASE+".setting.valueOutOfRange"; private static final String LANG_KEY_ADDENDUM_STATUS = LANG_KEY_BASE+".addendum.status"; private static final String LANG_KEY_ADDENDUM_SAVE = LANG_KEY_BASE+".addendum.save"; private static final Style STYLE_ERROR = new Style().setUnderlined(true).setColor(TextFormatting.DARK_RED); private static final Style STYLE_DKGREEN = new Style().setColor(TextFormatting.DARK_GREEN); private static final Style STYLE_GOLD = new Style().setColor(TextFormatting.GOLD); private static final Style STYLE_DKAQUA = new Style().setColor(TextFormatting.DARK_AQUA); private static final Style STYLE_AQUA = new Style().setColor(TextFormatting.AQUA); private static final Style STYLE_GRAY = new Style().setColor(TextFormatting.GRAY); private static final String CMD_ROOT = "passableleaves"; PLCommandTree() { this.addSubcommand(new CommandStatus(this.getName())); this.addSubcommand(new CommandSave(this.getName())); this.addSubcommand(new CommandTreeDamage(this.getName())); this.addSubcommand(new CommandTreeSpeed(this.getName())); } @Override public int getRequiredPermissionLevel() { return ACCESS_ALL; } // gives everyone access to '/passableleaves status' @Override public String getName() { return CMD_ROOT; } @Override public String getUsage(ICommandSender sender) { ITextComponent ret = new TextComponentString(""); getSubCommands().forEach(cmd -> { if (cmd instanceof CommandTreeBase) { ((CommandTreeBase)cmd).getSubCommands().forEach(rcmd -> ret.appendText("\n").appendText(rcmd.getUsage(sender))); } else { ret.appendText("\n").appendText(cmd.getUsage(sender)); } }); return ret.getFormattedText(); } static final class CommandStatus extends CommandBase { private static final String NAME = "status"; private final String parentName; CommandStatus(String parentName) { this.parentName = parentName; } @Override public int getRequiredPermissionLevel() { return ACCESS_ALL; } @Override public String getName() { return NAME; } @Override public String getUsage(ICommandSender sender) { return getUsageForBasicCommand(this, this.parentName, LANG_KEY_ADDENDUM_STATUS); } @Override public void execute(MinecraftServer server, ICommandSender sender, String[] args) { sender.sendMessage(new TextComponentString(" ") .appendSibling(new TextComponentTranslation(LANG_KEY_SETTINGS_HEADER).setStyle(STYLE_DKGREEN)).appendText(":") ); sender.sendMessage(new TextComponentString(" ") .appendSibling(new TextComponentTranslation(PLConfig.fallDamageReduction.getLanguageKey()).setStyle(STYLE_DKAQUA)).appendText(" : ") .appendSibling(new TextComponentString(PLConfig.fallDamageReduction.getString()).setStyle(STYLE_AQUA)) ); sender.sendMessage(new TextComponentString(" ") .appendSibling(new TextComponentTranslation(PLConfig.fallDamageThreshold.getLanguageKey()).setStyle(STYLE_DKAQUA)).appendText(" : ") .appendSibling(new TextComponentString(PLConfig.fallDamageThreshold.getString()).setStyle(STYLE_AQUA)) ); sender.sendMessage(new TextComponentString(" ") .appendSibling(new TextComponentTranslation(PLConfig.speedReductionHorizontal.getLanguageKey()).setStyle(STYLE_DKAQUA)).appendText(" : ") .appendSibling(new TextComponentString(PLConfig.speedReductionHorizontal.getString()).setStyle(STYLE_AQUA)) ); sender.sendMessage(new TextComponentString(" ") .appendSibling(new TextComponentTranslation(PLConfig.speedReductionVertical.getLanguageKey()).setStyle(STYLE_DKAQUA)).appendText(" : ") .appendSibling(new TextComponentString(PLConfig.speedReductionVertical.getString()).setStyle(STYLE_AQUA)) ); } } static final class CommandSave extends CommandBase { private static final String NAME = "save"; private final String parentName; CommandSave(String parentName) { this.parentName = parentName; } @Override public int getRequiredPermissionLevel() { return ACCESS_ADMIN; } @Override public String getName() { return NAME; } @Override public String getUsage(ICommandSender sender) { return getUsageForBasicCommand(this, this.parentName, LANG_KEY_ADDENDUM_SAVE); } @Override public void execute(MinecraftServer server, ICommandSender sender, String[] args) { sender.sendMessage(new TextComponentString(" ").appendText("Saving current settings to PassableLeaves config.").setStyle(STYLE_DKGREEN)); PLConfig.sync(); } } static final class CommandTreeDamage extends CommandTreeBase { private static final String NAME = "damage"; private final String parentName; CommandTreeDamage(String parentName) { this.parentName = parentName; this.addSubcommand(new CommandFallDamageReduction(this.parentName+" "+this.getName())); this.addSubcommand(new CommandFallDamageThreshold(this.parentName+" "+this.getName())); } @Override public int getRequiredPermissionLevel() { return ACCESS_OPS; } @Override public String getName() { return NAME; } @Override public String getUsage(ICommandSender sender) { return getUsageForBasicCommand(this, this.parentName, "["+CommandFallDamageReduction.NAME+"|"+CommandFallDamageThreshold.NAME+"]"); } static final class CommandFallDamageReduction extends CommandBase { private static final String NAME = "reduction"; private final String parentName; private final Property cfgProp = PLConfig.fallDamageReduction; CommandFallDamageReduction(String parentName) { this.parentName = parentName; } @Override public int getRequiredPermissionLevel() { return ACCESS_OPS; } @Override public String getName() { return NAME; } @Override public String getUsage(ICommandSender sender) { return getUsageForPropCommand(this, this.parentName, this.cfgProp); } @Override public void execute(MinecraftServer server, ICommandSender sender, String[] args) { executor(this, sender, args, this.cfgProp); } } static final class CommandFallDamageThreshold extends CommandBase { private static final String NAME = "threshold"; private final String parentName; private final Property cfgProp = PLConfig.fallDamageThreshold; CommandFallDamageThreshold(String parentName) { this.parentName = parentName; } @Override public int getRequiredPermissionLevel() { return ACCESS_OPS; } @Override public String getName() { return NAME; } @Override public String getUsage(ICommandSender sender) { return getUsageForPropCommand(this, this.parentName, this.cfgProp); } @Override public void execute(MinecraftServer server, ICommandSender sender, String[] args) { executor(this, sender, args, this.cfgProp); } } } static final class CommandTreeSpeed extends CommandTreeBase { private static final String NAME = "speed"; private final String parentName; CommandTreeSpeed(String parentName) { this.parentName = parentName; this.addSubcommand(new CommandSpeedHorizontal(this.parentName+" "+this.getName())); this.addSubcommand(new CommandSpeedVertical(this.parentName+" "+this.getName())); } @Override public int getRequiredPermissionLevel() { return ACCESS_OPS; } @Override public String getName() { return NAME; } @Override public String getUsage(ICommandSender sender) { return getUsageForBasicCommand(this, this.parentName, "["+CommandSpeedHorizontal.NAME+"|"+CommandSpeedVertical.NAME+"]"); } static final class CommandSpeedHorizontal extends CommandBase { private static final String NAME = "horizontal"; private final String parentName; private final Property cfgProp = PLConfig.speedReductionHorizontal; CommandSpeedHorizontal(String parentName) { this.parentName = parentName; } @Override public int getRequiredPermissionLevel() { return ACCESS_OPS; } @Override public String getName() { return NAME; } @Override public String getUsage(ICommandSender sender) { return getUsageForPropCommand(this, this.parentName, this.cfgProp); } @Override public void execute(MinecraftServer server, ICommandSender sender, String[] args) { executor(this, sender, args, this.cfgProp); } } static final class CommandSpeedVertical extends CommandBase { private static final String NAME = "vertical"; private final String parentName; private final Property cfgProp = PLConfig.speedReductionVertical; CommandSpeedVertical(String parentName) { this.parentName = parentName; } @Override public int getRequiredPermissionLevel() { return ACCESS_OPS; } @Override public String getName() { return NAME; } @Override public String getUsage(ICommandSender sender) { return getUsageForPropCommand(this, this.parentName, this.cfgProp); } @Override public void execute(MinecraftServer server, ICommandSender sender, String[] args) { executor(this, sender, args, this.cfgProp); } } } private static String getUsageForBasicCommand(ICommand cmd, String parent, String addendum) { return new TextComponentString(" /") .appendSibling(new TextComponentString(parent+" "+cmd.getName()).setStyle(STYLE_DKAQUA)).appendText(" ") .appendSibling(new TextComponentTranslation(addendum).setStyle(STYLE_AQUA)).getFormattedText(); } private static String getUsageForPropCommand(ICommand cmd, String parent, Property cfgProp) { return new TextComponentString(" /") .appendSibling(new TextComponentString(parent+" "+cmd.getName()).setStyle(STYLE_DKAQUA)).appendText(" <") .appendSibling(new TextComponentString(cfgProp.getMinValue()).setStyle(STYLE_GRAY)).appendText(" - ") .appendSibling(new TextComponentString(cfgProp.getMaxValue()).setStyle(STYLE_GRAY)).appendText(">").getFormattedText(); } private static void executor(ICommand cmd, ICommandSender sender, String[] args, Property cfgProp) { if (args.length == 0) { sender.sendMessage(new TextComponentString(" ") .appendSibling(new TextComponentTranslation(cfgProp.getLanguageKey()).setStyle(STYLE_DKAQUA)) .appendText(" ").appendSibling(new TextComponentTranslation(LANG_KEY_CURRENT_SETTING)) .appendText(" ").appendSibling(new TextComponentString(cfgProp.getString()).setStyle(STYLE_AQUA)) ); return; } int value; try { value = CommandBase.parseInt(args[0]); } catch (NumberInvalidException e) { sender.sendMessage(new TextComponentString(" ") .appendSibling(new TextComponentTranslation(LANG_KEY_PREFIX_ERROR).setStyle(STYLE_ERROR)).appendText(": ") .appendSibling(new TextComponentTranslation(LANG_KEY_VALUE_INVALID)).appendText(": ") .appendSibling(new TextComponentString(((e.getErrorObjects().length>0)?e.getErrorObjects()[0].toString():"[NULL]")).setStyle(STYLE_GOLD)) ); sender.sendMessage(new TextComponentString(cmd.getUsage(sender))); return; } if (value < Integer.valueOf(cfgProp.getMinValue()) || value > Integer.valueOf(cfgProp.getMaxValue())) { sender.sendMessage(new TextComponentString(" ") .appendSibling(new TextComponentTranslation(LANG_KEY_PREFIX_ERROR).setStyle(STYLE_ERROR)).appendText(": ") .appendSibling(new TextComponentTranslation(LANG_KEY_VALUE_OUTOFRANGE)).appendText(": ") .appendSibling(new TextComponentString(String.valueOf(value)).setStyle(STYLE_GOLD)) ); sender.sendMessage(new TextComponentString(cmd.getUsage(sender))); return; } sender.sendMessage(new TextComponentString(" ") .appendText("Setting ").appendSibling(new TextComponentTranslation(cfgProp.getLanguageKey()).setStyle(STYLE_DKAQUA)) .appendText(" to: ").appendSibling(new TextComponentString(cfgProp.setValue(value).getString()).setStyle(STYLE_AQUA)) ); NetworkDispatcher.INSTANCE.sendConfigSyncMessageToAll(); } } static final class PLConfig { private PLConfig() {} private static File configFile; private static Configuration config; private static Property fallDamageThreshold; private static Property fallDamageReduction; private static Property speedReductionHorizontal; private static Property speedReductionVertical; private static void init(FMLPreInitializationEvent event) { if (configFile == null) { configFile = event.getSuggestedConfigurationFile(); } if (config == null) { config = new Configuration(configFile); } config.setCategoryComment(MOD_ID, "These settings get overridden when connected to a remote server."); fallDamageReduction = config.get( MOD_ID, "Fall Damage Reduction", 50, "The percentage of normal damage taken when taking damage from falling into leaves." + Configuration.NEW_LINE + "The damage will be reduced by a further 10% with the Jump Boost potion effect.", 0, 100 ).setLanguageKey(MOD_ID + ".config.fallDamageReduction"); fallDamageThreshold = config.get( MOD_ID, "Fall Damage Threshold", 20, "When falling into leaves, the (block) distance a player or mob has to fall before taking damage.", 5, 255 ).setLanguageKey(MOD_ID + ".config.fallDamageThreshold"); speedReductionHorizontal = config.get( MOD_ID, "Speed Reduction - Horizontal", 90, "The reduced horizontal speed when passing through leaves. (% of normal)", 0, 100 ).setLanguageKey(MOD_ID+".config.speedReductionHorizontal"); speedReductionVertical = config.get( MOD_ID, "Speed Reduction - Vertical", 90, "The reduced vertical speed when passing through leaves. (% of normal)", 0, 100 ).setLanguageKey(MOD_ID+".config.speedReductionVertical"); if (config.hasChanged()) { config.save(); } } private static void sync() { if (config.hasChanged()) { LOGGER.debug("Saving config"); config.save(); } if (LOCAL_SERVER) { LOGGER.debug("Syncing config settings on client"); PassableLeaves.fallDamageReduction = getFallDamageReduction(); PassableLeaves.fallDamageThreshold = getFallDamageThreshold(); PassableLeaves.speedReductionHorizontal = getSpeedReductionHorizontal(); PassableLeaves.speedReductionVertical = getSpeedReductionVertical(); } } static float getFallDamageReduction() { return ((float)fallDamageReduction.getInt())/100; } static int getFallDamageThreshold() { return fallDamageThreshold.getInt(); } static double getSpeedReductionHorizontal() { return speedReductionHorizontal.getDouble()/100; } static double getSpeedReductionVertical() { return speedReductionVertical.getDouble()/100; } } @SideOnly(Side.CLIENT) public static final class PLGuiConfig extends GuiConfig { PLGuiConfig(GuiScreen parent) { super(parent, getConfigElements(), MOD_ID, false, false, I18n.format(MOD_ID+".config.maintitle")); this.titleLine2 = I18n.format(MOD_ID+".config.maintitle2"); } private static List<IConfigElement> getConfigElements() { List<IConfigElement> ret = Lists.newArrayList(); PLConfig.config.getCategory(MOD_ID).values().forEach(e -> { e.setComment(I18n.format(e.getLanguageKey()+".comment",'\n','\n','\n')); ret.add(new ConfigElement(e)); }); return ret; } @Override public void onGuiClosed() { super.onGuiClosed(); PLConfig.sync(); } } @SideOnly(Side.CLIENT) public static final class PLGuiConfigFactory implements IModGuiFactory { @Override public void initialize(Minecraft mc) {} @Override public boolean hasConfigGui() { return true; } @Override public GuiScreen createConfigGui(GuiScreen parentScreen) { return new PLGuiConfig(parentScreen); } @Override public Set<RuntimeOptionCategoryElement> runtimeGuiCategories() { return null; } } public static final class ConfigSyncHandler { ConfigSyncHandler() {} @SubscribeEvent @SideOnly(Side.SERVER) public void onPlayerLoggedIn(PlayerLoggedInEvent event) { if (event.player instanceof EntityPlayerMP) { EntityPlayerMP player = (EntityPlayerMP) event.player; IThreadListener listener = player.getServer(); if (listener != null) { listener.addScheduledTask(() -> NetworkDispatcher.INSTANCE.sendConfigSyncMessageToPlayer(player)); } } } @SubscribeEvent @SideOnly(Side.CLIENT) public void onClientDisconnect(FMLNetworkEvent.ClientDisconnectionFromServerEvent event) { // Reset, so that a client can sync changes to it's own config while disconnected LOCAL_SERVER = true; PLConfig.sync(); } } // TODO: The below static fields (initialised to default values) and #onEntityCollidedWithLeaves should probably be // moved to the coremod where they belong. All manipulation of the values can be done from here with // PLConfig#sync and from the sync handler, as this Forge mod is merely a config frontend for the coremod. static float fallDamageReduction; static int fallDamageThreshold; static double speedReductionHorizontal; static double speedReductionVertical; private static final DamageSource DAMAGESOURCE_FALLINTOLEAVES = new DamageSource("fallintoleaves") { @Override public ITextComponent getDeathMessage(EntityLivingBase entity) { return new TextComponentTranslation(PassableLeaves.MOD_ID+".death.fallintoleaves", entity.getDisplayName()); } }; // This method name has to match the method that is called in PassableLeavesTransformer @SuppressWarnings("WeakerAccess") public static void onEntityCollidedWithLeaves(World world, BlockPos pos, IBlockState state, Entity entity) { if (entity instanceof EntityLivingBase) { EntityLivingBase livingEntity = (EntityLivingBase)entity; // play a sound when an entity falls into leaves; do this before altering motion if (livingEntity.fallDistance > 3f) { entity.playSound(SoundEvents.BLOCK_GRASS_BREAK, SoundType.PLANT.getVolume() * 0.6f, SoundType.PLANT.getPitch() * 0.65f); } // play a sound when an entity is moving through leaves (only play sound every 6 ticks as to not flood sound events) else if (world.getTotalWorldTime() % 6 == 0 && (entity.posX != entity.prevPosX || entity.posY != entity.prevPosY || entity.posZ != entity.prevPosZ)) { entity.playSound(SoundEvents.BLOCK_GRASS_HIT, SoundType.PLANT.getVolume() * 0.5f, SoundType.PLANT.getPitch() * 0.45f); } // reduce movement speed when inside of leaves, but allow players/mobs to jump out of them if (!livingEntity.isJumping) { entity.motionX *= speedReductionHorizontal; entity.motionY *= speedReductionVertical; entity.motionZ *= speedReductionHorizontal; } // modify falling damage when falling into leaves if (livingEntity.fallDistance > fallDamageThreshold) { livingEntity.fallDistance -= fallDamageThreshold; PotionEffect pe = livingEntity.getActivePotionEffect(MobEffects.JUMP_BOOST); int amount = MathHelper.ceil(livingEntity.fallDistance * fallDamageReduction * ((pe == null) ? 1.0f : 0.9f)); livingEntity.attackEntityFrom(DAMAGESOURCE_FALLINTOLEAVES, amount); } // reset fallDistance if (livingEntity.fallDistance > 1f) { livingEntity.fallDistance = 1f; } // Riding a mob won't protect you; Process riders last if (entity.isBeingRidden()) { for (Entity ent : entity.getPassengers()) { onEntityCollidedWithLeaves(world, pos, state, ent); } } } } }
package ui.components.pickers; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.value.ObservableValue; import javafx.geometry.Pos; import javafx.scene.control.CheckBox; import javafx.scene.control.ContentDisplay; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.util.Callback; import javafx.util.StringConverter; /** * Mostly a copy of CheckBoxListCell */ public class LabelPickerCell extends ListCell<LabelPicker.Label> { private final CheckBox checkBox; private ObservableValue<Boolean> booleanProperty; private ObjectProperty<Callback<LabelPicker.Label, ObservableValue<Boolean>>> selectedStateCallback = new SimpleObjectProperty<>( this, "selectedStateCallback"); private ObjectProperty<StringConverter<LabelPicker.Label>> converter = new SimpleObjectProperty<>(this, "converter"); private LabelPicker.Label item; public static Callback<ListView<LabelPicker.Label>, ListCell<LabelPicker.Label>> forListView( final Callback<LabelPicker.Label, ObservableValue<Boolean>> getSelectedProperty, final StringConverter<LabelPicker.Label> converter) { return list -> new LabelPickerCell(getSelectedProperty, converter); } public LabelPickerCell( final Callback<LabelPicker.Label, ObservableValue<Boolean>> getSelectedProperty, final StringConverter<LabelPicker.Label> converter) { this.getStyleClass().add("check-box-list-cell"); setSelectedStateCallback(getSelectedProperty); setConverter(converter); this.checkBox = new CheckBox(); setAlignment(Pos.CENTER_LEFT); setContentDisplay(ContentDisplay.LEFT); // by default the graphic is null until the cell stops being empty setGraphic(null); setOnMouseClicked(e -> { item.toggleChecked(); updateItem(item, false); }); } @Override public void updateItem(LabelPicker.Label item, boolean empty) { super.updateItem(item, empty); if (!empty) { this.item = item; StringConverter<LabelPicker.Label> c = getConverter(); Callback<LabelPicker.Label, ObservableValue<Boolean>> callback = getSelectedStateCallback(); if (callback == null) { throw new NullPointerException( "The CheckBoxListCell selectedStateCallbackProperty can not be null"); } setGraphic(checkBox); if (item != null && item.isSelected()) { setText(c != null ? " " + c.toString(item) : item.toString()); } else { setText(c != null ? c.toString(item) : (item == null ? "" : item.toString())); } setStyle(item != null ? item.getStyle() : null); if (booleanProperty != null) { checkBox.selectedProperty().unbindBidirectional((BooleanProperty) booleanProperty); } booleanProperty = callback.call(item); if (booleanProperty != null) { checkBox.selectedProperty().bindBidirectional((BooleanProperty) booleanProperty); } } else { setGraphic(null); setText(null); } } public final ObjectProperty<StringConverter<LabelPicker.Label>> converterProperty() { return converter; } public final void setSelectedStateCallback(Callback<LabelPicker.Label, ObservableValue<Boolean>> value) { selectedStateCallbackProperty().set(value); } public final void setConverter(StringConverter<LabelPicker.Label> value) { converterProperty().set(value); } public final ObjectProperty<Callback<LabelPicker.Label, ObservableValue<Boolean>>> selectedStateCallbackProperty() { return selectedStateCallback; } public final StringConverter<LabelPicker.Label> getConverter() { return converterProperty().get(); } public final Callback<LabelPicker.Label, ObservableValue<Boolean>> getSelectedStateCallback() { return selectedStateCallbackProperty().get(); } }
/* * @author <a href="mailto:novotny@aei.mpg.de">Jason Novotny</a> * @version $Id$ */ package org.gridlab.gridsphere.servlets; import org.gridlab.gridsphere.core.persistence.PersistenceManagerFactory; import org.gridlab.gridsphere.core.persistence.hibernate.DBTask; import org.gridlab.gridsphere.layout.PortletLayoutEngine; import org.gridlab.gridsphere.layout.PortletPageFactory; import org.gridlab.gridsphere.portlet.*; import org.gridlab.gridsphere.portlet.impl.*; import org.gridlab.gridsphere.portlet.service.PortletServiceException; import org.gridlab.gridsphere.portlet.service.spi.impl.SportletServiceFactory; import org.gridlab.gridsphere.portletcontainer.impl.GridSphereEventImpl; import org.gridlab.gridsphere.portletcontainer.impl.SportletMessageManager; import org.gridlab.gridsphere.portletcontainer.*; import org.gridlab.gridsphere.services.core.registry.PortletManagerService; import org.gridlab.gridsphere.services.core.security.acl.AccessControlManagerService; import org.gridlab.gridsphere.services.core.security.auth.AuthorizationException; import org.gridlab.gridsphere.services.core.security.auth.AuthenticationException; import org.gridlab.gridsphere.services.core.user.LoginService; import org.gridlab.gridsphere.services.core.user.UserManagerService; import org.gridlab.gridsphere.services.core.user.UserSessionManager; import org.gridlab.gridsphere.services.core.request.RequestService; import org.gridlab.gridsphere.services.core.request.GenericRequest; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.servlet.*; import javax.servlet.http.*; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.*; /** * The <code>GridSphereServlet</code> is the GridSphere portlet container. * All portlet requests get proccessed by the GridSphereServlet before they * are rendered. */ public class GridSphereServlet extends HttpServlet implements ServletContextListener, HttpSessionAttributeListener, HttpSessionListener, HttpSessionActivationListener { /* GridSphere logger */ private static PortletLog log = SportletLog.getInstance(GridSphereServlet.class); /* GridSphere service factory */ private static SportletServiceFactory factory = null; /* GridSphere Portlet Registry Service */ private static PortletManagerService portletManager = null; /* GridSphere Access Control Service */ private static AccessControlManagerService aclService = null; private static UserManagerService userManagerService = null; private static LoginService loginService = null; private PortletMessageManager messageManager = SportletMessageManager.getInstance(); /* GridSphere Portlet layout Engine handles rendering */ private static PortletLayoutEngine layoutEngine = null; /* Session manager maps users to sessions */ private UserSessionManager userSessionManager = UserSessionManager.getInstance(); /* creates cookie requests */ private RequestService requestService = null; private PortletContext context = null; private static Boolean firstDoGet = Boolean.TRUE; private static PortletSessionManager sessionManager = PortletSessionManager.getInstance(); //private static PortletRegistry registry = PortletRegistry.getInstance(); private static final String COOKIE_REQUEST = "cookie-request"; private int COOKIE_EXPIRATION_TIME = 60 * 60 * 24 * 7; // 1 week (in secs) private PortletGroup coreGroup = null; private boolean isTCK = false; /** * Initializes the GridSphere portlet container * * @param config the <code>ServletConfig</code> * @throws ServletException if an error occurs during initialization */ public final void init(ServletConfig config) throws ServletException { super.init(config); GridSphereConfig.setServletConfig(config); SportletLog.setConfigureURL(GridSphereConfig.getServletContext().getRealPath("/WEB-INF/classes/log4j.properties")); this.context = new SportletContext(config); factory = SportletServiceFactory.getInstance(); layoutEngine = PortletLayoutEngine.getInstance(); log.debug("in init of GridSphereServlet"); } public synchronized void initializeServices() throws PortletServiceException { requestService = (RequestService) factory.createPortletService(RequestService.class, getServletConfig().getServletContext(), true); log.debug("Creating access control manager service"); aclService = (AccessControlManagerService) factory.createPortletService(AccessControlManagerService.class, getServletConfig().getServletContext(), true); // create root user in default group if necessary log.debug("Creating user manager service"); userManagerService = (UserManagerService) factory.createPortletService(UserManagerService.class, getServletConfig().getServletContext(), true); loginService = (LoginService) factory.createPortletService(LoginService.class, getServletConfig().getServletContext(), true); log.debug("Creating portlet manager service"); portletManager = (PortletManagerService) factory.createPortletService(PortletManagerService.class, getServletConfig().getServletContext(), true); } /** * Processes GridSphere portal framework requests * * @param req the <code>HttpServletRequest</code> * @param res the <code>HttpServletResponse</code> * @throws IOException if an I/O error occurs * @throws ServletException if a servlet error occurs */ public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { processRequest(req, res); } public void setHeaders(HttpServletResponse res) { res.setContentType("text/html; charset=utf-8"); // Necessary to display UTF-8 encoded characters /* res.setHeader("Cache-Control","no-cache"); //Forces caches to obtain a new copy of the page from the origin server res.setHeader("Cache-Control","no-store"); //Directs caches not to store the page under any circumstance res.setDateHeader("Expires", 0); //Causes the proxy cache to see the page as "stale" res.setHeader("Pragma","no-cache"); //HTTP 1.0 backward compatibility */ } public void processRequest(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { setHeaders(res); GridSphereEvent event = new GridSphereEventImpl(context, req, res); PortletRequest portletReq = event.getPortletRequest(); // If first time being called, instantiate all portlets if (firstDoGet.equals(Boolean.TRUE)) { synchronized (firstDoGet) { firstDoGet = Boolean.FALSE; log.debug("Testing Database"); // checking if database setup is correct DBTask dt = new DBTask(); dt.setAction(DBTask.ACTION_CHECKDB); dt.setConfigDir(GridSphereConfig.getServletContext().getRealPath("")); try { dt.execute(); } catch (Exception e) { RequestDispatcher rd = req.getRequestDispatcher("/jsp/errors/database_error.jsp"); log.error("Check DB failed: ", e); req.setAttribute("error", "DB Error! Please contact your GridSphere/Database Administrator!"); rd.forward(req, res); return; } log.debug("Initializing portlets and services"); try { // initialize portlet service factory factory.init(); // initialize needed services initializeServices(); // create a root user if none available userManagerService.initRootUser(); // initialize all portlets PortletResponse portletRes = event.getPortletResponse(); PortletInvoker.initAllPortlets(portletReq, portletRes); // deep inside a service is used which is why this must follow the factory.init layoutEngine.init(); } catch (Exception e) { log.error("GridSphere initialization failed!", e); RequestDispatcher rd = req.getRequestDispatcher("/jsp/errors/init_error.jsp"); req.setAttribute("error", e); rd.forward(req, res); return; } coreGroup = aclService.getCoreGroup(); } } setUserAndGroups(portletReq); checkUserHasCookie(event); setTCKUser(portletReq); // Handle user login and logout if (event.hasAction()) { if (event.getAction().getName().equals(SportletProperties.LOGIN)) { login(event); //event = new GridSphereEventImpl(aclService, context, req, res); } if (event.getAction().getName().equals(SportletProperties.LOGOUT)) { logout(event); // since event is now invalidated, must create new one event = new GridSphereEventImpl(context, req, res); } } layoutEngine.actionPerformed(event); // is this a file download operation? downloadFile(event); // Handle any outstanding messages // This needs work certainly!!! Map portletMessageLists = messageManager.retrieveAllMessages(); if (!portletMessageLists.isEmpty()) { Set keys = portletMessageLists.keySet(); Iterator it = keys.iterator(); String concPortletID = null; List messages = null; while (it.hasNext()) { concPortletID = (String) it.next(); messages = (List) portletMessageLists.get(concPortletID); Iterator newit = messages.iterator(); while (newit.hasNext()) { PortletMessage msg = (PortletMessage) newit.next(); layoutEngine.messageEvent(concPortletID, msg, event); } } messageManager.removeAllMessages(); } setUserAndGroups(portletReq); setTCKUser(portletReq); layoutEngine.service(event); //log.debug("Session stats"); //userSessionManager.dumpSessions(); //log.debug("Portlet service factory stats"); //factory.logStatistics(); /* log.debug("Portlet page factory stats"); try { PortletPageFactory pageFactory = PortletPageFactory.getInstance(); pageFactory.logStatistics(); } catch (Exception e) { log.error("Unable to get page factory", e); } */ } public void setTCKUser(PortletRequest req) { //String tck = (String)req.getPortletSession(true).getAttribute("tck"); String[] portletNames = req.getParameterValues("portletName"); if ((isTCK) || (portletNames != null)) { log.info("Setting a TCK user"); SportletUserImpl u = new SportletUserImpl(); u.setUserName("tckuser"); u.setUserID("tckuser"); u.setID("500"); Map l = new HashMap(); l.put(coreGroup, PortletRole.USER); req.setAttribute(SportletProperties.PORTLET_USER, u); req.setAttribute(SportletProperties.PORTLETGROUPS, l); req.setAttribute(SportletProperties.PORTLET_ROLE, PortletRole.USER); isTCK = true; } } public void setUserAndGroups(PortletRequest req) { // Retrieve user if there is one User user = null; if (req.getPortletSession() != null) { String uid = (String) req.getPortletSession().getAttribute(SportletProperties.PORTLET_USER); if (uid != null) { user = userManagerService.getUser(uid); } } HashMap groups = new HashMap(); PortletRole role = PortletRole.GUEST; if (user == null) { user = GuestUser.getInstance(); groups = new HashMap(); groups.put(coreGroup, PortletRole.GUEST); } else { List mygroups = aclService.getGroups(user); Iterator it = mygroups.iterator(); while (it.hasNext()) { PortletGroup g = (PortletGroup) it.next(); role = aclService.getRoleInGroup(user, g); groups.put(g, role); } } // req.getPortletRole returns the role user has in core gridsphere group role = aclService.getRoleInGroup(user, coreGroup); // set user, role and groups in request req.setAttribute(SportletProperties.PORTLET_GROUP, coreGroup); req.setAttribute(SportletProperties.PORTLET_USER, user); req.setAttribute(SportletProperties.PORTLETGROUPS, groups); req.setAttribute(SportletProperties.PORTLET_ROLE, role); } protected void checkUserHasCookie(GridSphereEvent event) { PortletRequest req = event.getPortletRequest(); User user = req.getUser(); if (user instanceof GuestUser) { Cookie[] cookies = req.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { Cookie c = cookies[i]; System.err.println("found a cookie:"); System.err.println("name=" + c.getName()); System.err.println("value=" + c.getValue()); if (c.getName().equals("gsuid")) { String cookieVal = c.getValue(); int hashidx = cookieVal.indexOf(" if (hashidx > 0) { String uid = cookieVal.substring(0, hashidx); System.err.println("uid = " + uid); String reqid = cookieVal.substring(hashidx+1); System.err.println("reqid = " + reqid); GenericRequest genreq = requestService.getRequest(reqid, COOKIE_REQUEST); if (genreq != null) { if (genreq.getUserID().equals(uid)) { User newuser = userManagerService.getUser(uid); if (newuser != null) { setUserSettings(event, newuser); } } } } } } } } } protected void setUserCookie(GridSphereEvent event) { PortletRequest req = event.getPortletRequest(); PortletResponse res = event.getPortletResponse(); User user = req.getUser(); GenericRequest request = requestService.createRequest(COOKIE_REQUEST); Cookie cookie = new Cookie("gsuid", user.getID() + "#" + request.getOid()); request.setUserID(user.getID()); long time = Calendar.getInstance().getTime().getTime() + COOKIE_EXPIRATION_TIME * 1000; request.setLifetime(new Date(time)); requestService.saveRequest(request); // COOKIE_EXPIRATION_TIME is specified in secs cookie.setMaxAge(COOKIE_EXPIRATION_TIME); res.addCookie(cookie); System.err.println("adding a cookie"); } protected void removeUserCookie(GridSphereEvent event) { PortletRequest req = event.getPortletRequest(); PortletResponse res = event.getPortletResponse(); Cookie[] cookies = req.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { Cookie c = cookies[i]; if (c.getName().equals("gsuid")) { int idx = c.getValue().indexOf(" if (idx > 0) { String reqid = c.getValue().substring(idx+1); System.err.println("reqid= " + reqid); GenericRequest request = requestService.getRequest(reqid, COOKIE_REQUEST); if (request != null) requestService.deleteRequest(request); } c.setMaxAge(0); res.addCookie(c); } } } } /** * Handles login requests * * @param event a <code>GridSphereEvent</code> */ protected void login(GridSphereEvent event) { log.debug("in login of GridSphere Servlet"); String LOGIN_ERROR_FLAG = "LOGIN_FAILED"; PortletRequest req = event.getPortletRequest(); String username = req.getParameter("username"); String password = req.getParameter("password"); try { User user = loginService.login(username, password); // null out passwd password = null; setUserSettings(event, user); String remme = req.getParameter("remlogin"); if (remme != null) { setUserCookie(event); } else { removeUserCookie(event); } } catch (AuthorizationException err) { log.debug(err.getMessage()); req.setAttribute(LOGIN_ERROR_FLAG, err.getMessage()); } catch (AuthenticationException err) { log.debug(err.getMessage()); req.setAttribute(LOGIN_ERROR_FLAG, err.getMessage()); } } public void setUserSettings(GridSphereEvent event, User user) { PortletRequest req = event.getPortletRequest(); PortletSession session = req.getPortletSession(true); req.setAttribute(SportletProperties.PORTLET_USER, user); session.setAttribute(SportletProperties.PORTLET_USER, user.getID()); if (user.getAttribute(User.LOCALE) != null) { session.setAttribute(User.LOCALE, new Locale((String)user.getAttribute(User.LOCALE), "", "")); } if (aclService.hasSuperRole(user)) { log.debug("User: " + user.getUserName() + " logged in as SUPER"); } setUserAndGroups(req); log.debug("Adding User: " + user.getID() + " with session:" + session.getId() + " to usersessionmanager"); userSessionManager.addSession(user, session); layoutEngine.loginPortlets(event); } /** * Handles logout requests * * @param event a <code>GridSphereEvent</code> */ protected void logout(GridSphereEvent event) { log.debug("in logout of GridSphere Servlet"); PortletRequest req = event.getPortletRequest(); removeUserCookie(event); PortletSession session = req.getPortletSession(); session.removeAttribute(SportletProperties.PORTLET_USER); userSessionManager.removeSessions(req.getUser()); layoutEngine.logoutPortlets(event); } /** * Method to set the response headers to perform file downloads to a browser * * @param event the gridsphere event * @throws PortletException */ public void downloadFile(GridSphereEvent event) throws PortletException { PortletResponse res = event.getPortletResponse(); PortletRequest req = event.getPortletRequest(); try { String fileName = (String) req.getAttribute(SportletProperties.FILE_DOWNLOAD_NAME); String path = (String) req.getAttribute(SportletProperties.FILE_DOWNLOAD_PATH); if ((fileName == null) || (path == null)) return; log.debug("in downloadFile"); log.debug("filename: " + fileName + " filepath= " + path); File f = new File(path); FileDataSource fds = new FileDataSource(f); res.setContentType(fds.getContentType()); res.setHeader("Content-Disposition", "attachment; filename=" + fileName); res.setHeader("Content-Length", String.valueOf(f.length())); DataHandler handler = new DataHandler(fds); handler.writeTo(res.getOutputStream()); } catch (FileNotFoundException e) { log.error("Unable to find file!", e); } catch (SecurityException e) { // this gets thrown if a security policy applies to the file. see java.io.File for details. log.error("A security exception occured!", e); } catch (IOException e) { log.error("Caught IOException", e); //response.sendError(HttpServletResponse.SC_INTERNAL_SERVER,e.getMessage()); } } /** * @see #doGet */ public final void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { doGet(req, res); } /** * Return the servlet info. * * @return a string with the servlet information. */ public final String getServletInfo() { return "GridSphere Servlet 2.0.1"; } /** * Shuts down the GridSphere portlet container */ public final void destroy() { log.debug("in destroy: Shutting down services"); userSessionManager.destroy(); layoutEngine.destroy(); // Shutdown services factory.shutdownServices(); // shutdown the persistencemanagers PersistenceManagerFactory.shutdown(); System.gc(); } /** * Record the fact that a servlet context attribute was added. * * @param event The session attribute event */ public void attributeAdded(HttpSessionBindingEvent event) { log.debug("attributeAdded('" + event.getSession().getId() + "', '" + event.getName() + "', '" + event.getValue() + "')"); } /** * Record the fact that a servlet context attribute was removed. * * @param event The session attribute event */ public void attributeRemoved(HttpSessionBindingEvent event) { log.debug("attributeRemoved('" + event.getSession().getId() + "', '" + event.getName() + "', '" + event.getValue() + "')"); } /** * Record the fact that a servlet context attribute was replaced. * * @param event The session attribute event */ public void attributeReplaced(HttpSessionBindingEvent event) { log.debug("attributeReplaced('" + event.getSession().getId() + "', '" + event.getName() + "', '" + event.getValue() + "')"); } /** * Record the fact that this ui application has been destroyed. * * @param event The servlet context event */ public void contextDestroyed(ServletContextEvent event) { ServletContext ctx = event.getServletContext(); log.debug("contextDestroyed()"); log.debug("contextName: " + ctx.getServletContextName()); log.debug("context path: " + ctx.getRealPath("")); } /** * Record the fact that this ui application has been initialized. * * @param event The servlet context event */ public void contextInitialized(ServletContextEvent event) { log.debug("contextInitialized()"); ServletContext ctx = event.getServletContext(); GridSphereConfig.setServletContext(ctx); log.debug("contextName: " + ctx.getServletContextName()); log.debug("context path: " + ctx.getRealPath("")); } /** * Record the fact that a session has been created. * * @param event The session event */ public void sessionCreated(HttpSessionEvent event) { log.debug("sessionCreated('" + event.getSession().getId() + "')"); sessionManager.sessionCreated(event); } /** * Record the fact that a session has been destroyed. * * @param event The session event */ public void sessionDestroyed(HttpSessionEvent event) { sessionManager.sessionDestroyed(event); log.debug("sessionDestroyed('" + event.getSession().getId() + "')"); } /** * Record the fact that a session has been created. * * @param event The session event */ public void sessionDidActivate(HttpSessionEvent event) { log.debug("sessionDidActivate('" + event.getSession().getId() + "')"); sessionManager.sessionCreated(event); } /** * Record the fact that a session has been destroyed. * * @param event The session event */ public void sessionWillPassivate(HttpSessionEvent event) { sessionManager.sessionDestroyed(event); log.debug("sessionWillPassivate('" + event.getSession().getId() + "')"); } }
package org.irmacard.credentials.idemix; import java.math.BigInteger; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Random; import java.util.Vector; import org.irmacard.credentials.Attributes; import org.irmacard.credentials.BaseCredentials; import org.irmacard.credentials.CredentialsException; import org.irmacard.credentials.idemix.descriptions.IdemixCredentialDescription; import org.irmacard.credentials.idemix.descriptions.IdemixVerificationDescription; import org.irmacard.credentials.idemix.irma.IRMAIdemixDisclosureProof; import org.irmacard.credentials.idemix.irma.IRMAIdemixIssuer; import org.irmacard.credentials.idemix.messages.IssueCommitmentMessage; import org.irmacard.credentials.idemix.messages.IssueSignatureMessage; import org.irmacard.credentials.info.AttributeDescription; import org.irmacard.credentials.info.CredentialDescription; import org.irmacard.credentials.info.DescriptionStore; import org.irmacard.credentials.info.InfoException; import org.irmacard.credentials.info.VerificationDescription; import org.irmacard.credentials.util.log.IssueLogEntry; import org.irmacard.credentials.util.log.LogEntry; import org.irmacard.credentials.util.log.RemoveLogEntry; import org.irmacard.credentials.util.log.VerifyLogEntry; import org.irmacard.idemix.IdemixService; import org.irmacard.idemix.IdemixSmartcard; import org.irmacard.idemix.util.CardVersion; import org.irmacard.idemix.util.IdemixLogEntry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.sf.scuba.smartcards.CardService; import net.sf.scuba.smartcards.CardServiceException; import net.sf.scuba.smartcards.ProtocolCommands; import net.sf.scuba.smartcards.ProtocolResponses; /** * An Idemix specific implementation of the credentials interface. */ public class IdemixCredentials extends BaseCredentials { IdemixService service = null; private static final Logger logger = LoggerFactory.getLogger(IdemixCredentials.class); public IdemixCredentials(CardService cs) { super(cs); if (cs instanceof IdemixService) { service = (IdemixService) cs; } else { service = new IdemixService(cs); } } public void connect() throws CredentialsException { try { service.open(); } catch (CardServiceException e) { e.printStackTrace(); } } /** * Issue a credential to the user according to the provided specification * containing the specified values. * * This method requires the Idemix application to be selected and the card * holder to be verified (if this is required by the card). * * @param specification * of the issuer and the credential to be issued. * @param values * to be stored in the credential. * @param expires * at this date, or after 6 months if null. * @throws CredentialsException * if the issuance process fails. */ public void issue(CredentialDescription cd, IdemixSecretKey sk, Attributes attributes, Date expiry) throws CredentialsException { attributes.setExpireDate(expiry); attributes.setCredentialID(cd.getId()); CardVersion cv = service.getCardVersion(); IdemixCredentialDescription icd = null; BigInteger nonce1 = null; try { icd = new IdemixCredentialDescription(cd); nonce1 = icd.generateNonce(); } catch (InfoException e) { throw new CredentialsException(e); } // Initialize the issuer IRMAIdemixIssuer issuer = new IRMAIdemixIssuer(icd.getPublicKey(), sk, icd.getContext()); try { IssueCommitmentMessage commit_msg = IdemixSmartcard.processIssueCommitmentCommands(cv, service.execute( IdemixSmartcard.requestIssueCommitmentCommands(cv, icd, attributes, nonce1))); IssueSignatureMessage signature_msg = issuer.issueSignature(commit_msg, icd, attributes, nonce1); service.execute( IdemixSmartcard.requestIssueSignatureCommands(cv, icd, signature_msg)); // FIXME: Check responses to round 3 } catch (CardServiceException e) { throw new CredentialsException("Issuing caused exception", e); } } public void verifyPrepare() throws CredentialsException { try { service = new IdemixService(cs); service.open(); } catch (CardServiceException e) { e.printStackTrace(); } } /** * Verify a number of attributes listed in the specification. * * TODO: maybe interface is better when just passing VerificationDescription? * TODO: see also corresponding IdemixSmartcard methods * * @param desc The VerificationDescription of the credential to be verified * @return the attributes disclosed during the verification process or null * if verification failed * @throws CredentialsException */ public Attributes verify(IdemixVerificationDescription desc) throws CredentialsException { verifyPrepare(); CardVersion cv = service.getCardVersion(); BigInteger nonce = desc.generateNonce(); // Run the protocol try { return verifyProofResponses(desc, nonce, service.execute(IdemixSmartcard.buildProofCommands(cv, nonce, desc))); } catch (CardServiceException e) { throw new CredentialsException("Verification encountered error", e); } } private Attributes verifyProofResponses(IdemixVerificationDescription vd, BigInteger nonce, ProtocolResponses responses) throws CredentialsException { IRMAIdemixDisclosureProof proof = IdemixSmartcard .processBuildProofResponses(service.getCardVersion(), responses, vd); return proof.verify(vd, nonce); } /** * First part of issuance protocol. Not yet included in the interface as * this is subject to change. Most notably * - How do we integrate the issuer in this, I would guess the only state * in fact the nonce, so we could handle that a bit cleaner. Carrying around * the issuer object may not be the best solution * - We need to deal with the selectApplet and sendPinCommands better. * * TODO: seems this doesn't quite belong here * @throws CredentialsException */ public ProtocolCommands requestIssueCommitmentCommands( IdemixCredentialDescription cd, Attributes attributes, BigInteger nonce1) throws CredentialsException { CardVersion cv = service.getCardVersion(); return IdemixSmartcard.requestIssueCommitmentCommands(cv, cd, attributes, nonce1); } public BigInteger generateNonce(VerificationDescription cd) { // TODO: extract public key from credential description IdemixSystemParameters params = new IdemixSystemParameters(); Random rnd = new Random(); return new BigInteger(params.l_statzk, rnd); } /** * Get the attribute values stored on the card for the given credential. * * @param credential identifier. * @return attributes for the given credential. * @throws CardServiceException * @throws CredentialsException */ public Attributes getAttributes(CredentialDescription cd) throws CardServiceException, CredentialsException { IdemixCredentialDescription icd = null; try { icd = new IdemixCredentialDescription(cd); } catch (InfoException e) { throw new CredentialsException(e); } ProtocolResponses responses = service.execute(IdemixSmartcard .requestGetAttributesCommands(getCardVersion(), icd)); return IdemixSmartcard.processGetAttributesCommands(getCardVersion(), icd, responses); } public void removeCredential(CredentialDescription cd) throws CardServiceException { service.selectCredential(cd.getId()); service.removeCredential(cd.getId()); } /** * Get a list of credentials available on the card. * * @return list of credential identifiers. * @throws CardServiceException * @throws InfoException */ public List<CredentialDescription> getCredentials() throws CardServiceException, InfoException { Vector<Integer> credentialIDs = service.getCredentials(); List<CredentialDescription> credentialList = new Vector<CredentialDescription>();; DescriptionStore ds = DescriptionStore.getInstance(); for(Integer id : credentialIDs) { CredentialDescription cd = ds.getCredentialDescription(id.shortValue()); if(cd != null) { credentialList.add(cd); } else { throw new InfoException("Description for credential with ID=" + id + " not found"); } } return credentialList; } @Override public List<LogEntry> getLog() throws CardServiceException, InfoException { List<IdemixLogEntry> idemix_logs = service.getLogEntries(); Vector<LogEntry> logs = new Vector<LogEntry>(); LogEntry entry = null; for(IdemixLogEntry l : idemix_logs) { if(l.getAction() == IdemixLogEntry.Action.NONE) continue; DescriptionStore ds = DescriptionStore.getInstance(); Date timestamp = l.getTimestamp(); CredentialDescription credential = ds.getCredentialDescription(l.getCredential()); if(credential == null) { logger.warn("This shouldn't happen, cannot find the description"); logger.warn(l.toString()); continue; } switch (l.getAction()) { case ISSUE: entry = new IssueLogEntry(timestamp, credential); break; case REMOVE: entry = new RemoveLogEntry(timestamp, credential); break; case VERIFY: entry = new VerifyLogEntry(timestamp, credential, null, makeAttributeDisclosed(credential, l.getDisclose())); break; // These should not happen... case NONE: default: continue; } logs.add(entry); } return logs; } private HashMap<String, Boolean> makeAttributeDisclosed(CredentialDescription cred, short disclose) { HashMap<String, Boolean> attributeDisclosed = new HashMap<String, Boolean>(); List<AttributeDescription> attributes = cred.getAttributes(); // Start at 2 so we skip the master secret and metadata for (int i = 2; i < attributes.size() + 2; i++) { attributeDisclosed.put(attributes.get(i-2).getName(), new Boolean( (disclose & (1 << i)) != 0)); } return attributeDisclosed; } public CardVersion getCardVersion() { return service.getCardVersion(); } }
package foundation.omni.rpc; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JavaType; import com.google.common.primitives.UnsignedBytes; import org.consensusj.bitcoin.rpc.BitcoinExtendedClient; import foundation.omni.json.pojo.OmniPropertyInfo; import org.bitcoinj.core.LegacyAddress; import org.bitcoinj.core.SegwitAddress; import org.consensusj.bitcoin.rx.jsonrpc.RxBitcoinClient; import org.consensusj.jsonrpc.JsonRpcException; import org.consensusj.bitcoin.rpc.RpcConfig; import foundation.omni.CurrencyID; import foundation.omni.Ecosystem; import foundation.omni.OmniValue; import foundation.omni.PropertyType; import foundation.omni.json.conversion.OmniClientModule; import foundation.omni.net.OmniNetworkParameters; import org.bitcoinj.core.Address; import org.bitcoinj.core.Coin; import org.bitcoinj.core.NetworkParameters; import org.bitcoinj.core.Sha256Hash; import javax.net.ssl.SSLSocketFactory; import java.io.IOException; import java.math.BigDecimal; import java.net.URI; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; // TODO: add missing RPCs: // - omni_listtransactions // - omni_gettradehistoryforpair // - omni_gettradehistoryforaddress public class OmniClient extends RxBitcoinClient implements OmniClientRawTxSupport { public OmniClient(RpcConfig config) throws IOException { this(config.getNetParams(), config.getURI(), config.getUsername(), config.getPassword()); } public OmniClient(SSLSocketFactory sslSocketFactory, NetworkParameters netParams, URI server, String rpcuser, String rpcpassword, boolean useZmq) { super(sslSocketFactory, netParams, server, rpcuser, rpcpassword, useZmq); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.registerModule(new OmniClientModule(getNetParams())); } public OmniClient(SSLSocketFactory sslSocketFactory, NetworkParameters netParams, URI server, String rpcuser, String rpcpassword) { this(sslSocketFactory, netParams, server, rpcuser, rpcpassword, false); } public OmniClient(NetworkParameters netParams, URI server, String rpcuser, String rpcpassword) { this((SSLSocketFactory)SSLSocketFactory.getDefault(), netParams, server, rpcuser, rpcpassword); } public OmniNetworkParameters getOmniNetParams() { return OmniNetworkParameters.fromBitcoinParms(getNetParams()); } /** * Returns various state information of Omni Core and the Omni Layer protocol. * * @return An object with state information * @throws JsonRpcException JSON RPC error * @throws IOException network error */ public Map<String, Object> omniGetInfo() throws JsonRpcException, IOException { Map<String, Object> result = send("omni_getinfo"); return result; } /** * Lists all currencies, smart properties and tokens. * * @return A list with short information * @throws JsonRpcException JSON RPC error * @throws IOException network error */ public List<SmartPropertyListInfo> omniListProperties() throws JsonRpcException, IOException { JavaType resultType = mapper.getTypeFactory().constructCollectionType(List.class, SmartPropertyListInfo.class); return send("omni_listproperties", resultType); } /** * Returns information about the specified currency, property, or token. * * @param currency The identifier to look up * @return Omni Smart Property Info * @throws JsonRpcException JSON RPC error * @throws IOException network error */ public OmniPropertyInfo omniGetProperty(CurrencyID currency) throws JsonRpcException, IOException { OmniPropertyInfo result = send("omni_getproperty", OmniPropertyInfo.class, currency); return result; } /** * Returns information about a crowdsale. * * @param currency The identifier of the crowdsale * @return An object with detailed information * @throws JsonRpcException JSON RPC error * @throws IOException network error */ public Map<String, Object> omniGetCrowdsale(CurrencyID currency) throws JsonRpcException, IOException { Map<String, Object> result = send("omni_getcrowdsale", currency); return result; } /** * Lists currently active crowdsales. * * @return A list with information about active crowdsales * @throws JsonRpcException JSON RPC error * @throws IOException network error */ public List<Map<String, Object>> omniGetActiveCrowdsales() throws JsonRpcException, IOException { List<Map<String, Object>> result = send("omni_getactivecrowdsales"); return result; } /** * Lists currently active offers on the distributed BTC/OMNI exchange. * * @return A list with information about the active offers * @throws JsonRpcException JSON RPC error * @throws IOException network error */ public List<Map<String, Object>> omniGetActiveDExSells() throws JsonRpcException, IOException { List<Map<String, Object>> result = send("omni_getactivedexsells"); return result; } /** * Returns the balance for a given address and property. * * @param address The address to look up * @param currency The identifier of the token to look up * @return The available and reserved balance * @throws JsonRpcException JSON RPC error * @throws IOException network error */ public BalanceEntry omniGetBalance(Address address, CurrencyID currency) throws JsonRpcException, IOException { return send("omni_getbalance", BalanceEntry.class, address, currency.getValue()); } /** * Returns a sorted map of address-balances for a given identifier. * * @param currency The identifier of the token to look up * @return A Sorted Map indexed by addresses to available and reserved balances * @throws JsonRpcException JSON RPC error * @throws IOException network error */ public SortedMap<Address, BalanceEntry> omniGetAllBalancesForId(CurrencyID currency) throws JsonRpcException, IOException { return send("omni_getallbalancesforid", AddressBalanceEntries.class, currency); } /** * Returns a list of address-balances for a given identifier. * * @param currency The identifier of the token to look up * @return A list of address-balances * @throws JsonRpcException JSON RPC error * @throws IOException network error */ public List<AddressBalanceEntry> omniGetAllBalancesForIdAsList(CurrencyID currency) throws JsonRpcException, IOException { JavaType resultType = mapper.getTypeFactory().constructCollectionType(List.class, AddressBalanceEntry.class); return send("omni_getallbalancesforid", resultType, currency); } /** * Returns a sorted map of all token balances for a given address. * * @param address The address to look up * @return A Sorted Map indexed by currency/propertyid to available and reserved balances * @throws JsonRpcException JSON RPC error * @throws IOException network error */ public SortedMap<CurrencyID, BalanceEntry> omniGetAllBalancesForAddress(Address address) throws JsonRpcException, IOException { return send("omni_getallbalancesforaddress", PropertyBalanceEntries.class, address); } /** * Returns a list of all token balances for a given address. * @param address The address to look up * @return A List of {@link PropertyBalanceEntry} * @throws JsonRpcException JSON RPC error * @throws IOException network error */ public List<PropertyBalanceEntry> omniGetAllBalancesForAddressAsList(Address address) throws JsonRpcException, IOException { JavaType resultType = mapper.getTypeFactory().constructCollectionType(List.class, PropertyBalanceEntry.class); return send("omni_getallbalancesforaddress", resultType, address); } /** * Returns information about an Omni Layer transaction. * * @param txid The hash of the transaction to look up * @return Information about the transaction * @throws JsonRpcException JSON RPC error * @throws IOException network error */ public Map<String, Object> omniGetTransaction(Sha256Hash txid) throws JsonRpcException, IOException { Map<String, Object> transaction = send("omni_gettransaction", txid); return transaction; } /** * Lists all Omni transactions in a block. * * @param blockIndex The block height or block index * @return A list of transaction hashes * @throws JsonRpcException JSON RPC error * @throws IOException network error */ public List<Sha256Hash> omniListBlockTransactions(Integer blockIndex) throws JsonRpcException, IOException { JavaType resultType = mapper.getTypeFactory().constructCollectionType(List.class, Sha256Hash.class); return send("omni_listblocktransactions", resultType, blockIndex); } /** * Broadcasts a raw Omni Layer transaction. * * @param fromAddress The address to send from * @param rawTxHex The hex-encoded raw transaction * @return The hash of the transaction * @throws JsonRpcException JSON RPC error * @throws IOException network error */ @Override public Sha256Hash omniSendRawTx(Address fromAddress, String rawTxHex) throws JsonRpcException, IOException { return omniSendRawTx(fromAddress, rawTxHex, null); } /** * Broadcasts a raw Omni Layer transaction with reference address. * * @param fromAddress The address to send from * @param rawTxHex The hex-encoded raw transaction * @param referenceAddress The reference address * @return The hash of the transaction * @throws JsonRpcException JSON RPC error * @throws IOException network error */ @Override public Sha256Hash omniSendRawTx(Address fromAddress, String rawTxHex, Address referenceAddress) throws JsonRpcException, IOException { return send("omni_sendrawtx", Sha256Hash.class, fromAddress, rawTxHex, referenceAddress); } /** * Creates and broadcasts a "simple send" transaction. * * @param fromAddress The address to spent from * @param toAddress The address to send to * @param currency The identifier of the token to transfer * @param amount The amount to transfer (Divisible/Indivisible type should match currency ID) * @return The hash of the transaction * @throws JsonRpcException JSON RPC error * @throws IOException network error */ public Sha256Hash omniSend(Address fromAddress, Address toAddress, CurrencyID currency, OmniValue amount) throws JsonRpcException, IOException { return send("omni_send", Sha256Hash.class, fromAddress, toAddress, currency, amount); } /** * Creates and broadcasts a "send to owners" transaction. * * @param fromAddress The address to spent from * @param currency The identifier of the token to distribute * @param amount The amount to distribute * @return The hash of the transaction * @throws JsonRpcException JSON RPC error * @throws IOException network error */ public Sha256Hash omniSendSTO(Address fromAddress, CurrencyID currency, OmniValue amount) throws JsonRpcException, IOException { return send("omni_sendsto", Sha256Hash.class, fromAddress, currency, amount); } /** * Creates and broadcasts a "send all" transaction. * * @param fromAddress The address to spent from * @param toAddress The address to send to * @param ecosystem The ecosystem of the tokens to send * @return The hash of the transaction * @throws JsonRpcException JSON RPC error * @throws IOException network error * @since Omni Core 0.0.10 */ public Sha256Hash omniSendAll(Address fromAddress, Address toAddress, Ecosystem ecosystem) throws JsonRpcException, IOException { return send("omni_sendall", Sha256Hash.class, fromAddress, toAddress, ecosystem); } /** * Creates an offer on the traditional distributed exchange. * * @param fromAddress The address * @param currencyId The identifier of the currency for sale * @param amountForSale The amount of currency (BigDecimal coins) * @param amountDesired The amount of desired Bitcoin (in BTC) * @param paymentWindow The payment window measured in blocks * @param commitmentFee The minimum transaction fee required to be paid as commitment when accepting this offer * @param action The action applied to the offer (1 = new, 2 = update, 3 = cancel) * @return The hash of the transaction * @throws JsonRpcException JSON RPC error * @throws IOException network error * @since Omni Core 0.0.10 */ public Sha256Hash omniSendDExSell(Address fromAddress, CurrencyID currencyId, OmniValue amountForSale, Coin amountDesired, Byte paymentWindow, Coin commitmentFee, Byte action) throws JsonRpcException, IOException { return send("omni_senddexsell", Sha256Hash.class, fromAddress, currencyId, amountForSale, amountDesired.toString(), // Omni Core expects string for BTC value, unlike BTC RPCs? paymentWindow, commitmentFee.toString(), action); } /** * Create and broadcast an accept order for the specified token and amount. * * @param fromAddress The address to send from * @param toAddress The address of the seller * @param currencyId The identifier of the token to purchase * @param amount The amount to accept * @param override Override minimum accept fee and payment window checks (use with caution!) * @return The hash of the transaction * @throws JsonRpcException JSON RPC error * @throws IOException network error * @since Omni Core 0.0.10 */ public Sha256Hash omniSendDExAccept(Address fromAddress, Address toAddress, CurrencyID currencyId, OmniValue amount, Boolean override) throws JsonRpcException, IOException { return send("omni_senddexaccept", Sha256Hash.class, fromAddress, toAddress, currencyId, amount, override); } /** * Place a trade offer on the distributed token exchange. * * @param fromAddress The address to trade with * @param propertyForSale The identifier of the tokens to list for sale * @param amountForSale The amount of tokens to list for sale * @param propertyDesired The identifier of the tokens desired in exchange * @param amountDesired The amount of tokens desired in exchange * @return The hash of the transaction * @throws JsonRpcException JSON RPC error * @throws IOException network error * @since Omni Core 0.0.10 */ public Sha256Hash omniSendTrade(Address fromAddress, CurrencyID propertyForSale, OmniValue amountForSale, CurrencyID propertyDesired, OmniValue amountDesired) throws JsonRpcException, IOException { return send("omni_sendtrade", Sha256Hash.class, fromAddress, propertyForSale, amountForSale, propertyDesired, amountDesired); } /** * Cancel offers on the distributed token exchange with the specified price. * * @param fromAddress The address to trade with * @param propertyForSale The identifier of the tokens to list for sale * @param amountForSale The amount of tokens to list for sale * @param propertyDesired The identifier of the tokens desired in exchange * @param amountDesired The amount of tokens desired in exchange * @return The hash of the transaction * @throws JsonRpcException JSON RPC error * @throws IOException network error * @since Omni Core 0.0.10 */ public Sha256Hash omniSendCancelTradesByPrice(Address fromAddress, CurrencyID propertyForSale, OmniValue amountForSale, CurrencyID propertyDesired, OmniValue amountDesired) throws JsonRpcException, IOException { return send("omni_sendcanceltradesbyprice", Sha256Hash.class, fromAddress, propertyForSale, amountForSale, propertyDesired, amountDesired); } /** * Cancel all offers on the distributed token exchange with the given currency pair. * * @param fromAddress The address to trade with * @param propertyForSale The identifier of the tokens listed for sale * @param propertyDesired The identifier of the tokens desired in exchange * @return The hash of the transaction * @throws JsonRpcException JSON RPC error * @throws IOException network error * @since Omni Core 0.0.10 */ public Sha256Hash omniSendCancelTradesByPair(Address fromAddress, CurrencyID propertyForSale, CurrencyID propertyDesired) throws JsonRpcException, IOException { return send("omni_sendcanceltradesbypair", Sha256Hash.class, fromAddress, propertyForSale, propertyDesired); } /** * Cancel all offers on the distributed token exchange with the given currency pair. * * @param fromAddress The address to trade with * @param ecosystem The ecosystem of the offers to cancel: (1) main, (2) test * @return The hash of the transaction * @throws JsonRpcException JSON RPC error * @throws IOException network error * @since Omni Core 0.0.10 */ public Sha256Hash omniSendCancelAllTrades(Address fromAddress, Ecosystem ecosystem) throws JsonRpcException, IOException { return send("omni_sendcancelalltrades", Sha256Hash.class, fromAddress, ecosystem); } /** * Create new tokens with fixed supply. * * @param fromAddress The address to send from * @param ecosystem The ecosystem to create the tokens in * @param propertyType The type of the tokens to create * @param previousId An identifier of a predecessor token (0 for new tokens) * @param category A category for the new tokens (can be "") * @param subCategory A subcategory for the new tokens (can be "") * @param name The name of the new tokens to create * @param url An URL for further information about the new tokens (can be "") * @param data A description for the new tokens (can be "") * @param amount The number of tokens to create * @return The hash of the transaction * @throws JsonRpcException JSON RPC error * @throws IOException network error * @since Omni Core 0.0.10 */ public Sha256Hash omniSendIssuanceFixed(Address fromAddress, Ecosystem ecosystem, PropertyType propertyType, CurrencyID previousId, String category, String subCategory, String name, String url, String data, OmniValue amount) throws JsonRpcException, IOException { return send("omni_sendissuancefixed", Sha256Hash.class, fromAddress, ecosystem, propertyType, previousId, category, subCategory, name, url, data, amount); } /** * Create new tokens as crowdsale. * * @param fromAddress The address to send from * @param ecosystem The ecosystem to create the tokens in * @param propertyType The type of the tokens to create * @param previousId An identifier of a predecessor token (0 for new tokens) * @param category A category for the new tokens (can be "") * @param subCategory A subcategory for the new tokens (can be "") * @param name The name of the new tokens to create * @param url An URL for further information about the new tokens (can be "") * @param data A description for the new tokens (can be "") * @param propertyDesired the identifier of a token eligible to participate in the crowdsale * @param tokensPerUnit the amount of tokens granted per unit invested in the crowdsale * @param deadline the deadline of the crowdsale as Unix timestamp * @param earlyBirdBonus an early bird bonus for participants in percent per week * @param issuerBonus a percentage of tokens that will be granted to the issuer * @return The hash of the transaction * @throws JsonRpcException JSON RPC error * @throws IOException network error * @since Omni Core 0.0.10 */ public Sha256Hash omniSendIssuanceCrowdsale(Address fromAddress, Ecosystem ecosystem, PropertyType propertyType, CurrencyID previousId, String category, String subCategory, String name, String url, String data, CurrencyID propertyDesired, BigDecimal tokensPerUnit, Long deadline, Byte earlyBirdBonus, Byte issuerBonus) throws JsonRpcException, IOException { return send("omni_sendissuancecrowdsale", Sha256Hash.class, fromAddress, ecosystem, propertyType, previousId, category, subCategory, name, url, data, propertyDesired, tokensPerUnit.toPlainString(), deadline, earlyBirdBonus, issuerBonus); } /** * Manually close a crowdsale. * * @param fromAddress The address associated with the crowdsale to close * @param propertyId The identifier of the crowdsale to close * @return The hash of the transaction * @throws JsonRpcException JSON RPC error * @throws IOException network error * @since Omni Core 0.0.10 */ public Sha256Hash omniSendCloseCrowdsale(Address fromAddress, CurrencyID propertyId) throws JsonRpcException, IOException { return send("omni_sendclosecrowdsale", Sha256Hash.class, fromAddress, propertyId); } /** * Create new tokens with manageable supply. * * @param fromAddress The address to send from * @param ecosystem The ecosystem to create the tokens in * @param propertyType The type of the tokens to create * @param previousId An identifier of a predecessor token (0 for new tokens) * @param category A category for the new tokens (can be "") * @param subCategory A subcategory for the new tokens (can be "") * @param name The name of the new tokens to create * @param url An URL for further information about the new tokens (can be "") * @param data A description for the new tokens (can be "") * @return The hash of the transaction * @throws JsonRpcException JSON RPC error * @throws IOException network error * @since Omni Core 0.0.10 */ public Sha256Hash omniSendIssuanceManaged(Address fromAddress, Ecosystem ecosystem, PropertyType propertyType, CurrencyID previousId, String category, String subCategory, String name, String url, String data) throws JsonRpcException, IOException { return send("omni_sendissuancemanaged", Sha256Hash.class, fromAddress, ecosystem, propertyType, previousId, category, subCategory, name, url, data); } /** * Issue or grant new units of managed tokens. * * @param fromAddress The address to send from * @param toAddress The receiver of the tokens * @param propertyId The identifier of the tokens to grant * @param amount The amount of tokens to create * @return The hash of the transaction * @throws JsonRpcException JSON RPC error * @throws IOException network error * @since Omni Core 0.0.10 */ public Sha256Hash omniSendGrant(Address fromAddress, Address toAddress, CurrencyID propertyId, OmniValue amount) throws JsonRpcException, IOException { return send("omni_sendgrant", Sha256Hash.class, fromAddress, toAddress, propertyId, amount); } /** * Revoke units of managed tokens. * * @param fromAddress The address to revoke the tokens from * @param propertyId The identifier of the tokens to revoke * @param amount The amount of tokens to revoke * @return The hash of the transaction * @throws JsonRpcException JSON RPC error * @throws IOException network error * @since Omni Core 0.0.10 */ public Sha256Hash omniSendRevoke(Address fromAddress, CurrencyID propertyId, OmniValue amount) throws JsonRpcException, IOException { return send("omni_sendrevoke", Sha256Hash.class, fromAddress, propertyId, amount); } /** * Change the issuer on record of the given tokens. * * @param fromAddress The address associated with the tokens * @param toAddress The address to transfer administrative control to * @param propertyId The identifier of the tokens * @return The hash of the transaction * @throws JsonRpcException JSON RPC error * @throws IOException network error * @since Omni Core 0.0.10 */ public Sha256Hash omniSendChangeIssuer(Address fromAddress, Address toAddress, CurrencyID propertyId) throws JsonRpcException, IOException { return send("omni_sendchangeissuer", Sha256Hash.class, fromAddress, toAddress, propertyId); } /** * Activates a protocol feature. * * @param fromAddress The address to send from * @param featureId The identifier of the feature to activate * @param block The activation block * @param minVersion The minimum supported client version * @return The hash of the transaction * @throws JsonRpcException JSON RPC error * @throws IOException network error * @since Omni Core 0.0.10 */ public Sha256Hash omniSendActivation(Address fromAddress, Short featureId, Integer block, Integer minVersion) throws JsonRpcException, IOException { return send("omni_sendactivation", Sha256Hash.class, fromAddress, featureId, block, minVersion); } /** * Get information and recipients of a send-to-owners transaction. * * @param txid The hash of the transaction to lookup * @return Information about the transaction * @throws JsonRpcException JSON RPC error * @throws IOException network error */ public Map<String, Object> omniGetSTO(Sha256Hash txid) throws JsonRpcException, IOException { String filter = "*"; // no filter at all Map<String, Object> stoInfo = send("omni_getsto", txid, filter); return stoInfo; } /** * Returns information about an order on the distributed token exchange. * * @param txid The transaction hash of the order to look up * @return Information about the order, trade, and order matches * @throws JsonRpcException JSON RPC error * @throws IOException network error * @since Omni Core 0.0.10 */ public Map<String, Object> omniGetTrade(Sha256Hash txid) throws JsonRpcException, IOException { Map<String, Object> trade = send("omni_gettrade", txid); return trade; } /** * Lists orders on the distributed token exchange with the given token for sale. * * @param propertyForSale The identifier of the token for sale, used as filter * @return A list of orders * @throws JsonRpcException JSON RPC error * @throws IOException network error * @since Omni Core 0.0.10 */ public List<Map<String, Object>> omniGetOrderbook(CurrencyID propertyForSale) throws JsonRpcException, IOException { List<Map<String, Object>> orders = send("omni_getorderbook", propertyForSale); return orders; } /** * Lists orders on the distributed token exchange with the given token for sale, and token desired. * * @param propertyForSale The identifier of the token for sale, used as filter * @param propertyDesired The identifier of the token desired, used as filter * @return A list of orders * @throws JsonRpcException JSON RPC error * @throws IOException network error * @since Omni Core 0.0.10 */ public List<Map<String, Object>> omniGetOrderbook(CurrencyID propertyForSale, CurrencyID propertyDesired) throws JsonRpcException, IOException { List<Map<String, Object>> orders = send("omni_getorderbook", propertyForSale, propertyDesired); return orders; } /** * Returns information about granted and revoked units of managed tokens. * * @param propertyid The identifier of the managed tokens to lookup * @return A list of grants and revokes * @throws JsonRpcException JSON RPC error * @throws IOException network error */ public List<Map<String, Object>> omniGetGrants(CurrencyID propertyid) throws JsonRpcException, IOException { List<Map<String, Object>> orders = send("omni_getgrants", propertyid); return orders; } /** * Returns pending and completed feature activations. * * @return Pending and complete feature activations * @throws JsonRpcException JSON RPC error * @throws IOException network error * @since Omni Core 0.0.10 */ public Map<String, List<Map<String, Object>>> omniGetActivations() throws JsonRpcException, IOException { Map<String, List<Map<String, Object>>> activations = send("omni_getactivations"); return activations; } /** * Obtains the current amount of fees cached (pending distribution). * * If a property ID is supplied the results will be filtered to show this property ID only. If no property ID is * supplied the results will contain all properties that currently have fees cached pending distribution. * * @param propertyid the identifier of the property to filter results on * @return A list of amounts of fees cached * @throws JsonRpcException JSON RPC error * @throws IOException network error * @since Omni Core 0.0.11 */ public List<Map<String, Object>> omniGetFeeCache(CurrencyID propertyid) throws JsonRpcException, IOException { List<Map<String, Object>> cache = send("omni_getfeecache", propertyid); return cache; } /** * Obtains the amount at which cached fees will be distributed. * * If a property ID is supplied the results will be filtered to show this property ID only. If no property ID is * supplied the results will contain all properties. * * @param propertyId the identifier of the property to filter results on * @return A list of amounts of fees required to trigger distribution * @throws JsonRpcException JSON RPC error * @throws IOException network error * @since Omni Core 0.0.11 */ public List<Map<String, Object>> omniGetFeeTrigger(CurrencyID propertyId) throws JsonRpcException, IOException { List<Map<String, Object>> triggers = send("omni_getfeetrigger", propertyId); return triggers; } /** * Obtains the current percentage share of fees addresses would receive if a distribution were to occur. * * If an address is supplied the results will be filtered to show this address only. If no address is supplied the * results will be filtered to show wallet addresses only. * * If an ecosystem is supplied the results will reflect the fee share for that ecosystem (main or test). If no * ecosystem is supplied the results will reflect the main ecosystem. * * @param address the address to filter results on * @param ecosystem the ecosystem to obtain the current percentage fee share * @return A list of percentages of fees the address(es) will receive based on the current state * @throws JsonRpcException JSON RPC error * @throws IOException network error * @since Omni Core 0.0.11 */ public List<Map<String, Object>> omniGetFeeShare(Address address, Ecosystem ecosystem) throws JsonRpcException, IOException { List<Map<String, Object>> shares; if (address == null) { shares = send("omni_getfeeshare", "", ecosystem); } else { shares = send("omni_getfeeshare", address, ecosystem); } return shares; } /** * Obtains data for a past distribution of fees. * * A distribution ID must be supplied to identify the distribution to obtain data for. * * @param distributionId the identifier of the distribution to obtain data for * @return Information about a fee distribution * @throws JsonRpcException JSON RPC error * @throws IOException network error * @since Omni Core 0.0.11 */ public Map<String, Object> omniGetFeeDistribution(Integer distributionId) throws JsonRpcException, IOException { Map<String, Object> info = send("omni_getfeedistribution", distributionId); return info; } /** * Obtains data for past distributions of fees for a property. * * A property ID must be supplied to retrieve past distributions for. * * @param propertyId the identifier of the property to retrieve past distributions for * @return A list of fee distributions * @throws JsonRpcException JSON RPC error * @throws IOException network error * @since Omni Core 0.0.11 */ public List<Map<String, Object>> omniGetFeeDistributions(CurrencyID propertyId) throws JsonRpcException, IOException { List<Map<String, Object>> infos = send("omni_getfeedistributions", propertyId); return infos; } }
package org.jetbrains.plugins.scala.util; import scala.tools.ant.Scalac; public class AntScalaCompiler extends Scalac { public void execute() { setAddparams("-Xgenerics"); setAddparams("-target:jvm-1.5"); super.execute(); } }
package org.opencms.file.types; import org.opencms.file.CmsObject; import org.opencms.file.CmsProperty; import org.opencms.file.CmsResource; import org.opencms.main.CmsException; import org.opencms.main.CmsLog; import org.opencms.util.CmsMacroResolver; import org.opencms.util.CmsStringUtil; import org.opencms.xml.content.CmsDefaultXmlContentHandler; import java.util.List; import org.apache.commons.logging.Log; /** * Resource type descriptor for the type "jsprenderer".<p> * * @author Tobias Herrmann * * @version $Revision: 1.2 $ * * @since 7.9.0 */ public class CmsResourceTypeJspRenderer extends CmsResourceTypeXmlContent { /** The log object for this class. */ private static final Log LOG = CmsLog.getLog(CmsResourceTypeJspRenderer.class); /** Property name for formatter property. */ protected static final String PROPERTY_FORMATTER = "ade.formatter"; /** Property name for container types property. */ protected static final String PROPERTY_CONTAINERTYPES = "ade.containertypes"; /** Macro key to resolve container type. */ private static final String MACRO_CONTAINERTYPE = "ade.containertype"; /** * @see org.opencms.file.types.I_CmsResourceType#getFormatterForContainerType(CmsObject, CmsResource, String) */ @Override public String getFormatterForContainerType(CmsObject cms, CmsResource resource, String containerType) { if (containerType.equals(CmsDefaultXmlContentHandler.DEFAULT_FORMATTER_TYPE)) { return CmsDefaultXmlContentHandler.DEFAULT_FORMATTER; } try { CmsProperty formatterProp = cms.readPropertyObject(resource, PROPERTY_FORMATTER, true); String formatter = formatterProp.getValue(); if (!CmsStringUtil.isEmptyOrWhitespaceOnly(formatter)) { CmsMacroResolver resolver = CmsMacroResolver.newInstance(); resolver.addMacro(MACRO_CONTAINERTYPE, containerType); formatter = resolver.resolveMacros(formatter); CmsProperty typesProp = cms.readPropertyObject(resource, PROPERTY_CONTAINERTYPES, true); List<String> types = typesProp.getValueList(); if (types.isEmpty() || types.contains(containerType)) { return formatter; } } } catch (CmsException e) { if (LOG.isErrorEnabled()) { LOG.error(Messages.get().getBundle().key( Messages.ERR_READING_FORMATTER_CONFIGURATION_1, cms.getSitePath(resource)), e); } } return null; } }
package org.pentaho.di.spoon.delegates; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.pentaho.di.core.dialog.ErrorDialog; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.gui.GUIResource; import org.pentaho.di.core.gui.Point; import org.pentaho.di.spoon.Messages; import org.pentaho.di.spoon.Spoon; import org.pentaho.di.trans.TransHopMeta; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.StepDialogInterface; import org.pentaho.di.trans.step.StepErrorMeta; import org.pentaho.di.trans.step.StepErrorMetaDialog; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; public class SpoonStepsDelegate extends SpoonDelegate { public SpoonStepsDelegate(Spoon spoon) { super(spoon); } public void editStepErrorHandling(TransMeta transMeta, StepMeta stepMeta) { if (stepMeta != null && stepMeta.supportsErrorHandling()) { StepErrorMeta stepErrorMeta = stepMeta.getStepErrorMeta(); if (stepErrorMeta == null) { stepErrorMeta = new StepErrorMeta(transMeta, stepMeta); } List<StepMeta> targetSteps = new ArrayList<StepMeta>(); int nrNext = transMeta.findNrNextSteps(stepMeta); for (int i = 0; i < nrNext; i++) targetSteps.add(transMeta.findNextStep(stepMeta, i)); // now edit this stepErrorMeta object: StepErrorMetaDialog dialog = new StepErrorMetaDialog(spoon.getShell(), stepErrorMeta, transMeta, targetSteps); if (dialog.open()) { stepMeta.setStepErrorMeta(stepErrorMeta); spoon.refreshGraph(); } } } public void dupeStep(TransMeta transMeta, StepMeta stepMeta) { spoon.getLog().logDebug(toString(), Messages.getString("Spoon.Log.DuplicateStep") + stepMeta.getName());// Duplicate // step: StepMeta stMeta = (StepMeta) stepMeta.clone(); if (stMeta != null) { String newname = transMeta.getAlternativeStepname(stepMeta.getName()); int nr = 2; while (transMeta.findStep(newname) != null) { newname = stepMeta.getName() + " (copy " + nr + ")"; nr++; } stMeta.setName(newname); // Don't select this new step! stMeta.setSelected(false); Point loc = stMeta.getLocation(); stMeta.setLocation(loc.x + 20, loc.y + 20); transMeta.addStep(stMeta); spoon.addUndoNew(transMeta, new StepMeta[] { (StepMeta) stMeta.clone() }, new int[] { transMeta .indexOfStep(stMeta) }); spoon.refreshTree(); spoon.refreshGraph(); } } public void clipStep(StepMeta stepMeta) { String xml = stepMeta.getXML(); GUIResource.getInstance().toClipboard(xml); } public String editStep(TransMeta transMeta, StepMeta stepMeta) { boolean refresh = false; try { String name = stepMeta.getName(); // Before we do anything, let's store the situation the way it // was... StepMeta before = (StepMeta) stepMeta.clone(); StepDialogInterface dialog = spoon.getStepEntryDialog(stepMeta.getStepMetaInterface(), transMeta, name); String stepname = null; if (dialog != null) { dialog.setRepository(spoon.getRepository()); stepname = dialog.open(); } if (stepname != null) { // See if the new name the user enter, doesn't collide with // another step. // If so, change the stepname and warn the user! String newname = stepname; StepMeta smeta = transMeta.findStep(newname, stepMeta); int nr = 2; while (smeta != null) { newname = stepname + " " + nr; smeta = transMeta.findStep(newname); nr++; } if (nr > 2) { stepname = newname; MessageBox mb = new MessageBox(spoon.getShell(), SWT.OK | SWT.ICON_INFORMATION); mb.setMessage(Messages.getString("Spoon.Dialog.StepnameExists.Message", stepname)); // $NON-NLS-1$ mb.setText(Messages.getString("Spoon.Dialog.StepnameExists.Title")); // $NON-NLS-1$ mb.open(); } if (!stepname.equals(name)) refresh = true; stepMeta.setName(stepname); // OK, so the step has changed... // Backup the situation for undo/redo StepMeta after = (StepMeta) stepMeta.clone(); spoon.addUndoChange(transMeta, new StepMeta[] { before }, new StepMeta[] { after }, new int[] { transMeta.indexOfStep(stepMeta) }); } else { // Scenario: change connections and click cancel... // Perhaps new connections were created in the step dialog? if (transMeta.haveConnectionsChanged()) { refresh = true; } } spoon.refreshGraph(); // name is displayed on the graph too. // TODO: verify "double pathway" steps for bug #4365 // After the step was edited we can complain about the possible // deadlock here. } catch (Throwable e) { if (spoon.getShell().isDisposed()) return null; new ErrorDialog(spoon.getShell(), Messages.getString("Spoon.Dialog.UnableOpenDialog.Title"), Messages.getString("Spoon.Dialog.UnableOpenDialog.Message"), new Exception(e)); } if (refresh) spoon.refreshTree(); // Perhaps new connections were created in // the step // dialog or the step name changed. return stepMeta.getName(); } public void delStep(TransMeta transMeta, StepMeta stepMeta) { spoon.getLog().logDebug(toString(), Messages.getString("Spoon.Log.DeleteStep") + stepMeta.getName());// "Delete // step: for (int i = transMeta.nrTransHops() - 1; i >= 0; i { TransHopMeta hi = transMeta.getTransHop(i); if (hi.getFromStep().equals(stepMeta) || hi.getToStep().equals(stepMeta)) { spoon.addUndoDelete(transMeta, new TransHopMeta[] { hi }, new int[] { transMeta .indexOfTransHop(hi) }, true); transMeta.removeTransHop(i); spoon.refreshTree(); } } int pos = transMeta.indexOfStep(stepMeta); transMeta.removeStep(pos); spoon.addUndoDelete(transMeta, new StepMeta[] { stepMeta }, new int[] { pos }); spoon.refreshTree(); spoon.refreshGraph(); } public StepDialogInterface getStepEntryDialog(StepMetaInterface stepMeta, TransMeta transMeta, String stepName) throws KettleException { String dialogClassName = stepMeta.getDialogClassName(); Class<?> dialogClass; Class<?>[] paramClasses = new Class[] { Shell.class, Object.class, TransMeta.class, String.class }; Object[] paramArgs = new Object[] { spoon.getShell(), stepMeta, transMeta, stepName }; Constructor<?> dialogConstructor; try { dialogClass = stepMeta.getClass().getClassLoader().loadClass(dialogClassName); dialogConstructor = dialogClass.getConstructor(paramClasses); return (StepDialogInterface) dialogConstructor.newInstance(paramArgs); } catch (Exception e) { // try the old way for compatibility Method method = null; try { Class sig[] = new Class[] {Shell.class, StepMetaInterface.class, TransMeta.class, String.class}; method = stepMeta.getClass().getDeclaredMethod( "getDialog", sig ); if( method != null ) { return (StepDialogInterface) method.invoke( stepMeta, new Object[] { spoon.getShell(), stepMeta, transMeta, stepName } ); } } catch (Throwable t) { } throw new KettleException(e); } } }
package org.texastorque.texastorque2015.input; import org.texastorque.torquelib.util.GenericController; import org.texastorque.torquelib.util.TorqueFilter; public class DriverInput extends Input { private GenericController driver; private GenericController operator; private TorqueFilter driveAccelFilter; private TorqueFilter turnAccelFilter; public DriverInput() { driver = new GenericController(0, GenericController.TYPE_XBOX, 0.2); operator = new GenericController(1, GenericController.TYPE_XBOX, 0.2); driveAccelFilter = new TorqueFilter(50); turnAccelFilter = new TorqueFilter(50); override = false; armOpen = false; punchOut = false; tiltUp = false; } @Override public void run() { if (operator.getLeftCenterButton()) { override = true; } else if (operator.getRightCenterButton()) { override = false; } if (override) { calcOverride(); } else { calcElevator(); } calcIntake(); calcDrivebase(); } //Drivebase private void calcDrivebase() { strafeSpeed = driver.getLeftXAxis(); if (driver.getLeftBumper()) { driveAccelFilter.add(-driver.getLeftYAxis()); turnAccelFilter.add(driver.getRightXAxis()); leftSpeed = (driveAccelFilter.getAverage() + turnAccelFilter.getAverage()) / 2; rightSpeed = (driveAccelFilter.getAverage() - turnAccelFilter.getAverage()) / 2; } else { driveAccelFilter.reset(); turnAccelFilter.reset(); leftSpeed = -1 * driver.getLeftYAxis() + driver.getRightXAxis(); rightSpeed = -1 * driver.getLeftYAxis() - driver.getRightXAxis(); } } private void calcElevator() { } private void calcOverride() { overrideElevatorMotorSpeed = -1 * operator.getLeftYAxis(); } private void calcIntake() { if (operator.getRightBumper()) { leftIntakeSpeed = 1.0 - operator.getRightXAxis(); rightIntakeSpeed = 1.0 + operator.getRightXAxis(); intakeIn = operator.getRightYAxis() > 0.75; } else { leftIntakeSpeed = 0.0; rightIntakeSpeed = 0.0; intakeIn = false; } } }
package org.torproject.jtor.directory.impl; import java.util.Date; import org.torproject.jtor.data.HexDigest; import org.torproject.jtor.directory.Directory; import org.torproject.jtor.directory.GuardEntry; import org.torproject.jtor.directory.Router; public class GuardEntryImpl implements GuardEntry { private final static String NL = System.getProperty("line.separator"); private final Directory directory; private final StateFile stateFile; private final String nickname; private final String identity; private final Object lock = new Object(); private String version; private Date createdTime; private boolean isAdded; private Date unlistedSince; private Date downSince; private Date lastConnect; GuardEntryImpl(Directory directory, StateFile stateFile, String nickname, String identity) { this.directory = directory; this.stateFile = stateFile; this.nickname = nickname; this.identity = identity; } void setAddedFlag() { isAdded = true; } void setVersion(String version) { this.version = version; } void setCreatedTime(Date date) { this.createdTime = date; } void setUnlistedSince(Date date) { synchronized(lock) { unlistedSince = date; } } void setDownSince(Date downSince, Date lastTried) { synchronized (lock) { this.downSince = downSince; this.lastConnect = lastTried; } } public boolean isAdded() { return isAdded; } public void markAsDown() { synchronized(lock) { final Date now = new Date(); if(downSince == null) { downSince = now; } else { lastConnect = now; } } if(isAdded) { stateFile.writeFile(); } } public void clearDownSince() { synchronized (lock) { downSince = null; lastConnect = null; } if(isAdded) { stateFile.writeFile(); } } public void clearUnlistedSince() { synchronized (lock) { unlistedSince = null; } if(isAdded) { stateFile.writeFile(); } } public String getNickname() { return nickname; } public String getIdentity() { return identity; } public String getVersion() { return version; } public Date getCreatedTime() { synchronized (lock) { return dup(createdTime); } } public Date getDownSince() { synchronized (lock) { return dup(downSince); } } public Date getLastConnectAttempt() { synchronized (lock) { return dup(lastConnect); } } public Date getUnlistedSince() { synchronized (lock) { return dup(unlistedSince); } } private Date dup(Date date) { if(date == null) { return null; } else { return new Date(date.getTime()); } } public String writeToString() { final StringBuilder sb = new StringBuilder(); synchronized (lock) { appendEntryGuardLine(sb); appendEntryGuardAddedBy(sb); if(downSince != null) { appendEntryGuardDownSince(sb); } if(unlistedSince != null) { appendEntryGuardUnlistedSince(sb); } } return sb.toString(); } private void appendEntryGuardLine(StringBuilder sb) { sb.append(StateFile.KEYWORD_ENTRY_GUARD); sb.append(" "); sb.append(nickname); sb.append(" "); sb.append(identity); sb.append(NL); } private void appendEntryGuardAddedBy(StringBuilder sb) { sb.append(StateFile.KEYWORD_ENTRY_GUARD_ADDED_BY); sb.append(" "); sb.append(identity); sb.append(" "); sb.append(version); sb.append(" "); sb.append(formatDate(createdTime)); sb.append(NL); } private void appendEntryGuardDownSince(StringBuilder sb) { if(downSince == null) { return; } sb.append(StateFile.KEYWORD_ENTRY_GUARD_DOWN_SINCE); sb.append(" "); sb.append(formatDate(downSince)); if(lastConnect != null) { sb.append(" "); sb.append(formatDate(lastConnect)); } sb.append(NL); } private void appendEntryGuardUnlistedSince(StringBuilder sb) { if(unlistedSince == null) { return; } sb.append(StateFile.KEYWORD_ENTRY_GUARD_UNLISTED_SINCE); sb.append(" "); sb.append(formatDate(unlistedSince)); sb.append(NL); } private String formatDate(Date date) { return stateFile.formatDate(date); } public Router getRouterForEntry() { final HexDigest id = HexDigest.createFromString(identity); return directory.getRouterByIdentity(id); } public boolean testCurrentlyUsable() { final Router router = getRouterForEntry(); boolean isUsable = router != null && router.isValid() && router.isPossibleGuard() && router.isRunning(); if(isUsable) { markUsable(); return true; } else { markUnusable(); return false; } } private void markUsable() { synchronized (lock) { if(unlistedSince != null) { unlistedSince = null; if(isAdded) { stateFile.writeFile(); } } } } private synchronized void markUnusable() { synchronized (lock) { if(unlistedSince == null) { unlistedSince = new Date(); if(isAdded) { stateFile.writeFile(); } } } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((identity == null) ? 0 : identity.hashCode()); result = prime * result + ((nickname == null) ? 0 : nickname.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; GuardEntryImpl other = (GuardEntryImpl) obj; if (identity == null) { if (other.identity != null) return false; } else if (!identity.equals(other.identity)) return false; if (nickname == null) { if (other.nickname != null) return false; } else if (!nickname.equals(other.nickname)) return false; return true; } }