answer
stringlengths
17
10.2M
package com.venki; import java.io.*; import java.sql.*; import javax.servlet.ServletException; import javax.servlet.http.*; import org.json.*; @SuppressWarnings("serial") public class JqueryDatatablePluginDemo extends HttpServlet { private String GLOBAL_SEARCH_TERM; private String COLUMN_NAME; private String DIRECTION; private int INITIAL; private int RECORD_SIZE; private String ID_SEARCH_TERM,NAME_SEARCH_TERM,PLACE_SEARCH_TERM,CITY_SEARCH_TERM, STATE_SEARCH_TERM,PHONE_SEARCH_TERM; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String[] columnNames = { "id", "message", "status", "senderId", "messageId","mobileNumber" }; JSONObject jsonResult = new JSONObject(); int listDisplayAmount = 10; int start = 0; int column = 0; String dir = "asc"; String pageNo = request.getParameter("iDisplayStart"); String pageSize = request.getParameter("iDisplayLength"); String colIndex = request.getParameter("iSortCol_0"); String sortDirection = request.getParameter("sSortDir_0"); if (pageNo != null) { start = Integer.parseInt(pageNo); if (start < 0) { start = 0; } } if (pageSize != null) { listDisplayAmount = Integer.parseInt(pageSize); if (listDisplayAmount < 10 || listDisplayAmount > 50) { listDisplayAmount = 10; } } if (colIndex != null) { column = Integer.parseInt(colIndex); if (column < 0 || column > 5) column = 0; } if (sortDirection != null) { if (!sortDirection.equals("asc")) dir = "desc"; } String colName = columnNames[column]; int totalRecords= -1; try { totalRecords = getTotalRecordCount(); } catch (SQLException e1) { e1.printStackTrace(); } RECORD_SIZE = listDisplayAmount; GLOBAL_SEARCH_TERM = request.getParameter("sSearch"); ID_SEARCH_TERM=request.getParameter("sSearch_0"); NAME_SEARCH_TERM=request.getParameter("sSearch_1"); PLACE_SEARCH_TERM=request.getParameter("sSearch_2"); CITY_SEARCH_TERM=request.getParameter("sSearch_3"); STATE_SEARCH_TERM=request.getParameter("sSearch_4"); PHONE_SEARCH_TERM=request.getParameter("sSearch_5"); COLUMN_NAME = colName; DIRECTION = dir; INITIAL = start; try { jsonResult = getPersonDetails(totalRecords, request); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } response.setContentType("application/json"); response.setHeader("Cache-Control", "no-store"); PrintWriter out = response.getWriter(); out.print(jsonResult); } public JSONObject getPersonDetails(int totalRecords, HttpServletRequest request) throws SQLException, ClassNotFoundException { int totalAfterSearch = totalRecords; JSONObject result = new JSONObject(); JSONArray array = new JSONArray(); String searchSQL = ""; try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } String dbConnectionURL = "jdbc:mysql://localhost:3306/comm?user=root&password=root"; Connection con = DriverManager.getConnection(dbConnectionURL); String sql = "SELECT * FROM comm.sms_data " + "WHERE "; String globeSearch = "id like '%" + GLOBAL_SEARCH_TERM + "%'" + "or message like '%" + GLOBAL_SEARCH_TERM + "%'" + "or messageId like '%" + GLOBAL_SEARCH_TERM + "%'" + "or senderId like '%" + GLOBAL_SEARCH_TERM + "%'" + "or status like '%" + GLOBAL_SEARCH_TERM + "%'" + "or mobileNumber like '%" + GLOBAL_SEARCH_TERM + "%'"; String idSearch="id like " + ID_SEARCH_TERM + ""; String nameSearch="message like '%" + NAME_SEARCH_TERM + "%'"; String placeSearch=" messageId like '%" + PLACE_SEARCH_TERM + "%'"; String citySearch=" senderId like '%" + CITY_SEARCH_TERM + "%'"; String stateSearch=" status like '%" + STATE_SEARCH_TERM + "%'"; String phoneSearch=" mobileNumber like '%" + PHONE_SEARCH_TERM + "%'"; System.out.println(phoneSearch); if (GLOBAL_SEARCH_TERM != "") { searchSQL = globeSearch; } else if(ID_SEARCH_TERM !="") { searchSQL=idSearch; } else if(NAME_SEARCH_TERM !="") { searchSQL=nameSearch; } else if(PLACE_SEARCH_TERM!="") { searchSQL=placeSearch; } else if(CITY_SEARCH_TERM!="") { searchSQL=citySearch; } else if(STATE_SEARCH_TERM!="") { searchSQL=stateSearch; } else if(PHONE_SEARCH_TERM!=null) { searchSQL=phoneSearch; } sql += searchSQL; sql += " order by " + COLUMN_NAME + " " + DIRECTION; sql += " limit " + INITIAL + ", " + RECORD_SIZE; //for searching PreparedStatement stmt = con.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); while (rs.next()) { JSONArray ja = new JSONArray(); ja.put(rs.getString("id")); ja.put(rs.getString("message")); ja.put(rs.getString("status")); ja.put(rs.getString("senderId")); ja.put(rs.getString("messageId")); ja.put(rs.getString("mobileNumber")); array.put(ja); } System.out.println(array); stmt.close(); rs.close(); String query = "SELECT " + "COUNT(*) as count " + "FROM " + "comm.sms_data " + "WHERE "; //for pagination if (GLOBAL_SEARCH_TERM != ""||ID_SEARCH_TERM != "" || NAME_SEARCH_TERM != "" ||PLACE_SEARCH_TERM != ""||CITY_SEARCH_TERM != ""|| STATE_SEARCH_TERM != "" || PHONE_SEARCH_TERM != "" ) { query += searchSQL; PreparedStatement st = con.prepareStatement(query); ResultSet results = st.executeQuery(); if (results.next()) { totalAfterSearch = results.getInt("count"); } st.close(); results.close(); con.close(); } try { result.put("iTotalRecords", totalRecords); result.put("iTotalDisplayRecords", totalAfterSearch); result.put("aaData", array); } catch (Exception e) { } return result; } public int getTotalRecordCount() throws SQLException { int totalRecords = -1; String sql = "SELECT COUNT(*) as count FROM comm.sms_data"; String dbConnectionURL = "jdbc:mysql://localhost:3306/comm?user=root&password=root"; try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } Connection con = DriverManager.getConnection(dbConnectionURL); PreparedStatement statement = con.prepareStatement(sql); ResultSet resultSet = statement.executeQuery(); if (resultSet.next()) { totalRecords = resultSet.getInt("count"); } resultSet.close(); statement.close(); con.close(); return totalRecords; } //successs }
package bt.data.file; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.SeekableByteChannel; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import bt.BtException; import bt.data.StorageUnit; class FileSystemStorageUnit implements StorageUnit { private static final Logger LOGGER = LoggerFactory.getLogger(FileSystemStorageUnit.class); private Path parent, file; private SeekableByteChannel sbc; private long capacity; private volatile boolean closed; FileSystemStorageUnit(Path root, String path, long capacity) { this.file = root.resolve(path); this.parent = file.getParent(); this.capacity = capacity; this.closed = true; } // TODO: this is temporary fix for verification upon app start // should be re-done (probably need additional API to know if storage unit is "empty") private boolean init(boolean create) { if (closed) { if (!Files.exists(parent)) { try { Files.createDirectory(parent); } catch(IOException e) { if(create) { throw new BtException("Failed to create file storage -- can't create (some of the) directories"); } throw new BtException("Failed to create file storage -- unexpected I/O error", e); } } if (!Files.exists(file)) { if (create) { try { Files.createFile(file); } catch (IOException e) { throw new BtException("Failed to create file storage "can't create new file: " + file.toAbsolutePath()); } } else { return false; } } try { sbc = Files.newByteChannel(file, StandardOpenOption.READ, StandardOpenOption.WRITE); } catch (IOException e) { throw new BtException("Unexpected I/O error", e); } closed = false; } return true; } @Override public synchronized void readBlock(ByteBuffer buffer, long offset) { if (closed) { if (!init(false)) { return; } } if (offset < 0) { throw new BtException("Illegal arguments: offset (" + offset + ")"); } else if (offset > capacity - buffer.remaining()) { throw new BtException("Received a request to read past the end of file (offset: " + offset + ", requested block length: " + buffer.remaining() + ", file size: " + capacity); } try { sbc.position(offset); sbc.read(buffer); } catch (IOException e) { throw new BtException("Failed to read bytes (offset: " + offset + ", requested block length: " + buffer.remaining() + ", file size: " + capacity + ")", e); } } @Override public synchronized byte[] readBlock(long offset, int length) { if (closed) { if (!init(false)) { // TODO: should we return null here? or init this "stub" in constructor? return new byte[length]; } } if (offset < 0 || length < 0) { throw new BtException("Illegal arguments: offset (" + offset + "), length (" + length + ")"); } else if (offset > capacity - length) { throw new BtException("Received a request to read past the end of file (offset: " + offset + ", requested block length: " + length + ", file size: " + capacity); } try { raf.seek(offset); byte[] block = new byte[length]; raf.read(block); return block; } catch (IOException e) { throw new BtException("Failed to read bytes (offset: " + offset + ", requested block length: " + length + ", file size: " + capacity + ")", e); } } @Override public synchronized void writeBlock(ByteBuffer buffer, long offset) { if (closed) { init(true); } if (offset < 0) { throw new BtException("Negative offset: " + offset); } else if (offset > capacity - buffer.remaining()) { throw new BtException("Received a request to write past the end of file (offset: " + offset + ", block length: " + buffer.remaining() + ", file size: " + capacity); } try { raf.seek(offset); raf.getChannel().write(buffer); } catch (IOException e) { throw new BtException("Failed to write bytes (offset: " + offset + ", block length: " + buffer.remaining() + ", file size: " + capacity + ")", e); } } @Override public synchronized void writeBlock(byte[] block, long offset) { if (closed) { init(true); } if (offset < 0) { throw new BtException("Negative offset: " + offset); } else if (offset > capacity - block.length) { throw new BtException("Received a request to write past the end of file (offset: " + offset + ", block length: " + block.length + ", file size: " + capacity); } try { raf.seek(offset); raf.write(block); } catch (IOException e) { throw new BtException("Failed to write bytes (offset: " + offset + ", block length: " + block.length + ", file size: " + capacity + ")", e); } } @Override public long capacity() { return capacity; } @Override public long size() { return file.length(); } @Override public String toString() { return "(" + capacity + " B) " + file.getPath(); } @Override public void close() throws IOException { if (!closed) { try { raf.close(); } catch (IOException e) { LOGGER.warn("Failed to close file: " + file.getPath(), e); } finally { closed = true; } } } }
package main.swapship.desktop; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; import com.badlogic.gdx.tools.imagepacker.TexturePacker2; import main.swapship.SwapShipGame; import main.swapship.common.Constants; public class DesktopLauncher { public static void main (String[] arg) { packImages(); LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); config.title = "Swap Ship"; config.width = Constants.SCREEN_WIDTH; config.height = Constants.SCREEN_HEIGHT; config.y = 0; config.x = 480; new LwjglApplication(new SwapShipGame(), config); } private static void packImages() { TexturePacker2.process("../images/game", "../android/assets/game", "gameImages"); TexturePacker2.process("../images/ui", "../android/assets/ui", "uiskin"); } }
package com.diozero; import java.nio.ByteBuffer; import org.junit.Assert; import org.junit.Test; import org.pmw.tinylog.Logger; import com.diozero.util.BitManipulation; @SuppressWarnings("static-method") public class BitSetTest { private static final int PINS_PER_PORT = 8; @Test public void test() { System.out.format("0x%02x%n", Integer.valueOf(1<<7)); System.out.format("0x%08x%n", Integer.valueOf(1<<16)); System.out.format("0x%02x%n", Integer.valueOf(0x0f<<4)); System.out.format("0x%02x%n", Integer.valueOf((0x0f<<4) & 0xf0)); byte b = (byte) 0xff; byte b2 = (byte) (b >>> 4); System.out.format("b=0x%02x, b2=0x%02x%n", Byte.valueOf(b), Byte.valueOf(b2)); byte val = 0; val = BitManipulation.setBitValue(val, true, 1); byte expected_val = 2; Assert.assertEquals(expected_val, val); val = BitManipulation.setBitValue(val, true, 0); expected_val += 1; Assert.assertEquals(expected_val, val); val = BitManipulation.setBitValue(val, true, 4); expected_val += 16; Assert.assertEquals(expected_val, val); val = BitManipulation.setBitValue(val, false, 5); Assert.assertEquals(expected_val, val); val = BitManipulation.setBitValue(val, false, 1); expected_val -= 2; Assert.assertEquals(expected_val, val); byte mask = BitManipulation.getBitMask(4, 5); Assert.assertEquals(16+32, mask); } @Test public void testMcp23017() { int pinNumber = 7; byte bit = (byte)(pinNumber % PINS_PER_PORT); Assert.assertEquals(7, bit); int port = pinNumber / PINS_PER_PORT; Assert.assertEquals(0, port); pinNumber = 0; bit = (byte)(pinNumber % PINS_PER_PORT); Assert.assertEquals(0, bit); port = pinNumber / PINS_PER_PORT; Assert.assertEquals(0, port); pinNumber = 8; bit = (byte)(pinNumber % PINS_PER_PORT); Assert.assertEquals(0, bit); port = pinNumber / PINS_PER_PORT; Assert.assertEquals(1, port); pinNumber = 15; bit = (byte)(pinNumber % PINS_PER_PORT); Assert.assertEquals(7, bit); port = pinNumber / PINS_PER_PORT; Assert.assertEquals(1, port); } @Test public void testMcpAdc() { // MCP3304 ADC // x0SRRRRR RRRRRRRx // 00011111 11111110 0 1111 1111 1111 +4095 // 00011111 11111100 0 1111 1111 1110 +4094 // 00000000 00000100 0 0000 0000 0010 +2 // 00000000 00000010 0 0000 0000 0001 +1 // 00000000 00000000 0 0000 0000 0000 0 // 00111111 11111110 1 1111 1111 1111 -1 // 00111111 11111100 1 1111 1111 1110 -2 // 00100000 00000010 1 0000 0000 0001 -4095 // 00100000 00000000 1 0000 0000 0000 -4096 byte[][] values = { { (byte) 0b00011111, (byte) 0b11111110 }, { (byte) 0b00011111, (byte) 0b11111100 }, { (byte) 0b00000000, (byte) 0b00000100 }, { (byte) 0b00000000, (byte) 0b00000010 }, { (byte) 0b00000000, (byte) 0b00000000 }, { (byte) 0b00111111, (byte) 0b11111110 }, { (byte) 0b00111111, (byte) 0b11111100 }, { (byte) 0b00100000, (byte) 0b00000010 }, { (byte) 0b00100000, (byte) 0b00000000 }, }; int[] expected = { 4095, 4094, 2, 1, 0, -1, -2, -4095, -4096 }; ByteBuffer buffer = ByteBuffer.allocateDirect(2); for (int i=0; i<values.length; i++) { buffer.put(values[i][0]); buffer.put(values[i][1]); buffer.flip(); int v = extractValue(buffer, McpAdc.Type.MCP3304); Assert.assertEquals(expected[i], v); buffer.clear(); } int resolution = 12; int m = (1 << resolution-8) - 1; Assert.assertEquals(0b00001111, m); resolution = 10; m = (1 << resolution-8) - 1; Assert.assertEquals(0b00000011, m); // Rx x0RRRRRR RRRRxxxx for the 300x (10 bit) // Rx x0RRRRRR RRRRRRxx for the 320x (12 bit) // Rx x0SRRRRR RRRRRRRx for the 330x (13 bit signed) buffer.put((byte)0x01); buffer.put((byte)0xfe); buffer.flip(); int v = (buffer.getShort() << 2) >> 3; Assert.assertEquals(255, v); buffer.clear(); buffer.put((byte) 0b00011111); buffer.put((byte) 0xfe); buffer.flip(); v = ((short)(buffer.getShort() << 2)) >> 3; Assert.assertEquals(4095, v); buffer.clear(); buffer.put((byte)0b00111111); buffer.put((byte)0xfe); buffer.flip(); v = ((short)(buffer.getShort() << 2)) >> 3; Assert.assertEquals(-1, v); buffer.clear(); buffer.put((byte)0b00100000); buffer.put((byte)0x00); buffer.flip(); v = ((short)(buffer.getShort() << 2)) >> 3; Assert.assertEquals(-4096, v); Assert.assertTrue("MCP3301".substring(0, 5).equals("MCP33")); Assert.assertTrue("MCP3302".substring(0, 5).equals("MCP33")); Assert.assertTrue("MCP3304".substring(0, 5).equals("MCP33")); McpAdc.Type type = McpAdc.Type.valueOf("MCP3008"); Assert.assertEquals(McpAdc.Type.MCP3008, type); // Unsigned type = McpAdc.Type.MCP3208; buffer.rewind(); //buffer.put((byte)0b00111111); //buffer.put((byte)0xfe); buffer.put((byte)0xff); buffer.put((byte)0xff); buffer.flip(); // Doesn't work as >>> is promoted to integer short s = (short)((short)(buffer.getShort() << 2) >>> (short)(14+2-type.getResolution())); System.out.format("Resolution=%d, s=%d, expected %d%n", Integer.valueOf(14+2-type.getResolution()), Integer.valueOf(s), Integer.valueOf((int)Math.pow(2, type.getResolution())-1)); buffer.rewind(); v = (buffer.getShort() & 0x3fff) >> (14 - type.getResolution()); System.out.format("Resolution=%d, v=%d%n", Integer.valueOf(14+2-type.getResolution()), Integer.valueOf(v)); // Signed type = McpAdc.Type.MCP3304; buffer.rewind(); v = ((short)(buffer.getShort() << 2)) >> (14+2-type.getResolution()); System.out.format("Resolution=%d, v=%d%n", Integer.valueOf(14+2-type.getResolution()), Integer.valueOf(v)); // Unsigned type = McpAdc.Type.MCP3208; buffer.rewind(); if (type.isSigned()) { v = ((short)(buffer.getShort() << 2)) >> (14+2-type.getResolution()); } else { v = (buffer.getShort() & 0x3fff) >> (14 - type.getResolution()); } System.out.format("Resolution=%d, v=%d%n", Integer.valueOf(14+2-type.getResolution()), Integer.valueOf(v)); // Signed type = McpAdc.Type.MCP3304; buffer.rewind(); if (type.isSigned()) { v = ((short)(buffer.getShort() << 2)) >> (14+2-type.getResolution()); } else { v = (buffer.getShort() & 0x3fff) >> (14 - type.getResolution()); } System.out.format("Right shift=%d, v=%d%n", Integer.valueOf(14+2-type.getResolution()), Integer.valueOf(v)); } private static int extractValue(ByteBuffer in, McpAdc.Type type) { /* * Rx x0RRRRRR RRRRxxxx for the 30xx (10-bit unsigned) * Rx x0RRRRRR RRRRRRxx for the 32xx (12-bit unsigned) * Rx x0SRRRRR RRRRRRRx for the 33xx (13-bit signed) */ if (type.isSigned()) { short s = in.getShort(); Logger.debug("Signed reading, s={}", Short.valueOf(s)); // Relies on the >> operator to preserve the sign bit return ((short) (s << 2)) >> (14+2-type.getResolution()); } // Note can't use >>> to propagate MSB 0s as it doesn't work with short, only integer return (in.getShort() & 0x3fff) >> (14 - type.getResolution()); } }
package org.flymine.web.widget; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.intermine.api.profile.InterMineBag; import org.intermine.bio.util.BioUtil; import org.intermine.model.bio.Gene; import org.intermine.model.bio.MRNA; import org.intermine.model.bio.MiRNATarget; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.query.BagConstraint; import org.intermine.objectstore.query.ConstraintOp; import org.intermine.objectstore.query.ConstraintSet; import org.intermine.objectstore.query.ContainsConstraint; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.QueryClass; import org.intermine.objectstore.query.QueryCollectionReference; import org.intermine.objectstore.query.QueryField; import org.intermine.objectstore.query.QueryFunction; import org.intermine.objectstore.query.QueryObjectReference; import org.intermine.web.logic.widget.EnrichmentWidgetLdr; /** * @author Julie Sullivan */ public class MirandaLdr extends EnrichmentWidgetLdr { // private static final Logger LOG = Logger.getLogger(MirandaLdr.class); private Collection<String> organisms = new ArrayList<String>(); private Collection<String> organismsLower = new ArrayList<String>(); private InterMineBag bag; /** * Create a new Loader. * @param bag list of objects for this widget * @param os object store * @param extraAttribute an extra attribute for this widget (if needed) */ public MirandaLdr(InterMineBag bag, ObjectStore os, String extraAttribute) { this.bag = bag; organisms = BioUtil.getOrganisms(os, bag, false); for (String s : organisms) { organismsLower.add(s.toLowerCase()); } } /** * {@inheritDoc} */ public Query getQuery(String action, List<String> keys) { QueryClass qcMiRNATarget = null; qcMiRNATarget = new QueryClass(MiRNATarget.class); QueryClass qcGene = new QueryClass(Gene.class); QueryClass qcMiR = new QueryClass(Gene.class); QueryClass qcTranscript = new QueryClass(MRNA.class); QueryField qfGeneIdentifier = new QueryField(qcGene, "symbol"); QueryField qfGeneId = new QueryField(qcGene, "id"); QueryField qfMiRIdentifier = new QueryField(qcMiR, "symbol"); ConstraintSet cs = new ConstraintSet(ConstraintOp.AND); if (keys != null) { cs.addConstraint(new BagConstraint(qfMiRIdentifier, ConstraintOp.IN, keys)); } if (!action.startsWith("population")) { cs.addConstraint(new BagConstraint(qfGeneId, ConstraintOp.IN, bag.getOsb())); } QueryCollectionReference r1 = new QueryCollectionReference(qcMiR, "miRNAtargets"); cs.addConstraint(new ContainsConstraint(r1, ConstraintOp.CONTAINS, qcMiRNATarget)); QueryObjectReference qcr1 = new QueryObjectReference(qcMiRNATarget, "target"); cs.addConstraint(new ContainsConstraint(qcr1, ConstraintOp.CONTAINS, qcTranscript)); QueryObjectReference qcr2 = new QueryObjectReference(qcTranscript, "gene"); cs.addConstraint(new ContainsConstraint(qcr2, ConstraintOp.CONTAINS, qcGene)); Query q = new Query(); q.addFrom(qcMiRNATarget); q.addFrom(qcGene); q.addFrom(qcMiR); q.addFrom(qcTranscript); q.setConstraint(cs); // which columns to return when the user clicks on 'export' if ("export".equals(action)) { q.addToSelect(qfMiRIdentifier); q.addToSelect(qfGeneIdentifier); q.addToOrderBy(qfMiRIdentifier); // analysed query: return the gene only } else if ("analysed".equals(action)) { q.addToSelect(qfGeneId); // total query: only return the count of unique genes } else if (action.endsWith("Total")) { q.addToSelect(qfGeneId); Query subQ = q; q = new Query(); q.addFrom(subQ); q.addToSelect(new QueryFunction()); // enrichment queries } else { // subquery Query subQ = q; // used for count subQ.addToSelect(qfGeneId); // feature name subQ.addToSelect(qfMiRIdentifier); // needed so we can select this field in the parent query QueryField qfUniqueTargets = new QueryField(subQ, qfMiRIdentifier); q = new Query(); q.setDistinct(false); q.addFrom(subQ); // add the unique-ified targets to select q.addToSelect(qfUniqueTargets); // gene count q.addToSelect(new QueryFunction()); // if this is the sample query, it expects a third column if ("sample".equals(action)) { q.addToSelect(qfUniqueTargets); } // group by target q.addToGroupBy(qfUniqueTargets); } return q; } }
package cpw.mods.fml.client; import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.opengl.GL12.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.lang.Thread.UncaughtExceptionHandler; import java.nio.IntBuffer; import java.util.Iterator; import java.util.Properties; import java.util.concurrent.Semaphore; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.client.resources.FileResourcePack; import net.minecraft.client.resources.FolderResourcePack; import net.minecraft.client.resources.IResourcePack; import net.minecraft.crash.CrashReport; import net.minecraft.launchwrapper.Launch; import net.minecraft.util.ResourceLocation; import org.apache.commons.io.IOUtils; import org.apache.logging.log4j.Level; import org.lwjgl.BufferUtils; import org.lwjgl.LWJGLException; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.Drawable; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.SharedDrawable; import org.lwjgl.util.glu.GLU; import cpw.mods.fml.common.EnhancedRuntimeException; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.ICrashCallable; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.ProgressManager; import cpw.mods.fml.common.ProgressManager.ProgressBar; import cpw.mods.fml.common.asm.FMLSanityChecker; /** * @deprecated not a stable API, will break, don't use this yet */ @Deprecated public class SplashProgress { private static Drawable d; private static volatile boolean pause = false; private static volatile boolean done = false; private static Thread thread; private static volatile Throwable threadError; private static int angle = 0; private static final Lock lock = new ReentrantLock(true); private static SplashFontRenderer fontRenderer; private static final IResourcePack mcPack = Minecraft.getMinecraft().mcDefaultResourcePack; private static final IResourcePack fmlPack = createResourcePack(FMLSanityChecker.fmlLocation); private static IResourcePack miscPack; private static Texture fontTexture; private static Texture logoTexture; private static Texture forgeTexture; private static Properties config; private static boolean enabled; private static boolean rotate; private static int logoOffset; private static int backgroundColor; private static int fontColor; private static int barBorderColor; private static int barColor; private static int barBackgroundColor; static final Semaphore mutex = new Semaphore(1); private static String getString(String name, String def) { String value = config.getProperty(name, def); config.setProperty(name, value); return value; } private static boolean getBool(String name, boolean def) { return Boolean.parseBoolean(getString(name, Boolean.toString(def))); } private static int getInt(String name, int def) { return Integer.decode(getString(name, Integer.toString(def))); } private static int getHex(String name, int def) { return Integer.decode(getString(name, "0x" + Integer.toString(def, 16).toUpperCase())); } public static void start() { File configFile = new File(Minecraft.getMinecraft().mcDataDir, "config/splash.properties"); FileReader r = null; config = new Properties(); try { r = new FileReader(configFile); config.load(r); } catch(IOException e) { FMLLog.info("Could not load splash.properties, will create a default one"); } finally { IOUtils.closeQuietly(r); } // Enable if we have the flag, and there's either no optifine, or optifine has added a key to the blackboard ("optifine.ForgeSplashCompatible") // Optifine authors - add this key to the blackboard if you feel your modifications are now compatible with this code. enabled = getBool("enabled", true) && ( (!FMLClientHandler.instance().hasOptifine()) || Launch.blackboard.containsKey("optifine.ForgeSplashCompatible")); rotate = getBool("rotate", false); logoOffset = getInt("logoOffset", 0); backgroundColor = getHex("background", 0xFFFFFF); fontColor = getHex("font", 0x000000); barBorderColor = getHex("barBorder", 0xC0C0C0); barColor = getHex("bar", 0xCB3D35); barBackgroundColor = getHex("barBackground", 0xFFFFFF); final ResourceLocation fontLoc = new ResourceLocation(getString("fontTexture", "textures/font/ascii.png")); final ResourceLocation logoLoc = new ResourceLocation(getString("logoTexture", "textures/gui/title/mojang.png")); final ResourceLocation forgeLoc = new ResourceLocation(getString("forgeTexture", "fml:textures/gui/forge.gif")); File miscPackFile = new File(Minecraft.getMinecraft().mcDataDir, getString("resourcePackPath", "resources")); FileWriter w = null; try { w = new FileWriter(configFile); config.store(w, "Splash screen properties"); } catch(IOException e) { FMLLog.log(Level.ERROR, e, "Could not save the splash.properties file"); } finally { IOUtils.closeQuietly(w); } miscPack = createResourcePack(miscPackFile); if(!enabled) return; // getting debug info out of the way, while we still can FMLCommonHandler.instance().registerCrashCallable(new ICrashCallable() { public String call() throws Exception { return "' Vendor: '" + glGetString(GL_VENDOR) + "' Version: '" + glGetString(GL_VERSION) + "' Renderer: '" + glGetString(GL_RENDERER) + "'"; } public String getLabel() { return "GL info"; } }); CrashReport report = CrashReport.makeCrashReport(new Throwable() { @Override public String getMessage(){ return "This is just a prompt for computer specs to be printed. THIS IS NOT A ERROR"; } @Override public void printStackTrace(final PrintWriter s){ s.println(getMessage()); } @Override public void printStackTrace(final PrintStream s) { s.println(getMessage()); } }, "Loading screen debug info"); System.out.println(report.getCompleteReport()); try { d = new SharedDrawable(Display.getDrawable()); Display.getDrawable().releaseContext(); d.makeCurrent(); } catch (LWJGLException e) { e.printStackTrace(); throw new RuntimeException(e); } Thread mainThread = Thread.currentThread(); thread = new Thread(new Runnable() { private final int barWidth = 400; private final int barHeight = 20; private final int textHeight2 = 20; private final int barOffset = 55; public void run() { setGL(); fontTexture = new Texture(fontLoc); logoTexture = new Texture(logoLoc); forgeTexture = new Texture(forgeLoc); glEnable(GL_TEXTURE_2D); fontRenderer = new SplashFontRenderer(); glDisable(GL_TEXTURE_2D); while(!done) { ProgressBar first = null, penult = null, last = null; Iterator<ProgressBar> i = ProgressManager.barIterator(); while(i.hasNext()) { if(first == null) first = i.next(); else { penult = last; last = i.next(); } } glClear(GL_COLOR_BUFFER_BIT); // matrix setup int w = Display.getWidth(); int h = Display.getHeight(); glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(320 - w/2, 320 + w/2, 240 + h/2, 240 - h/2, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // mojang logo setColor(backgroundColor); glEnable(GL_TEXTURE_2D); logoTexture.bind(); glBegin(GL_QUADS); logoTexture.texCoord(0, 0, 0); glVertex2f(320 - 256, 240 - 256); logoTexture.texCoord(0, 0, 1); glVertex2f(320 - 256, 240 + 256); logoTexture.texCoord(0, 1, 1); glVertex2f(320 + 256, 240 + 256); logoTexture.texCoord(0, 1, 0); glVertex2f(320 + 256, 240 - 256); glEnd(); glDisable(GL_TEXTURE_2D); // bars if(first != null) { glPushMatrix(); glTranslatef(320 - (float)barWidth / 2, 310, 0); drawBar(first); if(penult != null) { glTranslatef(0, barOffset, 0); drawBar(penult); } if(last != null) { glTranslatef(0, barOffset, 0); drawBar(last); } glPopMatrix(); } angle += 1; // forge logo setColor(backgroundColor); float fw = (float)forgeTexture.getWidth() / 2 / 2; float fh = (float)forgeTexture.getHeight() / 2 / 2; if(rotate) { float sh = Math.max(fw, fh); glTranslatef(320 + w/2 - sh - logoOffset, 240 + h/2 - sh - logoOffset, 0); glRotatef(angle, 0, 0, 1); } else { glTranslatef(320 + w/2 - fw - logoOffset, 240 + h/2 - fh - logoOffset, 0); } int f = (angle / 10) % forgeTexture.getFrames(); glEnable(GL_TEXTURE_2D); forgeTexture.bind(); glBegin(GL_QUADS); forgeTexture.texCoord(f, 0, 0); glVertex2f(-fw, -fh); forgeTexture.texCoord(f, 0, 1); glVertex2f(-fw, fh); forgeTexture.texCoord(f, 1, 1); glVertex2f(fw, fh); forgeTexture.texCoord(f, 1, 0); glVertex2f(fw, -fh); glEnd(); glDisable(GL_TEXTURE_2D); // We use mutex to indicate safely to the main thread that we're taking the display global lock // So the main thread can skip processing messages while we're updating. // There are system setups where this call can pause for a while, because the GL implementation // is trying to impose a framerate or other thing is occurring. Without the mutex, the main // thread would delay waiting for the same global display lock mutex.acquireUninterruptibly(); Display.update(); // As soon as we're done, we release the mutex. The other thread can now ping the processmessages // call as often as it wants until we get get back here again mutex.release(); if(pause) { clearGL(); setGL(); } Display.sync(100); } clearGL(); } private void setColor(int color) { glColor3ub((byte)((color >> 16) & 0xFF), (byte)((color >> 8) & 0xFF), (byte)(color & 0xFF)); } private void drawBox(int w, int h) { glBegin(GL_QUADS); glVertex2f(0, 0); glVertex2f(0, h); glVertex2f(w, h); glVertex2f(w, 0); glEnd(); } private void drawBar(ProgressBar b) { glPushMatrix(); // title - message setColor(fontColor); glScalef(2, 2, 1); glEnable(GL_TEXTURE_2D); fontRenderer.drawString(b.getTitle() + " - " + b.getMessage(), 0, 0, 0x000000); glDisable(GL_TEXTURE_2D); glPopMatrix(); // border glPushMatrix(); glTranslatef(0, textHeight2, 0); setColor(barBorderColor); drawBox(barWidth, barHeight); // interior setColor(barBackgroundColor); glTranslatef(1, 1, 0); drawBox(barWidth - 2, barHeight - 2); // slidy part setColor(barColor); drawBox((barWidth - 2) * b.getStep() / b.getSteps(), barHeight - 2); // progress text String progress = "" + b.getStep() + "/" + b.getSteps(); glTranslatef(((float)barWidth - 2) / 2 - fontRenderer.getStringWidth(progress), 2, 0); setColor(fontColor); glScalef(2, 2, 1); glEnable(GL_TEXTURE_2D); fontRenderer.drawString(progress, 0, 0, 0x000000); glPopMatrix(); } private void setGL() { lock.lock(); try { Display.getDrawable().makeCurrent(); } catch (LWJGLException e) { e.printStackTrace(); throw new RuntimeException(e); } glClearColor((float)((backgroundColor >> 16) & 0xFF) / 0xFF, (float)((backgroundColor >> 8) & 0xFF) / 0xFF, (float)(backgroundColor & 0xFF) / 0xFF, 1); glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } private void clearGL() { Minecraft mc = Minecraft.getMinecraft(); mc.displayWidth = Display.getWidth(); mc.displayHeight = Display.getHeight(); mc.resize(mc.displayWidth, mc.displayHeight); glClearColor(1, 1, 1, 1); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GREATER, .1f); try { Display.getDrawable().releaseContext(); } catch (LWJGLException e) { e.printStackTrace(); throw new RuntimeException(e); } finally { lock.unlock(); } } }); thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { FMLLog.log(Level.ERROR, e, "Splash thread Exception"); threadError = e; } }); thread.start(); checkThreadState(); } private static void checkThreadState() { if(thread.getState() == Thread.State.TERMINATED || threadError != null) { throw new IllegalStateException("Splash thread", threadError); } } /** * Call before you need to explicitly modify GL context state during loading. * Resource loading doesn't usually require this call. * Call {@link #resume()} when you're done. * @deprecated not a stable API, will break, don't use this yet */ @Deprecated public static void pause() { if(!enabled) return; checkThreadState(); pause = true; lock.lock(); try { d.releaseContext(); Display.getDrawable().makeCurrent(); } catch (LWJGLException e) { e.printStackTrace(); throw new RuntimeException(e); } } /** * @deprecated not a stable API, will break, don't use this yet */ @Deprecated public static void resume() { if(!enabled) return; checkThreadState(); pause = false; try { Display.getDrawable().releaseContext(); d.makeCurrent(); } catch (LWJGLException e) { e.printStackTrace(); throw new RuntimeException(e); } lock.unlock(); } public static void finish() { if(!enabled) return; try { checkThreadState(); done = true; thread.join(); d.releaseContext(); Display.getDrawable().makeCurrent(); fontTexture.delete(); logoTexture.delete(); forgeTexture.delete(); } catch (Exception e) { e.printStackTrace(); if (disableSplash()) { throw new EnhancedRuntimeException(e) { @Override protected void printStackTrace(WrappedPrintStream stream) { stream.println("SplashProgress has detected a error loading Minecraft."); stream.println("This can sometimes be caused by bad video drivers."); stream.println("We have automatically disabeled the new Splash Screen in config/splash.properties."); stream.println("Try reloading minecraft before reporting any errors."); } }; } else { throw new EnhancedRuntimeException(e) { @Override protected void printStackTrace(WrappedPrintStream stream) { stream.println("SplashProgress has detected a error loading Minecraft."); stream.println("This can sometimes be caused by bad video drivers."); stream.println("Please try disabeling the new Splash Screen in config/splash.properties."); stream.println("After doing so, try reloading minecraft before reporting any errors."); } }; } } } private static boolean disableSplash() { File configFile = new File(Minecraft.getMinecraft().mcDataDir, "config/splash.properties"); FileReader r = null; enabled = false; config.setProperty("enabled", "false"); FileWriter w = null; try { w = new FileWriter(configFile); config.store(w, "Splash screen properties"); } catch(IOException e) { FMLLog.log(Level.ERROR, e, "Could not save the splash.properties file"); return false; } finally { IOUtils.closeQuietly(w); } return true; } private static IResourcePack createResourcePack(File file) { if(file.isDirectory()) { return new FolderResourcePack(file); } else { return new FileResourcePack(file); } } private static final IntBuffer buf = BufferUtils.createIntBuffer(4 * 1024 * 1024); private static class Texture { private final ResourceLocation location; private final int name; private final int width; private final int height; private final int frames; private final int size; public Texture(ResourceLocation location) { InputStream s = null; try { this.location = location; s = open(location); ImageInputStream stream = ImageIO.createImageInputStream(s); Iterator<ImageReader> readers = ImageIO.getImageReaders(stream); if(!readers.hasNext()) throw new IOException("No suitable reader found for image" + location); ImageReader reader = readers.next(); reader.setInput(stream); frames = reader.getNumImages(true); BufferedImage[] images = new BufferedImage[frames]; for(int i = 0; i < frames; i++) { images[i] = reader.read(i); } reader.dispose(); int size = 1; width = images[0].getWidth(); height = images[0].getHeight(); while((size / width) * (size / height) < frames) size *= 2; this.size = size; glEnable(GL_TEXTURE_2D); synchronized(SplashProgress.class) { name = glGenTextures(); glBindTexture(GL_TEXTURE_2D, name); } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, size, size, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, (IntBuffer)null); checkGLError("Texture creation"); for(int i = 0; i * (size / width) < frames; i++) { for(int j = 0; i * (size / width) + j < frames && j < size / width; j++) { buf.clear(); BufferedImage image = images[i * (size / width) + j]; for(int k = 0; k < height; k++) { for(int l = 0; l < width; l++) { buf.put(image.getRGB(l, k)); } } buf.position(0).limit(width * height); glTexSubImage2D(GL_TEXTURE_2D, 0, j * width, i * height, width, height, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, buf); checkGLError("Texture uploading"); } } glBindTexture(GL_TEXTURE_2D, 0); glDisable(GL_TEXTURE_2D); } catch(IOException e) { e.printStackTrace(); throw new RuntimeException(e); } finally { IOUtils.closeQuietly(s); } } public ResourceLocation getLocation() { return location; } public int getName() { return name; } public int getWidth() { return width; } public int getHeight() { return height; } public int getFrames() { return frames; } public int getSize() { return size; } public void bind() { glBindTexture(GL_TEXTURE_2D, name); } public void delete() { glDeleteTextures(name); } public float getU(int frame, float u) { return width * (frame % (size / width) + u) / size; } public float getV(int frame, float v) { return height * (frame / (size / width) + v) / size; } public void texCoord(int frame, float u, float v) { glTexCoord2f(getU(frame, u), getV(frame, v)); } } private static class SplashFontRenderer extends FontRenderer { public SplashFontRenderer() { super(Minecraft.getMinecraft().gameSettings, fontTexture.getLocation(), null, false); super.onResourceManagerReload(null); } @Override protected void bindTexture(ResourceLocation location) { if(location != locationFontTexture) throw new IllegalArgumentException(); fontTexture.bind(); } @Override protected InputStream getResourceInputStream(ResourceLocation location) throws IOException { return Minecraft.getMinecraft().mcDefaultResourcePack.getInputStream(location); } } public static void drawVanillaScreen() throws LWJGLException { if(!enabled) { Minecraft.getMinecraft().loadScreen(); } } public static void clearVanillaResources(TextureManager renderEngine, ResourceLocation mojangLogo) { if(!enabled) { renderEngine.deleteTexture(mojangLogo); } } public static void checkGLError(String where) { int err = GL11.glGetError(); if (err != 0) { throw new IllegalStateException(where + ": " + GLU.gluErrorString(err)); } } private static InputStream open(ResourceLocation loc) throws IOException { if(miscPack.resourceExists(loc)) { return miscPack.getInputStream(loc); } else if(fmlPack.resourceExists(loc)) { return fmlPack.getInputStream(loc); } return mcPack.getInputStream(loc); } }
package com.valkryst.generator; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; import java.util.function.IntUnaryOperator; public class GrammarNameGeneratorTest { private static final List<String> RULES = new ArrayList<>(); static { // Balin, Bifur, Bofur, Bombur, Borin // Dain, Dis, Dori, Dwalin, Farin, Fili // Floi, Frar, Frerin, Fror, Fundin, Gaiml // Gimli, Gloin, Groin, Gror, Ibun, Khim // Kili, Loni, Mim, Nain, Nali, Nar, Narvi // Nori, Oin, Ori, Telchar, Thorin, Thrain // Thror, RULES.add("S B D F G I K L M N O T"); RULES.add("A a aL aI aR"); RULES.add("B b bA bI bO"); RULES.add("C c"); RULES.add("D d dA dI dO dW dU"); RULES.add("E e eR eL"); RULES.add("F f fA fI fL fR fU fO"); RULES.add("G g gA gI gL gR"); RULES.add("H h hI hA"); RULES.add("I i"); RULES.add("K k kH kI"); RULES.add("L l lO"); RULES.add("M m mI"); RULES.add("N n nA nO"); RULES.add("O o oI oR"); RULES.add("P p"); RULES.add("Q q"); RULES.add("R r rI rO rV"); RULES.add("S s"); RULES.add("T t tE tH"); RULES.add("U u uR uN"); RULES.add("V v"); RULES.add("W w wA"); RULES.add("X x"); RULES.add("Y y"); RULES.add("Z z"); } @Test public void generateName() { // Setup & Test the Generator: final GrammarNameGenerator grammarNameGenerator = new GrammarNameGenerator(RULES); for(int i = 0 ; i < 100 ; i++) { grammarNameGenerator.generateName(i % 6); } } @Test public void longGeneration() { // Setup & Test the Generator: final GrammarNameGenerator grammarNameGenerator = new GrammarNameGenerator(RULES); for (int i = 0 ; i < 100 ; i++) { System.out.println(grammarNameGenerator.generateName(i % 6)); } for (int i = 0 ; i < 1_000_000 ; i++) { grammarNameGenerator.generateName(i % 6); } } }
package org.zkoss.ganttz; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.util.Map; import java.util.UUID; import org.apache.commons.lang.Validate; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.zkoss.ganttz.adapters.IDisabilityConfiguration; import org.zkoss.ganttz.data.GanttDate; import org.zkoss.ganttz.data.ITaskFundamentalProperties.IModifications; import org.zkoss.ganttz.data.ITaskFundamentalProperties.IUpdatablePosition; import org.zkoss.ganttz.data.Milestone; import org.zkoss.ganttz.data.Task; import org.zkoss.ganttz.data.Task.IReloadResourcesTextRequested; import org.zkoss.ganttz.data.TaskContainer; import org.zkoss.ganttz.data.constraint.Constraint; import org.zkoss.ganttz.data.constraint.Constraint.IConstraintViolationListener; import org.zkoss.ganttz.util.WeakReferencedListeners.Mode; import org.zkoss.lang.Objects; import org.zkoss.zk.au.AuRequest; import org.zkoss.zk.au.AuService; import org.zkoss.zk.au.out.AuInvoke; import org.zkoss.zk.mesg.MZk; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.UiException; import org.zkoss.zk.ui.event.Event; import org.zkoss.zk.ui.event.Events; import org.zkoss.zk.ui.ext.AfterCompose; import org.zkoss.zk.ui.sys.ContentRenderer; import org.zkoss.zul.Div; public class TaskComponent extends Div implements AfterCompose { private static final Log LOG = LogFactory.getLog(TaskComponent.class); private static final int HEIGHT_PER_TASK = 10; private static final int CONSOLIDATED_MARK_HALF_WIDTH = 3; private static final int HALF_DEADLINE_MARK = 3; protected final IDisabilityConfiguration disabilityConfiguration; private PropertyChangeListener criticalPathPropertyListener; private PropertyChangeListener showingAdvancePropertyListener; private PropertyChangeListener showingReportedHoursPropertyListener; public static TaskComponent asTaskComponent(Task task, IDisabilityConfiguration disabilityConfiguration, boolean isTopLevel) { final TaskComponent result; if (task.isContainer()) { result = TaskContainerComponent.asTask((TaskContainer) task, disabilityConfiguration); } else if (task instanceof Milestone) { result = new MilestoneComponent(task, disabilityConfiguration); } else { result = new TaskComponent(task, disabilityConfiguration); } result.isTopLevel = isTopLevel; return TaskRow.wrapInRow(result); } public static TaskComponent asTaskComponent(Task task, IDisabilityConfiguration disabilityConfiguration) { return asTaskComponent(task, disabilityConfiguration, true); } private IReloadResourcesTextRequested reloadResourcesTextRequested; public TaskComponent(Task task, IDisabilityConfiguration disabilityConfiguration) { setHeight(HEIGHT_PER_TASK + "px"); setContext("idContextMenuTaskAssignment"); this.task = task; setClass(calculateCSSClass()); setId(UUID.randomUUID().toString()); this.disabilityConfiguration = disabilityConfiguration; taskViolationListener = Constraint .onlyOnZKExecution(new IConstraintViolationListener<GanttDate>() { @Override public void constraintViolated(Constraint<GanttDate> constraint, GanttDate value) { // TODO mark graphically task as violated } @Override public void constraintSatisfied(Constraint<GanttDate> constraint, GanttDate value) { // TODO mark graphically dependency as not violated } }); this.task.addConstraintViolationListener(taskViolationListener, Mode.RECEIVE_PENDING); reloadResourcesTextRequested = new IReloadResourcesTextRequested() { @Override public void reloadResourcesTextRequested() { if (canShowResourcesText()) { smartUpdate("resourcesText", getResourcesText()); } String cssClass = calculateCSSClass(); response("setClass", new AuInvoke(TaskComponent.this, "setClass", cssClass)); // FIXME: Refactorize to another listener updateDeadline(); invalidate(); } }; this.task.addReloadListener(reloadResourcesTextRequested); setAuService(new AuService(){ public boolean service(AuRequest request, boolean everError){ String command = request.getCommand(); final TaskComponent ta; if (command.equals("onUpdatePosition")){ ta = retrieveTaskComponent(request); ta.doUpdatePosition( toInteger(retrieveData(request, "left")), toInteger(retrieveData(request, "top"))); Events.postEvent(new Event(getId(), ta, request.getData())); return true; } if (command.equals("onUpdateWidth")){ ta = retrieveTaskComponent(request); ta.doUpdateSize(toInteger(retrieveData(request, "width"))); Events.postEvent(new Event(getId(), ta, request.getData())); return true; } if (command.equals("onAddDependency")){ ta = retrieveTaskComponent(request); ta.doAddDependency((String) retrieveData(request, "dependencyId")); Events.postEvent(new Event(getId(), ta, request.getData())); return true; } return false; } private int toInteger(Object valueFromRequestData) { return ((Number) valueFromRequestData).intValue(); } private TaskComponent retrieveTaskComponent(AuRequest request){ final TaskComponent ta = (TaskComponent) request.getComponent(); if (ta == null) { throw new UiException(MZk.ILLEGAL_REQUEST_COMPONENT_REQUIRED, this); } return ta; } private Object retrieveData(AuRequest request, String key){ Object value = request.getData().get(key); if ( value == null) throw new UiException(MZk.ILLEGAL_REQUEST_WRONG_DATA, new Object[] { key, this }); return value; } }); } /* Generate CSS class attribute depending on task properties */ protected String calculateCSSClass() { String cssClass = isSubcontracted() ? "box subcontracted-task" : "box standard-task"; cssClass += isResizingTasksEnabled() ? " yui-resize" : ""; if (isContainer()) { cssClass += task.isExpanded() ? " expanded" : " closed "; cssClass += task.isInCriticalPath() && !task.isExpanded() ? " critical" : ""; } else { cssClass += task.isInCriticalPath() ? " critical" : ""; } cssClass += " " + task.getAssignedStatus(); if (task.isLimiting()) { cssClass += task.isLimitingAndHasDayAssignments() ? " limiting-assigned " : " limiting-unassigned "; } if (task.isRoot() && task.belongsClosedProject()) { cssClass += " project-closed "; } return cssClass; } public boolean isLimiting() { return task.isLimiting(); } protected void updateClass() { setSclass(calculateCSSClass()); } public final void afterCompose() { updateProperties(); if (propertiesListener == null) { propertiesListener = new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { updateProperties(); } }; } this.task .addFundamentalPropertiesChangeListener(propertiesListener); if (showingAdvancePropertyListener == null) { showingAdvancePropertyListener = new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if (isInPage() && !(task instanceof Milestone)) { updateCompletionAdvance(); } } }; } this.task .addAdvancesPropertyChangeListener(showingAdvancePropertyListener); if (showingReportedHoursPropertyListener == null) { showingReportedHoursPropertyListener = new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if (isInPage() && !(task instanceof Milestone)) { updateCompletionReportedHours(); } } }; } this.task .addReportedHoursPropertyChangeListener(showingReportedHoursPropertyListener); if (criticalPathPropertyListener == null) { criticalPathPropertyListener = new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { updateClass(); } }; } this.task .addCriticalPathPropertyChangeListener(criticalPathPropertyListener); updateClass(); } /** * Note: This method is intended to be overridden. */ protected boolean canShowResourcesText() { return true; } private String _color; private boolean isTopLevel; private final Task task; private transient PropertyChangeListener propertiesListener; private IConstraintViolationListener<GanttDate> taskViolationListener; // FIXME Bug #1270 private String progressType; public TaskRow getRow() { if (getParent() == null) { throw new IllegalStateException( "the TaskComponent should have been wraped by a " + TaskRow.class.getName()); } return (TaskRow) getParent(); } public Task getTask() { return task; } public String getTaskName() { return task.getName(); } public String getLength() { return null; } public boolean isResizingTasksEnabled() { return (disabilityConfiguration != null) && disabilityConfiguration.isResizingTasksEnabled() && !task.isSubcontracted() && task.canBeExplicitlyResized(); } public boolean isMovingTasksEnabled() { return (disabilityConfiguration != null) && disabilityConfiguration.isMovingTasksEnabled() && task.canBeExplicitlyMoved(); } void doUpdatePosition(int leftX, int topY) { GanttDate startBeforeMoving = this.task.getBeginDate(); final LocalDate newPosition = getMapper().toDate(leftX); this.task.doPositionModifications(new IModifications() { @Override public void doIt(IUpdatablePosition position) { position.moveTo(GanttDate.createFrom(newPosition)); } }); boolean remainsInOriginalPosition = this.task.getBeginDate().equals( startBeforeMoving); if (remainsInOriginalPosition) { updateProperties(); } } void doUpdateSize(int size) { DateTime end = new DateTime(this.task.getBeginDate() .toDayRoundedDate().getTime()).plus(getMapper().toDuration( size)); this.task.resizeTo(end.toLocalDate()); updateProperties(); } void doAddDependency(String destinyTaskId) { getTaskList().addDependency(this, ((TaskComponent) getFellow(destinyTaskId))); } public String getColor() { return _color; } public void setColor(String color) { if ((color != null) && (color.length() == 0)) { color = null; } if (!Objects.equals(_color, color)) { _color = color; } } /* * We override the method of renderProperties to put the color property as part * of the style */ protected void renderProperties(ContentRenderer renderer) throws IOException{ if(getColor() != null) setStyle("background-color : " + getColor()); setWidgetAttribute("movingTasksEnabled",((Boolean)isMovingTasksEnabled()).toString()); setWidgetAttribute("resizingTasksEnabled", ((Boolean)isResizingTasksEnabled()).toString()); /*We can't use setStyle because of restrictions * involved with UiVisualizer#getResponses and the * smartUpdate method (when the request is asynchronous) */ render(renderer, "style", "position : absolute"); render(renderer, "_labelsText", getLabelsText()); render(renderer, "_resourcesText", getResourcesText()); render(renderer, "_tooltipText", getTooltipText()); super.renderProperties(renderer); } /* * We send a response to the client to create the arrow we are going to use * to create the dependency */ public void addDependency() { response("depkey", new AuInvoke(this, "addDependency")); } private IDatesMapper getMapper() { return getTaskList().getMapper(); } public TaskList getTaskList() { return getRow().getTaskList(); } @Override public void setParent(Component parent) { Validate.isTrue(parent == null || parent instanceof TaskRow); super.setParent(parent); } public final void zoomChanged() { updateProperties(); } public void updateProperties() { if (!isInPage()) { return; } setLeft("0"); setLeft(this.task.getBeginDate().toPixels(getMapper()) + "px"); updateWidth(); smartUpdate("name", this.task.getName()); updateDeadline(); updateCompletionIfPossible(); updateClass(); } private void updateWidth() { setWidth("0"); int pixelsEnd = this.task.getEndDate().toPixels(getMapper()); int pixelsStart = this.task.getBeginDate().toPixels(getMapper()); setWidth((pixelsEnd - pixelsStart) + "px"); } private void updateDeadline() { if (task.getDeadline() != null) { String position = (getMapper().toPixels( LocalDate.fromDateFields(task.getDeadline())) - HALF_DEADLINE_MARK) + "px"; response(null, new AuInvoke(this, "moveDeadline", position)); } else { // Move deadline out of visible area response(null, new AuInvoke(this, "moveDeadline","-100px")); } if (task.getConsolidatedline() != null) { int pixels = getMapper().toPixels( LocalDate.fromDateFields(task.getConsolidatedline() .toDayRoundedDate())) - CONSOLIDATED_MARK_HALF_WIDTH; String position = pixels + "px"; response(null, new AuInvoke(this, "moveConsolidatedline", position)); } else { // Move consolidated line out of visible area response(null, new AuInvoke(this, "moveConsolidatedline", "-100px")); } } public void updateCompletionIfPossible() { if (task instanceof Milestone) { return; } updateCompletionReportedHours(); updateCompletionAdvance(); } public void updateCompletionReportedHours() { if (task.isShowingReportedHours()) { int startPixels = this.task.getBeginDate().toPixels(getMapper()); String widthHoursAdvancePercentage = pixelsFromStartUntil( startPixels, this.task.getHoursAdvanceEndDate()) + "px"; response(null, new AuInvoke(this, "resizeCompletionAdvance", widthHoursAdvancePercentage)); } else { response(null, new AuInvoke(this, "resizeCompletionAdvance", "0px")); } } private void updateCompletionAdvance() { if (task.isShowingAdvances()) { int startPixels = this.task.getBeginDate().toPixels(getMapper()); String widthAdvancePercentage = pixelsFromStartUntil(startPixels, this.task.getAdvanceEndDate()) + "px"; response(null, new AuInvoke(this, "resizeCompletion2Advance", widthAdvancePercentage)); } else { response(null, new AuInvoke(this, "resizeCompletion2Advance", "0px")); } } public void updateCompletion(String progressType) { if (task.isShowingAdvances()) { int startPixels = this.task.getBeginDate().toPixels(getMapper()); String widthAdvancePercentage = pixelsFromStartUntil(startPixels, this.task.getAdvanceEndDate(progressType)) + "px"; response(null, new AuInvoke(this, "resizeCompletion2Advance", widthAdvancePercentage)); } else { response(null, new AuInvoke(this, "resizeCompletion2Advance", "0px")); } } private int pixelsFromStartUntil(int startPixels, GanttDate until) { int endPixels = until.toPixels(getMapper()); assert endPixels >= startPixels; return endPixels - startPixels; } public void updateTooltipText() { // FIXME Bug #1270 this.progressType = null; } public void updateTooltipText(String progressType) { // FIXME Bug #1270 this.progressType = progressType; } private GanttPanel getGanntPanel() { return getTaskList().getGanttPanel(); } private boolean isInPage() { return getPage() != null; } void publishTaskComponents(Map<Task, TaskComponent> resultAccumulated) { resultAccumulated.put(getTask(), this); publishDescendants(resultAccumulated); } protected void publishDescendants(Map<Task, TaskComponent> resultAccumulated) { } protected void remove() { this.getRow().detach(); task.removeReloadListener(reloadResourcesTextRequested); } public boolean isTopLevel() { return isTopLevel; } public String getTooltipText() { // FIXME Bug #1270 if (progressType == null) { return task.getTooltipText(); } else { return task.updateTooltipText(progressType); } } public String getLabelsText() { return task.getLabelsText(); } public String getLabelsDisplay() { Planner planner = getTaskList().getGanttPanel().getPlanner(); return planner.isShowingLabels() ? "inline" : "none"; } public String getResourcesText() { return task.getResourcesText(); } public String getResourcesDisplay() { Planner planner = getTaskList().getGanttPanel().getPlanner(); return planner.isShowingResources() ? "inline" : "none"; } public boolean isSubcontracted() { return task.isSubcontracted(); } public boolean isContainer() { return task.isContainer(); } @Override public String toString() { return task.toString(); } }
package com.badlogic.gdx.maps.tiled; import com.badlogic.gdx.assets.AssetDescriptor; import com.badlogic.gdx.assets.AssetLoaderParameters; import com.badlogic.gdx.assets.loaders.AsynchronousAssetLoader; import com.badlogic.gdx.assets.loaders.FileHandleResolver; import com.badlogic.gdx.assets.loaders.TextureLoader; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.maps.*; import com.badlogic.gdx.maps.objects.EllipseMapObject; import com.badlogic.gdx.maps.objects.PolygonMapObject; import com.badlogic.gdx.maps.objects.PolylineMapObject; import com.badlogic.gdx.maps.objects.RectangleMapObject; import com.badlogic.gdx.maps.tiled.TiledMapTileLayer.Cell; import com.badlogic.gdx.maps.tiled.objects.TiledMapTileMapObject; import com.badlogic.gdx.maps.tiled.tiles.AnimatedTiledMapTile; import com.badlogic.gdx.maps.tiled.tiles.StaticTiledMapTile; import com.badlogic.gdx.math.Polygon; import com.badlogic.gdx.math.Polyline; import com.badlogic.gdx.utils.*; import com.badlogic.gdx.utils.XmlReader.Element; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.StringTokenizer; import java.util.zip.GZIPInputStream; import java.util.zip.InflaterInputStream; public abstract class BaseTmxMapLoader<P extends BaseTmxMapLoader.Parameters> extends AsynchronousAssetLoader<TiledMap, P> { public static class Parameters extends AssetLoaderParameters<TiledMap> { /** generate mipmaps? **/ public boolean generateMipMaps = false; /** The TextureFilter to use for minification **/ public TextureFilter textureMinFilter = TextureFilter.Nearest; /** The TextureFilter to use for magnification **/ public TextureFilter textureMagFilter = TextureFilter.Nearest; /** Whether to convert the objects' pixel position and size to the equivalent in tile space. **/ public boolean convertObjectToTileSpace = false; /** Whether to flip all Y coordinates so that Y positive is up. All LibGDX renderers require flipped Y coordinates, and * thus flipY set to true. This parameter is included for non-rendering related purposes of TMX files, or custom renderers. */ public boolean flipY = true; } protected static final int FLAG_FLIP_HORIZONTALLY = 0x80000000; protected static final int FLAG_FLIP_VERTICALLY = 0x40000000; protected static final int FLAG_FLIP_DIAGONALLY = 0x20000000; protected static final int MASK_CLEAR = 0xE0000000; protected XmlReader xml = new XmlReader(); protected Element root; protected boolean convertObjectToTileSpace; protected boolean flipY = true; protected int mapTileWidth; protected int mapTileHeight; protected int mapWidthInPixels; protected int mapHeightInPixels; protected TiledMap map; public BaseTmxMapLoader (FileHandleResolver resolver) { super(resolver); } @Override public Array<AssetDescriptor> getDependencies (String fileName, FileHandle tmxFile, P parameter) { this.root = xml.parse(tmxFile); TextureLoader.TextureParameter textureParameter = new TextureLoader.TextureParameter(); if (parameter != null) { textureParameter.genMipMaps = parameter.generateMipMaps; textureParameter.minFilter = parameter.textureMinFilter; textureParameter.magFilter = parameter.textureMagFilter; } return getDependencyAssetDescriptors(tmxFile, textureParameter); } protected abstract Array<AssetDescriptor> getDependencyAssetDescriptors (FileHandle tmxFile, TextureLoader.TextureParameter textureParameter); /** * Loads the map data, given the XML root element * * @param tmxFile the Filehandle of the tmx file * @param parameter * @param imageResolver * @return the {@link TiledMap} */ protected TiledMap loadTiledMap (FileHandle tmxFile, P parameter, ImageResolver imageResolver) { this.map = new TiledMap(); if (parameter != null) { this.convertObjectToTileSpace = parameter.convertObjectToTileSpace; this.flipY = parameter.flipY; } else { this.convertObjectToTileSpace = false; this.flipY = true; } String mapOrientation = root.getAttribute("orientation", null); int mapWidth = root.getIntAttribute("width", 0); int mapHeight = root.getIntAttribute("height", 0); int tileWidth = root.getIntAttribute("tilewidth", 0); int tileHeight = root.getIntAttribute("tileheight", 0); int hexSideLength = root.getIntAttribute("hexsidelength", 0); String staggerAxis = root.getAttribute("staggeraxis", null); String staggerIndex = root.getAttribute("staggerindex", null); String mapBackgroundColor = root.getAttribute("backgroundcolor", null); MapProperties mapProperties = map.getProperties(); if (mapOrientation != null) { mapProperties.put("orientation", mapOrientation); } mapProperties.put("width", mapWidth); mapProperties.put("height", mapHeight); mapProperties.put("tilewidth", tileWidth); mapProperties.put("tileheight", tileHeight); mapProperties.put("hexsidelength", hexSideLength); if (staggerAxis != null) { mapProperties.put("staggeraxis", staggerAxis); } if (staggerIndex != null) { mapProperties.put("staggerindex", staggerIndex); } if (mapBackgroundColor != null) { mapProperties.put("backgroundcolor", mapBackgroundColor); } this.mapTileWidth = tileWidth; this.mapTileHeight = tileHeight; this.mapWidthInPixels = mapWidth * tileWidth; this.mapHeightInPixels = mapHeight * tileHeight; if (mapOrientation != null) { if ("staggered".equals(mapOrientation)) { if (mapHeight > 1) { this.mapWidthInPixels += tileWidth / 2; this.mapHeightInPixels = mapHeightInPixels / 2 + tileHeight / 2; } } } Element properties = root.getChildByName("properties"); if (properties != null) { loadProperties(map.getProperties(), properties); } Array<Element> tilesets = root.getChildrenByName("tileset"); for (Element element : tilesets) { loadTileSet(element, tmxFile, imageResolver); root.removeChild(element); } for (int i = 0, j = root.getChildCount(); i < j; i++) { Element element = root.getChild(i); loadLayer(map, map.getLayers(), element, tmxFile, imageResolver); } return map; } protected void loadLayer (TiledMap map, MapLayers parentLayers, Element element, FileHandle tmxFile, ImageResolver imageResolver) { String name = element.getName(); if (name.equals("group")) { loadLayerGroup(map, parentLayers, element, tmxFile, imageResolver); } else if (name.equals("layer")) { loadTileLayer(map, parentLayers, element); } else if (name.equals("objectgroup")) { loadObjectGroup(map, parentLayers, element); } else if (name.equals("imagelayer")) { loadImageLayer(map, parentLayers, element, tmxFile, imageResolver); } } protected void loadLayerGroup (TiledMap map, MapLayers parentLayers, Element element, FileHandle tmxFile, ImageResolver imageResolver) { if (element.getName().equals("group")) { MapGroupLayer groupLayer = new MapGroupLayer(); loadBasicLayerInfo(groupLayer, element); Element properties = element.getChildByName("properties"); if (properties != null) { loadProperties(groupLayer.getProperties(), properties); } for (int i = 0, j = element.getChildCount(); i < j; i++) { Element child = element.getChild(i); loadLayer(map, groupLayer.getLayers(), child, tmxFile, imageResolver); } for (MapLayer layer : groupLayer.getLayers()) { layer.setParent(groupLayer); } parentLayers.add(groupLayer); } } protected void loadTileLayer (TiledMap map, MapLayers parentLayers, Element element) { if (element.getName().equals("layer")) { int width = element.getIntAttribute("width", 0); int height = element.getIntAttribute("height", 0); int tileWidth = map.getProperties().get("tilewidth", Integer.class); int tileHeight = map.getProperties().get("tileheight", Integer.class); TiledMapTileLayer layer = new TiledMapTileLayer(width, height, tileWidth, tileHeight); loadBasicLayerInfo(layer, element); int[] ids = getTileIds(element, width, height); TiledMapTileSets tilesets = map.getTileSets(); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int id = ids[y * width + x]; boolean flipHorizontally = ((id & FLAG_FLIP_HORIZONTALLY) != 0); boolean flipVertically = ((id & FLAG_FLIP_VERTICALLY) != 0); boolean flipDiagonally = ((id & FLAG_FLIP_DIAGONALLY) != 0); TiledMapTile tile = tilesets.getTile(id & ~MASK_CLEAR); if (tile != null) { Cell cell = createTileLayerCell(flipHorizontally, flipVertically, flipDiagonally); cell.setTile(tile); layer.setCell(x, flipY ? height - 1 - y : y, cell); } } } Element properties = element.getChildByName("properties"); if (properties != null) { loadProperties(layer.getProperties(), properties); } parentLayers.add(layer); } } protected void loadObjectGroup (TiledMap map, MapLayers parentLayers, Element element) { if (element.getName().equals("objectgroup")) { MapLayer layer = new MapLayer(); loadBasicLayerInfo(layer, element); Element properties = element.getChildByName("properties"); if (properties != null) { loadProperties(layer.getProperties(), properties); } for (Element objectElement : element.getChildrenByName("object")) { loadObject(map, layer, objectElement); } parentLayers.add(layer); } } protected void loadImageLayer (TiledMap map, MapLayers parentLayers, Element element, FileHandle tmxFile, ImageResolver imageResolver) { if (element.getName().equals("imagelayer")) { float x = 0; float y = 0; if (element.hasAttribute("offsetx")) { x = Float.parseFloat(element.getAttribute("offsetx", "0")); } else { x = Float.parseFloat(element.getAttribute("x", "0")); } if (element.hasAttribute("offsety")) { y = Float.parseFloat(element.getAttribute("offsety", "0")); } else { y = Float.parseFloat(element.getAttribute("y", "0")); } if (flipY) y = mapHeightInPixels - y; TextureRegion texture = null; Element image = element.getChildByName("image"); if (image != null) { String source = image.getAttribute("source"); FileHandle handle = getRelativeFileHandle(tmxFile, source); texture = imageResolver.getImage(handle.path()); y -= texture.getRegionHeight(); } TiledMapImageLayer layer = new TiledMapImageLayer(texture, x, y); loadBasicLayerInfo(layer, element); Element properties = element.getChildByName("properties"); if (properties != null) { loadProperties(layer.getProperties(), properties); } parentLayers.add(layer); } } protected void loadBasicLayerInfo (MapLayer layer, Element element) { String name = element.getAttribute("name", null); float opacity = Float.parseFloat(element.getAttribute("opacity", "1.0")); boolean visible = element.getIntAttribute("visible", 1) == 1; float offsetX = element.getFloatAttribute("offsetx", 0); float offsetY = element.getFloatAttribute("offsety", 0); layer.setName(name); layer.setOpacity(opacity); layer.setVisible(visible); layer.setOffsetX(offsetX); layer.setOffsetY(offsetY); } protected void loadObject (TiledMap map, MapLayer layer, Element element) { loadObject(map, layer.getObjects(), element, mapHeightInPixels); } protected void loadObject (TiledMap map, TiledMapTile tile, Element element) { loadObject(map, tile.getObjects(), element, tile.getTextureRegion().getRegionHeight()); } protected void loadObject (TiledMap map, MapObjects objects, Element element, float heightInPixels) { if (element.getName().equals("object")) { MapObject object = null; float scaleX = convertObjectToTileSpace ? 1.0f / mapTileWidth : 1.0f; float scaleY = convertObjectToTileSpace ? 1.0f / mapTileHeight : 1.0f; float x = element.getFloatAttribute("x", 0) * scaleX; float y = (flipY ? (heightInPixels - element.getFloatAttribute("y", 0)) : element.getFloatAttribute("y", 0)) * scaleY; float width = element.getFloatAttribute("width", 0) * scaleX; float height = element.getFloatAttribute("height", 0) * scaleY; if (element.getChildCount() > 0) { Element child = null; if ((child = element.getChildByName("polygon")) != null) { String[] points = child.getAttribute("points").split(" "); float[] vertices = new float[points.length * 2]; for (int i = 0; i < points.length; i++) { String[] point = points[i].split(","); vertices[i * 2] = Float.parseFloat(point[0]) * scaleX; vertices[i * 2 + 1] = Float.parseFloat(point[1]) * scaleY * (flipY ? -1 : 1); } Polygon polygon = new Polygon(vertices); polygon.setPosition(x, y); object = new PolygonMapObject(polygon); } else if ((child = element.getChildByName("polyline")) != null) { String[] points = child.getAttribute("points").split(" "); float[] vertices = new float[points.length * 2]; for (int i = 0; i < points.length; i++) { String[] point = points[i].split(","); vertices[i * 2] = Float.parseFloat(point[0]) * scaleX; vertices[i * 2 + 1] = Float.parseFloat(point[1]) * scaleY * (flipY ? -1 : 1); } Polyline polyline = new Polyline(vertices); polyline.setPosition(x, y); object = new PolylineMapObject(polyline); } else if ((child = element.getChildByName("ellipse")) != null) { object = new EllipseMapObject(x, flipY ? y - height : y, width, height); } } if (object == null) { String gid = null; if ((gid = element.getAttribute("gid", null)) != null) { int id = (int)Long.parseLong(gid); boolean flipHorizontally = ((id & FLAG_FLIP_HORIZONTALLY) != 0); boolean flipVertically = ((id & FLAG_FLIP_VERTICALLY) != 0); TiledMapTile tile = map.getTileSets().getTile(id & ~MASK_CLEAR); TiledMapTileMapObject tiledMapTileMapObject = new TiledMapTileMapObject(tile, flipHorizontally, flipVertically); TextureRegion textureRegion = tiledMapTileMapObject.getTextureRegion(); tiledMapTileMapObject.getProperties().put("gid", id); tiledMapTileMapObject.setX(x); tiledMapTileMapObject.setY(flipY ? y : y - height); float objectWidth = element.getFloatAttribute("width", textureRegion.getRegionWidth()); float objectHeight = element.getFloatAttribute("height", textureRegion.getRegionHeight()); tiledMapTileMapObject.setScaleX(scaleX * (objectWidth / textureRegion.getRegionWidth())); tiledMapTileMapObject.setScaleY(scaleY * (objectHeight / textureRegion.getRegionHeight())); tiledMapTileMapObject.setRotation(element.getFloatAttribute("rotation", 0)); object = tiledMapTileMapObject; } else { object = new RectangleMapObject(x, flipY ? y - height : y, width, height); } } object.setName(element.getAttribute("name", null)); String rotation = element.getAttribute("rotation", null); if (rotation != null) { object.getProperties().put("rotation", Float.parseFloat(rotation)); } String type = element.getAttribute("type", null); if (type != null) { object.getProperties().put("type", type); } int id = element.getIntAttribute("id", 0); if (id != 0) { object.getProperties().put("id", id); } object.getProperties().put("x", x); if (object instanceof TiledMapTileMapObject) { object.getProperties().put("y", y); } else { object.getProperties().put("y", (flipY ? y - height : y)); } object.getProperties().put("width", width); object.getProperties().put("height", height); object.setVisible(element.getIntAttribute("visible", 1) == 1); Element properties = element.getChildByName("properties"); if (properties != null) { loadProperties(object.getProperties(), properties); } objects.add(object); } } protected void loadProperties (MapProperties properties, Element element) { if (element == null) return; if (element.getName().equals("properties")) { for (Element property : element.getChildrenByName("property")) { String name = property.getAttribute("name", null); String value = property.getAttribute("value", null); String type = property.getAttribute("type", null); if (value == null) { value = property.getText(); } Object castValue = castProperty(name, value, type); properties.put(name, castValue); } } } private Object castProperty (String name, String value, String type) { if (type == null) { return value; } else if (type.equals("int")) { return Integer.valueOf(value); } else if (type.equals("float")) { return Float.valueOf(value); } else if (type.equals("bool")) { return Boolean.valueOf(value); } else if (type.equals("color")) { // Tiled uses the format #AARRGGBB String opaqueColor = value.substring(3); String alpha = value.substring(1, 3); return Color.valueOf(opaqueColor + alpha); } else { throw new GdxRuntimeException("Wrong type given for property " + name + ", given : " + type + ", supported : string, bool, int, float, color"); } } protected Cell createTileLayerCell (boolean flipHorizontally, boolean flipVertically, boolean flipDiagonally) { Cell cell = new Cell(); if (flipDiagonally) { if (flipHorizontally && flipVertically) { cell.setFlipHorizontally(true); cell.setRotation(Cell.ROTATE_270); } else if (flipHorizontally) { cell.setRotation(Cell.ROTATE_270); } else if (flipVertically) { cell.setRotation(Cell.ROTATE_90); } else { cell.setFlipVertically(true); cell.setRotation(Cell.ROTATE_270); } } else { cell.setFlipHorizontally(flipHorizontally); cell.setFlipVertically(flipVertically); } return cell; } static public int[] getTileIds (Element element, int width, int height) { Element data = element.getChildByName("data"); String encoding = data.getAttribute("encoding", null); if (encoding == null) { // no 'encoding' attribute means that the encoding is XML throw new GdxRuntimeException("Unsupported encoding (XML) for TMX Layer Data"); } int[] ids = new int[width * height]; if (encoding.equals("csv")) { String[] array = data.getText().split(","); for (int i = 0; i < array.length; i++) ids[i] = (int)Long.parseLong(array[i].trim()); } else { if (true) if (encoding.equals("base64")) { InputStream is = null; try { String compression = data.getAttribute("compression", null); byte[] bytes = Base64Coder.decode(data.getText()); if (compression == null) is = new ByteArrayInputStream(bytes); else if (compression.equals("gzip")) is = new BufferedInputStream(new GZIPInputStream(new ByteArrayInputStream(bytes), bytes.length)); else if (compression.equals("zlib")) is = new BufferedInputStream(new InflaterInputStream(new ByteArrayInputStream(bytes))); else throw new GdxRuntimeException("Unrecognised compression (" + compression + ") for TMX Layer Data"); byte[] temp = new byte[4]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int read = is.read(temp); while (read < temp.length) { int curr = is.read(temp, read, temp.length - read); if (curr == -1) break; read += curr; } if (read != temp.length) throw new GdxRuntimeException("Error Reading TMX Layer Data: Premature end of tile data"); ids[y * width + x] = unsignedByteToInt(temp[0]) | unsignedByteToInt(temp[1]) << 8 | unsignedByteToInt(temp[2]) << 16 | unsignedByteToInt(temp[3]) << 24; } } } catch (IOException e) { throw new GdxRuntimeException("Error Reading TMX Layer Data - IOException: " + e.getMessage()); } finally { StreamUtils.closeQuietly(is); } } else { // any other value of 'encoding' is one we're not aware of, probably a feature of a future version of Tiled // or another editor throw new GdxRuntimeException("Unrecognised encoding (" + encoding + ") for TMX Layer Data"); } } return ids; } protected static int unsignedByteToInt (byte b) { return b & 0xFF; } protected static FileHandle getRelativeFileHandle (FileHandle file, String path) { StringTokenizer tokenizer = new StringTokenizer(path, "\\/"); FileHandle result = file.parent(); while (tokenizer.hasMoreElements()) { String token = tokenizer.nextToken(); if (token.equals("..")) result = result.parent(); else { result = result.child(token); } } return result; } protected void loadTileSet (Element element, FileHandle tmxFile, ImageResolver imageResolver) { if (element.getName().equals("tileset")) { String imageSource = ""; int imageWidth = 0; int imageHeight = 0; FileHandle image = null; String source = element.getAttribute("source", null); if (source != null) { FileHandle tsx = getRelativeFileHandle(tmxFile, source); try { element = xml.parse(tsx); Element imageElement = element.getChildByName("image"); if (imageElement != null) { imageSource = imageElement.getAttribute("source"); imageWidth = imageElement.getIntAttribute("width", 0); imageHeight = imageElement.getIntAttribute("height", 0); image = getRelativeFileHandle(tsx, imageSource); } } catch (SerializationException e) { throw new GdxRuntimeException("Error parsing external tileset."); } } else { Element imageElement = element.getChildByName("image"); if (imageElement != null) { imageSource = imageElement.getAttribute("source"); imageWidth = imageElement.getIntAttribute("width", 0); imageHeight = imageElement.getIntAttribute("height", 0); image = getRelativeFileHandle(tmxFile, imageSource); } } String name = element.get("name", null); int firstgid = element.getIntAttribute("firstgid", 1); int tilewidth = element.getIntAttribute("tilewidth", 0); int tileheight = element.getIntAttribute("tileheight", 0); int spacing = element.getIntAttribute("spacing", 0); int margin = element.getIntAttribute("margin", 0); Element offset = element.getChildByName("tileoffset"); int offsetX = 0; int offsetY = 0; if (offset != null) { offsetX = offset.getIntAttribute("x", 0); offsetY = offset.getIntAttribute("y", 0); } TiledMapTileSet tileSet = new TiledMapTileSet(); // TileSet tileSet.setName(name); final MapProperties tileSetProperties = tileSet.getProperties(); Element properties = element.getChildByName("properties"); if (properties != null) { loadProperties(tileSetProperties, properties); } tileSetProperties.put("firstgid", firstgid); // Tiles Array<Element> tileElements = element.getChildrenByName("tile"); addStaticTiles(tmxFile, imageResolver, tileSet, element, tileElements, name, firstgid, tilewidth, tileheight, spacing, margin, source, offsetX, offsetY, imageSource, imageWidth, imageHeight, image); for (Element tileElement : tileElements) { int localtid = tileElement.getIntAttribute("id", 0); TiledMapTile tile = tileSet.getTile(firstgid + localtid); if (tile != null) { addTileProperties(tile, tileElement); addTileObjectGroup(tile, tileElement); addAnimatedTile(tileSet, tile, tileElement, firstgid); } } map.getTileSets().addTileSet(tileSet); } } protected abstract void addStaticTiles (FileHandle tmxFile, ImageResolver imageResolver, TiledMapTileSet tileset, Element element, Array<Element> tileElements, String name, int firstgid, int tilewidth, int tileheight, int spacing, int margin, String source, int offsetX, int offsetY, String imageSource, int imageWidth, int imageHeight, FileHandle image); protected void addTileProperties (TiledMapTile tile, Element tileElement) { String terrain = tileElement.getAttribute("terrain", null); if (terrain != null) { tile.getProperties().put("terrain", terrain); } String probability = tileElement.getAttribute("probability", null); if (probability != null) { tile.getProperties().put("probability", probability); } Element properties = tileElement.getChildByName("properties"); if (properties != null) { loadProperties(tile.getProperties(), properties); } } protected void addTileObjectGroup (TiledMapTile tile, Element tileElement) { Element objectgroupElement = tileElement.getChildByName("objectgroup"); if (objectgroupElement != null) { for (Element objectElement : objectgroupElement.getChildrenByName("object")) { loadObject(map, tile, objectElement); } } } protected void addAnimatedTile (TiledMapTileSet tileSet, TiledMapTile tile, Element tileElement, int firstgid) { Element animationElement = tileElement.getChildByName("animation"); if (animationElement != null) { Array<StaticTiledMapTile> staticTiles = new Array<StaticTiledMapTile>(); IntArray intervals = new IntArray(); for (Element frameElement : animationElement.getChildrenByName("frame")) { staticTiles.add((StaticTiledMapTile)tileSet.getTile(firstgid + frameElement.getIntAttribute("tileid"))); intervals.add(frameElement.getIntAttribute("duration")); } AnimatedTiledMapTile animatedTile = new AnimatedTiledMapTile(intervals, staticTiles); animatedTile.setId(tile.getId()); tileSet.putTile(tile.getId(), animatedTile); } } protected void addStaticTiledMapTile (TiledMapTileSet tileSet, TextureRegion textureRegion, int tileId, float offsetX, float offsetY) { TiledMapTile tile = new StaticTiledMapTile(textureRegion); tile.setId(tileId); tile.setOffsetX(offsetX); tile.setOffsetY(flipY ? -offsetY : offsetY); tileSet.putTile(tileId, tile); } }
package ca.stephenjust.todolist; import ca.stephenjust.todolist.data.TodoContainer; import ca.stephenjust.todolist.data.TodoItem; import ca.stephenjust.todolist.data.TodoList; import android.app.ActionBar; import android.app.Activity; import android.app.DialogFragment; import android.app.FragmentTransaction; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import android.widget.ViewSwitcher; public class TodoListActivity extends Activity implements TodoListFragment.OnFragmentInteractionListener, TodoEditFragment.OnFragmentInteractionListener { TodoContainer mTodoContainer = null; TodoListFragment m_fragment = null; TodoListFragment m_fragment_archived = null; ViewSwitcher mViewSwitcher = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mTodoContainer = TodoContainer.getInstance(); setupTabs(); setContentView(R.layout.activity_todo_list); if (savedInstanceState == null) { m_fragment = TodoListFragment.newInstance(TodoContainer.TODO_CURRENT, TodoContainer.TODO_ARCHIVE); m_fragment_archived = TodoListFragment.newInstance(TodoContainer.TODO_ARCHIVE, TodoContainer.TODO_CURRENT); getFragmentManager().beginTransaction() .add(R.id.container, m_fragment, "MAIN_FRAGMENT") .add(R.id.container_archived, m_fragment_archived).commit(); mViewSwitcher = (ViewSwitcher) findViewById(R.id.view_switcher); } } public void setupTabs() { final ActionBar actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); ActionBar.TabListener tabListener = new ActionBar.TabListener() { public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) { if (mViewSwitcher != null) { mViewSwitcher.setDisplayedChild(tab.getPosition()); } if (m_fragment != null) { m_fragment.finishActionMode(); } if (m_fragment_archived != null) { m_fragment_archived.finishActionMode(); } } public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) { // hide the given tab } public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) { // probably ignore this event } }; actionBar.addTab( actionBar.newTab() .setText(R.string.tab_current) .setTabListener(tabListener)); actionBar.addTab( actionBar.newTab() .setText(R.string.tab_archived) .setTabListener(tabListener)); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.todo_list, menu); return true; } @Override public void onPause() { super.onPause(); mTodoContainer.saveLists(getApplication()); } private void addTodoItem() { DialogFragment dlg = TodoEditFragment.newInstance(""); FragmentTransaction ft = getFragmentManager().beginTransaction(); dlg.show(ft, "dialog"); mTodoContainer.saveLists(this); } private void launchSummary() { Intent intent = new Intent(this, SummaryActivity.class); startActivity(intent); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_add) { addTodoItem(); return true; } else if (id == R.id.action_summary) { launchSummary(); return true; } else if (id == R.id.action_email_all) { TodoList current = mTodoContainer.getList(this, TodoContainer.TODO_CURRENT); TodoList archived = mTodoContainer.getList(this, TodoContainer.TODO_ARCHIVE); TodoList emailList = new TodoList(); emailList.addAll(current); emailList.addAll(archived); TodoEmailer e = new TodoEmailer(this, emailList); e.send(); return true; } return super.onOptionsItemSelected(item); } @Override public void onFragmentInteraction(Bundle bundle) { String fragment = bundle.getString("fragment"); if (m_fragment == null) { m_fragment = (TodoListFragment) getFragmentManager().findFragmentByTag("MAIN_FRAGMENT"); } if (fragment.equals("edit")) { TodoList list = m_fragment.getTodoList(); if (list != null) { try { list.add(new TodoItem(bundle.getString("value"))); TodoAdapter la = (TodoAdapter) m_fragment.getListAdapter(); la.notifyDataSetChanged(); Toast.makeText(this, R.string.todo_created, Toast.LENGTH_SHORT).show(); } catch (IllegalArgumentException ex) { Toast.makeText(this, R.string.invalid_todo_text, Toast.LENGTH_SHORT).show(); } } } } }
package com.ajinkya.javaapp2; public class MainRunner { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Welcome to git"); System.out.println("Changed by Aarish "); } }
package ru.pack.tests; import com.google.common.collect.ImmutableMap; import com.jcabi.github.*; import org.testng.annotations.Test; import java.io.IOException; public class GithubTests { @Test public void testCommitBarantsev() throws IOException { Github github = new RtGithub("e1074a3eeb968f536fae506bfe0921f8160f7fc1"); RepoCommits commits = github.repos().get(new Coordinates.Simple("javerdy", "ja_verdy")).commits(); for (RepoCommit commit : commits.iterate(new ImmutableMap.Builder<String, String>().build())) { System.out.println(new RepoCommit.Smart(commit).message()); } } @Test public void testCommitGmail() throws IOException { Github github = new RtGithub("e1074a3eeb968f536fae506bfe0921f8160f7fc1"); RepoCommits commits = github.repos().get(new Coordinates.Simple("javerdy", "gettingtest")).commits(); for (RepoCommit commit : commits.iterate(new ImmutableMap.Builder<String, String>().build())) { System.out.println(new RepoCommit.Smart(commit).message()); } } }
package app.hongs.db.util; import app.hongs.Core; import app.hongs.HongsException; import app.hongs.db.Table; import app.hongs.util.Dict; import app.hongs.util.Synt; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * * <h3>:</h3> * <pre> * : 0x10c2~0x10cf * 0x10c2 (LINK) * 0x10c4 (JOIN) * 0x10c6 (LINK) * 0x10c8 (JOIN) * 0x10ca Map * 0x10cc MapList * </pre> * * @author Hongs */ public class UniteTool { /** * * @param table * @param caze * @param assocs * @return * @throws HongsException */ public static List fetchMore (Table table, FetchCase caze, Map assocs) throws HongsException { if (assocs == null) assocs = new HashMap(); List<Map> lnks = new ArrayList ( ); fetchMore(table, caze, assocs, lnks, null); buildCase(caze, table.getParams()); // Fixed in 2015/10/22 if (!caze.hasField()) { caze.select(".*"); } List rows = table.db.fetchMore(caze); fetchMore(table, caze, rows , lnks); return rows; } private static void fetchMore (Table table, FetchCase caze, Map assocs, List lnks2, String pn) throws HongsException { Set tns = (Set)caze.getOption("ASSOCS"); Set tps = (Set)caze.getOption("ASSOC_TYPES"); Set jns = (Set)caze.getOption("ASSOC_JOINS"); Set jis = new HashSet(Arrays.asList("MERGE", "")); String tn = caze.name; if (tn == null || tn.length() == 0) tn = caze.tableName; for(Map.Entry et : (Set<Map.Entry>)assocs.entrySet()) { Map assoc = (Map) et.getValue(); String tp = (String)assoc.get("type"); String jn = (String)assoc.get("join"); String an = (String)assoc.get("name"); String rn = (String)assoc.get("tableName"); if (rn == null || rn.length() == 0) rn = an ; if (rn == null || rn.length() == 0) continue; if (tns != null && !tns.contains(rn) && !tns.contains(an)) { continue; } if (tps != null && !tps.contains(tp)) { continue; } if (jn != null && !jis.contains(jn)) { if (jns != null && !jns.contains(jn)) { continue; }} else { // JOIN assoc.put("assocName", tn); lnks2.add( assoc ); continue; } Map assocs2 = (Map)assoc.get("assocs"); String fk = (String)assoc.get("foreignKey"); String pk = (String)assoc.get("primaryKey"); Table table2 = table.db.getTable(rn); FetchCase caze2 = caze.gotJoin (an).from(table2.tableName); if ("BLS_TO".equals(tp)) { if (pk == null) pk = table2.primaryKey; if (tn == null || tn.length() == 0) { fk = ":`"+fk+"`"; } else { fk = "`"+tn+"`.`"+fk+"`"; } pk = "`"+an+"`.`"+pk+"`"; } else if ("HAS_ONE".equals(tp)) { if (pk == null) pk = table .primaryKey; if (tn == null || tn.length() == 0) { pk = ":`"+pk+"`"; } else { pk = "`"+tn+"`.`"+pk+"`"; } fk = "`"+an+"`.`"+fk+"`"; } else if ("HAS_MANY".equals(tp) || "HAS_MORE".equals(tp)) { throw new HongsException(0x10c2, "Unsupported assoc type '"+tp+"'"); } else { throw new HongsException(0x10c2, "Unrecognized assoc type '"+tp+"'"); } caze2.on( pk +"="+ fk ); byte ji; if ( "LEFT".equals(jn)) { ji = FetchCase.LEFT; } else if ("RIGHT".equals(jn)) { ji = FetchCase.RIGHT; } else if ( "FULL".equals(jn)) { ji = FetchCase.FULL; } else if ("INNER".equals(jn)) { ji = FetchCase.INNER; } else if ("CROSS".equals(jn)) { throw new HongsException(0x10c4, "Unsupported assoc join '"+jn+"'"); } else { throw new HongsException(0x10c4, "Unrecognized assoc join '"+jn+"'"); } caze2.by( ji ); String pu = an; if (null != pn) { pu = pn +"."+ pu; } caze2.in( pu ); buildCase(caze2 , (Map) assoc.get("params")); if ( assocs2 != null ) { fetchMore(table2, caze2, assocs2, lnks2, pu); } // Fixed in 2015/10/22 // JOIN * (), if ( ! caze.hasField( ) && ! caze2.hasField( ) ) { Set<String> cols = table2.getFields().keySet(); for(String col : cols) { caze2.select(".`"+ col +"` AS `"+an+"."+ col +"`"); } } } } private static void fetchMore (Table table, FetchCase caze, List rows2, List lnks2) throws HongsException { Set tns = (Set)caze.getOption("ASSOCS"); Set tps = (Set)caze.getOption("ASSOC_TYPES"); FetchMore join = new FetchMore( rows2 ); while (!lnks2.isEmpty()) { List lnkz2 = new ArrayList( ); for(Map assoc : (List<Map>) lnks2) { String tp = (String)assoc.get("type"); String jn = (String)assoc.get("join"); String an = (String)assoc.get("name"); String rn = (String)assoc.get("tableName"); String tn = (String)assoc.get("assocName"); if (rn == null || rn.length() == 0) rn = an ; if (rn == null || rn.length() == 0) continue; if (tns != null && !tns.contains(rn) && !tns.contains(an)) { continue; } if (tps != null && !tps.contains(tp)) { continue; } Map assocs2 = (Map)assoc.get("assocs"); String fk = (String)assoc.get("foreignKey"); String pk = (String)assoc.get("primaryKey"); Table table2 = table.db.getTable(rn); FetchCase caze2 = caze.gotJoin (an).from(table2.tableName); if ("BLS_TO".equals(tp)) { String xk = fk; fk = pk; pk = xk; if (fk == null) fk = table2.primaryKey; caze2.setOption("ASSOC_MULTI" , false); } else if ("HAS_ONE".equals(tp)) { if (pk == null) pk = table .primaryKey; caze2.setOption("ASSOC_MULTI" , false); } else if ("HAS_MANY".equals(tp)) { if (pk == null) pk = table .primaryKey; caze2.setOption("ASSOC_MULTI" , true ); } else if ("HAS_MORE".equals(tp)) { if (pk == null) pk = table .primaryKey; caze2.setOption("ASSOC_MULTI" , true ); if (assocs2 != null) { for(Map ass : ( Collection<Map> ) assocs2.values()) { if (ass.containsKey ( "join" ) != true) { ass.put( "join", "MERGE" ); } } } } else { throw new HongsException(0x10c2, "Unrecognized assoc type '"+tp+"'"); } if (tn != null && tn.length() != 0 && !tn.equals(caze.name)) { pk = tn +"."+ pk; } caze2.setOption("ASSOC_MERGE", "MERGE".equals(jn)); buildCase(caze2 , (Map) assoc.get( "params" )); if ( assocs2 != null ) { fetchMore(table2, caze2, assocs2, lnkz2, null); } join.join (table2, caze2, pk, fk.startsWith(":") ? fk.substring(1) : fk); } lnks2 = lnkz2; } } private static void buildCase(FetchCase caze, Map assoc) { if (assoc == null || assoc.isEmpty()) { return ; } String sql; boolean has = false; boolean haz = false; sql = (String) assoc.get("select"); if (sql != null) { caze.field (sql); if (!sql.startsWith(".") && sql.length() != 0) { has = true; haz = true; } } sql = (String) assoc.get("orders"); if (sql != null) { caze.order(sql); if (!has && !sql.startsWith(".") && sql.length() != 0) { has = true; } } sql = (String) assoc.get("filter"); if (sql != null && sql.length() != 0) { caze.filter(sql); if (!has && !sql.startsWith(".")) { has = true; } } sql = (String) assoc.get("groups"); if (sql != null) { caze.group(sql); if (!has && !sql.startsWith(".") && sql.length() != 0) { has = true; } } sql = (String) assoc.get("having"); if (sql != null && sql.length() != 0) { caze.having(sql); if (!has && !sql.startsWith(".")) { has = true; } } sql = (String) assoc.get("limits"); if (sql != null && sql.length() != 0) { caze.limit (Synt.asserts(sql, 1)); // JOIN } if (has) { caze.setOption("UNFIX_FIELD", false); } if (haz) { caze.setOption("UNFIX_ALIAS", false); } } /** * * * @param table * @param rows * @param keys * @param where / * @param params where * @throws HongsException */ public static void updateMore( Table table, List<Map> rows, String[ ] keys, String where, Object... params ) throws HongsException { List<Object> params1 = Arrays.asList(params); List<Object> params2; Object[] params3; StringBuilder where2 = new StringBuilder(where); String where3; for (String k : keys) { where2.append(" AND `").append(k).append("` = ?"); } where3 = where2.toString( ); List ids = new ArrayList( ); // , 2015/12/15 String rstat = table.getField( "state" ); String vstat = table.getState("default"); for (Map row : rows) { // , 2015/12/15 if (rstat != null && vstat != null && !row.containsKey(rstat)) { row.put( rstat , vstat ); } params2 = new ArrayList(params1); for (String k : keys ) { params2.add(row.get(k) ); } params3 = params2.toArray( ); String sql = "SELECT `" + table.primaryKey + "` FROM `" + table.tableName + "` WHERE " + where2; Map<String, Object> one = table.db.fetchOne( sql , params3 ); if (!one.isEmpty()) { if (!row.containsKey(table.primaryKey) || "".equals(row.get(table.primaryKey))) { row.put(table.primaryKey, one.get(table.primaryKey)); } table.update(row, where3, params3); } else { if (!row.containsKey(table.primaryKey) || "".equals(row.get(table.primaryKey))) { row.put(table.primaryKey, Core.getUniqueId(/*SID*/)); } table.insert(row); } ids.add(row.get(table.primaryKey)); } where2 = new StringBuilder(where); where2.append(" AND `").append(table.primaryKey).append("` NOT IN (?)"); params2 = new ArrayList( params1 ); params2.add( ids ); table .delete( where2.toString( ), params2.toArray()); } /** * * * unique , updateMore * * @param table * @param assocs * @param values * @throws app.hongs.HongsException */ public static void insertMore(Table table, Map assocs, Map values) throws HongsException { if ( assocs == null || assocs.isEmpty( ) ) return; String id = (String) values.get(table.primaryKey); Iterator it = assocs.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next( ); Map config = (Map)entry.getValue(); String type = (String)config.get("type"); String name = (String)config.get("name"); String tableName = (String)config.get("tableName" ); String foreignKey = (String)config.get("foreignKey"); if (!values.containsKey(name)) { continue; } if (!type.equals("HAS_ONE") && !type.equals("HAS_MANY") && !type.equals("HAS_MORE")) { continue; } if (tableName == null || tableName.length() == 0) { tableName = name; } Table tb = table.db.getTable(tableName); // List Object subValues = values.get(name); List subValues2 = new ArrayList( ); if ("HAS_ONE".equals(type)) { if (subValues instanceof Map) { subValues2.add( subValues ); } else { throw new HongsException(0x10ca, "Sub data type for table '"+tb.name+"' must be Map"); } } else { if (subValues instanceof Map) { subValues2.addAll(((Map)subValues).values()); } else if (subValues instanceof Collection) { subValues2.addAll(( Collection ) subValues ); } else { throw new HongsException(0x10cc, "Sub data type for table '"+tb.name+"' must be Map or List"); } } /** * Add by Hongs on 2016/4/13 * filter , filter */ String wh = (String) config.get("filter"); if (wh != null && wh.length() != 0) { Pattern pat = Pattern.compile("(?:`(.*?)`|(\\w+))\\s*=\\s*(?:'(.*?)'|(\\d+(?:\\.\\d+)?))"); Matcher mat = pat.matcher(wh); Map map = new HashMap(); while ( mat.find()) { String n = mat.group(1); if (null == n ) { n = mat.group(2); } String v = mat.group(3); if (null == v ) { v = mat.group(4); } map.put( n, v ); } Iterator it2 = subValues2.iterator(); while ( it2.hasNext() ) { Map subValues3 = (Map) it2.next( ); subValues3.putAll(map); } wh = "`"+foreignKey+"`=? AND " + wh ; } else { wh = "`"+foreignKey+"`=?"; } /** * Add by Hongs on 2016/4/13 * convey , convey */ String cs = (String) config.get("convey"); if (cs != null && cs.length() != 0) { String[] cz = cs.split("\\s*,\\s*" ); Map cd = new HashMap(); for(String cn : cz ) { cd.put(cn , values.get( cn ) ); } Iterator it2 = subValues2.iterator(); while ( it2.hasNext() ) { Map subValues3 = (Map) it2.next( ); subValues3.putAll (cd); } } /** * Add by Hongs on 2013/6/6 * , , ID; * : ; * unique , updateMore , : * , , . */ String ks = (String) config.get("unique"); if (ks == null || ks.length() == 0) { // 2016/4/15, ks = Dict.getValue(tb.getAssocs(), "", "@", "unique"); } if (ks != null && ks.length() != 0) { String[] kz = ks.split("\\s*,\\s*" ); Iterator it2 = subValues2.iterator(); while ( it2.hasNext() ) { Map subValues3 = (Map) it2.next( ); subValues3.put ( foreignKey , id ); } updateMore(tb, subValues2, kz, wh, id); } else { tb.delete("`"+foreignKey+"`=?" , id); Iterator it2 = subValues2.iterator(); while ( it2.hasNext() ) { Map subValues3 = (Map) it2.next( ); subValues3.put ( foreignKey , id ); if (tb.primaryKey != null && tb.primaryKey.length() != 0 && ! subValues3.containsKey( tb.primaryKey )) { subValues3.put(tb.primaryKey, Core.getUniqueId()); } tb.insert(subValues3); } } } } /** * * * @param table * @param assocs * @param ids * @throws app.hongs.HongsException */ public static void deleteMore(Table table, Map assocs, Object... ids) throws HongsException { if ( assocs == null || assocs.isEmpty( ) ) return; Iterator it = assocs.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next( ); Map config = (Map)entry.getValue(); String type = (String)config.get("type"); String name = (String)config.get("name"); String tableName = (String)config.get("tableName" ); String foreignKey = (String)config.get("foreignKey"); if (!type.equals("HAS_ONE") && !type.equals("HAS_MANY") && !type.equals("HAS_MORE")) { continue; } if (tableName == null || tableName.length() == 0) { tableName = name; } Table tbl = table.db.getTable(tableName); List idx = null; if (tbl.primaryKey != null && tbl.primaryKey.length() != 0) { List<Map> lst = tbl.fetchMore ( new FetchCase() .select("`" + tbl.primaryKey + "`") .filter("`" + foreignKey + "`=?", ids ) ); idx = new ArrayList(); for ( Map row : lst ) { idx.add(row.get(tbl.primaryKey)); } } tbl.delete("`"+foreignKey+"`=?",ids); if (idx != null && ! idx.isEmpty() ) { deleteMore(tbl , tbl.getAssocs() , idx.toArray()); } } } }
package io.github.ihongs; import io.github.ihongs.util.thread.Block; import io.github.ihongs.util.thread.Block.Larder; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Date; import java.util.HashMap; import java.util.Map; public abstract class CoreSerial implements Serializable { /** * * @param path * @param name * @param time * @throws io.github.ihongs.HongsException */ public CoreSerial(String path, String name, long time) throws HongsException { this.init(path, name, time); } /** * * @param path * @param name * @param date * @throws io.github.ihongs.HongsException */ public CoreSerial(String path, String name, Date date) throws HongsException { this.init(path, name, date); } /** * * @param name * @param time * @throws io.github.ihongs.HongsException */ public CoreSerial(String name, long time) throws HongsException { this.init(name, time); } /** * * @param name * @param date * @throws io.github.ihongs.HongsException */ public CoreSerial(String name, Date date) throws HongsException { this.init(name, date); } /** * * @param name * @throws io.github.ihongs.HongsException */ public CoreSerial(String name) throws HongsException { this.init(name); } /** * (init) */ public CoreSerial() { // TODO: init } /** * * @throws io.github.ihongs.HongsException */ abstract protected void imports() throws HongsException; /** * * @param time * @return true * @throws io.github.ihongs.HongsException */ protected boolean expired(long time) throws HongsException { return time != 0 && time < System.currentTimeMillis(); } /** * () * @param path * @param name * @param time * @throws io.github.ihongs.HongsException */ protected final void init(String path, String name, long time) throws HongsException { if (path == null) { path = Core.DATA_PATH + File.separator + "serial"; } File file = new File(path + File.separator + name + ".ser"); this.init(name, file, time + file.lastModified( )); } /** * () * @param path * @param name * @param date * @throws io.github.ihongs.HongsException */ protected final void init(String path, String name, Date date) throws HongsException { if (path == null) { path = Core.DATA_PATH + File.separator + "serial"; } File file = new File(path + File.separator + name + ".ser"); this.init(name, file, date!=null?date.getTime():0); } protected final void init(String name, long time) throws HongsException { this.init(null, name, time); } protected final void init(String name, Date date) throws HongsException { this.init(null, name, date); } protected final void init(String name) throws HongsException { this.init(null, name, null); } /** * * @param file * @param time * @throws io.github.ihongs.HongsException */ protected final void init(String name, File file, long time) throws HongsException { Larder lock = Block.getLarder(CoreSerial.class.getName() + ":" + name); lock.lockr(); try { if (file.exists() && !expired(time)) { load(file); return; } } finally { lock.unlockr(); } lock.lockw(); try { imports (); save(file); } finally { lock.unlockw(); } } /** * * @param file * @throws io.github.ihongs.HongsException */ protected final void load(File file) throws HongsException { try { FileInputStream fis = null; ObjectInputStream ois = null; try { fis = new FileInputStream(file); ois = new ObjectInputStream(fis ); load(ois.readObject()); } finally { if (ois != null) ois.close(); if (fis != null) fis.close(); } } catch (ClassNotFoundException ex) { throw new HongsException(0x10d8, ex); } catch (FileNotFoundException ex) { throw new HongsException(0x10d6, ex); } catch (IOException ex) { throw new HongsException(0x10d4, ex); } } /** * * @param file * @throws io.github.ihongs.HongsException */ protected final void save(File file) throws HongsException { if (!file.exists()) { File dn = file.getParentFile( ); if (!dn.exists()) { dn.mkdirs(); } try { file.createNewFile( ); } catch (IOException e) { throw new HongsException(0x10d0,e); } } try { FileOutputStream fos = null; ObjectOutputStream oos = null; try { fos = new FileOutputStream(file); oos = new ObjectOutputStream(fos ); oos.writeObject(save()); oos.flush(); } finally { if (oos != null) oos.close(); if (fos != null) fos.close(); } } catch (FileNotFoundException ex) { throw new HongsException(0x10d6, ex); } catch (IOException ex) { throw new HongsException(0x10d2, ex); } } /** * * @param obj * @throws io.github.ihongs.HongsException */ protected void load(Object obj) throws HongsException { Map map = ( Map ) obj ; Class clazz = getClass(); Field[] fields; fields = clazz.getFields(); for (Field field : fields) { int ms = field.getModifiers(); if (Modifier.isTransient(ms ) || Modifier.isStatic(ms ) || Modifier.isFinal (ms)) { continue; } String name = field.getName(); try { field.set(this, map.get(name)); } catch (IllegalAccessException e) { throw new HongsException(0x10da, e); } catch (IllegalArgumentException e) { throw new HongsException(0x10da, e); } } fields = clazz.getDeclaredFields(); for (Field field : fields) { int ms = field.getModifiers(); if (Modifier.isTransient(ms ) || Modifier.isPublic(ms ) || Modifier.isStatic(ms ) || Modifier.isFinal (ms)) { continue; } String name = field.getName(); field.setAccessible ( true ); try { field.set(this, map.get(name)); } catch (IllegalAccessException e) { throw new HongsException(0x10da, e); } catch (IllegalArgumentException e) { throw new HongsException(0x10da, e); } } } /** * * @return * @throws io.github.ihongs.HongsException */ protected Object save() throws HongsException { Map map =new HashMap(); Class clazz = getClass(); Field[] fields; fields = clazz.getFields(); for (Field field : fields) { int ms = field.getModifiers(); if (Modifier.isTransient(ms ) || Modifier.isStatic(ms ) || Modifier.isFinal (ms)) { continue; } String name = field.getName(); try { map.put(name, field.get(this)); } catch (IllegalAccessException e) { throw new HongsException(0x10da, e); } catch (IllegalArgumentException e) { throw new HongsException(0x10da, e); } } fields = clazz.getDeclaredFields(); for (Field field : fields) { int ms = field.getModifiers(); if (Modifier.isTransient(ms ) || Modifier.isPublic(ms ) || Modifier.isStatic(ms ) || Modifier.isFinal (ms)) { continue; } String name = field.getName(); field.setAccessible ( true ); try { map.put(name, field.get(this)); } catch (IllegalAccessException e) { throw new HongsException(0x10dc, e); } catch (IllegalArgumentException e) { throw new HongsException(0x10dc, e); } } return map; } }
package org.broadinstitute.sting.utils; /** * QualityUtils is a static class (no instantiation allowed!) with some utility methods for manipulating * quality scores. * * @author Kiran Garimella */ public class QualityUtils { /** * Private constructor. No instantiating this class! */ private QualityUtils() {} /** * Convert a quality score to a probability. This is the Phred-style * conversion, *not* the Illumina-style conversion (though asymptotically, they're the same). * * @param qual a quality score (0-40) * @return a probability (0.0-1.0) */ static public double qualToProb(byte qual) { return 1.0 - Math.pow(10.0, ((double) qual)/-10.0); } /** * Convert a probability to a quality score. Note, this is capped at Q40. * * @param prob a probability (0.0-1.0) * @return a quality score (0-40) */ static public byte probToQual(double prob) { return (byte) Math.round(-10.0*Math.log10(1.0 - prob + 0.0001)); } /** * Compress a base and a probability into a single byte so that it can be output in a SAMRecord's SQ field. * Note: the highest probability this function can encode is 64%, so this function should only never be used on the best base hypothesis. * Another note: the probability encoded here gets rounded to the nearest 1%. * * @param baseIndex the base index * @param prob the base probability * @return a byte containing the index and the probability */ static public byte baseAndProbToCompressedQuality(int baseIndex, double prob) { byte compressedQual = 0; compressedQual = (byte) baseIndex; byte cprob = (byte) (100.0*prob); byte qualmask = (byte) 252; compressedQual += ((cprob << 2) & qualmask); return compressedQual; } /** * From a compressed base, extract the base index (0:A, 1:C, 2:G, 3:T) * * @param compressedQual the compressed quality score, as returned by baseAndProbToCompressedQuality * @return base index */ static public int compressedQualityToBaseIndex(byte compressedQual) { return (int) (compressedQual & 0x3); } /** * From a compressed base, extract the base probability * * @param compressedQual the compressed quality score, as returned by baseAndProbToCompressedQuality * @return the probability */ static public double compressedQualityToProb(byte compressedQual) { // Because java natives are signed, extra care must be taken to avoid // shifting a 1 into the sign bit in the implicit promotion of 2 to an int. int x2 = ((int) compressedQual) & 0xff; x2 = (x2 >>> 2); return ((double) x2)/100.0; } /** * Return the complement of a base index. * * @param baseIndex the base index (0:A, 1:C, 2:G, 3:T) * @return the complementary base index */ static public byte complement(int baseIndex) { switch (baseIndex) { case 0: return 3; // a -> t case 1: return 2; // c -> g case 2: return 1; // g -> c case 3: return 0; // t -> a default: return -1; // wtf? } } /** * Return the complement of a compressed quality * * @param compressedQual the compressed quality score (as returned by baseAndProbToCompressedQuality) * @return the complementary compressed quality */ static public byte complementCompressedQuality(byte compressedQual) { int baseIndex = compressedQualityToBaseIndex(compressedQual); double prob = compressedQualityToProb(compressedQual); return baseAndProbToCompressedQuality(complement(baseIndex), prob); } /** * Return the reverse complement of a byte array of compressed qualities * * @param compressedQuals a byte array of compressed quality scores * @return the reverse complement of the byte array */ static public byte[] reverseComplementCompressedQualityArray(byte[] compressedQuals) { byte[] rcCompressedQuals = new byte[compressedQuals.length]; for (int pos = 0; pos < compressedQuals.length; pos++) { rcCompressedQuals[compressedQuals.length - pos - 1] = complementCompressedQuality(compressedQuals[pos]); } return rcCompressedQuals; } }
package com.bkromhout.minerva; import android.app.Application; import android.content.Context; import com.bkromhout.minerva.data.UniqueIdFactory; import com.bkromhout.minerva.prefs.DefaultPrefs; import com.bkromhout.minerva.realm.RTag; import com.bkromhout.ruqus.Ruqus; import com.google.common.collect.Lists; import com.karumi.dexter.Dexter; import io.realm.Realm; import io.realm.RealmConfiguration; import org.greenrobot.eventbus.EventBus; /** * Custom Application class. */ public class Minerva extends Application { /** * Realm filename. */ private static final String REALM_FILE_NAME = "minerva.realm"; /** * Realm schema version. */ private static final long REALM_SCHEMA_VERSION = 0; /** * Static instance of application context. Beware, this isn't available before the application starts. */ private static Minerva instance; @Override public void onCreate() { super.onCreate(); // Stash application context. instance = this; // Load certain resources into memory for fast access. C.init(this); // Set up EventBus to use the generated index. EventBus.builder().addIndex(new EventBusIndex()).installDefaultEventBus(); // Init Dexter. Dexter.initialize(this); // Do first time init if needed. doFirstTimeInitIfNeeded(); // Set up Realm. setupRealm(); // Initialize UniqueIdFactory. try (Realm realm = Realm.getDefaultInstance()) { UniqueIdFactory.getInstance().initialize(realm); } // Init Ruqus. Ruqus.init(this); } /** * Initializes some default data for the app the first time it runs. */ private void doFirstTimeInitIfNeeded() { if (DefaultPrefs.get().doneFirstTimeInit()) return; // Put default new/updated book tag names. DefaultPrefs.get().putNewBookTag(C.getStr(R.string.default_new_book_tag)); DefaultPrefs.get().putUpdatedBookTag(C.getStr(R.string.default_updated_book_tag)); } /** * Set up Realm's default configuration. */ private void setupRealm() { Realm.setDefaultConfiguration(new RealmConfiguration.Builder(this) .name(REALM_FILE_NAME) .schemaVersion(REALM_SCHEMA_VERSION) .initialData(this::initialRealmData) .build()); } /** * Add initial data to Realm. Only runs on first app run (or after data has been cleared). * @param realm Instance of Realm to use to add data. */ private void initialRealmData(Realm realm) { // Create default tags for new and updated books. realm.copyToRealm(Lists.newArrayList(new RTag(C.getStr(R.string.default_new_book_tag)), new RTag(C.getStr(R.string.default_updated_book_tag)))); } /** * Get the application context. DO NOT use the context returned by this method in methods which affect the UI (such * as when inflating a layout, for example). * @return Application context. */ public static Context getAppCtx() { if (instance == null) throw new IllegalStateException("The application context isn't available yet."); return instance.getApplicationContext(); } }
package com.jady.sample.api; public class UrlConfig { //baseUrl public static final String BASE_URL = "http://123.206.219.27:8080/retrofitclientserver/"; public static final String USER_INFO = "user/info"; public static final String USER_LOGIN = "user/login"; public static final String USER_LOGIN_BY_BODY = "user/loginByBody"; public static final String USER_UPDATE = "user/update"; public static final String FEED_DELETE = "feed/delete"; public static final String SINGLE_FILE_UPLOAD = "file/upload/single"; public static final String MULTIPLE_FILE_UPLOAD = "file/upload/multiple"; public static final String DOUBAN_MOVIE_IN_THEATERS = "https://api.douban.com/v2/movie/in_theaters"; }
package com.quchen.flappycow; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import com.quchen.flappycow.Game.MyHandler; import com.quchen.flappycow.sprites.Background; import com.quchen.flappycow.sprites.Coin; import com.quchen.flappycow.sprites.Cow; import com.quchen.flappycow.sprites.Frontground; import com.quchen.flappycow.sprites.NyanCat; import com.quchen.flappycow.sprites.Obstacle; import com.quchen.flappycow.sprites.PauseButton; import com.quchen.flappycow.sprites.PlayableCharacter; import com.quchen.flappycow.sprites.PowerUp; import com.quchen.flappycow.sprites.Toast; import com.quchen.flappycow.sprites.Tutorial; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.os.Build; import android.os.Message; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import com.google.android.gms.games.Games; public class GameView extends SurfaceView{ /** Milliseconds for game timer tick */ public static final long UPDATE_INTERVAL = 50; // = 20 FPS private Timer timer = new Timer(); private TimerTask timerTask; /** The surfaceholder needed for the canvas drawing */ private SurfaceHolder holder; private Game game; private PlayableCharacter player; private Background background; private Frontground frontground; private List<Obstacle> obstacles = new ArrayList<Obstacle>(); private List<PowerUp> powerUps = new ArrayList<PowerUp>(); private PauseButton pauseButton; volatile private boolean paused = true; private Tutorial tutorial; private boolean tutorialIsShown = true; public GameView(Context context) { super(context); this.game = (Game) context; setFocusable(true); holder = getHolder(); player = new Cow(this, game); background = new Background(this, game); frontground = new Frontground(this, game); pauseButton = new PauseButton(this, game); tutorial = new Tutorial(this, game); } private void startTimer() { setUpTimerTask(); timer = new Timer(); timer.schedule(timerTask, UPDATE_INTERVAL, UPDATE_INTERVAL); } private void stopTimer() { if (timer != null) { timer.cancel(); timer.purge(); } if (timerTask != null) { timerTask.cancel(); } } private void setUpTimerTask() { stopTimer(); timerTask = new TimerTask() { @Override public void run() { GameView.this.run(); } }; } @Override public boolean performClick() { return super.performClick(); // Just to remove the stupid warning } @Override public boolean onTouchEvent(MotionEvent event) { performClick(); if(event.getAction() == MotionEvent.ACTION_DOWN // Only for "touchdowns" && !this.player.isDead()){ // No support for dead players if(tutorialIsShown){ // dismiss tutorial tutorialIsShown = false; resume(); this.player.onTap(); }else if(paused){ resume(); }else if(pauseButton.isTouching((int) event.getX(), (int) event.getY()) && !this.paused){ pause(); }else{ this.player.onTap(); } } return true; } /** * content of the timertask */ public void run() { checkPasses(); checkOutOfRange(); checkCollision(); createObstacle(); move(); draw(); } /** * Draw Tutorial */ public void showTutorial(){ player.move(); pauseButton.move(); while(!holder.getSurface().isValid()){ /*wait*/ try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } Canvas canvas = holder.lockCanvas(); drawCanvas(canvas, true); tutorial.move(); tutorial.draw(canvas); holder.unlockCanvasAndPost(canvas); } public void pause(){ stopTimer(); paused = true; } public void drawOnce(){ (new Thread(new Runnable() { @Override public void run() { if(tutorialIsShown){ showTutorial(); } else { draw(); } } })).start(); } public void resume(){ paused = false; startTimer(); } /** * Draws all gameobjects on the surface */ private void draw() { while(!holder.getSurface().isValid()){ /*wait*/ try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } Canvas canvas; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { canvas = holder.lockHardwareCanvas(); } else { canvas = holder.lockCanvas(); } drawCanvas(canvas, true); holder.unlockCanvasAndPost(canvas); } /** * Draws everything normal, * except the player will only be drawn, when the parameter is true * @param drawPlayer */ private void drawCanvas(Canvas canvas, boolean drawPlayer){ background.draw(canvas); for(Obstacle r : obstacles){ r.draw(canvas); } for(PowerUp p : powerUps){ p.draw(canvas); } if(drawPlayer){ player.draw(canvas); } frontground.draw(canvas); pauseButton.draw(canvas); // Score Text Paint paint = new Paint(); paint.setColor(Color.BLACK); paint.setTextSize(getScoreTextMetrics()); canvas.drawText(game.getResources().getString(R.string.onscreen_score_text) + " " + game.accomplishmentBox.points + " / " + game.getResources().getString(R.string.onscreen_coin_text) + " " + game.coins, 0, getScoreTextMetrics(), paint); } /** * Let the player fall to the ground */ private void playerDeadFall(){ player.dead(); do{ player.move(); draw(); // sleep try { Thread.sleep(UPDATE_INTERVAL/4); } catch (InterruptedException e) { e.printStackTrace(); } }while(!player.isTouchingGround()); } /** * Checks whether an obstacle is passed. */ private void checkPasses(){ for(Obstacle o : obstacles){ if(o.isPassed()){ if(!o.isAlreadyPassed){ // probably not needed o.onPass(); createPowerUp(); } } } } /** * Creates a toast with a certain chance */ private void createPowerUp(){ // Toast if(game.accomplishmentBox.points >= Toast.POINTS_TO_TOAST /*&& powerUps.size() < 1*/ && !(player instanceof NyanCat)){ // If no powerUp is present and you have more than / equal 42 points if(game.accomplishmentBox.points == Toast.POINTS_TO_TOAST){ // First time 100 % chance powerUps.add(new Toast(this, game)); } else if(Math.random()*100 < 33){ // 33% chance powerUps.add(new Toast(this, game)); } } if((powerUps.size() < 1) && (Math.random()*100 < 20)){ // If no powerUp is present and 20% chance powerUps.add(new Coin(this, game)); } } /** * Checks whether the obstacles or powerUps are out of range and deletes them */ private void checkOutOfRange(){ for(int i=0; i<obstacles.size(); i++){ if(this.obstacles.get(i).isOutOfRange()){ this.obstacles.remove(i); i } } for(int i=0; i<powerUps.size(); i++){ if(this.powerUps.get(i).isOutOfRange()){ this.powerUps.remove(i); i } } } /** * Checks collisions and performs the action */ private void checkCollision(){ for(Obstacle o : obstacles){ if(o.isColliding(player)){ o.onCollision(); gameOver(); } } for(int i=0; i<powerUps.size(); i++){ if(this.powerUps.get(i).isColliding(player)){ this.powerUps.get(i).onCollision(); this.powerUps.remove(i); i } } if(player.isTouchingEdge()){ gameOver(); } } /** * if no obstacle is present a new one is created */ private void createObstacle(){ if(obstacles.size() < 1){ obstacles.add(new Obstacle(this, game)); } } /** * Update sprite movements */ private void move(){ for(Obstacle o : obstacles){ o.setSpeedX(-getSpeedX()); o.move(); } for(PowerUp p : powerUps){ p.move(); } background.setSpeedX(-getSpeedX()/2); background.move(); frontground.setSpeedX(-getSpeedX()*4/3); frontground.move(); pauseButton.move(); player.move(); } /** * Changes the player to Nyan Cat */ public void changeToNyanCat(){ game.accomplishmentBox.achievement_toastification = true; if(game.getApiClient().isConnected()){ Games.Achievements.unlock(game.getApiClient(), getResources().getString(R.string.achievement_toastification)); }else{ game.handler.sendMessage(Message.obtain(game.handler,1,R.string.toast_achievement_toastification, MyHandler.SHOW_TOAST)); } PlayableCharacter tmp = this.player; this.player = new NyanCat(this, game); this.player.setX(tmp.getX()); this.player.setY(tmp.getY()); this.player.setSpeedX(tmp.getSpeedX()); this.player.setSpeedY(tmp.getSpeedY()); game.musicShouldPlay = true; Game.musicPlayer.start(); } /** * return the speed of the obstacles/cow */ public int getSpeedX(){ // 16 @ 720x1280 px int speedDefault = this.getWidth() / 45; // 1,2 every 4 points @ 720x1280 px int speedIncrease = (int) (this.getWidth() / 600f * (game.accomplishmentBox.points / 4)); int speed = speedDefault + speedIncrease; return Math.min(speed, 2*speedDefault); } /** * Let's the player fall down dead, makes sure the runcycle stops * and invokes the next method for the dialog and stuff. */ public void gameOver(){ pause(); playerDeadFall(); game.gameOver(); } public void revive() { game.numberOfRevive++; // This needs to run another thread, so the dialog can close. new Thread(new Runnable() { @Override public void run() { setupRevive(); } }).start(); } /** * Sets the player into startposition * Removes obstacles. * Let's the character blink a few times. */ private void setupRevive(){ game.gameOverDialog.hide(); player.setY(this.getHeight()/2 - player.getWidth()/2); player.setX(this.getWidth()/6); obstacles.clear(); powerUps.clear(); player.revive(); for(int i = 0; i < 6; ++i){ while(!holder.getSurface().isValid()){/*wait*/} Canvas canvas = holder.lockCanvas(); drawCanvas(canvas, i%2 == 0); holder.unlockCanvasAndPost(canvas); // sleep try { Thread.sleep(UPDATE_INTERVAL*6); } catch (InterruptedException e) { e.printStackTrace(); } } resume(); } /** * A value for the position and size of the onScreen score Text */ public int getScoreTextMetrics(){ return (int) (this.getHeight() / 21.0f); /*/ game.getResources().getDisplayMetrics().density)*/ } public PlayableCharacter getPlayer(){ return this.player; } public Game getGame(){ return this.game; } }
package me.zq.youjoin.model; import java.util.List; public class TweetInfo { private String result; private List<TweetsEntity> tweets; public void setResult(String result) { this.result = result; } public void setTweets(List<TweetsEntity> tweets) { this.tweets = tweets; } public String getResult() { return result; } public List<TweetsEntity> getTweets() { return tweets; } public static class TweetsEntity { private String friend_id; private String tweets_id; private String comment_num; private String upvote_num; private String upvote_status; private String tweets_content; private String tweets_img; public void setFriend_id(String friend_id) { this.friend_id = friend_id; } public void setTweets_id(String tweets_id) { this.tweets_id = tweets_id; } public void setComment_num(String comment_num) { this.comment_num = comment_num; } public void setUpvote_num(String upvote_num) { this.upvote_num = upvote_num; } public void setUpvote_status(String upvote_status) { this.upvote_status = upvote_status; } public void setTweets_content(String tweets_content) { this.tweets_content = tweets_content; } public void setTweets_img(String tweets_img) { this.tweets_img = tweets_img; } public String getFriend_id() { return friend_id; } public String getTweets_id() { return tweets_id; } public String getComment_num() { return comment_num; } public String getUpvote_num() { return upvote_num; } public String getUpvote_status() { return upvote_status; } public String getTweets_content() { return tweets_content; } public String getTweets_img() { return tweets_img; } } }
package org.wikipedia.edit; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.VisibleForTesting; import org.json.JSONException; import org.json.JSONObject; import org.wikipedia.captcha.CaptchaResult; import org.wikipedia.dataclient.WikiSite; import org.wikipedia.dataclient.retrofit.MwCachedService; import org.wikipedia.json.GsonMarshaller; import org.wikipedia.page.PageTitle; import java.util.concurrent.TimeUnit; import retrofit2.Call; import retrofit2.Response; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.POST; class EditClient { @NonNull private final MwCachedService<Service> cachedService = new MwCachedService<>(Service.class); @SuppressWarnings("checkstyle:parameternumber") public Call<Edit> request(@NonNull WikiSite wiki, @NonNull PageTitle title, int section, @NonNull String text, @NonNull String token, @NonNull String summary, boolean loggedIn, @Nullable String captchaId, @Nullable String captchaWord, @NonNull Callback cb) { Service service = cachedService.service(wiki); return request(service, title, section, text, token, summary, loggedIn, captchaId, captchaWord, cb); } @SuppressWarnings("checkstyle:parameternumber") @VisibleForTesting Call<Edit> request(@NonNull Service service, @NonNull PageTitle title, int section, @NonNull String text, @NonNull String token, @NonNull String summary, boolean loggedIn, @Nullable String captchaId, @Nullable String captchaWord, @NonNull final Callback cb) { Call<Edit> call = service.edit(title.getPrefixedText(), section, text, token, summary, loggedIn ? "user" : null, captchaId, captchaWord); call.enqueue(new retrofit2.Callback<Edit>() { @Override public void onResponse(Call<Edit> call, Response<Edit> response) { if (response.isSuccessful() && response.body().hasEditResult()) { Edit.Result result = response.body().edit(); if ("Success".equals(result.status())) { try { // TODO: get edit revision and request that revision Thread.sleep(TimeUnit.SECONDS.toMillis(2)); cb.success(call, new EditSuccessResult(result.newRevId())); } catch (InterruptedException e) { cb.failure(call, e); } } else if (result.hasErrorCode()) { try { JSONObject json = new JSONObject(GsonMarshaller.marshal(result)); cb.success(call, new EditAbuseFilterResult(json)); } catch (JSONException e) { cb.failure(call, e); } } else if (result.hasSpamBlacklistResponse()) { cb.success(call, new EditSpamBlacklistResult(result.spamblacklist())); } else if (result.hasCaptchaResponse()) { cb.success(call, new CaptchaResult(result.captchaId())); } else { cb.failure(call, new RuntimeException("Received unrecognized edit response")); } } else if ("assertuserfailed".equals(response.body().code())) { cb.failure(call, new UserNotLoggedInException()); } else if (response.body().info() != null) { String info = response.body().info(); cb.failure(call, new RuntimeException(info)); } else { cb.failure(call, new RuntimeException("Received unrecognized edit response")); } } @Override public void onFailure(Call<Edit> call, Throwable t) { cb.failure(call, t); } }); return call; } @VisibleForTesting interface Callback { void success(@NonNull Call<Edit> call, @NonNull EditResult result); void failure(@NonNull Call<Edit> call, @NonNull Throwable caught); } @VisibleForTesting interface Service { @FormUrlEncoded @POST("w/api.php?action=edit&format=json") @SuppressWarnings("checkstyle:parameternumber") Call<Edit> edit(@NonNull @Field("title") String title, @Field("section") int section, @NonNull @Field("text") String text, @NonNull @Field("token") String token, @NonNull @Field("summary") String summary, @Nullable @Field("assert") String user, @Nullable @Field("captchaid") String captchaId, @Nullable @Field("captchaword") String captchaWord); } }
package org.commcare.models.database; import android.database.Cursor; import net.sqlcipher.database.SQLiteDatabase; import net.sqlcipher.database.SQLiteQueryBuilder; import net.sqlcipher.database.SQLiteStatement; import org.commcare.android.logging.ForceCloseLogger; import org.commcare.modern.database.DatabaseHelper; import org.commcare.modern.database.TableBuilder; import org.commcare.modern.models.EncryptedModel; import org.commcare.modern.util.Pair; import org.commcare.util.LogTypes; import org.commcare.utils.SessionUnavailableException; import org.javarosa.core.model.condition.RequestAbandonedException; import org.javarosa.core.services.Logger; import org.javarosa.core.services.storage.EntityFilter; import org.javarosa.core.services.storage.IStorageIterator; import org.javarosa.core.services.storage.IStorageUtilityIndexed; import org.javarosa.core.services.storage.Persistable; import org.javarosa.core.util.InvalidIndexException; import org.javarosa.core.util.externalizable.DeserializationException; import org.javarosa.core.util.externalizable.Externalizable; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.NoSuchElementException; import java.util.Vector; /** * @author ctsims */ public class SqlStorage<T extends Persistable> implements IStorageUtilityIndexed, Iterable<T> { /** * Static flag identifying whether storage optimizations are active. */ public static boolean STORAGE_OPTIMIZATIONS_ACTIVE = true; public static final boolean STORAGE_OUTPUT_DEBUG = false; String table; private final Class<? extends T> ctype; protected final EncryptedModel em; protected final AndroidDbHelper helper; protected SqlStorage() { em = null; helper = null; ctype = null; } public SqlStorage(String table, Class<? extends T> ctype, AndroidDbHelper helper) { this.table = table; this.ctype = ctype; this.helper = helper; T e = null; try { e = ctype.newInstance(); } catch (IllegalAccessException ie) { ie.printStackTrace(); } catch (InstantiationException ie) { ie.printStackTrace(); } if (e != null && e instanceof EncryptedModel) { em = (EncryptedModel)e; } else { em = null; } } @Override public Vector<Integer> getIDsForValue(String fieldName, Object value) { return getIDsForValues(new String[]{fieldName}, new Object[]{value}); } @Override public Vector<Integer> getIDsForValues(String[] fieldNames, Object[] values) { return getIDsForValues(fieldNames, values, null); } @Override public Vector<Integer> getIDsForValues(String[] fieldNames, Object[] values, LinkedHashSet returnSet) { SQLiteDatabase db = helper.getHandle(); Pair<String, String[]> whereClause = helper.createWhereAndroid(fieldNames, values, em, null); return getIDsForValuesInner(db, whereClause, returnSet); } @Override public List<Integer> getIDsForValues(String[] fieldNames, Object[] values, String[] inverseFieldNames, Object[] inverseValues, LinkedHashSet returnSet) { SQLiteDatabase db = helper.getHandle(); Pair<String, String[]> whereClause = DatabaseHelper.createWhere(fieldNames, values, inverseFieldNames, inverseValues, em, null); return getIDsForValuesInner(db, whereClause, returnSet); } private Vector<Integer> getIDsForValuesInner(SQLiteDatabase db, Pair<String, String[]> whereClause, LinkedHashSet returnSet) { if (STORAGE_OUTPUT_DEBUG) { String sql = SQLiteQueryBuilder.buildQueryString(false, table, new String[]{DatabaseHelper.ID_COL}, whereClause.first, null, null, null, null); DbUtil.explainSql(db, sql, whereClause.second); } Cursor c = db.query(table, new String[]{DatabaseHelper.ID_COL}, whereClause.first, whereClause.second, null, null, null); return fillIdWindow(c, DatabaseHelper.ID_COL, returnSet); } public static Vector<Integer> fillIdWindow(Cursor c, String columnName, LinkedHashSet<Integer> newReturn) { Vector<Integer> indices = new Vector<>(); try { if (c.moveToFirst()) { int index = c.getColumnIndexOrThrow(columnName); while (!c.isAfterLast()) { int id = c.getInt(index); if (newReturn != null) { newReturn.add(id); } indices.add(id); c.moveToNext(); } } return indices; } finally { if (c != null) { c.close(); } } } public Vector<T> getRecordsForValue(String fieldName, Object value) { return getRecordsForValues(new String[]{fieldName}, new Object[]{value}); } /** * Return all records from this SqlStorage object for which, for each field in fieldNames, * the record has the correct corresponding value in values */ public Vector<T> getRecordsForValues(String[] fieldNames, Object[] values) { Pair<String, String[]> whereClause = helper.createWhereAndroid(fieldNames, values, em, null); Cursor c = helper.getHandle().query(table, new String[]{DatabaseHelper.ID_COL, DatabaseHelper.DATA_COL}, whereClause.first, whereClause.second, null, null, null); try { if (c.getCount() == 0) { return new Vector<>(); } else { c.moveToFirst(); Vector<T> indices = new Vector<>(); int index = c.getColumnIndexOrThrow(DatabaseHelper.DATA_COL); while (!c.isAfterLast()) { byte[] data = c.getBlob(index); indices.add(newObject(data, c.getInt(c.getColumnIndexOrThrow(DatabaseHelper.ID_COL)))); c.moveToNext(); } return indices; } } finally { c.close(); } } public String getMetaDataFieldForRecord(int recordId, String rawFieldName) { String rid = String.valueOf(recordId); String scrubbedName = TableBuilder.scrubName(rawFieldName); Cursor c = helper.getHandle().query(table, new String[]{scrubbedName}, DatabaseHelper.ID_COL + "=?", new String[]{rid}, null, null, null); try { if (c.getCount() == 0) { throw new NoSuchElementException("No record in table " + table + " for ID " + recordId); } c.moveToFirst(); return c.getString(c.getColumnIndexOrThrow(scrubbedName)); } finally { c.close(); } } @Override public String[] getMetaDataForRecord(int recordId, String[] metaDataNames) { String rid = String.valueOf(recordId); String[] scrubbedNames = scrubMetadataNames(metaDataNames); String[] projection = getProjectedFieldsWithId(false, scrubbedNames); Cursor c = helper.getHandle().query(table, projection, DatabaseHelper.ID_COL + "=?", new String[]{rid}, null, null, null); try { if (c.getCount() == 0) { throw new NoSuchElementException("No record in table " + table + " for ID " + recordId); } c.moveToFirst(); return readMetaDataFromCursor(c, scrubbedNames); } finally { c.close(); } } public T getRecordForValues(String[] rawFieldNames, Object[] values) throws NoSuchElementException, InvalidIndexException { SQLiteDatabase appDb = helper.getHandle(); Pair<String, String[]> whereClause = helper.createWhereAndroid(rawFieldNames, values, em, null); Cursor c = appDb.query(table, new String[]{DatabaseHelper.ID_COL, DatabaseHelper.DATA_COL}, whereClause.first, whereClause.second, null, null, null); try { int queryCount = c.getCount(); if (queryCount == 0) { throw new NoSuchElementException("No element in table " + table + " with names " + Arrays.toString(rawFieldNames) + " and values " + Arrays.toString(values)); } else if (queryCount > 1) { throw new InvalidIndexException("Invalid unique column set" + Arrays.toString(rawFieldNames) + ". Multiple records found with value " + Arrays.toString(values), Arrays.toString(rawFieldNames)); } c.moveToFirst(); byte[] data = c.getBlob(c.getColumnIndexOrThrow(DatabaseHelper.DATA_COL)); return newObject(data, c.getInt(c.getColumnIndexOrThrow(DatabaseHelper.ID_COL))); } finally { c.close(); } } @Override public T getRecordForValue(String rawFieldName, Object value) throws NoSuchElementException, InvalidIndexException { return getRecordForValues(new String[]{rawFieldName}, new Object[]{value}); } /** * @param dbEntryId Set the deserialized persistable's id to the database entry id. * Doing so now is more effecient then during writes */ public T newObject(InputStream serializedObjectInputStream, int dbEntryId) { try { T e = ctype.newInstance(); e.readExternal(new DataInputStream(serializedObjectInputStream), helper.getPrototypeFactory()); e.setID(dbEntryId); return e; } catch (IllegalAccessException e) { throw logAndWrap(e, "Illegal Access Exception"); } catch (InstantiationException e) { throw logAndWrap(e, "Instantiation Exception"); } catch (IOException e) { throw logAndWrap(e, "Totally non-sensical IO Exception"); } catch (DeserializationException e) { throw logAndWrap(e, "CommCare ran into an issue deserializing data"); } } /** * @param dbEntryId Set the deserialized persistable's id to the database entry id. * Doing so now is more effecient then during writes */ public T newObject(byte[] serializedObjectAsBytes, int dbEntryId) { return newObject(new ByteArrayInputStream(serializedObjectAsBytes), dbEntryId); } private RuntimeException logAndWrap(Exception e, String message) { RuntimeException re = new RuntimeException(message + " while inflating type " + ctype.getName()); re.initCause(e); Logger.log(LogTypes.TYPE_ERROR_STORAGE, "Error while inflating type " + ctype.getName() + ": " + ForceCloseLogger.getStackTraceWithContext(re)); return re; } @Override public int add(Externalizable e) { SQLiteDatabase db; db = helper.getHandle(); int i = -1; db.beginTransaction(); try { long ret = db.insertOrThrow(table, DatabaseHelper.DATA_COL, helper.getContentValues(e)); if (ret > Integer.MAX_VALUE) { throw new RuntimeException("Waaaaaaaaaay too many values"); } i = (int)ret; db.setTransactionSuccessful(); } finally { db.endTransaction(); } return i; } @Override public void close() { try { helper.getHandle().close(); } catch (SessionUnavailableException e) { // The db isn't available so don't worry about closing it. } } @Override public boolean exists(int id) { Cursor c = helper.getHandle().query(table, new String[]{DatabaseHelper.ID_COL}, DatabaseHelper.ID_COL + "= ? ", new String[]{String.valueOf(id)}, null, null, null); try { int queryCount = c.getCount(); if (queryCount == 0) { return false; } else if (queryCount > 1) { throw new InvalidIndexException("Invalid ID column. Multiple records found with value " + id, "ID"); } } finally { c.close(); } return true; } @Override public SQLiteDatabase getAccessLock() { return helper.getHandle(); } @Override public int getNumRecords() { Cursor c = helper.getHandle().query(table, new String[]{DatabaseHelper.ID_COL}, null, null, null, null, null); try { int records = c.getCount(); return records; } finally { c.close(); } } @Override public boolean isEmpty() { return (getNumRecords() == 0); } @Override public SqlStorageIterator<T> iterate() { return iterate(true); } /** * Creates a custom iterator for this storage which can either include or exclude the actual data. * Useful for getting an overview of data for querying into without wasting the bits to transfer over * the huge full records. * * @param includeData True to return an iterator with all records. False to return only the index. */ @Override public SqlStorageIterator<T> iterate(boolean includeData) { SQLiteDatabase db = helper.getHandle(); SqlStorageIterator<T> spanningIterator = getIndexSpanningIteratorOrNull(db, includeData); if (spanningIterator != null) { return spanningIterator; } else { return new SqlStorageIterator<>(getIterateCursor(db, includeData), this); } } protected SqlStorageIterator<T> getIndexSpanningIteratorOrNull(SQLiteDatabase db, boolean includeData) { //If we're just iterating over ID's, we may want to use a different, much //faster method depending on our stats. This method retrieves the //index records that _don't_ exist so we can assume the spans that if (!includeData && STORAGE_OPTIMIZATIONS_ACTIVE) { SQLiteStatement min = db.compileStatement("SELECT MIN(" + DatabaseHelper.ID_COL + ") from " + table); SQLiteStatement max = db.compileStatement("SELECT MAX(" + DatabaseHelper.ID_COL + ") from " + table); SQLiteStatement count = db.compileStatement("SELECT COUNT(" + DatabaseHelper.ID_COL + ") from " + table); int minValue = (int)min.simpleQueryForLong(); int maxValue = (int)max.simpleQueryForLong() + 1; int countValue = (int)count.simpleQueryForLong(); min.close(); max.close(); count.close(); double density = countValue / (maxValue - minValue * 1.0); //Ok, so basic metrics: //1) Only use a covering iterator if the number of records is > 1k //2) Only use a covering iterator if the number of records is less than 100k (vital, hard limit) //3) Only use a covering iterator if the record density is 50% or more if (countValue > 1000 && countValue < 100000 && density >= 0.5) { return getCoveringIndexIterator(db, minValue, maxValue, countValue); } } return null; } protected Cursor getIterateCursor(SQLiteDatabase db, boolean includeData) { String[] projection = includeData ? new String[]{DatabaseHelper.ID_COL, DatabaseHelper.DATA_COL} : new String[]{DatabaseHelper.ID_COL}; return db.query(table, projection, null, null, null, null, null); } /** * Creates a custom iterator for this storage which can either include or exclude the actual data, and * additionally collects a primary ID that will be returned and available during iteration. * * Useful for situations where the iterator is loading data that will be indexed by the primary id * since it will prevent the need to turn that primary id into the storage key for retrieving each * record. * * TODO: This is a bit too close to comfort to the other custom iterator. It's possible we should just * have a method to query for all metadata? * * @param includeData True to return an iterator with all records. False to return only the index. * @param metaDataToInclude A set of metadata keys that should be included in the request, * independently of any other data. */ public SqlStorageIterator<T> iterate(boolean includeData, String[] metaDataToInclude) { String[] projection = getProjectedFieldsWithId(includeData, scrubMetadataNames(metaDataToInclude)); Cursor c = helper.getHandle().query(table, projection, null, null, null, null, DatabaseHelper.ID_COL); return new SqlStorageIterator<>(c, this, metaDataToInclude); } private String[] scrubMetadataNames(String[] metaDataNames) { String[] scrubbedNames = new String[metaDataNames.length]; for (int i = 0; i < metaDataNames.length; ++i) { scrubbedNames[i] = TableBuilder.scrubName(metaDataNames[i]); } return scrubbedNames; } private String[] getProjectedFieldsWithId(boolean includeData, String[] columnNamesToInclude) { String[] projection = new String[columnNamesToInclude.length + (includeData ? 2 : 1)]; int firstIndex = 0; projection[firstIndex] = DatabaseHelper.ID_COL; firstIndex++; if (includeData) { projection[firstIndex] = DatabaseHelper.DATA_COL; firstIndex++; } for (int i = 0; i < columnNamesToInclude.length; ++i) { projection[i + firstIndex] = columnNamesToInclude[i]; } return projection; } @Override public Iterator<T> iterator() { return iterate(); } @Override public T read(int id) { return newObject(readBytes(id), id); } @Override public byte[] readBytes(int id) { Cursor c = helper.getHandle().query(table, new String[]{DatabaseHelper.ID_COL, DatabaseHelper.DATA_COL}, DatabaseHelper.ID_COL + "=?", new String[]{String.valueOf(id)}, null, null, null); try { if (!c.moveToFirst()) { throw new NoSuchElementException("No record in table " + table + " for ID " + id); } return c.getBlob(c.getColumnIndexOrThrow(DatabaseHelper.DATA_COL)); } finally { c.close(); } } @Override public void remove(int id) { SQLiteDatabase db = helper.getHandle(); db.beginTransaction(); try { db.delete(table, DatabaseHelper.ID_COL + "=?", new String[]{String.valueOf(id)}); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } public void remove(List<Integer> ids) { if (ids.size() == 0) { return; } SQLiteDatabase db = helper.getHandle(); db.beginTransaction(); try { List<Pair<String, String[]>> whereParamList = TableBuilder.sqlList(ids); for (Pair<String, String[]> whereParams : whereParamList) { db.delete(table, DatabaseHelper.ID_COL + " IN " + whereParams.first, whereParams.second); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } } @Override public void remove(Persistable p) { this.remove(p.getID()); } @Override public void removeAll() { wipeTable(helper.getHandle(), table); } public static void wipeTableWithoutCommit(SQLiteDatabase db, String table) { db.delete(table, null, null); } public static void wipeTable(SQLiteDatabase db, String table) { db.beginTransaction(); try { if (isTableExist(db, table)) { db.delete(table, null, null); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } } private static boolean isTableExist(SQLiteDatabase db, String table) { Cursor cursor = db.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '" + table + "'", null); if (cursor != null) { if (cursor.getCount() > 0) { cursor.close(); return true; } cursor.close(); } return false; } public Vector<Integer> removeAll(Vector<Integer> toRemove) { if (toRemove.size() == 0) { return toRemove; } List<Pair<String, String[]>> whereParamList = TableBuilder.sqlList(toRemove); SQLiteDatabase db = helper.getHandle(); db.beginTransaction(); try { for (Pair<String, String[]> whereParams : whereParamList) { db.delete(table, DatabaseHelper.ID_COL + " IN " + whereParams.first, whereParams.second); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } return toRemove; } @Override public Vector<Integer> removeAll(EntityFilter ef) { Vector<Integer> removed = new Vector<>(); for (IStorageIterator iterator = this.iterate(); iterator.hasMore(); ) { int id = iterator.nextID(); switch (ef.preFilter(id, null)) { case EntityFilter.PREFILTER_INCLUDE: removed.add(id); continue; case EntityFilter.PREFILTER_EXCLUDE: continue; case EntityFilter.PREFILTER_FILTER: if (ef.matches(read(id))) { removed.add(id); } } } return removeAll(removed); } @Override public void update(int id, Externalizable e) { SQLiteDatabase db = helper.getHandle(); db.beginTransaction(); try { db.update(table, helper.getContentValues(e), DatabaseHelper.ID_COL + "=?", new String[]{String.valueOf(id)}); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } @Override public void write(Persistable p) { if (p.getID() != -1) { update(p.getID(), p); return; } SQLiteDatabase db = helper.getHandle(); db.beginTransaction(); try { long ret = db.insertOrThrow(table, DatabaseHelper.DATA_COL, helper.getContentValues(p)); if (ret > Integer.MAX_VALUE) { throw new RuntimeException("Waaaaaaaaaay too many values"); } // won't effect already stored obj id, which is set when reading out of db. // rather, needed in case persistable object is used after being written to storage. p.setID((int)ret); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } /** * @return An iterator which can provide a list of all of the indices in this table. */ private SqlStorageIterator<T> getCoveringIndexIterator(SQLiteDatabase db, int minValue, int maxValue, int countValue) { //So here's what we're doing: //Build a select statement that has all of the numbers from 1 to 100k //Filter it to contain our real boundaries //Select all id's from our table's index //Except those ids from the virtual table //This returns what is essentially a set of spans from min -> max where ID's do _not_ //exist in this table. String vals = "select 10000 * tenthousands.i + 1000 * thousands.i + 100*hundreds.i + 10*tens.i + units.i as " + DatabaseHelper.ID_COL + " from integers tenthousands " + ", integers thousands " + ", integers hundreds " + ", integers tens " + ", integers units " + " WHERE " + DatabaseHelper.ID_COL + " >= CAST(? AS INTEGER) AND " + DatabaseHelper.ID_COL + " <= CAST(? AS INTEGER)"; String[] args = new String[]{String.valueOf(minValue), String.valueOf(maxValue)}; String stmt = vals + " EXCEPT SELECT " + DatabaseHelper.ID_COL + " FROM " + table; Cursor c = db.rawQuery(stmt, args); //Return a covering iterator return new IndexSpanningIterator<>(c, this, minValue, maxValue, countValue); } @Override public void bulkRead(LinkedHashSet cuedCases, HashMap recordMap) throws RequestAbandonedException { List<Pair<String, String[]>> whereParamList = TableBuilder.sqlList(cuedCases); for (Pair<String, String[]> querySet : whereParamList) { Cursor c = helper.getHandle().query(table, new String[]{DatabaseHelper.ID_COL, DatabaseHelper.DATA_COL}, DatabaseHelper.ID_COL + " IN " + querySet.first, querySet.second, null, null, null); try { if (c.getCount() == 0) { return; } else { c.moveToFirst(); int index = c.getColumnIndexOrThrow(DatabaseHelper.DATA_COL); while (!c.isAfterLast()) { if (Thread.interrupted()) { throw new RequestAbandonedException(); } byte[] data = c.getBlob(index); recordMap.put(c.getInt(c.getColumnIndexOrThrow(DatabaseHelper.ID_COL)), newObject(data, c.getInt(c.getColumnIndexOrThrow(DatabaseHelper.ID_COL)))); c.moveToNext(); } } } finally { c.close(); } } } @Override public void bulkReadMetadata(LinkedHashSet cuedCases, String[] metaDataIds, HashMap metadataMap) { List<Pair<String, String[]>> whereParamList = TableBuilder.sqlList(cuedCases); String[] scrubbedNames = scrubMetadataNames(metaDataIds); String[] projection = getProjectedFieldsWithId(false, scrubbedNames); for (Pair<String, String[]> querySet : whereParamList) { Cursor c = helper.getHandle().query(table, projection, DatabaseHelper.ID_COL + " IN " + querySet.first, querySet.second, null, null, null); try { if (c.getCount() == 0) { return; } else { c.moveToFirst(); int idIndex = c.getColumnIndexOrThrow(DatabaseHelper.ID_COL); while (!c.isAfterLast()) { String[] metaRead = readMetaDataFromCursor(c, scrubbedNames); metadataMap.put(c.getInt(idIndex), metaRead); c.moveToNext(); } } } finally { c.close(); } } } /** * Reads out the metadata columns from the provided cursor. * * NOTE: The column names _must be scrubbed here_ before the method is called */ private String[] readMetaDataFromCursor(Cursor c, String[] columnNames) { String[] results = new String[columnNames.length]; int i = 0; for (String columnName : columnNames) { results[i] = c.getString(c.getColumnIndexOrThrow(columnName)); i++; } return results; } /** * Retrieves a set of the models in storage based on a list of values matching one of the * indexes of this storage */ public List<T> getBulkRecordsForIndex(String indexName, Collection<String> matchingValues) { List<T> returnSet = new ArrayList<>(); String fieldName = TableBuilder.scrubName(indexName); List<Pair<String, String[]>> whereParamList = TableBuilder.sqlList(matchingValues, "?"); for (Pair<String, String[]> querySet : whereParamList) { Cursor c = helper.getHandle().query(table, new String[]{DatabaseHelper.ID_COL, DatabaseHelper.DATA_COL, fieldName}, fieldName + " IN " + querySet.first, querySet.second, null, null, null); try { if (c.getCount() == 0) { return returnSet; } else { c.moveToFirst(); int index = c.getColumnIndexOrThrow(DatabaseHelper.DATA_COL); while (!c.isAfterLast()) { byte[] data = c.getBlob(index); returnSet.add(newObject(data, c.getInt(c.getColumnIndexOrThrow(DatabaseHelper.ID_COL)))); c.moveToNext(); } } } finally { c.close(); } } return returnSet; } }
package com.thaiopensource.xml.dtd; import java.util.Hashtable; import java.util.Vector; import java.util.Enumeration; class DtdBuilder { private Vector atoms; private Vector decls = new Vector(); private Hashtable paramEntityTable = new Hashtable(); DtdBuilder(Vector atoms) { this.atoms = atoms; } Vector getDecls() { return decls; } Entity lookupParamEntity(String name) { return (Entity)paramEntityTable.get(name); } Entity createParamEntity(String name) { Entity e = (Entity)paramEntityTable.get(name); if (e != null) return null; e = new Entity(name); paramEntityTable.put(name, e); return e; } void unexpandEntities() { for (Enumeration e = paramEntityTable.elements(); e.hasMoreElements();) ((Entity)e.nextElement()).unexpandEntities(); } void createDecls() { new AtomParser(new AtomStream(atoms), new PrologParser(PrologParser.EXTERNAL_ENTITY), decls).parse(); } void analyzeSemantics() { for (Enumeration e = paramEntityTable.elements(); e.hasMoreElements();) ((Entity)e.nextElement()).analyzeSemantic(); } Vector createTopLevel() { Vector v = new Vector(); int n = decls.size(); for (int i = 0; i < n; i++) { TopLevel t = ((Decl)decls.elementAt(i)).createTopLevel(); if (t != null) v.addElement(t); } return v; } void dump() { dumpEntity("#doc", atoms); } private static void dumpEntity(String name, Vector atoms) { System.out.println("<e name=\"" + name + "\">"); dumpAtoms(atoms); System.out.println("</e>"); } private static void dumpAtoms(Vector v) { int n = v.size(); for (int i = 0; i < n; i++) { Atom a = (Atom)v.elementAt(i); Entity e = a.getEntity(); if (e != null) dumpEntity(e.name, e.atoms); else if (a.getTokenType() != Tokenizer.TOK_PROLOG_S) { System.out.print("<t>"); dumpString(a.getToken()); System.out.println("</t>"); } } } private static void dumpString(String s) { int n = s.length(); for (int i = 0; i < n; i++) switch (s.charAt(i)) { case '<': System.out.print("&lt;"); break; case '>': System.out.print("&gt;"); break; case '&': System.out.print("&amp;"); break; default: System.out.print(s.charAt(i)); break; } } }
package weapons; import java.awt.Image; import javax.swing.ImageIcon; public class Weapon { private boolean isMurderWeapon; private Image weaponPicture; public Weapon() { isMurderWeapon = false; weaponPicture = null; } public void makeMurderWeapon() { isMurderWeapon = true; } public void switchMurderWeapon() { if(isMurderWeapon) { isMurderWeapon = false; } else isMurderWeapon = true; } public void setWeaponPicture(Image weapPic) { weaponPicture = weapPic; } public boolean getIsMurderWeapon() { return isMurderWeapon; } public Image getWeaponPicture() { return weaponPicture; } }
package org.sirix.node; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.common.hash.HashFunction; import org.brackit.xquery.atomic.Atomic; import org.brackit.xquery.atomic.QNm; import org.brackit.xquery.module.Namespaces; import org.brackit.xquery.xdm.Type; import org.sirix.access.ResourceConfiguration; import org.sirix.access.trx.node.HashType; import org.sirix.api.PageReadOnlyTrx; import org.sirix.index.AtomicUtil; import org.sirix.index.avltree.AVLNode; import org.sirix.index.avltree.keyvalue.CASValue; import org.sirix.index.avltree.keyvalue.NodeReferences; import org.sirix.index.path.summary.PathNode; import org.sirix.node.delegates.NameNodeDelegate; import org.sirix.node.delegates.NodeDelegate; import org.sirix.node.delegates.StructNodeDelegate; import org.sirix.node.delegates.ValueNodeDelegate; import org.sirix.node.interfaces.DataRecord; import org.sirix.node.interfaces.NodePersistenter; import org.sirix.node.json.NullNode; import org.sirix.node.json.*; import org.sirix.node.xml.*; import org.sirix.page.UnorderedKeyValuePage; import org.sirix.service.xml.xpath.AtomicValue; import org.sirix.settings.Constants; import org.sirix.settings.Fixed; import javax.annotation.Nonnegative; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.ByteBuffer; import java.util.*; import static org.sirix.node.Utils.getVarLong; import static org.sirix.node.Utils.putVarLong; /** * Enumeration for different nodes. All nodes are determined by a unique id. * * @author Sebastian Graf, University of Konstanz * @author Johannes Lichtenberger, University of Konstanz */ public enum NodeKind implements NodePersistenter { /** * Node kind is element. */ ELEMENT((byte) 1, ElementNode.class) { @Override public DataRecord deserialize(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID deweyID, final PageReadOnlyTrx pageReadTrx) throws IOException { final BigInteger hashCode = getHash(source, pageReadTrx); // Node delegate. final NodeDelegate nodeDel = deserializeNodeDelegate(source, recordID, deweyID, pageReadTrx); // Struct delegate. final StructNodeDelegate structDel = deserializeStructDel(this, nodeDel, source, pageReadTrx.getResourceManager().getResourceConfig()); // Name delegate. final NameNodeDelegate nameDel = deserializeNameDelegate(nodeDel, source); // Attributes. final int attrCount = source.readInt(); final List<Long> attrKeys = new ArrayList<>(attrCount); final BiMap<Long, Long> attrs = HashBiMap.create(); for (int i = 0; i < attrCount; i++) { final long nodeKey = source.readLong(); attrKeys.add(nodeKey); attrs.put(source.readLong(), nodeKey); } // Namespaces. final int nsCount = source.readInt(); final List<Long> namespKeys = new ArrayList<>(nsCount); for (int i = 0; i < nsCount; i++) { namespKeys.add(source.readLong()); } final String uri = pageReadTrx.getName(nameDel.getURIKey(), NodeKind.NAMESPACE); final int prefixKey = nameDel.getPrefixKey(); final String prefix = prefixKey == -1 ? "" : pageReadTrx.getName(prefixKey, NodeKind.ELEMENT); final int localNameKey = nameDel.getLocalNameKey(); final String localName = localNameKey == -1 ? "" : pageReadTrx.getName(localNameKey, NodeKind.ELEMENT); return new ElementNode(hashCode, structDel, nameDel, attrKeys, attrs, namespKeys, new QNm(uri, prefix, localName)); } @Override public void serialize(final DataOutput sink, final DataRecord record, final PageReadOnlyTrx pageReadTrx) throws IOException { final ElementNode node = (ElementNode) record; if (pageReadTrx.getResourceManager().getResourceConfig().hashType != HashType.NONE) writeHash(sink, node.getHash() == null ? BigInteger.ZERO : node.getHash()); serializeDelegate(node.getNodeDelegate(), sink); serializeStructDelegate(this, node.getStructNodeDelegate(), sink, pageReadTrx.getResourceManager().getResourceConfig()); serializeNameDelegate(node.getNameNodeDelegate(), sink); sink.writeInt(node.getAttributeCount()); for (int i = 0, attCount = node.getAttributeCount(); i < attCount; i++) { final long key = node.getAttributeKey(i); sink.writeLong(key); sink.writeLong(node.getAttributeNameKey(key).get()); } sink.writeInt(node.getNamespaceCount()); for (int i = 0, nspCount = node.getNamespaceCount(); i < nspCount; i++) { sink.writeLong(node.getNamespaceKey(i)); } } }, /** * Node kind is attribute. */ ATTRIBUTE((byte) 2, AttributeNode.class) { @Override public DataRecord deserialize(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID deweyID, final PageReadOnlyTrx pageReadTrx) throws IOException { final BigInteger hashCode = getHash(source, pageReadTrx); // Node delegate. final NodeDelegate nodeDel = deserializeNodeDelegate(source, recordID, deweyID, pageReadTrx); // Name delegate. final NameNodeDelegate nameDel = deserializeNameDelegate(nodeDel, source); // Val delegate. final boolean isCompressed = source.readByte() == (byte) 1; final byte[] vals = new byte[source.readInt()]; source.readFully(vals, 0, vals.length); final ValueNodeDelegate valDel = new ValueNodeDelegate(nodeDel, vals, isCompressed); final String uri = pageReadTrx.getName(nameDel.getURIKey(), NodeKind.NAMESPACE); final int prefixKey = nameDel.getPrefixKey(); final String prefix = prefixKey == -1 ? "" : pageReadTrx.getName(prefixKey, NodeKind.ATTRIBUTE); final int localNameKey = nameDel.getLocalNameKey(); final String localName = localNameKey == -1 ? "" : pageReadTrx.getName(localNameKey, NodeKind.ATTRIBUTE); final QNm name = new QNm(uri, prefix, localName); // Returning an instance. return new AttributeNode(hashCode, nodeDel, nameDel, valDel, name); } @Override public void serialize(final DataOutput sink, final DataRecord record, final PageReadOnlyTrx pageReadTrx) throws IOException { final AttributeNode node = (AttributeNode) record; if (pageReadTrx.getResourceManager().getResourceConfig().hashType != HashType.NONE) writeHash(sink, node.getHash() == null ? BigInteger.ZERO : node.getHash()); serializeDelegate(node.getNodeDelegate(), sink); serializeNameDelegate(node.getNameNodeDelegate(), sink); serializeValDelegate(node.getValNodeDelegate(), sink); } }, /** * Node kind is namespace. */ NAMESPACE((byte) 13, NamespaceNode.class) { @Override public DataRecord deserialize(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID deweyID, final PageReadOnlyTrx pageReadTrx) throws IOException { final BigInteger hashCode = getHash(source, pageReadTrx); // Node delegate. final NodeDelegate nodeDel = deserializeNodeDelegate(source, recordID, deweyID, pageReadTrx); // Name delegate. final NameNodeDelegate nameDel = deserializeNameDelegate(nodeDel, source); final String uri = pageReadTrx.getName(nameDel.getURIKey(), NodeKind.NAMESPACE); final int prefixKey = nameDel.getPrefixKey(); final String prefix = prefixKey == -1 ? "" : pageReadTrx.getName(prefixKey, NodeKind.ELEMENT); final int localNameKey = nameDel.getLocalNameKey(); final String localName = localNameKey == -1 ? "" : pageReadTrx.getName(localNameKey, NodeKind.ELEMENT); final QNm name = new QNm(uri, prefix, localName); return new NamespaceNode(hashCode, nodeDel, nameDel, name); } @Override public void serialize(final DataOutput sink, final DataRecord record, final PageReadOnlyTrx pageReadTrx) throws IOException { final NamespaceNode node = (NamespaceNode) record; if (pageReadTrx.getResourceManager().getResourceConfig().hashType != HashType.NONE) writeHash(sink, node.getHash() == null ? BigInteger.ZERO : node.getHash()); serializeDelegate(node.getNodeDelegate(), sink); serializeNameDelegate(node.getNameNodeDelegate(), sink); } }, /** * Node kind is text. */ TEXT((byte) 3, TextNode.class) { @Override public DataRecord deserialize(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID deweyID, final PageReadOnlyTrx pageReadTrx) throws IOException { final BigInteger hashCode = getHash(source, pageReadTrx); // Node delegate. final NodeDelegate nodeDel = deserializeNodeDelegate(source, recordID, deweyID, pageReadTrx); // Val delegate. final boolean isCompressed = source.readByte() == (byte) 1; final byte[] vals = new byte[source.readInt()]; source.readFully(vals, 0, vals.length); final ValueNodeDelegate valDel = new ValueNodeDelegate(nodeDel, vals, isCompressed); // Struct delegate. final long nodeKey = nodeDel.getNodeKey(); final StructNodeDelegate structDel = new StructNodeDelegate(nodeDel, Fixed.NULL_NODE_KEY.getStandardProperty(), nodeKey - getVarLong(source), nodeKey - getVarLong(source), 0L, 0L); // Returning an instance. return new TextNode(hashCode, valDel, structDel); } @Override public void serialize(final DataOutput sink, final DataRecord record, final PageReadOnlyTrx pageReadTrx) throws IOException { final TextNode node = (TextNode) record; if (pageReadTrx.getResourceManager().getResourceConfig().hashType != HashType.NONE) writeHash(sink, node.getHash() == null ? BigInteger.ZERO : node.getHash()); serializeDelegate(node.getNodeDelegate(), sink); serializeValDelegate(node.getValNodeDelegate(), sink); final StructNodeDelegate del = node.getStructNodeDelegate(); final long nodeKey = node.getNodeKey(); putVarLong(sink, nodeKey - del.getRightSiblingKey()); putVarLong(sink, nodeKey - del.getLeftSiblingKey()); } }, /** * Node kind is processing instruction. */ PROCESSING_INSTRUCTION((byte) 7, PINode.class) { @Override public DataRecord deserialize(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID deweyID, final PageReadOnlyTrx pageReadTrx) throws IOException { final BigInteger hashCode = getHash(source, pageReadTrx); // Node delegate. final NodeDelegate nodeDel = deserializeNodeDelegate(source, recordID, deweyID, pageReadTrx); // Struct delegate. final StructNodeDelegate structDel = deserializeStructDel(this, nodeDel, source, pageReadTrx.getResourceManager().getResourceConfig()); // Name delegate. final NameNodeDelegate nameDel = deserializeNameDelegate(nodeDel, source); // Val delegate. final boolean isCompressed = source.readByte() == (byte) 1; final byte[] vals = new byte[source.readInt()]; source.readFully(vals, 0, vals.length); final ValueNodeDelegate valDel = new ValueNodeDelegate(nodeDel, vals, isCompressed); // Returning an instance. return new PINode(hashCode, structDel, nameDel, valDel, pageReadTrx); } @Override public void serialize(final DataOutput sink, final DataRecord record, final PageReadOnlyTrx pageReadTrx) throws IOException { final PINode node = (PINode) record; if (pageReadTrx.getResourceManager().getResourceConfig().hashType != HashType.NONE) writeHash(sink, node.getHash() == null ? BigInteger.ZERO : node.getHash()); serializeDelegate(node.getNodeDelegate(), sink); serializeStructDelegate(this, node.getStructNodeDelegate(), sink, pageReadTrx.getResourceManager().getResourceConfig()); serializeNameDelegate(node.getNameNodeDelegate(), sink); serializeValDelegate(node.getValNodeDelegate(), sink); } }, /** * Node kind is comment. */ COMMENT((byte) 8, CommentNode.class) { @Override public DataRecord deserialize(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID deweyID, final PageReadOnlyTrx pageReadTrx) throws IOException { final BigInteger hashCode = getHash(source, pageReadTrx); // Node delegate. final NodeDelegate nodeDel = deserializeNodeDelegate(source, recordID, deweyID, pageReadTrx); // Val delegate. final boolean isCompressed = source.readByte() == (byte) 1; final byte[] vals = new byte[source.readInt()]; source.readFully(vals, 0, vals.length); final ValueNodeDelegate valDel = new ValueNodeDelegate(nodeDel, vals, isCompressed); // Struct delegate. final long nodeKey = nodeDel.getNodeKey(); final StructNodeDelegate structDel = new StructNodeDelegate(nodeDel, Fixed.NULL_NODE_KEY.getStandardProperty(), nodeKey - getVarLong(source), nodeKey - getVarLong(source), 0L, 0L); // Returning an instance. return new CommentNode(hashCode, valDel, structDel); } @Override public void serialize(final DataOutput sink, final DataRecord record, final PageReadOnlyTrx pageReadTrx) throws IOException { final CommentNode node = (CommentNode) record; if (pageReadTrx.getResourceManager().getResourceConfig().hashType != HashType.NONE) writeHash(sink, node.getHash() == null ? BigInteger.ZERO : node.getHash()); serializeDelegate(node.getNodeDelegate(), sink); serializeValDelegate(node.getValNodeDelegate(), sink); final StructNodeDelegate del = node.getStructNodeDelegate(); final long nodeKey = node.getNodeKey(); putVarLong(sink, nodeKey - del.getRightSiblingKey()); putVarLong(sink, nodeKey - del.getLeftSiblingKey()); } }, /** * Node kind is document root. */ // Virtualize document root node? XML_DOCUMENT((byte) 9, XmlDocumentRootNode.class) { @Override public DataRecord deserialize(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID deweyID, final PageReadOnlyTrx pageReadTrx) throws IOException { final HashFunction hashFunction = pageReadTrx.getResourceManager().getResourceConfig().nodeHashFunction; final NodeDelegate nodeDel = new NodeDelegate(Fixed.DOCUMENT_NODE_KEY.getStandardProperty(), Fixed.NULL_NODE_KEY.getStandardProperty(), hashFunction, null, getVarLong(source), SirixDeweyID.newRootID()); final StructNodeDelegate structDel = new StructNodeDelegate(nodeDel, getVarLong(source), Fixed.NULL_NODE_KEY.getStandardProperty(), Fixed.NULL_NODE_KEY.getStandardProperty(), source.readByte() == ((byte) 0) ? 0 : 1, source.readLong()); return new XmlDocumentRootNode(nodeDel, structDel); } @Override public void serialize(final DataOutput sink, final DataRecord record, final PageReadOnlyTrx pageReadTrx) throws IOException { final XmlDocumentRootNode node = (XmlDocumentRootNode) record; // writeHash(sink, node.getHash()); putVarLong(sink, node.getRevision()); putVarLong(sink, node.getFirstChildKey()); sink.writeByte(node.hasFirstChild() ? (byte) 1 : (byte) 0); sink.writeLong(node.getDescendantCount()); } @Override public SirixDeweyID deserializeDeweyID(DataInput source, SirixDeweyID previousDeweyID, ResourceConfiguration resourceConfig) throws IOException { return null; } @Override public void serializeDeweyID(DataOutput sink, NodeKind nodeKind, SirixDeweyID deweyID, SirixDeweyID prevDeweyID, ResourceConfiguration resourceConfig) throws IOException { } }, /** * Whitespace text. */ WHITESPACE((byte) 4, null) { @Override public DataRecord deserialize(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID deweyID, final PageReadOnlyTrx pageReadTrx) throws IOException { throw new UnsupportedOperationException(); } @Override public void serialize(final DataOutput sink, final DataRecord record, final PageReadOnlyTrx pageReadTrx) { throw new UnsupportedOperationException(); } @Override public SirixDeweyID deserializeDeweyID(DataInput source, SirixDeweyID previousDeweyID, ResourceConfiguration resourceConfig) { return null; } @Override public void serializeDeweyID(DataOutput sink, NodeKind nodeKind, SirixDeweyID deweyID, SirixDeweyID prevDeweyID, ResourceConfiguration resourceConfig) { } }, /** * Node kind is deleted node. */ DELETE((byte) 5, DeletedNode.class) { @Override public DataRecord deserialize(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID deweyID, final PageReadOnlyTrx pageReadTrx) { final HashFunction hashFunction = pageReadTrx.getResourceManager().getResourceConfig().nodeHashFunction; final NodeDelegate delegate = new NodeDelegate(recordID, 0, hashFunction, null, 0, null); return new DeletedNode(delegate); } @Override public void serialize(final DataOutput sink, final DataRecord record, final PageReadOnlyTrx pageReadTrx) { } @Override public SirixDeweyID deserializeDeweyID(DataInput source, SirixDeweyID previousDeweyID, ResourceConfiguration resourceConfig) { return null; } @Override public void serializeDeweyID(DataOutput sink, NodeKind nodeKind, SirixDeweyID deweyID, SirixDeweyID prevDeweyID, ResourceConfiguration resourceConfig) { } }, /** * NullNode to support the Null Object pattern. */ NULL((byte) 6, NullNode.class) { @Override public DataRecord deserialize(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID deweyID, final PageReadOnlyTrx pageReadTrx) { throw new UnsupportedOperationException(); } @Override public void serialize(final DataOutput ink, final DataRecord record, final PageReadOnlyTrx pageReadTrx) { throw new UnsupportedOperationException(); } @Override public SirixDeweyID deserializeDeweyID(DataInput source, SirixDeweyID previousDeweyID, ResourceConfiguration resourceConfig) { return null; } @Override public void serializeDeweyID(DataOutput sink, NodeKind nodeKind, SirixDeweyID deweyID, SirixDeweyID prevDeweyID, ResourceConfiguration resourceConfig) { } }, /** * Dumb node for testing. */ DUMB((byte) 20, DumbNode.class) { @Override public DataRecord deserialize(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID deweyID, final PageReadOnlyTrx pageReadTrx) { return new DumbNode(recordID); } @Override public void serialize(final DataOutput sink, final DataRecord record, final PageReadOnlyTrx pageReadTrx) { throw new UnsupportedOperationException(); } @Override public SirixDeweyID deserializeDeweyID(DataInput source, SirixDeweyID previousDeweyID, ResourceConfiguration resourceConfig) { throw new UnsupportedOperationException(); } @Override public void serializeDeweyID(DataOutput sink, NodeKind nodeKind, SirixDeweyID deweyID, SirixDeweyID prevDeweyID, ResourceConfiguration resourceConfig) { throw new UnsupportedOperationException(); } }, /** * AtomicKind. */ ATOMIC((byte) 15, AtomicValue.class) { @Override public DataRecord deserialize(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID deweyID, final PageReadOnlyTrx pageReadTrx) { throw new UnsupportedOperationException(); } @Override public void serialize(final DataOutput sink, final DataRecord record, final PageReadOnlyTrx pageReadTrx) { throw new UnsupportedOperationException(); } @Override public SirixDeweyID deserializeDeweyID(DataInput source, SirixDeweyID previousDeweyID, ResourceConfiguration resourceConfig) { throw new UnsupportedOperationException(); } @Override public void serializeDeweyID(DataOutput sink, NodeKind nodeKind, SirixDeweyID deweyID, SirixDeweyID prevDeweyID, ResourceConfiguration resourceConfig) { throw new UnsupportedOperationException(); } }, /** * Node kind is path node. */ PATH((byte) 16, PathNode.class) { @Override public DataRecord deserialize(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID deweyID, final PageReadOnlyTrx pageReadTrx) throws IOException { // Node delegate. final NodeDelegate nodeDel = deserializeNodeDelegateWithoutIDs(source, recordID, pageReadTrx); // Struct delegate. final StructNodeDelegate structDel = deserializeStructDel(this, nodeDel, source, pageReadTrx.getResourceManager().getResourceConfig()); // Name delegate. final NameNodeDelegate nameDel = deserializeNameDelegate(nodeDel, source); final NodeKind kind = NodeKind.getKind(source.readByte()); final String uri = kind == NodeKind.OBJECT_STRING_VALUE ? "" : pageReadTrx.getName(nameDel.getURIKey(), NodeKind.NAMESPACE); final int prefixKey = nameDel.getPrefixKey(); final String prefix = prefixKey == -1 ? "" : pageReadTrx.getName(prefixKey, kind); final int localNameKey = nameDel.getLocalNameKey(); final String localName = localNameKey == -1 ? "" : pageReadTrx.getName(localNameKey, kind); return new PathNode(new QNm(uri, prefix, localName), nodeDel, structDel, nameDel, kind, source.readInt(), source.readInt()); } @Override public void serialize(final DataOutput sink, final DataRecord record, final PageReadOnlyTrx pageReadTrx) throws IOException { final PathNode node = (PathNode) record; serializeDelegate(node.getNodeDelegate(), sink); serializeStructDelegate(this, node.getStructNodeDelegate(), sink, pageReadTrx.getResourceManager().getResourceConfig()); serializeNameDelegate(node.getNameNodeDelegate(), sink); sink.writeByte(node.getPathKind().getId()); sink.writeInt(node.getReferences()); sink.writeInt(node.getLevel()); } @Override public SirixDeweyID deserializeDeweyID(DataInput source, SirixDeweyID previousDeweyID, ResourceConfiguration resourceConfig) { throw new UnsupportedOperationException(); } @Override public void serializeDeweyID(DataOutput sink, NodeKind nodeKind, SirixDeweyID deweyID, SirixDeweyID prevDeweyID, ResourceConfiguration resourceConfig) { throw new UnsupportedOperationException(); } }, /** * Node kind is a CAS-AVL node. */ CASAVL((byte) 17, AVLNode.class) { @Override public DataRecord deserialize(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID deweyID, final PageReadOnlyTrx pageReadTrx) throws IOException { final int valueSize = source.readInt(); final byte[] value = new byte[valueSize]; source.readFully(value, 0, valueSize); final int typeSize = source.readInt(); final byte[] type = new byte[typeSize]; source.readFully(type, 0, typeSize); final int keySize = source.readInt(); final Set<Long> nodeKeys = new HashSet<>(keySize); if (keySize > 0) { long key = getVarLong(source); nodeKeys.add(key); for (int i = 1; i < keySize; i++) { key += getVarLong(source); nodeKeys.add(key); } } final Type atomicType = resolveType(new String(type, Constants.DEFAULT_ENCODING)); // Node delegate. final NodeDelegate nodeDel = deserializeNodeDelegateWithoutIDs(source, recordID, pageReadTrx); final long leftChild = getVarLong(source); final long rightChild = getVarLong(source); final long pathNodeKey = getVarLong(source); final boolean isChanged = source.readBoolean(); final Atomic atomic = AtomicUtil.fromBytes(value, atomicType); AVLNode<CASValue, NodeReferences> node; node = new AVLNode<CASValue, NodeReferences>(new CASValue(atomic, atomicType, pathNodeKey), new NodeReferences(nodeKeys), nodeDel); node.setLeftChildKey(leftChild); node.setRightChildKey(rightChild); node.setChanged(isChanged); return node; } @Override public void serialize(final DataOutput sink, final DataRecord record, final PageReadOnlyTrx pageReadTrx) throws IOException { @SuppressWarnings("unchecked") final AVLNode<CASValue, NodeReferences> node = (AVLNode<CASValue, NodeReferences>) record; final CASValue key = node.getKey(); final byte[] textValue = key.getValue(); sink.writeInt(textValue.length); sink.write(textValue); final byte[] type = key.getType().toString().getBytes(Constants.DEFAULT_ENCODING); sink.writeInt(type.length); sink.write(type); final NodeReferences value = node.getValue(); final Set<Long> nodeKeys = value.getNodeKeys(); // Store in a list and sort the list. final List<Long> listNodeKeys = new ArrayList<>(nodeKeys); Collections.sort(listNodeKeys); sink.writeInt(listNodeKeys.size()); if (!listNodeKeys.isEmpty()) { putVarLong(sink, listNodeKeys.get(0)); for (int i = 0; i < listNodeKeys.size(); i++) { if (i + 1 < listNodeKeys.size()) { final long diff = listNodeKeys.get(i + 1) - listNodeKeys.get(i); putVarLong(sink, diff); } } } serializeDelegate(node.getNodeDelegate(), sink); putVarLong(sink, node.getLeftChildKey()); putVarLong(sink, node.getRightChildKey()); putVarLong(sink, key.getPathNodeKey()); sink.writeBoolean(node.isChanged()); } @Override public SirixDeweyID deserializeDeweyID(DataInput source, SirixDeweyID previousDeweyID, ResourceConfiguration resourceConfig) throws IOException { throw new UnsupportedOperationException(); } @Override public void serializeDeweyID(DataOutput sink, NodeKind nodeKind, SirixDeweyID deweyID, SirixDeweyID prevDeweyID, ResourceConfiguration resourceConfig) throws IOException { throw new UnsupportedOperationException(); } private Type resolveType(final String s) { final QNm name = new QNm(Namespaces.XS_NSURI, Namespaces.XS_PREFIX, s.substring(Namespaces.XS_PREFIX.length() + 1)); for (final Type type : Type.builtInTypes) { if (type.getName().getLocalName().equals(name.getLocalName())) { return type; } } throw new IllegalStateException("Unknown content type: " + name); } }, /** * Node kind is a PATH-AVL node. */ PATHAVL((byte) 18, AVLNode.class) { @Override public DataRecord deserialize(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID deweyID, final PageReadOnlyTrx pageReadTrx) throws IOException { final long key = getVarLong(source); final int keySize = source.readInt(); final Set<Long> nodeKeys = new HashSet<>(keySize); for (int i = 0; i < keySize; i++) { nodeKeys.add(source.readLong()); } // Node delegate. final NodeDelegate nodeDel = deserializeNodeDelegateWithoutIDs(source, recordID, pageReadTrx); final long leftChild = getVarLong(source); final long rightChild = getVarLong(source); final boolean isChanged = source.readBoolean(); final AVLNode<Long, NodeReferences> node = new AVLNode<>(key, new NodeReferences(nodeKeys), nodeDel); node.setLeftChildKey(leftChild); node.setRightChildKey(rightChild); node.setChanged(isChanged); return node; } @Override public void serialize(final DataOutput sink, final DataRecord record, final PageReadOnlyTrx pageReadTrx) throws IOException { @SuppressWarnings("unchecked") final AVLNode<Long, NodeReferences> node = (AVLNode<Long, NodeReferences>) record; putVarLong(sink, node.getKey().longValue()); final NodeReferences value = node.getValue(); final Set<Long> nodeKeys = value.getNodeKeys(); sink.writeInt(nodeKeys.size()); for (final long nodeKey : nodeKeys) { sink.writeLong(nodeKey); } serializeDelegate(node.getNodeDelegate(), sink); putVarLong(sink, node.getLeftChildKey()); putVarLong(sink, node.getRightChildKey()); sink.writeBoolean(node.isChanged()); } @Override public SirixDeweyID deserializeDeweyID(DataInput source, SirixDeweyID previousDeweyID, ResourceConfiguration resourceConfig) throws IOException { throw new UnsupportedOperationException(); } @Override public void serializeDeweyID(DataOutput sink, NodeKind nodeKind, SirixDeweyID deweyID, SirixDeweyID prevDeweyID, ResourceConfiguration resourceConfig) throws IOException { throw new UnsupportedOperationException(); } }, /** * Node kind is a PATH-AVL node. */ NAMEAVL((byte) 19, AVLNode.class) { @Override public DataRecord deserialize(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID deweyID, final PageReadOnlyTrx pageReadTrx) throws IOException { final byte[] nspBytes = new byte[source.readInt()]; source.readFully(nspBytes); final byte[] prefixBytes = new byte[source.readInt()]; source.readFully(prefixBytes); final byte[] localNameBytes = new byte[source.readInt()]; source.readFully(localNameBytes); final QNm name = new QNm(new String(nspBytes, Constants.DEFAULT_ENCODING), new String(prefixBytes, Constants.DEFAULT_ENCODING), new String(localNameBytes, Constants.DEFAULT_ENCODING)); final int keySize = source.readInt(); final Set<Long> nodeKeys = new HashSet<>(keySize); for (int i = 0; i < keySize; i++) { nodeKeys.add(source.readLong()); } // Node delegate. final NodeDelegate nodeDel = deserializeNodeDelegateWithoutIDs(source, recordID, pageReadTrx); final long leftChild = getVarLong(source); final long rightChild = getVarLong(source); final boolean isChanged = source.readBoolean(); final AVLNode<QNm, NodeReferences> node = new AVLNode<>(name, new NodeReferences(nodeKeys), nodeDel); node.setLeftChildKey(leftChild); node.setRightChildKey(rightChild); node.setChanged(isChanged); return node; } @Override public void serialize(final DataOutput sink, final DataRecord record, final PageReadOnlyTrx pageReadTrx) throws IOException { @SuppressWarnings("unchecked") final AVLNode<QNm, NodeReferences> node = (AVLNode<QNm, NodeReferences>) record; final byte[] nspBytes = node.getKey().getNamespaceURI().getBytes(); sink.writeInt(nspBytes.length); sink.write(nspBytes); final byte[] prefixBytes = node.getKey().getPrefix().getBytes(); sink.writeInt(prefixBytes.length); sink.write(prefixBytes); final byte[] localNameBytes = node.getKey().getLocalName().getBytes(); sink.writeInt(localNameBytes.length); sink.write(localNameBytes); final NodeReferences value = node.getValue(); final Set<Long> nodeKeys = value.getNodeKeys(); sink.writeInt(nodeKeys.size()); for (final long nodeKey : nodeKeys) { sink.writeLong(nodeKey); } serializeDelegate(node.getNodeDelegate(), sink); putVarLong(sink, node.getLeftChildKey()); putVarLong(sink, node.getRightChildKey()); sink.writeBoolean(node.isChanged()); } @Override public SirixDeweyID deserializeDeweyID(DataInput source, SirixDeweyID previousDeweyID, ResourceConfiguration resourceConfig) throws IOException { throw new UnsupportedOperationException(); } @Override public void serializeDeweyID(DataOutput sink, NodeKind nodeKind, SirixDeweyID deweyID, SirixDeweyID prevDeweyID, ResourceConfiguration resourceConfig) throws IOException { throw new UnsupportedOperationException(); } }, /** Node includes a deweyID &lt;=&gt; nodeKey mapping. */ DEWEYIDMAPPING((byte) 23, DeweyIDMappingNode.class) { @Override public DataRecord deserialize(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID deweyID, final PageReadOnlyTrx pageReadTrx) { throw new UnsupportedOperationException(); } @Override public void serialize(final DataOutput sink, final DataRecord record, final PageReadOnlyTrx pageReadTrx) { throw new UnsupportedOperationException(); } @Override public SirixDeweyID deserializeDeweyID(DataInput source, SirixDeweyID previousDeweyID, ResourceConfiguration resourceConfig) throws IOException { throw new UnsupportedOperationException(); } @Override public void serializeDeweyID(DataOutput sink, NodeKind nodeKind, SirixDeweyID deweyID, SirixDeweyID prevDeweyID, ResourceConfiguration resourceConfig) throws IOException { throw new UnsupportedOperationException(); } }, /** * JSON object node. */ OBJECT((byte) 24, ObjectNode.class) { @Override public DataRecord deserialize(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID deweyID, final PageReadOnlyTrx pageReadTrx) throws IOException { final BigInteger hashCode = getHash(source, pageReadTrx); // Node delegate. final NodeDelegate nodeDel = deserializeNodeDelegate(source, recordID, deweyID, pageReadTrx); // Struct delegate. final StructNodeDelegate structDel = deserializeStructDel(this, nodeDel, source, pageReadTrx.getResourceManager().getResourceConfig()); // Returning an instance. return new ObjectNode(hashCode, structDel); } @Override public void serialize(final DataOutput sink, final DataRecord record, final PageReadOnlyTrx pageReadTrx) throws IOException { final ObjectNode node = (ObjectNode) record; if (pageReadTrx.getResourceManager().getResourceConfig().hashType != HashType.NONE) { writeHash(sink, node.getHash() == null ? BigInteger.ZERO : node.getHash()); } serializeDelegate(node.getNodeDelegate(), sink); serializeStructDelegate(this, node.getStructNodeDelegate(), sink, pageReadTrx.getResourceManager().getResourceConfig()); } @Override public SirixDeweyID deserializeDeweyID(DataInput source, SirixDeweyID previousDeweyID, ResourceConfiguration resourceConfig) throws IOException { throw new UnsupportedOperationException(); } @Override public void serializeDeweyID(DataOutput sink, NodeKind nodeKind, SirixDeweyID deweyID, SirixDeweyID prevDeweyID, ResourceConfiguration resourceConfig) throws IOException { throw new UnsupportedOperationException(); } }, /** * JSON array node. */ ARRAY((byte) 25, ArrayNode.class) { @Override public DataRecord deserialize(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID deweyID, final PageReadOnlyTrx pageReadTrx) throws IOException { final BigInteger hashCode = getHash(source, pageReadTrx); final long pathNodeKey = source.readLong(); // Node delegate. final NodeDelegate nodeDel = deserializeNodeDelegate(source, recordID, deweyID, pageReadTrx); // Struct delegate. final StructNodeDelegate structDel = deserializeStructDel(this, nodeDel, source, pageReadTrx.getResourceManager().getResourceConfig()); // Returning an instance. return new ArrayNode(hashCode, structDel, pathNodeKey); } @Override public void serialize(final DataOutput sink, final DataRecord record, final PageReadOnlyTrx pageReadTrx) throws IOException { final ArrayNode node = (ArrayNode) record; if (pageReadTrx.getResourceManager().getResourceConfig().hashType != HashType.NONE) writeHash(sink, node.getHash() == null ? BigInteger.ZERO : node.getHash()); sink.writeLong(node.getPathNodeKey()); serializeDelegate(node.getNodeDelegate(), sink); serializeStructDelegate(this, node.getStructNodeDelegate(), sink, pageReadTrx.getResourceManager().getResourceConfig()); } @Override public SirixDeweyID deserializeDeweyID(DataInput source, SirixDeweyID previousDeweyID, ResourceConfiguration resourceConfig) throws IOException { throw new UnsupportedOperationException(); } @Override public void serializeDeweyID(DataOutput sink, NodeKind nodeKind, SirixDeweyID deweyID, SirixDeweyID prevDeweyID, ResourceConfiguration resourceConfig) throws IOException { throw new UnsupportedOperationException(); } }, /** * JSON array node. */ OBJECT_KEY((byte) 26, ObjectKeyNode.class) { @Override public DataRecord deserialize(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID deweyID, final PageReadOnlyTrx pageReadTrx) throws IOException { final BigInteger hashCode = getHash(source, pageReadTrx); final int nameKey = source.readInt(); final long pathNodeKey = getVarLong(source); // Node delegate. final NodeDelegate nodeDel = deserializeNodeDelegate(source, recordID, deweyID, pageReadTrx); // Struct delegate. final StructNodeDelegate structDel = deserializeStructDel(this, nodeDel, source, pageReadTrx.getResourceManager().getResourceConfig()); final String name = nameKey == -1 ? "" : pageReadTrx.getName(nameKey, NodeKind.OBJECT_KEY); // Name can be null for removed nodes (the previous record page still has the ObjectKeyNode). // Returning an instance. return new ObjectKeyNode(hashCode, structDel, nameKey, name, pathNodeKey); } @Override public void serialize(final DataOutput sink, final DataRecord record, final PageReadOnlyTrx pageReadTrx) throws IOException { final ObjectKeyNode node = (ObjectKeyNode) record; if (pageReadTrx.getResourceManager().getResourceConfig().hashType != HashType.NONE) writeHash(sink, node.getHash() == null ? BigInteger.ZERO : node.getHash()); sink.writeInt(node.getNameKey()); putVarLong(sink, node.getPathNodeKey()); serializeDelegate(node.getNodeDelegate(), sink); serializeStructDelegate(this, node.getStructNodeDelegate(), sink, pageReadTrx.getResourceManager().getResourceConfig()); } @Override public SirixDeweyID deserializeDeweyID(DataInput source, SirixDeweyID previousDeweyID, ResourceConfiguration resourceConfig) throws IOException { throw new UnsupportedOperationException(); } @Override public void serializeDeweyID(DataOutput sink, NodeKind nodeKind, SirixDeweyID deweyID, SirixDeweyID prevDeweyID, ResourceConfiguration resourceConfig) throws IOException { throw new UnsupportedOperationException(); } }, /** * JSON string value node. */ OBJECT_STRING_VALUE((byte) 40, ObjectStringNode.class) { @Override public DataRecord deserialize(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID deweyID, final PageReadOnlyTrx pageReadTrx) throws IOException { final BigInteger hashCode = getHash(source, pageReadTrx); // Node delegate. final NodeDelegate nodeDel = deserializeNodeDelegate(source, recordID, deweyID, pageReadTrx); // Val delegate. final boolean isCompressed = source.readByte() == (byte) 1; final byte[] vals = new byte[source.readInt()]; source.readFully(vals, 0, vals.length); final ValueNodeDelegate valDel = new ValueNodeDelegate(nodeDel, vals, isCompressed); // Struct delegate. final StructNodeDelegate structDelegate = new StructNodeDelegate(nodeDel, Fixed.NULL_NODE_KEY.getStandardProperty(), Fixed.NULL_NODE_KEY.getStandardProperty(), Fixed.NULL_NODE_KEY.getStandardProperty(), 0, 0); // Returning an instance. return new ObjectStringNode(hashCode, valDel, structDelegate); } @Override public void serialize(final DataOutput sink, final DataRecord record, final PageReadOnlyTrx pageReadTrx) throws IOException { final ObjectStringNode node = (ObjectStringNode) record; if (pageReadTrx.getResourceManager().getResourceConfig().hashType != HashType.NONE) writeHash(sink, node.getHash() == null ? BigInteger.ZERO : node.getHash()); serializeDelegate(node.getNodeDelegate(), sink); serializeValDelegate(node.getValNodeDelegate(), sink); } @Override public SirixDeweyID deserializeDeweyID(DataInput source, SirixDeweyID previousDeweyID, ResourceConfiguration resourceConfig) throws IOException { throw new UnsupportedOperationException(); } @Override public void serializeDeweyID(DataOutput sink, NodeKind nodeKind, SirixDeweyID deweyID, SirixDeweyID prevDeweyID, ResourceConfiguration resourceConfig) throws IOException { throw new UnsupportedOperationException(); } }, /** * JSON boolean value node. */ OBJECT_BOOLEAN_VALUE((byte) 41, ObjectBooleanNode.class) { @Override public DataRecord deserialize(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID deweyID, final PageReadOnlyTrx pageReadTrx) throws IOException { final BigInteger hashCode = getHash(source, pageReadTrx); final boolean boolValue = source.readBoolean(); // Node delegate. final NodeDelegate nodeDel = deserializeNodeDelegate(source, recordID, deweyID, pageReadTrx); // Struct delegate. final StructNodeDelegate structDelegate = new StructNodeDelegate(nodeDel, Fixed.NULL_NODE_KEY.getStandardProperty(), Fixed.NULL_NODE_KEY.getStandardProperty(), Fixed.NULL_NODE_KEY.getStandardProperty(), 0, 0); // Returning an instance. return new ObjectBooleanNode(hashCode, boolValue, structDelegate); } @Override public void serialize(final DataOutput sink, final DataRecord record, final PageReadOnlyTrx pageReadTrx) throws IOException { final ObjectBooleanNode node = (ObjectBooleanNode) record; if (pageReadTrx.getResourceManager().getResourceConfig().hashType != HashType.NONE) writeHash(sink, node.getHash() == null ? BigInteger.ZERO : node.getHash()); sink.writeBoolean(node.getValue()); serializeDelegate(node.getNodeDelegate(), sink); } @Override public SirixDeweyID deserializeDeweyID(DataInput source, SirixDeweyID previousDeweyID, ResourceConfiguration resourceConfig) throws IOException { throw new UnsupportedOperationException(); } @Override public void serializeDeweyID(DataOutput sink, NodeKind nodeKind, SirixDeweyID deweyID, SirixDeweyID prevDeweyID, ResourceConfiguration resourceConfig) throws IOException { throw new UnsupportedOperationException(); } }, /** * JSON number value node. */ OBJECT_NUMBER_VALUE((byte) 42, ObjectNumberNode.class) { @Override public DataRecord deserialize(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID deweyID, final PageReadOnlyTrx pageReadTrx) throws IOException { final BigInteger hashCode = getHash(source, pageReadTrx); final byte valueType = source.readByte(); final Number number; switch (valueType) { case 0: number = source.readDouble(); break; case 1: number = source.readFloat(); break; case 2: number = source.readInt(); break; case 3: number = source.readLong(); break; case 4: number = deserializeBigInteger(source); break; case 5: final BigInteger bigInt = deserializeBigInteger(source); final int scale = source.readInt(); number = new BigDecimal(bigInt, scale); break; default: throw new AssertionError("Type not known."); } // Node delegate. final NodeDelegate nodeDel = deserializeNodeDelegate(source, recordID, deweyID, pageReadTrx); // Struct delegate. final StructNodeDelegate structDelegate = new StructNodeDelegate(nodeDel, Fixed.NULL_NODE_KEY.getStandardProperty(), Fixed.NULL_NODE_KEY.getStandardProperty(), Fixed.NULL_NODE_KEY.getStandardProperty(), 0, 0); // Returning an instance. return new ObjectNumberNode(hashCode, number, structDelegate); } private BigInteger deserializeBigInteger(final DataInput source) throws IOException { final byte[] bytes = new byte[source.readInt()]; source.readFully(bytes); return new BigInteger(bytes); } @Override public void serialize(final DataOutput sink, final DataRecord record, final PageReadOnlyTrx pageReadTrx) throws IOException { final ObjectNumberNode node = (ObjectNumberNode) record; if (pageReadTrx.getResourceManager().getResourceConfig().hashType != HashType.NONE) writeHash(sink, node.getHash() == null ? BigInteger.ZERO : node.getHash()); final Number number = node.getValue(); if (number instanceof Double) { sink.writeByte(0); sink.writeDouble(number.doubleValue()); } else if (number instanceof Float) { sink.writeByte(1); sink.writeFloat(number.floatValue()); } else if (number instanceof Integer) { sink.writeByte(2); sink.writeInt(number.intValue()); } else if (number instanceof Long) { sink.writeByte(3); sink.writeLong(number.longValue()); } else if (number instanceof BigInteger) { sink.writeByte(4); serializeBigInteger(sink, (BigInteger) number); } else if (number instanceof BigDecimal) { sink.writeByte(5); final BigDecimal value = (BigDecimal) number; final BigInteger bigInt = value.unscaledValue(); final int scale = value.scale(); serializeBigInteger(sink, bigInt); sink.writeInt(scale); } else { throw new AssertionError("Type not known."); } serializeDelegate(node.getNodeDelegate(), sink); } private void serializeBigInteger(final DataOutput sink, final BigInteger bigInteger) throws IOException { final byte[] bytes = bigInteger.toByteArray(); sink.writeInt(bytes.length); sink.write(bytes); } @Override public SirixDeweyID deserializeDeweyID(DataInput source, SirixDeweyID previousDeweyID, ResourceConfiguration resourceConfig) throws IOException { throw new UnsupportedOperationException(); } @Override public void serializeDeweyID(DataOutput sink, NodeKind nodeKind, SirixDeweyID deweyID, SirixDeweyID prevDeweyID, ResourceConfiguration resourceConfig) throws IOException { throw new UnsupportedOperationException(); } }, /** * JSON null node. */ OBJECT_NULL_VALUE((byte) 43, ObjectNullNode.class) { @Override public DataRecord deserialize(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID deweyID, final PageReadOnlyTrx pageReadTrx) throws IOException { final BigInteger hashCode = getHash(source, pageReadTrx); // Node delegate. final NodeDelegate nodeDel = deserializeNodeDelegate(source, recordID, deweyID, pageReadTrx); // Struct delegate. final StructNodeDelegate structDelegate = new StructNodeDelegate(nodeDel, Fixed.NULL_NODE_KEY.getStandardProperty(), Fixed.NULL_NODE_KEY.getStandardProperty(), Fixed.NULL_NODE_KEY.getStandardProperty(), 0, 0); // Returning an instance. return new ObjectNullNode(hashCode, structDelegate); } @Override public void serialize(final DataOutput sink, final DataRecord record, final PageReadOnlyTrx pageReadTrx) throws IOException { final ObjectNullNode node = (ObjectNullNode) record; if (pageReadTrx.getResourceManager().getResourceConfig().hashType != HashType.NONE) writeHash(sink, node.getHash() == null ? BigInteger.ZERO : node.getHash()); serializeDelegate(node.getNodeDelegate(), sink); } @Override public SirixDeweyID deserializeDeweyID(DataInput source, SirixDeweyID previousDeweyID, ResourceConfiguration resourceConfig) throws IOException { throw new UnsupportedOperationException(); } @Override public void serializeDeweyID(DataOutput sink, NodeKind nodeKind, SirixDeweyID deweyID, SirixDeweyID prevDeweyID, ResourceConfiguration resourceConfig) throws IOException { throw new UnsupportedOperationException(); } }, /** * JSON string value node. */ STRING_VALUE((byte) 30, StringNode.class) { @Override public DataRecord deserialize(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID deweyID, final PageReadOnlyTrx pageReadTrx) throws IOException { final BigInteger hashCode = getHash(source, pageReadTrx); // Node delegate. final NodeDelegate nodeDel = deserializeNodeDelegate(source, recordID, deweyID, pageReadTrx); // Val delegate. final boolean isCompressed = source.readByte() == (byte) 1; final byte[] vals = new byte[source.readInt()]; source.readFully(vals, 0, vals.length); final ValueNodeDelegate valDel = new ValueNodeDelegate(nodeDel, vals, isCompressed); // Struct delegate. final StructNodeDelegate structDel = deserializeStructDel(this, nodeDel, source, pageReadTrx.getResourceManager().getResourceConfig()); // Returning an instance. return new StringNode(hashCode, valDel, structDel); } @Override public void serialize(final DataOutput sink, final DataRecord record, final PageReadOnlyTrx pageReadTrx) throws IOException { final StringNode node = (StringNode) record; if (pageReadTrx.getResourceManager().getResourceConfig().hashType != HashType.NONE) writeHash(sink, node.getHash() == null ? BigInteger.ZERO : node.getHash()); serializeDelegate(node.getNodeDelegate(), sink); serializeValDelegate(node.getValNodeDelegate(), sink); serializeStructDelegate(this, node.getStructNodeDelegate(), sink, pageReadTrx.getResourceManager().getResourceConfig()); } @Override public SirixDeweyID deserializeDeweyID(DataInput source, SirixDeweyID previousDeweyID, ResourceConfiguration resourceConfig) throws IOException { throw new UnsupportedOperationException(); } @Override public void serializeDeweyID(DataOutput sink, NodeKind nodeKind, SirixDeweyID deweyID, SirixDeweyID prevDeweyID, ResourceConfiguration resourceConfig) throws IOException { throw new UnsupportedOperationException(); } }, /** * JSON boolean value node. */ BOOLEAN_VALUE((byte) 27, BooleanNode.class) { @Override public DataRecord deserialize(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID deweyID, final PageReadOnlyTrx pageReadTrx) throws IOException { final BigInteger hashCode = getHash(source, pageReadTrx); final boolean boolValue = source.readBoolean(); // Node delegate. final NodeDelegate nodeDel = deserializeNodeDelegate(source, recordID, deweyID, pageReadTrx); // Struct delegate. final StructNodeDelegate structDel = deserializeStructDel(this, nodeDel, source, pageReadTrx.getResourceManager().getResourceConfig()); // Returning an instance. return new BooleanNode(hashCode, boolValue, structDel); } @Override public void serialize(final DataOutput sink, final DataRecord record, final PageReadOnlyTrx pageReadTrx) throws IOException { final BooleanNode node = (BooleanNode) record; if (pageReadTrx.getResourceManager().getResourceConfig().hashType != HashType.NONE) writeHash(sink, node.getHash() == null ? BigInteger.ZERO : node.getHash()); sink.writeBoolean(node.getValue()); serializeDelegate(node.getNodeDelegate(), sink); serializeStructDelegate(this, node.getStructNodeDelegate(), sink, pageReadTrx.getResourceManager().getResourceConfig()); } @Override public SirixDeweyID deserializeDeweyID(DataInput source, SirixDeweyID previousDeweyID, ResourceConfiguration resourceConfig) throws IOException { throw new UnsupportedOperationException(); } @Override public void serializeDeweyID(DataOutput sink, NodeKind nodeKind, SirixDeweyID deweyID, SirixDeweyID prevDeweyID, ResourceConfiguration resourceConfig) throws IOException { throw new UnsupportedOperationException(); } }, /** * JSON number value node. */ NUMBER_VALUE((byte) 28, NumberNode.class) { @Override public DataRecord deserialize(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID deweyID, final PageReadOnlyTrx pageReadTrx) throws IOException { final BigInteger hashCode = getHash(source, pageReadTrx); final byte valueType = source.readByte(); final Number number; switch (valueType) { case 0: number = source.readDouble(); break; case 1: number = source.readFloat(); break; case 2: number = source.readInt(); break; case 3: number = source.readLong(); break; case 4: number = deserializeBigInteger(source); break; case 5: final BigInteger bigInt = deserializeBigInteger(source); final int scale = source.readInt(); number = new BigDecimal(bigInt, scale); break; default: throw new AssertionError("Type not known."); } // Node delegate. final NodeDelegate nodeDel = deserializeNodeDelegate(source, recordID, deweyID, pageReadTrx); // Struct delegate. final StructNodeDelegate structDel = deserializeStructDel(this, nodeDel, source, pageReadTrx.getResourceManager().getResourceConfig()); // Returning an instance. return new NumberNode(hashCode, number, structDel); } private BigInteger deserializeBigInteger(final DataInput source) throws IOException { final byte[] bytes = new byte[source.readInt()]; source.readFully(bytes); return new BigInteger(bytes); } @Override public void serialize(final DataOutput sink, final DataRecord record, final PageReadOnlyTrx pageReadTrx) throws IOException { final NumberNode node = (NumberNode) record; if (pageReadTrx.getResourceManager().getResourceConfig().hashType != HashType.NONE) writeHash(sink, node.getHash() == null ? BigInteger.ZERO : node.getHash()); final Number number = node.getValue(); if (number instanceof Double) { sink.writeByte(0); sink.writeDouble(number.doubleValue()); } else if (number instanceof Float) { sink.writeByte(1); sink.writeFloat(number.floatValue()); } else if (number instanceof Integer) { sink.writeByte(2); sink.writeInt(number.intValue()); } else if (number instanceof Long) { sink.writeByte(3); sink.writeLong(number.longValue()); } else if (number instanceof BigInteger) { sink.writeByte(4); serializeBigInteger(sink, (BigInteger) number); } else if (number instanceof BigDecimal) { sink.writeByte(5); final BigDecimal value = (BigDecimal) number; final BigInteger bigInt = value.unscaledValue(); final int scale = value.scale(); serializeBigInteger(sink, bigInt); sink.writeInt(scale); } else { throw new AssertionError("Type not known."); } serializeDelegate(node.getNodeDelegate(), sink); serializeStructDelegate(this, node.getStructNodeDelegate(), sink, pageReadTrx.getResourceManager().getResourceConfig()); } private void serializeBigInteger(final DataOutput sink, final BigInteger bigInteger) throws IOException { final byte[] bytes = bigInteger.toByteArray(); sink.writeInt(bytes.length); sink.write(bytes); } @Override public SirixDeweyID deserializeDeweyID(DataInput source, SirixDeweyID previousDeweyID, ResourceConfiguration resourceConfig) throws IOException { throw new UnsupportedOperationException(); } @Override public void serializeDeweyID(DataOutput sink, NodeKind nodeKind, SirixDeweyID deweyID, SirixDeweyID prevDeweyID, ResourceConfiguration resourceConfig) throws IOException { throw new UnsupportedOperationException(); } }, /** * JSON null node. */ NULL_VALUE((byte) 29, NullNode.class) { @Override public DataRecord deserialize(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID deweyID, final PageReadOnlyTrx pageReadTrx) throws IOException { final BigInteger hashCode = getHash(source, pageReadTrx); // Node delegate. final NodeDelegate nodeDel = deserializeNodeDelegate(source, recordID, deweyID, pageReadTrx); // Struct delegate. final StructNodeDelegate structDel = deserializeStructDel(this, nodeDel, source, pageReadTrx.getResourceManager().getResourceConfig()); // Returning an instance. return new NullNode(hashCode, structDel); } @Override public void serialize(final DataOutput sink, final DataRecord record, final PageReadOnlyTrx pageReadTrx) throws IOException { final NullNode node = (NullNode) record; if (pageReadTrx.getResourceManager().getResourceConfig().hashType != HashType.NONE) writeHash(sink, node.getHash() == null ? BigInteger.ZERO : node.getHash()); serializeDelegate(node.getNodeDelegate(), sink); serializeStructDelegate(this, node.getStructNodeDelegate(), sink, pageReadTrx.getResourceManager().getResourceConfig()); } @Override public SirixDeweyID deserializeDeweyID(DataInput source, SirixDeweyID previousDeweyID, ResourceConfiguration resourceConfig) throws IOException { throw new UnsupportedOperationException(); } @Override public void serializeDeweyID(DataOutput sink, NodeKind nodeKind, SirixDeweyID deweyID, SirixDeweyID prevDeweyID, ResourceConfiguration resourceConfig) throws IOException { throw new UnsupportedOperationException(); } }, /** * Node kind is document root. */ // Virtualize document root node? JSON_DOCUMENT((byte) 31, JsonDocumentRootNode.class) { @Override public DataRecord deserialize(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID deweyID, final PageReadOnlyTrx pageReadTrx) throws IOException { final HashFunction hashFunction = pageReadTrx.getResourceManager().getResourceConfig().nodeHashFunction; final NodeDelegate nodeDel = new NodeDelegate(Fixed.DOCUMENT_NODE_KEY.getStandardProperty(), Fixed.NULL_NODE_KEY.getStandardProperty(), hashFunction, null, getVarLong(source), SirixDeweyID.newRootID()); final StructNodeDelegate structDel = new StructNodeDelegate(nodeDel, getVarLong(source), Fixed.NULL_NODE_KEY.getStandardProperty(), Fixed.NULL_NODE_KEY.getStandardProperty(), source.readByte() == ((byte) 0) ? 0 : 1, source.readLong()); return new JsonDocumentRootNode(nodeDel, structDel); } @Override public void serialize(final DataOutput sink, final DataRecord record, final PageReadOnlyTrx pageReadTrx) throws IOException { final JsonDocumentRootNode node = (JsonDocumentRootNode) record; putVarLong(sink, node.getRevision()); putVarLong(sink, node.getFirstChildKey()); sink.writeByte(node.hasFirstChild() ? (byte) 1 : (byte) 0); sink.writeLong(node.getDescendantCount()); } @Override public SirixDeweyID deserializeDeweyID(DataInput source, SirixDeweyID previousDeweyID, ResourceConfiguration resourceConfig) throws IOException { return null; } @Override public void serializeDeweyID(DataOutput sink, NodeKind nodeKind, SirixDeweyID deweyID, SirixDeweyID prevDeweyID, ResourceConfiguration resourceConfig) throws IOException { } }, HASH_ENTRY((byte) 32, HashEntryNode.class) { @Override public DataRecord deserialize(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID deweyID, final PageReadOnlyTrx pageReadTrx) throws IOException { return new HashEntryNode(recordID, source.readInt(), source.readUTF()); } @Override public void serialize(final DataOutput sink, final DataRecord record, final PageReadOnlyTrx pageReadTrx) throws IOException { final HashEntryNode node = (HashEntryNode) record; sink.writeInt(node.getKey()); sink.writeUTF(node.getValue()); } @Override public SirixDeweyID deserializeDeweyID(DataInput source, SirixDeweyID previousDeweyID, ResourceConfiguration resourceConfig) throws IOException { return null; } @Override public void serializeDeweyID(DataOutput sink, NodeKind nodeKind, SirixDeweyID deweyID, SirixDeweyID prevDeweyID, ResourceConfiguration resourceConfig) throws IOException { } }, HASH_NAME_COUNT_TO_NAME_ENTRY((byte) 33, HashCountEntryNode.class) { @Override public DataRecord deserialize(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID deweyID, final PageReadOnlyTrx pageReadTrx) throws IOException { return new HashCountEntryNode(recordID, source.readInt()); } @Override public void serialize(final DataOutput sink, final DataRecord record, final PageReadOnlyTrx pageReadTrx) throws IOException { final HashCountEntryNode node = (HashCountEntryNode) record; sink.writeInt(node.getValue()); } @Override public SirixDeweyID deserializeDeweyID(DataInput source, SirixDeweyID previousDeweyID, ResourceConfiguration resourceConfig) { return null; } @Override public void serializeDeweyID(DataOutput sink, NodeKind nodeKind, SirixDeweyID deweyID, SirixDeweyID prevDeweyID, ResourceConfiguration resourceConfig) throws IOException { } }, /** * Node type not known. */ UNKNOWN((byte) 22, null) { @Override public DataRecord deserialize(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID deweyID, final PageReadOnlyTrx pageReadTrx) throws IOException { throw new UnsupportedOperationException(); } @Override public void serialize(final DataOutput sink, final DataRecord record, final PageReadOnlyTrx pageReadTrx) throws IOException { throw new UnsupportedOperationException(); } @Override public SirixDeweyID deserializeDeweyID(DataInput source, SirixDeweyID previousDeweyID, ResourceConfiguration resourceConfig) throws IOException { throw new UnsupportedOperationException(); } @Override public void serializeDeweyID(DataOutput sink, NodeKind nodeKind, SirixDeweyID deweyID, SirixDeweyID prevDeweyID, ResourceConfiguration resourceConfig) throws IOException { throw new UnsupportedOperationException(); } }; /** * Identifier. */ private final byte mId; /** * Class. */ private final Class<? extends DataRecord> mClass; /** * Mapping of keys -> nodes. */ private static final Map<Byte, NodeKind> INSTANCEFORID = new HashMap<>(); /** * Mapping of class -> nodes. */ private static final Map<Class<? extends DataRecord>, NodeKind> INSTANCEFORCLASS = new HashMap<>(); static { for (final NodeKind node : values()) { INSTANCEFORID.put(node.mId, node); INSTANCEFORCLASS.put(node.mClass, node); } } /** * Constructor. * * @param id unique identifier * @param clazz class */ NodeKind(final byte id, final Class<? extends DataRecord> clazz) { mId = id; mClass = clazz; } /** * Get the nodeKind. * * @return the unique kind */ public byte getId() { return mId; } /** * Get class of node. * * @return class of node */ public Class<? extends DataRecord> getNodeClass() { return mClass; } /** * Public method to get the related node based on the identifier. * * @param id the identifier for the node * @return the related node */ public static NodeKind getKind(final byte id) { return INSTANCEFORID.get(id); } /** * Public method to get the related node based on the class. * * @param clazz the class for the node * @return the related node */ public static NodeKind getKind(final Class<? extends DataRecord> clazz) { return INSTANCEFORCLASS.get(clazz); } @Override public SirixDeweyID deserializeDeweyID(DataInput source, SirixDeweyID previousDeweyID, ResourceConfiguration resourceConfig) throws IOException { if (resourceConfig.areDeweyIDsStored) { if (previousDeweyID != null) { final byte[] previousDeweyIDBytes = previousDeweyID.toBytes(); final int cutOffSize = source.readByte(); final int size = source.readByte(); final byte[] deweyIDBytes = new byte[size]; source.readFully(deweyIDBytes); final byte[] bytes = new byte[cutOffSize + deweyIDBytes.length]; final ByteBuffer target = ByteBuffer.wrap(bytes); target.put(Arrays.copyOfRange(previousDeweyIDBytes, 0, cutOffSize)); target.put(deweyIDBytes); return new SirixDeweyID(bytes); } else { final byte deweyIDLength = source.readByte(); final byte[] deweyIDBytes = new byte[deweyIDLength]; source.readFully(deweyIDBytes, 0, deweyIDLength); return new SirixDeweyID(deweyIDBytes); } } return null; } @Override public void serializeDeweyID(DataOutput sink, NodeKind nodeKind, SirixDeweyID deweyID, SirixDeweyID nextDeweyID, ResourceConfiguration resourceConfig) throws IOException { if (resourceConfig.areDeweyIDsStored) { if (nextDeweyID != null) { final byte[] deweyIDBytes = deweyID.toBytes(); final byte[] nextDeweyIDBytes = nextDeweyID.toBytes(); assert deweyIDBytes.length <= nextDeweyIDBytes.length; int i = 0; for (; i < deweyIDBytes.length; i++) { if (deweyIDBytes[i] != nextDeweyIDBytes[i]) { break; } } writeDeweyID(sink, nextDeweyIDBytes, i); } else { final byte[] deweyIDBytes = deweyID.toBytes(); sink.writeByte(deweyIDBytes.length); sink.write(deweyIDBytes); } } } private static final BigInteger getHash(final DataInput source, final PageReadOnlyTrx pageReadTrx) throws IOException { final BigInteger hashCode; if (pageReadTrx.getResourceManager().getResourceConfig().hashType == HashType.NONE) hashCode = null; else hashCode = readHash(source); return hashCode; } private static final NodeDelegate deserializeNodeDelegateWithoutIDs(final DataInput source, final @Nonnegative long recordID, final PageReadOnlyTrx pageReadTrx) throws IOException { final long nodeKey = recordID; final long parentKey = nodeKey - getVarLong(source); final long revision = getVarLong(source); final HashFunction hashFunction = pageReadTrx.getResourceManager().getResourceConfig().nodeHashFunction; return new NodeDelegate(nodeKey, parentKey, hashFunction, null, revision, null); } private static final NodeDelegate deserializeNodeDelegate(final DataInput source, final @Nonnegative long recordID, final SirixDeweyID id, final PageReadOnlyTrx pageReadTrx) throws IOException { final long nodeKey = recordID; final long parentKey = nodeKey - getVarLong(source); final long revision = getVarLong(source); final HashFunction hashFunction = pageReadTrx.getResourceManager().getResourceConfig().nodeHashFunction; return new NodeDelegate(nodeKey, parentKey, hashFunction, null, revision, id); } private static final void serializeDelegate(final NodeDelegate nodeDel, final DataOutput sink) throws IOException { putVarLong(sink, nodeDel.getNodeKey() - nodeDel.getParentKey()); putVarLong(sink, nodeDel.getRevision()); } private static void writeDeweyID(final DataOutput sink, final byte[] deweyID, final @Nonnegative int i) throws IOException { sink.writeByte(i); sink.writeByte(deweyID.length - i); sink.write(Arrays.copyOfRange(deweyID, i, deweyID.length)); } private static final void serializeStructDelegate(final NodeKind kind, final StructNodeDelegate nodeDel, final DataOutput sink, final ResourceConfiguration config) throws IOException { final var isValueNode = kind == NodeKind.NUMBER_VALUE || kind == NodeKind.STRING_VALUE || kind == NodeKind.BOOLEAN_VALUE || kind == NodeKind.NULL_VALUE; final boolean storeChildCount = config.getStoreChildCount(); putVarLong(sink, nodeDel.getNodeKey() - nodeDel.getRightSiblingKey()); putVarLong(sink, nodeDel.getNodeKey() - nodeDel.getLeftSiblingKey()); if (!isValueNode) { putVarLong(sink, nodeDel.getNodeKey() - nodeDel.getFirstChildKey()); if (storeChildCount) { putVarLong(sink, nodeDel.getNodeKey() - nodeDel.getChildCount()); } if (config.hashType != HashType.NONE) putVarLong(sink, nodeDel.getDescendantCount() - nodeDel.getChildCount()); } } private static final StructNodeDelegate deserializeStructDel(final NodeKind kind, final NodeDelegate nodeDel, final DataInput source, final ResourceConfiguration config) throws IOException { final long currKey = nodeDel.getNodeKey(); final boolean storeChildNodes = config.getStoreChildCount(); final var isValueNode = kind == NodeKind.NUMBER_VALUE || kind == NodeKind.STRING_VALUE || kind == NodeKind.BOOLEAN_VALUE || kind == NodeKind.NULL_VALUE; final long rightSibl; final long leftSibl; final long firstChild; final long childCount; rightSibl = currKey - getVarLong(source); leftSibl = currKey - getVarLong(source); if (isValueNode) firstChild = Fixed.NULL_NODE_KEY.getStandardProperty(); else firstChild = currKey - getVarLong(source); if (isValueNode || !storeChildNodes) childCount = 0; else childCount = currKey - getVarLong(source); final long descendantCount; if (config.hashType == HashType.NONE || isValueNode) { descendantCount = 0; } else { descendantCount = getVarLong(source) + childCount; } return new StructNodeDelegate(nodeDel, firstChild, rightSibl, leftSibl, childCount, descendantCount); } private static final NameNodeDelegate deserializeNameDelegate(final NodeDelegate nodeDel, final DataInput source) throws IOException { final int uriKey = source.readInt(); int prefixKey = source.readInt(); int localNameKey = source.readInt(); return new NameNodeDelegate(nodeDel, uriKey, prefixKey, localNameKey, getVarLong(source)); } /** * Serializing the {@link NameNodeDelegate} instance. * * @param nameDel {@link NameNodeDelegate} instance * @param sink to serialize to */ private static final void serializeNameDelegate(final NameNodeDelegate nameDel, final DataOutput sink) throws IOException { sink.writeInt(nameDel.getURIKey()); sink.writeInt(nameDel.getPrefixKey()); sink.writeInt(nameDel.getLocalNameKey()); putVarLong(sink, nameDel.getPathNodeKey()); } /** * Serializing the {@link ValueNodeDelegate} instance. * * @param valueDel to be serialized * @param sink to serialize to */ private static final void serializeValDelegate(final ValueNodeDelegate valueDel, final DataOutput sink) throws IOException { final boolean isCompressed = valueDel.isCompressed(); sink.writeByte(isCompressed ? (byte) 1 : (byte) 0); final byte[] value = isCompressed ? valueDel.getCompressed() : valueDel.getRawValue(); sink.writeInt(value.length); sink.write(value); } private static BigInteger readHash(final DataInput source) throws IOException { final byte[] hashBytes = new byte[source.readByte()]; source.readFully(hashBytes); return new BigInteger(1, hashBytes); } private static void writeHash(final DataOutput sink, final BigInteger hashCode) throws IOException { final byte[] bigIntegerBytes = hashCode.toByteArray(); final List<Byte> bytes = new ArrayList<>(); final int maxLength = Math.min(bigIntegerBytes.length, 17); for (int i = 1; i < maxLength; i++) { bytes.add(bigIntegerBytes[i]); } assert bytes.size() < 17; sink.writeByte(bigIntegerBytes.length); sink.write(bigIntegerBytes); } /** * Simple DumbNode just for testing the {@link UnorderedKeyValuePage}s. * * @author Sebastian Graf, University of Konstanz * @author Johannes Lichtenberger */ public static class DumbNode implements DataRecord { /** * Node key. */ private final long nodeKey; /** * Simple constructor. * * @param nodeKey to be set */ public DumbNode(final long nodeKey) { this.nodeKey = nodeKey; } @Override public long getNodeKey() { return nodeKey; } @Override public NodeKind getKind() { return NodeKind.NULL; } @Override public long getRevision() { return 0; } @Override public SirixDeweyID getDeweyID() { return null; } } }
package io.minecloud.bungee; import com.google.common.io.Files; import io.minecloud.MineCloud; import io.minecloud.MineCloudException; import io.minecloud.db.mongo.MongoDatabase; import io.minecloud.db.redis.RedisDatabase; import io.minecloud.db.redis.msg.MessageType; import io.minecloud.db.redis.msg.binary.MessageInputStream; import io.minecloud.db.redis.pubsub.SimpleRedisChannel; import io.minecloud.models.bungee.Bungee; import io.minecloud.models.bungee.type.BungeeType; import io.minecloud.models.plugins.PluginType; import io.minecloud.models.server.Server; import io.minecloud.models.server.ServerRepository; import io.minecloud.models.server.type.ServerType; import net.md_5.bungee.api.config.ServerInfo; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Plugin; import net.md_5.bungee.api.plugin.PluginManager; import org.bson.types.ObjectId; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.logging.Level; public class MineCloudPlugin extends Plugin { MongoDatabase mongo; RedisDatabase redis; @Override public void onEnable() { MineCloud.environmentSetup(); mongo = MineCloud.instance().mongo(); redis = MineCloud.instance().redis(); redis.addChannel(SimpleRedisChannel.create("server-start-notif", redis) .addCallback((message) -> getProxy().getScheduler().schedule(this, () -> { if (message.type() != MessageType.BINARY) { return; } try { MessageInputStream stream = message.contents(); Server server = mongo.repositoryBy(Server.class).findFirst(stream.readString()); addServer(server); } catch (IOException ignored) { } }, 1, TimeUnit.SECONDS))); redis.addChannel(SimpleRedisChannel.create("server-shutdown-notif", redis) .addCallback((message) -> { if (message.type() != MessageType.BINARY) { return; } MessageInputStream stream = message.contents(); removeServer(stream.readString()); })); redis.addChannel(SimpleRedisChannel.create("teleport", redis) .addCallback((message) -> { if (message.type() != MessageType.BINARY) { return; } MessageInputStream stream = message.contents(); ProxiedPlayer player = getProxy().getPlayer(stream.readString()); if (player == null) { return; } ServerInfo info = getProxy().getServerInfo(stream.readString()); player.connect(info); })); redis.addChannel(SimpleRedisChannel.create("teleport-type", redis) .addCallback((message) -> { if (message.type() != MessageType.BINARY) { return; } MessageInputStream stream = message.contents(); ProxiedPlayer player = getProxy().getPlayer(stream.readString()); if (player == null) { return; } ServerType type = mongo.repositoryBy(ServerType.class) .findFirst(stream.readString()); if (type == null) { getLogger().log(Level.SEVERE, "Received teleport message with invalid server type"); return; } ServerRepository repository = mongo.repositoryBy(Server.class); List<Server> servers = repository.find(repository.createQuery() .field("network").equal(bungee().network()) .field("type").equal(type)) .asList(); Collections.sort(servers, (a, b) -> b.onlinePlayers().size() - a.onlinePlayers().size()); Server server = servers.get(0); ServerInfo info = getProxy().getServerInfo(server.name()); if (info == null) { getLogger().warning("Cannot find " + server.name() + " in ServerInfo store, adding."); addServer(server); info = getProxy().getServerInfo(server.name()); } player.connect(info); })); getProxy().getScheduler().schedule(this, () -> getProxy().getScheduler().runAsync(this, () -> { Bungee bungee = bungee(); if (bungee != null) { return; } getLogger().info("Bungee removed from database, going down..."); getProxy().stop(); // bye bye }), 2, 2, TimeUnit.SECONDS); BungeeType type = bungee().type(); File nContainer = new File("nplugins/"); nContainer.mkdirs(); type.plugins().forEach((plugin) -> { String version = plugin.version(); PluginType pluginType = plugin.type(); File pluginsContainer = new File("/mnt/minecloud/plugins/", pluginType.name() + "/" + version); List<File> plugins = new ArrayList<>(); getLogger().info("Loading " + pluginType.name() + "..."); if (validateFolder(pluginsContainer, pluginType, version)) return; for (File f : pluginsContainer.listFiles()) { if (f.isDirectory()) continue; // ignore directories File pl = new File(nContainer, f.getName()); try { Files.copy(f, pl); } catch (IOException ex) { getLogger().log(Level.SEVERE, "Could not load " + pluginType.name() + ", printing stacktrace..."); ex.printStackTrace(); return; } plugins.add(pl); } File configs = new File("/mnt/minecloud/configs/", pluginType.name() + "/" + (plugin.config() == null ? version : plugin.config())); File configContainer = new File(nContainer, pluginType.name()); if (!validateFolder(configs, pluginType, version)) copyFolder(configs, configContainer); }); getProxy().getScheduler().schedule(this, () -> { ServerRepository repository = mongo.repositoryBy(Server.class); List<Server> servers = repository.find(repository.createQuery() .field("network").equal(bungee().network())) .asList(); servers.removeIf((s) -> s.port() == -1); servers.forEach(this::addServer); getProxy().setReconnectHandler(new ReconnectHandler(this)); getProxy().getPluginManager().registerListener(this, new MineCloudListener(this)); // release plugin manager lock try { Field f = PluginManager.class.getDeclaredField("toLoad"); f.setAccessible(true); f.set(getProxy().getPluginManager(), new HashMap<>()); } catch (NoSuchFieldException | IllegalAccessException ignored) { } getProxy().getPluginManager().detectPlugins(nContainer); getProxy().getPluginManager().loadPlugins(); getProxy().getPluginManager().getPlugins().stream() .filter((p) -> !p.getDescription().getName().equals("MineCloud-Bungee")) .forEach(Plugin::onEnable); }, 0, TimeUnit.SECONDS); } @Override public void onDisable() { Bungee bungee = bungee(); if (bungee != null) mongo.repositoryBy(Bungee.class).delete(bungee); } private boolean validateFolder(File file, PluginType pluginType, String version) { if (!file.exists()) { getLogger().info(file.getPath() + " does not exist! Cannot load " + pluginType.name()); return true; } if (!(file.isDirectory()) || file.listFiles() == null || file.listFiles().length < 1) { getLogger().info(pluginType.name() + " " + version + " has either no files or has an invalid setup"); return true; } return false; } private void copyFolder(File folder, File folderContainer) { folderContainer.mkdirs(); for (File f : folder.listFiles()) { if (f.isDirectory()) { File newContainer = new File(folderContainer, f.getName()); copyFolder(f, newContainer); } try { Files.copy(f, new File(folderContainer, f.getName())); } catch (IOException ex) { throw new MineCloudException(ex); } } } public void addServer(Server server) { ServerInfo info = getProxy().constructServerInfo(server.name(), new InetSocketAddress(server.node().privateIp(), server.port()), "", false); getProxy().getServers().put(server.name(), info); getLogger().info("Added " + server.name() + " to server list, " + server.node().privateIp() + ":" + server.port()); } public void removeServer(String server) { getProxy().getServers().remove(server); } public Bungee bungee() { return mongo.repositoryBy(Bungee.class) .findFirst((bungee) -> bungee.entityId().equals(System.getenv("bungee_id"))); } }
package ru.job4j.start; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Arrays; import ru.job4j.models.*; /**. * Chapter_002 * Create action * * @author Anton Vasilyuk * @version 1.0 * @since 0.1 */ public class Tracker { /**. * @items Array items */ private List<Item> items = new ArrayList<>(); /**. * @RN git id */ private static final Random RN = new Random(); /**. * method for add items * @param item item object * @return result */ public Item add(Item item) { item.setId(String.valueOf(RN.nextInt())); this.items.add(item); return item; } /**. * method for update items * @param item item for update */ public void update(Item item) { for (Item a : items) { if (item != null && item.getId().equals(a.getId())) { items.set(items.indexOf(a), item); break; } } } /**. * method for delete items * @param item item for delete */ public void delete(Item item) { items.remove(item); } /**. * method for find all items * @return result */ public List<Item> findAll() { return this.items; } /**. * method for find items * @param key name * @return array with dublicate name */ public List<Item> findByName(String key) { List<Item> nameList = new ArrayList<>(); for (Item a : items) { if (a != null && a.getName().equals(key)) { nameList.add(a); } } return nameList; } /**. * method for show all items * @param id id for item * @return item */ public Item findById(String id) { Item result = null; for (Item item : items) { if (item != null && item.getId().equals(id)) { result = item; break; } } return result; } }
package com.malhartech.lib.math; import com.malhartech.annotation.InputPortFieldAnnotation; import com.malhartech.annotation.OutputPortFieldAnnotation; import com.malhartech.api.BaseOperator; import com.malhartech.api.DefaultInputPort; import com.malhartech.api.DefaultOutputPort; import com.malhartech.lib.util.MutableDouble; import java.util.HashMap; import java.util.Map; /** * * Takes in two streams via input ports "numerator" and "denominator". At the * end of window computes the margin for each key and emits the result on port * "margin" (1 - numerator/denominator).<p> <br> Each stream is added to a hash. * The values are added for each key within the window and for each stream.<<br> * This node only functions in a windowed stram application<br> <br> Compile * time error processing is done on configuration parameters<br> * <b>Ports</b>: * <b>numerator</b> expects HashMap<K,V><br> * <b>denominator</b> expects HashMap<K,V><br> * <b>margin</b> emits HashMap<K,Double>, one entry per key<br> * <br> * <b>Compile time checks</b><br> * None<br> * <br> Run time error processing are emitted on _error port. The errors * are:<br> Divide by zero (Error): no result is emitted on "outport".<br> Input * tuple not an integer on denominator stream: This tuple would not be counted * towards the result.<br> Input tuple not an integer on numerator stream: This * tuple would not be counted towards the result.<br> <br> * <b>Benchmarks</b><br> * Min operator processes >40 million tuples/sec. The processing is high as it only emits one tuple per window, and is not bound by outbound throughput<br> * <br> * * @author amol<br> * */ public class Margin<K, V extends Number> extends BaseNumberOperator<V> { @InputPortFieldAnnotation(name = "numerator") public final transient DefaultInputPort<HashMap<K, V>> numerator = new DefaultInputPort<HashMap<K, V>>(this) { @Override public void process(HashMap<K, V> tuple) { addTuple(tuple, numerators); } }; @InputPortFieldAnnotation(name = "denominator") public final transient DefaultInputPort<HashMap<K, V>> denominator = new DefaultInputPort<HashMap<K, V>>(this) { @Override public void process(HashMap<K, V> tuple) { addTuple(tuple, denominators); } }; public void addTuple(HashMap<K, V> tuple, HashMap<K, MutableDouble> map) { for (Map.Entry<K, V> e: tuple.entrySet()) { MutableDouble val = map.get(e.getKey()); if (val == null) { val = new MutableDouble(0.0); map.put(e.getKey(), val); } val.value += e.getValue().doubleValue(); } } @OutputPortFieldAnnotation(name = "margin") public final transient DefaultOutputPort<HashMap<K, V>> margin = new DefaultOutputPort<HashMap<K, V>>(this); HashMap<K, MutableDouble> numerators = new HashMap<K, MutableDouble>(); HashMap<K, MutableDouble> denominators = new HashMap<K, MutableDouble>(); boolean percent = false; void setPercent(boolean val) { percent = val; } @Override public void beginWindow() { numerators.clear(); denominators.clear(); } @Override public void endWindow() { HashMap<K, V> tuples = new HashMap<K, V>(); Double val; for (Map.Entry<K, MutableDouble> e: denominators.entrySet()) { MutableDouble nval = numerators.get(e.getKey()); if (nval == null) { nval = new MutableDouble(0.0); } else { numerators.remove(e.getKey()); // so that all left over keys can be reported } if (percent) { val = 1 - nval.value / e.getValue().value * 100; } else { val = 1 - nval.value / e.getValue().value; } tuples.put(e.getKey(), getValue(val.doubleValue())); } if (!tuples.isEmpty()) { margin.emit(tuples); } } }
package org.coderoller.springlayout; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.util.SparseIntArray; import android.view.View; import android.view.ViewDebug; import android.view.ViewGroup; import java.util.Stack; import org.coderoller.springlayout.LayoutMath.Value; import org.coderoller.springlayout.LayoutMath.ValueWrapper; public class SpringLayout extends ViewGroup { private static int RELATIVE_SIZE_DENOMINATOR = 100; public static final int PARENT = -2; public static final int TRUE = -1; /** * Rule that aligns a child's right edge with another child's left edge. */ public static final int LEFT_OF = 0; /** * Rule that aligns a child's left edge with another child's right edge. */ public static final int RIGHT_OF = 1; /** * Rule that aligns a child's bottom edge with another child's top edge. */ public static final int ABOVE = 2; /** * Rule that aligns a child's top edge with another child's bottom edge. */ public static final int BELOW = 3; /** * Rule that aligns a child's left edge with another child's left edge. */ public static final int ALIGN_LEFT = 4; /** * Rule that aligns a child's top edge with another child's top edge. */ public static final int ALIGN_TOP = 5; /** * Rule that aligns a child's right edge with another child's right edge. */ public static final int ALIGN_RIGHT = 6; /** * Rule that aligns a child's bottom edge with another child's bottom edge. */ public static final int ALIGN_BOTTOM = 7; /** * Center will be aligned both horizontally and vertically. */ public static final int ALIGN_CENTER = 8; /** * Center will be aligned horizontally. */ public static final int ALIGN_CENTER_HORIZONTALLY = 9; /** * Center will be aligned vertically. */ public static final int ALIGN_CENTER_VERTICALLY = 10; /** * Rule that aligns the child's left edge with its SpringLayout parent's * left edge. */ private static final int ALIGN_PARENT_LEFT = 11; /** * Rule that aligns the child's top edge with its SpringLayout parent's top * edge. */ private static final int ALIGN_PARENT_TOP = 12; /** * Rule that aligns the child's right edge with its SpringLayout parent's * right edge. */ private static final int ALIGN_PARENT_RIGHT = 13; /** * Rule that aligns the child's bottom edge with its SpringLayout parent's * bottom edge. */ private static final int ALIGN_PARENT_BOTTOM = 14; /** * Rule that centers the child with respect to the bounds of its * SpringLayout parent. */ public static final int CENTER_IN_PARENT = 15; /** * Rule that centers the child horizontally with respect to the bounds of * its SpringLayout parent. */ public static final int CENTER_HORIZONTAL = 16; /** * Rule that centers the child vertically with respect to the bounds of its * SpringLayout parent. */ public static final int CENTER_VERTICAL = 17; private static final int VERB_COUNT = 18; private static int[] VALID_RELATIONS = new int[] { LEFT_OF, RIGHT_OF, ALIGN_LEFT, ALIGN_RIGHT, ABOVE, BELOW, ALIGN_TOP, ALIGN_BOTTOM, ALIGN_CENTER_HORIZONTALLY, ALIGN_CENTER_VERTICALLY }; private ViewConstraints mRootConstraints; private final SparseIntArray mIdToViewConstraints = new SparseIntArray(); private ViewConstraints[] mViewConstraints; private final Stack<ViewConstraints> mSpringMetrics = new Stack<ViewConstraints>(); private final SimpleIdentitySet<ViewConstraints> mHorizontalChains = new SimpleIdentitySet<ViewConstraints>(); private final SimpleIdentitySet<ViewConstraints> mVerticalChains = new SimpleIdentitySet<ViewConstraints>(); private LayoutMath mLayoutMath = new LayoutMath(); private boolean mDirtyHierarchy = true; private boolean mDirtySize = true; private int mMinWidth = 0, mMinHeight = 0; public SpringLayout(Context context) { super(context); } public SpringLayout(Context context, AttributeSet attrs) { super(context, attrs); initFromAttributes(context, attrs); } public SpringLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initFromAttributes(context, attrs); } private void initFromAttributes(Context context, AttributeSet attrs) { TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SpringLayout); setMinimumWidth(a.getDimensionPixelSize(R.styleable.SpringLayout_minWidth, 0)); setMinimumHeight(a.getDimensionPixelSize(R.styleable.SpringLayout_minHeight, 0)); a.recycle(); } @Override public void addView(View child, int index, ViewGroup.LayoutParams params) { mDirtyHierarchy = true; super.addView(child, index, params); } @Override public void removeView(View view) { mDirtyHierarchy = true; super.removeView(view); } @Override public void removeViewAt(int index) { mDirtyHierarchy = true; super.removeViewAt(index); } @Override public void removeViews(int start, int count) { mDirtyHierarchy = true; super.removeViews(start, count); } @Override public void requestLayout() { super.requestLayout(); mDirtySize = true; if (!mDirtyHierarchy) { final int count = getChildCount(); for (int i = 0; i < count; i++) { final LayoutParams params = ((LayoutParams) getChildAt(i).getLayoutParams()); if (params.dirty) { mDirtyHierarchy = true; params.dirty = false; } } } } private void resizeViewConstraintsArray(int newLen) { if (mViewConstraints.length < newLen) { ViewConstraints[] oldConstraints = mViewConstraints; mViewConstraints = new ViewConstraints[newLen]; System.arraycopy(oldConstraints, 0, mViewConstraints, 0, oldConstraints.length); } } private void createViewMetrics(Stack<ViewConstraints> springMetrics) { springMetrics.clear(); mIdToViewConstraints.clear(); if (mRootConstraints != null) { mRootConstraints.release(); for (int i = 0; i < mViewConstraints.length; i++) { mViewConstraints[i].release(); } mRootConstraints.reset(this); resizeViewConstraintsArray(getChildCount()); } else { mRootConstraints = new ViewConstraints(this, mLayoutMath); mViewConstraints = new ViewConstraints[getChildCount()]; } mRootConstraints.left.setValueObject(mLayoutMath.variable(0)); mRootConstraints.top.setValueObject(mLayoutMath.variable(0)); final int count = getChildCount(); for (int i = 0; i < count; i++) { final View v = getChildAt(i); mIdToViewConstraints.append(v.getId(), i); if (mViewConstraints[i] == null) { mViewConstraints[i] = new ViewConstraints(v, mLayoutMath); } else { mViewConstraints[i].reset(v); } } for (int i = 0; i < count; i++) { final ViewConstraints viewConstraints = mViewConstraints[i]; final LayoutParams layoutParams = (LayoutParams) viewConstraints.getView().getLayoutParams(); int[] childRules = layoutParams.getRelations(); for (int relation : VALID_RELATIONS) { final ViewConstraints metrics = getViewMetrics(childRules[relation]); if (metrics != null) { metrics.updateRelation(viewConstraints, relation); } } if (viewConstraints.isSpring()) { springMetrics.add(viewConstraints); } } } private ViewConstraints getViewMetrics(int id) { if (id == PARENT) { return mRootConstraints; } else if (id > 0 && mIdToViewConstraints.indexOfKey(id) >= 0) { return mViewConstraints[mIdToViewConstraints.get(id)]; } return null; } private void adaptLayoutParameters() { int count = getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); final LayoutParams childParams = (LayoutParams) child.getLayoutParams(); int[] relations = childParams.getRelations(); // If view is aligned both to parent's top and bottom (left and // right) then its height (width) is MATCH_PARENT and the other way // around if (relations[ALIGN_PARENT_TOP] != 0 && relations[ALIGN_PARENT_BOTTOM] != 0) { childParams.height = LayoutParams.MATCH_PARENT; } else if (childParams.height == LayoutParams.MATCH_PARENT) { relations[ALIGN_PARENT_TOP] = relations[ALIGN_PARENT_BOTTOM] = TRUE; } if (relations[ALIGN_PARENT_LEFT] != 0 && relations[ALIGN_PARENT_RIGHT] != 0) { childParams.width = LayoutParams.MATCH_PARENT; } else if (childParams.width == LayoutParams.MATCH_PARENT) { relations[ALIGN_PARENT_LEFT] = relations[ALIGN_PARENT_RIGHT] = TRUE; } if (relations[ALIGN_PARENT_TOP] == TRUE) { relations[ALIGN_TOP] = PARENT; } if (relations[ALIGN_PARENT_BOTTOM] == TRUE) { relations[ALIGN_BOTTOM] = PARENT; } if (relations[ALIGN_PARENT_LEFT] == TRUE) { relations[ALIGN_LEFT] = PARENT; } if (relations[ALIGN_PARENT_RIGHT] == TRUE) { relations[ALIGN_RIGHT] = PARENT; } if (relations[ALIGN_CENTER] != 0) { relations[ALIGN_CENTER_HORIZONTALLY] = relations[ALIGN_CENTER]; relations[ALIGN_CENTER_VERTICALLY] = relations[ALIGN_CENTER]; } if (relations[CENTER_IN_PARENT] == TRUE) { relations[CENTER_HORIZONTAL] = relations[CENTER_VERTICAL] = TRUE; } if (relations[CENTER_HORIZONTAL] == TRUE) { relations[ALIGN_CENTER_HORIZONTALLY] = PARENT; } if (relations[CENTER_VERTICAL] == TRUE) { relations[ALIGN_CENTER_VERTICALLY] = PARENT; } if (!hasHorizontalRelations(relations)) { relations[ALIGN_LEFT] = PARENT; } if (!hasVerticalRelations(relations)) { relations[ALIGN_TOP] = PARENT; } } } private boolean hasHorizontalRelations(int[] relations) { return relations[LEFT_OF] != 0 || relations[RIGHT_OF] != 0 || relations[ALIGN_LEFT] != 0 || relations[ALIGN_RIGHT] != 0 || relations[ALIGN_CENTER_HORIZONTALLY] != 0; } private boolean hasVerticalRelations(int[] relations) { return relations[BELOW] != 0 || relations[ABOVE] != 0 || relations[ALIGN_TOP] != 0 || relations[ALIGN_BOTTOM] != 0 || relations[ALIGN_CENTER_VERTICALLY] != 0; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int myWidth = -1; int myHeight = -1; int width = 0; int height = 0; int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); final boolean isWrapContentWidth = widthMode != MeasureSpec.EXACTLY; final boolean isWrapContentHeight = heightMode != MeasureSpec.EXACTLY; if (mDirtyHierarchy) { mDirtyHierarchy = false; adaptLayoutParameters(); createViewMetrics(mSpringMetrics); handleSprings(mSpringMetrics, isWrapContentWidth, isWrapContentHeight); } // Record our dimensions if they are known; if (widthMode != MeasureSpec.UNSPECIFIED) { myWidth = widthSize; } if (heightMode != MeasureSpec.UNSPECIFIED) { myHeight = heightSize; } if (widthMode == MeasureSpec.EXACTLY) { width = myWidth; } if (heightMode == MeasureSpec.EXACTLY) { height = myHeight; } if (mDirtySize) { mDirtySize = false; invalidateMathCache(); updateChildrenSize(widthMeasureSpec, heightMeasureSpec); updateLayoutSize(isWrapContentWidth, width, isWrapContentHeight, height); cacheLayoutPositions(); } setMeasuredDimension(mRootConstraints.right.getValue(), mRootConstraints.bottom.getValue()); } private void invalidateMathCache() { mRootConstraints.invalidate(); for (int i = 0; i < getChildCount(); i++) { final ViewConstraints viewConstraints = mViewConstraints[i]; viewConstraints.invalidate(); } } private void updateChildrenSize(final int widthMeasureSpec, final int heightMeasureSpec) { for (int i = 0; i < getChildCount(); i++) { final ViewConstraints viewConstraints = mViewConstraints[i]; if (viewConstraints.isSpring()) { if (!viewConstraints.hasHorizontalSibling()) { viewConstraints.setWidth(mLayoutMath.variable(0)); } if (!viewConstraints.hasVerticalSibling()) { viewConstraints.setHeight(mLayoutMath.variable(0)); } } else { final View v = viewConstraints.getView(); final LayoutParams layoutParams = (LayoutParams) v.getLayoutParams(); final int mL = layoutParams.leftMargin, mR = layoutParams.rightMargin, mT = layoutParams.topMargin, mB = layoutParams.bottomMargin; measureChildWithMargins(v, widthMeasureSpec, 0, heightMeasureSpec, 0); Value childWidth, childHeight; if (v.getVisibility() == View.GONE) { childWidth = mLayoutMath.variable(0); } else if (layoutParams.relativeWidth > 0) { childWidth = mRootConstraints.innerRight.subtract(mRootConstraints.innerLeft).multiply(mLayoutMath.variable(layoutParams.relativeWidth)).divide(mLayoutMath.variable(RELATIVE_SIZE_DENOMINATOR)); } else { childWidth = mLayoutMath.variable(v.getMeasuredWidth()); } if (v.getVisibility() == View.GONE) { childHeight = mLayoutMath.variable(0); } else if (layoutParams.relativeHeight > 0) { childHeight = mRootConstraints.innerBottom.subtract(mRootConstraints.innerTop).multiply(mLayoutMath.variable(layoutParams.relativeHeight)).divide(mLayoutMath.variable(RELATIVE_SIZE_DENOMINATOR)); } else { childHeight = mLayoutMath.variable(v.getMeasuredHeight()); } viewConstraints.leftMargin.setValue(mL); viewConstraints.rightMargin.setValue(mR); viewConstraints.topMargin.setValue(mT); viewConstraints.bottomMargin.setValue(mB); Value outerWidth = childWidth.add(mLayoutMath.variable(mL + mR)).retain(); viewConstraints.setWidth(outerWidth); outerWidth.release(); Value outerHeight = childHeight.add(mLayoutMath.variable(mT + mB)).retain(); viewConstraints.setHeight(outerHeight); outerHeight.release(); } } } private void handleSprings(final Stack<ViewConstraints> springMetrics, final boolean isWrapContentWidth, final boolean isWrapContentHeight) { if (!springMetrics.isEmpty()) { mHorizontalChains.clear(); mVerticalChains.clear(); while (!springMetrics.isEmpty()) { final ViewConstraints spring = springMetrics.pop(); final ViewConstraints chainHeadX = getChainHorizontalHead(spring); final ViewConstraints chainHeadY = getChainVerticalHead(spring); if (chainHeadX != null) { if (isWrapContentWidth && mMinWidth <= 0) { throw new IllegalStateException("Horizontal springs not supported when layout width is wrap_content"); } mHorizontalChains.add(chainHeadX); } if (chainHeadY != null) { if (isWrapContentHeight && mMinHeight <= 0) { throw new IllegalStateException( "Vertical springs not supported when layout height is wrap_content and minHeight is not defined"); } mVerticalChains.add(chainHeadY); } } for (int i = 0; i < mHorizontalChains.size(); i++) { final ViewConstraints chainHead = mHorizontalChains.get(i); int totalWeight = 0; Value contentWidth = mLayoutMath.variable(0); final ValueWrapper totalWeightWrapper = mLayoutMath.wrap(); final ValueWrapper chainWidthWrapper = mLayoutMath.wrap(); ViewConstraints chainElem = chainHead, prevElem = null; Value start = chainElem.left, end; while (chainElem != null) { if (chainElem.isSpring()) { final int weight = ((LayoutParams) chainElem.getView().getLayoutParams()).springWeight; totalWeight += weight; final Value width = chainWidthWrapper.multiply(mLayoutMath.variable(weight)).divide(totalWeightWrapper).retain(); chainElem.setWidth(width); width.release(); } else { contentWidth = contentWidth.add(chainElem.getWidth()); } prevElem = chainElem; chainElem = chainElem.nextX; } end = prevElem.right; totalWeightWrapper.setValueObject(mLayoutMath.variable(totalWeight)); chainWidthWrapper.setValueObject(end.subtract(start).subtract(contentWidth)); } for (int i = 0; i < mVerticalChains.size(); i++) { final ViewConstraints chainHead = mVerticalChains.get(i); int totalWeight = 0; Value contentHeight = mLayoutMath.variable(0); final ValueWrapper totalWeightWrapper = mLayoutMath.wrap(); final ValueWrapper chainWidthWrapper = mLayoutMath.wrap(); ViewConstraints chainElem = chainHead, prevElem = null; Value start = chainElem.top, end; while (chainElem != null) { if (chainElem.isSpring()) { final int weight = ((LayoutParams) chainElem.getView().getLayoutParams()).springWeight; totalWeight += weight; final Value height = chainWidthWrapper.multiply(mLayoutMath.variable(weight)).divide(totalWeightWrapper).retain(); chainElem.setHeight(height); height.release(); } else { contentHeight = contentHeight.add(chainElem.getHeight()); } prevElem = chainElem; chainElem = chainElem.nextY; } end = prevElem.bottom; totalWeightWrapper.setValueObject(mLayoutMath.variable(totalWeight)); chainWidthWrapper.setValueObject(end.subtract(start).subtract(contentHeight)); } } } private void updateLayoutSize(final boolean isWrapContentWidth, int width, final boolean isWrapContentHeight, int height) { final int pL = getPaddingLeft(), pR = getPaddingRight(), pT = getPaddingTop(), pB = getPaddingBottom(); mRootConstraints.leftMargin.setValue(pL); mRootConstraints.rightMargin.setValue(pR); mRootConstraints.topMargin.setValue(pT); mRootConstraints.bottomMargin.setValue(pB); Value widthValue, heightValue; if (isWrapContentWidth) { int maxSize = mMinWidth > 0 ? mMinWidth : -1; for (int i = 0; i < getChildCount(); i++) { final ViewConstraints viewConstraints = mViewConstraints[i]; try { maxSize = Math.max(maxSize, viewConstraints.right.getValue() + pR); viewConstraints.right.invalidate(); } catch (IllegalStateException e) { } } if (maxSize < 0) { throw new IllegalStateException( "Parent layout_width == wrap_content is not supported if width of all children depends on parent width."); } widthValue = mLayoutMath.variable(maxSize); } else { widthValue = mLayoutMath.variable(width); } mRootConstraints.right.setValueObject(widthValue); if (isWrapContentHeight) { int maxSize = mMinHeight > 0 ? mMinHeight : -1; for (int i = 0; i < getChildCount(); i++) { final ViewConstraints viewConstraints = mViewConstraints[i]; try { maxSize = Math.max(maxSize, viewConstraints.bottom.getValue() + pB); viewConstraints.bottom.invalidate(); } catch (IllegalStateException e) { } } if (maxSize < 0) { throw new IllegalStateException( "Parent layout_height == wrap_content is not supported if height of all children depends on parent height."); } heightValue = mLayoutMath.variable(maxSize); } else { heightValue = mLayoutMath.variable(height); } mRootConstraints.bottom.setValueObject(heightValue); } private void cacheLayoutPositions() { for (int i = 0; i < getChildCount(); i++) { final ViewConstraints viewConstraints = mViewConstraints[i]; final View v = viewConstraints.getView(); if (!viewConstraints.isSpring()) { try { SpringLayout.LayoutParams st = (SpringLayout.LayoutParams) v.getLayoutParams(); st.left = viewConstraints.innerLeft.getValue(); st.right = viewConstraints.innerRight.getValue(); st.top = viewConstraints.innerTop.getValue(); st.bottom = viewConstraints.innerBottom.getValue(); v.measure(MeasureSpec.makeMeasureSpec(st.right - st.left, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(st.bottom - st.top, MeasureSpec.EXACTLY)); } catch (StackOverflowError e) { throw new IllegalStateException( "Constraints of a view could not be resolved (circular dependency), please review your layout. Problematic view (please also check other dependant views): " + v + ", problematic layout: " + this); } } } } private ViewConstraints getChainVerticalHead(ViewConstraints spring) { if (spring.nextY == null && spring.prevY == null) { return null; } else { while (spring.prevY != null) { spring = spring.prevY; } return spring; } } private ViewConstraints getChainHorizontalHead(ViewConstraints spring) { if (spring.nextX == null && spring.prevX == null) { return null; } else { while (spring.prevX != null) { spring = spring.prevX; } return spring; } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int count = getChildCount(); for (int i = 0; i < count; i++) { View child = getChildAt(i); if (child.getVisibility() != View.GONE) { SpringLayout.LayoutParams st = (SpringLayout.LayoutParams) child.getLayoutParams(); child.layout(st.left, st.top, st.right, st.bottom); } } } @Override public void setMinimumHeight(int minHeight) { super.setMinimumHeight(minHeight); mMinHeight = minHeight; } @Override public void setMinimumWidth(int minWidth) { super.setMinimumWidth(minWidth); mMinWidth = minWidth; } @Override public LayoutParams generateLayoutParams(AttributeSet attrs) { return new SpringLayout.LayoutParams(getContext(), attrs); } /** * Returns a set of layout parameters with a width of * {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT}, a height of * {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} and no spanning. */ @Override protected ViewGroup.LayoutParams generateDefaultLayoutParams() { return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); } // Override to allow type-checking of LayoutParams. @Override protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { return p instanceof SpringLayout.LayoutParams; } @Override protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { return new LayoutParams(p); } /** * Per-child layout information associated with SpringLayout. * * @attr ref R.styleable#SpringLayout_Layout_layout_toLeftOf * @attr ref R.styleable#SpringLayout_Layout_layout_toRightOf * @attr ref R.styleable#SpringLayout_Layout_layout_above * @attr ref R.styleable#SpringLayout_Layout_layout_below * @attr ref R.styleable#SpringLayout_Layout_layout_alignBaseline * @attr ref R.styleable#SpringLayout_Layout_layout_alignLeft * @attr ref R.styleable#SpringLayout_Layout_layout_alignTop * @attr ref R.styleable#SpringLayout_Layout_layout_alignRight * @attr ref R.styleable#SpringLayout_Layout_layout_alignBottom * @attr ref R.styleable#SpringLayout_Layout_layout_alignCenterHorizontally * @attr ref R.styleable#SpringLayout_Layout_layout_alignCenterVertically * @attr ref R.styleable#SpringLayout_Layout_layout_alignParentLeft * @attr ref R.styleable#SpringLayout_Layout_layout_alignParentTop * @attr ref R.styleable#SpringLayout_Layout_layout_alignParentRight * @attr ref R.styleable#SpringLayout_Layout_layout_alignParentBottom * @attr ref R.styleable#SpringLayout_Layout_layout_centerInParent * @attr ref R.styleable#SpringLayout_Layout_layout_centerHorizontal * @attr ref R.styleable#SpringLayout_Layout_layout_centerVertical */ public static class LayoutParams extends ViewGroup.MarginLayoutParams { @ViewDebug.ExportedProperty(resolveId = true, indexMapping = { @ViewDebug.IntToString(from = ABOVE, to = "above"), @ViewDebug.IntToString(from = BELOW, to = "below"), @ViewDebug.IntToString(from = LEFT_OF, to = "leftOf"), @ViewDebug.IntToString(from = RIGHT_OF, to = "rightOf"), @ViewDebug.IntToString(from = ALIGN_PARENT_LEFT, to = "alignParentLeft"), @ViewDebug.IntToString(from = ALIGN_PARENT_RIGHT, to = "alignParentRight"), @ViewDebug.IntToString(from = ALIGN_PARENT_TOP, to = "alignParentTop"), @ViewDebug.IntToString(from = ALIGN_PARENT_BOTTOM, to = "alignParentBottom"), @ViewDebug.IntToString(from = ALIGN_LEFT, to = "alignLeft"), @ViewDebug.IntToString(from = ALIGN_RIGHT, to = "alignRight"), @ViewDebug.IntToString(from = ALIGN_TOP, to = "alignTop"), @ViewDebug.IntToString(from = ALIGN_BOTTOM, to = "alignBottom"), @ViewDebug.IntToString(from = ALIGN_CENTER, to = "alignCenter"), @ViewDebug.IntToString(from = ALIGN_CENTER_HORIZONTALLY, to = "alignCenterHorizontally"), @ViewDebug.IntToString(from = ALIGN_CENTER_VERTICALLY, to = "alignCenterVertically"), @ViewDebug.IntToString(from = CENTER_HORIZONTAL, to = "centerHorizontal"), @ViewDebug.IntToString(from = CENTER_IN_PARENT, to = "centerInParent"), @ViewDebug.IntToString(from = CENTER_VERTICAL, to = "centerVertical"), }, mapping = { @ViewDebug.IntToString(from = TRUE, to = "true"), @ViewDebug.IntToString(from = 0, to = "false/NO_ID"), @ViewDebug.IntToString(from = PARENT, to = "parent") }) int[] relations = new int[VERB_COUNT]; int left, top, right, bottom; int relativeHeight, relativeWidth; int springWeight = 1; boolean dirty = true; public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.SpringLayout_Layout); final int[] relations = this.relations; final int N = a.getIndexCount(); for (int i = 0; i < N; i++) { int attr = a.getIndex(i); switch (attr) { case R.styleable.SpringLayout_Layout_layout_toLeftOf: relations[LEFT_OF] = a.getResourceId(attr, 0); break; case R.styleable.SpringLayout_Layout_layout_toRightOf: relations[RIGHT_OF] = a.getResourceId(attr, 0); break; case R.styleable.SpringLayout_Layout_layout_above: relations[ABOVE] = a.getResourceId(attr, 0); break; case R.styleable.SpringLayout_Layout_layout_below: relations[BELOW] = a.getResourceId(attr, 0); break; case R.styleable.SpringLayout_Layout_layout_alignLeft: relations[ALIGN_LEFT] = a.getResourceId(attr, 0); break; case R.styleable.SpringLayout_Layout_layout_alignTop: relations[ALIGN_TOP] = a.getResourceId(attr, 0); break; case R.styleable.SpringLayout_Layout_layout_alignRight: relations[ALIGN_RIGHT] = a.getResourceId(attr, 0); break; case R.styleable.SpringLayout_Layout_layout_alignBottom: relations[ALIGN_BOTTOM] = a.getResourceId(attr, 0); break; case R.styleable.SpringLayout_Layout_layout_alignCenter: relations[ALIGN_CENTER] = a.getResourceId(attr, 0); break; case R.styleable.SpringLayout_Layout_layout_alignCenterHorizontally: relations[ALIGN_CENTER_HORIZONTALLY] = a.getResourceId(attr, 0); break; case R.styleable.SpringLayout_Layout_layout_alignCenterVertically: relations[ALIGN_CENTER_VERTICALLY] = a.getResourceId(attr, 0); break; case R.styleable.SpringLayout_Layout_layout_alignParentLeft: relations[ALIGN_PARENT_LEFT] = a.getBoolean(attr, false) ? TRUE : 0; break; case R.styleable.SpringLayout_Layout_layout_alignParentTop: relations[ALIGN_PARENT_TOP] = a.getBoolean(attr, false) ? TRUE : 0; break; case R.styleable.SpringLayout_Layout_layout_alignParentRight: relations[ALIGN_PARENT_RIGHT] = a.getBoolean(attr, false) ? TRUE : 0; break; case R.styleable.SpringLayout_Layout_layout_alignParentBottom: relations[ALIGN_PARENT_BOTTOM] = a.getBoolean(attr, false) ? TRUE : 0; break; case R.styleable.SpringLayout_Layout_layout_centerInParent: relations[CENTER_IN_PARENT] = a.getBoolean(attr, false) ? TRUE : 0; break; case R.styleable.SpringLayout_Layout_layout_centerHorizontal: relations[CENTER_HORIZONTAL] = a.getBoolean(attr, false) ? TRUE : 0; break; case R.styleable.SpringLayout_Layout_layout_centerVertical: relations[CENTER_VERTICAL] = a.getBoolean(attr, false) ? TRUE : 0; break; case R.styleable.SpringLayout_Layout_layout_relativeWidth: relativeWidth = (int) a.getFraction(attr, RELATIVE_SIZE_DENOMINATOR, 1, 0); break; case R.styleable.SpringLayout_Layout_layout_relativeHeight: relativeHeight = (int) a.getFraction(attr, RELATIVE_SIZE_DENOMINATOR, 1, 0); break; case R.styleable.SpringLayout_Layout_layout_springWeight: springWeight = a.getInteger(attr, 1); break; } } a.recycle(); } public LayoutParams(int w, int h) { super(w, h); } /** * {@inheritDoc} */ public LayoutParams(ViewGroup.LayoutParams source) { super(source); } /** * {@inheritDoc} */ public LayoutParams(ViewGroup.MarginLayoutParams source) { super(source); } public void addRelation(int relation, int anchor) { relations[relation] = anchor; dirty = true; } /** * Retrieves a complete list of all supported relations, where the index * is the relation verb, and the element value is the value specified, * or "false" if it was never set. * * @return the supported relations * @see #addRelation(int, int) */ public int[] getRelations() { return relations; } public int getRelativeHeight() { return relativeHeight; } public void setRelativeHeight(int relativeHeight) { this.relativeHeight = relativeHeight; } public int getRelativeWidth() { return relativeWidth; } public void setRelativeWidth(int relativeWidth) { dirty = true; this.relativeWidth = relativeWidth; } public int getSpringWeight() { return springWeight; } public void setSpringWeight(int springWeight) { dirty = true; this.springWeight = springWeight; } public void setWidth(int width) { if (width == MATCH_PARENT || this.width == MATCH_PARENT) { dirty = true; } this.width = width; } public void setHeight(int height) { if (height == MATCH_PARENT || this.height == MATCH_PARENT) { dirty = true; } this.height = height; } } }
package beginner; import java.io.IOException; import com.sandwich.koan.Koan; import static com.sandwich.koan.constant.KoanConstants.__; import static com.sandwich.util.Assert.assertEquals; public class AboutExceptions { private void doStuff() throws IOException { throw new IOException(); } @Koan public void catchCheckedExceptions() { String s; try { doStuff(); s = "code ran normally"; } catch(IOException e) { s = "exception thrown"; } assertEquals(s, "exception thrown"); } @Koan public void useFinally() { String s = ""; try { doStuff(); s += "code ran normally"; } catch(IOException e) { s += "exception thrown"; } finally { s += " and finally ran as well"; } assertEquals(s, "exception thrown and finally ran as well"); } @Koan public void finallyWithoutCatch() { String s = ""; try { s = "code ran normally"; } finally { s += " and finally ran as well"; } assertEquals(s, "code ran normally and finally ran as well"); } private void tryCatchFinallyWithVoidReturn(StringBuilder whatHappened) { try { whatHappened.append("did something dangerous"); doStuff(); } catch(IOException e) { whatHappened.append("; the catch block executed"); return; } finally { whatHappened.append(", but so did the finally!"); } } @Koan public void finallyIsAlwaysRan() { StringBuilder whatHappened = new StringBuilder(); tryCatchFinallyWithVoidReturn(whatHappened); assertEquals(whatHappened.toString(), __); } @SuppressWarnings("finally") // this is suppressed because returning in finally block is obviously a compiler warning private String returnStatementsEverywhere(StringBuilder whatHappened) { try { whatHappened.append("try"); doStuff(); return "from try"; } catch (IOException e) { whatHappened.append(", catch"); return "from catch"; } finally { whatHappened.append(", finally"); // Think about how bad an idea it is to put a return statement in the finally block // DO NOT DO THIS! return "from finally"; } } @Koan public void returnInFinallyBlock() { StringBuilder whatHappened = new StringBuilder(); // Which value will be returned here? assertEquals(returnStatementsEverywhere(whatHappened), __); assertEquals(whatHappened.toString(), __); } private void doUncheckedStuff() { throw new RuntimeException(); } @Koan public void catchUncheckedExceptions() { // What do you need to do to catch the unchecked exception? doUncheckedStuff(); } @SuppressWarnings("serial") static class ParentException extends Exception {} @SuppressWarnings("serial") static class ChildException extends ParentException {} private void throwIt() throws ParentException { throw new ChildException(); } @Koan public void catchOrder() { String s = ""; try { throwIt(); } catch(ChildException e) { s = "ChildException"; } catch(ParentException e) { s = "ParentException"; } assertEquals(s, __); } }
package beginner; import static com.sandwich.koan.constant.KoanConstants.__; import static com.sandwich.util.Assert.assertEquals; import com.sandwich.koan.Koan; public class AboutPrimitives { @Koan public void wholeNumbersAreOfTypeInt() { assertEquals(getType(1), int.class); // hint: int.class } @Koan public void primitivesOfTypeIntHaveAnObjectTypeInteger() { Object number = 1; assertEquals(getType(number), Integer.class); // Primitives can be automatically changed into their object type via a process called auto-boxing // We will explore this in more detail in intermediate.AboutAutoboxing } @Koan public void integersHaveAFairlyLargeRange() { assertEquals(Integer.MIN_VALUE, -2147483648); assertEquals(Integer.MAX_VALUE, 2147483647); } @Koan public void integerSize() { assertEquals(Integer.SIZE, 32); // This is the amount of bits used to store an int } @Koan public void wholeNumbersCanAlsoBeOfTypeLong() { assertEquals(getType(1L), long.class); } @Koan public void primitivesOfTypeLongHaveAnObjectTypeLong() { Object number = 1L; assertEquals(getType(number), Long.class); } @Koan public void longsHaveALargerRangeThanInts() { assertEquals(Long.MIN_VALUE, -9223372036854775808L); assertEquals(Long.MAX_VALUE, 9223372036854775807L); } @Koan public void longSize() { assertEquals(Long.SIZE, 64); } @Koan public void wholeNumbersCanAlsoBeOfTypeShort() { assertEquals(getType((short) 1), short.class); // The '(short)' is called an explicit cast - to type 'short' } @Koan public void primitivesOfTypeShortHaveAnObjectTypeShort() { Object number = (short) 1; assertEquals(getType(number), __); } @Koan public void shortsHaveASmallerRangeThanInts() { assertEquals(Short.MIN_VALUE, __); // hint: You'll need an explicit cast assertEquals(Short.MAX_VALUE, __); } @Koan public void shortSize() { assertEquals(Short.SIZE, __); } @Koan public void wholeNumbersCanAlsoBeOfTypeByte() { assertEquals(getType((byte) 1), __); } @Koan public void primitivesOfTypeByteHaveAnObjectTypeByte() { Object number = (byte) 1; assertEquals(getType(number), __); } @Koan public void bytesHaveASmallerRangeThanShorts() { assertEquals(Byte.MIN_VALUE, __); assertEquals(Byte.MAX_VALUE, __); // Why would you use short or byte considering that you need to do explicit casts? } @Koan public void byteSize() { assertEquals(Byte.SIZE, __); } @Koan public void wholeNumbersCanAlsoBeOfTypeChar() { assertEquals(getType((char) 1), __); } @Koan public void singleCharactersAreOfTypeChar() { assertEquals(getType('a'), __); } @Koan public void primitivesOfTypeCharHaveAnObjectTypeCharacter() { Object number = (char) 1; assertEquals(getType(number), __); } @Koan public void charsCanOnlyBePositive() { assertEquals((int) Character.MIN_VALUE, __); assertEquals((int) Character.MAX_VALUE, __); // Why did we cast MIN_VALUE and MAX_VALUE to int? Try it without the cast. } @Koan public void charSize() { assertEquals(Character.SIZE, __); } @Koan public void decimalNumbersAreOfTypeDouble() { assertEquals(getType(1.0), __); } @Koan public void primitivesOfTypeDoubleCanBeDeclaredWithoutTheDecimalPoint() { assertEquals(getType(1d), __); } @Koan public void primitivesOfTypeDoubleCanBeDeclaredWithExponents() { assertEquals(getType(1e3), __); assertEquals(1.0e3, __); assertEquals(1E3, __); } @Koan public void primitivesOfTypeDoubleHaveAnObjectTypeDouble() { Object number = 1.0; assertEquals(getType(number), __); } @Koan public void doublesHaveALargeRange() { assertEquals(Double.MIN_VALUE, __); assertEquals(Double.MAX_VALUE, __); } @Koan public void doubleSize() { assertEquals(Double.SIZE, __); } @Koan public void decimalNumbersCanAlsoBeOfTypeFloat() { assertEquals(getType(1f), __); } @Koan public void primitivesOfTypeFloatCanBeDeclaredWithExponents() { assertEquals(getType(1e3f), __); assertEquals(1.0e3f, __); assertEquals(1E3f, __); } @Koan public void primitivesOfTypeFloatHaveAnObjectTypeFloat() { Object number = 1f; assertEquals(getType(number), __); } @Koan public void floatsHaveASmallerRangeThanDoubles() { assertEquals(Float.MIN_VALUE, __); assertEquals(Float.MAX_VALUE, __); } @Koan public void floatSize() { assertEquals(Float.SIZE, __); } private Class<?> getType(int value) { return int.class; } private Class<?> getType(long value) { return long.class; } private Class<?> getType(float value) { return float.class; } private Class<?> getType(double value) { return double.class; } private Class<?> getType(byte value) { return byte.class; } private Class<?> getType(char value) { return char.class; } private Class<?> getType(short value) { return short.class; } private Class<?> getType(Object value) { return value.getClass(); } }
package ai.h2o.automl; import ai.h2o.automl.strategies.initial.InitModel; import hex.Model; import hex.ModelBuilder; import water.*; import water.api.KeyV3; import water.fvec.Frame; import java.util.Arrays; /** * Initial draft of AutoML * * AutoML is a node-local driver class that is responsible for managing multiple threads * of execution in an effort to discover an optimal supervised model for some given * (dataset, response, loss) combo. */ public final class AutoML extends Keyed<AutoML> implements H2ORunnable { private final String _datasetName; // dataset name private final Frame _fr; // all learning on this frame private final int _response; // response column, -1 for no response column private final String _loss; // overarching loss to minimize (meta loss) private final long _maxTime; // maximum amount of time allotted to automl private final double _minAcc; // minimum accuracy to achieve private final boolean _ensemble; // allow ensembles? private final models[] _modelEx; // model types to exclude; e.g. don't allow DL private final boolean _allowMutations; // allow for INPLACE mutations on input frame FrameMeta _fm; // metadata for _fr private boolean _isClassification; enum models { RF, GBM, GLM, GLRM, DL, KMEANS } // consider EnumSet public AutoML(Key<AutoML> key, String datasetName, Frame fr, int response, String loss, long maxTime, double minAccuracy, boolean ensemble, String[] modelExclude, boolean tryMutations) { super(key); _datasetName=datasetName; _fr=fr; _response=response; _loss=loss; _maxTime=maxTime; _minAcc=minAccuracy; _ensemble=ensemble; _modelEx=modelExclude==null?null:new models[modelExclude.length]; if( modelExclude!=null ) for( int i=0; i<modelExclude.length; ++i ) _modelEx[i] = models.valueOf(modelExclude[i]); _allowMutations=tryMutations; } // used to launch the AutoML asynchronously @Override public void run() { learn(); } // manager thread: // 1. Do extremely cursory pass over data and gather only the most basic information. // During this pass, AutoML will learn how timely it will be to do more info // gathering on _fr. There's already a number of interesting stats available // thru the rollups, so no need to do too much too soon. // 2. Build a very dumb RF (with stopping_rounds=1, stopping_tolerance=0.01) // 3. TODO: refinement passes and strategy selection public void learn() { // step 1: gather initial frame metadata and guess the problem type _fm = new FrameMeta(_fr, _response, _datasetName).computeFrameMetaPass1(); _isClassification = _fm.isClassification(); // step 2: build a fast RF ModelBuilder initModel = selectInitial(_fm); initModel._parms._ignored_columns = _fm.ignoredCols(); Model m = build(initModel); // need to track this... System.out.println("bink"); // gather more data? build more models? start applying transforms? what next ...? } public Key<Model> getLeaderKey() { return LEADER; } public void delete() { for(Model m: models()) m.delete(); DKV.remove(MODELLIST); DKV.remove(LEADER); } private ModelBuilder selectInitial(FrameMeta fm) { // may use _isClassification so not static method return InitModel.initRF(fm._fr, fm.response()._name); } // track models built by automl public static final Key<Model> MODELLIST = Key.make(" AutoMLModelList ", (byte) 0, (byte) 2 /*builtin key*/, false); // public for the test static class ModelList extends Keyed { Key<Model>[] _models; ModelList() { super(MODELLIST); _models = new Key[0]; } @Override protected long checksum_impl() { throw H2O.fail("no such method for ModelList"); } } static Model[] models() { final Value val = DKV.get(MODELLIST); if( val==null ) return new Model[0]; ModelList ml = val.get(); Model[] models = new Model[ml._models.length]; int j=0; for( int i=0; i<ml._models.length; i++ ) { final Value model = DKV.get(ml._models[i]); if( model != null ) models[j++] = model.get(); } assert j==models.length; // All models still exist return models; } public static final Key<Model> LEADER = Key.make(" AutoMLModelLeader ", (byte) 0, (byte) 2, false); static class ModelLeader extends Keyed { Key _leader; ModelLeader() { super(LEADER); _leader = null; } @Override protected long checksum_impl() { throw H2O.fail("no such method for ModelLeader"); } } static Model leader() { final Value val = DKV.get(LEADER); if( val==null ) return null; ModelLeader ml = val.get(); final Value model = DKV.get(ml._leader); assert model!=null; // if the LEADER is in the DKV, then there better be a model! return model.get(); } private void updateLeader(Model m) { Model leader = leader(); final Key leaderKey; if (leader == null) leaderKey = m._key; else { // compare leader to m; get the key that minimizes this._loss leaderKey = leader._key; } // update the leader if needed if (leader == null || leaderKey.equals(leader._key) ) { new TAtomic<ModelLeader>() { @Override public ModelLeader atomic(ModelLeader old) { if (old == null) old = new ModelLeader(); old._leader = leaderKey; return old; } }.invoke(LEADER); } } // all model builds by AutoML call into this // expected to only ever have a single AutoML instance going at a time Model build(ModelBuilder mb) { Model m = (Model)mb.trainModel().get(); final Key<Model> modelKey = m._key; new TAtomic<ModelList>() { @Override public ModelList atomic(ModelList old) { if( old == null ) old = new ModelList(); Key[] models = old._models; old._models = Arrays.copyOf(models, models.length + 1); old._models[models.length] = modelKey; return old; } }.invoke(MODELLIST); updateLeader(m); return m; } // satisfy typing for job return type... public static class AutoMLKeyV3 extends KeyV3<Iced,AutoMLKeyV3,Job>{} @Override public Class<AutoMLKeyV3> makeSchema() { return AutoMLKeyV3.class; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.micromanager.acquisition; import ij.CompositeImage; import ij.ImagePlus; import ij.WindowManager; import ij.gui.ImageWindow; import ij.gui.Overlay; import ij.gui.StackWindow; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.Dimension; import java.util.ArrayList; import java.util.Arrays; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.DebugGraphics; import javax.swing.DefaultComboBoxModel; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSpinner; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.ScrollPaneConstants; import javax.swing.SpinnerNumberModel; import javax.swing.SpringLayout; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableModel; import mmcorej.TaggedImage; import org.json.JSONException; import org.json.JSONObject; import org.micromanager.MMStudioMainFrame; import org.micromanager.api.ImageCache; import org.micromanager.graph.ContrastPanel; import org.micromanager.utils.ImageFocusListener; import org.micromanager.utils.GUIUtils; import org.micromanager.utils.JavaUtils; import org.micromanager.utils.MDUtils; import org.micromanager.utils.NumberUtils; import org.micromanager.utils.ReportingUtils; import org.micromanager.utils.ScaleBar; /** * * @author arthur */ public class MetadataPanel extends JPanel implements ImageFocusListener { private static final String SINGLE_CHANNEL = "Single Channel"; private static final String MULTIPLE_CHANNELS = "Multiple Channels"; ; private JSplitPane CommentsSplitPane; private JCheckBox autostretchCheckBox; private JPanel multipleChannelsPanel_; private JScrollPane contrastScrollPane; private JComboBox displayModeCombo; private JLabel imageCommentsLabel; private JPanel imageCommentsPanel; private JScrollPane imageCommentsScrollPane; private JTextArea imageCommentsTextArea; private JPanel imageMetadataScrollPane; private JTable imageMetadataTable; private JScrollPane imageMetadataTableScrollPane; private JLabel jLabel1; private JLabel jLabel2; private JLabel jLabel3; private JPanel jPanel1; private JCheckBox logScaleCheckBox; private JSplitPane metadataSplitPane; private JComboBox overlayColorComboBox_; private JCheckBox rejectOutliersCB_; private JSpinner rejectPercentSpinner_; private JCheckBox showUnchangingPropertiesCheckbox; private JCheckBox sizeBarCheckBox; private JComboBox sizeBarComboBox; private JLabel summaryCommentsLabel; private JPanel summaryCommentsPane; private JScrollPane summaryCommentsScrollPane; private JTextArea summaryCommentsTextArea; private JPanel summaryMetadataPanel; private JScrollPane summaryMetadataScrollPane; private JTable summaryMetadataTable; private JTabbedPane tabbedPane; private JPanel masterContrastPanel_; private JPanel singleChannelPanel_; private CardLayout contrastPanelLayout_; private ContrastPanel singleChannelContrastPanel_; private static MetadataPanel singletonViewer_ = null; private final MetadataTableModel imageMetadataModel_; private final MetadataTableModel summaryMetadataModel_; private final String[] columnNames_ = {"Property", "Value"}; private boolean showUnchangingKeys_; private boolean updatingDisplayModeCombo_ = false; private ArrayList<ChannelControlPanel> ccpList_; private Color overlayColor_ = Color.white; private ImageWindow focusedWindow_; private boolean prevUseSingleChannelHist_ = true; /** Creates new form MetadataPanel */ public MetadataPanel(ContrastPanel cp) { singleChannelContrastPanel_ = cp; initialize(); imageMetadataModel_ = new MetadataTableModel(); summaryMetadataModel_ = new MetadataTableModel(); // ImagePlus.addImageListener(this); GUIUtils.registerImageFocusListener(this); //update(WindowManager.getCurrentImage()); imageMetadataTable.setModel(imageMetadataModel_); summaryMetadataTable.setModel(summaryMetadataModel_); addTextChangeListeners(); setDisplayState(CompositeImage.COMPOSITE); this.autostretchCheckBoxStateChanged(null); rejectPercentSpinner_.setModel(new SpinnerNumberModel(0., 0., 100., 0.1)); } public static MetadataPanel showMetadataPanel() { if (singletonViewer_ == null) { try { singletonViewer_ = new MetadataPanel((ContrastPanel) JavaUtils.getRestrictedFieldValue(new ContrastPanel(), ContrastPanel.class, "contrastPanel_")); //GUIUtils.recallPosition(singletonViewer_); } catch (NoSuchFieldException ex) { ReportingUtils.logError(ex); } } singletonViewer_.setVisible(true); return singletonViewer_; } /** 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"> private void initialize() { tabbedPane = new JTabbedPane(); singleChannelPanel_ = new JPanel(new BorderLayout()); multipleChannelsPanel_ = new JPanel(); jPanel1 = new JPanel(); displayModeCombo = new JComboBox(); jLabel1 = new JLabel(); autostretchCheckBox = new JCheckBox(); rejectOutliersCB_ = new JCheckBox(); rejectPercentSpinner_ = new JSpinner(); logScaleCheckBox = new JCheckBox(); sizeBarCheckBox = new JCheckBox(); sizeBarComboBox = new JComboBox(); overlayColorComboBox_ = new JComboBox(); contrastScrollPane = new JScrollPane(); metadataSplitPane = new JSplitPane(); imageMetadataScrollPane = new JPanel(); imageMetadataTableScrollPane = new JScrollPane(); imageMetadataTable = new JTable(); showUnchangingPropertiesCheckbox = new JCheckBox(); jLabel2 = new JLabel(); summaryMetadataPanel = new JPanel(); summaryMetadataScrollPane = new JScrollPane(); summaryMetadataTable = new JTable(); jLabel3 = new JLabel(); CommentsSplitPane = new JSplitPane(); summaryCommentsPane = new JPanel(); summaryCommentsLabel = new JLabel(); summaryCommentsScrollPane = new JScrollPane(); summaryCommentsTextArea = new JTextArea(); imageCommentsPanel = new JPanel(); imageCommentsLabel = new JLabel(); imageCommentsScrollPane = new JScrollPane(); imageCommentsTextArea = new JTextArea(); tabbedPane.setToolTipText("Examine and adjust display settings, metadata, and comments for the multi-dimensional acquisition in the frontmost window."); tabbedPane.setFocusable(false); tabbedPane.setPreferredSize(new java.awt.Dimension(400, 640)); tabbedPane.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent evt) { tabbedPaneStateChanged(evt); } }); multipleChannelsPanel_.setPreferredSize(new java.awt.Dimension(400, 594)); displayModeCombo.setModel(new DefaultComboBoxModel(new String[] { "Composite", "Color", "Grayscale" })); displayModeCombo.setToolTipText("<html>Choose display mode:<br> - Composite = Multicolor overlay<br> - Color = Single channel color view<br> - Grayscale = Single channel grayscale view</li></ul></html>"); displayModeCombo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { displayModeComboActionPerformed(evt); } }); jLabel1.setText("Display mode:"); autostretchCheckBox.setText("Autostretch"); autostretchCheckBox.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent evt) { autostretchCheckBoxStateChanged(evt); } }); rejectOutliersCB_.setText("ignore %"); rejectOutliersCB_.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { rejectOutliersCB_ActionPerformed(evt); } }); rejectPercentSpinner_.setFont(new java.awt.Font("Lucida Grande", 0, 10)); rejectPercentSpinner_.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent evt) { rejectPercentSpinner_StateChanged(evt); } }); rejectPercentSpinner_.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { rejectPercentSpinner_KeyPressed(evt); } }); logScaleCheckBox.setText("Log hist"); logScaleCheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { logScaleCheckBoxActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel1Layout.createSequentialGroup() .addContainerGap(24, Short.MAX_VALUE) .add(jLabel1) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(displayModeCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 134, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(autostretchCheckBox) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(rejectOutliersCB_) .add(6, 6, 6) .add(rejectPercentSpinner_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 63, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(logScaleCheckBox)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER) .add(autostretchCheckBox) .add(rejectOutliersCB_) .add(rejectPercentSpinner_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(logScaleCheckBox)) .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(displayModeCombo, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel1)) ); sizeBarCheckBox.setText("Scale Bar"); sizeBarCheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { sizeBarCheckBoxActionPerformed(evt); } }); sizeBarComboBox.setModel(new DefaultComboBoxModel(new String[] { "Top-Left", "Top-Right", "Bottom-Left", "Bottom-Right" })); sizeBarComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { sizeBarComboBoxActionPerformed(evt); } }); overlayColorComboBox_.setModel(new DefaultComboBoxModel(new String[] { "White", "Black", "Yellow", "Gray" })); overlayColorComboBox_.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { overlayColorComboBox_ActionPerformed(evt); } }); contrastScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); contrastScrollPane.setPreferredSize(new java.awt.Dimension(400, 4)); singleChannelPanel_.add(singleChannelContrastPanel_); contrastPanelLayout_ = new CardLayout(); masterContrastPanel_ = new JPanel(contrastPanelLayout_); masterContrastPanel_.add(multipleChannelsPanel_, MULTIPLE_CHANNELS); masterContrastPanel_.add(singleChannelPanel_, SINGLE_CHANNEL); showSingleChannelContrastPanel(); org.jdesktop.layout.GroupLayout channelsTablePanel_Layout = new org.jdesktop.layout.GroupLayout(multipleChannelsPanel_); multipleChannelsPanel_.setLayout(channelsTablePanel_Layout); channelsTablePanel_Layout.setHorizontalGroup( channelsTablePanel_Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(channelsTablePanel_Layout.createSequentialGroup() .add(sizeBarCheckBox) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(sizeBarComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 134, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(overlayColorComboBox_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 105, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(channelsTablePanel_Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(contrastScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 620, Short.MAX_VALUE)) ); channelsTablePanel_Layout.setVerticalGroup( channelsTablePanel_Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(channelsTablePanel_Layout.createSequentialGroup() .add(channelsTablePanel_Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(sizeBarCheckBox) .add(sizeBarComboBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(overlayColorComboBox_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addContainerGap(589, Short.MAX_VALUE)) .add(channelsTablePanel_Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(channelsTablePanel_Layout.createSequentialGroup() .add(79, 79, 79) .add(contrastScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 571, Short.MAX_VALUE))) ); tabbedPane.addTab("Channels", masterContrastPanel_); metadataSplitPane.setBorder(null); metadataSplitPane.setOrientation(JSplitPane.VERTICAL_SPLIT); imageMetadataTable.setModel(new DefaultTableModel( new Object [][] { }, new String [] { "Property", "Value" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class }; boolean[] canEdit = new boolean [] { false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); imageMetadataTable.setToolTipText("Metadata tags for each individual image"); imageMetadataTable.setDebugGraphicsOptions(DebugGraphics.NONE_OPTION); imageMetadataTable.setDoubleBuffered(true); imageMetadataTableScrollPane.setViewportView(imageMetadataTable); showUnchangingPropertiesCheckbox.setText("Show unchanging properties"); showUnchangingPropertiesCheckbox.setToolTipText("Show/hide properties that are the same for all images in the acquisition"); showUnchangingPropertiesCheckbox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { showUnchangingPropertiesCheckboxActionPerformed(evt); } }); jLabel2.setText("Per-image properties"); org.jdesktop.layout.GroupLayout imageMetadataScrollPaneLayout = new org.jdesktop.layout.GroupLayout(imageMetadataScrollPane); imageMetadataScrollPane.setLayout(imageMetadataScrollPaneLayout); imageMetadataScrollPaneLayout.setHorizontalGroup( imageMetadataScrollPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(imageMetadataTableScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 620, Short.MAX_VALUE) .add(org.jdesktop.layout.GroupLayout.TRAILING, imageMetadataScrollPaneLayout.createSequentialGroup() .add(jLabel2) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 308, Short.MAX_VALUE) .add(showUnchangingPropertiesCheckbox)) ); imageMetadataScrollPaneLayout.setVerticalGroup( imageMetadataScrollPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(imageMetadataScrollPaneLayout.createSequentialGroup() .add(imageMetadataScrollPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(showUnchangingPropertiesCheckbox) .add(jLabel2)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(imageMetadataTableScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 517, Short.MAX_VALUE)) ); metadataSplitPane.setRightComponent(imageMetadataScrollPane); summaryMetadataPanel.setMinimumSize(new java.awt.Dimension(0, 100)); summaryMetadataPanel.setPreferredSize(new java.awt.Dimension(539, 100)); summaryMetadataScrollPane.setMinimumSize(new java.awt.Dimension(0, 0)); summaryMetadataScrollPane.setPreferredSize(new java.awt.Dimension(454, 80)); summaryMetadataTable.setModel(new DefaultTableModel( new Object [][] { {null, null}, {null, null}, {null, null}, {null, null} }, new String [] { "Property", "Value" } ) { boolean[] canEdit = new boolean [] { false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); summaryMetadataTable.setToolTipText("Metadata tags for the whole acquisition"); summaryMetadataScrollPane.setViewportView(summaryMetadataTable); jLabel3.setText("Acquisition properties"); org.jdesktop.layout.GroupLayout summaryMetadataPanelLayout = new org.jdesktop.layout.GroupLayout(summaryMetadataPanel); summaryMetadataPanel.setLayout(summaryMetadataPanelLayout); summaryMetadataPanelLayout.setHorizontalGroup( summaryMetadataPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, summaryMetadataScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 620, Short.MAX_VALUE) .add(summaryMetadataPanelLayout.createSequentialGroup() .add(jLabel3) .addContainerGap()) ); summaryMetadataPanelLayout.setVerticalGroup( summaryMetadataPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, summaryMetadataPanelLayout.createSequentialGroup() .add(jLabel3) .add(4, 4, 4) .add(summaryMetadataScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); metadataSplitPane.setLeftComponent(summaryMetadataPanel); tabbedPane.addTab("Metadata", metadataSplitPane); CommentsSplitPane.setBorder(null); CommentsSplitPane.setDividerLocation(200); CommentsSplitPane.setOrientation(JSplitPane.VERTICAL_SPLIT); summaryCommentsLabel.setText("Acquisition comments:"); summaryCommentsTextArea.setColumns(20); summaryCommentsTextArea.setLineWrap(true); summaryCommentsTextArea.setRows(1); summaryCommentsTextArea.setTabSize(3); summaryCommentsTextArea.setToolTipText("Enter your comments for the whole acquisition here"); summaryCommentsTextArea.setWrapStyleWord(true); summaryCommentsScrollPane.setViewportView(summaryCommentsTextArea); org.jdesktop.layout.GroupLayout summaryCommentsPaneLayout = new org.jdesktop.layout.GroupLayout(summaryCommentsPane); summaryCommentsPane.setLayout(summaryCommentsPaneLayout); summaryCommentsPaneLayout.setHorizontalGroup( summaryCommentsPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(summaryCommentsPaneLayout.createSequentialGroup() .add(summaryCommentsLabel) .addContainerGap(491, Short.MAX_VALUE)) .add(summaryCommentsScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 620, Short.MAX_VALUE) ); summaryCommentsPaneLayout.setVerticalGroup( summaryCommentsPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(summaryCommentsPaneLayout.createSequentialGroup() .add(summaryCommentsLabel) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(summaryCommentsScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 177, Short.MAX_VALUE)) ); CommentsSplitPane.setLeftComponent(summaryCommentsPane); imageCommentsPanel.setPreferredSize(new java.awt.Dimension(500, 300)); imageCommentsLabel.setText("Per-image comments:"); imageCommentsTextArea.setColumns(20); imageCommentsTextArea.setLineWrap(true); imageCommentsTextArea.setRows(1); imageCommentsTextArea.setTabSize(3); imageCommentsTextArea.setToolTipText("Comments for each image may be entered here."); imageCommentsTextArea.setWrapStyleWord(true); imageCommentsScrollPane.setViewportView(imageCommentsTextArea); org.jdesktop.layout.GroupLayout imageCommentsPanelLayout = new org.jdesktop.layout.GroupLayout(imageCommentsPanel); imageCommentsPanel.setLayout(imageCommentsPanelLayout); imageCommentsPanelLayout.setHorizontalGroup( imageCommentsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(imageCommentsPanelLayout.createSequentialGroup() .add(imageCommentsLabel) .add(400, 400, 400)) .add(imageCommentsScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 620, Short.MAX_VALUE) ); imageCommentsPanelLayout.setVerticalGroup( imageCommentsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(imageCommentsPanelLayout.createSequentialGroup() .add(imageCommentsLabel) .add(0, 0, 0) .add(imageCommentsScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 429, Short.MAX_VALUE)) ); CommentsSplitPane.setRightComponent(imageCommentsPanel); tabbedPane.addTab("Comments", CommentsSplitPane); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .addContainerGap() .add(tabbedPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 625, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .addContainerGap() .add(tabbedPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 680, Short.MAX_VALUE) .addContainerGap()) ); } private void displayModeComboActionPerformed(java.awt.event.ActionEvent evt) { if (!updatingDisplayModeCombo_) { setDisplayState(displayModeCombo.getSelectedIndex() + 1); } } private void showUnchangingPropertiesCheckboxActionPerformed(java.awt.event.ActionEvent evt) { showUnchangingKeys_ = showUnchangingPropertiesCheckbox.isSelected(); update(WindowManager.getCurrentImage()); } private void tabbedPaneStateChanged(ChangeEvent evt) { try { update(WindowManager.getCurrentImage()); } catch (Exception e) { } } private void sizeBarCheckBoxActionPerformed(java.awt.event.ActionEvent evt) { showSizeBar(); } private void sizeBarComboBoxActionPerformed(java.awt.event.ActionEvent evt) { showSizeBar(); } private void overlayColorComboBox_ActionPerformed(java.awt.event.ActionEvent evt) { if ((overlayColorComboBox_.getSelectedItem()).equals("Black")) { overlayColor_ = Color.black; } else if ((overlayColorComboBox_.getSelectedItem()).equals("White")) { overlayColor_ = Color.white; } else if ((overlayColorComboBox_.getSelectedItem()).equals("Yellow")) { overlayColor_ = Color.yellow; } else if ((overlayColorComboBox_.getSelectedItem()).equals("Gray")) { overlayColor_ = Color.gray; } showSizeBar(); } private void logScaleCheckBoxActionPerformed(java.awt.event.ActionEvent evt) { for (ChannelControlPanel ccp : ccpList_) { ccp.setLogScale(logScaleCheckBox.isSelected()); } updateAndDrawHistograms(); } private void rejectOutliersCB_ActionPerformed(java.awt.event.ActionEvent evt) { rejectPercentSpinner_.setEnabled(rejectOutliersCB_.isSelected() && autostretchCheckBox.isSelected()); updateAndDrawHistograms(); } private void rejectPercentSpinner_StateChanged(ChangeEvent evt) { updateAndDrawHistograms(); } private void autostretchCheckBoxStateChanged(ChangeEvent evt) { rejectOutliersCB_.setEnabled(autostretchCheckBox.isSelected()); boolean rejectem = rejectOutliersCB_.isSelected() && autostretchCheckBox.isSelected(); rejectPercentSpinner_.setEnabled(rejectem); updateAndDrawHistograms(); } private void rejectPercentSpinner_KeyPressed(java.awt.event.KeyEvent evt) { updateAndDrawHistograms(); } public ContrastPanel getSingleChannelContrastPanel() { return singleChannelContrastPanel_; } private ImagePlus getCurrentImage() { try { return WindowManager.getCurrentImage(); } catch (Exception e) { return null; } } private void setDisplayState(int state) { ImagePlus imgp = getCurrentImage(); if (imgp instanceof CompositeImage) { CompositeImage ci = (CompositeImage) imgp; ci.setMode(state); ci.updateAndDraw(); } } void setAutostretch(boolean state) { autostretchCheckBox.setSelected(state); } private void addTextChangeListeners() { summaryCommentsTextArea.getDocument() .addDocumentListener(new DocumentListener() { private void handleChange() { writeSummaryComments(WindowManager.getCurrentImage()); } public void insertUpdate(DocumentEvent e) { handleChange(); } public void removeUpdate(DocumentEvent e) { handleChange(); } public void changedUpdate(DocumentEvent e) { handleChange(); } }); imageCommentsTextArea.getDocument() .addDocumentListener(new DocumentListener() { private void handleChange() { writeImageComments(WindowManager.getCurrentImage()); } public void insertUpdate(DocumentEvent e) { handleChange(); } public void removeUpdate(DocumentEvent e) { handleChange(); } public void changedUpdate(DocumentEvent e) { handleChange(); } }); } class MetadataTableModel extends AbstractTableModel { Vector<Vector<String>> data_; MetadataTableModel() { data_ = new Vector<Vector<String>>(); } public int getRowCount() { return data_.size(); } public void addRow(Vector<String> rowData) { data_.add(rowData); } public int getColumnCount() { return 2; } public synchronized Object getValueAt(int rowIndex, int columnIndex) { if (data_.size() > rowIndex) { Vector<String> row = data_.get(rowIndex); if (row.size() > columnIndex) { return data_.get(rowIndex).get(columnIndex); } else { return ""; } } else { return ""; } } public void clear() { data_.clear(); } @Override public String getColumnName(int colIndex) { return columnNames_[colIndex]; } public synchronized void setMetadata(JSONObject md) { clear(); if (md != null) { String[] keys = MDUtils.getKeys(md); Arrays.sort(keys); for (String key : keys) { Vector<String> rowData = new Vector<String>(); rowData.add((String) key); try { rowData.add(md.getString(key)); } catch (JSONException ex) { //ReportingUtils.logError(ex); } addRow(rowData); } } fireTableDataChanged(); } } private JSONObject selectChangingTags(ImagePlus imgp, JSONObject md) { JSONObject mdChanging = new JSONObject(); ImageCache cache = getCache(imgp); if (cache != null) { for (String key : cache.getChangingKeys()) { if (md.has(key)) { try { mdChanging.put(key, md.get(key)); } catch (JSONException ex) { try { mdChanging.put(key, ""); //ReportingUtils.logError(ex); } catch (JSONException ex1) { ReportingUtils.logError(ex1); } } } } } return mdChanging; } private boolean isHyperImage(ImagePlus imgp) { return VirtualAcquisitionDisplay.getDisplay(imgp) != null; } private AcquisitionVirtualStack getAcquisitionStack(ImagePlus imp) { VirtualAcquisitionDisplay display = VirtualAcquisitionDisplay.getDisplay(imp); if (display != null) { return display.virtualStack_; } else { return null; } } @Override public void setVisible(boolean visible) { super.setVisible(visible); } private void writeSummaryComments(ImagePlus imp) { VirtualAcquisitionDisplay acq = getVirtualAcquisitionDisplay(imp); if (acq != null) { acq.setSummaryComment(summaryCommentsTextArea.getText()); } } private void writeImageComments(ImagePlus imgp) { VirtualAcquisitionDisplay acq = getVirtualAcquisitionDisplay(imgp); if (acq != null) { acq.setImageComment(imageCommentsTextArea.getText()); } } private ImageCache getCache(ImagePlus imgp) { if (VirtualAcquisitionDisplay.getDisplay(imgp) != null) { return VirtualAcquisitionDisplay.getDisplay(imgp).imageCache_; } else { return null; } } // should be called whenever image changes or sliders are moved public void update(ImagePlus imp) { if (imp != null) { ImageWindow win = imp.getWindow(); if (win instanceof StackWindow) { if (((StackWindow) win).getAnimate()) { return; } } } int tabSelected = tabbedPane.getSelectedIndex(); if (imp == null) { imageMetadataModel_.setMetadata(null); summaryMetadataModel_.setMetadata(null); summaryCommentsTextArea.setText(null); contrastScrollPane.setViewportView(null); ccpList_ = null; if(useSingleChannelHistogram()) singleChannelContrastPanel_.clearHistogram(); else updateAndDrawHistograms(); } else { if (tabSelected == 1) { AcquisitionVirtualStack stack = getAcquisitionStack(imp); if (stack != null) { int slice = imp.getCurrentSlice(); TaggedImage taggedImg = stack.getTaggedImage(slice); if (taggedImg == null) { imageMetadataModel_.setMetadata(null); } else { JSONObject md = stack.getTaggedImage(slice).tags; if (!showUnchangingKeys_) { md = selectChangingTags(imp, md); } imageMetadataModel_.setMetadata(md); } summaryMetadataModel_.setMetadata(stack.getCache().getSummaryMetadata()); } else { imageMetadataModel_.setMetadata(null); } } else if (tabSelected == 0) { updateAndDrawHistograms(); } else if (tabSelected == 2) { VirtualAcquisitionDisplay acq = getVirtualAcquisitionDisplay(imp); if (acq != null) { imageCommentsTextArea.setText(acq.getImageComment()); } } } } private void showSizeBar() { boolean show = sizeBarCheckBox.isSelected(); ImagePlus ip = WindowManager.getCurrentImage(); if (show) { ScaleBar sizeBar = new ScaleBar(ip); if (sizeBar != null) { Overlay ol = new Overlay(); //ol.setFillColor(Color.white); // this causes the text to get a white background! ol.setStrokeColor(overlayColor_); String selected = (String) sizeBarComboBox.getSelectedItem(); if (selected.equals("Top-Right")) { sizeBar.setPosition(ScaleBar.Position.TOPRIGHT); } if (selected.equals("Top-Left")) { sizeBar.setPosition(ScaleBar.Position.TOPLEFT); } if (selected.equals("Bottom-Right")) { sizeBar.setPosition(ScaleBar.Position.BOTTOMRIGHT); } if (selected.equals("Bottom-Left")) { sizeBar.setPosition(ScaleBar.Position.BOTTOMLEFT); } sizeBar.addToOverlay(ol); ol.setStrokeColor(overlayColor_); ip.setOverlay(ol); } } ip.setHideOverlay(!show); } //Implements AWTEventListener /* * This is called, in contrast to update(), only when the ImageWindow * in focus has changed. */ public void focusReceived(ImageWindow focusedWindow) { if (focusedWindow == null) { update((ImagePlus)null); return; } focusedWindow_ = focusedWindow; ImagePlus imgp = focusedWindow.getImagePlus(); ImageCache cache = getCache(imgp); VirtualAcquisitionDisplay acq = getVirtualAcquisitionDisplay(imgp); sizeBarCheckBox.setSelected(imgp.getOverlay() != null && !imgp.getHideOverlay()); if (useSingleChannelHistogram()) singleChannelContrastPanel_.setImage(imgp); //this call loads appropriate contrast settings if (acq != null) { summaryCommentsTextArea.setText(acq.getSummaryComment()); JSONObject md = cache.getSummaryMetadata(); summaryMetadataModel_.setMetadata(md); } else { summaryCommentsTextArea.setText(null); } if (imgp instanceof CompositeImage) { CompositeImage cimp = (CompositeImage) imgp; updatingDisplayModeCombo_ = true; displayModeCombo.setSelectedIndex(cimp.getMode() - 1); updatingDisplayModeCombo_ = false; } if (acq != null) { setupChannelControls(acq); if (acq.firstImage()) if (useSingleChannelHistogram()) { singleChannelContrastPanel_.autostretch(true); singleChannelContrastPanel_.updateHistogram(); } else if (ccpList_ != null) for (ChannelControlPanel c : ccpList_) c.autoScale(); update(imgp); } } private VirtualAcquisitionDisplay getVirtualAcquisitionDisplay(ImagePlus imgp) { if (imgp == null) { return null; } return VirtualAcquisitionDisplay.getDisplay(imgp); } public synchronized void setupChannelControls(VirtualAcquisitionDisplay acq) { if (useSingleChannelHistogram() ) { showSingleChannelContrastPanel(); singleChannelContrastPanel_.setDisplay(acq); } else { showMultipleChannelsContrastPanel(); int hpHeight = 110; int nChannels = acq.getNumGrayChannels(); JPanel p = new JPanel(); p.setPreferredSize(new Dimension(200, nChannels * hpHeight)); contrastScrollPane.setViewportView(p); SpringLayout layout = new SpringLayout(); p.setLayout(layout); ccpList_ = new ArrayList<ChannelControlPanel>(); for (int i = 0; i < nChannels; ++i) { ChannelControlPanel ccp = new ChannelControlPanel(acq, i, this); layout.putConstraint(SpringLayout.NORTH, ccp, hpHeight * i, SpringLayout.NORTH, p); layout.putConstraint(SpringLayout.EAST, ccp, 0, SpringLayout.EAST, p); layout.putConstraint(SpringLayout.WEST, ccp, 0, SpringLayout.WEST, p); layout.putConstraint(SpringLayout.SOUTH, ccp, hpHeight * (i + 1), SpringLayout.NORTH, p); p.add(ccp); ccpList_.add(ccp); } updateAndDrawHistograms(); } } private Double getFractionOutliersToReject() { try { double value = 0.01 * NumberUtils.displayStringToDouble(this.rejectPercentSpinner_.getValue().toString()); return value; } catch (Exception e) { return null; } } private void drawDisplaySettings(ChannelControlPanel ccp) { ccp.drawDisplaySettings(); } private synchronized void updateAndDrawHistograms() { if (useSingleChannelHistogram() ) { singleChannelContrastPanel_.updateContrast(); } else if (ccpList_ != null) { for (ChannelControlPanel ccp : ccpList_) { updateChannelSettings(ccp); drawDisplaySettings(ccp); } } } private void updateChannelSettings(ChannelControlPanel ccp) { Double fractionOutliersToReject = getFractionOutliersToReject(); if (fractionOutliersToReject != null) { ccp.setFractionToReject(fractionOutliersToReject); } ccp.setAutostretch(autostretchCheckBox.isSelected()); ccp.setRejectOutliers(rejectOutliersCB_.isSelected() && autostretchCheckBox.isSelected()); ccp.updateChannelSettings(); } private boolean useSingleChannelHistogram() { if (focusedWindow_ == null) return prevUseSingleChannelHist_; ImagePlus imgp = focusedWindow_.getImagePlus(); if (imgp == null ) return prevUseSingleChannelHist_; VirtualAcquisitionDisplay vad = getVirtualAcquisitionDisplay(imgp); if (vad != null) prevUseSingleChannelHist_ = (vad.getNumChannels()== 1); return prevUseSingleChannelHist_; } private void showSingleChannelContrastPanel() { contrastPanelLayout_.show(masterContrastPanel_, SINGLE_CHANNEL); } private void showMultipleChannelsContrastPanel() { contrastPanelLayout_.show(masterContrastPanel_, MULTIPLE_CHANNELS); } }
package com.jediterm.terminal.ui; import com.google.common.base.Ascii; import com.google.common.base.Predicate; import com.google.common.base.Supplier; import com.google.common.collect.Lists; import com.jediterm.terminal.*; import com.jediterm.terminal.TextStyle.Option; import com.jediterm.terminal.emulator.ColorPalette; import com.jediterm.terminal.emulator.charset.CharacterSets; import com.jediterm.terminal.emulator.mouse.MouseMode; import com.jediterm.terminal.emulator.mouse.TerminalMouseListener; import com.jediterm.terminal.model.*; import com.jediterm.terminal.ui.settings.SettingsProvider; import com.jediterm.terminal.util.Pair; import org.apache.log4j.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.*; import java.awt.datatransfer.*; import java.awt.event.*; import java.awt.font.TextHitInfo; import java.awt.im.InputMethodRequests; import java.awt.image.BufferedImage; import java.awt.image.ImageObserver; import java.io.IOException; import java.lang.ref.WeakReference; import java.text.AttributedCharacterIterator; import java.text.CharacterIterator; import java.util.List; public class TerminalPanel extends JComponent implements TerminalDisplay, ClipboardOwner, TerminalActionProvider { private static final Logger LOG = Logger.getLogger(TerminalPanel.class); private static final long serialVersionUID = -1048763516632093014L; private static final double FPS = 50; public static final double SCROLL_SPEED = 0.05; private final Component myTerminalPanel = this; /*font related*/ private Font myNormalFont; private Font myItalicFont; private Font myBoldFont; private Font myBoldItalicFont; private int myDescent = 0; protected Dimension myCharSize = new Dimension(); private boolean myMonospaced; protected Dimension myTermSize = new Dimension(80, 24); private TerminalStarter myTerminalStarter = null; private MouseMode myMouseMode = MouseMode.MOUSE_REPORTING_NONE; private Point mySelectionStartPoint = null; private TerminalSelection mySelection = null; private Clipboard myClipboard; private TerminalPanelListener myTerminalPanelListener; private SettingsProvider mySettingsProvider; final private TerminalTextBuffer myTerminalTextBuffer; final private StyleState myStyleState; /*scroll and cursor*/ final private TerminalCursor myCursor = new TerminalCursor(); private final BoundedRangeModel myBoundedRangeModel = new DefaultBoundedRangeModel(0, 80, 0, 80); protected int myClientScrollOrigin; protected KeyListener myKeyListener; private long myLastCursorChange; private boolean myCursorIsShown; private long myLastResize; private boolean myScrollingEnabled = true; private String myWindowTitle = "Terminal"; private TerminalActionProvider myNextActionProvider; private String myInputMethodUncommitedChars; public TerminalPanel(@NotNull SettingsProvider settingsProvider, @NotNull TerminalTextBuffer terminalTextBuffer, @NotNull StyleState styleState) { mySettingsProvider = settingsProvider; myTerminalTextBuffer = terminalTextBuffer; myStyleState = styleState; myTermSize.width = terminalTextBuffer.getWidth(); myTermSize.height = terminalTextBuffer.getHeight(); updateScrolling(); enableEvents(AWTEvent.KEY_EVENT_MASK | AWTEvent.INPUT_METHOD_EVENT_MASK); enableInputMethods(true); } @Deprecated protected void reinitFontAndResize() { initFont(); sizeTerminalFromComponent(); } protected void initFont() { myNormalFont = createFont(); myBoldFont = myNormalFont.deriveFont(Font.BOLD); myItalicFont = myNormalFont.deriveFont(Font.ITALIC); myBoldItalicFont = myBoldFont.deriveFont(Font.ITALIC); establishFontMetrics(); } public void init() { initFont(); setUpClipboard(); setPreferredSize(new Dimension(getPixelWidth(), getPixelHeight())); setFocusable(true); enableInputMethods(true); setFocusTraversalKeysEnabled(false); addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseDragged(final MouseEvent e) { if (!isLocalMouseAction(e)) { return; } final Point charCoords = panelToCharCoords(e.getPoint()); if (mySelection == null) { // prevent unlikely case where drag started outside terminal panel if (mySelectionStartPoint == null) { mySelectionStartPoint = charCoords; } mySelection = new TerminalSelection(new Point(mySelectionStartPoint)); } repaint(); mySelection.updateEnd(charCoords); if (mySettingsProvider.copyOnSelect()) { handleCopy(false); } if (e.getPoint().y < 0) { moveScrollBar((int) ((e.getPoint().y) * SCROLL_SPEED)); } if (e.getPoint().y > getPixelHeight()) { moveScrollBar((int) ((e.getPoint().y - getPixelHeight()) * SCROLL_SPEED)); } } }); addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { if (isLocalMouseAction(e)) { int notches = e.getWheelRotation(); moveScrollBar(notches); } } }); addMouseListener(new MouseAdapter() { @Override public void mousePressed(final MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { if (e.getClickCount() == 1) { mySelectionStartPoint = panelToCharCoords(e.getPoint()); mySelection = null; repaint(); } } } @Override public void mouseReleased(final MouseEvent e) { requestFocusInWindow(); repaint(); } @Override public void mouseClicked(final MouseEvent e) { requestFocusInWindow(); if (e.getButton() == MouseEvent.BUTTON1 && isLocalMouseAction(e)) { int count = e.getClickCount(); if (count == 1) { // do nothing } else if (count == 2) { // select word final Point charCoords = panelToCharCoords(e.getPoint()); Point start = SelectionUtil.getPreviousSeparator(charCoords, myTerminalTextBuffer); Point stop = SelectionUtil.getNextSeparator(charCoords, myTerminalTextBuffer); mySelection = new TerminalSelection(start); mySelection.updateEnd(stop); if (mySettingsProvider.copyOnSelect()) { handleCopy(false); } } else if (count == 3) { // select line final Point charCoords = panelToCharCoords(e.getPoint()); int startLine = charCoords.y; while (startLine > -getScrollBuffer().getLineCount() && myTerminalTextBuffer.getLine(startLine - 1).isWrapped()) { startLine } int endLine = charCoords.y; while (endLine < myTerminalTextBuffer.getHeight() && myTerminalTextBuffer.getLine(endLine).isWrapped()) { endLine++; } mySelection = new TerminalSelection(new Point(0, startLine)); mySelection.updateEnd(new Point(myTermSize.width, endLine)); if (mySettingsProvider.copyOnSelect()) { handleCopy(false); } } } else if (e.getButton() == MouseEvent.BUTTON2 && mySettingsProvider.pasteOnMiddleMouseClick() && isLocalMouseAction(e)) { handlePaste(); } else if (e.getButton() == MouseEvent.BUTTON3) { JPopupMenu popup = createPopupMenu(); popup.show(e.getComponent(), e.getX(), e.getY()); } repaint(); } }); addComponentListener(new ComponentAdapter() { @Override public void componentResized(final ComponentEvent e) { myLastResize = System.currentTimeMillis(); sizeTerminalFromComponent(); } }); myBoundedRangeModel.addChangeListener(new ChangeListener() { public void stateChanged(final ChangeEvent e) { myClientScrollOrigin = myBoundedRangeModel.getValue(); } }); Timer redrawTimer = new Timer((int) (1000 / FPS), new WeakRedrawTimer(this)); setDoubleBuffered(true); redrawTimer.start(); repaint(); } public boolean isLocalMouseAction(MouseEvent e) { return mySettingsProvider.forceActionOnMouseReporting() || (isMouseReporting() == e.isShiftDown()); } public boolean isRemoteMouseAction(MouseEvent e) { return isMouseReporting() && !e.isShiftDown(); } protected boolean isRetina() { return UIUtil.isRetina(); } static class WeakRedrawTimer implements ActionListener { private WeakReference<TerminalPanel> ref; public WeakRedrawTimer(TerminalPanel terminalPanel) { this.ref = new WeakReference<TerminalPanel>(terminalPanel); } @Override public void actionPerformed(ActionEvent e) { TerminalPanel terminalPanel = ref.get(); if (terminalPanel != null) { try { terminalPanel.redraw(); } catch (Exception ex) { LOG.error("Error while terminal panel redraw", ex); } } else { // terminalPanel was garbage collected Timer timer = (Timer) e.getSource(); timer.removeActionListener(this); timer.stop(); } } } @Override public void terminalMouseModeSet(MouseMode mode) { myMouseMode = mode; } private boolean isMouseReporting() { return myMouseMode != MouseMode.MOUSE_REPORTING_NONE; } private void scrollToBottom() { myBoundedRangeModel.setValue(myTermSize.height); } private void moveScrollBar(int k) { myBoundedRangeModel.setValue(myBoundedRangeModel.getValue() + k); } protected Font createFont() { return mySettingsProvider.getTerminalFont(); } protected Point panelToCharCoords(final Point p) { int x = Math.min(p.x / myCharSize.width, getColumnCount() - 1); x = Math.max(0, x); int y = Math.min(p.y / myCharSize.height, getRowCount() - 1) + myClientScrollOrigin; return new Point(x, y); } protected Point charToPanelCoords(final Point p) { return new Point(p.x * myCharSize.width, (p.y - myClientScrollOrigin) * myCharSize.height); } void setUpClipboard() { myClipboard = Toolkit.getDefaultToolkit().getSystemSelection(); if (myClipboard == null) { myClipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); } } protected void copySelection(final Point selectionStart, final Point selectionEnd) { if (selectionStart == null || selectionEnd == null) { return; } final String selectionText = SelectionUtil .getSelectionText(selectionStart, selectionEnd, myTerminalTextBuffer); if (selectionText.length() != 0) { try { setCopyContents(new StringSelection(selectionText)); } catch (final IllegalStateException e) { LOG.error("Could not set clipboard:", e); } } } protected void setCopyContents(StringSelection selection) { myClipboard.setContents(selection, this); } protected void pasteSelection() { final String selection = getClipboardString(); if (selection == null) { return; } try { myTerminalStarter.sendString(selection); } catch (RuntimeException e) { LOG.info(e); } } private String getClipboardString() { try { return getClipboardContent(); } catch (final Exception e) { LOG.info(e); } return null; } protected String getClipboardContent() throws IOException, UnsupportedFlavorException { try { return (String) myClipboard.getData(DataFlavor.stringFlavor); } catch (Exception e) { LOG.info(e); return null; } } /* Do not care */ public void lostOwnership(final Clipboard clipboard, final Transferable contents) { } private void drawImage(Graphics2D gfx, BufferedImage image) { drawImage(gfx, image, 0, 0, myTerminalPanel); } protected void drawImage(Graphics2D gfx, BufferedImage image, int x, int y, ImageObserver observer) { gfx.drawImage(image, x, y, image.getWidth(), image.getHeight(), observer); } private Pair<BufferedImage, Graphics2D> createAndInitImage(int width, int height) { BufferedImage image = createBufferedImage(width, height); Graphics2D gfx = image.createGraphics(); setupAntialiasing(gfx); gfx.setColor(getBackground()); gfx.fillRect(0, 0, width, height); return Pair.create(image, gfx); } protected BufferedImage createBufferedImage(int width, int height) { return new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); } private void sizeTerminalFromComponent() { if (myTerminalStarter != null) { final int newWidth = getWidth() / myCharSize.width; final int newHeight = getHeight() / myCharSize.height; if (newHeight > 0 && newWidth > 0) { final Dimension newSize = new Dimension(newWidth, newHeight); myTerminalStarter.postResize(newSize, RequestOrigin.User); } } } public void setTerminalStarter(final TerminalStarter terminalStarter) { myTerminalStarter = terminalStarter; sizeTerminalFromComponent(); } public void setKeyListener(final KeyListener keyListener) { this.myKeyListener = keyListener; } public Dimension requestResize(final Dimension newSize, final RequestOrigin origin, int cursorY, JediTerminal.ResizeHandler resizeHandler) { if (!newSize.equals(myTermSize)) { myTerminalTextBuffer.lock(); try { myTerminalTextBuffer.resize(newSize, origin, cursorY, resizeHandler, mySelection); myTermSize = (Dimension) newSize.clone(); final Dimension pixelDimension = new Dimension(getPixelWidth(), getPixelHeight()); setPreferredSize(pixelDimension); if (myTerminalPanelListener != null) { myTerminalPanelListener.onPanelResize(pixelDimension, origin); } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { updateScrolling(); } }); } finally { myTerminalTextBuffer.unlock(); } } return new Dimension(getPixelWidth(), getPixelHeight()); } public void setTerminalPanelListener(final TerminalPanelListener resizeDelegate) { myTerminalPanelListener = resizeDelegate; } private void establishFontMetrics() { final BufferedImage img = createBufferedImage(1, 1); final Graphics2D graphics = img.createGraphics(); graphics.setFont(myNormalFont); final float lineSpace = mySettingsProvider.getLineSpace(); final FontMetrics fo = graphics.getFontMetrics(); myDescent = fo.getDescent(); myCharSize.width = fo.charWidth('W'); myCharSize.height = fo.getHeight() + (int) (lineSpace * 2); myDescent += lineSpace; myMonospaced = isMonospaced(fo); if (!myMonospaced) { LOG.info("WARNING: Font " + myNormalFont.getName() + " is non-monospaced"); } img.flush(); graphics.dispose(); } private static boolean isMonospaced(FontMetrics fontMetrics) { boolean isMonospaced = true; int charWidth = -1; for (int codePoint = 0; codePoint < 128; codePoint++) { if (Character.isValidCodePoint(codePoint)) { char character = (char) codePoint; if (isWordCharacter(character)) { int w = fontMetrics.charWidth(character); if (charWidth != -1) { if (w != charWidth) { isMonospaced = false; break; } } else { charWidth = w; } } } } return isMonospaced; } private static boolean isWordCharacter(char character) { return Character.isLetterOrDigit(character); } protected void setupAntialiasing(Graphics graphics) { if (graphics instanceof Graphics2D) { Graphics2D myGfx = (Graphics2D) graphics; final Object mode = mySettingsProvider.useAntialiasing() ? RenderingHints.VALUE_TEXT_ANTIALIAS_ON : RenderingHints.VALUE_TEXT_ANTIALIAS_OFF; final RenderingHints hints = new RenderingHints( RenderingHints.KEY_TEXT_ANTIALIASING, mode); myGfx.setRenderingHints(hints); } } @Override public Color getBackground() { return getPalette().getColor(myStyleState.getBackground()); } @Override public Color getForeground() { return getPalette().getColor(myStyleState.getForeground()); } @Override public void paintComponent(final Graphics g) { final Graphics2D gfx = (Graphics2D) g; gfx.setColor(getBackground()); gfx.fillRect(0, 0, getWidth(), getHeight()); myTerminalTextBuffer.processHistoryAndScreenLines(myClientScrollOrigin, new StyledTextConsumer() { @Override public void consume(int x, int y, @NotNull TextStyle style, @NotNull CharBuffer characters, int startRow) { int row = y - startRow; drawCharacters(x, row, style, characters, gfx); if (mySelection != null) { Pair<Integer, Integer> interval = mySelection.intersect(x, row + myClientScrollOrigin, characters.getLength()); if (interval != null) { TextStyle selectionStyle = getSelectionStyle(style); drawCharacters(interval.first, row, selectionStyle, characters.subBuffer(interval.first - x, interval.second), gfx); } } } }); int cursorY = myCursor.getCoordY(); if (myClientScrollOrigin + getRowCount() > cursorY) { myCursor.changeStateIfNeeded(); int cursorX = myCursor.getCoordX(); TextStyle s = myTerminalTextBuffer.getStyleAt(cursorX, cursorY); char c = myTerminalTextBuffer.getBuffersCharAt(cursorX, cursorY); TextStyle normalStyle = s != null ? s : myStyleState.getCurrent(); myCursor.drawCursor(c, gfx, inSelection(cursorX, cursorY) ? getSelectionStyle(normalStyle) : normalStyle, getInversedStyle(normalStyle)); } drawInputMethodUncommitedChars(gfx); } private TextStyle getSelectionStyle(TextStyle style) { TextStyle selectionStyle = style.clone(); if (mySettingsProvider.useInverseSelectionColor()) { selectionStyle = getInversedStyle(style); } else { TextStyle mySelectionStyle = mySettingsProvider.getSelectionColor(); selectionStyle.setBackground(mySelectionStyle.getBackground()); selectionStyle.setForeground(mySelectionStyle.getForeground()); } return selectionStyle; } private void drawInputMethodUncommitedChars(Graphics2D gfx) { if (myInputMethodUncommitedChars != null && myInputMethodUncommitedChars.length() > 0) { int x = myCursor.getCoordX() * myCharSize.width; int y = (myCursor.getCoordY()) * myCharSize.height - 2; int len = (myInputMethodUncommitedChars.length()) * myCharSize.width; gfx.setColor(getBackground()); gfx.fillRect(x, (myCursor.getCoordY() - 1) * myCharSize.height, len, myCharSize.height); gfx.setColor(getForeground()); gfx.setFont(myNormalFont); gfx.drawString(myInputMethodUncommitedChars, x, y); Stroke saved = gfx.getStroke(); BasicStroke dotted = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, new float[]{0, 2, 0, 2}, 0); gfx.setStroke(dotted); gfx.drawLine(x, y, x + len, y); gfx.setStroke(saved); } } private boolean inSelection(int x, int y) { return mySelection != null && mySelection.contains(new Point(x, y)); } @Override public void processKeyEvent(final KeyEvent e) { handleKeyEvent(e); e.consume(); } public void handleKeyEvent(KeyEvent e) { final int id = e.getID(); if (id == KeyEvent.KEY_PRESSED) { myKeyListener.keyPressed(e); } else if (id == KeyEvent.KEY_RELEASED) { /* keyReleased(e); */ } else if (id == KeyEvent.KEY_TYPED) { myKeyListener.keyTyped(e); } } public int getPixelWidth() { return myCharSize.width * myTermSize.width; } public int getPixelHeight() { return myCharSize.height * myTermSize.height; } public int getColumnCount() { return myTermSize.width; } public int getRowCount() { return myTermSize.height; } public String getWindowTitle() { return myWindowTitle; } public void addTerminalMouseListener(final TerminalMouseListener listener) { addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (mySettingsProvider.enableMouseReporting() && isRemoteMouseAction(e)) { Point p = panelToCharCoords(e.getPoint()); listener.mousePressed(p.x, p.y, e); } } @Override public void mouseReleased(MouseEvent e) { if (mySettingsProvider.enableMouseReporting() && isRemoteMouseAction(e)) { Point p = panelToCharCoords(e.getPoint()); listener.mouseReleased(p.x, p.y, e); } } }); addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { if (mySettingsProvider.enableMouseReporting() && isRemoteMouseAction(e)) { mySelection = null; Point p = panelToCharCoords(e.getPoint()); listener.mouseWheelMoved(p.x, p.y, e); } } }); addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseMoved(MouseEvent e) { if (mySettingsProvider.enableMouseReporting() && isRemoteMouseAction(e)) { Point p = panelToCharCoords(e.getPoint()); listener.mouseMoved(p.x, p.y, e); } } @Override public void mouseDragged(MouseEvent e) { if (mySettingsProvider.enableMouseReporting() && isRemoteMouseAction(e)) { Point p = panelToCharCoords(e.getPoint()); listener.mouseDragged(p.x, p.y, e); } } }); } public void initKeyHandler() { setKeyListener(new TerminalKeyHandler()); } public class TerminalCursor { private boolean myCursorHasChanged; protected Point myCursorCoordinates = new Point(); private boolean myShouldDrawCursor = true; private boolean myBlinking = true; private boolean calculateIsCursorShown() { if (!isBlinking()) { return true; } return myCursorHasChanged || myCursorIsShown; } private boolean cursorShouldChangeBlinkState(long currentTime) { return currentTime - myLastCursorChange > mySettingsProvider.caretBlinkingMs(); } public void setX(int x) { myCursorCoordinates.x = x; myCursorHasChanged = true; } public void setY(int y) { myCursorCoordinates.y = y; myCursorHasChanged = true; } public int getCoordX() { return myCursorCoordinates.x; } public int getCoordY() { return myCursorCoordinates.y - 1 - myClientScrollOrigin; } public void setShouldDrawCursor(boolean shouldDrawCursor) { myShouldDrawCursor = shouldDrawCursor; } public boolean shouldDrawCursor() { return myShouldDrawCursor && isFocusOwner(); } private boolean noRecentResize(long time) { return time - myLastResize > mySettingsProvider.caretBlinkingMs(); } public void setBlinking(boolean blinking) { myBlinking = blinking; } public boolean isBlinking() { return myBlinking && (mySettingsProvider.caretBlinkingMs() > 0); } public void changeStateIfNeeded() { long currentTime = System.currentTimeMillis(); if (cursorShouldChangeBlinkState(currentTime)) { myCursorIsShown = !myCursorIsShown; myLastCursorChange = currentTime; myCursorHasChanged = false; } } public void drawCursor(char c, Graphics2D gfx, TextStyle style, TextStyle inversedStyle) { if (!shouldDrawCursor()) { return; } final int y = getCoordY(); final int x = getCoordX(); if (y >= 0 && y < myTermSize.height) { boolean isCursorShown = calculateIsCursorShown(); TextStyle styleToDraw = isCursorShown ? inversedStyle : style; drawCharacters(x, y, styleToDraw, new CharBuffer(c, 1), gfx); } } } private void drawImage(Graphics2D g, BufferedImage image, int x1, int y1, int x2, int y2) { drawImage(g, image, x1, y1, x2, y2, x1, y1, x2, y2); } protected void drawImage(Graphics2D g, BufferedImage image, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2) { g.drawImage(image, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, null); } private TextStyle getInversedStyle(TextStyle style) { TextStyle selectionStyle; selectionStyle = style.clone(); selectionStyle.setOption(Option.INVERSE, !selectionStyle.hasOption(Option.INVERSE)); if (selectionStyle.getForeground() == null) { selectionStyle.setForeground(myStyleState.getForeground()); } if (selectionStyle.getBackground() == null) { selectionStyle.setBackground(myStyleState.getBackground()); } return selectionStyle; } private void drawCharacters(int x, int y, TextStyle style, CharBuffer buf, Graphics2D gfx) { gfx.setColor(getPalette().getColor(myStyleState.getBackground(style.getBackgroundForRun()))); int textLength = CharacterUtils.getTextLength(buf.getBuf(), buf.getStart(), buf.getLength()); gfx.fillRect(x * myCharSize.width, y * myCharSize.height, textLength * myCharSize.width, myCharSize.height); drawChars(x, y, buf, style, gfx); gfx.setColor(getPalette().getColor(myStyleState.getForeground(style.getForegroundForRun()))); int baseLine = (y + 1) * myCharSize.height - myDescent; if (style.hasOption(TextStyle.Option.UNDERLINED)) { gfx.drawLine(x * myCharSize.width, baseLine + 1, (x + textLength) * myCharSize.width, baseLine + 1); } } /** * Draw every char in separate terminal cell to guaranty equal width for different lines. * Nevertheless to improve kerning we draw word characters as one block for monospaced fonts. */ private void drawChars(int x, int y, CharBuffer buf, TextStyle style, Graphics2D gfx) { int newBlockLen = 1; int offset = 0; int drawCharsOffset = 0; // workaround to fix Swing bad rendering of bold special chars on Linux // TODO required for italic? CharBuffer renderingBuffer; if (mySettingsProvider.DECCompatibilityMode() && style.hasOption(TextStyle.Option.BOLD)) { renderingBuffer = CharacterUtils.heavyDecCompatibleBuffer(buf); } else { renderingBuffer = buf; } while (offset + newBlockLen <= buf.getLength()) { Font font = getFontToDisplay(buf.charAt(offset + newBlockLen - 1), style); // while (myMonospaced && (offset + newBlockLen < buf.getLength()) && isWordCharacter(buf.charAt(offset + newBlockLen - 1)) // && (font == getFontToDisplay(buf.charAt(offset + newBlockLen - 1), style))) { // newBlockLen++; gfx.setFont(font); int descent = gfx.getFontMetrics(font).getDescent(); int baseLine = (y + 1) * myCharSize.height - descent; int xCoord = (x + drawCharsOffset) * myCharSize.width; int textLength = CharacterUtils.getTextLength(buf.getBuf(), buf.getStart() + offset, newBlockLen); gfx.setClip(xCoord, y * myCharSize.height, textLength * myCharSize.width, myCharSize.height); gfx.setColor(getPalette().getColor(myStyleState.getForeground(style.getForegroundForRun()))); gfx.drawChars(renderingBuffer.getBuf(), buf.getStart() + offset, newBlockLen, xCoord, baseLine); drawCharsOffset += textLength; offset += newBlockLen; newBlockLen = 1; } gfx.setClip(null); } protected Font getFontToDisplay(char c, TextStyle style) { boolean bold = style.hasOption(TextStyle.Option.BOLD); boolean italic = style.hasOption(TextStyle.Option.ITALIC); // workaround to fix Swing bad rendering of bold special chars on Linux if (bold && mySettingsProvider.DECCompatibilityMode() && CharacterSets.isDecBoxChar(c)) { return myNormalFont; } return bold ? (italic ? myBoldItalicFont : myBoldFont) : (italic ? myItalicFont : myNormalFont); } private ColorPalette getPalette() { return mySettingsProvider.getTerminalColorPalette(); } private void copyArea(Graphics2D gfx, BufferedImage image, int x, int y, int width, int height, int dx, int dy) { if (isRetina()) { Pair<BufferedImage, Graphics2D> pair = createAndInitImage(x + width, y + height); drawImage(pair.second, image, x, y, x + width, y + height ); drawImage(gfx, pair.first, x + dx, y + dy, x + dx + width, y + dy + height, //destination x, y, x + width, y + height //source ); } else { gfx.copyArea(x, y, width, height, dx, dy); } } public void redraw() { repaint(); } private void drawMargins(Graphics2D gfx, int width, int height) { gfx.setColor(getBackground()); gfx.fillRect(0, height, getWidth(), getHeight() - height); gfx.fillRect(width, 0, getWidth() - width, getHeight()); } public void scrollArea(final int scrollRegionTop, final int scrollRegionSize, int dy) { if (dy < 0) { //Moving lines off the top of the screen SwingUtilities.invokeLater(new Runnable() { @Override public void run() { updateScrolling(); } }); } mySelection = null; } private void updateScrolling() { if (myScrollingEnabled) { myBoundedRangeModel .setRangeProperties(0, myTermSize.height, -myTerminalTextBuffer.getHistoryBuffer().getLineCount(), myTermSize.height, false); } else { myBoundedRangeModel.setRangeProperties(0, myTermSize.height, 0, myTermSize.height, false); } } public void setCursor(final int x, final int y) { myCursor.setX(x); myCursor.setY(y); } public void beep() { if (mySettingsProvider.audibleBell()) { Toolkit.getDefaultToolkit().beep(); } } public BoundedRangeModel getBoundedRangeModel() { return myBoundedRangeModel; } public TerminalTextBuffer getBackBuffer() { return myTerminalTextBuffer; } public TerminalSelection getSelection() { return mySelection; } public LinesBuffer getScrollBuffer() { return myTerminalTextBuffer.getHistoryBuffer(); } @Override public void setCursorVisible(boolean shouldDrawCursor) { myCursor.setShouldDrawCursor(shouldDrawCursor); } protected JPopupMenu createPopupMenu() { JPopupMenu popup = new JPopupMenu(); TerminalAction.addToMenu(popup, this); return popup; } public void setScrollingEnabled(boolean scrollingEnabled) { myScrollingEnabled = scrollingEnabled; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { updateScrolling(); } }); } @Override public void setBlinkingCursor(boolean enabled) { myCursor.setBlinking(enabled); } public TerminalCursor getTerminalCursor() { return myCursor; } public TerminalOutputStream getTerminalOutputStream() { return myTerminalStarter; } @Override public void setWindowTitle(String name) { myWindowTitle = name; if (myTerminalPanelListener != null) { myTerminalPanelListener.onTitleChanged(myWindowTitle); } } @Override public List<TerminalAction> getActions() { return Lists.newArrayList( new TerminalAction("Copy", mySettingsProvider.getCopyKeyStrokes(), new Predicate<KeyEvent>() { @Override public boolean apply(KeyEvent input) { return handleCopy(true); } }).withMnemonicKey(KeyEvent.VK_C).withEnabledSupplier(new Supplier<Boolean>() { @Override public Boolean get() { return mySelection != null; } }), new TerminalAction("Paste", mySettingsProvider.getPasteKeyStrokes(), new Predicate<KeyEvent>() { @Override public boolean apply(KeyEvent input) { handlePaste(); return true; } }).withMnemonicKey(KeyEvent.VK_P).withEnabledSupplier(new Supplier<Boolean>() { @Override public Boolean get() { return getClipboardString() != null; } }) ); } @Override public TerminalActionProvider getNextProvider() { return myNextActionProvider; } @Override public void setNextProvider(TerminalActionProvider provider) { myNextActionProvider = provider; } private void processTerminalKeyPressed(KeyEvent e) { try { final int keycode = e.getKeyCode(); final char keychar = e.getKeyChar(); // numLock does not change the code sent by keypad VK_DELETE // although it send the char '.' if (keycode == KeyEvent.VK_DELETE && keychar == '.') { myTerminalStarter.sendBytes(new byte[]{'.'}); return; } // CTRL + Space is not handled in KeyEvent; handle it manually else if (keychar == ' ' && (e.getModifiers() & KeyEvent.CTRL_MASK) != 0) { myTerminalStarter.sendBytes(new byte[]{Ascii.NUL}); return; } final byte[] code = myTerminalStarter.getCode(keycode); if (code != null) { myTerminalStarter.sendBytes(code); if (mySettingsProvider.scrollToBottomOnTyping() && isCodeThatScrolls(keycode)) { scrollToBottom(); } } else if ((keychar & 0xff00) == 0) { final byte[] obuffer = new byte[1]; obuffer[0] = (byte) keychar; myTerminalStarter.sendBytes(obuffer); if (mySettingsProvider.scrollToBottomOnTyping()) { scrollToBottom(); } } } catch (final Exception ex) { LOG.error("Error sending key to emulator", ex); } } private static boolean isCodeThatScrolls(int keycode) { return keycode == KeyEvent.VK_UP || keycode == KeyEvent.VK_DOWN || keycode == KeyEvent.VK_LEFT || keycode == KeyEvent.VK_RIGHT || keycode == KeyEvent.VK_BACK_SPACE || keycode == KeyEvent.VK_DELETE; } private void processTerminalKeyTyped(KeyEvent e) { final char keychar = e.getKeyChar(); if ((keychar & 0xff00) != 0) { final char[] foo = new char[1]; foo[0] = keychar; try { myTerminalStarter.sendString(new String(foo)); if (mySettingsProvider.scrollToBottomOnTyping()) { scrollToBottom(); } } catch (final RuntimeException ex) { LOG.error("Error sending key to emulator", ex); } } } public class TerminalKeyHandler implements KeyListener { public TerminalKeyHandler() { } public void keyPressed(final KeyEvent e) { if (!TerminalAction.processEvent(TerminalPanel.this, e)) { processTerminalKeyPressed(e); } } public void keyTyped(final KeyEvent e) { processTerminalKeyTyped(e); } //Ignore releases public void keyReleased(KeyEvent e) { } } private void handlePaste() { pasteSelection(); } // "unselect" is needed to handle Ctrl+C copy shortcut collision with ^C signal shortcut private boolean handleCopy(boolean unselect) { if (mySelection != null) { Pair<Point, Point> points = mySelection.pointsForRun(myTermSize.width); copySelection(points.first, points.second); if (unselect) { mySelection = null; repaint(); } return true; } return false; } @Override protected void processInputMethodEvent(InputMethodEvent e) { int commitCount = e.getCommittedCharacterCount(); if (commitCount > 0) { myInputMethodUncommitedChars = null; AttributedCharacterIterator text = e.getText(); if (text != null) { //noinspection ForLoopThatDoesntUseLoopVariable for (char c = text.first(); commitCount > 0; c = text.next(), commitCount if (c >= 0x20 && c != 0x7F) { // Hack just like in javax.swing.text.DefaultEditorKit.DefaultKeyTypedAction int id = (c & 0xff00) == 0 ? KeyEvent.KEY_PRESSED : KeyEvent.KEY_TYPED; handleKeyEvent(new KeyEvent(this, id, e.getWhen(), 0, 0, c)); } } } } else { myInputMethodUncommitedChars = uncommitedChars(e.getText()); } } private static String uncommitedChars(AttributedCharacterIterator text) { StringBuilder sb = new StringBuilder(); for (char c = text.first(); c != CharacterIterator.DONE; c = text.next()) { if (c >= 0x20 && c != 0x7F) { // Hack just like in javax.swing.text.DefaultEditorKit.DefaultKeyTypedAction sb.append(c); } } return sb.toString(); } @Override public InputMethodRequests getInputMethodRequests() { return new MyInputMethodRequests(); } private class MyInputMethodRequests implements InputMethodRequests { @Override public Rectangle getTextLocation(TextHitInfo offset) { Rectangle r = new Rectangle(myCursor.getCoordX() * myCharSize.width, (myCursor.getCoordY() + 1) * myCharSize.height, 0, 0); Point p = TerminalPanel.this.getLocationOnScreen(); r.translate(p.x, p.y); return r; } @Nullable @Override public TextHitInfo getLocationOffset(int x, int y) { return null; } @Override public int getInsertPositionOffset() { return 0; } @Override public AttributedCharacterIterator getCommittedText(int beginIndex, int endIndex, AttributedCharacterIterator.Attribute[] attributes) { return null; } @Override public int getCommittedTextLength() { return 0; } @Nullable @Override public AttributedCharacterIterator cancelLatestCommittedText(AttributedCharacterIterator.Attribute[] attributes) { return null; } @Nullable @Override public AttributedCharacterIterator getSelectedText(AttributedCharacterIterator.Attribute[] attributes) { return null; } } }
package ch.usi.dag.disl.test.dispatch; import ch.usi.dag.dislreserver.netreference.NetReference; import ch.usi.dag.dislreserver.reflectiveinfo.ClassInfo; import ch.usi.dag.dislreserver.reflectiveinfo.ClassInfoResolver; import ch.usi.dag.dislreserver.reflectiveinfo.InvalidClass; import ch.usi.dag.dislreserver.remoteanalysis.RemoteAnalysis; // NOTE that this class is not static anymore public class CodeExecuted extends RemoteAnalysis { long totalExecutedBytecodes = 0; public void bytecodesExecuted(int count) { totalExecutedBytecodes += count; } public void testingBasic(boolean b, byte by, char c, short s, int i, long l, float f, double d) { if(b != true) { throw new RuntimeException("Incorect transfer of boolean"); } if(by != (byte) 125) { throw new RuntimeException("Incorect transfer of byte"); } if(c != 'š') { throw new RuntimeException("Incorect transfer of char"); } if(s != (short) 50000) { throw new RuntimeException("Incorect transfer of short"); } if(i != 100000) { throw new RuntimeException("Incorect transfer of int"); } if(l != 10000000000L) { throw new RuntimeException("Incorect transfer of long"); } if(f != 1.5F) { throw new RuntimeException("Incorect transfer of float"); } if(d != 2.5) { throw new RuntimeException("Incorect transfer of double"); } } public static void testingAdvanced(String s, Object o, Class<?> c, int classId) { if(! s.equals("ěščřžýáíé")) { throw new RuntimeException("Incorect transfer of String"); } long objId = ((NetReference)o).getObjectId(); // object id should be non 0 if(! (o instanceof NetReference) || objId == 0) { throw new RuntimeException("Incorect transfer of Object"); } System.out.println("Received object id: " + objId); // class id should be non 0 if(! c.equals(InvalidClass.class) || classId == 0) { throw new RuntimeException("Incorect transfer of Class"); } System.out.println("Received class id: " + classId); } public static void printClassInfo(ClassInfo ci) { if(ci == null) { System.out.println("null"); return; } System.out.println("sig: " + ci.getSignature()); System.out.println("gen: " + ci.getGenericStr()); } public static void testingAdvanced2(Object o1, Object o2, Object o3, Object o4, Class<?> class1, int cid1, Class<?> class2, int cid2, Class<?> class3, int cid3, Class<?> class4, int cid4) { System.out.println("* o1 class *"); printClassInfo(((NetReference)o1).getClassInfo()); System.out.println("* o2 class *"); printClassInfo(((NetReference)o2).getClassInfo()); System.out.println("* o3 class *"); printClassInfo(((NetReference)o3).getClassInfo()); System.out.println("* o4 class *"); printClassInfo(((NetReference)o4).getClassInfo()); System.out.println("* class 1 *"); printClassInfo(ClassInfoResolver.getClass(cid1)); System.out.println("* class 2 *"); printClassInfo(ClassInfoResolver.getClass(cid2)); System.out.println("* class 3 *"); printClassInfo(ClassInfoResolver.getClass(cid3)); System.out.println("* class 4 *"); printClassInfo(ClassInfoResolver.getClass(cid4)); } public void atExit() { System.out.println("Total number of executed bytecodes: " + totalExecutedBytecodes); } public void objectFree(NetReference netRef) { System.out.println("Object free for id " + netRef.getObjectId()); } }
package org.xwalk.core; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.Signature; import android.os.Build; import android.util.Log; import dalvik.system.DexClassLoader; import java.io.File; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.LinkedList; import java.util.HashMap; import junit.framework.Assert; /** * The appropriate invocation order is: * handlePreInit() - attachXWalkCore() - dockXWalkCore() - handlePostInit() - over */ class XWalkCoreWrapper { private static final String XWALK_APK_PACKAGE = "org.xwalk.core"; private static final String WRAPPER_PACKAGE = "org.xwalk.core"; private static final String BRIDGE_PACKAGE = "org.xwalk.core.internal"; private static final String TAG = "XWalkLib"; private static final String XWALK_CORE_EXTRACTED_DIR = "extracted_xwalkcore"; private static final String XWALK_CORE_CLASSES_DEX = "classes.dex"; private static final String OPTIMIZED_DEX_DIR = "dex"; private static final String META_XWALK_ENABLE_DOWNLOAD_MODE = "xwalk_enable_download_mode"; private static XWalkCoreWrapper sProvisionalInstance; private static XWalkCoreWrapper sInstance; private static LinkedList<String> sReservedActivities = new LinkedList<String>(); private static HashMap<String, LinkedList<ReservedAction> > sReservedActions = new HashMap<String, LinkedList<ReservedAction> >(); private static class ReservedAction { ReservedAction(Object object) { mObject = object; } ReservedAction(Class<?> clazz) { mClass = clazz; } ReservedAction(ReflectMethod method) { mMethod = method; if (method.getArguments() != null) { mArguments = Arrays.copyOf(method.getArguments(), method.getArguments().length); } } Object mObject; Class<?> mClass; ReflectMethod mMethod; Object[] mArguments; } private int mApiVersion; private int mMinApiVersion; private int mCoreStatus; private Context mWrapperContext; private Context mBridgeContext; private ClassLoader mBridgeLoader; public static XWalkCoreWrapper getInstance() { return sInstance; } public static int getCoreStatus() { if (sInstance != null) return XWalkLibraryInterface.STATUS_MATCH; if (sProvisionalInstance == null) return XWalkLibraryInterface.STATUS_PENDING; return sProvisionalInstance.mCoreStatus; } /** * This method must be invoked on the UI thread. */ public static void handlePreInit(String tag) { if (sInstance != null) return; Log.d(TAG, "Pre init xwalk core in " + tag); if (sReservedActions.containsKey(tag)) { sReservedActions.remove(tag); } else { sReservedActivities.add(tag); } sReservedActions.put(tag, new LinkedList<ReservedAction>()); } public static void reserveReflectObject(Object object) { String tag = sReservedActivities.getLast(); Log.d(TAG, "Reserve object " + object.getClass() + " to " + tag); sReservedActions.get(tag).add(new ReservedAction(object)); } public static void reserveReflectClass(Class<?> clazz) { String tag = sReservedActivities.getLast(); Log.d(TAG, "Reserve class " + clazz.toString() + " to " + tag); sReservedActions.get(tag).add(new ReservedAction(clazz)); } public static void reserveReflectMethod(ReflectMethod method) { String tag = sReservedActivities.getLast(); Log.d(TAG, "Reserve method " + method.toString() + " to " + tag); sReservedActions.get(tag).add(new ReservedAction(method)); } /** * This method must be invoked on the UI thread. */ public static void handlePostInit(String tag) { if (!sReservedActions.containsKey(tag)) return; Log.d(TAG, "Post init xwalk core in " + tag); LinkedList<ReservedAction> reservedActions = sReservedActions.get(tag); for (ReservedAction action : reservedActions) { if (action.mObject != null) { Log.d(TAG, "Init reserved object: " + action.mObject.getClass()); new ReflectMethod(action.mObject, "reflectionInit").invoke(); } else if (action.mClass != null) { Log.d(TAG, "Init reserved class: " + action.mClass.toString()); new ReflectMethod(action.mClass, "reflectionInit").invoke(); } else { Log.d(TAG, "Call reserved method: " + action.mMethod.toString()); Object[] args = action.mArguments; if (args != null) { for (int i = 0; i < args.length; ++i) { if (args[i] instanceof ReflectMethod) { args[i] = ((ReflectMethod) args[i]).invokeWithArguments(); } } } action.mMethod.invoke(args); } } sReservedActivities.remove(tag); sReservedActions.remove(tag); } public static int attachXWalkCore(Context context) { Assert.assertFalse(sReservedActivities.isEmpty()); Assert.assertNull(sInstance); Log.d(TAG, "Attach xwalk core"); sProvisionalInstance = new XWalkCoreWrapper(context, -1); if (!sProvisionalInstance.findEmbeddedCore()) { if (sProvisionalInstance.isDownloadMode()) { sProvisionalInstance.findDownloadedCore(); } else { sProvisionalInstance.findSharedCore(); } } return sProvisionalInstance.mCoreStatus; } /** * This method must be invoked on the UI thread. */ public static void dockXWalkCore() { Assert.assertNotNull(sProvisionalInstance); Assert.assertNull(sInstance); Log.d(TAG, "Dock xwalk core"); sInstance = sProvisionalInstance; sProvisionalInstance = null; sInstance.initCoreBridge(); sInstance.initXWalkView(); } /** * This method must be invoked on the UI thread. */ public static void initEmbeddedMode() { if (sInstance != null || !sReservedActivities.isEmpty()) return; Log.d(TAG, "Init embedded mode"); XWalkCoreWrapper provisionalInstance = new XWalkCoreWrapper(null, -1); if (!provisionalInstance.findEmbeddedCore()) { Assert.fail("Please have your activity extend XWalkActivity for shared mode"); } sInstance = provisionalInstance; sInstance.initCoreBridge(); } private XWalkCoreWrapper(Context context, int minApiVersion) { mApiVersion = XWalkAppVersion.API_VERSION; mMinApiVersion = (minApiVersion > 0 && minApiVersion <= mApiVersion) ? minApiVersion : mApiVersion; mCoreStatus = XWalkLibraryInterface.STATUS_PENDING; mWrapperContext = context; } private void initCoreBridge() { Log.d(TAG, "Init core bridge"); Class<?> clazz = getBridgeClass("XWalkCoreBridge"); ReflectMethod method = new ReflectMethod(clazz, "init", Context.class, Object.class); method.invoke(mBridgeContext, this); } private void initXWalkView() { Log.d(TAG, "Init xwalk view"); Class<?> clazz = getBridgeClass("XWalkViewDelegate"); ReflectMethod method = new ReflectMethod(clazz, "init", Context.class, Context.class); method.invoke(mBridgeContext, mWrapperContext); } private boolean findEmbeddedCore() { mBridgeContext = null; mBridgeLoader = XWalkCoreWrapper.class.getClassLoader(); if (!checkCoreVersion() || !checkCoreArchitecture()) { mBridgeLoader = null; return false; } Log.d(TAG, "Running in embedded mode"); mCoreStatus = XWalkLibraryInterface.STATUS_MATCH; return true; } private boolean findSharedCore() { if (!checkCorePackage()) return false; mBridgeLoader = mBridgeContext.getClassLoader(); if (!checkCoreVersion() || !checkCoreArchitecture()) { mBridgeContext = null; mBridgeLoader = null; return false; } Log.d(TAG, "Running in shared mode"); mCoreStatus = XWalkLibraryInterface.STATUS_MATCH; return true; } private boolean findDownloadedCore() { String libDir = mWrapperContext.getDir(XWALK_CORE_EXTRACTED_DIR, Context.MODE_PRIVATE). getAbsolutePath(); String dexPath = libDir + File.separator + XWALK_CORE_CLASSES_DEX; String dexOutputPath = mWrapperContext.getDir(OPTIMIZED_DEX_DIR, Context.MODE_PRIVATE). getAbsolutePath(); ClassLoader localClassLoader = ClassLoader.getSystemClassLoader(); mBridgeLoader = new DexClassLoader(dexPath, dexOutputPath, libDir, localClassLoader); if (!checkCoreVersion() || !checkCoreArchitecture()) { mBridgeLoader = null; return false; } Log.d(TAG, "Running in downloaded mode"); mCoreStatus = XWalkLibraryInterface.STATUS_MATCH; return true; } private boolean isDownloadMode() { try { PackageManager packageManager = mWrapperContext.getPackageManager(); ApplicationInfo appInfo = packageManager.getApplicationInfo( mWrapperContext.getPackageName(), PackageManager.GET_META_DATA); String enableStr = appInfo.metaData.getString(META_XWALK_ENABLE_DOWNLOAD_MODE); return enableStr.equalsIgnoreCase("enable"); } catch (NameNotFoundException | NullPointerException e) { } return false; } private boolean checkCoreVersion() { try { Class<?> clazz = getBridgeClass("XWalkCoreVersion"); int libVersion = (int) new ReflectField(clazz, "API_VERSION").get(); int minLibVersion = (int) new ReflectField(clazz, "MIN_API_VERSION").get(); Log.d(TAG, "lib version, api:" + libVersion + ", min api:" + minLibVersion); Log.d(TAG, "app version, api:" + mApiVersion + ", min api:" + mMinApiVersion); if (mMinApiVersion > libVersion) { mCoreStatus = XWalkLibraryInterface.STATUS_OLDER_VERSION; return false; } else if (mApiVersion < minLibVersion) { mCoreStatus = XWalkLibraryInterface.STATUS_NEWER_VERSION; return false; } } catch (RuntimeException e) { Log.d(TAG, "XWalk core not found"); mCoreStatus = XWalkLibraryInterface.STATUS_NOT_FOUND; return false; } Log.d(TAG, "XWalk core version matched"); return true; } private boolean checkCoreArchitecture() { try { Class<?> clazz = getBridgeClass("XWalkViewDelegate"); ReflectMethod method = new ReflectMethod(clazz, "loadXWalkLibrary", Context.class, String.class); boolean architectureMatched = false; String libDir = null; if (mBridgeContext != null) { // Only load the native library from /data/data if in shared mode and the Android // version is lower than 4.2. Android enables a system path /data/app-lib to store // native libraries starting from 4.2 and load them automatically. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) { libDir = "/data/data/" + mBridgeContext.getPackageName() + "/lib"; } architectureMatched = (boolean) method.invoke(mBridgeContext, libDir); } else { try { architectureMatched = (boolean) method.invoke(mBridgeContext, libDir); } catch (RuntimeException ex) { Log.d(TAG, ex.getLocalizedMessage()); } if (!architectureMatched && mWrapperContext != null) { libDir = mWrapperContext.getDir( XWalkLibraryInterface.PRIVATE_DATA_DIRECTORY_SUFFIX, Context.MODE_PRIVATE).toString(); architectureMatched = (boolean) method.invoke(mBridgeContext, libDir); } } if (!architectureMatched) { Log.d(TAG, "Mismatch of CPU architecture"); mCoreStatus = XWalkLibraryInterface.STATUS_ARCHITECTURE_MISMATCH; return false; } } catch (RuntimeException e) { Log.d(TAG, e.getLocalizedMessage()); mCoreStatus = XWalkLibraryInterface.STATUS_INCOMPLETE_LIBRARY; return false; } Log.d(TAG, "XWalk core architecture matched"); return true; } private boolean checkCorePackage() { if (!XWalkAppVersion.VERIFY_XWALK_APK) { Log.d(TAG, "Not verifying the package integrity of Crosswalk runtime library"); } else { try { PackageInfo packageInfo = mWrapperContext.getPackageManager().getPackageInfo( XWALK_APK_PACKAGE, PackageManager.GET_SIGNATURES); if (!verifyPackageInfo(packageInfo, XWalkAppVersion.XWALK_APK_HASH_ALGORITHM, XWalkAppVersion.XWALK_APK_HASH_CODE)) { mCoreStatus = XWalkLibraryInterface.STATUS_SIGNATURE_CHECK_ERROR; return false; } } catch (NameNotFoundException e) { Log.d(TAG, "Crosswalk package not found"); return false; } } try { mBridgeContext = mWrapperContext.createPackageContext(XWALK_APK_PACKAGE, Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY); } catch (NameNotFoundException e) { Log.d(TAG, "Crosswalk package not found"); return false; } Log.d(TAG, "Created package context for " + XWALK_APK_PACKAGE); return true; } private boolean verifyPackageInfo(PackageInfo packageInfo, String hashAlgorithm, String hashCode) { if (packageInfo.signatures == null) { Log.e(TAG, "No signature in package info"); return false; } MessageDigest md = null; try { md = MessageDigest.getInstance(hashAlgorithm); } catch (NoSuchAlgorithmException | NullPointerException e) { Assert.fail("Invalid hash algorithm"); } byte[] hashArray = hexStringToByteArray(hashCode); if (hashArray == null) { Assert.fail("Invalid hash code"); } for (int i = 0; i < packageInfo.signatures.length; ++i) { Log.d(TAG, "Checking signature " + i); byte[] binaryCert = packageInfo.signatures[i].toByteArray(); byte[] digest = md.digest(binaryCert); if (!MessageDigest.isEqual(digest, hashArray)) { Log.e(TAG, "Hash code does not match"); continue; } Log.d(TAG, "Signature passed verification"); return true; } return false; } private byte[] hexStringToByteArray(String str) { if (str == null || str.isEmpty() || str.length()%2 != 0) return null; byte[] result = new byte[str.length() / 2]; for (int i = 0; i < str.length(); i += 2) { int digit = Character.digit(str.charAt(i), 16); digit <<= 4; digit += Character.digit(str.charAt(i+1), 16); result[i/2] = (byte) digit; } return result; } public boolean isSharedMode() { return mBridgeContext != null; } public Object getBridgeObject(Object object) { try { return new ReflectMethod(object, "getBridge").invoke(); } catch (RuntimeException e) { } return null; } public Object getWrapperObject(Object object) { try { return new ReflectMethod(object, "getWrapper").invoke(); } catch (RuntimeException e) { } return null; } public Class<?> getBridgeClass(String name) { try { return mBridgeLoader.loadClass(BRIDGE_PACKAGE + "." + name); } catch (ClassNotFoundException e) { } return null; } }
package org.xwalk.core; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * This class represents the preferences and could be set by callers. * It is not thread-safe and must be called on the UI thread. * Afterwards, the preference could be read from all threads and can impact * all XWalkView instances. */ public final class XWalkPreferences { private static HashMap<String, Boolean> sPrefMap = new HashMap<String, Boolean>(); // Here we use WeakReference to make sure the KeyValueChangeListener instance // can be GC-ed to avoid memory leaking issue. private static ArrayList<WeakReference<KeyValueChangeListener> > sListeners = new ArrayList<WeakReference<KeyValueChangeListener> >(); private static ReferenceQueue<KeyValueChangeListener> sRefQueue = new ReferenceQueue<KeyValueChangeListener>(); /** * The key string to enable/disable remote debugging. */ public static final String REMOTE_DEBUGGING = "remote-debugging"; static { sPrefMap.put(REMOTE_DEBUGGING, Boolean.FALSE); } /** * Set a preference value into Crosswalk. An exception will be thrown if * the key for the preference is not valid. * @param key the string name of the key. * @param enabled true if setting it as enabled. */ public static synchronized void setValue(String key, boolean enabled) throws RuntimeException { checkKey(key); if (sPrefMap.get(key) != enabled) { sPrefMap.put(key, new Boolean(enabled)); onKeyValueChanged(key, enabled); } } /** * Get a preference value from Crosswalk. An exception will be thrown if * the key for the preference is not valid. * @param key the string name of the key. * @return true if it's enabled. */ public static synchronized boolean getValue(String key) throws RuntimeException { checkKey(key); return sPrefMap.get(key); } // TODO(yongsheng): I believe this is needed? /*public static synchronized void setValue(String key, int value) throws RuntimeException { }*/ static synchronized void load(KeyValueChangeListener listener) { // Load current settings for initialization of a listener implementor. for (Map.Entry<String, Boolean> entry : sPrefMap.entrySet()) { listener.onKeyValueChanged(entry.getKey(), entry.getValue()); } registerListener(listener); } static synchronized void unload(KeyValueChangeListener listener) { unregisterListener(listener); } // Listen to value changes. interface KeyValueChangeListener { public void onKeyValueChanged(String key, boolean value); } private static synchronized void registerListener(KeyValueChangeListener listener) { removeEnqueuedReference(); WeakReference<KeyValueChangeListener> weakListener = new WeakReference<KeyValueChangeListener>(listener, sRefQueue); sListeners.add(weakListener); } private static synchronized void unregisterListener(KeyValueChangeListener listener) { removeEnqueuedReference(); for (WeakReference<KeyValueChangeListener> weakListener : sListeners) { if (weakListener.get() == listener) { sListeners.remove(weakListener); break; } } } private static void onKeyValueChanged(String key, boolean enabled) { for (WeakReference<KeyValueChangeListener> weakListener : sListeners) { KeyValueChangeListener listener = weakListener.get(); if (listener != null) listener.onKeyValueChanged(key, enabled); } } private static void checkKey(String key) throws RuntimeException { removeEnqueuedReference(); if (!sPrefMap.containsKey(key)) { throw new RuntimeException("Warning: the preference key " + key + " is not supported by Crosswalk."); } } /** * Internal method to keep track of weak references and remove the enqueued * references from listener list by polling the reference queue. */ @SuppressWarnings("unchecked") private static void removeEnqueuedReference() { WeakReference<KeyValueChangeListener> toRemove; while ((toRemove = (WeakReference<KeyValueChangeListener>) sRefQueue.poll()) != null) { sListeners.remove(toRemove); } } }
package ws.gazebo.brontes; import org.apache.maven.repository.internal.MavenRepositorySystemUtils; import org.apache.maven.settings.Settings; import org.apache.maven.settings.building.SettingsBuildingException; import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.artifact.DefaultArtifact; import org.eclipse.aether.connector.basic.BasicRepositoryConnectorFactory; import org.eclipse.aether.impl.DefaultServiceLocator; import org.eclipse.aether.repository.LocalRepository; import org.eclipse.aether.repository.LocalRepositoryManager; import org.eclipse.aether.resolution.ArtifactRequest; import org.eclipse.aether.resolution.ArtifactResolutionException; import org.eclipse.aether.resolution.ArtifactResult; import org.eclipse.aether.spi.connector.RepositoryConnectorFactory; import org.eclipse.aether.spi.connector.transport.TransporterFactory; import org.eclipse.aether.transport.wagon.WagonTransporterFactory; public class Resolver { private ResolverConfig config; private RepositorySystem repositorySystem; private RepositorySystemSession session = null; public Resolver(ResolverConfig config) { super(); this.config = config; } public Resolver(ResolverConfig config, RepositorySystem rs) { this(config); repositorySystem = rs; } public ResolverConfig getConfig() { return config; } public void setConfig(ResolverConfig config) { this.config = config; } public RepositorySystem getRepositorySystem() { return repositorySystem; } public void setRepositorySystem(RepositorySystem repositorySystem) { this.repositorySystem = repositorySystem; } public RepositorySystemSession getSession() { return session; } public void setSession(RepositorySystemSession session) { this.session = session; } public ArtifactResult resolve(ArtifactRequest request) throws ArtifactResolutionException { return getRepositorySystem().resolveArtifact(ensureSession(), request); } public ArtifactResult resolve(Artifact artifact) throws ArtifactResolutionException { ArtifactRequest req = new ArtifactRequest(); req.setArtifact(artifact); return resolve(req); } public ArtifactResult resolve(String artifact) throws ArtifactResolutionException { Artifact a = new DefaultArtifact(artifact); return resolve(a); } /** * Ensure that this instance is configured with a * {@link RepositorySystemSession}. When {@link #getSession()} returns * {@code null}, this method calls {@link #newDefaultSession()} and sets the * resulting session object as the {@link RepositorySystemSession} for the * instance, then returns the session object. Else, this method returns the * non-null result of the initial call to {@link #getSession()} * * @return the {@link RepositorySystemSession} object for this * {@link Resolver} */ public RepositorySystemSession ensureSession() { RepositorySystemSession s = getSession(); if (s == null) { s = newDefaultSession(); setSession(s); } return s; } public static void main(String[] args) throws SettingsBuildingException { // "Built in test method" // NOTE: This does not download archives, only resolves those that exist // locally in the appropriate configuration locations... ResolverConfig cfg = new ResolverConfig(); cfg.ensureSettingsDefault(); RepositorySystem rs = makeDefaultRepositorySystem(); Resolver resolver = new Resolver(cfg, rs); resolver.ensureSession(); try { // FIXME: Does not download, only resolves existing resources // (need to copy settings over?) ArtifactResult result = resolver .resolve("org.apache.maven:maven-model:3.1.0"); System.out.println("Resolved: " + result.getArtifact().getFile()); } catch (ArtifactResolutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static <C extends RepositoryConnectorFactory, T extends TransporterFactory> DefaultServiceLocator makeDefaultServiceLocator( Class<C> connectorFactoryClass, Class<T> transporterFactoryClass) { DefaultServiceLocator loc = MavenRepositorySystemUtils .newServiceLocator(); loc.addService(RepositoryConnectorFactory.class, connectorFactoryClass); loc.addService(TransporterFactory.class, transporterFactoryClass); return loc; } /** * Create and initialize a {@link DefaultServiceLocator} with a * {@link BasicRepositoryConnectorFactory} and a * {@link WagonTransporterFactory} * * @return the {@link RepositorySystem} assigned to the * {@link DefaultServiceLocator} */ public static RepositorySystem makeDefaultRepositorySystem() { DefaultServiceLocator loc = makeDefaultServiceLocator( BasicRepositoryConnectorFactory.class, WagonTransporterFactory.class); // ^ FIXME: Is that enough to ensure availability of HTTP transport? // FIXME: see also // * WagonTransporterFactory#setWagonConfigurator(...) // * WagonTransporterFactory#setWagonProvider(...) return loc.getService(RepositorySystem.class); } public RepositorySystemSession newDefaultSession() { // Point of reference: // namely, "creating such a session that mimics Maven's setup" // That pattern has been refactored here for a more modular design DefaultRepositorySystemSession session = MavenRepositorySystemUtils .newSession(); configureSession(session); // session.setReadOnly(); // Note that that will not be called here return session; } /** * Set the {@link LocalRepositoryManager} for the {@code session}, based on * the result of {@link ResolverConfig#getLocalRepository()} for the * {@link ResolverConfig} of this instance * * @param session * the session instance to configure */ public void configureLocalRepository(DefaultRepositorySystemSession session) { // transfer local repository LocalRepository localRepo = new LocalRepository(getConfig() .getLocalRepository()); RepositorySystem sys = getRepositorySystem(); LocalRepositoryManager lmgr = sys.newLocalRepositoryManager(session, localRepo); session.setLocalRepositoryManager(lmgr); } /** * Ensure that the {@code session} is configured for this {@link Resolver} * and its {@link ResolverConfig} * * @param session * the {@link DefaultRepositorySystemSession} instance to * configure */ public void configureSession(DefaultRepositorySystemSession session) { // Note that it may be unclear as to whether or not any more settings // should be transferred from the ResolverConfig's settings object into // the session. At least the local repository info must be transferred, // or else the resolver will be unable to resolve artifacts configureLocalRepository(session); } }
package de.ifgi.lod4wfs.web; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Enumeration; import java.util.Scanner; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import de.ifgi.lod4wfs.core.WFSFeature; import de.ifgi.lod4wfs.facade.Facade; /** * @author jones * @version 1.0 */ public class ServletWFS extends HttpServlet { private String greeting="Linked Open Data for Web Feature Services Adapter"; private static Logger logger = Logger.getLogger("Web-Interface"); public ServletWFS(){ } public ServletWFS(String greeting) { this.greeting=greeting; } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Enumeration<String> listParameters = request.getParameterNames(); String CapabilitiesDocuemnt = new String(); String currentVersion = new String(); String currentRequest = new String(); String currentService = new String(); String currentTypeName = new String(); String currentSRSName = new String(); String currentOutputFormat = new String(); String currentOptionsFormat = new String(); System.out.println("\nIncoming request:\n"); // System.out.println(request.getRequestURL()); // System.out.println(request.getRequestURI()); // System.out.println(request.getQueryString() + "\n"); // TODO Implement MAXFEATURE for GetFeature while (listParameters.hasMoreElements()) { String parameter = (String) listParameters.nextElement(); System.out.println(parameter + " -> "+ request.getParameter(parameter)+""); if (parameter.toUpperCase().equals("VERSION")) { currentVersion=request.getParameter(parameter); } if(parameter.toUpperCase().equals("REQUEST")){ currentRequest=request.getParameter(parameter); } if(parameter.toUpperCase().equals("TYPENAME")){ currentTypeName=request.getParameter(parameter); } if(parameter.toUpperCase().equals("SRSNAME")){ currentSRSName=request.getParameter(parameter); } if(parameter.toUpperCase().equals("SERVICE")){ currentService=request.getParameter(parameter); } if(parameter.toUpperCase().equals("OUTPUTFORMAT")){ currentOutputFormat=request.getParameter(parameter); } if(parameter.toUpperCase().equals("FORMAT_OPTIONS")){ currentOptionsFormat=request.getParameter(parameter); } } /** * Checking if the current request is valid */ String validRequest = new String(); validRequest = this.validateRequest(currentVersion, currentRequest, currentService, currentTypeName, currentSRSName, currentOutputFormat, currentOptionsFormat); if(validRequest.equals("valid")){ System.out.println("\n"); /** * GetCapabilities request */ if(currentRequest.toUpperCase().equals("GETCAPABILITIES")){ if(currentVersion.equals("1.0.0")){ logger.info("Processing " + currentRequest + " ..."); CapabilitiesDocuemnt = Facade.getInstance().getCapabilities(currentVersion); } response.setContentType("text/xml"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println(CapabilitiesDocuemnt); logger.info(currentRequest + " request delivered. "); /** * GetFeature request */ } else if (currentRequest.toUpperCase().equals("GETFEATURE")) { WFSFeature layer = new WFSFeature(); layer.setName(currentTypeName); if (currentOutputFormat.toUpperCase().equals("TEXT/JAVASCRIPT")) { layer.setOutputFormat("geojson"); response.setContentType("text/javascript"); } else { response.setContentType("text/xml"); layer.setOutputFormat("xml"); } response.setStatus(HttpServletResponse.SC_OK); logger.info("Processing " + currentRequest + " request for the feature "+ layer.getName() + " ..."); if (currentOptionsFormat.toUpperCase().equals("CALLBACK:LOADGEOJSON") && currentOutputFormat.toUpperCase().equals("TEXT/JAVASCRIPT")){ //Wrapping response with the callback function for JSONP javascript requests. response.getWriter().println("loadGeoJson("+Facade.getInstance().getFeature(layer)+")"); } else { response.getWriter().println(Facade.getInstance().getFeature(layer)); } logger.info(currentRequest + " request delivered. \n"); /** * DescribeFeatureType request */ } else if (currentRequest.toUpperCase().equals("DESCRIBEFEATURETYPE")) { WFSFeature layer = new WFSFeature(); layer.setName(currentTypeName); response.setContentType("text/xml"); response.setStatus(HttpServletResponse.SC_OK); logger.info("Processing " + currentRequest + " request for the feature "+ layer.getName() + " ..."); response.getWriter().println(Facade.getInstance().describeFeatureType(layer)); logger.info(currentRequest + " request delivered."); } } else { response.getWriter().println(validRequest); } } private String validateRequest(String version, String request, String service, String typeName, String SRS, String outputFormat, String formatOptions){ String result = new String(); boolean valid = true; try { //result = new Scanner(new File("src/main/resources/wfs/ServiceExceptionReport.xml")).useDelimiter("\\Z").next(); result = new Scanner(new File("wfs/ServiceExceptionReport.xml")).useDelimiter("\\Z").next(); if(!service.toUpperCase().equals("WFS")){ if(service.isEmpty()){ result = result.replace("PARAM_REPORT", "No service provided in the request."); result = result.replace("PARAM_CODE", "ServiceNotProvided"); logger.error("No service provided in the request."); } else { result = result.replace("PARAM_REPORT", "Service " + service + " is not supported by this server."); result = result.replace("PARAM_CODE", "ServiceNotSupported"); logger.error("Service " + service + " is not supported by this server."); } valid = false; } else if (!version.equals("1.0.0")){ if (version.isEmpty()){ result = result.replace("PARAM_REPORT", "Web Feature Service version not informed."); result = result.replace("PARAM_CODE", "VersionNotProvided"); logger.error("Web Feature Service version not informed."); } else { result = result.replace("PARAM_REPORT", "WFS version " + version + " is not supported by this server."); result = result.replace("PARAM_CODE", "VersionNotSupported"); logger.error("WFS version " + version + " is not supported by this server."); } valid = false; } else if(!request.toUpperCase().equals("GETCAPABILITIES") && !request.toUpperCase().equals("DESCRIBEFEATURETYPE") && !request.toUpperCase().equals("GETFEATURE")){ result = result.replace("PARAM_REPORT", "Operation " + request + " not supported by WFS."); result = result.replace("PARAM_CODE", "OperationNotSupported"); logger.error("Operation " + request + " not supported by WFS."); valid = false; } else if (request.toUpperCase().equals("DESCRIBEFEATURETYPE") && typeName.isEmpty()){ result = result.replace("PARAM_REPORT", "No feature provided for " + request + "."); result = result.replace("PARAM_CODE", "FeatureNotProvided"); logger.error("No feature provided for " + request + "."); valid = false; } else if (request.toUpperCase().equals("GETFEATURE") && typeName.isEmpty()){ result = result.replace("PARAM_REPORT", "No feature provided for " + request + "."); result = result.replace("PARAM_CODE", "FeatureNotProvided"); logger.error("No feature provided for " + request + "."); valid = false; /* * Supported output formats: * GeoJSON (text/javascript) * GML2 */ } else if (!outputFormat.toUpperCase().equals("TEXT/JAVASCRIPT") && !outputFormat.isEmpty() && //GML2 is assumed for requests without an explicit output format. !outputFormat.toUpperCase().equals("GML2")){ result = result.replace("PARAM_REPORT", "Invalid output format for " + request + ". The output format '"+ outputFormat + "' is not supported."); result = result.replace("PARAM_CODE", "InvalidOutputFormat"); logger.error("Invalid output format for " + request + ". The output format "+ outputFormat + " is not supported."); valid = false; } if(!valid){ result = result.replace("PARAM_LOCATOR", request); } else { result = "valid"; } } catch (FileNotFoundException e) { e.printStackTrace(); } return result; } }
package core.log; import core.framework.http.HTTPMethod; import core.framework.internal.log.message.EventMessage; import core.framework.internal.log.message.LogTopics; import core.framework.module.App; import core.framework.module.SystemModule; import core.framework.util.Sets; import core.framework.util.Strings; import core.log.web.CollectEventRequest; import core.log.web.CollectEventRequestValidator; import core.log.web.EventController; import java.util.Set; /** * @author neo */ public class LogCollectorApp extends App { @Override protected void initialize() { load(new SystemModule("sys.properties")); loadProperties("app.properties"); http().maxForwardedIPs(3); // loose x-forwarded-for ip config, there are cdn/proxy before system, and in event collector, preventing fake client ip is less important site().security(); site().staticContent("/robots.txt"); kafka().publish(LogTopics.TOPIC_EVENT, EventMessage.class); bind(CollectEventRequestValidator.class); Set<String> allowedOrigins = allowedOrigins(requiredProperty("app.allowedOrigins")); EventController controller = bind(new EventController(allowedOrigins)); http().route(HTTPMethod.OPTIONS, "/event/:app", controller::options); http().route(HTTPMethod.PUT, "/event/:app", controller::put); http().bean(CollectEventRequest.class); } Set<String> allowedOrigins(String value) { String[] origins = Strings.split(value, ','); Set<String> result = Sets.newHashSetWithExpectedSize(origins.length); for (String origin : origins) { result.add(origin.strip()); } return result; } }
package psn.lotus.crawler; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.junit.Test; import java.net.URI; import java.nio.charset.Charset; /** * @author xjl * @project lotus * @time 2016/9/29 11:06 */ public class T_3023Api { //3023 app key static final String appKey = ""; static final String API_SERVER_URL = ""; @Test public void doIt() throws Exception { String url = API_SERVER_URL.replace("BARCODE", "6936292120079"); URI uri = new URI(url); HttpGet httpGet = new HttpGet(uri); httpGet.setHeader("3023-key", appKey); doGet(httpGet); int i = 0; } @Test public void forReqImg() throws Exception { long code = 6936292120000l; HttpGet httpGet = new HttpGet(); URI uri; for (int i = 0; i < 80; i++) { code += i; String url = "".concat(String.valueOf(code)); uri = new URI(url); httpGet.setURI(uri); doGet(httpGet); } int i = 0; } private static void doGet(HttpGet httpGet) throws Exception { HttpClient httpClient = HttpClientBuilder.create().build(); HttpResponse response = httpClient.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int code = statusLine.getStatusCode(); System.out.println("code: " + code); if (code == HttpStatus.SC_OK) { String entityToStr = EntityUtils.toString(response.getEntity(), Charset.defaultCharset().displayName()); System.out.println(entityToStr); } httpGet.completed(); } }
package com.joelapenna.foursquared.app; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquared.Foursquared; import com.joelapenna.foursquared.FriendsActivity; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.preferences.Preferences; import com.joelapenna.foursquared.util.StringFormatters; import android.app.AlarmManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.location.Location; import android.location.LocationManager; import android.os.SystemClock; import android.preference.PreferenceManager; import android.util.Log; import android.widget.RemoteViews; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * This service will run every N minutes (specified by the user in settings). An alarm * handles running the service. * * When the service runs, we call /checkins. From the list of checkins, we cut down the * list of relevant checkins as follows: * <ul> * <li>Not one of our own checkins.</li> * <li>We haven't turned pings off for the user. This can be toggled on/off in the * UserDetailsActivity activity, per user.</li> * <li>The checkin is younger than the last time we ran this service.</li> * <li>The checkin is younger than a static threshold in minutes (currently 20 minutes).</li> * </ul> * * The last criteria (the 20 minute threshold) exists for the higher refresh intervals. If * the user is running pings every 2 hours, they probably don't care about a checkin * that is 1.9 hours old. * * Note that the server might override the pings attribute to 'off' for certain checkins, * usually if the checkin is far away from our current location. * * Pings will not be cleared from the notification bar until a subsequent run can * generate at least one new ping. A new batch of pings will clear all * previous pings so as to not clutter the notification bar. * * @date May 21, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class PingsService extends WakefulIntentService { public static final String TAG = "PingsService"; private static final boolean DEBUG = true; private static final String SHARED_PREFS_NAME = "SharedPrefsPingsService"; private static final String SHARED_PREFS_KEY_LAST_RUN_TIME = "SharedPrefsKeyLastRunTime"; private SharedPreferences mSharedPrefs; public PingsService() { super("PingsService"); } @Override public void onCreate() { super.onCreate(); mSharedPrefs = getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE); } @Override protected void doWakefulWork(Intent intent) { // The user must have logged in once previously for this to work, // and not leave the app in a logged-out state. Foursquared foursquared = (Foursquared) getApplication(); Foursquare foursquare = foursquared.getFoursquare(); if (!foursquared.isReady()) { if (DEBUG) Log.d(TAG, "User not logged in, cannot proceed."); return; } // Before running, make sure the user still wants pings on. // For example, the user could have turned pings on from // this device, but then turned it off on a second device. This // service would continue running then, continuing to notify the // user. if (!checkUserStillWantsPings(foursquared.getUserId(), foursquare)) { // Turn off locally. SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); prefs.edit().putBoolean(Preferences.PREFERENCE_PINGS, false).commit(); cancelPings(this); return; } // Get the users current location and then request nearby checkins. Group<Checkin> checkins = null; Location location = getLastGeolocation(); if (location != null) { try { checkins = foursquare.checkins( LocationUtils.createFoursquareLocation(location)); } catch (Exception ex) { Log.e(TAG, "Error getting checkins in pings service.", ex); } } else { Log.e(TAG, "Could not find location in pings service, cannot proceed."); } if (checkins != null) { if (DEBUG) Log.e(TAG, "Checking " + checkins.size() + " checkins for pings."); // Don't accept any checkins that are older than the last time we ran. long lastRunTime = mSharedPrefs.getLong(SHARED_PREFS_KEY_LAST_RUN_TIME, 0L); Date dateLast = new Date(lastRunTime); // Now build the list of 'new' checkins. List<Checkin> newCheckins = new ArrayList<Checkin>(); for (Checkin it : checkins) { if (DEBUG) Log.d(TAG, "Checking checkin of " + it.getUser().getFirstname()); // Ignore ourselves. The server should handle this by setting the pings flag off but.. if (it.getUser() != null && it.getUser().getId().equals(foursquared.getUserId())) { if (DEBUG) Log.d(TAG, " Ignoring checkin of ourselves."); continue; } // Check that our user wanted to see pings from this user. if (!it.getPing()) { if (DEBUG) Log.d(TAG, " Pings are off for this user."); continue; } // Check against date times. try { Date date = StringFormatters.DATE_FORMAT.parse(it.getCreated()); if (DEBUG) { Log.d(TAG, " Comaring date times for checkin."); Log.d(TAG, " Last run time: " + dateLast.toLocaleString()); Log.d(TAG, " Checkin time: " + date.toLocaleString()); } if (date.after(dateLast)) { if (DEBUG) Log.d(TAG, " Checkin is younger than our last run time, passes all tests!!"); newCheckins.add(it); } else { if (DEBUG) Log.d(TAG, " Checkin is older than last run time."); } } catch (ParseException ex) { } } notifyUser(newCheckins); } // Record this as the last time we ran. mSharedPrefs.edit().putLong(SHARED_PREFS_KEY_LAST_RUN_TIME, System.currentTimeMillis()).commit(); } private Location getLastGeolocation() { LocationManager manager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); List<String> providers = manager.getAllProviders(); Location bestLocation = null; for (String it : providers) { Location location = manager.getLastKnownLocation(it); if (location != null) { if (bestLocation == null || location.getAccuracy() < bestLocation.getAccuracy()) { bestLocation = location; } } } return bestLocation; } private void notifyUser(List<Checkin> newCheckins) { // If we have no new checkins to show, nothing to do. We would also be leaving the // previous batch of pings alive (if any) which is ok. if (newCheckins.size() < 1) { return; } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); boolean vibrate = prefs.getBoolean(Preferences.PREFERENCE_PINGS_VIBRATE, false); boolean vibratedOnce = false; // Clear all previous pings before showing new ones. NotificationManager mgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); mgr.cancelAll(); PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this, FriendsActivity.class), 0); int nextNotificationId = 0; for (Checkin it : newCheckins) { RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.pings_list_item); contentView.setTextViewText(R.id.text1, StringFormatters.getPingMessageTitle(it)); contentView.setTextViewText(R.id.text2, StringFormatters.getPingMessageInfo(it)); Notification notification = new Notification( R.drawable.icon, "Foursquare Checkin", System.currentTimeMillis()); notification.contentView = contentView; notification.contentIntent = pi; notification.flags |= Notification.FLAG_AUTO_CANCEL; if (vibrate && !vibratedOnce) { notification.defaults |= Notification.DEFAULT_VIBRATE; vibratedOnce = true; } mgr.notify(nextNotificationId++, notification); } } private boolean checkUserStillWantsPings(String userId, Foursquare foursquare) { try { User user = foursquare.user(userId, false, false, null); if (user != null) { return user.getSettings().getPings().equals("on"); } } catch (Exception ex) { // Assume they still want it on. } return true; } public static void setupPings(Context context) { // If the user has pings on, set an alarm every N minutes, where N is their // requested refresh rate. We default to 30 if some problem reading set interval. SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); if (prefs.getBoolean(Preferences.PREFERENCE_PINGS, false)) { int refreshRateInMinutes = 30; try { refreshRateInMinutes = Integer.parseInt(prefs.getString( Preferences.PREFERENCE_PINGS_INTERVAL, String.valueOf(refreshRateInMinutes))); } catch (NumberFormatException ex) { Log.e(TAG, "Error parsing pings interval time, defaulting to: " + refreshRateInMinutes); } if (DEBUG) { Log.d(TAG, "User has pings on, attempting to setup alarm with interval: " + refreshRateInMinutes + ".."); } // Set the current time as the last run time. Just add 10 seconds difference because the // service doesn't always get started at exactly the interval expected. prefs.edit().putLong(SHARED_PREFS_KEY_LAST_RUN_TIME, System.currentTimeMillis() - (60 * 1000 * 10)).commit(); // Schedule the alarm. AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + (refreshRateInMinutes * 60 * 1000), refreshRateInMinutes * 60 * 1000, makePendingIntentAlarm(context)); } } public static void cancelPings(Context context) { AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); mgr.cancel(makePendingIntentAlarm(context)); } private static PendingIntent makePendingIntentAlarm(Context context) { return PendingIntent.getBroadcast(context, 0, new Intent(context, PingsOnAlarmReceiver.class), 0); } public static void generatePingsTest(Context context) { PendingIntent pi = PendingIntent.getActivity(context, 0, new Intent(context, FriendsActivity.class), 0); NotificationManager mgr = (NotificationManager)context.getSystemService(NOTIFICATION_SERVICE); RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.pings_list_item); contentView.setTextViewText(R.id.text1, "Ping title line"); contentView.setTextViewText(R.id.text2, "Ping message line"); Notification notification = new Notification( R.drawable.icon, "Foursquare Checkin", System.currentTimeMillis()); notification.contentView = contentView; notification.contentIntent = pi; notification.defaults |= Notification.DEFAULT_VIBRATE; mgr.notify(-1, notification); } }
package net.java.sip.communicator.plugin.otr; import java.awt.event.*; import java.lang.ref.*; import javax.swing.*; import net.java.otr4j.*; import net.java.otr4j.session.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.plugin.desktoputil.*; /** * A special {@link JMenu} that holds the menu items for controlling the * Off-the-Record functionality for a specific contact. * * @author George Politis * @author Lyubomir Marinov */ class OtrContactMenu implements ActionListener, ScOtrEngineListener, ScOtrKeyManagerListener { private static final String ACTION_COMMAND_AUTHENTICATE_BUDDY = "AUTHENTICATE_BUDDY"; private static final String ACTION_COMMAND_CB_AUTO = "CB_AUTO"; private static final String ACTION_COMMAND_CB_ENABLE = "CB_ENABLE"; private static final String ACTION_COMMAND_CB_REQUIRE = "CB_REQUIRE"; private static final String ACTION_COMMAND_CB_RESET = "CB_RESET"; private static final String ACTION_COMMAND_END_OTR = "END_OTR"; private static final String ACTION_COMMAND_REFRESH_OTR = "REFRESH_OTR"; private static final String ACTION_COMMAND_START_OTR = "START_OTR"; private final Contact contact; /** * The indicator which determines whether this <tt>JMenu</tt> is displayed * in the Mac OS X screen menu bar and thus should work around the known * problem of PopupMenuListener not being invoked. */ private final boolean inMacOSXScreenMenuBar; /** * We keep this variable so we can determine if the policy has changed * or not in {@link OtrContactMenu#setOtrPolicy(OtrPolicy)}. */ private OtrPolicy otrPolicy; private SessionStatus sessionStatus; private final JMenu parentMenu; private final SIPCommMenu separateMenu; /** * The OtrContactMenu constructor. * * @param contact the Contact this menu refers to. * @param inMacOSXScreenMenuBar <tt>true</tt> if the new menu is to be * displayed in the Mac OS X screen menu bar; <tt>false</tt>, otherwise * @param menu the parent menu */ public OtrContactMenu( Contact contact, boolean inMacOSXScreenMenuBar, JMenu menu, boolean isSeparateMenu) { this.contact = contact; this.inMacOSXScreenMenuBar = inMacOSXScreenMenuBar; this.parentMenu = menu; separateMenu = isSeparateMenu ? new SIPCommMenu(contact.getDisplayName()) : null; /* * XXX This OtrContactMenu instance cannot be added as a listener to * scOtrEngine and scOtrKeyManager without being removed later on * because the latter live forever. Unfortunately, the dispose() method * of this instance is never executed. WeakListener will keep this * instance as a listener of scOtrEngine and scOtrKeyManager for as long * as this instance is necessary. And this instance will be strongly * referenced by the JMenuItems which depict it. So when the JMenuItems * are gone, this instance will become obsolete and WeakListener will * remove it as a listener of scOtrEngine and scOtrKeyManager. */ new WeakListener( this, OtrActivator.scOtrEngine, OtrActivator.scOtrKeyManager); setSessionStatus(OtrActivator.scOtrEngine.getSessionStatus(contact)); setOtrPolicy(OtrActivator.scOtrEngine.getContactPolicy(contact)); buildMenu(); } /* * Implements ActionListener#actionPerformed(ActionEvent). */ public void actionPerformed(ActionEvent e) { String actionCommand = e.getActionCommand(); if (ACTION_COMMAND_END_OTR.equals(actionCommand)) // End session. OtrActivator.scOtrEngine.endSession(contact); else if (ACTION_COMMAND_START_OTR.equals(actionCommand)) // Start session. OtrActivator.scOtrEngine.startSession(contact); else if (ACTION_COMMAND_REFRESH_OTR.equals(actionCommand)) // Refresh session. OtrActivator.scOtrEngine.refreshSession(contact); else if (ACTION_COMMAND_AUTHENTICATE_BUDDY.equals(actionCommand)) // Launch auth buddy dialog. OtrActionHandlers.openAuthDialog(contact); else if (ACTION_COMMAND_CB_ENABLE.equals(actionCommand)) { OtrPolicy policy = OtrActivator.scOtrEngine.getContactPolicy(contact); boolean state = ((JCheckBoxMenuItem) e.getSource()).isSelected(); policy.setEnableManual(state); OtrActivator.scOtrEngine.setContactPolicy(contact, policy); } else if (ACTION_COMMAND_CB_AUTO.equals(actionCommand)) { OtrPolicy policy = OtrActivator.scOtrEngine.getContactPolicy(contact); boolean state = ((JCheckBoxMenuItem) e.getSource()).isSelected(); policy.setEnableAlways(state); OtrActivator.configService.setProperty( OtrActivator.AUTO_INIT_OTR_PROP, Boolean.toString(state)); OtrActivator.scOtrEngine.setContactPolicy(contact, policy); } else if (ACTION_COMMAND_CB_REQUIRE.equals(actionCommand)) { OtrPolicy policy = OtrActivator.scOtrEngine.getContactPolicy(contact); boolean state = ((JCheckBoxMenuItem) e.getSource()).isSelected(); policy.setRequireEncryption(state); OtrActivator.configService.setProperty( OtrActivator.OTR_MANDATORY_PROP, Boolean.toString(state)); OtrActivator.scOtrEngine.setContactPolicy(contact, policy); } else if (ACTION_COMMAND_CB_RESET.equals(actionCommand)) OtrActivator.scOtrEngine.setContactPolicy(contact, null); } /* * Implements ScOtrEngineListener#contactPolicyChanged(Contact). */ public void contactPolicyChanged(Contact contact) { // Update the corresponding to the contact menu. if (contact.equals(OtrContactMenu.this.contact)) setOtrPolicy(OtrActivator.scOtrEngine.getContactPolicy(contact)); } /* * Implements ScOtrKeyManagerListener#contactVerificationStatusChanged( * Contact). */ public void contactVerificationStatusChanged(Contact contact) { if (contact.equals(OtrContactMenu.this.contact)) setSessionStatus(OtrActivator.scOtrEngine.getSessionStatus(contact)); } /** * Disposes of this instance by making it available for garage collection * e.g. removes the listeners it has installed on global instances such as * <tt>OtrActivator#scOtrEngine</tt> and * <tt>OtrActivator#scOtrKeyManager</tt>. */ void dispose() { OtrActivator.scOtrEngine.removeListener(this); OtrActivator.scOtrKeyManager.removeListener(this); } /* * Implements ScOtrEngineListener#globalPolicyChanged(). */ public void globalPolicyChanged() { setOtrPolicy(OtrActivator.scOtrEngine.getContactPolicy(contact)); } /** * Rebuilds own menuitems according to {@link OtrContactMenu#sessionStatus} * and the {@link OtrPolicy} for {@link OtrContactMenu#contact}. */ private void buildMenu() { if(separateMenu != null) separateMenu.removeAll(); OtrPolicy policy = OtrActivator.scOtrEngine.getContactPolicy(contact); JMenuItem endOtr = new JMenuItem(); endOtr.setText(OtrActivator.resourceService .getI18NString("plugin.otr.menu.END_OTR")); endOtr.setActionCommand(ACTION_COMMAND_END_OTR); endOtr.addActionListener(this); JMenuItem startOtr = new JMenuItem(); startOtr.setText(OtrActivator.resourceService .getI18NString("plugin.otr.menu.START_OTR")); startOtr.setEnabled(policy.getEnableManual()); startOtr.setActionCommand(ACTION_COMMAND_START_OTR); startOtr.addActionListener(this); switch (this.sessionStatus) { case ENCRYPTED: JMenuItem refreshOtr = new JMenuItem(); refreshOtr.setText(OtrActivator.resourceService .getI18NString("plugin.otr.menu.REFRESH_OTR")); refreshOtr.setEnabled(policy.getEnableManual()); refreshOtr.setActionCommand(ACTION_COMMAND_REFRESH_OTR); refreshOtr.addActionListener(this); JMenuItem authBuddy = new JMenuItem(); authBuddy.setText(OtrActivator.resourceService .getI18NString("plugin.otr.menu.AUTHENTICATE_BUDDY")); authBuddy.setActionCommand(ACTION_COMMAND_AUTHENTICATE_BUDDY); authBuddy.addActionListener(this); if (separateMenu != null) { separateMenu.add(endOtr); separateMenu.add(refreshOtr); separateMenu.add(authBuddy); } else { parentMenu.add(endOtr); parentMenu.add(refreshOtr); parentMenu.add(authBuddy); } break; case FINISHED: if (separateMenu != null) { separateMenu.add(endOtr); separateMenu.add(startOtr); } else { parentMenu.add(endOtr); parentMenu.add(startOtr); } break; case PLAINTEXT: if (separateMenu != null) separateMenu.add(startOtr); else parentMenu.add(startOtr); break; } JCheckBoxMenuItem cbEnable = new JCheckBoxMenuItem(); cbEnable.setText(OtrActivator.resourceService .getI18NString("plugin.otr.menu.CB_ENABLE")); cbEnable.setSelected(policy.getEnableManual()); cbEnable.setActionCommand(ACTION_COMMAND_CB_ENABLE); cbEnable.addActionListener(this); JCheckBoxMenuItem cbAlways = new JCheckBoxMenuItem(); cbAlways.setText(OtrActivator.resourceService .getI18NString("plugin.otr.menu.CB_AUTO")); cbAlways.setEnabled(policy.getEnableManual()); String autoInitPropValue = OtrActivator.configService.getString( OtrActivator.AUTO_INIT_OTR_PROP); boolean isAutoInit = policy.getEnableAlways(); if (autoInitPropValue != null) isAutoInit = Boolean.parseBoolean(autoInitPropValue); cbAlways.setSelected(isAutoInit); cbAlways.setActionCommand(ACTION_COMMAND_CB_AUTO); cbAlways.addActionListener(this); JCheckBoxMenuItem cbRequire = new JCheckBoxMenuItem(); cbRequire.setText(OtrActivator.resourceService .getI18NString("plugin.otr.menu.CB_REQUIRE")); cbRequire.setEnabled(policy.getEnableManual()); String otrMandatoryPropValue = OtrActivator.configService.getString( OtrActivator.OTR_MANDATORY_PROP); String defaultOtrPropValue = OtrActivator.resourceService.getSettingsString( OtrActivator.OTR_MANDATORY_PROP); boolean isMandatory = policy.getRequireEncryption(); if (otrMandatoryPropValue != null) isMandatory = Boolean.parseBoolean(otrMandatoryPropValue); else if (!isMandatory && defaultOtrPropValue != null) isMandatory = Boolean.parseBoolean(defaultOtrPropValue); cbRequire.setSelected(isMandatory); cbRequire.setActionCommand(ACTION_COMMAND_CB_REQUIRE); cbRequire.addActionListener(this); JMenuItem cbReset = new JMenuItem(); cbReset.setText(OtrActivator.resourceService .getI18NString("plugin.otr.menu.CB_RESET")); cbReset.setActionCommand(ACTION_COMMAND_CB_RESET); cbReset.addActionListener(this); if (separateMenu != null) { separateMenu.addSeparator(); separateMenu.add(cbEnable); separateMenu.add(cbAlways); separateMenu.add(cbRequire); separateMenu.addSeparator(); separateMenu.add(cbReset); parentMenu.add(separateMenu); } else { parentMenu.addSeparator(); parentMenu.add(cbEnable); parentMenu.add(cbAlways); parentMenu.add(cbRequire); parentMenu.addSeparator(); parentMenu.add(cbReset); } } /* * Implements ScOtrEngineListener#sessionStatusChanged(Contact). */ public void sessionStatusChanged(Contact contact) { if (contact.equals(OtrContactMenu.this.contact)) setSessionStatus(OtrActivator.scOtrEngine.getSessionStatus(contact)); } /** * Sets the {@link OtrContactMenu#sessionStatus} value, updates the menu * icon and, if necessary, rebuilds the menuitems to match the passed in * sessionStatus. * * @param sessionStatus the {@link SessionStatus}. */ private void setSessionStatus(SessionStatus sessionStatus) { if (sessionStatus != this.sessionStatus) { this.sessionStatus = sessionStatus; if (separateMenu != null) { updateIcon(); if (separateMenu.isPopupMenuVisible() || inMacOSXScreenMenuBar) buildMenu(); } } } /** * Sets the {@link OtrContactMenu#otrPolicy} and, if necessary, rebuilds the * menuitems to match the passed in otrPolicy. * * @param otrPolicy */ private void setOtrPolicy(OtrPolicy otrPolicy) { if (!otrPolicy.equals(this.otrPolicy)) { this.otrPolicy = otrPolicy; if ((separateMenu != null) && (separateMenu.isPopupMenuVisible() || inMacOSXScreenMenuBar)) { buildMenu(); } } } /** * Updates the menu icon based on {@link OtrContactMenu#sessionStatus} * value. */ private void updateIcon() { if (separateMenu == null) return; String imageID; switch (sessionStatus) { case ENCRYPTED: imageID = OtrActivator.scOtrKeyManager.isVerified(contact) ? "plugin.otr.ENCRYPTED_ICON_16x16" : "plugin.otr.ENCRYPTED_UNVERIFIED_ICON_16x16"; break; case FINISHED: imageID = "plugin.otr.FINISHED_ICON_16x16"; break; case PLAINTEXT: imageID = "plugin.otr.PLAINTEXT_ICON_16x16"; break; default: return; } separateMenu.setIcon(OtrActivator.resourceService.getImage(imageID)); } /** * Implements a <tt>ScOtrEngineListener</tt> and * <tt>ScOtrKeyManagerListener</tt> listener for the purposes of * <tt>OtrContactMenu</tt> which listens to <tt>ScOtrEngine</tt> and * <tt>ScOtrKeyManager</tt> while weakly referencing the * <tt>OtrContactMenu</tt>. Fixes a memory leak of <tt>OtrContactMenu</tt> * instances because these cannot determine when they are to be explicitly * disposed. * * @author Lyubomir Marinov */ private static class WeakListener implements ScOtrEngineListener, ScOtrKeyManagerListener { /** * The <tt>ScOtrEngine</tt> the <tt>OtrContactMenu</tt> associated with * this instance is to listen to. */ private final ScOtrEngine engine; /** * The <tt>ScOtrKeyManager</tt> the <tt>OtrContactMenu</tt> associated * with this instance is to listen to. */ private final ScOtrKeyManager keyManager; /** * The <tt>OtrContactMenu</tt> which is associated with this instance * and which is to listen to {@link #engine} and {@link #keyManager}. */ private final WeakReference<OtrContactMenu> listener; /** * Initializes a new <tt>WeakListener</tt> instance which is to allow * a specific <tt>OtrContactMenu</tt> to listener to a specific * <tt>ScOtrEngine</tt> and a specific <tt>ScOtrKeyManager</tt> without * being retained by them forever (because they live forever). * * @param listener the <tt>OtrContactMenu</tt> which is to listen to the * specified <tt>engine</tt> and <tt>keyManager</tt> * @param engine the <tt>ScOtrEngine</tt> which is to be listened to by * the specified <tt>OtrContactMenu</tt> * @param keyManager the <tt>ScOtrKeyManager</tt> which is to be * listened to by the specified <tt>OtrContactMenu</tt> */ public WeakListener( OtrContactMenu listener, ScOtrEngine engine, ScOtrKeyManager keyManager) { if (listener == null) throw new NullPointerException("listener"); this.listener = new WeakReference<OtrContactMenu>(listener); this.engine = engine; this.keyManager = keyManager; this.engine.addListener(this); this.keyManager.addListener(this); } /** * {@inheritDoc} * * Forwards the event/notification to the associated * <tt>OtrContactMenu</tt> if it is still needed by the application. */ public void contactPolicyChanged(Contact contact) { ScOtrEngineListener l = getListener(); if (l != null) l.contactPolicyChanged(contact); } /** * {@inheritDoc} * * Forwards the event/notification to the associated * <tt>OtrContactMenu</tt> if it is still needed by the application. */ public void contactVerificationStatusChanged(Contact contact) { ScOtrKeyManagerListener l = getListener(); if (l != null) l.contactVerificationStatusChanged(contact); } /** * Gets the <tt>OtrContactMenu</tt> which is listening to * {@link #engine} and {@link #keyManager}. If the * <tt>OtrContactMenu</tt> is no longer needed by the application, this * instance seizes listening to <tt>engine</tt> and <tt>keyManager</tt> * and allows the memory used by this instance to be reclaimed by the * Java virtual machine. * * @return the <tt>OtrContactMenu</tt> which is listening to * <tt>engine</tt> and <tt>keyManager</tt> if it is still needed by the * application; otherwise, <tt>null</tt> */ private OtrContactMenu getListener() { OtrContactMenu l = this.listener.get(); if (l == null) { engine.removeListener(this); keyManager.removeListener(this); } return l; } /** * {@inheritDoc} * * Forwards the event/notification to the associated * <tt>OtrContactMenu</tt> if it is still needed by the application. */ public void globalPolicyChanged() { ScOtrEngineListener l = getListener(); if (l != null) l.globalPolicyChanged(); } /** * {@inheritDoc} * * Forwards the event/notification to the associated * <tt>OtrContactMenu</tt> if it is still needed by the application. */ public void sessionStatusChanged(Contact contact) { ScOtrEngineListener l = getListener(); if (l != null) l.sessionStatusChanged(contact); } } }
/* * ConvertSBitTBitPlugin */ package net.maizegenetics.baseplugins; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URL; import java.util.List; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTabbedPane; import net.maizegenetics.gui.DialogUtils; import net.maizegenetics.pal.alignment.Alignment; import net.maizegenetics.pal.alignment.BitAlignment; import net.maizegenetics.plugindef.AbstractPlugin; import net.maizegenetics.plugindef.DataSet; import net.maizegenetics.plugindef.Datum; import net.maizegenetics.plugindef.PluginEvent; import net.maizegenetics.plugindef.PluginListener; import net.maizegenetics.util.ExceptionUtils; import net.maizegenetics.util.ProgressListener; import net.maizegenetics.util.Utils; import org.apache.log4j.Logger; /** * * @author terry */ public class ConvertSBitTBitPlugin extends AbstractPlugin { private static final Logger myLogger = Logger.getLogger(ConvertSBitTBitPlugin.class); public enum CONVERT_TYPE { sbit, tbit }; public CONVERT_TYPE myType = CONVERT_TYPE.sbit; public ConvertSBitTBitPlugin(Frame parentFrame, boolean isInteractive) { super(parentFrame, isInteractive); } public ConvertSBitTBitPlugin(Frame parentFrame, PluginListener listener) { super(parentFrame, false); if (listener != null) { addListener(listener); } } @Override public DataSet performFunction(DataSet input) { String name = null; try { List inputData = input.getDataOfType(Alignment.class); if (inputData.size() != 1) { if (isInteractive()) { JOptionPane.showMessageDialog(getParentFrame(), "Please Select a Single Alignment."); } else { myLogger.error("performFunction: Please Select a Single Alignment."); } return null; } Datum alignDatum = (Datum) inputData.get(0); name = alignDatum.getName(); if (isInteractive()) { ConvertSBitTBitPluginDialog theDialog = new ConvertSBitTBitPluginDialog(); theDialog.setLocationRelativeTo(getParentFrame()); theDialog.setVisible(true); if (theDialog.isCancel()) { return null; } myType = theDialog.getConvertType(); theDialog.dispose(); } return convertAlignment(alignDatum); } catch (Exception e) { e.printStackTrace(); showErrorMessage(name, e, myType); return null; } finally { fireProgress(100); } } private DataSet convertAlignment(Datum datum) { String name = datum.getName(); Alignment alignment = null; try { alignment = (Alignment) datum.getData(); } catch (Exception e) { throw new IllegalArgumentException("ConvertSBitTBitPlugin: convertAlignment: input must be an alignment."); } Alignment result = convertAlignment(alignment, myType, this); DataSet tds = new DataSet(new Datum(datum.getName(), result, null), this); fireDataSetReturned(new PluginEvent(tds, ConvertSBitTBitPlugin.class)); return tds; } public static Alignment convertAlignment(Alignment alignment, CONVERT_TYPE type, ProgressListener listener) { Alignment result = null; if (type == CONVERT_TYPE.sbit) { try { alignment.optimizeForSites(listener); result = alignment; } catch (UnsupportedOperationException e) { result = BitAlignment.getInstance(alignment, true); } } else if (type == CONVERT_TYPE.tbit) { try { alignment.optimizeForTaxa(listener); result = alignment; } catch (UnsupportedOperationException e) { result = BitAlignment.getInstance(alignment, false); } } else { throw new IllegalStateException("ConvertSBitTBitPlugin: convertAlignment: Unknown type: " + type); } return result; } private void showErrorMessage(String name, Exception e, CONVERT_TYPE type) { StringBuilder builder = new StringBuilder(); builder.append("Error converting: "); builder.append(name); builder.append(" to: "); builder.append(type); if (e != null) { builder.append("\n"); builder.append(Utils.shortenStrLineLen(ExceptionUtils.getExceptionCauses(e), 50)); } String str = builder.toString(); if (getParentFrame() != null) { DialogUtils.showError(str, getParentFrame()); } else { myLogger.error(str); } } public ImageIcon getIcon() { URL imageURL = ConvertSBitTBitPlugin.class.getResource("images/STConvert.gif"); if (imageURL == null) { return null; } else { return new ImageIcon(imageURL); } } public String getButtonName() { return "Optimize"; } public String getToolTipText() { return "Converts Between Taxa and Site Optimized Data Sets."; } public CONVERT_TYPE getType() { return myType; } public void setType(CONVERT_TYPE type) { myType = type; } } class ConvertSBitTBitPluginDialog extends JDialog { private JTabbedPane myTabbedPane = new JTabbedPane(); private ButtonGroup myButtonGroup = new ButtonGroup(); private JRadioButton mySBit = new JRadioButton(); private JRadioButton myTBit = new JRadioButton(); private boolean myIsCancel = true; public ConvertSBitTBitPluginDialog() { super((Frame) null, "Converts Between Taxa and Site Optimized Data Sets.", true); JButton okButton = new JButton(); okButton.setActionCommand("Ok"); okButton.setText("Ok"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { myIsCancel = false; setVisible(false); } }); JButton closeButton = new JButton(); closeButton.setText("Close"); closeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { myIsCancel = true; setVisible(false); } }); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); //Radio Buttons mySBit.setText("Optimize For Site Operations"); myTBit.setText("Optimize For Taxa Operations"); myButtonGroup.add(mySBit); myButtonGroup.add(myTBit); myButtonGroup.setSelected(mySBit.getModel(), true); panel.add(mySBit); panel.add(myTBit); myTabbedPane.add(panel, "Optimized Data Set"); JPanel pnlButtons = new JPanel(); pnlButtons.setLayout(new FlowLayout()); pnlButtons.add(okButton); pnlButtons.add(closeButton); getContentPane().add(myTabbedPane, BorderLayout.CENTER); getContentPane().add(pnlButtons, BorderLayout.SOUTH); pack(); } public boolean isCancel() { return myIsCancel; } public ConvertSBitTBitPlugin.CONVERT_TYPE getConvertType() { if (mySBit.isSelected()) { return ConvertSBitTBitPlugin.CONVERT_TYPE.sbit; } else if (myTBit.isSelected()) { return ConvertSBitTBitPlugin.CONVERT_TYPE.tbit; } else { throw new IllegalStateException("ConvertSBitTBitPluginDialog: getType: Unknown state."); } } }
package org.jpos.qi; import com.vaadin.shared.ui.MarginInfo; import com.vaadin.ui.*; import org.jpos.ee.BLException; public class ConfirmDialog extends Window implements Button.ClickListener { Callback callback; Button yes = new Button("Yes", this); Button no = new Button("No", this); public ConfirmDialog(String caption, String question, Callback callback) { super(caption); setModal(true); setResizable(false); VerticalLayout content = new VerticalLayout(); content.setMargin(true); content.setSpacing(true); setContent(content); this.callback = callback; if (question != null) { content.addComponent(new Label(question)); } HorizontalLayout hl = new HorizontalLayout(); hl.setMargin(new MarginInfo(true, false, false, false)); hl.setSpacing(true); hl.setWidth("100%"); hl.addComponent(yes); hl.setComponentAlignment(yes, Alignment.MIDDLE_CENTER); hl.addComponent(no); hl.setComponentAlignment(no, Alignment.MIDDLE_CENTER); content.addComponent(hl); } @Override public void buttonClick(Button.ClickEvent event) { if (getParent() != null) close(); try { callback.onDialogResult(event.getSource() == yes); } catch (BLException e) { QI.getQI().getLog().error(e); } } public interface Callback{ void onDialogResult(boolean resultIsYes) throws BLException; } }
package org.adligo.xml_io.client; import java.math.BigDecimal; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.adligo.i.util.client.I_Iterator; import org.adligo.models.params.client.I_XMLBuilder; import org.adligo.models.params.client.Parser; import org.adligo.models.params.client.TagAttribute; import org.adligo.models.params.client.TagInfo; /** * this kind of code will be autogenerated, * it is just a simple example * * @author scott * */ public class CustomSimpleModelConverter implements I_Converter<CustomSimpleModel> { public static final String CUSTOM_NAMESPACE = "http: private static final String TAG_NAME = "ctm"; private static final Map<String, I_AttributeSetter<CustomSimpleModel>> SETTERS = getSetters(); public static Map<String, I_AttributeSetter<CustomSimpleModel>> getSetters() { Map<String, I_AttributeSetter<CustomSimpleModel>> toRet = new HashMap<String, I_AttributeSetter<CustomSimpleModel>>(); toRet.put("a", new I_AttributeSetter<CustomSimpleModel>() { public void set(CustomSimpleModel obj, String value, Xml_IOReaderContext context) { Object toSet = context.readAttribute(BigDecimal.class, value); obj.setA((BigDecimal) toSet); } }); toRet.put("b", new I_AttributeSetter<CustomSimpleModel>() { public void set(CustomSimpleModel obj, String value, Xml_IOReaderContext context) { Object toSet = context.readAttribute(BigDecimal.class, value); obj.setB((BigDecimal) toSet); } }); return Collections.unmodifiableMap(toRet); } @Override public ObjectFromXml<CustomSimpleModel> fromXml(String xml, TagInfo info, Xml_IOReaderContext context) { //the CustomModel class is mutable so just call setters CustomSimpleModel toRet = new CustomSimpleModel(); I_Iterator it = Parser.getAttributes(info, xml); while (it.hasNext()) { TagAttribute attrib = (TagAttribute) it.next(); String name = attrib.getName(); String value = attrib.getValue(); I_AttributeSetter<CustomSimpleModel> setter = SETTERS.get(name); if (setter != null) { setter.set(toRet, value, context); } } return new ObjectFromXml<CustomSimpleModel>(toRet); } @Override public void toXml(CustomSimpleModel p, Xml_IOWriterContext context) { I_XMLBuilder builder = context.getBuilder(); context.appendTagHeaderStart(CUSTOM_NAMESPACE, TAG_NAME); context.appendSchemaInfoToFirstTag(); String name = context.getNextTagNameAttribute(); if (name != null) { builder.appendAttribute(Xml_IOConstants.N_NAME_ATTRIBUTE, name); } context.writeXmlAttribute("a", p.getA()); context.writeXmlAttribute("b", p.getB()); builder.appendTagHeaderEndNoChildren(); } public static void setUp(Xml_IOSettings settings) { settings.addNamespace(CUSTOM_NAMESPACE); NamespaceConverters converters = new NamespaceConverters(); converters.setNamespace(CUSTOM_NAMESPACE); converters.addXmlToObjectConverter(TAG_NAME, new CustomSimpleModelConverter()); converters.addObjectToXmlConverter(CustomSimpleModel.class, new CustomSimpleModelConverter()); settings.addNamespaceConverter(converters); } }
package org.bouncycastle.mail.smime.test; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.security.KeyPair; import java.security.MessageDigest; import java.security.cert.X509Certificate; import java.util.Arrays; import javax.activation.CommandMap; import javax.activation.MailcapCommandMap; import javax.mail.MessagingException; import javax.mail.internet.MimeBodyPart; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.bouncycastle.cms.RecipientId; import org.bouncycastle.cms.RecipientInformation; import org.bouncycastle.cms.RecipientInformationStore; import org.bouncycastle.cms.test.CMSTestUtil; import org.bouncycastle.mail.smime.SMIMECompressedGenerator; import org.bouncycastle.mail.smime.SMIMEEnveloped; import org.bouncycastle.mail.smime.SMIMEEnvelopedGenerator; import org.bouncycastle.mail.smime.SMIMEEnvelopedParser; import org.bouncycastle.mail.smime.SMIMEUtil; public class SMIMEEnvelopedTest extends TestCase { /* * * VARIABLES * */ public boolean DEBUG = true; private static String _signDN; private static KeyPair _signKP; private static X509Certificate _signCert; private static String _origDN; private static KeyPair _origKP; private static X509Certificate _origCert; private static String _reciDN; private static KeyPair _reciKP; private static X509Certificate _reciCert; private static boolean _initialised = false; private static void init() throws Exception { if (!_initialised) { _initialised = true; _signDN = "O=Bouncy Castle, C=AU"; _signKP = CMSTestUtil.makeKeyPair(); _signCert = CMSTestUtil.makeCertificate(_signKP, _signDN, _signKP, _signDN); _origDN = "CN=Bob, OU=Sales, O=Bouncy Castle, C=AU"; _origKP = CMSTestUtil.makeKeyPair(); _origCert = CMSTestUtil.makeCertificate(_origKP, _origDN, _signKP, _signDN); _reciDN = "CN=Doug, OU=Sales, O=Bouncy Castle, C=AU"; _reciKP = CMSTestUtil.makeKeyPair(); _reciCert = CMSTestUtil.makeCertificate(_reciKP, _reciDN, _signKP, _signDN); } } /* * * INFRASTRUCTURE * */ public SMIMEEnvelopedTest(String name) { super(name); } public static void main(String args[]) { MailcapCommandMap _mailcap = (MailcapCommandMap)CommandMap.getDefaultCommandMap(); _mailcap.addMailcap("application/pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_signature"); _mailcap.addMailcap("application/pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_mime"); _mailcap.addMailcap("application/x-pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_signature"); _mailcap.addMailcap("application/x-pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_mime"); _mailcap.addMailcap("multipart/signed;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.multipart_signed"); CommandMap.setDefaultCommandMap(_mailcap); junit.textui.TestRunner.run(SMIMEEnvelopedTest.class); } public static Test suite() throws Exception { init(); return new SMIMETestSetup(new TestSuite(SMIMEEnvelopedTest.class)); } public void log(Exception _ex) { if(DEBUG) { _ex.printStackTrace(); } } public void log(String _msg) { if(DEBUG) { System.out.println(_msg); } } public void testHeaders() throws Exception { MimeBodyPart _msg = SMIMETestUtil.makeMimeBodyPart("WallaWallaWashington"); SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator(); gen.addKeyTransRecipient(_reciCert); // generate a MimeBodyPart object which encapsulates the content // we want encrypted. MimeBodyPart mp = gen.generate(_msg, SMIMEEnvelopedGenerator.DES_EDE3_CBC, "BC"); assertEquals("application/pkcs7-mime; name=\"smime.p7m\"; smime-type=enveloped-data", mp.getHeader("Content-Type")[0]); assertEquals("attachment; filename=\"smime.p7m\"", mp.getHeader("Content-Disposition")[0]); assertEquals("S/MIME Encrypted Message", mp.getHeader("Content-Description")[0]); } public void testDESEDE3Encrypted() throws Exception { MimeBodyPart _msg = SMIMETestUtil.makeMimeBodyPart("WallaWallaWashington"); SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator(); gen.addKeyTransRecipient(_reciCert); // generate a MimeBodyPart object which encapsulates the content // we want encrypted. MimeBodyPart mp = gen.generate(_msg, SMIMEEnvelopedGenerator.DES_EDE3_CBC, "BC"); SMIMEEnveloped m = new SMIMEEnveloped(mp); RecipientId recId = new RecipientId(); recId.setSerialNumber(_reciCert.getSerialNumber()); recId.setIssuer(_reciCert.getIssuerX500Principal().getEncoded()); RecipientInformationStore recipients = m.getRecipientInfos(); RecipientInformation recipient = recipients.get(recId); MimeBodyPart res = SMIMEUtil.toMimeBodyPart(recipient.getContent(_reciKP.getPrivate(), "BC")); verifyMessageBytes(_msg, res); } public void testParserDESEDE3Encrypted() throws Exception { MimeBodyPart _msg = SMIMETestUtil.makeMimeBodyPart("WallaWallaWashington"); SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator(); gen.addKeyTransRecipient(_reciCert); // generate a MimeBodyPart object which encapsulates the content // we want encrypted. MimeBodyPart mp = gen.generate(_msg, SMIMEEnvelopedGenerator.DES_EDE3_CBC, "BC"); SMIMEEnvelopedParser m = new SMIMEEnvelopedParser(mp); RecipientId recId = new RecipientId(); recId.setSerialNumber(_reciCert.getSerialNumber()); recId.setIssuer(_reciCert.getIssuerX500Principal().getEncoded()); RecipientInformationStore recipients = m.getRecipientInfos(); RecipientInformation recipient = recipients.get(recId); MimeBodyPart res = new MimeBodyPart(recipient.getContentStream(_reciKP.getPrivate(), "BC").getContentStream()); verifyMessageBytes(_msg, res); } public void testIDEAEncrypted() throws Exception { MimeBodyPart _msg = SMIMETestUtil.makeMimeBodyPart("WallaWallaWashington"); SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator(); gen.addKeyTransRecipient(_reciCert); // generate a MimeBodyPart object which encapsulates the content // we want encrypted. MimeBodyPart mp = gen.generate(_msg, SMIMEEnvelopedGenerator.IDEA_CBC, "BC"); SMIMEEnveloped m = new SMIMEEnveloped(mp); RecipientId recId = new RecipientId(); recId.setSerialNumber(_reciCert.getSerialNumber()); recId.setIssuer(_reciCert.getIssuerX500Principal().getEncoded()); RecipientInformationStore recipients = m.getRecipientInfos(); RecipientInformation recipient = recipients.get(recId); MimeBodyPart res = SMIMEUtil.toMimeBodyPart(recipient.getContent(_reciKP.getPrivate(), "BC")); verifyMessageBytes(_msg, res); } private void verifyMessageBytes(MimeBodyPart a, MimeBodyPart b) throws IOException, MessagingException { ByteArrayOutputStream _baos = new ByteArrayOutputStream(); a.writeTo(_baos); _baos.close(); byte[] _msgBytes = _baos.toByteArray(); _baos = new ByteArrayOutputStream(); b.writeTo(_baos); _baos.close(); byte[] _resBytes = _baos.toByteArray(); assertEquals(true, Arrays.equals(_msgBytes, _resBytes)); } public void testRC2Encrypted() throws Exception { MimeBodyPart _msg = SMIMETestUtil.makeMimeBodyPart("WallaWallaWashington"); SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator(); gen.addKeyTransRecipient(_reciCert); // generate a MimeBodyPart object which encapsulates the content // we want encrypted. MimeBodyPart mp = gen.generate(_msg, SMIMEEnvelopedGenerator.RC2_CBC, "BC"); SMIMEEnveloped m = new SMIMEEnveloped(mp); RecipientId recId = new RecipientId(); recId.setSerialNumber(_reciCert.getSerialNumber()); recId.setIssuer(_reciCert.getIssuerX500Principal().getEncoded()); RecipientInformationStore recipients = m.getRecipientInfos(); RecipientInformation recipient = recipients.get(recId); MimeBodyPart res = SMIMEUtil.toMimeBodyPart(recipient.getContent(_reciKP.getPrivate(), "BC")); verifyMessageBytes(_msg, res); } public void testCASTEncrypted() throws Exception { MimeBodyPart _msg = SMIMETestUtil.makeMimeBodyPart("WallaWallaWashington"); SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator(); gen.addKeyTransRecipient(_reciCert); // generate a MimeBodyPart object which encapsulates the content // we want encrypted. MimeBodyPart mp = gen.generate(_msg, SMIMEEnvelopedGenerator.CAST5_CBC, "BC"); SMIMEEnveloped m = new SMIMEEnveloped(mp); RecipientId recId = new RecipientId(); recId.setSerialNumber(_reciCert.getSerialNumber()); recId.setIssuer(_reciCert.getIssuerX500Principal().getEncoded()); RecipientInformationStore recipients = m.getRecipientInfos(); RecipientInformation recipient = recipients.get(recId); MimeBodyPart res = SMIMEUtil.toMimeBodyPart(recipient.getContent(_reciKP.getPrivate(), "BC")); verifyMessageBytes(_msg, res); } public void testSubKeyId() throws Exception { MimeBodyPart _msg = SMIMETestUtil.makeMimeBodyPart("WallaWallaWashington"); SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator(); // create a subject key id - this has to be done the same way as // it is done in the certificate associated with the private key MessageDigest dig = MessageDigest.getInstance("SHA1", "BC"); dig.update(_reciCert.getPublicKey().getEncoded()); gen.addKeyTransRecipient(_reciCert.getPublicKey(), dig.digest()); // generate a MimeBodyPart object which encapsulates the content // we want encrypted. MimeBodyPart mp = gen.generate(_msg, SMIMEEnvelopedGenerator.DES_EDE3_CBC, "BC"); SMIMEEnveloped m = new SMIMEEnveloped(mp); RecipientId recId = new RecipientId(); dig.update(_reciCert.getPublicKey().getEncoded()); recId.setSubjectKeyIdentifier(dig.digest()); RecipientInformationStore recipients = m.getRecipientInfos(); RecipientInformation recipient = recipients.get(recId); MimeBodyPart res = SMIMEUtil.toMimeBodyPart(recipient.getContent(_reciKP.getPrivate(), "BC")); verifyMessageBytes(_msg, res); } public void testCapEncrypt() throws Exception { MimeBodyPart _msg = SMIMETestUtil.makeMimeBodyPart("WallaWallaWashington"); SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator(); // create a subject key id - this has to be done the same way as // it is done in the certificate associated with the private key MessageDigest dig = MessageDigest.getInstance("SHA1", "BC"); dig.update(_reciCert.getPublicKey().getEncoded()); gen.addKeyTransRecipient(_reciCert.getPublicKey(), dig.digest()); // generate a MimeBodyPart object which encapsulates the content // we want encrypted. MimeBodyPart mp = gen.generate(_msg, SMIMEEnvelopedGenerator.RC2_CBC, 40, "BC"); SMIMEEnveloped m = new SMIMEEnveloped(mp); RecipientId recId = new RecipientId(); dig.update(_reciCert.getPublicKey().getEncoded()); recId.setSubjectKeyIdentifier(dig.digest()); RecipientInformationStore recipients = m.getRecipientInfos(); RecipientInformation recipient = recipients.get(recId); MimeBodyPart res = SMIMEUtil.toMimeBodyPart(recipient.getContent(_reciKP.getPrivate(), "BC")); verifyMessageBytes(_msg, res); } }
package org.jetbrains.plugins.scala.compiler; import com.intellij.compiler.CompilerConfigurationImpl; import com.intellij.compiler.OutputParser; import com.intellij.compiler.impl.javaCompiler.DependencyProcessor; import com.intellij.compiler.impl.javaCompiler.ExternalCompiler; import com.intellij.compiler.impl.javaCompiler.ModuleChunk; import com.intellij.compiler.impl.javaCompiler.javac.JavacSettings; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.compiler.CompileContext; import com.intellij.openapi.compiler.CompileScope; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.module.Module; import com.intellij.openapi.options.Configurable; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.JavaSdkType; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.projectRoots.impl.MockJdkWrapper; import com.intellij.openapi.roots.*; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.JarFileSystem; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.PathUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.scala.ScalaBundle; import org.jetbrains.plugins.scala.ScalaFileType; import org.jetbrains.plugins.scala.compiler.rt.ScalacRunner; import org.jetbrains.plugins.scala.config.ScalaConfigUtils; import org.jetbrains.plugins.scala.util.ScalaUtils; import java.io.*; import java.util.*; /** * @author ilyas */ public class ScalacCompiler extends ExternalCompiler { private static final Logger LOG = Logger.getInstance("#org.jetbrains.plugins.scala.compiler.ScalacCompiler"); private final Project myProject; private final List<File> myTempFiles = new ArrayList<File>(); // VM properties @NonNls private static final String XMX_COMPILER_PROPERTY = "-Xmx300m"; @NonNls private final String XSS_COMPILER_PROPERTY = "-Xss128m"; // Scalac parameters @NonNls private static final String DEBUG_INFO_LEVEL_PROPEERTY = "-g:vars"; @NonNls private static final String VERBOSE_PROPERTY = "-verbose"; @NonNls private static final String DESTINATION_COMPILER_PROPERTY = "-d"; @NonNls private static final String DEBUG_PROPERTY = "-Ydebug"; @NonNls private static final String WARNINGS_PROPERTY = "-unchecked"; private final static HashSet<FileType> COMPILABLE_FILE_TYPES = new HashSet<FileType>(Arrays.asList(ScalaFileType.SCALA_FILE_TYPE, StdFileTypes.JAVA)); public ScalacCompiler(Project project) { myProject = project; } public boolean checkCompiler(CompileScope scope) { VirtualFile[] files = scope.getFiles(ScalaFileType.SCALA_FILE_TYPE, true); if (files.length == 0) return true; final ProjectFileIndex index = ProjectRootManager.getInstance(myProject).getFileIndex(); Set<Module> modules = new HashSet<Module>(); for (VirtualFile file : files) { Module module = index.getModuleForFile(file); if (module != null) { modules.add(module); } } boolean hasJava = false; for (Module module : modules) { if (ScalaUtils.isSuitableModule(module)) { hasJava = true; } } if (!hasJava) return false; //this compiler work with only Java modules, so we don't need to continue. for (Module module : modules) { final String installPath = ScalaConfigUtils.getScalaInstallPath(module); if (installPath.length() == 0 && ScalaUtils.isSuitableModule(module)) { Messages.showErrorDialog(myProject, ScalaBundle.message("cannot.compile.scala.files.no.facet", module.getName()), ScalaBundle.message("cannot.compile")); return false; } } Set<Module> nojdkModules = new HashSet<Module>(); for (Module module : scope.getAffectedModules()) { if (!(ScalaUtils.isSuitableModule(module))) continue; Sdk sdk = ModuleRootManager.getInstance(module).getSdk(); if (sdk == null || !(sdk.getSdkType() instanceof JavaSdkType)) { nojdkModules.add(module); } } if (!nojdkModules.isEmpty()) { final Module[] noJdkArray = nojdkModules.toArray(new Module[nojdkModules.size()]); if (noJdkArray.length == 1) { Messages.showErrorDialog(myProject, ScalaBundle.message("cannot.compile.scala.files.no.sdk", noJdkArray[0].getName()), ScalaBundle.message("cannot.compile")); } else { StringBuffer modulesList = new StringBuffer(); for (int i = 0; i < noJdkArray.length; i++) { if (i > 0) modulesList.append(", "); modulesList.append(noJdkArray[i].getName()); } Messages.showErrorDialog(myProject, ScalaBundle.message("cannot.compile.scala.files.no.sdk.mult", modulesList.toString()), ScalaBundle.message("cannot.compile")); } return false; } return true; } @NotNull public String getId() { return "Scalac"; } @NotNull public String getPresentableName() { return ScalaBundle.message("scalac.compiler.name"); } @NotNull public Configurable createConfigurable() { return null; } public OutputParser createErrorParser(String outputDir) { return new ScalacOutputParser(); } public OutputParser createOutputParser(String outputDir) { return new OutputParser() { @Override public boolean processMessageLine(Callback callback) { if (super.processMessageLine(callback)) { return true; } return callback.getCurrentLine() != null; } }; } @NotNull public String[] createStartupCommand(final ModuleChunk chunk, CompileContext context, final String outputPath) throws IOException, IllegalArgumentException { final ArrayList<String> commandLine = new ArrayList<String>(); final Exception[] ex = new Exception[]{null}; ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { try { createStartupCommandImpl(chunk, commandLine, outputPath); } catch (IllegalArgumentException e) { ex[0] = e; } catch (IOException e) { ex[0] = e; } } }); if (ex[0] != null) { if (ex[0] instanceof IOException) { throw (IOException) ex[0]; } else if (ex[0] instanceof IllegalArgumentException) { throw (IllegalArgumentException) ex[0]; } else { LOG.error(ex[0]); } } return commandLine.toArray(new String[commandLine.size()]); } @NotNull @Override public Set<FileType> getCompilableFileTypes() { return COMPILABLE_FILE_TYPES; } @Override public DependencyProcessor getDependencyProcessor() { return new ScalacDependencyProcessor(); } private void createStartupCommandImpl(ModuleChunk chunk, ArrayList<String> commandLine, String outputPath) throws IOException { final Sdk jdk = getJdkForStartupCommand(chunk); final String versionString = jdk.getVersionString(); if (versionString == null || "".equals(versionString)) { throw new IllegalArgumentException(ScalaBundle.message("javac.error.unknown.jdk.version", jdk.getName())); } final JavaSdkType sdkType = (JavaSdkType) jdk.getSdkType(); final String toolsJarPath = sdkType.getToolsPath(jdk); if (toolsJarPath == null) { throw new IllegalArgumentException(ScalaBundle.message("javac.error.tools.jar.missing", jdk.getName())); } if (!allModulesHaveSameScalaSdk(chunk)) { throw new IllegalArgumentException(ScalaBundle.message("different.scala.sdk.in.modules")); } String javaExecutablePath = sdkType.getVMExecutablePath(jdk); commandLine.add(javaExecutablePath); ScalacSettings settings = ScalacSettings.getInstance(myProject); commandLine.add(XSS_COMPILER_PROPERTY); commandLine.add("-Xmx" + settings.MAXIMUM_HEAP_SIZE + "m"); commandLine.add("-cp"); // For debug // commandLine.add("-Xdebug"); // commandLine.add("-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=127.0.0.1:5448"); String rtJarPath = PathUtil.getJarPathForClass(ScalacRunner.class); final StringBuilder classPathBuilder = new StringBuilder(); classPathBuilder.append(rtJarPath).append(File.pathSeparator); classPathBuilder.append(sdkType.getToolsPath(jdk)).append(File.pathSeparator); String scalaPath = ScalaConfigUtils.getScalaInstallPath(chunk.getModules()[0]); String libPath = (scalaPath + "/lib").replace(File.separatorChar, '/'); VirtualFile lib = LocalFileSystem.getInstance().findFileByPath(libPath); if (lib != null) { for (VirtualFile file : lib.getChildren()) { if (required(file.getName())) { classPathBuilder.append(file.getPath()); classPathBuilder.append(File.pathSeparator); } } } commandLine.add(classPathBuilder.toString()); commandLine.add(ScalacRunner.class.getName()); try { File fileWithParams = File.createTempFile("scalac", ".tmp"); fillFileWithScalacParams(chunk, fileWithParams, outputPath, myProject); commandLine.add(fileWithParams.getPath()); } catch (IOException e) { LOG.error(e); } } private static void fillFileWithScalacParams(ModuleChunk chunk, File fileWithParameters, String outputPath, Project myProject) throws FileNotFoundException { PrintStream printer = new PrintStream(new FileOutputStream(fileWithParameters)); ScalacSettings settings = ScalacSettings.getInstance(myProject); StringTokenizer tokenizer = new StringTokenizer(settings.getOptionsString(), " "); while (tokenizer.hasMoreTokens()) { printer.println(tokenizer.nextToken()); } printer.println(VERBOSE_PROPERTY); printer.println(DEBUG_PROPERTY); //printer.println(WARNINGS_PROPERTY); printer.println(DEBUG_INFO_LEVEL_PROPEERTY); printer.println(DESTINATION_COMPILER_PROPERTY); printer.println(outputPath.replace('/', File.separatorChar)); //write classpath printer.println("-cp"); final Module[] chunkModules = chunk.getModules(); final List<Module> modules = Arrays.asList(chunkModules); final Set<VirtualFile> sourceDependencies = new HashSet<VirtualFile>(); for (Module module : modules) { if (ScalaUtils.isSuitableModule(module)) { ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module); OrderEntry[] entries = moduleRootManager.getOrderEntries(); Set<VirtualFile> cpVFiles = new HashSet<VirtualFile>(); for (OrderEntry orderEntry : entries) { cpVFiles.addAll(Arrays.asList(orderEntry.getFiles(OrderRootType.COMPILATION_CLASSES))); // Add Java dependencies if (orderEntry instanceof ModuleOrderEntry && !(modules.contains(((ModuleOrderEntry) orderEntry).getModule()))) { sourceDependencies.addAll(Arrays.asList(orderEntry.getFiles(OrderRootType.SOURCES))); } } for (VirtualFile file : cpVFiles) { String path = file.getPath(); int jarSeparatorIndex = path.indexOf(JarFileSystem.JAR_SEPARATOR); if (jarSeparatorIndex > 0) { path = path.substring(0, jarSeparatorIndex); } printer.print(path); printer.print(File.pathSeparator); } } } printer.println(); boolean isTestChunk = false; if (chunkModules.length > 0) { ProjectRootManager rm = ProjectRootManager.getInstance(chunkModules[0].getProject()); for (VirtualFile file : chunk.getSourceRoots()) { if (file != null && rm.getFileIndex().isInTestSourceContent(file)) { isTestChunk = true; break; } } } //Little hack to make compiler fork with java files from test sources if (isTestChunk) { chunk.setSourcesFilter(ModuleChunk.ALL_SOURCES); } for (VirtualFile file : chunk.getFilesToCompile()) { printer.println(file.getPath()); } for (VirtualFile sourceDependency : sourceDependencies) { addJavaSourceFiles(printer, sourceDependency); } printer.close(); } private static void addJavaSourceFiles(PrintStream stream, VirtualFile src) { if (src.getPath().contains("!/")) return; if (src.isDirectory()) { for (VirtualFile file : src.getChildren()) { addJavaSourceFiles(stream, file); } } else if (src.getFileType() == StdFileTypes.JAVA){ stream.println(src.getPath()); } } private boolean allModulesHaveSameScalaSdk(ModuleChunk chunk) { if (chunk.getModuleCount() == 0) return false; final Module[] modules = chunk.getModules(); final Module first = modules[0]; final String firstVersion = ScalaConfigUtils.getScalaVersion(ScalaConfigUtils.getScalaInstallPath(first)); for (Module module : modules) { final String path = ScalaConfigUtils.getScalaInstallPath(module); final String version = ScalaConfigUtils.getScalaVersion(path); if (!version.equals(firstVersion)) return false; } return true; } public void compileFinished() { FileUtil.asyncDelete(myTempFiles); } private Sdk getJdkForStartupCommand(final ModuleChunk chunk) { final Sdk jdk = chunk.getJdk(); if (ApplicationManager.getApplication().isUnitTestMode() && JavacSettings.getInstance(myProject).isTestsUseExternalCompiler()) { final String jdkHomePath = CompilerConfigurationImpl.getTestsExternalCompilerHome(); if (jdkHomePath == null) { throw new IllegalArgumentException("[TEST-MODE] Cannot determine home directory for JDK to use javac from"); } // when running under Mock JDK use VM executable from the JDK on which the tests run return new MockJdkWrapper(jdkHomePath, jdk); } return jdk; } static HashSet<String> required = new HashSet<String>(); static { required.add("scala"); required.add("sbaz"); required.add("fjbg"); required.add("jline"); } private static boolean required(String name) { name = name.toLowerCase(); if (!name.endsWith(".jar")) return false; final String realName = name; name = name.substring(0, name.lastIndexOf('.')); int ind = name.lastIndexOf('-'); if (ind != -1 && name.length() > ind + 1 && Character.isDigit(name.charAt(ind + 1))) { name = name.substring(0, ind); } for (String requiredStr : required) { if (name.contains(requiredStr)) return true; } return false; } }
package io.airlift.stats; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Objects; import com.google.common.collect.ImmutableList; import org.weakref.jmx.Managed; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.ThreadSafe; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @ThreadSafe public class Distribution { private final static double MAX_ERROR = 0.01; @GuardedBy("this") private final QuantileDigest digest; public Distribution() { digest = new QuantileDigest(MAX_ERROR); } public Distribution(double alpha) { digest = new QuantileDigest(MAX_ERROR, alpha); } public Distribution(Distribution distribution) { digest = new QuantileDigest(distribution.digest); } public synchronized void add(long value) { digest.add(value); } public synchronized void add(long value, long count) { digest.add(value, count); } @Managed public synchronized double getMaxError() { return digest.getConfidenceFactor(); } @Managed public synchronized double getCount() { return digest.getCount(); } @Managed public synchronized long getP01() { return digest.getQuantile(0.01); } @Managed public synchronized long getP05() { return digest.getQuantile(0.05); } @Managed public synchronized long getP10() { return digest.getQuantile(0.10); } @Managed public synchronized long getP25() { return digest.getQuantile(0.25); } @Managed public synchronized long getP50() { return digest.getQuantile(0.5); } @Managed public synchronized long getP75() { return digest.getQuantile(0.75); } @Managed public synchronized long getP90() { return digest.getQuantile(0.90); } @Managed public synchronized long getP95() { return digest.getQuantile(0.95); } @Managed public synchronized long getP99() { return digest.getQuantile(0.99); } @Managed public synchronized long getMin() { return digest.getMin(); } @Managed public synchronized long getMax() { return digest.getMax(); } @Managed public Map<Double, Long> getPercentiles() { List<Double> percentiles = new ArrayList<>(100); for (int i = 0; i < 100; ++i) { percentiles.add(i / 100.0); } List<Long> values; synchronized (this) { values = digest.getQuantiles(percentiles); } Map<Double, Long> result = new LinkedHashMap<>(values.size()); for (int i = 0; i < percentiles.size(); ++i) { result.put(percentiles.get(i), values.get(i)); } return result; } public synchronized List<Long> getPercentiles(List<Double> percentiles) { return digest.getQuantiles(percentiles); } public synchronized DistributionSnapshot snapshot() { List<Long> quantiles = digest.getQuantiles(ImmutableList.of(0.01, 0.05, 0.10, 0.25, 0.5, 0.75, 0.9, 0.95, 0.99)); return new DistributionSnapshot( getMaxError(), getCount(), quantiles.get(0), quantiles.get(1), quantiles.get(2), quantiles.get(3), quantiles.get(4), quantiles.get(5), quantiles.get(6), quantiles.get(7), quantiles.get(8), getMin(), getMax()); } public static class DistributionSnapshot { private final double maxError; private final double count; private final long p01; private final long p05; private final long p10; private final long p25; private final long p50; private final long p75; private final long p90; private final long p95; private final long p99; private final long min; private final long max; @JsonCreator public DistributionSnapshot( @JsonProperty("maxError") double maxError, @JsonProperty("count") double count, @JsonProperty("p01") long p01, @JsonProperty("p05") long p05, @JsonProperty("p10") long p10, @JsonProperty("p25") long p25, @JsonProperty("p50") long p50, @JsonProperty("p75") long p75, @JsonProperty("p90") long p90, @JsonProperty("p95") long p95, @JsonProperty("p99") long p99, @JsonProperty("min") long min, @JsonProperty("max") long max) { this.maxError = maxError; this.count = count; this.p01 = p01; this.p05 = p05; this.p10 = p10; this.p25 = p25; this.p50 = p50; this.p75 = p75; this.p90 = p90; this.p95 = p95; this.p99 = p99; this.min = min; this.max = max; } @JsonProperty public double getMaxError() { return maxError; } @JsonProperty public double getCount() { return count; } @JsonProperty public long getP01() { return p01; } @JsonProperty public long getP05() { return p05; } @JsonProperty public long getP10() { return p10; } @JsonProperty public long getP25() { return p25; } @JsonProperty public long getP50() { return p50; } @JsonProperty public long getP75() { return p75; } @JsonProperty public long getP90() { return p90; } @JsonProperty public long getP95() { return p95; } @JsonProperty public long getP99() { return p99; } @JsonProperty public long getMin() { return min; } @JsonProperty public long getMax() { return max; } @Override public String toString() { return Objects.toStringHelper(this) .add("maxError", maxError) .add("count", count) .add("p01", p01) .add("p05", p05) .add("p10", p10) .add("p25", p25) .add("p50", p50) .add("p75", p75) .add("p90", p90) .add("p95", p95) .add("p99", p99) .add("min", min) .add("max", max) .toString(); } } }
package org.metawatch.manager; import java.util.Arrays; import org.metawatch.manager.MetaWatchService.Preferences; import android.accessibilityservice.AccessibilityService; import android.accessibilityservice.AccessibilityServiceInfo; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.Bitmap; import android.os.Parcelable; import android.preference.PreferenceManager; import android.util.Log; import android.view.accessibility.AccessibilityEvent; public class MetaWatchAccessibilityService extends AccessibilityService { @Override protected void onServiceConnected() { super.onServiceConnected(); AccessibilityServiceInfo asi = new AccessibilityServiceInfo(); asi.eventTypes = AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED | AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED; asi.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC; asi.flags = AccessibilityServiceInfo.DEFAULT; asi.notificationTimeout = 100; setServiceInfo(asi); // ArrayList<PInfo> apps = getInstalledApps(true); // for (PInfo pinfo : apps) { // appsByPackage.put(pinfo.pname, pinfo); } private String currentActivity = ""; public static boolean accessibilityReceived = false; private static String lastNotificationPackage = ""; private static String lastNotificationText = ""; private static long lastNotificationWhen = 0; @Override public void onAccessibilityEvent(AccessibilityEvent event) { if(!accessibilityReceived) { accessibilityReceived = true; MetaWatchService.notifyClients(); } /* Acquire details of event. */ int eventType = event.getEventType(); String packageName = event.getPackageName().toString(); String className = event.getClassName().toString(); if (eventType == AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED) { if (Preferences.logging) Log.d(MetaWatch.TAG, "MetaWatchAccessibilityService.onAccessibilityEvent(): Received event, packageName = '" + packageName + "' className = '" + className + "'"); Parcelable p = event.getParcelableData(); if (p instanceof android.app.Notification == false) { if (Preferences.logging) Log.d(MetaWatch.TAG, "MetaWatchAccessibilityService.onAccessibilityEvent(): Not a real notification, ignoring."); return; } android.app.Notification notification = (android.app.Notification) p; if (Preferences.logging) Log.d(MetaWatch.TAG, "MetaWatchAccessibilityService.onAccessibilityEvent(): notification text = '" + notification.tickerText + "' flags = " + notification.flags + " (" + Integer.toBinaryString(notification.flags) + ")"); if (notification.tickerText == null || notification.tickerText.toString().trim().length() == 0) { if (Preferences.logging) Log.d(MetaWatch.TAG, "MetaWatchAccessibilityService.onAccessibilityEvent(): Empty text, ignoring."); return; } String tickerText = notification.tickerText.toString(); if (lastNotificationPackage.equals(packageName) && lastNotificationText.equals(tickerText) && lastNotificationWhen == notification.when) { if (Preferences.logging) Log.d(MetaWatch.TAG, "MetaWatchAccessibilityService.onAccessibilityEvent(): Duplicate notification, ignoring."); return; } lastNotificationPackage = packageName; lastNotificationText = tickerText; lastNotificationWhen = notification.when; SharedPreferences sharedPreferences = PreferenceManager .getDefaultSharedPreferences(this); /* Forward calendar event */ if (packageName.equals("com.android.calendar")) { if (sharedPreferences.getBoolean("NotifyCalendar", true)) { if (Preferences.logging) Log.d(MetaWatch.TAG, "onAccessibilityEvent(): Sending calendar event: '" + tickerText + "'."); NotificationBuilder.createCalendar(this, tickerText); return; } } /* Forward google chat or voice event */ if (packageName.equals("com.google.android.gsf") || packageName.equals("com.google.android.apps.googlevoice")) { if (sharedPreferences.getBoolean("notifySMS", true)) { if (Preferences.logging) Log.d(MetaWatch.TAG, "onAccessibilityEvent(): Sending SMS event: '" + tickerText + "'."); NotificationBuilder.createSMS(this,"Google Message", tickerText); return; } } /* Deezer or Spotify track notification */ if (packageName.equals("deezer.android.app") || packageName.equals("com.spotify.mobile.android.ui")) { String text = tickerText.trim(); int truncatePos = text.indexOf(" - "); if (truncatePos>-1) { String artist = text.substring(0, truncatePos); String track = text.substring(truncatePos+3); MediaControl.updateNowPlaying(this, artist, "", track, packageName); return; } return; } if ((notification.flags & android.app.Notification.FLAG_ONGOING_EVENT) > 0) { /* Ignore updates to ongoing events. */ if (Preferences.logging) Log.d(MetaWatch.TAG, "MetaWatchAccessibilityService.onAccessibilityEvent(): Ongoing event, ignoring."); return; } /* Some other notification */ if (sharedPreferences.getBoolean("NotifyOtherNotification", true)) { String[] appBlacklist = sharedPreferences.getString("appBlacklist", OtherAppsList.DEFAULT_BLACKLIST).split(","); Arrays.sort(appBlacklist); /* Ignore if on blacklist */ if (Arrays.binarySearch(appBlacklist, packageName) >= 0) { if (Preferences.logging) Log.d(MetaWatch.TAG, "onAccessibilityEvent(): App is blacklisted, ignoring."); return; } Bitmap icon = null; PackageManager pm = getPackageManager(); PackageInfo packageInfo = null; String appName = null; try { packageInfo = pm.getPackageInfo(packageName.toString(), 0); appName = packageInfo.applicationInfo.loadLabel(pm).toString(); int iconId = notification.icon; icon = NotificationIconShrinker.shrink( pm.getResourcesForApplication(packageInfo.applicationInfo), iconId, packageName.toString(), NotificationIconShrinker.NOTIFICATION_ICON_SIZE); } catch (NameNotFoundException e) { /* OK, appName is null */ } int buzzes = sharedPreferences.getInt("appVibrate_" + packageName, -1); if (appName == null) { if (Preferences.logging) Log.d(MetaWatch.TAG, "onAccessibilityEvent(): Unknown app -- sending notification: '" + tickerText + "'."); NotificationBuilder.createOtherNotification(this, icon, "Notification", tickerText, buzzes); } else { if (Preferences.logging) Log.d(MetaWatch.TAG, "onAccessibilityEvent(): Sending notification: app='" + appName + "' notification='" + tickerText + "'."); NotificationBuilder.createOtherNotification(this, icon, appName, tickerText, buzzes); } } } else if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) { if (currentActivity.startsWith("com.fsck.k9")) { if (!className.startsWith("com.fsck.k9")) { // User has switched away from k9, so refresh the read count Utils.refreshUnreadK9Count(this); Idle.updateIdle(this, true); } } currentActivity = className; } } @Override public void onInterrupt() { /* Do nothing */ } }
package org.objectweb.proactive.ic2d.gui.util; /** * * @author manu */ public class RMIHostDialog extends javax.swing.JDialog { private RMIHostDialog(){} //empty default constructor to avoid compiler to add one /** Creates new form RMIHostDialog */ private RMIHostDialog(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); setJTextFielddepth(defaultMaxDepth); setSize(450,220); } /** 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. */ private void initComponents() { getContentPane().setLayout(new java.awt.FlowLayout()); jPanel1 = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jPanel4 = new javax.swing.JPanel(); jPanel5 = new javax.swing.JPanel(); jTextFieldHostIp = new javax.swing.JTextField(); jLabelHostIp = new javax.swing.JLabel(); jTextFielddepth = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jButtonOK = new javax.swing.JButton(); jButtonCancel = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); jButtonOK.setMnemonic(java.awt.event.KeyEvent.VK_ENTER); getRootPane().setDefaultButton(jButtonOK); setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE); setTitle("Adding host and assoc to monitor"); setModal(true); setResizable(false); jLabelHostIp.setText("Please enter the name or the IP of the host to monitor :"); jPanel1.add(jLabelHostIp); getContentPane().add(jPanel1); jTextFieldHostIp.setText("sdfsdfdsfsdfsd"); jTextFieldHostIp.setSize(400,18); jPanel2.add( jTextFieldHostIp); getContentPane().add(jPanel2); jLabel2.setText("Hosts will be recursively searched up to a depth of :"); jPanel3.add(jLabel2); jTextFielddepth.setText(defaultMaxDepth); jPanel3.add(jTextFielddepth); getContentPane().add(jPanel3); jLabel3.setText("You can change it there or from \"Menu Control, Set Depth Control\" "); jPanel4.add(jLabel3); getContentPane().add(jPanel4); jButtonOK.setText("OK"); jButtonOK.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jPanel5.add(jButtonOK); jButtonCancel.setText("Cancel"); jButtonCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jPanel5.add(jButtonCancel); getContentPane().add(jPanel5); pack(); } private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { setButtonOK(false); setVisible(false); } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { setButtonOK(true); setVisible(false); } /** * @param args the command line arguments */ public static void main(String args[]) { new RMIHostDialog(new javax.swing.JFrame(), true).show(); } // Variables declaration - do not modify private static javax.swing.JPanel jPanel1; private static javax.swing.JPanel jPanel2; private static javax.swing.JPanel jPanel3; private static javax.swing.JPanel jPanel4; private static javax.swing.JPanel jPanel5; private javax.swing.JButton jButtonOK; private javax.swing.JButton jButtonCancel; private static javax.swing.JLabel jLabelHostIp; private static javax.swing.JLabel jLabel2; private static javax.swing.JLabel jLabel3; private static javax.swing.JTextField jTextFieldHostIp; private static javax.swing.JTextField jTextFielddepth; private boolean buttonOK=false; private static RMIHostDialog _singleton=null; static private String defaultMaxDepth="10"; // End of variables declaration public String getJTextFielddepth() { return jTextFielddepth.getText(); } public void setJTextFielddepth(String textFielddepth) { jTextFielddepth.setText(textFielddepth); } public String getJTextFieldHostIp() { return jTextFieldHostIp.getText(); } public void setJTextFieldHostIp(String textFieldHostIp) { jTextFieldHostIp.setText(textFieldHostIp); } public boolean isButtonOK() { return buttonOK; } public void setButtonOK(boolean buttonOK) { this.buttonOK = buttonOK; } // satic method for singleton pattern static public RMIHostDialog showRMIHostDialog(javax.swing.JFrame parentComponent, String initialhostvalue){ if (null==_singleton){ _singleton = new RMIHostDialog(parentComponent, true); } jTextFieldHostIp.setText(initialhostvalue); _singleton.setLocationRelativeTo(parentComponent); _singleton.show(); return _singleton; } public static void openSetDepthControlDialog(javax.swing.JFrame parentComponent){ if (null==_singleton){ _singleton = new RMIHostDialog(parentComponent, true); } Object result = javax.swing.JOptionPane.showInputDialog(parentComponent, // Component parentComponent, "Please enter the max depth control:", // Object message, "Set Depth Control", // String title, javax.swing.JOptionPane.PLAIN_MESSAGE, // int messageType, null, // Icon icon, null, // Object[] selectionValues, jTextFielddepth.getText() // Object initialSelectionValue) ); if ((result == null) || (!(result instanceof String))) { return; } jTextFielddepth.setText((String)result); } }
package com.thoughtworks.xstream.core; import com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider; import com.thoughtworks.xstream.converters.reflection.ReflectionProvider; import java.security.AccessControlException; public class JVM { private ReflectionProvider reflectionProvider; private static final float majorJavaVersion = getMajorJavaVersion(System.getProperty("java.version")); static final float DEFAULT_JAVA_VERSION = 1.3f; /** * Parses the java version system property to determine the major java version, * ie 1.x * * @param javaVersion the system property 'java.version' * @return A float of the form 1.x */ static final float getMajorJavaVersion(String javaVersion) { try { return Float.parseFloat(javaVersion.substring(0, 3)); } catch ( NumberFormatException e ){ // Some JVMs may not conform to the x.y.z java.version format return DEFAULT_JAVA_VERSION; } } public static boolean is14() { return majorJavaVersion >= 1.4f; } public static boolean is15() { return majorJavaVersion >= 1.5f; } private static boolean isSun() { return System.getProperty("java.vm.vendor").indexOf("Sun") != -1; } private static boolean isApple() { return System.getProperty("java.vm.vendor").indexOf("Apple") != -1; } private static boolean isHPUX() { return System.getProperty("java.vm.vendor").indexOf("Hewlett-Packard Company") != -1; } private static boolean isIBM() { return System.getProperty("java.vm.vendor").indexOf("IBM") != -1; } private static boolean isBlackdown() { return System.getProperty("java.vm.vendor").indexOf("Blackdown") != -1; } public Class loadClass(String name) { try { return Class.forName(name, false, getClass().getClassLoader()); } catch (ClassNotFoundException e) { return null; } } public synchronized ReflectionProvider bestReflectionProvider() { if (reflectionProvider == null) { try { if ( canUseSun14ReflectionProvider() ) { String cls = "com.thoughtworks.xstream.converters.reflection.Sun14ReflectionProvider"; reflectionProvider = (ReflectionProvider) loadClass(cls).newInstance(); } else { reflectionProvider = new PureJavaReflectionProvider(); } } catch (InstantiationException e) { reflectionProvider = new PureJavaReflectionProvider(); } catch (IllegalAccessException e) { reflectionProvider = new PureJavaReflectionProvider(); } catch (AccessControlException e) { // thrown when trying to access sun.misc package in Applet context. reflectionProvider = new PureJavaReflectionProvider(); } } return reflectionProvider; } private boolean canUseSun14ReflectionProvider() { return (isSun() || isApple() || isHPUX() || isIBM() || isBlackdown()) && is14() && loadClass("sun.misc.Unsafe") != null; } }
package com.thoughtworks.xstream.core; import com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider; import com.thoughtworks.xstream.converters.reflection.ReflectionProvider; import java.lang.reflect.Field; import java.security.AccessControlException; import java.text.AttributedString; import java.util.HashMap; import java.util.Map; public class JVM { private ReflectionProvider reflectionProvider; private Map loaderCache = new HashMap(); private final boolean supportsAWT = loadClass("java.awt.Color") != null; private final boolean supportsSQL = loadClass("java.sql.Date") != null; private static final boolean reverseFieldOrder; private static final String vendor = System.getProperty("java.vm.vendor"); private static final float majorJavaVersion = getMajorJavaVersion(); static final float DEFAULT_JAVA_VERSION = 1.3f; static { boolean reverse = false; final Field[] fields = AttributedString.class.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { if (fields[i].getName().equals("text")) { reverse = i > 3; } } reverseFieldOrder = reverse; } /** * Parses the java version system property to determine the major java version, * ie 1.x * * @return A float of the form 1.x */ private static final float getMajorJavaVersion() { try { return Float.parseFloat(System.getProperty("java.specification.version")); } catch ( NumberFormatException e ){ // Some JVMs may not conform to the x.y.z java.version format return DEFAULT_JAVA_VERSION; } } public static boolean is14() { return majorJavaVersion >= 1.4f; } public static boolean is15() { return majorJavaVersion >= 1.5f; } public static boolean is16() { return majorJavaVersion >= 1.6f; } private static boolean isSun() { return vendor.indexOf("Sun") != -1; } private static boolean isApple() { return vendor.indexOf("Apple") != -1; } private static boolean isHPUX() { return vendor.indexOf("Hewlett-Packard Company") != -1; } private static boolean isIBM() { return vendor.indexOf("IBM") != -1; } private static boolean isBlackdown() { return vendor.indexOf("Blackdown") != -1; } /* * Support for sun.misc.Unsafe and sun.reflect.ReflectionFactory is present * in JRockit versions R25.1.0 and later, both 1.4.2 and 5.0 (and in future * 6.0 builds). */ private static boolean isBEAWithUnsafeSupport() { // This property should be "BEA Systems, Inc." if (vendor.indexOf("BEA") != -1) { /* * Recent 1.4.2 and 5.0 versions of JRockit have a java.vm.version * string starting with the "R" JVM version number, i.e. * "R26.2.0-38-57237-1.5.0_06-20060209..." */ String vmVersion = System.getProperty("java.vm.version"); if (vmVersion.startsWith("R")) { /* * We *could* also check that it's R26 or later, but that is * implicitly true */ return true; } /* * For older JRockit versions we can check java.vm.info. JRockit * 1.4.2 R24 -> "Native Threads, GC strategy: parallel" and JRockit * 5.0 R25 -> "R25.2.0-28". */ String vmInfo = System.getProperty("java.vm.info"); if (vmInfo != null) { // R25.1 or R25.2 supports Unsafe, other versions do not return (vmInfo.startsWith("R25.1") || vmInfo .startsWith("R25.2")); } } // If non-BEA, or possibly some very old JRockit version return false; } private static boolean isHitachi() { return vendor.indexOf("Hitachi") != -1; } private static boolean isSAP() { return vendor.indexOf("SAP AG") != -1; } public Class loadClass(String name) { try { Class clazz = (Class)loaderCache.get(name); if (clazz == null) { clazz = Class.forName(name, false, getClass().getClassLoader()); loaderCache.put(name, clazz); } return clazz; } catch (ClassNotFoundException e) { return null; } } public synchronized ReflectionProvider bestReflectionProvider() { if (reflectionProvider == null) { try { if ( canUseSun14ReflectionProvider() ) { String cls = "com.thoughtworks.xstream.converters.reflection.Sun14ReflectionProvider"; reflectionProvider = (ReflectionProvider) loadClass(cls).newInstance(); } else { reflectionProvider = new PureJavaReflectionProvider(); } } catch (InstantiationException e) { reflectionProvider = new PureJavaReflectionProvider(); } catch (IllegalAccessException e) { reflectionProvider = new PureJavaReflectionProvider(); } catch (AccessControlException e) { // thrown when trying to access sun.misc package in Applet context. reflectionProvider = new PureJavaReflectionProvider(); } } return reflectionProvider; } private boolean canUseSun14ReflectionProvider() { return (isSun() || isApple() || isHPUX() || isIBM() || isBlackdown() || isBEAWithUnsafeSupport() || isHitachi() || isSAP()) && is14() && loadClass("sun.misc.Unsafe") != null; } public static boolean reverseFieldDefinition() { return reverseFieldOrder; } /** * Checks if the jvm supports awt. */ public boolean supportsAWT() { return this.supportsAWT; } /** * Checks if the jvm supports sql. */ public boolean supportsSQL() { return this.supportsSQL; } public static void main(String[] args) { JVM jvm = new JVM(); System.out.println("XStream JVM diagnostics"); System.out.println("java.specification.version: " + System.getProperty("java.specification.version")); System.out.println("java.vm.vendor: " + vendor); System.out.println("Version: " + majorJavaVersion); System.out.println("Reverse field order: " + reverseFieldOrder); System.out.println("XStream support for enhanced Mode: " + jvm.canUseSun14ReflectionProvider()); System.out.println("Supports AWT: " + jvm.supportsAWT()); System.out.println("Supports SQL: " + jvm.supportsSQL()); } }
package org.teachingkidsprogramming.section02methods; import org.teachingextensions.logo.Tortoise; import org.teachingextensions.logo.utils.ColorUtils.PenColors.Grays; public class Houses { public static void main(String[] args) { Tortoise.show(); Tortoise.setSpeed(10); Tortoise.setX(200); int height = 40; drawHouse(height); drawHouse(120); drawHouse(90); drawHouse(20); } private static void drawHouse(int height) { // Change the pen color of the line the tortoise draws to lightGray -- Tortoise.setPenColor(Grays.LightGray); Tortoise.move(height); Tortoise.turn(90); Tortoise.move(30); Tortoise.turn(90); Tortoise.move(height); Tortoise.turn(-90); Tortoise.move(20); Tortoise.turn(-90); } }
package org.usfirst.frc.team2503.joystick; import org.usfirst.frc.team2503.joystick.interfaces.LeftRightForwardBackRotateSingleThrottleAxisStickTriggerButtonJoystick; public class MadCatzV1Joystick extends WarriorJoystick implements LeftRightForwardBackRotateSingleThrottleAxisStickTriggerButtonJoystick { public boolean getStickTriggerButton() { return getRawButton(1); } public boolean get2Button() { return getRawButton(2); } public boolean get3Button() { return getRawButton(3); } public boolean get4Button() { return getRawButton(4); } public boolean get5Button() { return getRawButton(5); } public boolean get6Button() { return getRawButton(6); } public boolean getGripButton() { return getRawButton(7); } public int getPov() { return getPOV(0); } public double getLeftRightAxisValue() { return getRawAxis(0); } public double getRightLeftAxisValue() { return -getRawAxis(0); } public double getForwardBackAxisValue() { return getRawAxis(1); } public double getBackForwardAxisValue() { return -getRawAxis(1); } public double getRotateLeftRightAxisValue() { return getRawAxis(3); } public double getRotateRightLeftAxisValue() { return -getRawAxis(3); } public double getThrottleUpDownAxisValue() { return getRawAxis(2); } public double getThrottleDownUpAxisValue() { return 1.0 - getRawAxis(2); } public MadCatzV1Joystick(WarriorJoystickSide side) { super(side); } public MadCatzV1Joystick(final int port) { super(port); } }
// 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.robot15.subsystems; import org.usfirst.frc1073.robot15.Robot; import org.usfirst.frc1073.robot15.RobotMap; import org.usfirst.frc1073.robot15.commands.*; import edu.wpi.first.wpilibj.*; import edu.wpi.first.wpilibj.DoubleSolenoid.Value; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; public class BinCollector extends Subsystem { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS CANTalon binCollectorTalon = RobotMap.binCollectorbinCollectorTalon; Solenoid binCollectorSolenoid = RobotMap.binCollectorbinCollectorSolenoid; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS private final double SPEED = 0.8; //May need to be changed // Put methods for controlling this subsystem // here. Call these from Commands. public void initDefaultCommand() { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND // Set the default command for a subsystem here. //setDefaultCommand(new MySpecialCommand()); } // Method to lift the bin public void binLift() { binCollectorTalon.set(SPEED); } // Method to lower the bin public void binLower() { binCollectorTalon.set(-SPEED); } // Method to stop the bin motor public void binStop() { binCollectorTalon.set(0.0); } // Returns the state public boolean getState() { return binCollectorSolenoid.get(); } // Returns true if it is collecting public boolean isCollecting() { if(binCollectorTalon.getSetpoint() > 0) { return true; } return false; } // Returns true if it is lowering public boolean islowering() { if(binCollectorTalon.getSetpoint() < 0) { return true; } return false; } // Method to open the bin collector claw public void open() { binCollectorSolenoid.set(true); } // Method to close the bin collector claw public void close() { binCollectorSolenoid.set(false); } }
package org.xtreemfs.flink; import java.io.BufferedOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import org.apache.flink.api.common.functions.MapFunction; import org.apache.flink.api.common.typeinfo.BasicTypeInfo; import org.apache.flink.api.java.DataSet; import org.apache.flink.api.java.ExecutionEnvironment; import org.apache.flink.api.java.aggregation.Aggregations; import org.apache.flink.api.java.io.TypeSerializerInputFormat; import org.apache.flink.api.java.tuple.Tuple3; public class DataLocalityTest { public static void main(String[] args) throws Exception { final ExecutionEnvironment env = ExecutionEnvironment .getExecutionEnvironment(); if (args.length != 1) { System.err .println("Invoke with one positional parameter: the number of OSDs."); System.exit(1); } int osdCount = 0; try { osdCount = Integer.parseInt(args[0]); } catch (NumberFormatException e) { System.err.println("Bad number of OSD argument: " + args[0]); System.exit(1); } final String workingDirectory = System.getenv("WORK"); if (workingDirectory == null) { System.err .println("$WORK must point to an XtreemFS volume mount point (as a file system path)."); System.exit(1); } final String defaultVolume = System.getenv("DEFAULT_VOLUME"); if (defaultVolume == null) { System.err .println("$DEFAULT_VOLUME must point to an XtreemFS volume URL ('xtreemfs://hostname:port/volume')."); System.exit(1); } // Generate enough data to distribute among the OSDs. DataOutputStream out = new DataOutputStream(new BufferedOutputStream( new FileOutputStream(workingDirectory + "/data.bin"))); // Each entry is 8 bytes and we want 128 kilobytes per OSD. for (int i = 0; i < osdCount * 128 * 1024 / 8; ++i) { // Always write the same value to each OSD. out.writeLong((i / (128 * 1024 / 8)) % osdCount); } out.close(); // Use words as input to Flink wordcount Job. DataSet<Long> input = env.readFile(new TypeSerializerInputFormat<Long>( BasicTypeInfo.LONG_TYPE_INFO), workingDirectory + "/data.bin"); DataSet<Long> filtered = input; // .filter(new FilterFunction<Long>() { // private static final long serialVersionUID = -7778608339455035028L; // @Override // public boolean filter(Long arg0) throws Exception { // return arg0 % 2 == 0; DataSet<Tuple3<Long, Integer, String>> counts = filtered .map(new MapFunction<Long, Tuple3<Long, Integer, String>>() { private static final long serialVersionUID = 7917635531979595929L; @Override public Tuple3<Long, Integer, String> map(Long arg0) throws Exception { return new Tuple3<Long, Integer, String>(arg0, 1, System.getenv("HOSTNAME")); } }).groupBy(2).aggregate(Aggregations.SUM, 1) .aggregate(Aggregations.MAX, 0); counts.print(); File file = new File(workingDirectory + "/data.bin"); System.out.println(file.length() + " bytes"); file.delete(); } }
package com.thoughtworks.biblioteca; import org.junit.Test; import java.util.ArrayList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; public class MovieLibraryTest { @Test public void shouldHaveAListOfAvailableMovies() { ArrayList<Movies> movies1 = new ArrayList<Movies>(); movies1.add(new Movies("Titanic", 1990, "James Cameron", 5)); MovieLibrary movieLibrary = new MovieLibrary(movies1); assertEquals(movies1,movieLibrary.getMovieLibrary()); } @Test public void shouldReturnEqualIfTheMovieListsAreEqual() { ArrayList<Movies> movies = new ArrayList<Movies>(); movies.add(new Movies("Titanic", 1990, "James Cameron", 5)); movies.add(new Movies("Inception", 2010, "Christopher Nolan", 9)); MovieLibrary movieLibrary1 = new MovieLibrary(movies); MovieLibrary movieLibrary2 = new MovieLibrary(movies); assertEquals(movieLibrary1,movieLibrary2); } @Test public void shouldReturnNotEqualIfTheMovieListsAreNotEqual() { ArrayList<Movies> movies = new ArrayList<Movies>(); movies.add(new Movies("Titanic", 1990, "James Cameron", 5)); movies.add(new Movies("Inception", 2010, "Christopher Nolan", 9)); MovieLibrary movieLibrary1 = new MovieLibrary(movies); ArrayList<Movies> movies1 = new ArrayList<Movies>(); movies1.add(new Movies("Titanic2", 1990, "James Cameron", 5)); movies1.add(new Movies("Inception", 2010, "Christopher Nolan", 9)); MovieLibrary movieLibrary2 = new MovieLibrary(movies1); assertNotEquals(movieLibrary1, movieLibrary2); } @Test public void shouldReturnEqualHashCodeIfTwoMoviesListsAreSame() { ArrayList<Movies> movies = new ArrayList<Movies>(); movies.add(new Movies("Titanic", 1990, "James Cameron", 5)); movies.add(new Movies("Inception", 2010, "Christopher Nolan", 9)); MovieLibrary movieLibrary1 = new MovieLibrary(movies); ArrayList<Movies> movies1 = new ArrayList<Movies>(); movies1.add(new Movies("Titanic", 1990, "James Cameron", 5)); movies1.add(new Movies("Inception", 2010, "Christopher Nolan", 9)); MovieLibrary movieLibrary2 = new MovieLibrary(movies1); assertEquals(movieLibrary1.hashCode(), movieLibrary2.hashCode()); } @Test public void shouldReturnEqualHashCodeIfTwoMoviesListsAreDifferent() { ArrayList<Movies> movies = new ArrayList<Movies>(); movies.add(new Movies("Titanic", 1990, "James Cameron", 5)); movies.add(new Movies("Inception", 2010, "Christopher Nolan", 9)); MovieLibrary movieLibrary1 = new MovieLibrary(movies); ArrayList<Movies> movies1 = new ArrayList<Movies>(); movies1.add(new Movies("Titanicjk", 1990, "James Cameron", 5)); movies1.add(new Movies("Inceptioon1", 2010, "Christopher Nolan", 9)); MovieLibrary movieLibrary2 = new MovieLibrary(movies1); assertNotEquals(movieLibrary1.hashCode(), movieLibrary2.hashCode()); } }
package com.commonsware.cwac.anddown.demo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.text.Html; import android.util.TimingLogger; import android.widget.TextView; import com.commonsware.cwac.anddown.AndDown; public class AndDownDemoActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView tv=(TextView)findViewById(R.id.text); TimingLogger timings = new TimingLogger("AndDown", "onCreate"); String raw=readRawTextFile(this, R.raw.readme); timings.addSplit("read raw"); timings.addSplit("instantiated AndDown"); String cooked=AndDown.markdownToHtml(raw); timings.addSplit("convert to HTML"); CharSequence cs=Html.fromHtml(cooked); timings.addSplit("convert to Spanned"); timings.dumpToLog(); tv.setText(cs); } public static String readRawTextFile(Context ctx, int resId) { InputStream inputStream=ctx.getResources().openRawResource(resId); InputStreamReader inputreader=new InputStreamReader(inputStream); BufferedReader buffreader=new BufferedReader(inputreader); String line; StringBuilder text=new StringBuilder(); try { while ((line=buffreader.readLine())!=null) { text.append(line); text.append('\n'); } } catch (IOException e) { return null; } return text.toString(); } }
package com.appengine.frame.help; import com.alibaba.fastjson.JSONObject; import com.appengine.deploy.Application; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Application.class) @SpringBootConfiguration public class HelpResourceTest { @Value("${local.server.port}") private int port; @Autowired private TestRestTemplate restTemplate; @Test public void testPing() { JSONObject json = restTemplate.getForObject("/help/ping", JSONObject.class); assertThat(json).isNotNull(); System.out.println(json.toJSONString()); assertThat(json.getInteger("apistatus")).isEqualTo(1); assertThat(json.getJSONObject("result").getInteger("uid")).isEqualTo(0); } @Test public void testEcho() { String msg = "hello"; MultiValueMap<String, String> map = new LinkedMultiValueMap<>(); map.add("msg", msg); HttpHeaders headers = new HttpHeaders(); headers.add("X-Engine-UID", 1000 + ""); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers); JSONObject json = restTemplate.postForObject("/help/echo", request, JSONObject.class); assertThat(json).isNotNull(); System.out.println(json.toJSONString()); assertThat(json.getInteger("apistatus")).isEqualTo(1); assertThat(json.getJSONObject("result").getString("msg")).isEqualTo(msg); } }
package be.ibridge.kettle.core.values; import java.math.BigDecimal; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Date; import junit.framework.TestCase; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.exception.KettleValueException; import be.ibridge.kettle.core.value.Value; /** * Test class for the basic functionality of Value. * * @author Sven Boden */ public class ValueTest extends TestCase { /** * Constructor test 1. */ public void testConstructor1() { Value vs = new Value(); // Set by clearValue() assertFalse(vs.isNull()); // historical probably assertTrue(vs.isEmpty()); // historical probably assertEquals(null, vs.getName()); assertEquals(null, vs.getOrigin()); assertEquals(Value.VALUE_TYPE_NONE, vs.getType()); assertFalse(vs.isString()); assertFalse(vs.isDate()); assertFalse(vs.isNumeric()); assertFalse(vs.isInteger()); assertFalse(vs.isBigNumber()); assertFalse(vs.isNumber()); assertFalse(vs.isBoolean()); Value vs1 = new Value("Name"); // Set by clearValue() assertFalse(vs1.isNull()); // historical probably assertTrue(vs1.isEmpty()); // historical probably assertEquals("Name", vs1.getName()); assertEquals(null, vs1.getOrigin()); assertEquals(Value.VALUE_TYPE_NONE, vs1.getType()); } /** * Constructor test 2. */ public void testConstructor2() { Value vs = new Value("Name", Value.VALUE_TYPE_NUMBER); assertFalse(vs.isNull()); assertFalse(vs.isEmpty()); assertEquals("Name", vs.getName()); assertEquals(Value.VALUE_TYPE_NUMBER, vs.getType()); assertTrue(vs.isNumber()); assertTrue(vs.isNumeric()); Value vs1= new Value("Name", Value.VALUE_TYPE_STRING); assertFalse(vs1.isNull()); assertFalse(vs1.isEmpty()); assertEquals("Name", vs1.getName()); assertEquals(Value.VALUE_TYPE_STRING, vs1.getType()); assertTrue(vs1.isString()); Value vs2= new Value("Name", Value.VALUE_TYPE_DATE); assertFalse(vs2.isNull()); assertFalse(vs2.isEmpty()); assertEquals("Name", vs2.getName()); assertEquals(Value.VALUE_TYPE_DATE, vs2.getType()); assertTrue(vs2.isDate()); Value vs3= new Value("Name", Value.VALUE_TYPE_BOOLEAN); assertFalse(vs3.isNull()); assertFalse(vs3.isEmpty()); assertEquals("Name", vs3.getName()); assertEquals(Value.VALUE_TYPE_BOOLEAN, vs3.getType()); assertTrue(vs3.isBoolean()); Value vs4= new Value("Name", Value.VALUE_TYPE_INTEGER); assertFalse(vs4.isNull()); assertFalse(vs4.isEmpty()); assertEquals("Name", vs4.getName()); assertEquals(Value.VALUE_TYPE_INTEGER, vs4.getType()); assertTrue(vs4.isInteger()); assertTrue(vs4.isNumeric()); Value vs5= new Value("Name", Value.VALUE_TYPE_BIGNUMBER); assertFalse(vs5.isNull()); assertFalse(vs5.isEmpty()); assertEquals("Name", vs5.getName()); assertEquals(Value.VALUE_TYPE_BIGNUMBER, vs5.getType()); assertTrue(vs5.isBigNumber()); assertTrue(vs5.isNumeric()); Value vs6= new Value("Name", 1000000); assertEquals(Value.VALUE_TYPE_NONE, vs6.getType()); } /** * Constructors using Values */ public void testConstructor3() { Value vs = new Value("Name", Value.VALUE_TYPE_NUMBER); vs.setValue(10.0D); vs.setOrigin("origin"); vs.setLength(4, 2); Value copy = new Value(vs); assertEquals(vs.getType(), copy.getType()); assertEquals(vs.getNumber(), copy.getNumber(), 0.1D); assertEquals(vs.getLength(), copy.getLength()); assertEquals(vs.getPrecision(), copy.getPrecision()); assertEquals(vs.isNull(), copy.isNull()); assertEquals(vs.getOrigin(), copy.getOrigin()); assertEquals(vs.getName(), copy.getName()); // Show it's a deep copy copy.setName("newName"); assertEquals("Name", vs.getName()); assertEquals("newName", copy.getName()); copy.setOrigin("newOrigin"); assertEquals("origin", vs.getOrigin()); assertEquals("newOrigin", copy.getOrigin()); copy.setValue(11.0D); assertEquals(10.0D, vs.getNumber(), 0.1D); assertEquals(11.0D, copy.getNumber(), 0.1D); Value vs1 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs1.setName(null); // name and origin are null Value copy1 = new Value(vs1); assertEquals(vs1.getType(), copy1.getType()); assertEquals(vs1.getNumber(), copy1.getNumber(), 0.1D); assertEquals(vs1.getLength(), copy1.getLength()); assertEquals(vs1.getPrecision(), copy1.getPrecision()); assertEquals(vs1.isNull(), copy1.isNull()); assertEquals(vs1.getOrigin(), copy1.getOrigin()); assertEquals(vs1.getName(), copy1.getName()); Value vs2 = new Value((Value)null); assertTrue(vs2.isNull()); assertNull(vs2.getName()); assertNull(vs2.getOrigin()); } /** * Constructors using Values */ public void testConstructor4() { Value vs = new Value("Name", new StringBuffer("buffer")); assertEquals(Value.VALUE_TYPE_STRING, vs.getType()); assertEquals("buffer", vs.getString()); } /** * Constructors using Values */ public void testConstructor5() { Value vs = new Value("Name", 10.0D); assertEquals(Value.VALUE_TYPE_NUMBER, vs.getType()); assertEquals("Name", vs.getName()); Value copy = new Value("newName", vs); assertEquals("newName", copy.getName()); assertFalse(!vs.equals(copy)); copy.setName("Name"); assertTrue(vs.equals(copy)); } /** * Test of string representation of String Value. */ public void testToStringString() { String result = null; Value vs = new Value("Name", Value.VALUE_TYPE_STRING); vs.setValue("test string"); result = vs.toString(true); assertEquals("test string", result); vs.setLength(20); result = vs.toString(true); // padding assertEquals("test string ", result); vs.setLength(4); result = vs.toString(true); // truncate assertEquals("test", result); vs.setLength(0); result = vs.toString(true); // on 0 => full string assertEquals("test string", result); // no padding result = vs.toString(false); assertEquals("test string", result); vs.setLength(20); result = vs.toString(false); assertEquals("test string", result); vs.setLength(4); result = vs.toString(false); assertEquals("test string", result); vs.setLength(0); result = vs.toString(false); assertEquals("test string", result); vs.setLength(4); vs.setNull(); result = vs.toString(false); assertEquals("", result); Value vs1 = new Value("Name", Value.VALUE_TYPE_STRING); assertEquals("", vs1.toString()); // Just to get 100% coverage Value vs2 = new Value("Name", Value.VALUE_TYPE_NONE); assertEquals("", vs2.toString()); } /** * Test of string representation of Number Value. */ public void testToStringNumber() { Value vs1 = new Value("Name", Value.VALUE_TYPE_NUMBER); assertEquals(" 0"+Const.DEFAULT_DECIMAL_SEPARATOR+"0", vs1.toString(true)); Value vs2 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs2.setNull(); assertEquals("", vs2.toString(true)); Value vs3 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs3.setValue(100.0D); vs3.setLength(6); vs3.setNull(); assertEquals(" ", vs3.toString(true)); Value vs4 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs4.setValue(100.0D); vs4.setLength(6); assertEquals(" 000100"+Const.DEFAULT_DECIMAL_SEPARATOR+"00", vs4.toString(true)); Value vs5 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs5.setValue(100.5D); vs5.setLength(-1); vs5.setPrecision(-1); assertEquals(" 100"+Const.DEFAULT_DECIMAL_SEPARATOR+"5", vs5.toString(true)); Value vs6 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs6.setValue(100.5D); vs6.setLength(8); vs6.setPrecision(-1); assertEquals(" 00000100"+Const.DEFAULT_DECIMAL_SEPARATOR+"50", vs6.toString(true)); Value vs7 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs7.setValue(100.5D); vs7.setLength(0); vs7.setPrecision(3); assertEquals(" 100"+Const.DEFAULT_DECIMAL_SEPARATOR+"5", vs7.toString(true)); Value vs8 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs8.setValue(100.5D); vs8.setLength(5); vs8.setPrecision(3); assertEquals("100.5", vs8.toString(false)); Value vs9 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs9.setValue(100.0D); vs9.setLength(6); assertEquals("100.0", vs9.toString(false)); Value vs10 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs10.setValue(100.5D); vs10.setLength(-1); vs10.setPrecision(-1); assertEquals("100.5", vs10.toString(false)); Value vs11 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs11.setValue(100.5D); vs11.setLength(8); vs11.setPrecision(-1); assertEquals("100.5", vs11.toString(false)); Value vs12 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs12.setValue(100.5D); vs12.setLength(0); vs12.setPrecision(3); assertEquals("100.5", vs12.toString(false)); Value vs13 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs13.setValue(100.5D); vs13.setLength(5); vs13.setPrecision(3); assertEquals("100.5", vs13.toString(false)); Value vs14 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs14.setValue(100.5D); vs14.setLength(5); vs14.setPrecision(3); assertEquals(" 100"+Const.DEFAULT_DECIMAL_SEPARATOR+"500", vs14.toString(true)); } /** * Test of string representation of Integer Value. */ public void testToIntegerNumber() { Value vs1 = new Value("Name", Value.VALUE_TYPE_INTEGER); assertEquals(" 0", vs1.toString(true)); Value vs2 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs2.setNull(); assertEquals("", vs2.toString(true)); Value vs3 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs3.setValue(100); vs3.setLength(6); vs3.setNull(); assertEquals(" ", vs3.toString(true)); Value vs4 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs4.setValue(100); vs4.setLength(6); assertEquals(" 000100", vs4.toString(true)); Value vs5 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs5.setValue(100); vs5.setLength(-1); vs5.setPrecision(-1); assertEquals(" 100", vs5.toString(true)); Value vs6 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs6.setValue(105); vs6.setLength(8); vs6.setPrecision(-1); assertEquals(" 00000105", vs6.toString(true)); Value vs7 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs7.setValue(100); vs7.setLength(0); vs7.setPrecision(3); assertEquals(" 100", vs7.toString(true)); Value vs8 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs8.setValue(100); vs8.setLength(5); vs8.setPrecision(3); assertEquals(" 00100", vs8.toString(false)); Value vs9 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs9.setValue(100); vs9.setLength(6); assertEquals(" 000100", vs9.toString(false)); Value vs10 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs10.setValue(100); vs10.setLength(-1); vs10.setPrecision(-1); assertEquals(" 100", vs10.toString(false)); Value vs11 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs11.setValue(100); vs11.setLength(8); vs11.setPrecision(-1); assertEquals(" 00000100", vs11.toString(false)); Value vs12 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs12.setValue(100); vs12.setLength(0); vs12.setPrecision(3); assertEquals(" 100", vs12.toString(false)); Value vs13 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs13.setValue(100); vs13.setLength(5); vs13.setPrecision(3); assertEquals(" 00100", vs13.toString(false)); Value vs14 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs14.setValue(100); vs14.setLength(5); vs14.setPrecision(3); assertEquals(" 00100", vs14.toString(true)); } /** * Test of boolean representation of Value. */ public void testToStringBoolean() { String result = null; Value vs = new Value("Name", Value.VALUE_TYPE_BOOLEAN); vs.setValue(true); result = vs.toString(true); assertEquals("true", result); Value vs1 = new Value("Name", Value.VALUE_TYPE_BOOLEAN); vs1.setValue(false); result = vs1.toString(true); assertEquals("false", result); // set to "null" Value vs2 = new Value("Name", Value.VALUE_TYPE_BOOLEAN); vs2.setValue(true); vs2.setNull(); result = vs2.toString(true); assertEquals("", result); // set to "null" Value vs3 = new Value("Name", Value.VALUE_TYPE_BOOLEAN); vs3.setValue(false); vs3.setNull(); result = vs3.toString(true); assertEquals("", result); // set to length = 1 => get Y/N Value vs4 = new Value("Name", Value.VALUE_TYPE_BOOLEAN); vs4.setValue(true); vs4.setLength(1); result = vs4.toString(true); assertEquals("true", result); // set to length = 1 => get Y/N Value vs5 = new Value("Name", Value.VALUE_TYPE_BOOLEAN); vs5.setValue(false); vs5.setLength(1); result = vs5.toString(true); assertEquals("false", result); // set to length > 1 => get true/false Value vs6 = new Value("Name", Value.VALUE_TYPE_BOOLEAN); vs6.setValue(true); vs6.setLength(3); result = vs6.toString(true); assertEquals("true", result); // set to length > 1 => get true/false (+ truncation) Value vs7 = new Value("Name", Value.VALUE_TYPE_BOOLEAN); vs7.setValue(false); vs7.setLength(3); result = vs7.toString(true); assertEquals("false", result); } /** * Test of boolean representation of Value. */ public void testToStringDate() { String result = null; Value vs1 = new Value("Name", Value.VALUE_TYPE_DATE); result = vs1.toString(true); assertEquals("", result); Value vs2 = new Value("Name", Value.VALUE_TYPE_DATE); vs2.setNull(true); result = vs2.toString(true); assertEquals("", result); SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); Date dt = df.parse("2006/03/01 17:01:02.005", new ParsePosition(0)); Value vs3 = new Value("Name", Value.VALUE_TYPE_DATE); vs3.setValue(dt); result = vs3.toString(true); assertEquals("2006/03/01 17:01:02.005", result); Value vs4 = new Value("Name", Value.VALUE_TYPE_DATE); vs4.setNull(true); vs4.setLength(2); result = vs4.toString(true); assertEquals("", result); Value vs5 = new Value("Name", Value.VALUE_TYPE_DATE); vs3.setValue(dt); vs5.setLength(10); result = vs5.toString(true); assertEquals("", result); } public void testToStringMeta() { String result = null; // Strings Value vs = new Value("Name", Value.VALUE_TYPE_STRING); vs.setValue("test"); result = vs.toStringMeta(); assertEquals("String", result); Value vs1= new Value("Name", Value.VALUE_TYPE_STRING); vs1.setValue("test"); vs1.setLength(0); result = vs1.toStringMeta(); assertEquals("String", result); Value vs2= new Value("Name", Value.VALUE_TYPE_STRING); vs2.setValue("test"); vs2.setLength(4); result = vs2.toStringMeta(); assertEquals("String(4)", result); // Booleans: not affected by length on output Value vs3 = new Value("Name", Value.VALUE_TYPE_BOOLEAN); vs3.setValue(false); result = vs3.toStringMeta(); assertEquals("Boolean", result); Value vs4= new Value("Name", Value.VALUE_TYPE_BOOLEAN); vs4.setValue(false); vs4.setLength(0); result = vs4.toStringMeta(); assertEquals("Boolean", result); Value vs5= new Value("Name", Value.VALUE_TYPE_BOOLEAN); vs5.setValue(false); vs5.setLength(4); result = vs5.toStringMeta(); assertEquals("Boolean", result); // Integers Value vs6 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs6.setValue(10); result = vs6.toStringMeta(); assertEquals("Integer", result); Value vs7= new Value("Name", Value.VALUE_TYPE_INTEGER); vs7.setValue(10); vs7.setLength(0); result = vs7.toStringMeta(); assertEquals("Integer", result); Value vs8= new Value("Name", Value.VALUE_TYPE_INTEGER); vs8.setValue(10); vs8.setLength(4); result = vs8.toStringMeta(); assertEquals("Integer(4)", result); // Numbers Value vs9 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs9.setValue(10.0D); result = vs9.toStringMeta(); assertEquals("Number", result); Value vs10 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs10.setValue(10.0D); vs10.setLength(0); result = vs10.toStringMeta(); assertEquals("Number", result); Value vs11 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs11.setValue(10.0D); vs11.setLength(4); result = vs11.toStringMeta(); assertEquals("Number(4)", result); Value vs12 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs12.setValue(10.0D); vs12.setLength(4); vs12.setPrecision(2); result = vs12.toStringMeta(); assertEquals("Number(4, 2)", result); // BigNumber Value vs13 = new Value("Name", Value.VALUE_TYPE_BIGNUMBER); vs13.setValue(new BigDecimal(10)); result = vs13.toStringMeta(); assertEquals("BigNumber", result); Value vs14 = new Value("Name", Value.VALUE_TYPE_BIGNUMBER); vs14.setValue(new BigDecimal(10)); vs14.setLength(0); result = vs14.toStringMeta(); assertEquals("BigNumber", result); Value vs15 = new Value("Name", Value.VALUE_TYPE_BIGNUMBER); vs15.setValue(new BigDecimal(10)); vs15.setLength(4); result = vs15.toStringMeta(); assertEquals("BigNumber(4)", result); Value vs16 = new Value("Name", Value.VALUE_TYPE_BIGNUMBER); vs16.setValue(new BigDecimal(10)); vs16.setLength(4); vs16.setPrecision(2); result = vs16.toStringMeta(); assertEquals("BigNumber(4, 2)", result); // Date Value vs17 = new Value("Name", Value.VALUE_TYPE_DATE); vs17.setValue(new Date()); result = vs17.toStringMeta(); assertEquals("Date", result); Value vs18 = new Value("Name", Value.VALUE_TYPE_DATE); vs18.setValue(new Date()); vs18.setLength(0); result = vs18.toStringMeta(); assertEquals("Date", result); Value vs19 = new Value("Name", Value.VALUE_TYPE_DATE); vs19.setValue(new Date()); vs19.setLength(4); result = vs19.toStringMeta(); assertEquals("Date", result); Value vs20 = new Value("Name", Value.VALUE_TYPE_DATE); vs20.setValue(new Date()); vs20.setLength(4); vs20.setPrecision(2); result = vs20.toStringMeta(); assertEquals("Date", result); } /** * Constructors using Values. */ public void testClone1() { Value vs = new Value("Name", Value.VALUE_TYPE_NUMBER); vs.setValue(10.0D); vs.setOrigin("origin"); vs.setLength(4, 2); Value copy = (Value)vs.Clone(); assertEquals(vs.getType(), copy.getType()); assertEquals(vs.getNumber(), copy.getNumber(), 0.1D); assertEquals(vs.getLength(), copy.getLength()); assertEquals(vs.getPrecision(), copy.getPrecision()); assertEquals(vs.isNull(), copy.isNull()); assertEquals(vs.getOrigin(), copy.getOrigin()); assertEquals(vs.getName(), copy.getName()); // Show it's a deep copy copy.setName("newName"); assertEquals("Name", vs.getName()); assertEquals("newName", copy.getName()); copy.setOrigin("newOrigin"); assertEquals("origin", vs.getOrigin()); assertEquals("newOrigin", copy.getOrigin()); copy.setValue(11.0D); assertEquals(10.0D, vs.getNumber(), 0.1D); assertEquals(11.0D, copy.getNumber(), 0.1D); Value vs1 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs1.setName(null); // name and origin are null Value copy1 = new Value(vs1); assertEquals(vs1.getType(), copy1.getType()); assertEquals(vs1.getNumber(), copy1.getNumber(), 0.1D); assertEquals(vs1.getLength(), copy1.getLength()); assertEquals(vs1.getPrecision(), copy1.getPrecision()); assertEquals(vs1.isNull(), copy1.isNull()); assertEquals(vs1.getOrigin(), copy1.getOrigin()); assertEquals(vs1.getName(), copy1.getName()); Value vs2 = new Value((Value)null); assertTrue(vs2.isNull()); assertNull(vs2.getName()); assertNull(vs2.getOrigin()); } /** * Test of getStringLength(). * */ public void testGetStringLength() { int result = 0; Value vs1 = new Value("Name", Value.VALUE_TYPE_STRING); result = vs1.getStringLength(); assertEquals(0, result); Value vs2 = new Value("Name", Value.VALUE_TYPE_STRING); vs2.setNull(); result = vs2.getStringLength(); assertEquals(0, result); Value vs3 = new Value("Name", Value.VALUE_TYPE_STRING); vs3.setValue("stringlength"); result = vs3.getStringLength(); assertEquals(12, result); } public void testGetXML() { String result = null; Value vs1= new Value("Name", Value.VALUE_TYPE_STRING); vs1.setValue("test"); vs1.setLength(4); vs1.setPrecision(2); result = vs1.getXML(); assertEquals("<name>Name</name><type>String</type><text>test</text><length>4</length><precision>-1</precision><isnull>N</isnull>", result); Value vs2= new Value("Name", Value.VALUE_TYPE_BOOLEAN); vs2.setValue(false); vs2.setLength(4); vs2.setPrecision(2); result = vs2.getXML(); assertEquals("<name>Name</name><type>Boolean</type><text>false</text><length>-1</length><precision>-1</precision><isnull>N</isnull>", result); Value vs3= new Value("Name", Value.VALUE_TYPE_INTEGER); vs3.setValue(10); vs3.setLength(4); vs3.setPrecision(2); result = vs3.getXML(); assertEquals("<name>Name</name><type>Integer</type><text> 0010</text><length>4</length><precision>0</precision><isnull>N</isnull>", result); Value vs4 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs4.setValue(10.0D); vs4.setLength(4); vs4.setPrecision(2); result = vs4.getXML(); assertEquals("<name>Name</name><type>Number</type><text>10.0</text><length>4</length><precision>2</precision><isnull>N</isnull>", result); Value vs5 = new Value("Name", Value.VALUE_TYPE_BIGNUMBER); vs5.setValue(new BigDecimal(10)); vs5.setLength(4); vs5.setPrecision(2); result = vs5.getXML(); assertEquals("<name>Name</name><type>BigNumber</type><text>10</text><length>4</length><precision>2</precision><isnull>N</isnull>", result); SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); Date dt = df.parse("2006/03/01 17:01:02.005", new ParsePosition(0)); Value vs6 = new Value("Name", Value.VALUE_TYPE_DATE); vs6.setValue(dt); vs6.setLength(4); vs6.setPrecision(2); result = vs6.getXML(); assertEquals("<name>Name</name><type>Date</type><text>2006/03/01 17:01:02.005</text><length>-1</length><precision>-1</precision><isnull>N</isnull>", result); } /** * Test of setValue() */ public void testSetValue() { Value vs = new Value("Name", Value.VALUE_TYPE_INTEGER); vs.setValue(100L); vs.setOrigin("origin"); Value vs1 = new Value((Value)null); assertTrue(vs1.isNull()); assertTrue(vs1.isEmpty()); assertNull(vs1.getName()); assertNull(vs1.getOrigin()); assertEquals(Value.VALUE_TYPE_NONE, vs1.getType()); Value vs2 = new Value("newName", Value.VALUE_TYPE_INTEGER); vs2.setOrigin("origin1"); vs2.setValue(vs); assertEquals("origin", vs2.getOrigin()); assertEquals(vs.getInteger(), vs2.getInteger()); Value vs3 = new Value("newName", Value.VALUE_TYPE_INTEGER); vs3.setValue(new StringBuffer("Sven")); assertEquals(Value.VALUE_TYPE_STRING, vs3.getType()); assertEquals("Sven", vs3.getString()); Value vs4 = new Value("newName", Value.VALUE_TYPE_STRING); vs4.setValue(new StringBuffer("Test")); vs4.setValue(new StringBuffer("Sven")); assertEquals(Value.VALUE_TYPE_STRING, vs4.getType()); assertEquals("Sven", vs4.getString()); Value vs5 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs5.setValue((byte)4); assertEquals(4L, vs5.getInteger()); Value vs6 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs6.setValue((Value)null); assertFalse(vs6.isNull()); assertNull(vs6.getName()); assertNull(vs6.getOrigin()); assertEquals(Value.VALUE_TYPE_NONE, vs6.getType()); } /** * Test for isNumeric(). */ public void testIsNumeric() { assertEquals(false, Value.isNumeric(Value.VALUE_TYPE_NONE)); assertEquals(true, Value.isNumeric(Value.VALUE_TYPE_NUMBER)); assertEquals(false, Value.isNumeric(Value.VALUE_TYPE_STRING)); assertEquals(false, Value.isNumeric(Value.VALUE_TYPE_DATE)); assertEquals(false, Value.isNumeric(Value.VALUE_TYPE_BOOLEAN)); assertEquals(true, Value.isNumeric(Value.VALUE_TYPE_INTEGER)); assertEquals(true, Value.isNumeric(Value.VALUE_TYPE_BIGNUMBER)); assertEquals(false, Value.isNumeric(Value.VALUE_TYPE_SERIALIZABLE)); } public void testIsEqualTo() { Value vs1 = new Value("Name", Value.VALUE_TYPE_STRING); vs1.setValue("test"); assertTrue(vs1.isEqualTo("test")); assertFalse(vs1.isEqualTo("test1")); Value vs2 = new Value("Name", Value.VALUE_TYPE_STRING); vs2.setValue(new BigDecimal(1.0D)); assertTrue(vs2.isEqualTo(new BigDecimal(1.0D))); assertFalse(vs2.isEqualTo(new BigDecimal(2.0D))); Value vs3 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs3.setValue(10.0D); assertTrue(vs3.isEqualTo(10.0D)); assertFalse(vs3.isEqualTo(11.0D)); Value vs4 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs4.setValue(10L); assertTrue(vs4.isEqualTo(10L)); assertFalse(vs4.isEqualTo(11L)); Value vs5 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs5.setValue(10); assertTrue(vs5.isEqualTo(10)); assertFalse(vs5.isEqualTo(11)); Value vs6 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs6.setValue((byte)10); assertTrue(vs6.isEqualTo(10)); assertFalse(vs6.isEqualTo(11)); SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); Date dt = df.parse("2006/03/01 17:01:02.005", new ParsePosition(0)); Value vs7 = new Value("Name", Value.VALUE_TYPE_DATE); vs7.setValue(dt); assertTrue(vs7.isEqualTo(dt)); assertFalse(vs7.isEqualTo(new Date())); // assume it's not 2006/03/01 } /** * Test boolean operators. */ public void testBooleanOperators() { Value vs1 = new Value("Name", Value.VALUE_TYPE_BOOLEAN); Value vs2 = new Value("Name", Value.VALUE_TYPE_BOOLEAN); vs1.setValue(false); vs2.setValue(false); vs1.bool_and(vs2); assertEquals(false, vs1.getBoolean()); vs1.setValue(false); vs2.setValue(true); vs1.bool_and(vs2); assertEquals(false, vs1.getBoolean()); vs1.setValue(true); vs2.setValue(false); vs1.bool_and(vs2); assertEquals(false, vs1.getBoolean()); vs1.setValue(true); vs2.setValue(true); vs1.bool_and(vs2); assertEquals(true, vs1.getBoolean()); vs1.setValue(false); vs2.setValue(false); vs1.bool_or(vs2); assertEquals(false, vs1.getBoolean()); vs1.setValue(false); vs2.setValue(true); vs1.bool_or(vs2); assertEquals(true, vs1.getBoolean()); vs1.setValue(true); vs2.setValue(false); vs1.bool_or(vs2); assertEquals(true, vs1.getBoolean()); vs1.setValue(true); vs2.setValue(true); vs1.bool_or(vs2); assertEquals(true, vs1.getBoolean()); vs1.setValue(false); vs2.setValue(false); vs1.bool_xor(vs2); assertEquals(false, vs1.getBoolean()); vs1.setValue(false); vs2.setValue(true); vs1.bool_xor(vs2); assertEquals(true, vs1.getBoolean()); vs1.setValue(true); vs2.setValue(false); vs1.bool_xor(vs2); assertEquals(true, vs1.getBoolean()); vs1.setValue(true); vs2.setValue(true); vs1.bool_xor(vs2); assertEquals(false, vs1.getBoolean()); vs1.setValue(true); vs1.bool_not(); assertEquals(false, vs1.getBoolean()); vs1.setValue(false); vs1.bool_not(); assertEquals(true, vs1.getBoolean()); } /** * Test boolean operators. */ public void testBooleanOperators1() { Value vs1 = new Value("Name", Value.VALUE_TYPE_INTEGER); Value vs2 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs1.setValue(255L); vs2.setValue(255L); vs1.and(vs2); assertEquals(255L, vs1.getInteger()); vs1.setValue(255L); vs2.setValue(0L); vs1.and(vs2); assertEquals(0L, vs1.getInteger()); vs1.setValue(0L); vs2.setValue(255L); vs1.and(vs2); assertEquals(0L, vs1.getInteger()); vs1.setValue(0L); vs2.setValue(0L); vs1.and(vs2); assertEquals(0L, vs1.getInteger()); vs1.setValue(255L); vs2.setValue(255L); vs1.or(vs2); assertEquals(255L, vs1.getInteger()); vs1.setValue(255L); vs2.setValue(0L); vs1.or(vs2); assertEquals(255L, vs1.getInteger()); vs1.setValue(0L); vs2.setValue(255L); vs1.or(vs2); assertEquals(255L, vs1.getInteger()); vs1.setValue(0L); vs2.setValue(0L); vs1.or(vs2); assertEquals(0L, vs1.getInteger()); vs1.setValue(255L); vs2.setValue(255L); vs1.xor(vs2); assertEquals(0L, vs1.getInteger()); vs1.setValue(255L); vs2.setValue(0L); vs1.xor(vs2); assertEquals(255L, vs1.getInteger()); vs1.setValue(0L); vs2.setValue(255L); vs1.xor(vs2); assertEquals(255L, vs1.getInteger()); vs1.setValue(0L); vs2.setValue(0L); vs1.xor(vs2); assertEquals(0L, vs1.getInteger()); } /** * Test comparators. */ public void testComparators() { Value vs1 = new Value("Name", Value.VALUE_TYPE_INTEGER); Value vs2 = new Value("Name", Value.VALUE_TYPE_INTEGER); Value vs3 = new Value("Name", Value.VALUE_TYPE_INTEGER); vs1.setValue(128L); vs2.setValue(100L); vs3.setValue(128L); assertEquals(true, (vs1.Clone().greater_equal(vs2)).getBoolean()); assertEquals(true, (vs1.Clone().greater_equal(vs3)).getBoolean()); assertEquals(false, (vs2.Clone().greater_equal(vs1)).getBoolean()); assertEquals(false, (vs1.Clone().smaller_equal(vs2)).getBoolean()); assertEquals(true, (vs1.Clone().smaller_equal(vs3)).getBoolean()); assertEquals(true, (vs2.Clone().smaller_equal(vs1)).getBoolean()); assertEquals(true, (vs1.Clone().different(vs2)).getBoolean()); assertEquals(false, (vs1.Clone().different(vs3)).getBoolean()); assertEquals(false, (vs1.Clone().equal(vs2)).getBoolean()); assertEquals(true, (vs1.Clone().equal(vs3)).getBoolean()); assertEquals(true, (vs1.Clone().greater(vs2)).getBoolean()); assertEquals(false, (vs1.Clone().greater(vs3)).getBoolean()); assertEquals(false, (vs2.Clone().greater(vs1)).getBoolean()); assertEquals(false, (vs1.Clone().smaller(vs2)).getBoolean()); assertEquals(false, (vs1.Clone().smaller(vs3)).getBoolean()); assertEquals(true, (vs2.Clone().smaller(vs1)).getBoolean()); } /** * Test trim, ltrim, rtrim. */ public void testTrim() { Value vs1 = new Value("Name1", Value.VALUE_TYPE_INTEGER); Value vs2 = new Value("Name2", Value.VALUE_TYPE_STRING); vs1.setValue(128L); vs1.setNull(); assertNull(vs1.Clone().ltrim().getString()); assertNull(vs1.Clone().rtrim().getString()); assertNull(vs1.Clone().trim().getString()); vs1.setValue(128L); assertEquals("128", vs1.Clone().ltrim().getString()); assertEquals(" 128", vs1.Clone().rtrim().getString()); assertEquals("128", vs1.Clone().trim().getString()); vs2.setValue(" Sven Boden trim test "); assertEquals("Sven Boden trim test ", vs2.Clone().ltrim().getString()); assertEquals(" Sven Boden trim test", vs2.Clone().rtrim().getString()); assertEquals("Sven Boden trim test", vs2.Clone().trim().getString()); vs2.setValue(""); assertEquals("", vs2.Clone().ltrim().getString()); assertEquals("", vs2.Clone().rtrim().getString()); assertEquals("", vs2.Clone().trim().getString()); vs2.setValue(" "); assertEquals("", vs2.Clone().ltrim().getString()); assertEquals("", vs2.Clone().rtrim().getString()); assertEquals("", vs2.Clone().trim().getString()); } /** * Test hexDecode. */ public void testHexDecode() throws KettleValueException { Value vs1 = new Value("Name1", Value.VALUE_TYPE_INTEGER); vs1.setValue("6120622063"); vs1.hexDecode(); assertEquals("a b c", vs1.getString()); vs1.setValue("4161426243643039207A5A2E3F2F"); vs1.hexDecode(); assertEquals("AaBbCd09 zZ.?/", vs1.getString()); vs1.setValue("4161426243643039207a5a2e3f2f"); vs1.hexDecode(); assertEquals("AaBbCd09 zZ.?/", vs1.getString()); // leading 0 if odd. vs1.setValue("F6120622063"); vs1.hexDecode(); assertEquals("\u000fa b c", vs1.getString()); try { vs1.setValue("g"); vs1.hexDecode(); fail("Expected KettleValueException"); } catch (KettleValueException ex) { } } /** * Test hexEncode. */ public void testHexEncode() throws KettleValueException { Value vs1 = new Value("Name1", Value.VALUE_TYPE_INTEGER); vs1.setValue("AaBbCd09 zZ.?/"); vs1.hexEncode(); assertEquals("4161426243643039207A5A2E3F2F", vs1.getString()); vs1.setValue("1234567890"); vs1.hexEncode(); assertEquals("31323334353637383930", vs1.getString()); vs1.setNull(); vs1.hexEncode(); assertNull(vs1.getString()); } /** * Test like. */ public void testLike() { Value vs1 = new Value("Name1", Value.VALUE_TYPE_STRING); Value vs2 = new Value("Name2", Value.VALUE_TYPE_STRING); Value vs3 = new Value("Name3", Value.VALUE_TYPE_STRING); vs1.setValue("This is a test"); vs2.setValue("is a"); vs3.setValue("not"); assertEquals(true, (vs1.Clone().like(vs2)).getBoolean()); assertEquals(true, (vs1.Clone().like(vs1)).getBoolean()); assertEquals(false, (vs1.Clone().like(vs3)).getBoolean()); assertEquals(false, (vs3.Clone().like(vs1)).getBoolean()); } /** * Stuff which we didn't get in other checks. */ public void testLooseEnds() { assertEquals(Value.VALUE_TYPE_NONE, Value.getType("INVALID_TYPE")); assertEquals("String", Value.getTypeDesc(Value.VALUE_TYPE_STRING)); } /** * Constructors using Values DEBUG CLONE */ public void testClone2() { Value vs = new Value("Name", Value.VALUE_TYPE_NUMBER); vs.setValue(10.0D); vs.setOrigin("origin"); vs.setLength(4, 2); Value copy = (Value)vs.clone(); assertEquals(vs.getType(), copy.getType()); assertEquals(vs.getNumber(), copy.getNumber(), 0.1D); assertEquals(vs.getLength(), copy.getLength()); assertEquals(vs.getPrecision(), copy.getPrecision()); assertEquals(vs.isNull(), copy.isNull()); assertEquals(vs.getOrigin(), copy.getOrigin()); assertEquals(vs.getName(), copy.getName()); // Show it's a deep copy copy.setName("newName"); assertEquals("Name", vs.getName()); assertEquals("newName", copy.getName()); copy.setOrigin("newOrigin"); assertEquals("origin", vs.getOrigin()); assertEquals("newOrigin", copy.getOrigin()); copy.setValue(11.0D); assertEquals(10.0D, vs.getNumber(), 0.1D); assertEquals(11.0D, copy.getNumber(), 0.1D); Value vs1 = new Value("Name", Value.VALUE_TYPE_NUMBER); vs1.setName(null); // name and origin are null Value copy1 = new Value(vs1); assertEquals(vs1.getType(), copy1.getType()); assertEquals(vs1.getNumber(), copy1.getNumber(), 0.1D); assertEquals(vs1.getLength(), copy1.getLength()); assertEquals(vs1.getPrecision(), copy1.getPrecision()); assertEquals(vs1.isNull(), copy1.isNull()); assertEquals(vs1.getOrigin(), copy1.getOrigin()); assertEquals(vs1.getName(), copy1.getName()); Value vs2 = new Value((Value)null); assertTrue(vs2.isNull()); assertNull(vs2.getName()); assertNull(vs2.getOrigin()); } // Value.clone returns shallow copies of Value, is this intended // behaviour. }
package loop.confidence; import loop.Loop; import loop.LoopError; import loop.LoopTest; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.TreeMap; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Confidence tests run a bunch of semi-realistic programs and assert that their results are * as expected. This is meant to be our functional regression test suite. * * @author dhanji@gmail.com (Dhanji R. Prasanna) */ public class BasicFunctionsConfidenceTest extends LoopTest { @Test public final void reverseListPatternMatching() { assertEquals(Arrays.asList(3, 2, 1), Loop.run("test/loop/confidence/reverse.loop")); } @Test public final void reverseListPatternMatchingGuarded1() { assertEquals(Arrays.asList(3, 2, 1), Loop.run("test/loop/confidence/reverse_guarded_1.loop")); } @Test public final void reverseListPatternMatchingGuarded2() { // Doesn't reverse the list if the first element is >= 10. assertEquals(Arrays.asList(10, 20, 30), Loop.run("test/loop/confidence/reverse_guarded_2.loop")); } @Test public final void listStructurePatternMatchingGuarded1() { assertEquals(Arrays.asList(2, 3, 10), Loop.run("test/loop/confidence/list_pattern_guarded_1.loop")); } @Test public final void listStructurePatternMatchingGuarded2() { assertEquals(Arrays.asList(5, 2, 3), Loop.run("test/loop/confidence/list_pattern_guarded_2.loop")); } @Test public final void listStructurePatternMatchingGuarded3() { assertEquals(Arrays.asList(55), Loop.run("test/loop/confidence/list_pattern_guarded_3.loop")); } @Test public final void reverseListPatternMatchingUsingWhereBlock() { assertEquals(Arrays.asList(3, 2, 1), Loop.run("test/loop/confidence/whereblock_1.loop")); } @Test public final void reverseListPatternMatchingUsingNestedWhereBlocks() { assertEquals(Arrays.asList(4, 3, 2, 1), Loop.run("test/loop/confidence/whereblock_2.loop", true)); } @Test public final void whereBlockAssignments() { assertEquals(26208, Loop.run("test/loop/confidence/whereblock_3.loop")); } // @Test public final void objectPatternMatch1() { assertEquals("Stephen", Loop.run("test/loop/confidence/pattern_matching_objects_1.loop", true)); } // @Test public final void objectPatternMatch2() { assertEquals("Stephenpa", Loop.run("test/loop/confidence/pattern_matching_objects_2.loop")); } @Test public final void reverseStringPatternMatching() { assertEquals("olleh", Loop.run("test/loop/confidence/reverse_string.loop")); } @Test public final void splitLinesStringPatternMatching() { assertEquals("hellotheredude", Loop.run("test/loop/confidence/split_lines_string.loop")); } @Test public final void splitLinesStringMultiargPatternMatching() { assertEquals("hellotheredude", Loop.run("test/loop/confidence/split_lines_string_2.loop")); } @Test public final void splitVariousStringsPatternMatching() { assertEquals("1234", Loop.run("test/loop/confidence/split_various_string.loop")); } @Test public final void splitVariousStringsPatternMatchingWithWildcards() { assertEquals("3", Loop.run("test/loop/confidence/split_various_selective.loop")); } @Test(expected = RuntimeException.class) public final void splitVariousStringsPatternMatchingNotAllMatches() { assertTrue(Loop.run("test/loop/confidence/split_various_string_error.loop") instanceof LoopError); } @Test(expected = RuntimeException.class) public final void reverseLoopPatternMissingError() { assertTrue(Loop.run("test/loop/confidence/reverse_error.loop") instanceof LoopError); } @Test public final void callJavaMethodOnString() { assertEquals("hello", Loop.run("test/loop/confidence/java_call_on_string.loop", true)); } // @Test public final void nullSafeCallChain1() { assertEquals("dhanji", Loop.run("test/loop/confidence/nullsafe_1.loop")); } // @Test public final void nullSafeCallChain2() { assertEquals(null, Loop.run("test/loop/confidence/nullsafe_2.loop")); } @Test public final void stringInterpolation1() { assertEquals("Hello, Dhanji", Loop.run("test/loop/confidence/string_lerp_1.loop")); } @Test public final void stringInterpolation2() { assertEquals("There are 8 things going on in England", Loop.run("test/loop/confidence/string_lerp_2.loop")); } @Test public final void stringInterpolation3() { assertEquals("There are @{2 + 6} things going @{\"on\"} in @{name}land", Loop.run("test/loop/confidence/string_lerp_3.loop")); } @Test public final void intLiteralPatternMatching() { Map<String, String> map = new HashMap<String, String>(); map.put("name", "Michael"); map.put("age", "212"); assertEquals(map, Loop.run("test/loop/confidence/literal_pattern_matching.loop")); } @Test public final void wildcardPatternMatchingGuarded1() { Map<String, String> map = new HashMap<String, String>(); map.put("count", "10"); assertEquals(map, Loop.run("test/loop/confidence/wildcard_pattern_matching_guarded_1.loop")); } @Test public final void wildcardPatternMatchingGuarded2() { Map<String, String> map = new HashMap<String, String>(); map.put("count", "100"); assertEquals(map, Loop.run("test/loop/confidence/wildcard_pattern_matching_guarded_2.loop")); } @Test public final void wildcardPatternMatchingGuarded3() { Map<String, String> map = new HashMap<String, String>(); map.put("count", "infinity"); assertEquals(map, Loop.run("test/loop/confidence/wildcard_pattern_matching_guarded_3.loop")); } @Test public final void regexPatternMatching() { Map<String, String> map = new HashMap<String, String>(); map.put("name", "Michael"); map.put("age", "212"); assertEquals(map, Loop.run("test/loop/confidence/regex_pattern_matching.loop")); } @Test public final void regexPatternMatchingGuarded1() { Map<String, String> map = new HashMap<String, String>(); map.put("name", "Dhanji"); map.put("age", "20"); assertEquals(map, Loop.run("test/loop/confidence/regex_pattern_matching_guarded_1.loop")); } @Test public final void regexPatternMatchingGuarded2() { Map<String, String> map = new HashMap<String, String>(); assertEquals(map, Loop.run("test/loop/confidence/regex_pattern_matching_guarded_2.loop")); } @Test public final void regexPatternMatchingGuarded3() { Map<String, String> map = new HashMap<String, String>(); map.put("name", "Unknown"); map.put("age", "-1"); assertEquals(map, Loop.run("test/loop/confidence/regex_pattern_matching_guarded_3.loop")); } @Test public final void patternMatchingMultipleArg1() { Map<String, String> map = new HashMap<String, String>(); map.put("count", "10"); assertEquals(map, Loop.run("test/loop/confidence/pattern_matching_multiarg_1.loop", true)); } // @Test public final void propertyNavigation1() { assertEquals("Peter", Loop.run("test/loop/confidence/property_nav_1.loop")); } @Test public final void simpleSet() { assertEquals(new HashSet<Integer>(Arrays.asList(1, 2, 3, 5)), Loop.run("test/loop/confidence/sets_1.loop")); } @Test public final void stringSet() { assertEquals(new HashSet<String>(Arrays.asList("hi")), Loop.run("test/loop/confidence/sets_2.loop")); } @Test @SuppressWarnings("unchecked") public final void simpleTree() { Object tree = Loop.run("test/loop/confidence/trees_1.loop"); assertTrue(tree instanceof TreeMap); assertTrue(Arrays.asList( "l", "o", "o", "p").equals(new ArrayList<String>(((Map) tree).values()))); } }
package info.xiaomo.security; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class}) @ComponentScan("info.xiaomo") @EntityScan("info.xiaomo.*.model") @EnableWebSecurity public class SecurityMain extends WebSecurityConfigurerAdapter { public static void main(String[] args) throws Exception { SpringApplication.run(SecurityMain.class, args); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/", "/home").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("test").password("test").roles("USER"); } }
package com.breakersoft.plow.util; import java.sql.ResultSet; import java.sql.SQLException; import org.apache.commons.lang.StringUtils; import com.breakersoft.plow.thrift.TaskTotalsT; public final class JdbcUtils { public static String Insert(String table, String ... cols) { final StringBuilder sb = new StringBuilder(1024); sb.append("INSERT INTO "); sb.append(table); sb.append("("); sb.append(StringUtils.join(cols, ",")); sb.append(") VALUES ("); sb.append(StringUtils.repeat("?",",", cols.length)); sb.append(")"); return sb.toString(); } public static String Update(String table, String keyCol, String ... cols) { final StringBuilder sb = new StringBuilder(1024); sb.append("UPDATE "); sb.append(table); sb.append(" SET "); for (String col: cols) { sb.append(col); sb.append("=?,"); } sb.deleteCharAt(sb.length()-1); sb.append("WHERE "); sb.append(keyCol); sb.append("=?"); return sb.toString(); } public static String In(String col, int size) { return String.format("%s IN (%s)", col, StringUtils.repeat("?",",", size)); } public static String In(String col, int size, String cast) { final String repeat = "?::" + cast; return String.format("%s IN (%s)", col, StringUtils.repeat(repeat,",", size)); } public static final String limitOffset(int limit, int offset) { return String.format("LIMIT %d OFFSET %d", limit, offset); } public static TaskTotalsT getTaskTotals(ResultSet rs) throws SQLException { TaskTotalsT t = new TaskTotalsT(); t.setTotalTaskCount(rs.getInt("int_total")); t.setSucceededTaskCount(rs.getInt("int_succeeded")); t.setRunningTaskCount(rs.getInt("int_running")); t.setDeadTaskCount(rs.getInt("int_dead")); t.setEatenTaskCount(rs.getInt("int_eaten")); t.setWaitingTaskCount(rs.getInt("int_waiting")); t.setDependTaskCount(rs.getInt("int_depend")); return t; } }
package protocolsupport.protocol.utils; import java.text.MessageFormat; import java.util.EnumMap; import java.util.Map; import java.util.function.BiConsumer; import io.netty.buffer.ByteBuf; import protocolsupport.api.ProtocolVersion; public class SimpleTypeSerializer<T> { protected final Map<ProtocolVersion, BiConsumer<ByteBuf, T>> entries = new EnumMap<>(ProtocolVersion.class); public SimpleTypeSerializer() { } @SafeVarargs public SimpleTypeSerializer(Map.Entry<BiConsumer<ByteBuf, T>, ProtocolVersion[]>... entries) { for (Map.Entry<BiConsumer<ByteBuf, T>, ProtocolVersion[]> entry : entries) { BiConsumer<ByteBuf, T> serializer = entry.getKey(); for (ProtocolVersion version : entry.getValue()) { this.entries.put(version, serializer); } } } public BiConsumer<ByteBuf, T> get(ProtocolVersion version) { BiConsumer<ByteBuf, T> serializer = entries.get(version); if (serializer == null) { throw new IllegalArgumentException(MessageFormat.format("Don''t know how to serialize type for protocol version {0}", version)); } return entries.get(version); } protected void register(BiConsumer<ByteBuf, T> serializer, ProtocolVersion... versions) { for (ProtocolVersion version : versions) { entries.put(version, serializer); } } }
package com.devicehive.dao; import com.devicehive.configuration.Constants; import com.devicehive.model.Configuration; import com.devicehive.util.LogExecutionTime; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import javax.persistence.TypedQuery; import javax.validation.constraints.NotNull; import java.util.List; import static com.devicehive.model.Configuration.Queries.Names.DELETE; import static com.devicehive.model.Configuration.Queries.Names.GET_ALL; import static com.devicehive.model.Configuration.Queries.Names.GET_BY_NAME; import static com.devicehive.model.Configuration.Queries.Parameters.NAME; @Stateless @LogExecutionTime public class ConfigurationDAO { @PersistenceContext(unitName = Constants.PERSISTENCE_UNIT) private EntityManager em; public Configuration findByName(@NotNull String name) { TypedQuery<Configuration> query = em.createNamedQuery(GET_BY_NAME, Configuration.class); query.setParameter(NAME, name); CacheHelper.cacheable(query); List<Configuration> list = query.getResultList(); return list.isEmpty() ? null : list.get(0); } @TransactionAttribute(TransactionAttributeType.SUPPORTS) public List<Configuration> findAll() { TypedQuery<Configuration> query = em.createNamedQuery(GET_ALL, Configuration.class); CacheHelper.cacheable(query); return query.getResultList(); } public void save(@NotNull String name, String value) { Configuration existing = findByName(name); if (existing != null) { existing.setValue(value); } else { Configuration configuration = new Configuration(); configuration.setName(name); configuration.setValue(value); em.persist(configuration); } } public void delete(@NotNull String name) { Query query = em.createNamedQuery(DELETE); query.setParameter(NAME, name); query.executeUpdate(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.broad.igv.sam; import net.sf.samtools.SAMFileHeader; import net.sf.samtools.util.CloseableIterator; import org.broad.igv.PreferenceManager; import org.broad.igv.sam.reader.AlignmentReader; import org.broad.igv.sam.reader.AlignmentReaderFactory; import org.broad.igv.sam.reader.ReadGroupFilter; import org.broad.igv.util.ResourceLocator; import org.broad.igv.util.TestUtils; import org.junit.*; import java.io.IOException; import java.util.*; import static org.junit.Assert.*; /** * @author jrobinso */ public class CachingQueryReaderTest { String testFile = "http: String sequence = "chr1"; int start = 44680145; int end = 44789983; private boolean contained = false; public CachingQueryReaderTest() { } @BeforeClass public static void setUpClass() throws Exception { TestUtils.setUpHeadless(); } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of getHeader method, of class CachingQueryReader. The test compares * the results of CachingQueryReader with a non-caching reader which * is assumed to be correct. */ @Test public void testGetHeader() throws IOException { ResourceLocator loc = new ResourceLocator(testFile); AlignmentReader reader = AlignmentReaderFactory.getReader(loc); SAMFileHeader expectedHeader = reader.getHeader(); reader.close(); reader = AlignmentReaderFactory.getReader(loc); CachingQueryReader cachingReader = new CachingQueryReader(reader); SAMFileHeader header = cachingReader.getHeader(); cachingReader.close(); assertTrue(header.equals(expectedHeader)); } @Test public void testQuery() throws IOException { tstQuery(testFile, sequence, start, end, contained, Integer.MAX_VALUE / 1000); } /** * Test of query method, of class CachingQueryReader. The test compares * the results of CachingQueryReader non-caching reader which * is assumed to be correct. * <p/> * Note that SAMFileReader (which is the non-caching reader) is 1-based * and inclusive-end. CachingQueryReader is 0-based and exclusive end. */ public void tstQuery(String testFile, String sequence, int start, int end, boolean contained, int maxDepth) throws IOException { ResourceLocator loc = new ResourceLocator(testFile); AlignmentReader reader = AlignmentReaderFactory.getReader(loc); CloseableIterator<Alignment> iter = reader.query(sequence, start, end, contained); List<Alignment> expectedResult = new ArrayList<Alignment>(); while (iter.hasNext()) { Alignment rec = iter.next(); // the following filters are applied in the Caching reader, so we need to apply them here. boolean filterFailedReads = PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SAM_FILTER_FAILED_READS); ReadGroupFilter filter = ReadGroupFilter.getFilter(); boolean showDuplicates = PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SAM_SHOW_DUPLICATES); int qualityThreshold = PreferenceManager.getInstance().getAsInt(PreferenceManager.SAM_QUALITY_THRESHOLD); if (!rec.isMapped() || (!showDuplicates && rec.isDuplicate()) || (filterFailedReads && rec.isVendorFailedRead()) || rec.getMappingQuality() < qualityThreshold || (filter != null && filter.filterAlignment(rec))) { continue; } expectedResult.add(rec); //System.out.println("name: " + rec.getReadName() + "strt: " + rec.getStart() + " end: " + rec.getEnd()); if (contained) { assertTrue(rec.getStart() >= start); } else { //All we require is some overlap boolean overlap = rec.getStart() >= start && rec.getStart() < end; overlap |= (rec.getEnd() >= start) && (rec.getStart() < start); assertTrue(overlap); } assertEquals(sequence, rec.getChr()); } reader.close(); reader = AlignmentReaderFactory.getReader(loc); CachingQueryReader cachingReader = new CachingQueryReader(reader); CloseableIterator<Alignment> cachingIter = cachingReader.query(sequence, start, end, new ArrayList(), new ArrayList(), new ArrayList<CachingQueryReader.DownsampledInterval>(), maxDepth, null, null); List<Alignment> result = new ArrayList(); while (cachingIter.hasNext()) { result.add(cachingIter.next()); } cachingReader.close(); assertTrue(expectedResult.size() > 0); assertEquals(expectedResult.size(), result.size()); //Reads sorted by start position, apparently there is some wiggle room in the exact order //We sort each first by start position, then end position Collections.sort(expectedResult, new StartEndSorter()); Collections.sort(result, new StartEndSorter()); for (int i = 0; i < result.size(); i++) { Alignment rec = result.get(i); if (i % 2 == 0 && rec.isPaired()) { //Check that paired reads are together System.out.println(rec.getReadName()); System.out.println(result.get(i + 1).getReadName()); //assertEquals(rec.getReadName(), result.get(i+1).getReadName()); } if (contained) { assertTrue(rec.getStart() >= start); } else { //All we require is some overlap boolean overlap = rec.getStart() >= start && rec.getStart() < end; overlap |= start >= rec.getStart() && start < rec.getEnd(); assertTrue(overlap); } assertEquals(sequence, rec.getChr()); Alignment exp = expectedResult.get(i); assertEquals("Start mismatch at position " + i + " read name " + exp.getReadName(), exp.getStart(), rec.getStart()); assertEquals(exp.getReadName(), rec.getReadName()); assertEquals("End mismatch at position " + i + " read name " + rec.getReadName(), exp.getEnd(), rec.getEnd()); } } @Ignore @Test public void testQueryLargeFile() throws Exception { PreferenceManager.getInstance().put(PreferenceManager.SAM_MAX_VISIBLE_RANGE, "5"); String path = TestUtils.LARGE_DATA_DIR + "/ABCD_igvSample.bam"; ResourceLocator loc = new ResourceLocator(path); AlignmentReader reader = AlignmentReaderFactory.getReader(loc); CachingQueryReader cachingReader = new CachingQueryReader(reader); //Edge location String sequence = "chr12"; int start = 56815621 - 1; int end = start + 1; int expSize = 1066; tstSize(cachingReader, sequence, start, end, (int) (expSize * 1.6), expSize); tstQuery(path, sequence, start, end, false, 10000); //Edge location, downsampled sequence = "chr12"; start = 56815635 - 1; end = start + 1; expSize = 165; reader = AlignmentReaderFactory.getReader(loc); cachingReader = new CachingQueryReader(reader); tstSize(cachingReader, sequence, start, end, expSize + 20, expSize); tstQuery(path, sequence, start, end, false, 10000); //Center location sequence = "chr12"; start = 56815675 - 1; end = start + 1; expSize = 3288; reader = AlignmentReaderFactory.getReader(loc); cachingReader = new CachingQueryReader(reader); tstSize(cachingReader, sequence, start, end, expSize + 20, expSize); tstQuery(path, sequence, start, end, false, 10000); } @Test public void testQueryPiledUp() throws Exception { PreferenceManager.getInstance().put(PreferenceManager.SAM_MAX_VISIBLE_RANGE, "5"); String path = TestUtils.DATA_DIR + "/aligned/pileup.sorted.aligned"; ResourceLocator loc = new ResourceLocator(path); AlignmentReader reader = AlignmentReaderFactory.getReader(loc); CachingQueryReader cachingReader = new CachingQueryReader(reader); //Edge location String sequence = "chr1"; int start = 141 - 1; int end = start + 1; int expSize = 40; tstSize(cachingReader, sequence, start, end, expSize * 7, expSize); loc = new ResourceLocator(path); reader = AlignmentReaderFactory.getReader(loc); cachingReader = new CachingQueryReader(reader); tstSize(cachingReader, sequence, start, end, expSize * 100, expSize); tstQuery(path, sequence, start, end, false, 10000); //Center, deep coverage region sequence = "chr1"; start = 429; end = start + 1; int coverageLim = 1000; expSize = 1408; loc = new ResourceLocator(path); reader = AlignmentReaderFactory.getReader(loc); cachingReader = new CachingQueryReader(reader); tstSize(cachingReader, sequence, start, end, coverageLim, expSize); coverageLim = 10000; expSize = 1408; loc = new ResourceLocator(path); reader = AlignmentReaderFactory.getReader(loc); cachingReader = new CachingQueryReader(reader); tstSize(cachingReader, sequence, start, end, coverageLim, expSize); tstQuery(path, sequence, start, end, false, coverageLim); } public List<Alignment> tstSize(CachingQueryReader cachingReader, String sequence, int start, int end, int maxDepth, int expSize) { CloseableIterator<Alignment> cachingIter = cachingReader.query(sequence, start, end, new ArrayList(), new ArrayList(), new ArrayList<CachingQueryReader.DownsampledInterval>(), maxDepth, null, null); List<Alignment> result = new ArrayList(); while (cachingIter.hasNext()) { result.add(cachingIter.next()); } assertEquals(expSize, result.size()); return result; } /** * Test that sampling keeps pairs together. Note that this test requires a lot of memory (2Gb on this devs machine) * Pairs are only definitely kept together if they end up on the same tile, so we need 1 big tile. * * @throws Exception */ @Ignore @Test public void testKeepPairs() throws Exception { String path = "http: String sequence = "1"; int start = 1; int end = 2000; int maxDepth = 2; String max_vis = PreferenceManager.getInstance().get(PreferenceManager.SAM_MAX_VISIBLE_RANGE); PreferenceManager.getInstance().put(PreferenceManager.SAM_MAX_VISIBLE_RANGE, "" + (end - start)); try { ResourceLocator loc = new ResourceLocator(path); AlignmentReader reader = AlignmentReaderFactory.getReader(loc); CachingQueryReader cachingReader = new CachingQueryReader(reader); CloseableIterator<Alignment> iter = cachingReader.query(sequence, start, end, new ArrayList(), new ArrayList(), new ArrayList<CachingQueryReader.DownsampledInterval>(), maxDepth, null, null); int count = 0; Map<String, Integer> pairedReads = new HashMap<String, Integer>(); while (iter.hasNext()) { Alignment al = iter.next(); assertNotNull(al); count++; if (al.isPaired() && al.getMate().isMapped()) { //Mate may not be part of the query. //Make sure it's within bounds int mateStart = al.getMate().getStart(); //All we require is some overlap boolean overlap = mateStart >= start && mateStart < end; if (overlap) { Integer rdCnt = pairedReads.get(al.getReadName()); rdCnt = rdCnt != null ? rdCnt + 1 : 1; pairedReads.put(al.getReadName(), rdCnt); } } } assertTrue(count > 0); //Note: CachingQueryReader will not line alignments up properly if they land in different tiles int countmissing = 0; for (String readName : pairedReads.keySet()) { int val = pairedReads.get(readName); countmissing += 2 == val ? 0 : 1; if (val != 2) { System.out.println("Read " + readName + " has val " + val); } } //System.out.println("Number of paired reads: " + pairedReads.size()); assertTrue("No pairs in test data set", pairedReads.size() > 0); assertEquals("Missing " + countmissing + " out of " + pairedReads.size() + " pairs", 0, countmissing); } catch (Exception e) { PreferenceManager.getInstance().put(PreferenceManager.SAM_MAX_VISIBLE_RANGE, max_vis); throw e; } } /** * The main purpose of this test is to see if we get a * heap space error. * * @throws Exception */ @Test public void testQueryLargeFile2() throws Exception { String path = "http: ResourceLocator loc = new ResourceLocator(path); AlignmentReader reader = AlignmentReaderFactory.getReader(loc); CachingQueryReader cachingReader = new CachingQueryReader(reader); String sequence = "MT"; int start = 1000; int end = 3000; int maxDepth = 500; CloseableIterator<Alignment> iter = cachingReader.query(sequence, start, end, new ArrayList(), new ArrayList(), new ArrayList<CachingQueryReader.DownsampledInterval>(), maxDepth, null, null); int count = 0; while (iter.hasNext()) { Alignment al = iter.next(); assertNotNull(al); count++; } assertTrue(count > 0); } /** * Sorts by: read name, start, end */ private class StartEndSorter implements Comparator<Alignment> { public int compare(Alignment o1, Alignment o2) { Alignment al1 = (Alignment) o1; Alignment al2 = (Alignment) o2; String n1 = al1.getReadName(); n1 = n1 != null ? n1 : ""; int nStart = n1.compareTo(al2.getReadName()); if (nStart != 0) { return nStart; } int cStarts = compareInts(al1.getStart(), al2.getStart()); if (cStarts != 0) { return cStarts; } int cEnds = compareInts(al1.getEnd(), al2.getEnd()); return cEnds; } private int compareInts(int i1, int i2) { if (i1 < i2) { return -1; } else if (i1 > i2) { return +1; } else { return 0; } } } public static void main(String[] args) { //Represents total number of alignments long totalLength = (long) 1e6; //Memory used per alignment int longseach = 100; int maxKeep = 1000; float fmaxKeep = (float) maxKeep; int maxBucketDepth = (int) 1e5; long seed = 5310431327l; long t1 = System.currentTimeMillis(); liveSample(totalLength, longseach, seed, maxKeep, maxBucketDepth * 10); long t2 = System.currentTimeMillis(); System.out.println("Time for live sampling: " + (t2 - t1) + " mSec"); long t3 = System.currentTimeMillis(); downSample(totalLength, longseach, seed, maxKeep, maxBucketDepth); long t4 = System.currentTimeMillis(); System.out.println("Time for down sampling: " + (t4 - t3) + " mSec"); } /** * Test that our live sample gives a uniform distribution */ @Test public void testLiveSample() throws Exception { int totalLength = (int) 1e4; //Store the number of times each index is sampled int[] counts = new int[totalLength]; List<long[]> samples; int longseach = 1; long seed = 212338399; Random rand = new Random(seed); int maxKeep = 1000; int maxBucketDepth = Integer.MAX_VALUE; int trials = 10000; for (int _ = 0; _ < trials; _++) { seed = rand.nextLong(); samples = liveSample(totalLength, longseach, seed, maxKeep, maxBucketDepth); for (long[] dat : samples) { counts[(int) dat[0]] += 1; } } float avgFreq = ((float) maxKeep) / totalLength; int avgCount = (int) (avgFreq * trials); double stdDev = Math.sqrt(trials / 12); int numStds = 4; int ind = 0; //System.out.println("Expected number of times sampled: " + avgCount + ". Stdev " + stdDev); for (int cnt : counts) { //System.out.println("ind: " + ind + " cnt: " + cnt); assertTrue("Index " + ind + " outside of expected sampling range at " + cnt, Math.abs(cnt - avgCount) < numStds * stdDev); ind++; } } private static List<long[]> liveSample(long totalLength, int longseach, long seed, int maxKeep, int maxBucketDepth) { List<long[]> liveSampled = new ArrayList<long[]>(maxKeep); float fmaxKeep = (float) maxKeep; RandDataIterator iter1 = new RandDataIterator(totalLength, longseach); float prob = 0; Random rand = new Random(seed); int numAfterMax = 1; for (long[] data : iter1) { if (liveSampled.size() < maxKeep) { liveSampled.add(data); } else if (liveSampled.size() > maxBucketDepth) { break; } else { //Calculate whether to accept this element prob = fmaxKeep / (maxKeep + numAfterMax); numAfterMax += 1; boolean keep = rand.nextFloat() < prob; if (keep) { //Choose one to replace int torep = rand.nextInt(maxKeep); liveSampled.remove(torep); liveSampled.add(data); } } } return liveSampled; } private static List<long[]> downSample(long totalLength, int longseach, long seed, int maxKeep, int maxBucketDepth) { List<long[]> downSampled = new ArrayList<long[]>(maxKeep); RandDataIterator iter2 = new RandDataIterator(totalLength, longseach); Random rand = new Random(seed); for (long[] data : iter2) { if (downSampled.size() < maxBucketDepth) { downSampled.add(data); } else { break; } } //Actual downsampling while (downSampled.size() > maxKeep) { downSampled.remove(rand.nextInt(downSampled.size())); } return downSampled; } /** * Iterator over garbage data. */ private static class RandDataIterator implements Iterable<long[]>, Iterator<long[]> { private long counter; private long length; private int longseach; /** * @param length Number of elements that this iterator will have * @param longseach how large each element will be (byte array) */ public RandDataIterator(long length, int longseach) { this.length = length; this.longseach = longseach; } public boolean hasNext() { return counter < length; } public long[] next() { if (!hasNext()) { return null; } long[] arr = new long[longseach]; Arrays.fill(arr, counter); counter++; return arr; } public void remove() { throw new UnsupportedOperationException("Can't remove"); } public Iterator<long[]> iterator() { return this; } } }
package io.spine.server.model; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Streams; import com.google.common.graph.Traverser; import com.google.common.reflect.TypeToken; import com.google.errorprone.annotations.Immutable; import io.spine.base.CommandMessage; import io.spine.base.EventMessage; import io.spine.reflect.Types; import io.spine.server.type.CommandClass; import io.spine.server.type.EventClass; import io.spine.type.MessageClass; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.function.Predicate; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static io.spine.util.Exceptions.newIllegalArgumentException; /** * Obtains a set of command or event types produced by a {@link HandlerMethod}. * * <p>The set contains <em>class</em> information collected from method signatures. * If a method result refers to an interface (directly or as a generic parameter), this * interface is not added to the set. Thus, if a method returns {@code List<EventMessage>}, * the set would be empty. */ @Immutable final class MethodResults { /** * Checks if the class is a concrete {@linkplain CommandMessage command} or * {@linkplain EventMessage event}. */ private static final Predicate<Class<?>> IS_COMMAND_OR_EVENT = cls -> { if (cls.isInterface()) { return false; } if (Nothing.class.equals(cls)) { return false; } boolean isCommandOrEvent = CommandMessage.class.isAssignableFrom(cls) || EventMessage.class.isAssignableFrom(cls); return isCommandOrEvent; }; /** Prevents instantiation of this utility class. */ private MethodResults() { } /** * Collects command or event classes declared in the return type of the handler method. * * <p>If the method returns a parameterized type like {@link Iterable}, the produced messages * are gathered from its generic arguments. Generic arguments are traversed recursively enabling * correct parsing of return types like {@code Pair<ProjectCreated, Optional<ProjectStarted>>}. * * <p>Too broad types are ignored, so methods returning something like * {@code Optional<Message>} are deemed producing no types. * * @param method * the handler method * @param <P> * the type of the produced message classes * @return the set of message classes produced by the method */ @SuppressWarnings("unchecked") /* The cast to `<P>` is a convenience for calling sites, and is safe as all handler methods in the model produce either commands OR events. The method is thus parameterized with a produced message class, and the runtime checks are only used for convenience. */ static <P extends MessageClass<?>> ImmutableSet<P> collectMessageClasses(Method method) { checkNotNull(method); Type returnType = method.getGenericReturnType(); Iterable<Type> allTypes = Traverser.forTree(Types::resolveArguments) .breadthFirst(returnType); ImmutableSet<P> result = Streams.stream(allTypes) .map(TypeToken::of) .map(TypeToken::getRawType) .filter(IS_COMMAND_OR_EVENT) .map(c -> (P) toMessageClass(c)) .collect(toImmutableSet()); return result; } /** * Converts the command or event class to the corresponding {@link MessageClass}. */ @SuppressWarnings("unchecked") // checked by `isAssignableFrom()` private static MessageClass<?> toMessageClass(Class<?> cls) { if (CommandMessage.class.isAssignableFrom(cls)) { return CommandClass.from((Class<? extends CommandMessage>) cls); } if (EventMessage.class.isAssignableFrom(cls)) { return EventClass.from((Class<? extends EventMessage>) cls); } throw newIllegalArgumentException( "A given type `%s` is neither a command nor an event.", cls.getCanonicalName() ); } }
package org.jboss.as.server; import java.io.IOException; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.ObjectInputValidation; import java.io.Serializable; import java.util.List; import org.jboss.as.model.AbstractServerModelUpdate; import org.jboss.as.server.mgmt.DomainServerConfigurationPersister; import org.jboss.logging.Logger; import org.jboss.msc.service.ServiceActivator; /** * This is the task used by the Host Controller and passed to a Server instance * in order to bootstrap it from a remote source process. * * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> */ public final class ServerStartTask implements ServerTask, Serializable, ObjectInputValidation { private static final long serialVersionUID = -8505496119636153918L; private final String serverName; private final int portOffset; private final List<ServiceActivator> startServices; private final List<AbstractServerModelUpdate<?>> updates; private final ServerEnvironment providedEnvironment; private static final Logger log = Logger.getLogger("org.jboss.as.server"); public ServerStartTask(final String serverName, final int portOffset, final List<ServiceActivator> startServices, final List<AbstractServerModelUpdate<?>> updates) { if (serverName == null || serverName.length() == 0) { throw new IllegalArgumentException("Server name " + serverName + " is invalid; cannot be null or blank"); } this.serverName = serverName; this.portOffset = portOffset; this.startServices = startServices; this.updates = updates; providedEnvironment = new ServerEnvironment(System.getProperties(), System.getenv(), false); } public void run(final List<ServiceActivator> runServices) { final Bootstrap bootstrap = Bootstrap.Factory.newInstance(); final Bootstrap.Configuration configuration = new Bootstrap.Configuration(); configuration.setServerEnvironment(providedEnvironment); configuration.setConfigurationPersister(new DomainServerConfigurationPersister(updates)); configuration.setPortOffset(portOffset); bootstrap.start(configuration, startServices); } public void validateObject() throws InvalidObjectException { if (serverName == null) { throw new InvalidObjectException("serverName is null"); } if (portOffset < 0) { throw new InvalidObjectException("portOffset is out of range"); } if (updates == null) { throw new InvalidObjectException("updates is null"); } if (startServices == null) { throw new InvalidObjectException("startServices is null"); } } private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { ois.defaultReadObject(); ois.registerValidation(this, 100); } }
package com.caucho.lucene.bfs; import io.baratine.core.ServiceManager; import io.baratine.core.Services; import io.baratine.files.BfsFileSync; import org.apache.lucene.store.Directory; import org.apache.lucene.store.IOContext; import org.apache.lucene.store.IndexInput; import org.apache.lucene.store.IndexOutput; import org.apache.lucene.store.Lock; import java.io.IOException; import java.io.InputStream; import java.util.Collection; public class BFSDirectory extends Directory { BfsFileSync _root; public BFSDirectory() { ServiceManager manager = Services.getCurrentManager(); int pod = manager.getPodNode().getNodeIndex(); String path = String.format("bfs:///usr/lib/lucene/index/node-%1$s", pod); _root = manager.lookup(path).as(BfsFileSync.class); } @Override public String[] listAll() throws IOException { return _root.list(); } @Override public void deleteFile(String s) throws IOException { BfsFileSync file = _root.lookup(s); file.remove(); } @Override public long fileLength(String s) throws IOException { BfsFileSync file = _root.lookup(s); return file.getStatus().getLength(); } @Override public IndexOutput createOutput(String s, IOContext ioContext) throws IOException { BfsFileSync file = _root.lookup(s); return new BfsIndexOutput(s, file); } @Override public void sync(Collection<String> collection) throws IOException { System.out.println("BFSDirectory.sync " + collection); } @Override public void renameFile(String from, String to) throws IOException { throw new IOException(String.format("can't move file %1$s %2$s", from, to)); } @Override public IndexInput openInput(String s, IOContext ioContext) throws IOException { BfsFileSync file = _root.lookup(s); return new BfsIndexInput(s, file); } @Override public Lock makeLock(String s) { return null; } @Override public void close() throws IOException { } } class BfsIndexOutput extends IndexOutput { InputStream _in; BfsFileSync _file; public BfsIndexOutput(String resourceDescription, BfsFileSync file) { super(resourceDescription); _file = file; } @Override public void close() throws IOException { System.out.println("BfsIndexOutput.close"); } @Override public long getFilePointer() { return 0; } @Override public long getChecksum() throws IOException { return 0; } @Override public void writeByte(byte b) throws IOException { System.out.println("BfsIndexOutput.writeByte " + b); } @Override public void writeBytes(byte[] bytes, int i, int i1) throws IOException { System.out.println("BfsIndexOutput.writeBytes " + bytes); } } class BfsIndexInput extends IndexInput { BfsFileSync _file; public BfsIndexInput(String resourceDescription, BfsFileSync file) { super(resourceDescription); _file = file; } @Override public void close() throws IOException { System.out.println("BfsIndexInput.close"); } @Override public long getFilePointer() { return 0; } @Override public void seek(long l) throws IOException { } @Override public long length() { return 0; } @Override public IndexInput slice(String s, long l, long l1) throws IOException { return null; } @Override public byte readByte() throws IOException { return 0; } @Override public void readBytes(byte[] bytes, int i, int i1) throws IOException { } }
package com.litle.sdk; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.matches; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.File; import java.util.Calendar; import java.util.List; import java.util.Properties; import org.junit.BeforeClass; import org.junit.Test; import com.litle.sdk.generate.AuthInformation; import com.litle.sdk.generate.AuthReversal; import com.litle.sdk.generate.AuthReversalResponse; import com.litle.sdk.generate.Authentication; import com.litle.sdk.generate.Authorization; import com.litle.sdk.generate.AuthorizationResponse; import com.litle.sdk.generate.Capture; import com.litle.sdk.generate.CaptureGivenAuth; import com.litle.sdk.generate.CaptureGivenAuthResponse; import com.litle.sdk.generate.CaptureResponse; import com.litle.sdk.generate.CardType; import com.litle.sdk.generate.Contact; import com.litle.sdk.generate.Credit; import com.litle.sdk.generate.CreditResponse; import com.litle.sdk.generate.CustomerInfo; import com.litle.sdk.generate.EcheckAccountTypeEnum; import com.litle.sdk.generate.EcheckCredit; import com.litle.sdk.generate.EcheckCreditResponse; import com.litle.sdk.generate.EcheckRedeposit; import com.litle.sdk.generate.EcheckRedepositResponse; import com.litle.sdk.generate.EcheckSale; import com.litle.sdk.generate.EcheckSalesResponse; import com.litle.sdk.generate.EcheckType; import com.litle.sdk.generate.EcheckVerification; import com.litle.sdk.generate.EcheckVerificationResponse; import com.litle.sdk.generate.EcheckVoid; import com.litle.sdk.generate.EcheckVoidResponse; import com.litle.sdk.generate.ForceCapture; import com.litle.sdk.generate.ForceCaptureResponse; import com.litle.sdk.generate.LitleOnlineRequest; import com.litle.sdk.generate.MethodOfPaymentTypeEnum; import com.litle.sdk.generate.OrderSourceType; import com.litle.sdk.generate.RegisterTokenRequestType; import com.litle.sdk.generate.RegisterTokenResponse; import com.litle.sdk.generate.Sale; import com.litle.sdk.generate.SaleResponse; import com.litle.sdk.generate.TransactionTypeWithReportGroup; public class TestLitleBatchFileRequest { private static LitleBatchFileRequest litleBatchFileRequest; @BeforeClass public static void beforeClass() throws Exception { Properties property = new Properties(); property.setProperty("username", "PHXMLTEST"); property.setProperty("password", "password"); property.setProperty("version", "8.18"); property.setProperty("maxAllowedTransactionsPerFile", "1000"); property.setProperty("maxTransactionsPerBatch", "500"); property.setProperty("batchHost", "l-rraman-ws490"); property.setProperty("batchPort", "2104"); property.setProperty("batchTcpTimeout", "10000"); property.setProperty("batchUseSSL", "false"); property.setProperty("merchantId", "101"); litleBatchFileRequest = new LitleBatchFileRequest("testFile", property); } @Test public void testEndToEndMerchantBatchSDK() throws Exception { LitleBatchRequest litleBatchRequest = litleBatchFileRequest.createBatch("101"); Sale sale = new Sale(); sale.setAmount(106L); sale.setOrderId("12344"); sale.setOrderSource(OrderSourceType.ECOMMERCE); CardType card = new CardType(); card.setType(MethodOfPaymentTypeEnum.VI); card.setNumber("4100000000000002"); card.setExpDate("1210"); sale.setCard(card); sale.setReportGroup("ding"); litleBatchRequest.addTransaction(sale); Authorization auth = new Authorization(); auth.setAmount(200L); auth.setOrderId("12345"); auth.setOrderSource(OrderSourceType.ECOMMERCE); CardType card2 = new CardType(); card2.setType(MethodOfPaymentTypeEnum.VI); card2.setNumber("4242424242424242"); card2.setExpDate("1014"); auth.setCard(card2); auth.setReportGroup("Ramya"); litleBatchRequest.addTransaction(auth); LitleBatchRequest litleBatchRequest2 = litleBatchFileRequest.createBatch("101"); Sale sale1 = new Sale(); sale1.setAmount(2500L); sale1.setOrderId("12346"); sale1.setOrderSource(OrderSourceType.ECOMMERCE); CardType card3 = new CardType(); card3.setType(MethodOfPaymentTypeEnum.VI); card3.setNumber("4100000000000002"); card3.setExpDate("1218"); sale1.setCard(card3); sale1.setReportGroup("abc"); litleBatchRequest2.addTransaction(sale1); Authorization auth1 = new Authorization(); auth1.setAmount(8900L); auth1.setOrderId("12347"); auth1.setOrderSource(OrderSourceType.ECOMMERCE); CardType card4 = new CardType(); card4.setType(MethodOfPaymentTypeEnum.VI); card4.setNumber("4242424242424242"); card4.setExpDate("1220"); auth1.setCard(card4); auth1.setReportGroup("checking"); litleBatchRequest2.addTransaction(auth1); LitleBatchFileResponse litleBatchFileResponse = litleBatchFileRequest.sendToLitle(); assertNotNull(litleBatchFileResponse); // Generic way for accessing the objects // List<LitleBatchResponse> batchList = litleBatchFileResponse.getBatchResponseList(); // for (LitleBatchResponse batch : batchList) { // List<TransactionTypeWithReportGroup> txnList = batch.getResponseList(); // for(TransactionTypeWithReportGroup txn : txnList) { // if (txn instanceof SaleResponse) { // SaleResponse saleResponse = (SaleResponse) txn; // saleResponse.getOrderId(); // saleResponse.getResponse(); // saleResponse.getMessage(); // else if (txn instanceof AuthorizationResponse) { // AuthorizationResponse authResponse = (AuthorizationResponse) txn; // authResponse.getOrderId(); // authResponse.getResponse(); // authResponse.getMessage(); LitleBatchResponse litleBatchResponse0 = litleBatchFileResponse.getBatchResponseList().get(0); List<TransactionTypeWithReportGroup> txnList0 = litleBatchResponse0.getResponseList(); SaleResponse saleResponse = (SaleResponse) txnList0.get(0); assertEquals("12344", saleResponse.getOrderId()); assertEquals("000",saleResponse.getResponse()); assertEquals("Approved",saleResponse.getMessage()); AuthorizationResponse authResponse = (AuthorizationResponse) txnList0.get(1); assertEquals("12345",authResponse.getOrderId()); assertEquals("301",authResponse.getResponse()); assertEquals("Invalid Account Number",authResponse.getMessage()); LitleBatchResponse litleBatchResponse1 = litleBatchFileResponse.getBatchResponseList().get(1); List<TransactionTypeWithReportGroup> txnList1 = litleBatchResponse1.getResponseList(); SaleResponse saleResponse1 = (SaleResponse) txnList1.get(0); assertEquals("12346", saleResponse1.getOrderId()); assertEquals("000",saleResponse1.getResponse()); assertEquals("Approved",saleResponse1.getMessage()); AuthorizationResponse authResponse1 = (AuthorizationResponse) txnList1.get(1); assertEquals("12347",authResponse1.getOrderId()); assertEquals("301",authResponse1.getResponse()); assertEquals("Invalid Account Number",authResponse1.getMessage()); // litleBatchRequest.getBatchRequest().get(0); } @Test public void testEmptyCreateBatch() { LitleBatchFileRequest mockedLBFR = mock(LitleBatchFileRequest.class); Properties prpToPass = new Properties(); prpToPass.setProperty("maxTransactionsPerBatch", "0"); when(mockedLBFR.getConfig()).thenReturn(prpToPass); when(mockedLBFR.getNumberOfTransactionInFile()).thenReturn(0); when(mockedLBFR.getMaxAllowedTransactionsPerFile()).thenReturn(1); // LitleBatchRequest litleBatchRequest = litleBatchFileRequest.createBatch("101"); LitleBatchRequest objToTest = new LitleBatchRequest("101", mockedLBFR); try{ objToTest.addTransaction(null); } catch(LitleBatchException e){ } objToTest.addTransaction(null); //litleBatchFileRequest.sendToLitle(); } @Test public void testSendFileToIBC() throws Exception { File file = new File("/usr/local/litle-home/rraman/Requests/fileToPass1365454351441.xml"); //String responsePath = "/usr/local/litle-home/rraman/Responses/LitleResponse.xml"; Communication comm = new Communication(); Properties config = new Properties(); config.setProperty("batchHost", "l-rraman-ws490"); config.setProperty("batchPort", "2104"); config.setProperty("batchTcpTimeout", "100000"); config.setProperty("batchUseSSL", "false"); //LitleBatchFileResponse litleBatchFileResponse = new LitleBatchFileResponse(); comm.sendLitleBatchFileToIBC(file, config); } }
package org.objectweb.proactive.core.body; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import org.objectweb.proactive.ProActive; import org.objectweb.proactive.ProActiveInternalObject; import org.objectweb.proactive.benchmarks.timit.util.CoreTimersContainer; import org.objectweb.proactive.core.ProActiveException; import org.objectweb.proactive.core.ProActiveRuntimeException; import org.objectweb.proactive.core.UniqueID; import org.objectweb.proactive.core.body.ft.protocols.FTManager; import org.objectweb.proactive.core.body.future.Future; import org.objectweb.proactive.core.body.future.FuturePool; import org.objectweb.proactive.core.body.message.MessageEventProducerImpl; import org.objectweb.proactive.core.body.reply.Reply; import org.objectweb.proactive.core.body.reply.ReplyReceiver; import org.objectweb.proactive.core.body.request.BlockingRequestQueue; import org.objectweb.proactive.core.body.request.Request; import org.objectweb.proactive.core.body.request.RequestFactory; import org.objectweb.proactive.core.body.request.RequestImpl; import org.objectweb.proactive.core.body.request.RequestQueue; import org.objectweb.proactive.core.body.request.RequestReceiver; import org.objectweb.proactive.core.body.request.RequestReceiverImpl; import org.objectweb.proactive.core.body.request.ServeException; import org.objectweb.proactive.core.component.request.ComponentRequestImpl; import org.objectweb.proactive.core.config.ProActiveConfiguration; import org.objectweb.proactive.core.event.MessageEvent; import org.objectweb.proactive.core.event.MessageEventListener; import org.objectweb.proactive.core.exceptions.body.BodyNonFunctionalException; import org.objectweb.proactive.core.exceptions.body.SendReplyCommunicationException; import org.objectweb.proactive.core.exceptions.body.ServiceFailedCalleeNFE; import org.objectweb.proactive.core.exceptions.manager.NFEManager; import org.objectweb.proactive.core.exceptions.proxy.ProxyNonFunctionalException; import org.objectweb.proactive.core.exceptions.proxy.ServiceFailedCallerNFE; import org.objectweb.proactive.core.gc.GarbageCollector; import org.objectweb.proactive.core.jmx.notification.NotificationType; import org.objectweb.proactive.core.jmx.notification.RequestNotificationData; import org.objectweb.proactive.core.mop.MethodCall; import org.objectweb.proactive.core.security.exceptions.RenegotiateSessionException; import org.objectweb.proactive.core.util.profiling.Profiling; import org.objectweb.proactive.core.util.profiling.TimerWarehouse; /** * <i><font size="-1" color="#FF0000">**For internal use only** </font></i><br> * <p> * This class gives a common implementation of the Body interface. It provides all * the non specific behavior allowing sub-class to write the detail implementation. * </p><p> * Each body is identify by an unique identifier. * </p><p> * All active bodies that get created in one JVM register themselves into a table that allows * to tack them done. The registering and deregistering is done by the AbstractBody and * the table is managed here as well using some static methods. * </p><p> * In order to let somebody customize the body of an active object without subclassing it, * AbstractBody delegates lot of tasks to satellite objects that implements a given * interface. Abstract protected methods instantiate those objects allowing subclasses * to create them as they want (using customizable factories or instance). * </p> * * @author ProActive Team * @version 1.0, 2001/10/23 * @since ProActive 0.9 * @see org.objectweb.proactive.Body * @see UniqueID * */ public abstract class BodyImpl extends AbstractBody implements java.io.Serializable, BodyImplMBean { /** The component in charge of receiving reply */ protected ReplyReceiver replyReceiver; /** The component in charge of receiving request */ protected RequestReceiver requestReceiver; protected MessageEventProducerImpl messageEventProducer; // already checked methods private HashMap<String, HashSet<List<Class>>> checkedMethodNames; /** * Creates a new AbstractBody. * Used for serialization. */ public BodyImpl() { } /** * Creates a new AbstractBody for an active object attached to a given node. * @param reifiedObject the active object that body is for * @param nodeURL the URL of the node that body is attached to * @param factory the factory able to construct new factories for each type of meta objects * needed by this body */ public BodyImpl(Object reifiedObject, String nodeURL, MetaObjectFactory factory, String jobId) { super(reifiedObject, nodeURL, factory, jobId); // TIMING if (!CoreTimersContainer.checkReifiedObject(reifiedObject)) { final String timitActivationPropertyValue = CoreTimersContainer.checkNodeProperty(nodeURL); super.timersContainer = CoreTimersContainer.contructOnDemand(super.bodyID, factory, timitActivationPropertyValue); if (super.timersContainer != null) { TimerWarehouse.enableTimers(); // START TOTAL TIMER TimerWarehouse.startTimer(super.bodyID, TimerWarehouse.TOTAL); } } this.checkedMethodNames = new HashMap<String, HashSet<List<Class>>>(); this.requestReceiver = factory.newRequestReceiverFactory() .newRequestReceiver(); this.replyReceiver = factory.newReplyReceiverFactory().newReplyReceiver(); // ProActiveEvent this.messageEventProducer = new MessageEventProducerImpl(); // END ProActiveEvent setLocalBodyImpl(new ActiveLocalBodyStrategy(reifiedObject, factory.newRequestQueueFactory().newRequestQueue(bodyID), factory.newRequestFactory())); this.localBodyStrategy.getFuturePool().setOwnerBody(this); // FAULT TOLERANCE String ftstate = ProActiveConfiguration.getInstance().getFTState(); if ("enable".equals(ftstate)) { // if the object is a ProActive internal object, FT is disabled if (!(this.localBodyStrategy.getReifiedObject() instanceof ProActiveInternalObject)) { // if the object is not serilizable, FT is disabled if (this.localBodyStrategy.getReifiedObject() instanceof Serializable) { try { // create the fault tolerance manager int protocolSelector = FTManager.getProtoSelector(ProActiveConfiguration.getInstance() .getFTProtocol()); this.ftmanager = factory.newFTManagerFactory() .newFTManager(protocolSelector); this.ftmanager.init(this); if (bodyLogger.isDebugEnabled()) { bodyLogger.debug("Init FTManager on " + this.getNodeURL()); } } catch (ProActiveException e) { bodyLogger.error( "**ERROR** Unable to init FTManager. Fault-tolerance is disabled " + e); this.ftmanager = null; } } else { // target body is not serilizable bodyLogger.error( "**ERROR** Activated object is not serializable. Fault-tolerance is disabled"); this.ftmanager = null; } } } else { this.ftmanager = null; } this.gc = new GarbageCollector(this); } public void addMessageEventListener(MessageEventListener listener) { if (messageEventProducer != null) { messageEventProducer.addMessageEventListener(listener); } } public void removeMessageEventListener(MessageEventListener listener) { if (messageEventProducer != null) { messageEventProducer.removeMessageEventListener(listener); } } /** * Receives a request for later processing. The call to this method is non blocking * unless the body cannot temporary receive the request. * @param request the request to process * @exception java.io.IOException if the request cannot be accepted */ @Override protected int internalReceiveRequest(Request request) throws java.io.IOException, RenegotiateSessionException { // ProActiveEvent if (messageEventProducer != null) { messageEventProducer.notifyListeners(request, MessageEvent.REQUEST_RECEIVED, bodyID, getRequestQueue().size() + 1); } // END ProActiveEvent // JMX Notification if (this.mbean != null) { RequestNotificationData requestNotificationData = new RequestNotificationData(request.getSourceBodyID(), this.bodyID, request.getMethodName(), getRequestQueue().size() + 1); this.mbean.sendNotification(NotificationType.requestReceived, requestNotificationData); } // END JMX Notification // request queue length = number of requests in queue // + the one to add now return requestReceiver.receiveRequest(request, this); } /** * Receives a reply in response to a former request. * @param reply the reply received * @exception java.io.IOException if the reply cannot be accepted */ @Override protected int internalReceiveReply(Reply reply) throws java.io.IOException { // ProActiveEvent if (messageEventProducer != null) { messageEventProducer.notifyListeners(reply, MessageEvent.REPLY_RECEIVED, bodyID); } // END ProActiveEvent // JMX Notification if (this.mbean != null) { this.mbean.sendNotification(NotificationType.replyReceived); } // END JMX Notification return replyReceiver.receiveReply(reply, this, getFuturePool()); } /** * Signals that the activity of this body, managed by the active thread has just stopped. * @param completeACs if true, and if there are remaining AC in the futurepool, the AC thread * is not killed now; it will be killed after the sending of the last remaining AC. */ @Override protected void activityStopped(boolean completeACs) { super.activityStopped(completeACs); messageEventProducer = null; try { this.localBodyStrategy.getRequestQueue().destroy(); } catch (ProActiveRuntimeException e) { // this method can be called twos times if the automatic contunation thread // is killed *after* the activity thread. bodyLogger.debug("Terminating already terminated body " + this.getID()); } this.getFuturePool().terminateAC(completeACs); if (!completeACs) { setLocalBodyImpl(new InactiveLocalBodyStrategy()); } else { // the futurepool is still needed for remaining ACs setLocalBodyImpl(new InactiveLocalBodyStrategy(this.getFuturePool())); } } public boolean checkMethod(String methodName) { return checkMethod(methodName, null); } public void setImmediateService(String methodName) { // TODO uncomment this code after the getComponentParameters immediate service issue has been resolved // if (!checkMethod(methodName)) { // throw new NoSuchMethodError(methodName + " is not defined in " + // getReifiedObject().getClass().getName()); ((RequestReceiverImpl) this.requestReceiver).setImmediateService(methodName); } public void setImmediateService(String methodName, Class[] parametersTypes) { // TODO uncomment this code after the getComponentParameters immediate service issue has been resolved // if (!checkMethod(methodName, parametersTypes)) { // String signature = methodName+"("; // for (int i = 0 ; i < parametersTypes.length; i++) { // signature+=parametersTypes[i] + ((i < parametersTypes.length - 1)?",":""); // signature += " is not defined in " + // getReifiedObject().getClass().getName(); // throw new NoSuchMethodError(signature); ((RequestReceiverImpl) this.requestReceiver).setImmediateService(methodName, parametersTypes); } public void removeImmediateService(String methodName) { ((RequestReceiverImpl) this.requestReceiver).removeImmediateService(methodName); } public void removeImmediateService(String methodName, Class[] parametersTypes) { ((RequestReceiverImpl) this.requestReceiver).removeImmediateService(methodName, parametersTypes); } public void updateNodeURL(String newNodeURL) { this.nodeURL = newNodeURL; } @Override public boolean isInImmediateService() throws IOException { return this.requestReceiver.isInImmediateService(); } public boolean checkMethod(String methodName, Class[] parametersTypes) { if (this.checkedMethodNames.containsKey(methodName)) { if (parametersTypes != null) { // the method name with the right signature has already been checked List<Class> parameterTlist = Arrays.asList(parametersTypes); HashSet<List<Class>> signatures = this.checkedMethodNames.get(methodName); if (signatures.contains(parameterTlist)) { return true; } } else { // the method name has already been checked return true; } } // check if the method is defined as public Class reifiedClass = getReifiedObject().getClass(); boolean exists = org.objectweb.proactive.core.mop.Utils.checkMethodExistence(reifiedClass, methodName, parametersTypes); if (exists) { storeInMethodCache(methodName, parametersTypes); return true; } return false; } /** * Stores the given method name with the given parameters types inside our method signature cache to avoid re-testing them * @param methodName name of the method * @param parametersTypes parameter type list */ private void storeInMethodCache(String methodName, Class[] parametersTypes) { List<Class> parameterTlist = null; if (parametersTypes != null) { parameterTlist = Arrays.asList(parametersTypes); } // if we already know a version of this method, we store the new version in the existing set if (this.checkedMethodNames.containsKey(methodName) && (parameterTlist != null)) { HashSet<List<Class>> signatures = this.checkedMethodNames.get(methodName); signatures.add(parameterTlist); } // otherwise, we create a set containing a single element else { HashSet<List<Class>> signatures = new HashSet<List<Class>>(); if (parameterTlist != null) { signatures.add(parameterTlist); } checkedMethodNames.put(methodName, signatures); } } private class ActiveLocalBodyStrategy implements LocalBodyStrategy, java.io.Serializable { /** A pool future that contains the pending future objects */ protected FuturePool futures; /** The reified object target of the request processed by this body */ protected Object reifiedObject; protected BlockingRequestQueue requestQueue; protected RequestFactory internalRequestFactory; private long absoluteSequenceID; public ActiveLocalBodyStrategy(Object reifiedObject, BlockingRequestQueue requestQueue, RequestFactory requestFactory) { this.reifiedObject = reifiedObject; this.futures = new FuturePool(); this.requestQueue = requestQueue; this.internalRequestFactory = requestFactory; } public FuturePool getFuturePool() { return futures; } public BlockingRequestQueue getRequestQueue() { return requestQueue; } public Object getReifiedObject() { return reifiedObject; } public String getName() { return reifiedObject.getClass().getName(); } /** Serves the request. The request should be removed from the request queue * before serving, which is correctly done by all methods of the Service class. * However, this condition is not ensured for custom calls on serve. */ public void serve(Request request) { if (Profiling.TIMERS_COMPILED) { TimerWarehouse.startTimer(bodyID, TimerWarehouse.SERVE); // TimerWarehouse.startTimerWithInfos(bodyID, TimerWarehouse.SERVE, request.getMethodName()); } // push the new context LocalBodyStore.getInstance() .pushContext(new Context(BodyImpl.this, request)); serveInternal(request); LocalBodyStore.getInstance().popContext(); if (Profiling.TIMERS_COMPILED) { TimerWarehouse.stopTimer(bodyID, TimerWarehouse.SERVE); //TimerWarehouse.stopTimerWithInfos(bodyID, TimerWarehouse.SERVE, request.getMethodName()); } } private void serveInternal(Request request) { if (request == null) { return; } try { // ProActiveEvent messageEventProducer.notifyListeners(request, MessageEvent.SERVING_STARTED, bodyID, getRequestQueue().size()); // END ProActiveEvent // JMX Notification if (mbean != null) { mbean.sendNotification(NotificationType.servingStarted, new Integer(getRequestQueue().size())); } // END JMX Notification Reply reply = null; try { //If the request is not a "terminate Active Object" request, //it is served normally. if (!isTerminateAORequest(request)) { reply = request.serve(BodyImpl.this); } } catch (ServeException e) { // Create a non functional exception encapsulating the service exception BodyNonFunctionalException calleeNFE = new ServiceFailedCalleeNFE( "Exception occured while serving pending request = " + request.getMethodName(), e, this, ProActive.getBodyOnThis()); NFEManager.fireNFE(calleeNFE, BodyImpl.this); // Create a non functional exception encapsulating the service exception ProxyNonFunctionalException callerNFE = new ServiceFailedCallerNFE( "Exception occured while serving pending request = " + request.getMethodName(), e); // Create a new reply that contains this NFE instead of the result Reply replyAlternate = null; replyAlternate = request.serveAlternate(BodyImpl.this, callerNFE); // Send reply and stop local node if desired if (replyAlternate == null) { if (!isActive()) { return; //test if active in case of terminate() method otherwise eventProducer would be null } // ProActiveEvent messageEventProducer.notifyListeners(request, MessageEvent.VOID_REQUEST_SERVED, bodyID, getRequestQueue().size()); // END ProActiveEvent // JMX Notification if (mbean != null) { mbean.sendNotification(NotificationType.voidRequestServed, new Integer(getRequestQueue().size())); } // END JMX Notification return; } if (Profiling.TIMERS_COMPILED) { TimerWarehouse.startTimer(bodyID, TimerWarehouse.SEND_REPLY); } // ProActiveEvent UniqueID destinationBodyId = request.getSourceBodyID(); if ((destinationBodyId != null) && (messageEventProducer != null)) { messageEventProducer.notifyListeners(reply, MessageEvent.REPLY_SENT, destinationBodyId, getRequestQueue().size()); } // END ProActiveEvent // JMX Notification if (mbean != null) { mbean.sendNotification(NotificationType.replySent, new Integer(getRequestQueue().size())); } // END JMX Notification ArrayList<UniversalBody> destinations = new ArrayList<UniversalBody>(); destinations.add(request.getSender()); this.getFuturePool().registerDestinations(destinations); // FAULT-TOLERANCE if (BodyImpl.this.ftmanager != null) { BodyImpl.this.ftmanager.sendReply(replyAlternate, request.getSender()); } else { replyAlternate.send(request.getSender()); } if (Profiling.TIMERS_COMPILED) { TimerWarehouse.stopTimer(bodyID, TimerWarehouse.SEND_REPLY); } this.getFuturePool().removeDestinations(); return; } if (reply == null) { if (!isActive()) { return; //test if active in case of terminate() method otherwise eventProducer would be null } // ProActiveEvent if (messageEventProducer != null) { messageEventProducer.notifyListeners(request, MessageEvent.VOID_REQUEST_SERVED, bodyID, getRequestQueue().size()); } // END ProActiveEvent // JMX Notification if (mbean != null) { mbean.sendNotification(NotificationType.voidRequestServed, new Integer(getRequestQueue().size())); } // END JMX Notification return; } if (Profiling.TIMERS_COMPILED) { TimerWarehouse.startTimer(bodyID, TimerWarehouse.SEND_REPLY); } // ProActiveEvent UniqueID destinationBodyId = request.getSourceBodyID(); if ((destinationBodyId != null) && (messageEventProducer != null)) { messageEventProducer.notifyListeners(reply, MessageEvent.REPLY_SENT, destinationBodyId, getRequestQueue().size()); } // END ProActiveEvent // JMX Notification if (mbean != null) { mbean.sendNotification(NotificationType.replySent, new Integer(getRequestQueue().size())); } // END JMX Notification ArrayList<UniversalBody> destinations = new ArrayList<UniversalBody>(); destinations.add(request.getSender()); this.getFuturePool().registerDestinations(destinations); // FAULT-TOLERANCE if (BodyImpl.this.ftmanager != null) { BodyImpl.this.ftmanager.sendReply(reply, request.getSender()); } else { reply.send(request.getSender()); } if (Profiling.TIMERS_COMPILED) { TimerWarehouse.stopTimer(bodyID, TimerWarehouse.SEND_REPLY); } this.getFuturePool().removeDestinations(); } catch (java.io.IOException e) { // Create a non functional exception encapsulating the network exception BodyNonFunctionalException nfe = new SendReplyCommunicationException( "Exception occured in while sending reply to request = " + request.getMethodName(), e, BodyImpl.this, request.getSourceBodyID()); NFEManager.fireNFE(nfe, BodyImpl.this); } } public void sendRequest(MethodCall methodCall, Future future, UniversalBody destinationBody) throws java.io.IOException, RenegotiateSessionException { long sequenceID = getNextSequenceID(); Request request = internalRequestFactory.newRequest(methodCall, BodyImpl.this, future == null, sequenceID); // COMPONENTS : generate ComponentRequest for component messages if (methodCall.getComponentMetadata() != null) { request = new ComponentRequestImpl((RequestImpl) request); } if (future != null) { future.setID(sequenceID); futures.receiveFuture(future); } // ProActiveEvent messageEventProducer.notifyListeners(request, MessageEvent.REQUEST_SENT, destinationBody.getID()); // END ProActiveEvent // JMX Notification if (mbean != null) { mbean.sendNotification(NotificationType.requestSent); } // END JMX Notification // FAULT TOLERANCE if (BodyImpl.this.ftmanager != null) { BodyImpl.this.ftmanager.sendRequest(request, destinationBody); } else { request.send(destinationBody); } } /** * Returns a unique identifier that can be used to tag a future, a request * @return a unique identifier that can be used to tag a future, a request. */ public synchronized long getNextSequenceID() { return bodyID.toString().hashCode() + ++absoluteSequenceID; } /** * Test if the MethodName of the request is "terminateAO" or "terminateAOImmediately". * If true, AbstractBody.terminate() is called * @param request The request to serve * @return true if the name of the method is "terminateAO" or "terminateAOImmediately". */ private boolean isTerminateAORequest(Request request) { boolean terminateRequest = (request.getMethodName()).startsWith( "_terminateAO"); if (terminateRequest) { terminate(); } return terminateRequest; } } // end inner class LocalBodyImpl private class InactiveLocalBodyStrategy implements LocalBodyStrategy, java.io.Serializable { // An inactive body strategy can have a futurepool if some ACs to do // remain after the termination of the active object private FuturePool futures; public InactiveLocalBodyStrategy() { } public InactiveLocalBodyStrategy(FuturePool remainingsACs) { this.futures = remainingsACs; } public FuturePool getFuturePool() { return this.futures; } public BlockingRequestQueue getRequestQueue() { throw new InactiveBodyException(); } public RequestQueue getHighPriorityRequestQueue() { throw new InactiveBodyException(); } public Object getReifiedObject() { throw new InactiveBodyException(); } public String getName() { return "inactive body"; } public void serve(Request request) { throw new InactiveBodyException(request.getMethodName()); } public void sendRequest(MethodCall methodCall, Future future, UniversalBody destinationBody) throws java.io.IOException { throw new InactiveBodyException(destinationBody.getNodeURL(), destinationBody.getID(), methodCall.getName()); } /* * @see org.objectweb.proactive.core.body.LocalBodyStrategy#getNextSequenceID() */ public long getNextSequenceID() { return 0; } } // end inner class LocalInactiveBody private class InactiveBodyException extends ProActiveRuntimeException { public InactiveBodyException() { super("Cannot perform this call because body " + BodyImpl.this.getID() + "is inactive"); } public InactiveBodyException(String nodeURL, UniqueID id, String remoteMethodCallName) { // TODO when the class of the remote reified object will be available through UniversalBody, add this info. super("Cannot send request \"" + remoteMethodCallName + "\" to Body \"" + id + "\" located at " + nodeURL + " because body " + BodyImpl.this.getID() + " is inactive"); } public InactiveBodyException(String localMethodName) { super("Cannot serve method \"" + localMethodName + "\" because body " + BodyImpl.this.getID() + " is inactive"); } } // end inner class InactiveBodyException }
package dr.inference.mcmc; import dr.inference.loggers.LogColumn; import dr.inference.loggers.Loggable; import dr.inference.loggers.Logger; import dr.inference.markovchain.MarkovChain; import dr.inference.markovchain.MarkovChainDelegate; import dr.inference.markovchain.MarkovChainListener; import dr.inference.model.Likelihood; import dr.inference.model.Model; import dr.inference.operators.*; import dr.inference.prior.Prior; import dr.util.Identifiable; import dr.util.NumberFormatter; import dr.xml.Spawnable; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; /** * An MCMC analysis that estimates parameters of a probabilistic model. * * @author Alexei Drummond * @author Andrew Rambaut * @version $Id: MCMC.java,v 1.41 2005/07/11 14:06:25 rambaut Exp $ */ public class MCMC implements Identifiable, Spawnable, Loggable { public final static String LOAD_DUMP_FILE = "load.dump.file"; public final static String SAVE_DUMP_FILE = "save.dump.file"; public final static String DUMP_STATE = "dump.state"; public final static String DUMP_EVERY = "dump.every"; // Experimental public final static boolean TEST_CLONING = false; // additional boolean to continue analysis after data has been added or removed public final static boolean ALTERED_DATA = false; public MCMC(String id) { this.id = id; } /** * Must be called before calling chain. * * @param options the options for this MCMC analysis * @param schedule operator schedule to be used in chain. * @param likelihood the likelihood for this MCMC * @param loggers an array of loggers to record output of this MCMC run */ public void init( MCMCOptions options, Likelihood likelihood, OperatorSchedule schedule, Logger[] loggers) { init(options, likelihood, Prior.UNIFORM_PRIOR, schedule, loggers, new MarkovChainDelegate[0]); } /** * Must be called before calling chain. * * @param options the options for this MCMC analysis * @param schedule operator schedule to be used in chain. * @param likelihood the likelihood for this MCMC * @param loggers an array of loggers to record output of this MCMC run * @param delegates an array of delegates to handle tasks related to the MCMC */ public void init( MCMCOptions options, Likelihood likelihood, OperatorSchedule schedule, Logger[] loggers, MarkovChainDelegate[] delegates) { init(options, likelihood, Prior.UNIFORM_PRIOR, schedule, loggers, delegates); } /** * Must be called before calling chain. * * @param options the options for this MCMC analysis * @param prior the prior disitrbution on the model parameters. * @param schedule operator schedule to be used in chain. * @param likelihood the likelihood for this MCMC * @param loggers an array of loggers to record output of this MCMC run */ public void init( MCMCOptions options, Likelihood likelihood, Prior prior, OperatorSchedule schedule, Logger[] loggers) { init(options, likelihood, prior, schedule, loggers, new MarkovChainDelegate[0]); } /** * Must be called before calling chain. * * @param options the options for this MCMC analysis * @param prior the prior disitrbution on the model parameters. * @param schedule operator schedule to be used in chain. * @param likelihood the likelihood for this MCMC * @param loggers an array of loggers to record output of this MCMC run * @param delegates an array of delegates to handle tasks related to the MCMC */ public void init( MCMCOptions options, Likelihood likelihood, Prior prior, OperatorSchedule schedule, Logger[] loggers, MarkovChainDelegate[] delegates) { MCMCCriterion criterion = new MCMCCriterion(); criterion.setTemperature(options.getTemperature()); mc = new MarkovChain(prior, likelihood, schedule, criterion, options.getFullEvaluationCount(), options.minOperatorCountForFullEvaluation(), options.getEvaluationTestThreshold(), options.useCoercion()); this.options = options; this.loggers = loggers; this.schedule = schedule; //initialize transients currentState = 0; for(MarkovChainDelegate delegate : delegates) { delegate.setup(options, schedule, mc); } this.delegates = delegates; dumpStateFile = System.getProperty(LOAD_DUMP_FILE); String fileName = System.getProperty(SAVE_DUMP_FILE, null); if (System.getProperty(DUMP_STATE) != null) { long debugWriteState = Long.parseLong(System.getProperty(DUMP_STATE)); mc.addMarkovChainListener(new DebugChainListener(this, debugWriteState, false, fileName)); } if (System.getProperty(DUMP_EVERY) != null) { long debugWriteEvery = Long.parseLong(System.getProperty(DUMP_EVERY)); mc.addMarkovChainListener(new DebugChainListener(this, debugWriteEvery, true, fileName)); } } /** * Must be called before calling chain. * * @param chainlength chain length * @param likelihood the likelihood for this MCMC * @param operators an array of MCMC operators * @param loggers an array of loggers to record output of this MCMC run */ public void init(long chainlength, Likelihood likelihood, MCMCOperator[] operators, Logger[] loggers) { MCMCOptions options = new MCMCOptions(chainlength); MCMCCriterion criterion = new MCMCCriterion(); criterion.setTemperature(1); OperatorSchedule schedule = new SimpleOperatorSchedule(); for (MCMCOperator operator : operators) schedule.addOperator(operator); init(options, likelihood, Prior.UNIFORM_PRIOR, schedule, loggers); } public MarkovChain getMarkovChain() { return mc; } public Logger[] getLoggers() { return loggers; } public MCMCOptions getOptions() { return options; } public OperatorSchedule getOperatorSchedule() { return schedule; } public void run() { chain(); } /** * This method actually initiates the MCMC analysis. */ public void chain() { stopping = false; currentState = 0; timer.start(); if (loggers != null) { for (Logger logger : loggers) { logger.startLogging(); } } if (!stopping) { long loadedState = 0; if (dumpStateFile != null) { double[] savedLnL = new double[1]; loadedState = DebugUtils.readStateFromFile(new File(dumpStateFile), getOperatorSchedule(), savedLnL); mc.setCurrentLength(loadedState); double lnL = mc.evaluate(); mc.getLikelihood().makeDirty(); DebugUtils.writeStateToFile(new File("tmp.dump"), loadedState, lnL, getOperatorSchedule()); //first perform a simple check for equality of two doubles //when this test fails, go over the digits if (lnL != savedLnL[0]) { //15 is the floor value for the number of decimal digits when representing a double //checking for 15 identical digits below String originalString = Double.toString(savedLnL[0]); String restoredString = Double.toString(lnL); System.out.println(lnL + " " + originalString); System.out.println(savedLnL[0] + " " + restoredString); //assume values will be nearly identical int digits = 0; for (int i = 0; i < Math.max(originalString.length(), restoredString.length()); i++) { if (originalString.charAt(i) == restoredString.charAt(i)) { if (!(originalString.charAt(i) == '-' || originalString.charAt(i) == '.')) { digits++; } } else { break; } } //System.err.println("digits = " + digits); if (digits < 15 && !ALTERED_DATA) { throw new RuntimeException("Dumped lnL does not match loaded state: stored lnL: " + savedLnL[0] + ", recomputed lnL: " + lnL + " (difference " + (savedLnL[0] - lnL) + ")"); } } else { System.out.println("IDENTICAL LIKELIHOODS"); System.out.println("lnL" + " = " + lnL); System.out.println("savedLnL[0]" + " = " + savedLnL[0]); } // for (Likelihood likelihood : Likelihood.CONNECTED_LIKELIHOOD_SET) { // System.err.println(likelihood.getId() + ": " + likelihood.getLogLikelihood()); } mc.addMarkovChainListener(chainListener); for(MarkovChainDelegate delegate : delegates) { mc.addMarkovChainDelegate(delegate); } long chainLength = getChainLength(); //this also potentially gets the new coercionDelay of a possibly increased chain length final long coercionDelay = getCoercionDelay(); //assume that dumped state has passed the coercionDelay //TODO: discuss whether we want to dump the coercionDelay or chainLength to file if (coercionDelay > loadedState) { mc.runChain(coercionDelay - loadedState, true); chainLength -= coercionDelay; } //if (coercionDelay > 0) { // Run the chain for coercionDelay steps with coercion disabled //mc.runChain(coercionDelay, true); //chainLength -= coercionDelay; // reset operator acceptance levels //GB: we are now restoring these; commenting out for now /*for (int i = 0; i < schedule.getOperatorCount(); i++) { schedule.getOperator(i).reset(); }*/ mc.runChain(chainLength, false); mc.terminateChain(); mc.removeMarkovChainListener(chainListener); for(MarkovChainDelegate delegate : delegates) { mc.removeMarkovChainDelegate(delegate); } } timer.stop(); } @Override public LogColumn[] getColumns() { return new LogColumn[] { new LogColumn() { @Override public void setLabel(String label) { } @Override public String getLabel() { return "time"; } @Override public void setMinimumWidth(int minimumWidth) { } @Override public int getMinimumWidth() { return 0; } @Override public String getFormatted() { return Double.toString(getTimer().toSeconds()); } } }; } private final MarkovChainListener chainListener = new MarkovChainListener() { // for receiving messages from subordinate MarkovChain /** * Called to update the current model keepEvery states. */ public void currentState(long state, Model currentModel) { currentState = state; if (loggers != null) { for (Logger logger : loggers) { logger.log(state); } } } /** * Called when a new new best posterior state is found. */ public void bestState(long state, Model bestModel) { currentState = state; } /** * cleans up when the chain finishes (possibly early). */ public void finished(long chainLength) { currentState = chainLength; if (loggers != null) { for (Logger logger : loggers) { logger.stopLogging(); } } // OperatorAnalysisPrinter class can do the job now if (showOperatorAnalysis) { showOperatorAnalysis(System.out); } if (operatorAnalysisFile != null) { try { PrintStream out = new PrintStream(new FileOutputStream(operatorAnalysisFile)); showOperatorAnalysis(out); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } // How should premature finish be flagged? } }; /** * Writes ano operator analysis to the provided print stream * * @param out the print stream to write operator analysis to */ private void showOperatorAnalysis(PrintStream out) { out.println(); out.println("Operator analysis"); out.println(formatter.formatToFieldWidth("Operator", 50) + formatter.formatToFieldWidth("Tuning", 9) + formatter.formatToFieldWidth("Count", 11) + formatter.formatToFieldWidth("Time", 9) + formatter.formatToFieldWidth("Time/Op", 9) + formatter.formatToFieldWidth("Pr(accept)", 11) + (options.useCoercion() ? "" : " Performance suggestion")); for (int i = 0; i < schedule.getOperatorCount(); i++) { final MCMCOperator op = schedule.getOperator(i); if (op instanceof JointOperator) { JointOperator jointOp = (JointOperator) op; for (int k = 0; k < jointOp.getNumberOfSubOperators(); k++) { out.println(formattedOperatorName(jointOp.getSubOperatorName(k)) + formattedParameterString(jointOp.getSubOperator(k)) + formattedCountString(op) + formattedTimeString(op) + formattedTimePerOpString(op) + formattedProbString(jointOp) + (options.useCoercion() ? "" : formattedDiagnostics(jointOp, MCMCOperator.Utils.getAcceptanceProbability(jointOp))) ); } } else { out.println(formattedOperatorName(op.getOperatorName()) + formattedParameterString(op) + formattedCountString(op) + formattedTimeString(op) + formattedTimePerOpString(op) + formattedProbString(op) + (options.useCoercion() ? "" : formattedDiagnostics(op, MCMCOperator.Utils.getAcceptanceProbability(op))) ); } } out.println(); } private String formattedOperatorName(String operatorName) { return formatter.formatToFieldWidth(operatorName, 50); } private String formattedParameterString(MCMCOperator op) { String pString = " "; if (op instanceof CoercableMCMCOperator && ((CoercableMCMCOperator) op).getMode() != CoercionMode.COERCION_OFF) { pString = formatter.formatToFieldWidth(formatter.formatDecimal(((CoercableMCMCOperator) op).getRawParameter(), 3), 8); } return pString; } private String formattedCountString(MCMCOperator op) { final int count = op.getCount(); return formatter.formatToFieldWidth(Integer.toString(count), 10) + " "; } private String formattedTimeString(MCMCOperator op) { final long time = op.getTotalEvaluationTime(); return formatter.formatToFieldWidth(Long.toString(time), 8) + " "; } private String formattedTimePerOpString(MCMCOperator op) { final double time = op.getMeanEvaluationTime(); return formatter.formatToFieldWidth(formatter.formatDecimal(time, 2), 8) + " "; } private String formattedProbString(MCMCOperator op) { final double acceptanceProb = MCMCOperator.Utils.getAcceptanceProbability(op); return formatter.formatToFieldWidth(formatter.formatDecimal(acceptanceProb, 4), 11) + " "; } private String formattedDiagnostics(MCMCOperator op, double acceptanceProb) { String message = "good"; if (acceptanceProb < op.getMinimumGoodAcceptanceLevel()) { if (acceptanceProb < (op.getMinimumAcceptanceLevel() / 10.0)) { message = "very low"; } else if (acceptanceProb < op.getMinimumAcceptanceLevel()) { message = "low"; } else message = "slightly low"; } else if (acceptanceProb > op.getMaximumGoodAcceptanceLevel()) { double reallyHigh = 1.0 - ((1.0 - op.getMaximumAcceptanceLevel()) / 10.0); if (acceptanceProb > reallyHigh) { message = "very high"; } else if (acceptanceProb > op.getMaximumAcceptanceLevel()) { message = "high"; } else message = "slightly high"; } String performacsMsg; if (op instanceof GibbsOperator) { performacsMsg = "none (Gibbs operator)"; } else { final String suggestion = op.getPerformanceSuggestion(); performacsMsg = message + "\t" + suggestion; } return performacsMsg; } /** * @return the prior of this MCMC analysis. */ public Prior getPrior() { return mc.getPrior(); } /** * @return the likelihood function. */ public Likelihood getLikelihood() { return mc.getLikelihood(); } /** * @return the timer. */ public dr.util.Timer getTimer() { return timer; } /** * @return the length of this analysis. */ public final long getChainLength() { return options.getChainLength(); } /** * @return the current state of the MCMC analysis. */ public final long getCurrentState() { return currentState; } /** * @return the progress (0 to 1) of the MCMC analysis. */ public final double getProgress() { return (double) currentState / (double) options.getChainLength(); } /** * @return true if this MCMC is currently adapting the operators. */ public final boolean isAdapting() { return isAdapting; } /** * Requests that the MCMC chain stop prematurely. */ public void pleaseStop() { stopping = true; mc.pleaseStop(); } /** * @return true if Markov chain is stopped */ public boolean isStopped() { return mc.isStopped(); } public boolean getSpawnable() { return spawnable; } private boolean spawnable = true; public void setSpawnable(boolean spawnable) { this.spawnable = spawnable; } protected long getCoercionDelay() { long delay = options.getCoercionDelay(); if (delay < 0) { delay = (long)(options.getChainLength() / 100); } if (options.useCoercion()) return delay; for (int i = 0; i < schedule.getOperatorCount(); i++) { MCMCOperator op = schedule.getOperator(i); if (op instanceof CoercableMCMCOperator) { if (((CoercableMCMCOperator) op).getMode() == CoercionMode.COERCION_ON) return delay; } } return -1; } public void setShowOperatorAnalysis(boolean soa) { showOperatorAnalysis = soa; } public void setOperatorAnalysisFile(File operatorAnalysisFile) { this.operatorAnalysisFile = operatorAnalysisFile; } public String getId() { return id; } public void setId(String id) { this.id = id; } // PRIVATE TRANSIENTS private String dumpStateFile = null; //private FileLogger operatorLogger = null; protected final boolean isAdapting = true; protected boolean stopping = false; protected boolean showOperatorAnalysis = true; protected File operatorAnalysisFile = null; protected final dr.util.Timer timer = new dr.util.Timer(); protected long currentState = 0; //private int stepsPerReport = 1000; protected final NumberFormatter formatter = new NumberFormatter(8); /** * this markov chain does most of the work. */ protected MarkovChain mc; /** * the options of this MCMC analysis */ protected MCMCOptions options; protected Logger[] loggers; protected OperatorSchedule schedule; private MarkovChainDelegate[] delegates; private String id = null; }
package org.jasig.portal.container.om.common; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import org.apache.pluto.om.common.ObjectID; /** * Wraps around the internal Object IDs. By holding both * the string and the integer version of an Object ID this class * helps speed up the internal processing. Code copied from Apache Pluto. * @author Ken Weiner, kweiner@unicon.net * @version $Revision$ */ public class ObjectIDImpl implements ObjectID, Serializable { private String stringOID = null; private int intOID; private ObjectIDImpl(int oid) { stringOID = String.valueOf(oid); intOID = oid; } private ObjectIDImpl(int oid, String stringOID) { this.stringOID = stringOID; intOID = oid; } // Addtional methods public boolean equals(Object object) { boolean result = false; if (object instanceof ObjectID) result = (intOID == ((ObjectIDImpl)object).intOID); else if (object instanceof String) result = stringOID.equals(object); else if (object instanceof Integer) result = (intOID == ((Integer)object).intValue()); return result; } public int hashCode() { return intOID; } public String toString() { return stringOID; } public int intValue() { return intOID; } static public ObjectID createFromString(String idStr) { char[] id = idStr.toCharArray(); int _id = 1; for (int i = 0; i < id.length; i++) { if ((i % 2) == 0) _id *= id[i]; else _id ^= id[i]; _id = Math.abs(_id); } return new ObjectIDImpl(_id, idStr); } }
package org.jasig.portal.layout.channels; import java.util.Iterator; import java.util.Enumeration; import java.util.ArrayList; import java.util.Map; import java.util.Set; import java.util.HashMap; import org.jasig.portal.groups.IGroupMember; import org.jasig.portal.IServant; import org.jasig.portal.channels.groupsmanager.CGroupsManagerServantFactory; import org.jasig.portal.ChannelStaticData; import org.jasig.portal.ChannelRuntimeData; import org.jasig.portal.IPrivileged; import org.jasig.portal.services.GroupService; import org.jasig.portal.PortalControlStructures; import org.jasig.portal.PortalException; import org.jasig.portal.ThemeStylesheetUserPreferences; import org.jasig.portal.channels.BaseChannel; import org.jasig.portal.layout.ALFolder; import org.jasig.portal.layout.ALNode; import org.jasig.portal.layout.ALFragment; import org.jasig.portal.layout.IAggregatedUserLayoutManager; import org.jasig.portal.layout.ILayoutFragment; import org.jasig.portal.layout.IUserLayoutManager; import org.jasig.portal.layout.IUserLayoutNodeDescription; import org.jasig.portal.layout.TransientUserLayoutManagerWrapper; import org.jasig.portal.utils.CommonUtils; import org.jasig.portal.utils.DocumentFactory; import org.jasig.portal.utils.SAX2FilterImpl; import org.jasig.portal.utils.XSLT; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.Attributes; /** * A channel for adding new content to a layout. * @author Michael Ivanov, mvi@immagic.com * @version $Revision$ */ public class CFragmentManager extends BaseChannel implements IPrivileged { private static final String sslLocation = "/org/jasig/portal/channels/CFragmentManager/CFragmentManager.ssl"; private IAggregatedUserLayoutManager alm; private ThemeStylesheetUserPreferences themePrefs; private Map fragments; private boolean servantRender = false; private String servantFragmentId; private static Map servants = new HashMap(); private final static int MAX_SERVANTS = 50; public CFragmentManager() throws PortalException { super(); } private class ServantSAXFilter extends SAX2FilterImpl { public ServantSAXFilter(ContentHandler ch) throws PortalException { super(ch); } public void startElement (String uri, String localName, String qName, Attributes atts) throws SAXException { try { super.startElement(uri,localName,qName,atts); if(qName.equals("groupServant")) { if ( servantRender ) { getGroupServant().renderXML(contentHandler); } } } catch ( Exception e ) { throw new SAXException(e.toString()); } } } private synchronized IGroupMember[] getGroupMembers(String fragmentId) throws PortalException { Enumeration groupsEnum = alm.getPublishGroups(fragmentId); ArrayList groups = new ArrayList(); while ( groupsEnum.hasMoreElements() ) { String groupKey = (String) groupsEnum.nextElement(); IGroupMember member = GroupService.findGroup(groupKey); if ( member != null ) groups.add(member); } IGroupMember[] members = new IGroupMember[groups.size()]; for ( int i = 0; i < members.length; i++ ) { members[i] = (IGroupMember) groups.get(i); } return members; } private String getServantKey() { return CommonUtils.envl(servantFragmentId,"new"); } /** * Produces a group servant * @return the group servant */ private synchronized IServant getGroupServant() throws PortalException { if ( servants.size() > MAX_SERVANTS ) servants.clear(); IServant groupServant = (IServant) servants.get(getServantKey()); if ( groupServant == null ) { try { // create the appropriate servant if ( servantFragmentId != null && CommonUtils.parseInt(servantFragmentId) > 0 ) { groupServant = CGroupsManagerServantFactory.getGroupsServantforSelection(staticData, "Please select groups or people who should have access to this fragment:", GroupService.EVERYONE,true,true,getGroupMembers(servantFragmentId)); } else groupServant = CGroupsManagerServantFactory.getGroupsServantforSelection(staticData, "Please select groups or people who should have access to this fragment:", GroupService.EVERYONE); if ( groupServant != null ) servants.put(getServantKey(),groupServant); } catch (Exception e) { throw new PortalException(e); } } groupServant.setRuntimeData((ChannelRuntimeData)runtimeData.clone()); return groupServant; } private String createFolder( ALFragment fragment ) throws PortalException { IUserLayoutNodeDescription folderDesc = alm.createNodeDescription(IUserLayoutNodeDescription.FOLDER); folderDesc.setName("Fragment column"); return alm.addNode(folderDesc, getFragmentRootId(fragment.getId()), null).getId(); } private void analyzeParameters( XSLT xslt ) throws PortalException { String fragmentId = CommonUtils.nvl(runtimeData.getParameter("uPcFM_selectedID")); String action = CommonUtils.nvl(runtimeData.getParameter("uPcFM_action")); if (action.equals("save_new")) { String fragmentName = runtimeData.getParameter("fragment_name"); String funcName = runtimeData.getParameter("fragment_fname"); String fragmentDesc = runtimeData.getParameter("fragment_desc"); String fragmentType = runtimeData.getParameter("fragment_type"); String fragmentFolder = runtimeData.getParameter("fragment_add_folder"); boolean isPushedFragment = ("pushed".equals(fragmentType))?true:false; fragmentId = alm.createFragment(CommonUtils.nvl(funcName),CommonUtils.nvl(fragmentDesc),CommonUtils.nvl(fragmentName)); ALFragment newFragment = (ALFragment) alm.getFragment(fragmentId); if ( newFragment != null ) { if ( isPushedFragment ) newFragment.setPushedFragment(); else newFragment.setPulledFragment(); // Saving the changes in the database alm.saveFragment(newFragment); // Updating the fragments map fragments.put(fragmentId,newFragment); // Check if we need to create an additional folder on the fragment root if ( "true".equals(fragmentFolder) ) { alm.loadFragment(fragmentId); createFolder(newFragment); alm.saveFragment(); } } } else if (action.equals("save")) { String funcName = runtimeData.getParameter("fragment_fname"); String fragmentName = runtimeData.getParameter("fragment_name"); String fragmentDesc = runtimeData.getParameter("fragment_desc"); String fragmentType = runtimeData.getParameter("fragment_type"); boolean isPushedFragment = ("pushed".equals(fragmentType))?true:false; ALFragment fragment = (ALFragment) fragments.get(fragmentId); if ( fragment != null ) { if ( isPushedFragment ) fragment.setPushedFragment(); else fragment.setPulledFragment(); fragment.setFunctionalName(CommonUtils.nvl(funcName)); fragment.setDescription(CommonUtils.nvl(fragmentDesc)); String fragmentRootId = getFragmentRootId(fragmentId); ALNode fragmentRoot = fragment.getNode(fragmentRootId); fragmentRoot.getNodeDescription().setName(fragmentName); // Saving the changes in the database alm.saveFragment(fragment); } } else if (action.equals("delete")) { if (CommonUtils.parseInt(fragmentId) > 0) { alm.deleteFragment(fragmentId); // Updating the fragments map fragments.remove(fragmentId); fragmentId = (fragments != null && fragments.isEmpty())?(String) fragments.keySet().toArray()[0]:""; } else new PortalException ( "Invalid fragment ID="+fragmentId); } else if (action.equals("publish")) { servantRender = true; servantFragmentId = fragmentId; } else if (action.equals("publish_finish")) { IGroupMember[] gms = (IGroupMember[]) getGroupServant().getResults(); for ( int i = 0; i < gms.length; i++ ) System.out.println ( "group key: " + gms[i].getKey()); servantRender = false; } if ( getGroupServant().isFinished() ) { IGroupMember[] gms = (IGroupMember[]) getGroupServant().getResults(); if ( gms != null && "Done".equals(runtimeData.getParameter("grpCommand"))) alm.setPublishGroups(gms,servantFragmentId); servants.remove(getServantKey()); servantRender = false; } boolean noAction = action.equals(""); if ( servantRender && noAction ) { fragmentId = servantFragmentId; action = "publish"; } // Loading the default layout if the fragment is loaded in the theme if ( "default".equals(action) && alm.isFragmentLoaded() ) alm.loadUserLayout(); xslt.setStylesheetParameter("uPcFM_selectedID",fragmentId); xslt.setStylesheetParameter("uPcFM_action",action); } private String getFragmentRootId( String fragmentId ) throws PortalException { if ( fragments != null && !fragments.isEmpty() ) { ALFragment fragment = (ALFragment) fragments.get(fragmentId); ALFolder rootFolder = (ALFolder) fragment.getNode(fragment.getRootId()); return rootFolder.getFirstChildNodeId(); } return null; } /** * Passes portal control structure to the channel. * @see PortalControlStructures */ public void setPortalControlStructures(PortalControlStructures pcs) throws PortalException { IUserLayoutManager ulm = pcs.getUserPreferencesManager().getUserLayoutManager(); if (ulm instanceof TransientUserLayoutManagerWrapper) ulm = ((TransientUserLayoutManagerWrapper)ulm).getOriginalLayoutManager(); if (ulm instanceof IAggregatedUserLayoutManager) alm = (IAggregatedUserLayoutManager) ulm; themePrefs = pcs.getUserPreferencesManager().getUserPreferences().getThemeStylesheetUserPreferences(); // Refresh the fragment list refreshFragments(); } private Document getFragmentList() throws PortalException { Document document = DocumentFactory.getNewDocument(); Element fragmentsNode = document.createElement("fragments"); document.appendChild(fragmentsNode); //fragmentsNode.appendChild(getGroupsXML(document)); Element category = document.createElement("category"); category.setAttribute("name", "Fragments"); category.setAttribute("expanded", "true"); fragmentsNode.appendChild(category); boolean updateList = false; if (fragments != null) { for ( Iterator ids = fragments.keySet().iterator(); ids.hasNext(); ) { String fragmentId = (String) ids.next(); ALFragment fragment = (ALFragment) fragments.get(fragmentId); String fragmentRootId = getFragmentRootId(fragmentId); // if the fragment root ID is NULL then the fragment must be deleted // since it does not have any content if ( fragmentRootId == null ) { alm.deleteFragment(fragmentId); if ( !updateList ) updateList = true; continue; } Element fragmentNode = document.createElement("fragment"); category.appendChild(fragmentNode); Element id = document.createElement("ID"); id.appendChild(document.createTextNode(fragmentId)); fragmentNode.appendChild(id); Element rootId = document.createElement("rootNodeID"); rootId.appendChild(document.createTextNode(fragmentRootId)); rootId.setAttribute("immutable",fragment.getNode(fragmentRootId).getNodeDescription().isImmutable()?"Y":"N"); fragmentNode.appendChild(rootId); Element type = document.createElement("type"); type.appendChild( document.createTextNode( fragment.isPushedFragment() ? "pushed" : "pulled")); fragmentNode.appendChild(type); Element fname = document.createElement("fname"); fname.appendChild( document.createTextNode(fragment.getFunctionalName())); fragmentNode.appendChild(fname); Element name = document.createElement("name"); name.appendChild( document.createTextNode( fragmentRootId != null ? ((ALNode) fragment.getNode(fragmentRootId)).getNodeDescription().getName() : fragment.getFunctionalName())); fragmentNode.appendChild(name); Element desc = document.createElement("description"); desc.appendChild(document.createTextNode(fragment.getDescription())); fragmentNode.appendChild(desc); } // If there were any fragments withno rootID and these fragments were deleted - need to update the fragment list if ( updateList ) refreshFragments(); } //System.out.println ( org.jasig.portal.utils.XML.serializeNode(document)); return document; } public void setStaticData(ChannelStaticData sd) throws PortalException { staticData = sd; } public void setRuntimeData (ChannelRuntimeData rd) throws PortalException { runtimeData = rd; } public void refreshFragments() throws PortalException { Set fragmentIds = alm.getFragments(); fragments = new HashMap(); for (Iterator ids = fragmentIds.iterator(); ids.hasNext(); ) { String fragmentId = (String) ids.next(); ILayoutFragment layoutFragment = alm.getFragment(fragmentId); if (layoutFragment == null || !(layoutFragment instanceof ALFragment)) throw new PortalException("The fragment must be "+ALFragment.class.getName()+" type!"); fragments.put(fragmentId,layoutFragment); } } public void renderXML(ContentHandler out) throws PortalException { XSLT xslt = XSLT.getTransformer(this, runtimeData.getLocales()); analyzeParameters(xslt); xslt.setXML(getFragmentList()); xslt.setXSL(sslLocation,"fragmentManager",runtimeData.getBrowserInfo()); xslt.setTarget(new ServantSAXFilter(out)); xslt.setStylesheetParameter("baseActionURL",runtimeData.getBaseActionURL()); /*if ( servantRender ) { xslt.setStylesheetParameter("action", "selectGroupsButtons"); }*/ xslt.transform(); } }
package org.jfree.chart.labels; import java.io.Serializable; import java.text.DateFormat; import java.text.NumberFormat; import org.jfree.data.xy.XYDataset; import org.jfree.util.PublicCloneable; /** * A standard tool tip generator for use with an * {@link org.jfree.chart.renderer.xy.XYItemRenderer}. */ public class StandardXYToolTipGenerator extends AbstractXYItemLabelGenerator implements XYToolTipGenerator, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -3564164459039540784L; /** The default tooltip format. */ public static final String DEFAULT_TOOL_TIP_FORMAT = "{0}: ({1}, {2})"; /** * Returns a tool tip generator that formats the x-values as dates and the * y-values as numbers. * * @return A tool tip generator (never <code>null</code>). */ public static StandardXYToolTipGenerator getTimeSeriesInstance() { return new StandardXYToolTipGenerator(DEFAULT_TOOL_TIP_FORMAT, DateFormat.getInstance(), NumberFormat.getInstance()); } /** * Creates a tool tip generator using default number formatters. */ public StandardXYToolTipGenerator() { this(DEFAULT_TOOL_TIP_FORMAT, NumberFormat.getNumberInstance(), NumberFormat.getNumberInstance()); } /** * Creates a tool tip generator using the specified number formatters. * * @param formatString the item label format string (<code>null</code> not * permitted). * @param xFormat the format object for the x values (<code>null</code> * not permitted). * @param yFormat the format object for the y values (<code>null</code> * not permitted). */ public StandardXYToolTipGenerator(String formatString, NumberFormat xFormat, NumberFormat yFormat) { super(formatString, xFormat, yFormat); } /** * Creates a tool tip generator using the specified number formatters. * * @param formatString the label format string (<code>null</code> not * permitted). * @param xFormat the format object for the x values (<code>null</code> * not permitted). * @param yFormat the format object for the y values (<code>null</code> * not permitted). */ public StandardXYToolTipGenerator(String formatString, DateFormat xFormat, NumberFormat yFormat) { super(formatString, xFormat, yFormat); } /** * Creates a tool tip generator using the specified formatters (a * number formatter for the x-values and a date formatter for the * y-values). * * @param formatString the item label format string (<code>null</code> * not permitted). * @param xFormat the format object for the x values (<code>null</code> * permitted). * @param yFormat the format object for the y values (<code>null</code> * not permitted). * * @since 1.0.4 */ public StandardXYToolTipGenerator(String formatString, NumberFormat xFormat, DateFormat yFormat) { super(formatString, xFormat, yFormat); } /** * Creates a tool tip generator using the specified date formatters. * * @param formatString the label format string (<code>null</code> not * permitted). * @param xFormat the format object for the x values (<code>null</code> * not permitted). * @param yFormat the format object for the y values (<code>null</code> * not permitted). */ public StandardXYToolTipGenerator(String formatString, DateFormat xFormat, DateFormat yFormat) { super(formatString, xFormat, yFormat); } /** * Generates the tool tip text for an item in a dataset. * * @param dataset the dataset (<code>null</code> not permitted). * @param series the series index (zero-based). * @param item the item index (zero-based). * * @return The tooltip text (possibly <code>null</code>). */ public String generateToolTip(XYDataset dataset, int series, int item) { return generateLabelString(dataset, series, item); } /** * Tests this object for equality with an arbitrary object. * * @param obj the other object (<code>null</code> permitted). * * @return A boolean. */ public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof StandardXYToolTipGenerator)) { return false; } return super.equals(obj); } /** * Returns an independent copy of the generator. * * @return A clone. * * @throws CloneNotSupportedException if cloning is not supported. */ public Object clone() throws CloneNotSupportedException { return super.clone(); } }
package com.jediterm.terminal.emulator; import com.google.common.base.Ascii; import com.jediterm.terminal.*; import com.jediterm.terminal.display.StyleState; import org.apache.log4j.Logger; import java.awt.*; import java.io.IOException; import java.util.Arrays; /** * Obtains data from the {@link com.jediterm.terminal.TerminalDataStream}, interprets terminal ANSI escape sequences as commands and directs them * as well as plain data characters to the {@link com.jediterm.terminal.Terminal} * * @author traff */ public class JediEmulator extends DataStreamIteratingEmulator { private static final Logger LOG = Logger.getLogger(JediEmulator.class); /* * Character Attributes * * ESC [ Ps;Ps;Ps;...;Ps m * * Ps refers to a selective parameter. Multiple parameters are separated by * the semicolon character (0738). The parameters are executed in order and * have the following meanings: 0 or None All Attributes Off 1 Bold on 4 * Underscore on 5 Blink on 7 Reverse video on * * Any other parameter values are ignored. */ private final TerminalOutputStream myOutputStream; public JediEmulator(TerminalDataStream dataStream, TerminalOutputStream outputStream, Terminal terminal) { super(dataStream, terminal); myOutputStream = outputStream; } @Override public void processChar(char ch, Terminal terminal) throws IOException { switch (ch) { case 0: break; case Ascii.BEL: //Bell (Ctrl-G) terminal.beep(); break; case Ascii.BS: //Backspace (Ctrl-H) terminal.backspace(); break; case Ascii.CR: //Carriage return (Ctrl-M) terminal.carriageReturn(); break; case Ascii.ENQ: //Return terminal status (Ctrl-E). Default response is an empty string unsupported("Terminal status:" + escapeSequenceToString(ch)); break; case Ascii.FF: //Form Feed or New Page (NP). Ctrl-L treated the same as LF case Ascii.LF: //Line Feed or New Line (NL). (LF is Ctrl-J) case Ascii.VT: //Vertical TAb (Ctrl-K). This is treated the sane as LF. terminal.newLine(); break; case Ascii.SI: //Shift In (Ctrl-O) -> Switch to Standard Character Set. This invokes the G0 character set (the default) terminal.invokeCharacterSet(0); break; case Ascii.SO: //Shift Out (Ctrl-N) -> Switch to Alternate Character Set. This invokes the G1 character set (the default) terminal.invokeCharacterSet(1); break; case Ascii.HT: // Horizontal Tab (HT) (Ctrl-I) terminal.horizontalTab(); break; case CharacterUtils.ESC: // ESC processEscapeSequence(myDataStream.getChar(), myTerminal); break; default: if (ch <= CharacterUtils.US) { StringBuilder sb = new StringBuilder("Unhandled control character:"); CharacterUtils.appendChar(sb, CharacterUtils.CharacterType.NONE, ch); LOG.error(sb.toString()); } else { // Plain characters myDataStream.pushChar(ch); String nonControlCharacters = myDataStream.readNonControlCharacters(terminal.distanceToLineEnd()); terminal.writeCharacters(nonControlCharacters); } break; } } private void processEscapeSequence(char ch, Terminal terminal) throws IOException { switch (ch) { case '[': // Control Sequence Introducer (CSI) final ControlSequence args = new ControlSequence(myDataStream); if (LOG.isDebugEnabled()) { LOG.debug(args.appendTo("Control sequence\nparsed :")); } if (!args.pushBackReordered(myDataStream)) { boolean result = processControlSequence(args); if (!result) { StringBuilder sb = new StringBuilder(); sb.append("Unhandled Control sequence\n"); sb.append("parsed :"); args.appendToBuffer(sb); sb.append('\n'); sb.append("bytes read :ESC["); LOG.error(sb.toString()); } } break; case 'D': // Index (IND) terminal.index(); break; case 'E': // Next Line (NEL) terminal.nextLine(); break; case 'H': unsupported("Horizontal Tab Set (HTS)"); break; case 'M': // Reverse Index (RI) terminal.reverseIndex(); break; case 'N': terminal.singleShiftSelect(2); //Single Shift Select of G2 Character Set (SS2). This affects next character only. break; case 'O': terminal.singleShiftSelect(3); //Single Shift Select of G3 Character Set (SS3). This affects next character only. break; case ']': // Operating System Command (OSC) // xterm uses it to set parameters like windows title final SystemCommandSequence command = new SystemCommandSequence(myDataStream); if (!operatingSystemCommand(command)) { LOG.error("Error processing OSC " + command.getSequenceString()); } case '6': unsupported("Back Index (DECBI), VT420 and up"); break; case '7': //Save Cursor (DECSC) terminal.storeCursor(); break; case '8': terminal.restoreCursor(); break; case '9': unsupported("Forward Index (DECFI), VT420 and up"); break; case '=': unsupported("Application Keypad (DECKPAM)"); break; case '>': unsupported("Normal Keypad (DECKPNM)"); break; case 'F': unsupported("Cursor to lower left corner of the screen"); break; case 'c': //Full Reset (RIS) terminal.reset(); break; case 'l': case 'm': case 'n': case 'o': case '|': case '}': case '~': unsupported(escapeSequenceToString(ch)); break; case ' case '(': case ')': case '*': case '+': case '$': case '@': case '%': case '.': case '/': case ' ': processTwoCharSequence(ch, terminal); break; default: unsupported(ch); } } private boolean operatingSystemCommand(SystemCommandSequence args) { Integer i = args.getIntAt(0); if (i != null) { switch (i) { case 0: //Icon name/title case 2: //Title String name = args.getStringAt(1); if (name != null) { myTerminal.setWindowTitle(name); return true; } } } return false; } private void processTwoCharSequence(char ch, Terminal terminal) throws IOException { char secondCh = myDataStream.getChar(); switch (ch) { case ' ': switch (secondCh) { case 'F': //7-bit controls unsupported("Switching ot 7-bit"); break; case 'G': //8-bit controls unsupported("Switching ot 8-bit"); break; case 'L': //Set ANSI conformance level 1 case 'M': //Set ANSI conformance level 2 case 'N': //Set ANSI conformance level 3 unsupported("Settings conformance level: " + escapeSequenceToString(ch, secondCh)); break; default: unsupported(ch, secondCh); } break; case ' switch (secondCh) { case '8': terminal.fillScreen('E'); break; default: unsupported(ch, secondCh); } break; case '%': switch (secondCh) { case '@': // Select default character set. That is ISO 8859-1 case 'G': // Select UTF-8 character set. unsupported("Selecting charset is unsupported: " + escapeSequenceToString(ch, secondCh)); break; default: unsupported(ch, secondCh); } break; case '(': terminal.designateCharacterSet(0, parseCharacterSet(secondCh)); //Designate G0 Character set (VT100) break; case ')': terminal.designateCharacterSet(1, parseCharacterSet(secondCh)); //Designate G1 Character set (VT100) break; case '*': terminal.designateCharacterSet(2, parseCharacterSet(secondCh)); //Designate G2 Character set (VT220) break; case '+': terminal.designateCharacterSet(3, parseCharacterSet(secondCh)); //Designate G3 Character set (VT220) break; case '-': terminal.designateCharacterSet(1, parseCharacterSet(secondCh)); //Designate G1 Character set (VT300) break; case '.': terminal.designateCharacterSet(2, parseCharacterSet(secondCh)); //Designate G2 Character set (VT300) break; case '/': terminal.designateCharacterSet(3, parseCharacterSet(secondCh)); //Designate G3 Character set (VT300) break; case '$': case '@': unsupported(ch, secondCh); } } private static TermCharset parseCharacterSet(char ch) { switch (ch) { case '0': return TermCharset.SpecialCharacters; case 'A': return TermCharset.UK; case 'B': return TermCharset.USASCII; // Other character sets apply to VT220 and up default: return TermCharset.USASCII; } } private static void unsupported(char... b) { unsupported(escapeSequenceToString(b)); } private static void unsupported(String msg) { LOG.error("Unsupported control characters: " + msg); } private static String escapeSequenceToString(final char... b) { StringBuilder sb = new StringBuilder("ESC "); for (char c : b) { sb.append(' '); sb.append(c); } return sb.toString(); } private boolean processControlSequence(ControlSequence args) { switch (args.getFinalChar()) { case '@': return insertBlankCharacters(args); // ICH case 'A': return cursorUp(args); //CUU case 'B': return cursorDown(args); //CUD case 'C': return cursorForward(args); //CUF case 'D': return cursorBackward(args); //CUB case 'E': return cursorNextLine(args); //CNL case 'F': return cursorPrecedingLine(args); //CPL case 'G': case '`': return cursorHorizontalAbsolute(args); //CHA case 'f': case 'H': // CUP return cursorPosition(args); case 'J': // DECSED return eraseInDisplay(args); case 'K': return eraseInLine(args); case 'L': return insertLines(args); case 'c': //Send Device Attributes (Primary DA) return sendDeviceAttributes(); case 'd': // VPA return linePositionAbsolute(args); case 'h': //setModeEnabled(args, true); return false; case 'm': if (args.startsWithMoreMark()) { //Set or reset resource-values used by xterm // to decide whether to construct escape sequences holding information about // the modifiers pressed with a given key return false; } return characterAttributes(args); //Character Attributes (SGR) case 'n': return deviceStatusReport(args); // DSR case 'r': if (args.startsWithQuestionMark()) { return restoreDecPrivateModeValues(args); } else { return setScrollingRegion(args); } case 'l': //setModeEnabled(args, false); return false; default: return false; } } private boolean linePositionAbsolute(ControlSequence args) { int y = args.getArg(0, 1); myTerminal.linePositionAbsolute(y); return true; } private boolean restoreDecPrivateModeValues(ControlSequence args) { LOG.error("Unsupported: " + args.toString()); return false; } private boolean deviceStatusReport(ControlSequence args) { if (LOG.isDebugEnabled()) { LOG.debug("Sending Device Report Status"); } if (args.startsWithQuestionMark()) { LOG.error("Don't support DEC-specific Device Report Status"); return false; } int c = args.getArg(0, 0); if (c == 5) { myOutputStream.sendString(Ascii.ESC + "[0n"); return true; } else if (c == 6) { int row = myTerminal.getCursorY(); int column = myTerminal.getCursorX(); myOutputStream.sendString(Ascii.ESC + "[" + row + ";" + column + "R"); return true; } else { LOG.error("Unsupported parameter: " + args.toString()); return false; } } private boolean insertLines(ControlSequence args) { //TODO: implement return false; } private boolean sendDeviceAttributes() { if (LOG.isDebugEnabled()) { LOG.debug("Identifying to remote system as VT102"); } myOutputStream.sendBytes(CharacterUtils.VT102_RESPONSE); return true; } private boolean cursorHorizontalAbsolute(ControlSequence args) { int x = args.getArg(0, 1); myTerminal.cursorHorizontalAbsolute(x); return true; } private boolean cursorNextLine(ControlSequence args) { int dx = args.getArg(0, 1); dx = dx == 0 ? 1 : dx; myTerminal.cursorDown(dx); myTerminal.cursorHorizontalAbsolute(1); return true; } private boolean cursorPrecedingLine(ControlSequence args) { int dx = args.getArg(0, 1); dx = dx == 0 ? 1 : dx; myTerminal.cursorUp(dx); myTerminal.cursorHorizontalAbsolute(1); return true; } private boolean insertBlankCharacters(ControlSequence args) { final int arg = args.getArg(0, 1); char[] chars = new char[arg]; Arrays.fill(chars, ' '); myTerminal.writeCharacters(chars, 0, arg); return true; } private boolean eraseInDisplay(ControlSequence args) { // ESC [ Ps J final int arg = args.getArg(0, 0); if (args.startsWithQuestionMark()) { //TODO: support ESC [ ? Ps J - Selective Erase (DECSED) return false; } myTerminal.eraseInDisplay(arg); return true; } private boolean eraseInLine(ControlSequence args) { // ESC [ Ps K final int arg = args.getArg(0, 0); if (args.startsWithQuestionMark()) { //TODO: support ESC [ ? Ps K - Selective Erase (DECSEL) return false; } myTerminal.eraseInLine(arg); return true; } private boolean cursorBackward(ControlSequence args) { int dx = args.getArg(0, 1); dx = dx == 0 ? 1 : dx; myTerminal.cursorBackward(dx); return true; } private boolean setScrollingRegion(ControlSequence args) { final int top = args.getArg(0, 1); final int bottom = args.getArg(1, myTerminal.getTerminalHeight()); myTerminal.setScrollingRegion(top, bottom); return true; } private boolean cursorForward(ControlSequence args) { int countX = args.getArg(0, 1); countX = countX == 0 ? 1 : countX; myTerminal.cursorForward(countX); return true; } private boolean cursorDown(ControlSequence cs) { int countY = cs.getArg(0, 0); countY = countY == 0 ? 1 : countY; myTerminal.cursorDown(countY); return true; } private boolean cursorPosition(ControlSequence cs) { final int argy = cs.getArg(0, 1); final int argx = cs.getArg(1, 1); myTerminal.cursorPosition(argx, argy); return true; } private boolean characterAttributes(final ControlSequence args) { StyleState styleState = createStyleState(args); myTerminal.characterAttributes(styleState); return true; } private static StyleState createStyleState(ControlSequence args) { StyleState styleState = new StyleState(); final int argCount = args.getCount(); if (argCount == 0) { styleState.reset(); } for (int i = 0; i < argCount; i++) { final int arg = args.getArg(i, -1); if (arg == -1) { LOG.error("Error in processing char attributes, arg " + i); continue; } switch (arg) { case 0: //Normal (default) styleState.reset(); break; case 1:// Bold styleState.setOption(TextStyle.Option.BOLD, true); break; case 2:// Dim styleState.setOption(TextStyle.Option.DIM, true); break; case 4:// Underlined styleState.setOption(TextStyle.Option.UNDERLINED, true); break; case 5:// Blink (appears as Bold) styleState.setOption(TextStyle.Option.BLINK, true); break; case 7:// Inverse styleState.setOption(TextStyle.Option.INVERSE, true); break; case 8: // Invisible (hidden) styleState.setOption(TextStyle.Option.HIDDEN, true); break; case 22: //Normal (neither bold nor faint) styleState.setOption(TextStyle.Option.BOLD, false); styleState.setOption(TextStyle.Option.DIM, false); break; case 24: // Not underlined styleState.setOption(TextStyle.Option.UNDERLINED, false); case 25: //Steady (not blinking) styleState.setOption(TextStyle.Option.BLINK, false); case 27: //Positive (not inverse) styleState.setOption(TextStyle.Option.INVERSE, false); case 28: //Visible, i.e. not hidden styleState.setOption(TextStyle.Option.HIDDEN, false); case 30: case 31: case 32: case 33: case 34: case 35: case 36: case 37: styleState.setCurrentForeground(ColorPalette.getCurrentColorSettings()[arg - 30]); break; case 38: // Set xterm-256 text color Color color256 = getColor256(args); if (color256 != null) { styleState.setCurrentForeground(color256); } case 39: // Default (original) foreground styleState.setCurrentForeground(null); break; case 40: case 41: case 42: case 43: case 44: case 45: case 46: case 47: styleState.setCurrentBackground(ColorPalette.getCurrentColorSettings()[arg - 40]); break; case 48: // Set xterm-256 background color Color bgColor256 = getColor256(args); if (bgColor256 != null) { styleState.setCurrentBackground(bgColor256); } case 49: //Default (original) foreground styleState.setCurrentBackground(null); break; case 90: case 91: case 92: case 93: case 94: case 95: case 96: case 97: //Bright versions of the ISO colors for foreground styleState.setCurrentForeground(ColorPalette.getIndexedColor(arg - 82)); break; case 100: case 101: case 102: case 103: case 104: case 105: case 106: case 107: //Bright versions of the ISO colors for background styleState.setCurrentBackground(ColorPalette.getIndexedColor(arg - 92)); default: LOG.error("Unknown character attribute:" + arg); } } return styleState; } private static Color getColor256(ControlSequence args) { int code = args.getArg(1, 0); if (code == 2) { /* direct color in rgb space */ int val0 = args.getArg(2, -1); int val1 = args.getArg(3, -1); int val2 = args.getArg(4, -1); if ((val0 >= 0 && val0 < 256) && (val1 >= 0 && val1 < 256) && (val2 >= 0 && val2 < 256)) { return new Color(val0, val1, val2); } else { LOG.error("Bogus color setting " + args.toString()); return null; } } else if (code == 5) { /* indexed color */ return ColorPalette.getIndexedColor(args.getArg(2, 0)); } else { LOG.error("Unsupported code for color attribute " + args.toString()); return null; } } private boolean cursorUp(ControlSequence cs) { int arg = cs.getArg(0, 0); arg = arg == 0 ? 1 : arg; myTerminal.cursorUp(arg); return true; } private void setModeEnabled(final TerminalMode mode, final boolean on) throws IOException { if (on) { if (LOG.isInfoEnabled()) LOG.info("Modes: adding " + mode); myTerminal.setMode(mode); } else { if (LOG.isInfoEnabled()) LOG.info("Modes: removing " + mode); myTerminal.unsetMode(mode); } } }
package org.mobicents.protocols.ss7.mtp; import java.nio.ByteBuffer; import java.util.LinkedList; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.apache.log4j.Logger; public class Utils { // Some common statics // /** * Indicate value not set; */ public static final byte _VALUE_NOT_SET = -1; public final static String dump(ByteBuffer buff, int size, boolean asBits) { return dump(buff.array(), size, asBits); } public final static String dump(byte[] buff, int size, boolean asBits) { String s = ""; for (int i = 0; i < size; i++) { String ss = null; if(!asBits) { ss = Integer.toHexString(buff[i] & 0xff); } else { ss = Integer.toBinaryString(buff[i] & 0xff); } ss = fillInZeroPrefix(ss,asBits); s += " " + ss; } return s; } public final static String fillInZeroPrefix(String ss, boolean asBits) { if (asBits) { if (ss.length() < 8) { for (int j = ss.length(); j < 8; j++) { ss = "0" + ss; } } } else { // hex if (ss.length() < 2) { ss = "0" + ss; } } return ss; } public final static String dump(int[] buff, int size) { String s = ""; for (int i = 0; i < size; i++) { String ss = Integer.toHexString(buff[i] & 0xff); if (ss.length() == 1) { ss = "0" + ss; } s += " " + ss; } return s; } public static void createTrace(Throwable t,StringBuilder sb, boolean top) { if(!top) { sb.append("\nCaused by: "+t.toString()); } StackTraceElement[] trace = t.getStackTrace(); for (int i=0; i < trace.length; i++) sb.append("\tat " + trace[i]); Throwable ourCause = t.getCause(); if(ourCause!=null) { createTrace(ourCause, sb,false); } } public static String createTrace(Throwable t) { StringBuilder sb = new StringBuilder(); createTrace(t,sb,true); return sb.toString(); } public static Utils getInstance() { return _INSTANCE_; } /** * General logger. */ private static final Logger logger = Logger.getLogger(Utils.class); private static final Utils _INSTANCE_ = new Utils(); private StringBuilder loggBuilder = new StringBuilder(); private LinkedList<BufferHolder> dataHolder = new LinkedList<BufferHolder>(); private Future debugFuture; //this is doubling of vars, but.... private boolean enabledL2Debug = false; private boolean enableDataTrace = false; //private boolean enableSuTrace = false; private boolean enabledL3Debug = false; /** * @return the enabledL2Debug */ public boolean isEnabledL2Debug() { return enabledL2Debug; } /** * @param enabledL2Debug the enabledL2Debug to set */ public void setEnabledL2Debug(boolean enabledL2Debug) { this.enabledL2Debug = enabledL2Debug; } /** * @return the enableDataTrace */ public boolean isEnableDataTrace() { return enableDataTrace; } /** * @param enableDataTrace the enableDataTrace to set */ public void setEnableDataTrace(boolean enableDataTrace) { this.enableDataTrace = enableDataTrace; } // /** // * @return the enableSuTrace // */ // public boolean isEnableSuTrace() { // return enableSuTrace; // /** // * @param enableSuTrace the enableSuTrace to set // */ // public void setEnableSuTrace(boolean enableSuTrace) { // this.enableSuTrace = enableSuTrace; /** * @return the enabledL3Debug */ public boolean isEnabledL3Debug() { return enabledL3Debug; } /** * @param enabledL3Debug the enabledL3Debug to set */ public void setEnabledL3Debug(boolean enabledL3Debug) { this.enabledL3Debug = enabledL3Debug; } public void append(String s) { this.loggBuilder.append("\n"+s); } public void stopDebug() { if(this.debugFuture!=null) { this.debugFuture.cancel(false); this.debugFuture = null; } } private final class LogginAction implements Runnable { public void run() { // TODO Auto-generated method stub if((enabledL2Debug || enabledL3Debug) && loggBuilder.length() > 0) { logger.info(loggBuilder); loggBuilder = new StringBuilder(); } if(enableDataTrace && enabledL2Debug && dataHolder.size() > 0) { StringBuilder sb = new StringBuilder(); while(dataHolder.size()>0) { sb.append(dataHolder.remove(0)).append("\n"); } logger.info("\n"+sb); } } } //FIXME: this will be moved once everything is coded and we have proper framework // LOGGERS Section. Note that MTP acts // // on 2ms basis, logging proves to be // // killer, we use async loggin, one // // event per second // private class BufferHolder { private long stamp; private byte[] buffer; private int len; private String linkName; private int linkSls=-1; private String linkSetName; private int linkSetId=-1; private BufferHolder(long stamp, byte[] buffer, int len, String linkName, int linkSls, String linkSetName, int linkSetId) { super(); this.stamp = stamp; this.buffer = buffer; this.len = len; System.arraycopy(buffer, 0, this.buffer, 0, len); this.linkName = linkName; this.linkSls = linkSls; this.linkSetName = linkSetName; this.linkSetId = linkSetId; } @Override public String toString() { return "T:"+this.stamp+":"+linkName+":"+linkSls+":"+linkSetName+":"+linkSetId+":"+Utils.dump(this.buffer,len,false); } } public void addBuffer(int sls, String name, String linkSetName, int linkSetId, long currentTimeMillis, byte[] buff, int len) { //hmm works better if method is implemented :) BufferHolder bh = new BufferHolder(currentTimeMillis, buff, len, name, sls, linkSetName, linkSetId); dataHolder.add(bh); } }
package necromunda; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.Observable; import java.util.Set; import javax.swing.BoxLayout; import javax.swing.JFrame; import javax.swing.SwingUtilities; import javax.swing.ToolTipManager; import necromunda.MaterialFactory.MaterialIdentifier; import com.jme3.math.FastMath; import com.jme3.math.Vector3f; public class Necromunda extends Observable { public enum SelectionMode { DEPLOY_MODEL, DEPLOY_BUILDING, SELECT, MOVE, CLIMB, TARGET, REROLL } public enum Phase { MOVEMENT("Movement"), SHOOTING("Shooting"), HAND_TO_HAND("Hand to Hand"), RECOVERY("Recovery"); private String literal; private Phase(String literal) { this.literal = literal; } @Override public String toString() { return literal; } } public static final float RUN_SPOT_DISTANCE = 8; public static final float UNPIN_BY_INITIATIVE_DISTANCE = 2; public static final float SUSTAINED_FIRE_RADIUS = 4; public static final float STRAY_SHOT_RADIUS = 0.5f; public static Necromunda game; private static String statusMessage; private List<Gang> gangs; private List<Building> buildings; private Fighter selectedFighter; private LinkedList<Fighter> deployQueue; private SelectionMode selectionMode; private Gang currentGang; private int turn; private Phase phase; private Map<String, String> terrainTextureMap; private JFrame necromundaFrame; public static final int[][] STRENGTH_RESISTANCE_MAP = { {4, 5, 6, 6, 7, 7, 7, 7, 7, 7}, {3, 4, 5, 6, 6, 7, 7, 7, 7, 7}, {2, 3, 4, 5, 6, 6, 7, 7, 7, 7}, {2, 2, 3, 4, 5, 6, 6, 7, 7, 7}, {2, 2, 2, 3, 4, 5, 6, 6, 7, 7}, {2, 2, 2, 2, 3, 4, 5, 6, 6, 7}, {2, 2, 2, 2, 2, 3, 4, 5, 6, 6}, {2, 2, 2, 2, 2, 2, 3, 4, 5, 6}, {2, 2, 2, 2, 2, 2, 2, 3, 4, 5}, {2, 2, 2, 2, 2, 2, 2, 2, 3, 4}, }; /** * @param args */ public static void main(String[] args) { Necromunda game = Necromunda.getInstance(); } public Necromunda() { gangs = new ArrayList<Gang>(); selectionMode = SelectionMode.DEPLOY_BUILDING; turn = 1; statusMessage = ""; buildings = createBuildings(); terrainTextureMap = createTerrainTextureMapping(); deployQueue = new LinkedList<Fighter>(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { initialiseGUI(); } }); } public static Necromunda getInstance() { if (game == null) { game = new Necromunda(); } return game; } private List<Building> createBuildings() { List<Building> buildings = new ArrayList<Building>(); buildings.add(new Building("01")); buildings.add(new Building("02")); buildings.add(new Building("03")); buildings.add(new Building("04", "05")); buildings.add(new Building("06")); buildings.add(new Building("07")); buildings.add(new Building("08")); buildings.add(new Building("09")); return buildings; } private Map<String, String> createTerrainTextureMapping() { Map<String, String> map = new HashMap<String, String>(); map.put("Grass", "grass01.tgr"); map.put("Toxic Ash", "toxicash01.tgr"); map.put("Dark Ash", "darkash01.tgr"); return map; } private void initialiseGUI() { GangGenerationPanel gangGenerationPanel = new GangGenerationPanel(this); necromundaFrame = new JFrame("Necromunda"); necromundaFrame.setSize(1000, 800); necromundaFrame.setResizable(false); necromundaFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); necromundaFrame.setLocationRelativeTo(null); necromundaFrame.add(gangGenerationPanel); necromundaFrame.setVisible(true); } public void fighterDeployed() { selectedFighter = deployQueue.poll(); if (selectedFighter == null) { currentGang = gangs.get(0); currentGang.turnStarted(); selectionMode = SelectionMode.SELECT; phase = Phase.MOVEMENT; } } public void endTurn() { currentGang.turnEnded(); if (((gangs.indexOf(currentGang) + 1) % gangs.size()) == 0) { turn++; } currentGang = getNextGang(); currentGang.turnStarted(); selectedFighter = null; selectionMode = SelectionMode.SELECT; phase = Phase.MOVEMENT; } private Gang getNextGang() { Gang gang = null; int gangIndex = gangs.indexOf(currentGang); if ((gangIndex + 1) == gangs.size()) { gang = gangs.get(0); } else { gang = gangs.get(gangIndex + 1); } return gang; } public void nextPhase() { switch (phase) { case MOVEMENT: phase = Phase.SHOOTING; break; case SHOOTING: case HAND_TO_HAND: case RECOVERY: } selectionMode = SelectionMode.SELECT; } public void updateStatus() { setChanged(); notifyObservers(); } public void commitGeneratedGangs(Enumeration<?> gangs) { while (gangs.hasMoreElements()) { Gang nextGang = (Gang)gangs.nextElement(); deployQueue.addAll(nextGang.getGangMembers()); if (getCurrentGang() == null) { setCurrentGang(nextGang); setSelectedFighter(deployQueue.poll()); } getGangs().add(nextGang); } } public Gang getCurrentGang() { return currentGang; } public void setCurrentGang(Gang currentGang) { this.currentGang = currentGang; } public Fighter getSelectedFighter() { return selectedFighter; } public void setSelectedFighter(Fighter selectedFighter) { this.selectedFighter = selectedFighter; } public List<Gang> getGangs() { return gangs; } public JFrame getNecromundaFrame() { return necromundaFrame; } public SelectionMode getSelectionMode() { return selectionMode; } public void setSelectionMode(SelectionMode selectionMode) { this.selectionMode = selectionMode; } public int getTurn() { return turn; } public Phase getPhase() { return phase; } public void setPhase(Phase phase) { this.phase = phase; } public static String getStatusMessage() { return statusMessage; } public static void setStatusMessage(String statusMessage) { Necromunda.statusMessage = statusMessage; } public static void appendToStatusMessage(String statusMessage) { if (Necromunda.statusMessage.equals("")) { Necromunda.statusMessage = statusMessage; } else { Necromunda.statusMessage = String.format("%s %s", Necromunda.statusMessage, statusMessage); } } public List<Fighter> getHostileGangers() { return currentGang.getHostileGangers(gangs); } public List<Building> getBuildings() { return buildings; } public Map<String, String> getTerrainTextureMap() { return terrainTextureMap; } }
package ed25519.test; import java.math.BigInteger; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import ed25519.application.BigPoint; import ed25519.application.Curve; public class CurveTest { private Curve c; @BeforeClass protected void setUp() throws Exception { c = new Curve(); } @DataProvider(name = "invert") public static Object[][] invertProvider() { BigInteger one = BigInteger.valueOf(1); BigInteger five = BigInteger.valueOf(5); BigInteger large1 = new BigInteger("11579208923731619542357098500868790785326998466564056403945758400791312963990"); Object[][] data = {{one, one}, {five, large1}}; return data; } @Test(dataProvider = "invert", dependsOnMethods = {"ed25519.test.NumberUtilsTest.testExpmod"}, dependsOnGroups = {"getxx"}, groups = {"invert"}) public void testInvert(BigInteger value, BigInteger expected) { Assert.assertEquals(c.invert(value), expected); } @DataProvider(name = "getxx") public static Object[][] getxxProvider() { BigInteger minusOne = BigInteger.valueOf(-1); BigInteger zero = BigInteger.valueOf(0); BigInteger one = BigInteger.valueOf(1); BigInteger two = BigInteger.valueOf(2); BigInteger large1 = new BigInteger("159238947029881800007354471772647911766795077324544932017472991350137141588898"); Object[][] data = {{minusOne, zero}, {one, zero}, {two, large1}}; return data; } @Test(dataProvider = "getxx", dependsOnMethods = "ed25519.test.NumberUtilsTest.testExpmod", groups = {"getxx"}) public void testGetXX(BigInteger value, BigInteger expected) { Assert.assertEquals(c.getXX(value), expected); } @DataProvider(name = "xrecover") public static Object[][] xRecoverProvider() { BigInteger zero = BigInteger.valueOf(0); BigInteger four = BigInteger.valueOf(4); BigInteger large1 = new BigInteger("19681161376707505956807079304988542015446066515923890162744021073123829784752"); BigInteger large2 = new BigInteger("26193273134124080442446118532604303931175156347221147955160486408041496074798"); Object[][] data = {{zero, large1}, {four, large2}}; return data; } @Test(dataProvider = "xrecover", dependsOnMethods = {"ed25519.test.NumberUtilsTest.testExpmod", "testGetXX"}, groups = {"recoverx"}) public void testXRecover(BigInteger value, BigInteger expected) { Assert.assertEquals(c.recoverX(value), expected); } @Test(dependsOnGroups = {"bigpoint", "invert", "recoverx"}, groups = {"basepoint"}) public void testGetBasePoint() { BigInteger x = new BigInteger("15112221349535400772501151409588531511454012693041857206046113283949847762202"); BigInteger y = new BigInteger("46316835694926478169428394003475163141307993866256225615783033603165251855960"); BigPoint expected = new BigPoint(x,y); BigPoint basePoint = c.getBasePoint(); Assert.assertEquals(basePoint, expected); } // @Test // public void testgetD() { @Test(dependsOnGroups = {"bigpoint"}, groups = {"edward"}) public void testEdwards0and0() { BigPoint first = new BigPoint(new BigInteger("0"), new BigInteger("0")); BigPoint second = new BigPoint(new BigInteger("0"), new BigInteger("0")); BigPoint expected = new BigPoint(new BigInteger("0"), new BigInteger("0")); BigPoint result = c.edwards(first, second); Assert.assertEquals(result, expected); } // @Test(dependsOnGroups = {"bigpoint"}, groups = {"edward"}) // public void testEdwards1and1() { // BigPoint first = new BigPoint(new BigInteger("1"), new BigInteger("1")); // BigPoint second = new BigPoint(new BigInteger("1"), new BigInteger("1")); // BigPoint expected = new BigPoint(new BigInteger("243332"), new BigInteger("51380297829790456491237162401597246033761091082941378702394490295467508647106")); // BigPoint result = c.edwards(first, second); // Assert.assertEquals(result, expected); @Test(dependsOnGroups = {"bigpoint"}) public void testScalarMult0() { BigPoint expected = new BigPoint(new BigInteger("0"), new BigInteger("1")); BigPoint result = c.scalarmult(new BigInteger("0")); Assert.assertEquals(result, expected); } // public void testScalarMult1() { // BigInteger x = new BigInteger("15112221349535400772501151409588531511454012693041857206046113283949847762202"); // BigInteger y = new BigInteger("46316835694926478169428394003475163141307993866256225615783033603165251855960"); // BigPoint expected = new BigPoint(x, y); // BigPoint result = c.scalarmult(new BigInteger("1")); // assertEquals(expected, result); }
package com.conveyal.gtfs.graphql; import com.conveyal.gtfs.TestUtils; import com.conveyal.gtfs.loader.FeedLoadResult; import com.fasterxml.jackson.databind.ObjectMapper; import graphql.GraphQL; import org.apache.commons.io.IOUtils; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import javax.sql.DataSource; import java.io.FileInputStream; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.conveyal.gtfs.GTFS.createDataSource; import static com.conveyal.gtfs.GTFS.load; import static com.conveyal.gtfs.GTFS.validate; import static com.conveyal.gtfs.TestUtils.getResourceFileName; import static com.zenika.snapshotmatcher.SnapshotMatcher.matchesSnapshot; import static org.hamcrest.MatcherAssert.assertThat; /** * A test suite for all things related to fetching objects with GraphQL. * Important note: Snapshot testing is heavily used in this test suite and can potentially result in false negatives * in cases where the order of items in a list is not important. */ public class GTFSGraphQLTest { private static String testDBName; private static DataSource testDataSource; private static String testNamespace; private static String testInjectionDBName; private static DataSource testInjectionDataSource; private static String testInjectionNamespace; private ObjectMapper mapper = new ObjectMapper(); @BeforeClass public static void setUpClass() throws SQLException, IOException { // create a new database testDBName = TestUtils.generateNewDB(); String dbConnectionUrl = String.format("jdbc:postgresql://localhost/%s", testDBName); testDataSource = createDataSource(dbConnectionUrl, null, null); // zip up test folder into temp zip file String zipFileName = TestUtils.zipFolderFiles("fake-agency"); // load feed into db FeedLoadResult feedLoadResult = load(zipFileName, testDataSource); testNamespace = feedLoadResult.uniqueIdentifier; // validate feed to create additional tables validate(testNamespace, testDataSource); // create a separate injection database to use in injection tests // create a new database testInjectionDBName = TestUtils.generateNewDB(); String injectionDbConnectionUrl = String.format("jdbc:postgresql://localhost/%s", testInjectionDBName); testInjectionDataSource = createDataSource(injectionDbConnectionUrl, null, null); // load feed into db FeedLoadResult injectionFeedLoadResult = load(zipFileName, testInjectionDataSource); testInjectionNamespace = injectionFeedLoadResult.uniqueIdentifier; // validate feed to create additional tables validate(testInjectionNamespace, testInjectionDataSource); } @AfterClass public static void tearDownClass() { TestUtils.dropDB(testDBName); TestUtils.dropDB(testInjectionDBName); } // tests that the graphQL schema can initialize @Test public void canInitialize() { GTFSGraphQL.initialize(testDataSource); GraphQL graphQL = GTFSGraphQL.getGraphQl(); } // tests that the root element of a feed can be fetched @Test public void canFetchFeed() throws IOException { assertThat(queryGraphQL("feed.txt"), matchesSnapshot()); } // tests that the row counts of a feed can be fetched @Test public void canFetchFeedRowCounts() throws IOException { assertThat(queryGraphQL("feedRowCounts.txt"), matchesSnapshot()); } // tests that the errors of a feed can be fetched @Test public void canFetchErrors() throws IOException { assertThat(queryGraphQL("feedErrors.txt"), matchesSnapshot()); } // tests that the feed_info of a feed can be fetched @Test public void canFetchFeedInfo() throws IOException { assertThat(queryGraphQL("feedFeedInfo.txt"), matchesSnapshot()); } // tests that the patterns of a feed can be fetched @Test public void canFetchPatterns() throws IOException { assertThat(queryGraphQL("feedPatterns.txt"), matchesSnapshot()); } // tests that the agencies of a feed can be fetched @Test public void canFetchAgencies() throws IOException { assertThat(queryGraphQL("feedAgencies.txt"), matchesSnapshot()); } // tests that the calendars of a feed can be fetched @Test public void canFetchCalendars() throws IOException { assertThat(queryGraphQL("feedCalendars.txt"), matchesSnapshot()); } // tests that the fares of a feed can be fetched @Test public void canFetchFares() throws IOException { assertThat(queryGraphQL("feedFares.txt"), matchesSnapshot()); } // tests that the routes of a feed can be fetched @Test public void canFetchRoutes() throws IOException { assertThat(queryGraphQL("feedRoutes.txt"), matchesSnapshot()); } // tests that the stops of a feed can be fetched @Test public void canFetchStops() throws IOException { assertThat(queryGraphQL("feedStops.txt"), matchesSnapshot()); } // tests that the trips of a feed can be fetched @Test public void canFetchTrips() throws IOException { assertThat(queryGraphQL("feedTrips.txt"), matchesSnapshot()); } // TODO: make tests for schedule_exceptions / calendar_dates // tests that the stop times of a feed can be fetched @Test public void canFetchStopTimes() throws IOException { assertThat(queryGraphQL("feedStopTimes.txt"), matchesSnapshot()); } // tests that the stop times of a feed can be fetched @Test public void canFetchServices() throws IOException { assertThat(queryGraphQL("feedServices.txt"), matchesSnapshot()); } /** * attempt to fetch more than one record with SQL injection as inputs * the graphql library should properly escape the string and return 0 results for stops */ @Test public void canSanitizeSQLInjectionSentAsInput() throws IOException { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("namespace", testInjectionNamespace); variables.put("stop_id", Arrays.asList("' OR 1=1;")); assertThat( queryGraphQL( "feedStopsByStopId.txt", variables, testInjectionDataSource ), matchesSnapshot() ); } /** * attempt run a graphql query when one of the pieces of data contains a SQL injection * the graphql library should properly escape the string and complete the queries */ @Test public void canSanitizeSQLInjectionSentAsKeyValue() throws IOException, SQLException { // manually update the route_id key in routes and patterns String injection = "'' OR 1=1; Select ''99"; Connection connection = testInjectionDataSource.getConnection(); List<String> tablesToUpdate = Arrays.asList("routes", "fare_rules", "patterns", "trips"); for (String table : tablesToUpdate) { connection.createStatement() .execute(String.format("update %s.%s set route_id = '%s'", testInjectionNamespace, table, injection)); } connection.commit(); // make graphql query Map<String, Object> variables = new HashMap<String, Object>(); variables.put("namespace", testInjectionNamespace); assertThat(queryGraphQL("feedRoutes.txt", variables, testInjectionDataSource), matchesSnapshot()); } /** * Helper method to make a query with default variables * * @param queryFilename the filename that should be used to generate the GraphQL query. This file must be present * in the `src/test/resources/grahpql` folder */ private Map<String, Object> queryGraphQL(String queryFilename) throws IOException { Map<String, Object> variables = new HashMap<String, Object>(); variables.put("namespace", testNamespace); return queryGraphQL(queryFilename, variables, testDataSource); } /** * Helper method to execute a GraphQL query and return the result * * @param queryFilename the filename that should be used to generate the GraphQL query. This file must be present * in the `src/test/resources/grahpql` folder * @param variables a Map of input variables to the graphql query about to be executed * @param dataSource the datasource to use when initializing GraphQL */ private Map<String, Object> queryGraphQL( String queryFilename, Map<String,Object> variables, DataSource dataSource ) throws IOException { GTFSGraphQL.initialize(dataSource); FileInputStream inputStream = new FileInputStream( getResourceFileName(String.format("graphql/%s", queryFilename)) ); return GTFSGraphQL.getGraphQl().execute( IOUtils.toString(inputStream), null, null, variables ).toSpecification(); } }
package com.duck8823.model.twitter; import com.duck8823.TestConfiguration; import com.duck8823.context.twitter.QueryFactory; import com.duck8823.context.twitter.TestStatus; import com.duck8823.context.twitter.TestUser; import lombok.extern.log4j.Log4j; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import twitter4j.*; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @Log4j @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = TestConfiguration.class) public class FilterTypeTest { @Test public void () throws Exception { User user = new TestUser("TEST_NAME", "TEST_SCREEN_NAME"); Status status = new TestStatus(user, "TEXT"); Filter filter = new Filter(FilterType.SCREEN_NAME, "TEST_SCREEN_NAME"); assertTrue(filter.find(status)); } @Test public void () throws Exception { User user = new TestUser("NAME", "TEST_SCREEN_NAME"); Status status = new TestStatus(user, "TEXT"); Filter filter = new Filter(FilterType.SCREEN_NAME, "SCREEN_NAME"); assertFalse(filter.find(status)); } @Test public void () throws Exception { User user = new TestUser("NAME", "SCREEN_NAME"); Status status = new TestStatus(user, "TEST_TEXT"); Filter filter = new Filter(FilterType.TEXT, "TEST"); assertTrue(filter.find(status)); } @Test public void () throws Exception { User user = new TestUser("NAME", "SCREEN_NAME"); Status status = new TestStatus(user, "TEXT"); Filter filter = new Filter(FilterType.TEXT, "TEST"); assertFalse(filter.find(status)); } }
package com.github.davidmoten.bigsort; import rx.Observable; import rx.schedulers.Schedulers; public class BigSortMain { public static void main(String[] args) { // for profiling int n = 100000000; System.out.println(n * Math.log(n)); long t = System.currentTimeMillis(); BigSort.sort(Observable.range(1, n).map(i -> n - i + 1), 100000, 100, Schedulers.computation()).subscribe(); System.out.println(((System.currentTimeMillis() - t) / 1000.0) + "s"); } }
package net.localizethat; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import net.localizethat.gui.MainWindow; import net.localizethat.system.AppSettings; import net.localizethat.system.DBChecker; import net.localizethat.util.gui.GuiUtils; /** * LocalizeThat! Entry class * @author rpalomares */ public class Main { /** * String containing the version number in the format Major.Minor.devversion * Major and minor values are parsed and compared as integers, whereas the * devversion is parsed and compared as an String like "a1" for alpha * versions, "b2" for beta versions, or "r5" for release maintenance version * * For instance, when comparing "2.0.b4" to "12.0.r3", the comparison would be: * - Major: 2 &lt; 12 * - Minor: 0 == 0 * - Bugrelease: "b4" &lt; "r3" */ public static final String version = "0.7"; /** * Reference to the application settings */ public static AppSettings appSettings; /** * Reference to the application main window */ /** * Reference to the application main window */ public static MainWindow mainWindow; /** * Reference to global Entity Manager Factory */ public static EntityManagerFactory emf; /** * @param args the command line arguments (not used for now) */ public static void main(String[] args) { // Process parameters processParameters(args); // Process preferences appSettings = new AppSettings(); // Check database existence and create if needed DBChecker dbChecker = new DBChecker(appSettings.getString(AppSettings.PREF_DB_PATH), appSettings.getString(AppSettings.PREF_DB_LOGIN), appSettings.getString(AppSettings.PREF_DB_PASSWD)); if (!(dbChecker.checkAndCreateDBDir() && dbChecker.checkAndCreateDB())) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, "Can't properly access the database, check error dump log"); System.exit(1); } // Set up persistence unit Map<String, String> connProps = new HashMap<>(4); connProps.put("javax.persistence.jdbc.driver", "org.apache.derby.jdbc.EmbeddedDriver"); connProps.put("javax.persistence.jdbc.url", "jdbc:derby:" + DBChecker.DB_NAME); connProps.put("javax.persistence.jdbc.user", appSettings.getString(AppSettings.PREF_DB_LOGIN)); connProps.put("javax.persistence.jdbc.password", appSettings.getString(AppSettings.PREF_DB_PASSWD)); emf = Persistence.createEntityManagerFactory("localizethatPU", connProps); String preferredLafName = appSettings.getString(AppSettings.PREF_GUI_LOOK_AND_FEEL); if (!GuiUtils.setBestAvailableLookAndFeel(preferredLafName)) { System.exit(1); } mainWindow = new MainWindow(); /* Create and display the form */ java.awt.EventQueue.invokeLater(() -> { mainWindow.setVisible(true); }); } private static void processParameters(String[] args) { // Nothing to do at the moment } /** * Cleans up the resources used by the application before closing the system */ public static void cleanUpResources() { emf.close(); } }
package dejain.lang.ast; import dejain.lang.ASMCompiler; import dejain.lang.ASMCompiler.Region; import dejain.lang.ClassResolver; import java.util.Arrays; import java.util.Collections; import java.util.List; public class BinaryExpressionAST extends AbstractAST implements ExpressionAST { public static final int OPERATOR_ADD = 0; public static final int OPERATOR_SUB = 1; public int operator; public ExpressionAST lhs; public ExpressionAST rhs; public BinaryExpressionAST(Region region, int operator, ExpressionAST lhs, ExpressionAST rhs) { super(region); this.operator = operator; this.lhs = lhs; this.rhs = rhs; } @Override public TypeAST resultType() { return resultType; } @Override public <T> T accept(CodeVisitor<T> visitor) { return visitor.visitBinaryExpression(this); } private TypeAST resultType; @Override public void resolve(Scope thisClass, TypeAST expectedResultType, ClassResolver resolver, List<ASMCompiler.Message> errorMessages) { // resultType = new NameTypeAST(getRegion(), Void.class); // lhs.resolve(thisClass, expectedResultType, resolver, errorMessages); // rhs.resolve(thisClass, expectedResultType, resolver, errorMessages); // if(lhs.resultType().getDescriptor().equals("Ljava/lang/String;") || rhs.resultType().getDescriptor().equals("Ljava/lang/String;")) { // switch(operator) { // case OPERATOR_ADD: // if(!lhs.resultType().getDescriptor().equals("Ljava/lang/String;")) // lhs = expressionAsString(lhs); // if(!rhs.resultType().getDescriptor().equals("Ljava/lang/String;")) // rhs = expressionAsString(rhs); // resultType = new NameTypeAST(getRegion(), String.class); // break; // default: // errorMessages.add(new ASMCompiler.Message(getRegion(), "Bad operand types for binary operator '" + getOperatorString() + "'")); // break; // } else if(lhs.resultType().getSimpleName().equals("int") && rhs.resultType().getSimpleName().equals("int")) { // resultType = new NameTypeAST(getRegion(), int.class); } private String getOperatorString() { switch(operator) { case OPERATOR_ADD: return "+"; case OPERATOR_SUB: return "-"; } return null; } private ExpressionAST expressionAsString(ExpressionAST ctx) { switch(ctx.resultType().getSimpleName()) { case "int": return new InvocationAST(ctx.getRegion(), null, new NameTypeAST(ctx.getRegion(), Integer.class), "toString", Arrays.asList(ctx), new NameTypeAST(ctx.getRegion(), String.class)); default: return new InvocationAST(ctx.getRegion(), ctx, null, "toString", Collections.emptyList(), new NameTypeAST(ctx.getRegion(), String.class)); } } }
package nl.marayla.Xara; import java.util.LinkedList; import java.util.Map; import java.util.TreeMap; import nl.marayla.Xara.ElementCollisions.ElementCollision; import nl.marayla.Xara.ElementCollisions.ElementCollisionData; import nl.marayla.Xara.ElementEffects.ElementEffect; import nl.marayla.Xara.GameElements.GameElement; import nl.marayla.Xara.Levels.LevelGamePlay; import nl.marayla.Xara.Platform.XaraLog; import nl.marayla.Xara.Renderer.CellRenderer.RenderCellsBottom; import nl.marayla.Xara.Renderer.CellRenderer.RenderCellsTop; import nl.marayla.Xara.Renderer.CellRenderer.RenderCellsLeft; import nl.marayla.Xara.Renderer.CellRenderer.RenderCellsRight; import nl.marayla.Xara.Renderer.CellRenderer.RenderCells; import nl.marayla.Xara.Renderer.RenderData; import org.jetbrains.annotations.Contract; // Attributes of Field: // Contains physics (collision detection) // static objects cannot collide // dynamic objects do collide // 1. against static object -> // effect determined by static object, // executed on dynamic object by LevelGamePlay // 2. against dynamic object -> // Contains 2D-array of cells public final class Field { /* * Action */ public enum Action { NONE { @Override public void execute(final ElementCollisionData data) { // System.out.println("None " + data.getIndex()); } }, ADD { @Override public void execute(final ElementCollisionData data) { // System.out.println("Add " + data.getIndex()); addElement(data.getIndex(), data.getElement(), data.getDirection()); } }; public abstract void execute(final ElementCollisionData data); } @Contract("_, null -> fail") private static void executeAddAfterCollision( final int cellIndex, final ElementCollision.ElementCollisionResult result ) { //noinspection StatementWithEmptyBody if (result instanceof ElementCollision.Destroy) { // nothing to do } else if (result instanceof ElementCollision.Keep) { // System.out.println("Keep ++ Add " + cellIndex); addElement(cellIndex, result.getNextElement(), result.getNextDirection()); } else if (result instanceof ElementCollision.Move) { int nextIndex = calculateIndex(cellIndex, result.getRelativePosition()); if (getElement(nextIndex) == null) { // System.out.println("Move ++ Add " + nextIndex); addElement(nextIndex, result.getNextElement(), result.getNextDirection()); } } else { throw new UnsupportedOperationException(); } } /* * ConstantSize */ public interface ConstantSize { int getWidth(); int getHeight(); } /* * Size */ public static class Size implements ConstantSize { public Size(final int width, final int height) { set(width, height); } public Size(final ConstantSize other) { set(other); } @Override public final int getWidth() { return width; } @Override public final int getHeight() { return height; } public final void set(final int width, final int height) { this.width = width; this.height = height; } public final void set(final ConstantSize other) { width = other.getWidth(); height = other.getHeight(); } @Contract(pure = true) @Override public final boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof ConstantSize)) { return false; } ConstantSize other = (ConstantSize) o; return ((width == other.getWidth()) && (height == other.getHeight())); } @Contract(" -> fail") @Override public final int hashCode() { throw new UnsupportedOperationException(); } private int width = 0; private int height = 0; } /* * ConstantPosition */ public interface ConstantPosition { int getX(); int getY(); } /* * Position */ public static class Position implements ConstantPosition { public static final ConstantPosition ORIGIN = new Field.Position(0, 0); public Position(final int x, final int y) { set(x, y); } public Position(final ConstantPosition other) { set(other); } @Override public final int getX() { return x; } @Override public final int getY() { return y; } public final void set(final int x, final int y) { this.x = x; this.y = y; } public final void set(final ConstantPosition other) { x = other.getX(); y = other.getY(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || (getClass() != o.getClass())) { return false; } Position position = (Position) o; return (x == position.x) && (y == position.y); } @Override public int hashCode() { return 31 * x + y; } public final String toString() { return "Field.Position (" + x + ", " + y + ")"; } private int x = 0; private int y = 0; } /* * ConstantDirection */ public interface ConstantDirection { int getDeltaX(); int getDeltaY(); ConstantDirection reverse(); ConstantDirection combine(final ConstantDirection direction); ConstantDirection extract(final ConstantDirection direction); } /* * Direction */ public enum Direction implements ConstantDirection { STATIC(0, 0), LEFT_UP(-1, -1), UP(0, -1), RIGHT_UP(1, -1), RIGHT(1, 0), RIGHT_DOWN(1, 1), DOWN(0, 1), LEFT_DOWN(-1, 1), LEFT(-1, 0); @Override public final int getDeltaX() { return deltaX; } @Override public final int getDeltaY() { return deltaY; } @Contract(pure = true) @Override public final ConstantDirection reverse() { return determineDirectionBasedOnDeltaXandDeltaY(-deltaX, -deltaY); } @Override public final ConstantDirection combine(final ConstantDirection direction) { return determineDirectionBasedOnDeltaXandDeltaY( deltaX + direction.getDeltaX(), deltaY + direction.getDeltaY() ); } @Override public final ConstantDirection extract(final ConstantDirection direction) { return determineDirectionBasedOnDeltaXandDeltaY( (deltaX == direction.getDeltaX()) ? 0 : deltaX, // if x-direction equal extract else do not change (deltaY == direction.getDeltaY()) ? 0 : deltaY // if y-direction equal extract else do not change ); } Direction(final int deltaX, final int deltaY) { assert (deltaX >= -1) && (deltaX <= 1); assert (deltaY >= -1) && (deltaY <= 1); this.deltaX = deltaX; this.deltaY = deltaY; } @Contract(pure = true) private static Direction determineDirectionBasedOnDeltaXandDeltaY(final int deltaX, final int deltaY) { if (deltaX < 0) { // x => LEFT if (deltaY < 0) { // y => UP return LEFT_UP; } else if (deltaY > 0) { // y => DOWN return LEFT_DOWN; } else { // y => STATIC return LEFT; } } else if (deltaX > 0) { // x => RIGHT if (deltaY < 0) { // y => UP return RIGHT_UP; } else if (deltaY > 0) { // y => DOWN return RIGHT_DOWN; } else { // y=> STATIC return RIGHT; } } else { // x => STATIC if (deltaY < 0) { // y => UP return UP; } else if (deltaY > 0) { // y => DOWN return DOWN; } else { // y => STATIC return STATIC; } } } private final int deltaX; private final int deltaY; } /* * UpdateableDirection */ public static class UpdateableDirection implements ConstantDirection { public UpdateableDirection(ConstantDirection direction) { this.direction = direction; } @Override public final int getDeltaX() { return direction.getDeltaX(); } @Override public final int getDeltaY() { return direction.getDeltaY(); } @Override public final ConstantDirection reverse() { return direction.reverse(); } @Override public final ConstantDirection combine(final ConstantDirection direction) { return this.direction.combine(direction); } @Override public final ConstantDirection extract(final ConstantDirection direction) { return this.direction.extract(direction); } public final void update (final ConstantDirection direction) { this.direction = direction; } private ConstantDirection direction = Direction.STATIC; } /* * TopLinePosition */ public enum TopLinePosition { NONE, TOP, BOTTOM, LEFT, RIGHT } /* * FieldRenderer interface */ public static void render(final LevelGamePlay levelGamePlay, final RenderData renderData) { if (renderCells != null) { renderCells.render(levelGamePlay, cells, arraySize, topLine, renderData); } } /** * FieldCells interface */ @Contract(pure = true) public static GameElement getElement(final int index) { return cells[index]; } private static void addElement( final int index, final GameElement element, final ConstantDirection direction ) { assert (cells[index] == null) : "cells[" + index + "] = " + cells[index]; cells[index] = element; addDirection(index, direction); } /** * removeElement will remove an element in field. * It is allowed to point at an empty (= null) element. * @param index is the element-index that determines which element to remove */ private static void removeElement(final int index) { if (cells[index] != null) { cells[index] = null; dynamicCells.remove(index); } } private static void moveElement(final int index, final int nextIndex) { assert (cells[index] != null); assert (cells[nextIndex] == null); GameElement element = cells[index]; cells[index] = null; cells[nextIndex] = element; if (dynamicCells.containsKey(index)) { DynamicCellContent dynamicCell = dynamicCells.remove(index); dynamicCells.put(nextIndex, dynamicCell); } } private static int calculateIndex(final int index, final ConstantPosition relativePosition) { int result; switch (topLinePosition) { case NONE: case TOP: case BOTTOM: result = index + relativePosition.getX() + (relativePosition.getY() * topLineSize); break; case LEFT: case RIGHT: result = index + relativePosition.getY() + (relativePosition.getX() * topLineSize); break; default: throw new UnsupportedOperationException(); } if (result < 0) { result += cells.length; } else if (result >= cells.length) { result -= cells.length; } return result; } private static int calculateIndex(final int index, final ConstantDirection direction) { return calculateIndex(index, new Position(direction.getDeltaX(), direction.getDeltaY())); } public static void initialize( final ConstantSize externalSize, final TopLinePosition topLinePosition ) { setTopLinePosition(topLinePosition); resize(externalSize); switch (topLinePosition) { case NONE: topLineSize = arraySize.getWidth(); maxTopLine = arraySize.getHeight(); break; case TOP: case BOTTOM: topLineSize = arraySize.getWidth(); maxTopLine = arraySize.getHeight(); break; case LEFT: case RIGHT: topLineSize = arraySize.getHeight(); maxTopLine = arraySize.getWidth(); break; default: throw new UnsupportedOperationException(); } topLine = 0; frameCounter = 0; } public static void addElementTopLine(final GameElement element, final int externalPosition) { int internalPosition = externalToInternalPosition(externalPosition); assert (internalPosition < topLineSize); int index = (topLine * topLineSize) + internalPosition; removeElement(index); addElement(index, element, Direction.STATIC); } public static void addStaticElement( final GameElement element, final ConstantPosition externalPosition ) { doAddElement(element, externalPosition); } public static void addDynamicElement( final GameElement element, final ConstantPosition externalPosition, final ConstantDirection direction ) { int index = doAddElement(element, externalPosition); addDirection(index, direction); } public static void nextFrame(final LevelGamePlay levelGamePlay) { if (XaraLog.DEBUG) { System.out.println("hello debug"); XaraLog.log.d("Some tag", "Some message"); } else { System.out.println("hello no debug - error"); XaraLog.log.e("Some error", "Some error-message"); } frameCounter++; handleCollisions(levelGamePlay); // TODO Determine when exactly to update topLine if (topLinePosition != Field.TopLinePosition.NONE) { if (topLine == 0) { topLine = maxTopLine; } topLine } // Remove first row int line = topLine * topLineSize; for (int cell = 1; cell < (topLineSize - 1); cell++) { removeElement(line + cell); } // remove last row line -= topLineSize; if (line < 0) { line += cells.length; } for (int cell = 1; cell < (topLineSize - 1); cell++) { removeElement(line + cell); } // Remove all elements in the first and last column int cellIndex = -1; for (int rows = 0; rows < maxTopLine; rows++) { cellIndex++; removeElement(cellIndex); cellIndex += (topLineSize - 1); removeElement(cellIndex); } } @Contract(pure = true) private static int externalToInternalPosition(final int externalPosition) { return externalPosition + 1; } @Contract("_ -> !null") private static ConstantPosition externalToInternalPosition(final ConstantPosition externalPosition) { return new Position(externalPosition.getX() + 1, externalPosition.getY() + 1); } private static void addDirection(final int index, final Field.ConstantDirection direction) { assert (!dynamicCells.containsKey(index)); if (direction != Direction.STATIC) { dynamicCells.put(index, new DynamicCellContent(direction)); } } private static int doAddElement(final GameElement element, final ConstantPosition externalPosition) { int index; final ConstantPosition internalPosition = externalToInternalPosition(externalPosition); switch (topLinePosition) { case NONE: case TOP: case BOTTOM: index = internalPosition.getX() + (internalPosition.getY() * topLineSize); break; case LEFT: case RIGHT: index = internalPosition.getY() + (internalPosition.getX() * topLineSize); break; default: throw new UnsupportedOperationException(); } if (cells[index] != null) { removeElement(index); } addElement(index, element, Direction.STATIC); return index; } // Collisions private static void handleCollisions(final LevelGamePlay levelGamePlay) { LinkedList<Integer> collisions = new LinkedList<>(dynamicCells.keySet()); while (!collisions.isEmpty()) { int cellIndex = collisions.removeFirst(); assert (cells[cellIndex] != null); assert (dynamicCells.get(cellIndex) != null); assert (dynamicCells.get(cellIndex).direction != Direction.STATIC); doHandleCollision(collisions, cellIndex, levelGamePlay); } } /** * DONE Issue1 : Watch out for GameElement that does not move (Direction.STATIC) * -> ignore collision handling * DONE Issue2 : DynamicElements can collide in circle -> move all and no collision handling * TODO Issue3 : DynamicElement can point at each other and in that case pass each other * without collision -> not handled right now * TODO Issue4 : DynamicElement can end-up in same cell (started from different places) * -> most difficult to solve -> not handled right now * * @param collisions contains list of all collisions that still have to be handled * @param dynamicCellIndex is index of cell that is moving and which possible collision is handled * @param levelGamePlay gameplay of this level */ private static void doHandleCollision( final LinkedList<Integer> collisions, final int dynamicCellIndex, final LevelGamePlay levelGamePlay ) { final DynamicCellContent dynamicCell = dynamicCells.remove(dynamicCellIndex); assert (dynamicCell != null); final GameElement dynamicElement = cells[dynamicCellIndex]; assert (dynamicElement != null); final ConstantDirection dynamicDirection = dynamicCell.direction; cells[dynamicCellIndex] = null; final int staticCellIndex = calculateIndex(dynamicCellIndex, dynamicDirection); GameElement staticElement = cells[staticCellIndex]; if (staticElement == null) { // No collision or direction == STATIC doHandleNoCollision(dynamicCell, dynamicElement, staticCellIndex); return; } // Check if it collides with another dynamic element (remove it from collisions-list in case it does) ConstantDirection staticDirection = Direction.STATIC; boolean staticCollider = false; if (collisions.remove((Integer) staticCellIndex)) { // Check if staticElement collides with dynamicElement (directions are opposite) final DynamicCellContent staticCell = dynamicCells.get(staticCellIndex); staticDirection = staticCell.direction; if(staticDirection.reverse() != dynamicDirection) { doHandleCollision(collisions, staticCellIndex, levelGamePlay); // element can be moved by handling its collision, so determine element again staticElement = cells[staticCellIndex]; if (staticElement == null) { // Collision element moved so no collision doHandleNoCollision(dynamicCell, dynamicElement, staticCellIndex); return; } } else { staticCollider = true; } } // Determine collision type final ElementCollision dynamicCollision = levelGamePlay.determineElementCollision(dynamicElement, staticElement); final ElementCollision staticCollision = levelGamePlay.determineElementCollision(staticElement, dynamicElement); // Store information for dynamic-element ElementCollisionData dynamicElementCollisionData = ElementCollisionData.createInstance( Action.NONE, dynamicCellIndex, dynamicElement, dynamicDirection, dynamicCollision, true ); // Store information for collision-element ElementCollisionData staticElementCollisionData = ElementCollisionData.createInstance( Action.NONE, staticCellIndex, staticElement, staticDirection, staticCollision, staticCollider ); // Todo: improve way that classes are connected it is strange to use one of the collisions to call this general method ElementCollision.CollisionResult collisionResult = dynamicCollision.determineCollisionResult( dynamicElementCollisionData, staticElementCollisionData ); // Determine if static will be moved by collision final int nextStaticCellIndex = calculateIndex( staticCellIndex, collisionResult.getElement2Result().getRelativePosition() ); // Check if static moves if (nextStaticCellIndex != staticCellIndex) { // Static will move => // check if it moves to a cell that contains a dynamic-element if (collisions.remove((Integer) nextStaticCellIndex)) { // TODO: Issue5: what happens if the dynamic element did not move? doHandleCollision(collisions, nextStaticCellIndex, levelGamePlay); } } // TODO: determine ElementEffect based on CollisionResult final ElementEffect effect = levelGamePlay.determineElementEffect(dynamicCollision, dynamicElement, staticElement); // Handle collision // dynamic is already removed so no need to remove again removeElement(staticCellIndex); // TODO: add test for that position dynamic != static executeAddAfterCollision(staticCellIndex, collisionResult.getElement2Result()); executeAddAfterCollision(dynamicCellIndex, collisionResult.getElement1Result()); effect.execute(); } private static void doHandleNoCollision( final DynamicCellContent dynamicCell, final GameElement dynamicElement, final int nextDynamicCellIndex ) { cells[nextDynamicCellIndex] = dynamicElement; dynamicCells.put(nextDynamicCellIndex, dynamicCell); } private static void resize(final ConstantSize externalSize) { arraySize.set(externalSize.getWidth() + 2, externalSize.getHeight() + 2); createCells(); } private static void createCells() { cells = new GameElement[arraySize.getWidth() * arraySize.getHeight()]; dynamicCells.clear(); } private static void setTopLinePosition(final TopLinePosition inputTopLinePosition) { topLinePosition = inputTopLinePosition; switch (topLinePosition) { case NONE: renderCells = new RenderCellsTop(); break; case TOP: renderCells = new RenderCellsTop(); break; case BOTTOM: renderCells = new RenderCellsBottom(); break; case LEFT: renderCells = new RenderCellsLeft(); break; case RIGHT: renderCells = new RenderCellsRight(); break; default: throw new UnsupportedOperationException(); } } private static class DynamicCellContent { public DynamicCellContent(final ConstantDirection direction) { this.direction = direction; } public Field.ConstantDirection direction; } private static GameElement[] cells; private static Map<Integer, DynamicCellContent> dynamicCells = new TreeMap<>(); private static Size arraySize = new Size(0, 0); private static RenderCells renderCells; private static TopLinePosition topLinePosition; private static int topLine; private static int topLineSize; private static int maxTopLine; private static int frameCounter; // Hide constructor private Field() { } }
package net.tomp2p.rcon.prototype; import java.awt.Button; import java.awt.GridLayout; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; public class RconView { private JFrame frame = new JFrame(); private JPanel pane = new JPanel(); private Button sendMessageTestButton = new Button(); private Button sendDirectedMessageButton = new Button(); private Button sendDirectedNatPeerButton = new Button(); private Button permanentPeerConnectionButton = new Button(); private JTextField peerAddressField = new JTextField("my PeerAddress"); private JTextField ipField = new JTextField("192.168.10.146"); private JTextField idField = new JTextField("33"); public JFrame make() { frame.setResizable(true); makePanel(); frame.setVisible(true); return frame; } private void makePanel() { // sendMessageButton sendMessageTestButton.setEnabled(true); sendMessageTestButton.setLabel("sendTestMessage()"); peerAddressField.setToolTipText("My own PeerAddress"); peerAddressField.setEditable(false); peerAddressField.setEnabled(false); peerAddressField.setText(SimpleRconClient.getPeer().peerAddress().toString()); sendDirectedMessageButton.setEnabled(true); sendDirectedMessageButton.setLabel("sendDirectedMessage()"); sendDirectedNatPeerButton.setEnabled(true); sendDirectedNatPeerButton.setLabel("sendDirectedNatPeerMessage()"); permanentPeerConnectionButton.setEnabled(true); permanentPeerConnectionButton.setLabel("permanentPeerConnection()"); idField.setEditable(true); idField.setEnabled(true); ipField.setEditable(true); ipField.setEnabled(true); pane.setLayout(new GridLayout(7, 1)); pane.add(peerAddressField, 0); pane.add(sendMessageTestButton, 1); pane.add(ipField, 2); pane.add(idField, 3); pane.add(sendDirectedMessageButton, 4); pane.add(sendDirectedNatPeerButton, 5); pane.add(permanentPeerConnectionButton, 6); frame.add(pane); } public JFrame getJFrame() { return frame; } public Button getSendTestMessageButton() { return sendMessageTestButton; } public Button getSendDirectedMessageButton() { return sendDirectedMessageButton; } public Button getSendDirectedNatPeerButton() { return sendDirectedNatPeerButton; } public Button getPermanentPeerConnectionButton() { return permanentPeerConnectionButton; } public JTextField getPeerAddressField() { return peerAddressField; } public JTextField getIpField() { return ipField; } public JTextField getIdField() { return idField; } }
package com.staticiser.jetson; import com.staticiser.jetson.TestService.TestObject; import com.staticiser.jetson.exception.RPCException; import java.io.IOException; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.junit.Assert; import org.junit.Test; import static org.junit.Assert.fail; public class NormalOperationTest extends AbstractTest { public NormalOperationTest(final ClientFactory<TestService> client_factory, final ServerFactory<TestService> server_factory) { super(client_factory, server_factory); } // public static void main(final String[] args) throws Exception { // final NormalOperationTest t = new NormalOperationTest(); // t.setUp(); // int i = 0; // try { // while (!Thread.currentThread().isInterrupted()) { // t.startJsonRpcTestServer().expose(); // } finally { // System.out.println("NUMBER OF SERVERS: " + i); @Test public void testConcatenate() throws RPCException { final String text = "some text"; final int integer = 8852456; final TestObject object = new TestObject("X_1_23"); final char character = '='; final String result = client.concatenate(text, integer, object, character); Assert.assertEquals(text + integer + object + character, result); } @Test // @Ignore public void testConcurrentClients() throws RPCException, InterruptedException, ExecutionException { final ExecutorService executor = Executors.newFixedThreadPool(100); try { final CountDownLatch start_latch = new CountDownLatch(1); final List<Future<Void>> future_concurrent_tests = new ArrayList<Future<Void>>(); for (int i = 0; i < 100; i++) { future_concurrent_tests.add(executor.submit(new Callable<Void>() { @Override public Void call() throws Exception { start_latch.await(); testAdd(); testAddOnRemote(); testDoVoidWithNoParams(); testGetObject(); testGetObjectOnRemote(); testSay65535(); testSayFalse(); testSayFalseOnRemote(); testSayMinus65535(); testSaySomething(); testSayTrue(); testThrowException(); testThrowExceptionOnRemote(); return null; } })); } start_latch.countDown(); for (final Future<Void> f : future_concurrent_tests) { f.get(); } } finally { executor.shutdown(); } } @Test public void testGetObjectOnRemote() throws IOException { Assert.assertEquals(NormalOperationTestService.TEST_OBJECT_MESSAGE, client.getObjectOnRemote(temp_server_port).getMessage()); } @Test public void testSayFalseOnRemote() throws IOException { final Boolean _false = client.sayFalseOnRemote(temp_server_port); Assert.assertFalse(_false); } @Test public void testGetObject() throws RPCException { Assert.assertEquals(NormalOperationTestService.TEST_OBJECT_MESSAGE, client.getObject().getMessage()); } @Test public void testAddOnRemote() throws RPCException { testAddOnRemoteClient(client); } @Test public void testAdd() throws RPCException { testAddOnClient(client); } @Test public void testThrowExceptionOnRemote() { try { client.throwExceptionOnRemote(temp_server_port); fail("expected exception"); } catch (final Exception e) { Assert.assertEquals(NormalOperationTestService.TEST_EXCEPTION.getClass(), e.getClass()); Assert.assertEquals(NormalOperationTestService.TEST_EXCEPTION.getMessage(), e.getMessage()); } } @Test public void testThrowException() { try { client.throwException(); fail("expected exception"); } catch (final Exception e) { Assert.assertEquals(NormalOperationTestService.TEST_EXCEPTION.getClass(), e.getClass()); Assert.assertEquals(NormalOperationTestService.TEST_EXCEPTION.getMessage(), e.getMessage()); } } @Test public void testSayFalse() throws RPCException { final Boolean _false = client.sayFalse(); Assert.assertFalse(_false); } @Test public void testSayTrue() throws RPCException { final Boolean _true = client.sayTrue(); Assert.assertTrue(_true); } @Test public void testSayMinus65535() throws RPCException { final Integer minus65535 = client.sayMinus65535(); Assert.assertEquals(new Integer(-65535), minus65535); } @Test public void testSay65535() throws RPCException { final Integer _65535 = client.say65535(); Assert.assertEquals(new Integer(65535), _65535); } @Test public void testSaySomething() throws RPCException { final String something = client.saySomething(); Assert.assertEquals("something", something); } @Test public void testDoVoidWithNoParams() throws RPCException { client.doVoidWithNoParams(); } @Test // @Ignore public void testConcurrentServers() throws RPCException, InterruptedException, ExecutionException { final ExecutorService executor = Executors.newFixedThreadPool(100); try { final CountDownLatch start_latch = new CountDownLatch(1); final List<Future<Void>> future_concurrent_tests = new ArrayList<Future<Void>>(); for (int i = 0; i < 100; i++) { future_concurrent_tests.add(executor.submit(new Callable<Void>() { @Override public Void call() throws Exception { start_latch.await(); final Server server = startJsonRpcTestServer(); final InetSocketAddress server_address = server.getLocalSocketAddress(); final TestService client = client_factory.get(server_address); try { testAddOnClient(client); testAddOnRemoteClient(client); } finally { server.unexpose(); } return null; } })); } start_latch.countDown(); for (final Future<Void> f : future_concurrent_tests) { f.get(); } } finally { executor.shutdown(); } } private void testAddOnRemoteClient(final TestService client) throws RPCException { final Integer three = client.addOnRemote(1, 2, temp_server_port); Assert.assertEquals(new Integer(1 + 2), three); final Integer eleven = client.addOnRemote(12, -1, temp_server_port); Assert.assertEquals(new Integer(12 + -1), eleven); final Integer fifty_one = client.addOnRemote(-61, 112, temp_server_port); Assert.assertEquals(new Integer(-61 + 112), fifty_one); final Integer minus_seven = client.addOnRemote(-4, -3, temp_server_port); Assert.assertEquals(new Integer(-4 + -3), minus_seven); } private void testAddOnClient(final TestService client) throws RPCException { //TODO test null final Integer three = client.add(1, 2); Assert.assertEquals(new Integer(1 + 2), three); final Integer eleven = client.add(12, -1); Assert.assertEquals(new Integer(12 + -1), eleven); final Integer fifty_one = client.add(-61, 112); Assert.assertEquals(new Integer(-61 + 112), fifty_one); final Integer minus_seven = client.add(-4, -3); Assert.assertEquals(new Integer(-4 + -3), minus_seven); } @Override protected TestService getService() { return new NormalOperationTestService(client_factory); } }
package org.nakedobjects.distribution; import org.nakedobjects.NakedObjects; import org.nakedobjects.object.DirtyObjectSet; import org.nakedobjects.object.Naked; import org.nakedobjects.object.NakedObject; import org.nakedobjects.object.NakedObjectSpecification; import org.nakedobjects.object.persistence.Oid; import org.nakedobjects.object.reflect.NakedObjectAssociation; import org.nakedobjects.object.reflect.NakedObjectField; import org.nakedobjects.object.reflect.OneToManyAssociation; import org.nakedobjects.object.reflect.OneToOneAssociation; import org.nakedobjects.object.reflect.PojoAdapterFactory; import org.nakedobjects.object.reflect.ReflectiveActionException; public class DataHelper { public static Naked recreate(Data data) { if(data instanceof ValueData) { return recreateValue((ValueData) data); } else { return recreateObject((ObjectData) data); } } private static Naked recreateValue(ValueData valueData) { Naked value = NakedObjects.getPojoAdapterFactory().createAdapter(valueData.getValue()); return value; } public static NakedObject recreateObject(ObjectData data) { Oid oid = data.getOid(); String type = data.getType(); NakedObject object; if (oid != null && loadedObjects().isLoaded(oid)) { object = loadedObjects().getLoadedObject(oid); } else { NakedObjectSpecification specification = NakedObjects.getSpecificationLoader().loadSpecification(type); object = (NakedObject) specification.acquireInstance(); if (oid != null) { object.setOid(oid); loadedObjects().loaded(object); } } if(data.isResolved() && ! object.isResolved()) { object.setResolved(); } recreateObjectsInFields(data, object); return object; } private static void recreateObjectsInFields(ObjectData data, NakedObject object) { Object[] fieldContent = data.getFieldContent(); if (fieldContent != null && fieldContent.length > 0) { NakedObjectField[] fields = object.getSpecification().getFields(); for (int i = 0; i < fields.length; i++) { if (fields[i].isCollection()) { if (fieldContent[i] != null) { ObjectData collection = (ObjectData) fieldContent[i]; NakedObject[] instances = new NakedObject[collection.getFieldContent().length]; for (int j = 0; j < instances.length; j++) { instances[j] = (NakedObject) recreateObject(((ObjectData) collection.getFieldContent()[j])); } object.initOneToManyAssociation((OneToManyAssociation) fields[i], instances); } } else if (fields[i].isValue()) { object.initValue((OneToOneAssociation) fields[i], fieldContent[i]); } else { if (fieldContent[i] != null) { NakedObjectAssociation field = (NakedObjectAssociation) fields[i]; NakedObject value = (NakedObject) recreateObject(((ObjectData) fieldContent[i])); object.initAssociation(field, value); } } } } } public static void update(ObjectData data, DirtyObjectSet updateNotifier) { Oid oid = data.getOid(); Object[] fieldContent = data.getFieldContent(); String type = data.getType(); NakedObject object; if (oid != null && loadedObjects().isLoaded(oid)) { object = loadedObjects().getLoadedObject(oid); } else { NakedObjectSpecification specification = NakedObjects.getSpecificationLoader().loadSpecification(type); object = (NakedObject) specification.acquireInstance(); if (oid != null) { object.setOid(oid); loadedObjects().loaded(object); } } if (!object.isResolved() && data.isResolved()){ object.setResolved(); } NakedObjectField[] fields = object.getSpecification().getFields(); if (fields.length > 0) { for (int i = 0; i < fields.length; i++) { if (fields[i].isCollection()) { if (fieldContent[i] != null) { ObjectData collection = (ObjectData) fieldContent[i]; Object[] elements = collection.getFieldContent(); NakedObject[] instances = new NakedObject[elements.length]; for (int j = 0; j < instances.length; j++) { NakedObject instance = recreateObject((ObjectData) elements[j]); instances[j] = instance; } object.initOneToManyAssociation((OneToManyAssociation) fields[i], instances); } } else if (fields[i].isValue()) { object.initValue((OneToOneAssociation) fields[i], fieldContent[i]); } else { if (fieldContent[i] != null) { NakedObject field = recreateObject((ObjectData) fieldContent[i]); object.initAssociation((NakedObjectAssociation) fields[i], field); } } } } updateNotifier.addDirty(object); } private static PojoAdapterFactory loadedObjects() { return NakedObjects.getPojoAdapterFactory(); } public static void throwRemoteException(ExceptionData data) throws ReflectiveActionException { throw new NakedObjectsRemoteException(data.getType(), data.getMessage(), data.getStackTrace()); } }
package edu.hm.hafner.analysis; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.nio.file.Path; import java.nio.file.Paths; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.Test; import edu.hm.hafner.analysis.ModuleDetector.FileSystem; import edu.hm.hafner.util.PathUtil; import edu.hm.hafner.util.ResourceTest; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import static org.assertj.core.api.Assertions.*; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.*; /** * Tests the class {@link ModuleDetector}. */ @SuppressFBWarnings("DMI") class ModuleDetectorTest extends ResourceTest { private static final String MANIFEST = "MANIFEST.MF"; private static final String MANIFEST_NAME = "MANIFEST-NAME.MF"; private static final Path ROOT = Paths.get(File.pathSeparatorChar == ';' ? "C:\\Windows" : "/tmp"); private static final String PREFIX = new PathUtil().getAbsolutePath(ROOT) + "/"; private static final int NO_RESULT = 0; private static final String PATH_PREFIX_MAVEN = "path/to/maven/"; private static final String PATH_PREFIX_OSGI = "path/to/osgi/"; private static final String PATH_PREFIX_ANT = "path/to/ant/"; private static final String PATH_PREFIX_GRADLE = "path/to/gradle/"; private static final String EXPECTED_MAVEN_MODULE = "ADT Business Logic"; private static final String EXPECTED_ANT_MODULE = "checkstyle"; private static final String EXPECTED_OSGI_MODULE = "de.faktorlogik.prototyp"; private static final String EXPECTED_GRADLE_MODULE_ROOT_BY_PATH = "gradle"; private static final String EXPECTED_GRADLE_MODULE_ROOT = "root-project"; private static final String EXPECTED_GRADLE_MODULE_A = "a-module"; private static final String EXPECTED_GRADLE_MODULE_B = "moduleB"; private InputStream read(final String fileName) { return asInputStream(fileName); } @Test void shouldIdentifyModuleByReadingOsgiBundle() { FileSystem factory = createFileSystemStub(stub -> { when(stub.find(any(), anyString())).thenReturn(new String[]{PATH_PREFIX_OSGI + ModuleDetector.OSGI_BUNDLE}); when(stub.open(anyString())).thenReturn(read(MANIFEST)); }); ModuleDetector detector = new ModuleDetector(ROOT, factory); assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_OSGI + "something.txt"))) .isEqualTo(EXPECTED_OSGI_MODULE); assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_OSGI + "in/between/something.txt"))) .isEqualTo(EXPECTED_OSGI_MODULE); assertThat(detector.guessModuleName(PREFIX + "path/to/something.txt")) .isEqualTo(StringUtils.EMPTY); } @Test void shouldIdentifyModuleByReadingOsgiBundleWithVendorInL10nProperties() { FileSystem factory = createFileSystemStub(stub -> { when(stub.find(any(), anyString())).thenReturn(new String[]{PATH_PREFIX_OSGI + ModuleDetector.OSGI_BUNDLE}); when(stub.open(anyString())).thenReturn(read(MANIFEST), read("l10n.properties")); }); ModuleDetector detector = new ModuleDetector(ROOT, factory); String expectedName = "de.faktorlogik.prototyp (My Vendor)"; assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_OSGI + "something.txt"))) .isEqualTo(expectedName); assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_OSGI + "in/between/something.txt"))) .isEqualTo(expectedName); assertThat(detector.guessModuleName(PREFIX + "path/to/something.txt")) .isEqualTo(StringUtils.EMPTY); } @Test void shouldIdentifyModuleByReadingOsgiBundleWithManifestName() { FileSystem fileSystem = createFileSystemStub(stub -> { when(stub.find(any(), anyString())).thenReturn( new String[]{PATH_PREFIX_OSGI + ModuleDetector.OSGI_BUNDLE}); when(stub.open(anyString())).thenReturn(read(MANIFEST_NAME), read("l10n.properties")); }); ModuleDetector detector = new ModuleDetector(ROOT, fileSystem); String expectedName = "My Bundle"; assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_OSGI + "something.txt"))) .isEqualTo(expectedName); assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_OSGI + "in/between/something.txt"))) .isEqualTo(expectedName); assertThat(detector.guessModuleName(PREFIX + "path/to/something.txt")) .isEqualTo(StringUtils.EMPTY); } @Test void shouldIdentifyModuleByReadingMavenPom() { FileSystem factory = createFileSystemStub(stub -> { when(stub.find(any(), anyString())).thenReturn( new String[]{PATH_PREFIX_MAVEN + ModuleDetector.MAVEN_POM}); when(stub.open(anyString())).thenAnswer(fileName -> read(ModuleDetector.MAVEN_POM)); }); ModuleDetector detector = new ModuleDetector(ROOT, factory); assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_MAVEN + "something.txt"))).isEqualTo( EXPECTED_MAVEN_MODULE); assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_MAVEN + "in/between/something.txt"))).isEqualTo( EXPECTED_MAVEN_MODULE); assertThat(detector.guessModuleName(PREFIX + "path/to/something.txt")).isEqualTo(StringUtils.EMPTY); } @Test void shouldIdentifyModuleByReadingMavenPomWithoutName() { FileSystem factory = createFileSystemStub(stub -> { when(stub.find(any(), anyString())).thenReturn(new String[]{PATH_PREFIX_MAVEN + ModuleDetector.MAVEN_POM}); when(stub.open(anyString())).thenAnswer(filename -> read("no-name-pom.xml")); }); ModuleDetector detector = new ModuleDetector(ROOT, factory); String artifactId = "com.avaloq.adt.core"; assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_MAVEN + "something.txt"))) .isEqualTo(artifactId); assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_MAVEN + "in/between/something.txt"))) .isEqualTo(artifactId); assertThat(detector.guessModuleName(PREFIX + "path/to/something.txt")) .isEqualTo(StringUtils.EMPTY); } @Test void shouldIdentifyModuleByReadingGradlePath() { FileSystem factory = createFileSystemStub(stub -> { when(stub.find(any(), anyString())).thenReturn( new String[] {PATH_PREFIX_GRADLE + ModuleDetector.BUILD_GRADLE}); }); ModuleDetector detector = new ModuleDetector(ROOT, factory); assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_GRADLE + "build/reports/something.txt"))) .isEqualTo(EXPECTED_GRADLE_MODULE_ROOT_BY_PATH); assertThat(detector.guessModuleName(PREFIX + "build/reports/something.txt")) .isEqualTo(StringUtils.EMPTY); } @Test void shouldIdentifyModuleByFindingClosestGradlePath() { FileSystem factory = createFileSystemStub(stub -> { when(stub.find(any(), anyString())).thenReturn(new String[] { PATH_PREFIX_GRADLE + ModuleDetector.BUILD_GRADLE, PATH_PREFIX_GRADLE + "moduleB/" + ModuleDetector.BUILD_GRADLE, PATH_PREFIX_GRADLE + "a-module/" + ModuleDetector.BUILD_GRADLE, }); }); ModuleDetector detector = new ModuleDetector(ROOT, factory); String gradleWorkspace = PREFIX + PATH_PREFIX_GRADLE; assertThat(detector.guessModuleName( gradleWorkspace + "a-module/build/reports/something.txt")) .isEqualTo(EXPECTED_GRADLE_MODULE_A); assertThat(detector.guessModuleName( gradleWorkspace + "moduleB/build/reports/something.txt")) .isEqualTo(EXPECTED_GRADLE_MODULE_B); assertThat(detector.guessModuleName(gradleWorkspace + "build/reports/something.txt")) .isEqualTo(EXPECTED_GRADLE_MODULE_ROOT_BY_PATH); assertThat(detector.guessModuleName(PREFIX + "build/reports/something.txt")) .isEqualTo(StringUtils.EMPTY); } @Test void shouldIdentifyModuleByReadingGradleKtsPath() { FileSystem factory = createFileSystemStub(stub -> { when(stub.find(any(), anyString())).thenReturn( new String[] {PATH_PREFIX_GRADLE + ModuleDetector.BUILD_GRADLE_KTS}); }); ModuleDetector detector = new ModuleDetector(ROOT, factory); assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_GRADLE + "build/reports/something.txt"))) .isEqualTo(EXPECTED_GRADLE_MODULE_ROOT_BY_PATH); assertThat(detector.guessModuleName(PREFIX + "build/reports/something.txt")) .isEqualTo(StringUtils.EMPTY); } @Test void shouldIdentifyModuleByReadingGradleSettings() { FileSystem factory = createFileSystemStub(stub -> { when(stub.find(any(), anyString())).thenReturn(new String[] { PATH_PREFIX_GRADLE + ModuleDetector.SETTINGS_GRADLE, PATH_PREFIX_GRADLE + "moduleB/" + ModuleDetector.BUILD_GRADLE, PATH_PREFIX_GRADLE + "a-module/" + ModuleDetector.BUILD_GRADLE, }); when(stub.open(anyString())).thenAnswer(filename -> read("settings-1.gradle")); }); ModuleDetector detector = new ModuleDetector(ROOT, factory); String gradleWorkspace = PREFIX + PATH_PREFIX_GRADLE; assertThat(detector.guessModuleName( gradleWorkspace + "a-module/build/reports/something.txt")) .isEqualTo(EXPECTED_GRADLE_MODULE_A); assertThat(detector.guessModuleName( gradleWorkspace + "moduleB/build/reports/something.txt")) .isEqualTo(EXPECTED_GRADLE_MODULE_B); assertThat(detector.guessModuleName(gradleWorkspace + "build/reports/something.txt")) .isEqualTo(EXPECTED_GRADLE_MODULE_ROOT); assertThat(detector.guessModuleName(PREFIX + "build/reports/something.txt")) .isEqualTo(StringUtils.EMPTY); } @Test void shouldIdentifyModuleByReadingGradleSettingsKts() { FileSystem factory = createFileSystemStub(stub -> { when(stub.find(any(), anyString())).thenReturn(new String[] { PATH_PREFIX_GRADLE + ModuleDetector.SETTINGS_GRADLE_KTS, }); when(stub.open(anyString())).thenAnswer(filename -> read("settings-1.gradle")); }); ModuleDetector detector = new ModuleDetector(ROOT, factory); String gradleWorkspace = PREFIX + PATH_PREFIX_GRADLE; assertThat(detector.guessModuleName(gradleWorkspace + "build/reports/something.txt")) .isEqualTo(EXPECTED_GRADLE_MODULE_ROOT); assertThat(detector.guessModuleName(PREFIX + "build/reports/something.txt")) .isEqualTo(StringUtils.EMPTY); } @Test void shouldEnsureThatGradleSettingsHasPrecedenceOverRootBuild() { FileSystem factory = createFileSystemStub(stub -> { when(stub.find(any(), anyString())).thenReturn(new String[] { PATH_PREFIX_GRADLE + ModuleDetector.BUILD_GRADLE, PATH_PREFIX_GRADLE + ModuleDetector.SETTINGS_GRADLE, PATH_PREFIX_GRADLE + "moduleB/" + ModuleDetector.BUILD_GRADLE, PATH_PREFIX_GRADLE + "a-module/" + ModuleDetector.BUILD_GRADLE, }); when(stub.open(anyString())).thenAnswer(filename -> read("settings-1.gradle")); }); ModuleDetector detector = new ModuleDetector(ROOT, factory); String gradleWorkspace = PREFIX + PATH_PREFIX_GRADLE; assertThat(detector.guessModuleName( gradleWorkspace + "a-module/build/reports/something.txt")) .isEqualTo(EXPECTED_GRADLE_MODULE_A); assertThat(detector.guessModuleName( gradleWorkspace + "moduleB/build/reports/something.txt")) .isEqualTo(EXPECTED_GRADLE_MODULE_B); assertThat(detector.guessModuleName(gradleWorkspace + "build/reports/something.txt")) .isEqualTo(EXPECTED_GRADLE_MODULE_ROOT); assertThat(detector.guessModuleName(PREFIX + "build/reports/something.txt")) .isEqualTo(StringUtils.EMPTY); } @Test void shouldEnsureThatGradleSettingsCanParseFormat1() throws IOException { FileSystem factory = createFileSystemStub(stub -> { when(stub.find(any(), anyString())).thenReturn(new String[] { PATH_PREFIX_GRADLE + ModuleDetector.SETTINGS_GRADLE, }); when(stub.open(anyString())).thenAnswer(fileName -> read("settings-1.gradle")); }); String gradleWorkspace = PREFIX + PATH_PREFIX_GRADLE; ModuleDetector detector = new ModuleDetector(ROOT, factory); assertThat(detector.guessModuleName(gradleWorkspace + "build/reports/something.txt")) .isEqualTo(EXPECTED_GRADLE_MODULE_ROOT); } @Test void shouldEnsureThatGradleSettingsCanParseFormat2() throws IOException { FileSystem factory = createFileSystemStub(stub -> { when(stub.find(any(), anyString())).thenReturn(new String[] { PATH_PREFIX_GRADLE + ModuleDetector.SETTINGS_GRADLE, }); when(stub.open(anyString())).thenAnswer(fileName -> read("settings-2.gradle")); }); String gradleWorkspace = PREFIX + PATH_PREFIX_GRADLE; ModuleDetector detector = new ModuleDetector(ROOT, factory); assertThat(detector.guessModuleName(gradleWorkspace + "build/reports/something.txt")) .isEqualTo("root-project-2"); } @Test void shouldEnsureThatGradleSettingsCanParseFormat3() throws IOException { FileSystem factory = createFileSystemStub(stub -> { when(stub.find(any(), anyString())).thenReturn(new String[] { PATH_PREFIX_GRADLE + ModuleDetector.SETTINGS_GRADLE, }); when(stub.open(anyString())).thenAnswer(fileName -> read("settings-3.gradle")); }); String gradleWorkspace = PREFIX + PATH_PREFIX_GRADLE; ModuleDetector detector = new ModuleDetector(ROOT, factory); assertThat(detector.guessModuleName(gradleWorkspace + "build/reports/something.txt")) .isEqualTo("root-project-3"); } @Test void shouldEnsureThatGradleSettingsCanParseFormat4() throws IOException { FileSystem factory = createFileSystemStub(stub -> { when(stub.find(any(), anyString())).thenReturn(new String[] { PATH_PREFIX_GRADLE + ModuleDetector.SETTINGS_GRADLE, }); when(stub.open(anyString())).thenAnswer(fileName -> read("settings-4.gradle")); }); String gradleWorkspace = PREFIX + PATH_PREFIX_GRADLE; ModuleDetector detector = new ModuleDetector(ROOT, factory); assertThat(detector.guessModuleName(gradleWorkspace + "build/reports/something.txt")) .isEqualTo("root-project-4"); } @Test void shouldIgnoreGradleSettingsWithoutProjectName() { FileSystem factory = createFileSystemStub(stub -> { when(stub.find(any(), anyString())).thenReturn(new String[] { PATH_PREFIX_GRADLE + ModuleDetector.BUILD_GRADLE, PATH_PREFIX_GRADLE + ModuleDetector.SETTINGS_GRADLE, }); when(stub.open(anyString())).thenAnswer(fileName -> read("settings-5.gradle")); }); String gradleWorkspace = PREFIX + PATH_PREFIX_GRADLE; ModuleDetector detector = new ModuleDetector(ROOT, factory); assertThat(detector.guessModuleName(gradleWorkspace + "build/reports/something.txt")) .isEqualTo(EXPECTED_GRADLE_MODULE_ROOT_BY_PATH); } @Test void shouldIdentifyModuleByReadingAntProjectFile() { FileSystem factory = createFileSystemStub(stub -> { when(stub.find(any(), anyString())).thenReturn(new String[]{PATH_PREFIX_ANT + ModuleDetector.ANT_PROJECT}); when(stub.open(anyString())).thenAnswer(filename -> read(ModuleDetector.ANT_PROJECT)); }); ModuleDetector detector = new ModuleDetector(ROOT, factory); assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_ANT + "something.txt"))) .isEqualTo(EXPECTED_ANT_MODULE); assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_ANT + "in/between/something.txt"))) .isEqualTo(EXPECTED_ANT_MODULE); assertThat(detector.guessModuleName(PREFIX + "path/to/something.txt")) .isEqualTo(StringUtils.EMPTY); } @Test void shouldIgnoreExceptionsDuringParsing() { FileSystem fileSystem = createFileSystemStub(stub -> { when(stub.find(any(), anyString())).thenReturn(new String[]{ PATH_PREFIX_ANT + ModuleDetector.ANT_PROJECT, PATH_PREFIX_MAVEN + ModuleDetector.MAVEN_POM, PATH_PREFIX_OSGI + ModuleDetector.OSGI_BUNDLE, PATH_PREFIX_GRADLE + ModuleDetector.SETTINGS_GRADLE }); when(stub.open(anyString())).thenThrow(new FileNotFoundException("File not found")); }); ModuleDetector detector = new ModuleDetector(ROOT, fileSystem); assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_ANT + "something.txt"))) .isEqualTo(StringUtils.EMPTY); assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_MAVEN + "something.txt"))) .isEqualTo(StringUtils.EMPTY); assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_OSGI + "something.txt"))) .isEqualTo(StringUtils.EMPTY); assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_GRADLE + "build/reports/something.txt"))) .isEqualTo(StringUtils.EMPTY); } @Test void shouldIdentifyModuleIfThereAreMoreEntries() { FileSystem factory = createFileSystemStub(stub -> { String ant = PATH_PREFIX_ANT + ModuleDetector.ANT_PROJECT; String maven = PATH_PREFIX_MAVEN + ModuleDetector.MAVEN_POM; when(stub.find(any(), anyString())).thenReturn(new String[]{ant, maven}); when(stub.open(PREFIX + ant)).thenReturn(read(ModuleDetector.ANT_PROJECT)); when(stub.open(PREFIX + maven)).thenAnswer(filename -> read(ModuleDetector.MAVEN_POM)); }); ModuleDetector detector = new ModuleDetector(ROOT, factory); assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_ANT + "something.txt"))) .isEqualTo(EXPECTED_ANT_MODULE); assertThat(detector.guessModuleName(PREFIX + (PATH_PREFIX_MAVEN + "something.txt"))) .isEqualTo(EXPECTED_MAVEN_MODULE); } @Test void shouldEnsureThatMavenHasPrecedenceOverAnt() { String prefix = "/prefix/"; String ant = prefix + ModuleDetector.ANT_PROJECT; String maven = prefix + ModuleDetector.MAVEN_POM; verifyOrder(prefix, ant, maven, new String[]{ant, maven}); verifyOrder(prefix, ant, maven, new String[]{maven, ant}); } @Test void shouldEnsureThatOsgiHasPrecedenceOverMavenAndAnt() { String prefix = "/prefix/"; String ant = prefix + ModuleDetector.ANT_PROJECT; String maven = prefix + ModuleDetector.MAVEN_POM; String osgi = prefix + ModuleDetector.OSGI_BUNDLE; verifyOrder(prefix, ant, maven, osgi, ant, maven, osgi); verifyOrder(prefix, ant, maven, osgi, ant, osgi, maven); verifyOrder(prefix, ant, maven, osgi, maven, ant, osgi); verifyOrder(prefix, ant, maven, osgi, maven, osgi, ant); verifyOrder(prefix, ant, maven, osgi, osgi, ant, maven); verifyOrder(prefix, ant, maven, osgi, osgi, maven, osgi); } @SuppressWarnings("PMD.UseVarargs") private void verifyOrder(final String prefix, final String ant, final String maven, final String[] foundFiles) { FileSystem factory = createFileSystemStub(stub -> { when(stub.find(any(), anyString())).thenReturn(foundFiles); when(stub.open(ant)).thenReturn(read(ModuleDetector.ANT_PROJECT)); when(stub.open(maven)).thenAnswer(filename -> read(ModuleDetector.MAVEN_POM)); }); ModuleDetector detector = new ModuleDetector(ROOT, factory); assertThat(detector.guessModuleName(prefix + "something.txt")).isEqualTo(EXPECTED_MAVEN_MODULE); } private void verifyOrder(final String prefix, final String ant, final String maven, final String osgi, final String... foundFiles) { FileSystem fileSystem = createFileSystemStub(stub -> { when(stub.find(any(), anyString())).thenReturn(foundFiles); when(stub.open(ant)).thenAnswer(filename -> read(ModuleDetector.ANT_PROJECT)); when(stub.open(maven)).thenAnswer(filename -> read(ModuleDetector.MAVEN_POM)); when(stub.open(osgi)).thenAnswer(filename -> read(MANIFEST)); when(stub.open(prefix + "/" + ModuleDetector.PLUGIN_PROPERTIES)).thenAnswer(filename -> createEmptyStream()); when(stub.open(prefix + "/" + ModuleDetector.BUNDLE_PROPERTIES)).thenAnswer(filename -> createEmptyStream()); }); ModuleDetector detector = new ModuleDetector(ROOT, fileSystem); assertThat(detector.guessModuleName(prefix + "something.txt")).isEqualTo(EXPECTED_OSGI_MODULE); } private InputStream createEmptyStream() { try { return IOUtils.toInputStream("", "UTF-8"); } catch (IOException e) { throw new AssertionError(e); } } private FileSystem createFileSystemStub(final Stub stub) { try { FileSystem fileSystem = mock(FileSystem.class); stub.apply(fileSystem); return fileSystem; } catch (IOException exception) { throw new AssertionError(exception); } } /** * Stubs the {@link PackageDetectors.FileSystem} using a lambda. */ @FunctionalInterface private interface Stub { void apply(FileSystem f) throws IOException; } }
package net.openhft.chronicle.map; import net.openhft.lang.model.DataValueClasses; import net.openhft.lang.values.*; import org.junit.Ignore; import org.junit.Test; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.ExecutionException; import static org.junit.Assert.*; /** * This test enumerates common usecases for keys and values. */ // TODO Test for persisted map. // TODO Test for stateless map. public class CHMUseCasesTest { /** * String is not as efficient as CharSequence as a key or value but easier to use The key can only be on heap and * variable length serialised. */ @Test @Ignore public void testStringStringMap() throws ExecutionException, InterruptedException { /* TODO run the same test for multiple types of map stores for(ChronicleMapBuilder<String, String> chmb : Arrays.asList( ChronicleMapBuilder.of(String.class, String.class), ChronicleMapBuilder.of(String.class, String.class).file(TMP_FILE), ChronicleMapBuilder.of(String.class, String.class).statelessClient(CONFIG) )) { try (ChronicleMap<String, String> map = chmb.create()) { */ try (ChronicleMap<String, String> map = ChronicleMapBuilder .of(String.class, String.class) // TODO .checkSerializedValues() .create()) { map.put("Hello", "World"); assertEquals("World", map.get("Hello")); assertEquals("New World", map.mapForKey("Hello", new Function<String, String>() { @Override public String apply(String s) { return "New " + s; } })); assertEquals(null, map.mapForKey("No key", new Function<String, String>() { @Override public String apply(String s) { return "New " + s; } })); try { map.updateForKey("Hello", new Mutator<String, String>() { @Override public String update(String s) { return "New " + s; } }); fail("Operation not supported as value is not mutable"); } catch (Exception ignored) { // TODO replace with the specific exception. } assertEquals(null, map.putLater("Bye", "For now").get()); assertEquals("For now", map.getLater("Bye").get()); assertEquals("For now", map.removeLater("Bye").get()); assertEquals(null, map.removeLater("Bye").get()); } } /** * CharSequence is more efficient when object creation is avoided. The key can only be on heap and variable length * serialised. */ @Test @Ignore public void testCharSequenceCharSequenceMap() throws ExecutionException, InterruptedException { try (ChronicleMap<CharSequence, CharSequence> map = ChronicleMapBuilder .of(CharSequence.class, CharSequence.class) .create()) { map.put("Hello", "World"); StringBuilder key = new StringBuilder(); key.append("key-").append(1); StringBuilder value = new StringBuilder(); value.append("value-").append(1); map.put(key, value); assertEquals("value-1", map.get("key-1")); assertEquals(value, map.getUsing(key, value)); assertEquals("value-1", value.toString()); map.remove("key-1"); assertNull(map.getUsing(key, value)); map.close(); assertEquals("New World", map.mapForKey("Hello", new Function<CharSequence, CharSequence>() { @Override public CharSequence apply(CharSequence s) { return "New " + s; } })); assertEquals(null, map.mapForKey("No key", new Function<CharSequence, CharSequence>() { @Override public CharSequence apply(CharSequence s) { return "New " + s; } })); assertEquals("New World !!", map.updateForKey("Hello", new Mutator<CharSequence, CharSequence>() { @Override public CharSequence update(CharSequence s) { ((StringBuilder) s).append("!!"); return "New " + s; } })); assertEquals("New World !!", map.get("Hello").toString()); assertEquals(null, map.updateForKey("no-key", new Mutator<CharSequence, CharSequence>() { @Override public CharSequence update(CharSequence s) { ((StringBuilder) s).append("!!"); return "New " + s; } })); assertEquals(null, map.putLater("Bye", "For now").get()); assertEquals("For now", map.getLater("Bye").get().toString()); assertEquals("For now", map.removeLater("Bye").get().toString()); assertEquals(null, map.removeLater("Bye").get()); } } /** * StringValue represents any bean which contains a String Value */ @Test @Ignore public void testStringValueStringValueMap() { try (ChronicleMap<StringValue, StringValue> map = ChronicleMapBuilder .of(StringValue.class, StringValue.class) .create()) { StringValue key1 = DataValueClasses.newDirectInstance(StringValue.class); StringValue key2 = DataValueClasses.newInstance(StringValue.class); StringValue value1 = DataValueClasses.newDirectInstance(StringValue.class); StringValue value2 = DataValueClasses.newInstance(StringValue.class); key1.setValue(new StringBuilder("1")); value1.setValue("11"); map.put(key1, value1); assertEquals(value1, map.get(key1)); key2.setValue("2"); value2.setValue(new StringBuilder("22")); map.put(key2, value2); assertEquals(value2, map.get(key2)); StringBuilder sb = new StringBuilder(); try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertTrue(rc.present()); assertEquals("11", value1.getValue()); value1.getUsingValue(sb); assertEquals("11", sb.toString()); } try (ReadContext rc = map.getUsingLocked(key2, value1)) { assertTrue(rc.present()); assertEquals("22", value2.getValue()); value2.getUsingValue(sb); assertEquals("22", sb.toString()); } try (ReadContext rc = map.getUsingLocked(key1, value2)) { assertTrue(rc.present()); assertEquals("11", value2.getValue()); value2.getUsingValue(sb); assertEquals("11", sb.toString()); } try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertTrue(rc.present()); assertEquals("22", value2.getValue()); value2.getUsingValue(sb); assertEquals("22", sb.toString()); } key1.setValue("3"); try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertFalse(rc.present()); } key2.setValue("4"); try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertFalse(rc.present()); } try (WriteContext wc = map.acquireUsingLocked(key1, value1)) { assertEquals("", value1.getValue()); value1.getUsingValue(sb); assertEquals("", sb.toString()); sb.append(123); value1.setValue(sb); } try (WriteContext wc = map.acquireUsingLocked(key1, value2)) { assertEquals("123", value2.getValue()); value2.setValue(value2.getValue() + '4'); assertEquals("1234", value2.getValue()); } try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertTrue(rc.present()); assertEquals("1234", value1.getValue()); } try (WriteContext wc = map.acquireUsingLocked(key2, value2)) { assertEquals("", value2.getValue()); value2.getUsingValue(sb); assertEquals("", sb.toString()); sb.append(123); value2.setValue(sb); } try (WriteContext wc = map.acquireUsingLocked(key2, value1)) { assertEquals("123", value1.getValue()); value1.setValue(value1.getValue() + '4'); assertEquals("1234", value1.getValue()); } try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertTrue(rc.present()); assertEquals("1234", value2.getValue()); } } } @Test @Ignore public void testIntegerIntegerMap() throws ExecutionException, InterruptedException { try (ChronicleMap<Integer, Integer> map = ChronicleMapBuilder .of(Integer.class, Integer.class) .entrySize(8) // TODO .disableOversizedEntries(true) // disabled for testing purposes only. .create()) { Integer key1; Integer key2; Integer value1; Integer value2; key1 = 1; value1 = 11; map.put(key1, value1); assertEquals(value1, map.get(key1)); key2 = 2; value2 = 22; map.put(key2, value2); assertEquals(value2, map.get(key2)); assertEquals((Integer) 11, map.get(key1)); assertEquals((Integer) 22, map.get(key2)); assertEquals(null, map.get(3)); assertEquals(null, map.get(4)); assertEquals((Integer) 110, map.mapForKey(1, new Function<Integer, Integer>() { @Override public Integer apply(Integer s) { return 10 * s; } })); assertEquals(null, map.mapForKey(-1, new Function<Integer, Integer>() { @Override public Integer apply(Integer s) { return 10 * s; } })); try { map.updateForKey(1, new Mutator<Integer, Integer>() { @Override public Integer update(Integer s) { return s + 1; } }); fail("Update of Integer not supported"); } catch (Exception todoMoreSpecificException) { } assertEquals(null, map.putLater(3, 4).get()); assertEquals((Integer) 4, map.getLater(3).get()); assertEquals((Integer) 4, map.removeLater(3).get()); assertEquals(null, map.removeLater(3).get()); } } @Test @Ignore public void testLongLongMap() throws ExecutionException, InterruptedException { try (ChronicleMap<Long, Long> map = ChronicleMapBuilder .of(Long.class, Long.class) .entrySize(16) // TODO .disableOversizedEntries(true) // disabled for testing purposes only. .create()) { map.put(1L, 11L); assertEquals((Long) 11L, map.get(1L)); map.put(2L, 22L); assertEquals((Long) 22L, map.get(2L)); assertEquals(null, map.get(3L)); assertEquals(null, map.get(4L)); assertEquals((Long) 110L, map.mapForKey(1L, new Function<Long, Long>() { @Override public Long apply(Long s) { return 10 * s; } })); assertEquals(null, map.mapForKey(-1L, new Function<Long, Long>() { @Override public Long apply(Long s) { return 10 * s; } })); try { map.updateForKey(1L, new Mutator<Long, Long>() { @Override public Long update(Long s) { return s + 1; } }); fail("Update of Long not supported"); } catch (Exception todoMoreSpecificException) { } assertEquals(null, map.putLater(3L, 4L).get()); assertEquals((Long) 4L, map.getLater(3L).get()); assertEquals((Long) 4L, map.removeLater(3L).get()); assertEquals(null, map.removeLater(3L).get()); } } @Test @Ignore public void testDoubleDoubleMap() throws ExecutionException, InterruptedException { try (ChronicleMap<Double, Double> map = ChronicleMapBuilder .of(Double.class, Double.class) // TODO .disableOversizedEntries(true) // disabled for testing purposes only. .entrySize(16) .create()) { map.put(1.0, 11.0); assertEquals((Double) 11.0, map.get(1.0)); map.put(2.0, 22.0); assertEquals((Double) 22.0, map.get(2.0)); assertEquals(null, map.get(3.0)); assertEquals(null, map.get(4.0)); assertEquals((Double) 110.0, map.mapForKey(1.0, new Function<Double, Double>() { @Override public Double apply(Double s) { return 10 * s; } })); assertEquals(null, map.mapForKey(-1.0, new Function<Double, Double>() { @Override public Double apply(Double s) { return 10 * s; } })); try { map.updateForKey(1.0, new Mutator<Double, Double>() { @Override public Double update(Double s) { return s + 1; } }); fail("Update of Double not supported"); } catch (Exception todoMoreSpecificException) { } assertEquals(null, map.putLater(3.0, 4.0).get()); assertEquals((Double) 4.0, map.getLater(3.0).get()); assertEquals((Double) 4.0, map.removeLater(3.0).get()); assertEquals(null, map.removeLater(3.0).get()); } } @Test @Ignore public void testByteArrayByteArrayMap() throws ExecutionException, InterruptedException { try (ChronicleMap<byte[], byte[]> map = ChronicleMapBuilder .of(byte[].class, byte[].class) // TODO .disableOversizedEntries(true) // disabled for testing purposes only. .entrySize(12) .create()) { byte[] key1 = {1, 1, 1, 1}; byte[] key2 = {2, 2, 2, 2}; byte[] value1 = {11, 11, 11, 11}; byte[] value2 = {22, 22, 22, 22}; assertNull(map.put(key1, value1)); assertTrue(Arrays.equals(value1, map.put(key1, value2))); assertTrue(Arrays.equals(value1, map.get(key1))); assertNull(map.get(key2)); assertTrue(Arrays.equals(new byte[]{11, 11}, map.mapForKey(key1, new Function<byte[], byte[]>() { @Override public byte[] apply(byte[] s) { return Arrays.copyOf(s, 2); } }))); assertEquals(null, map.mapForKey(key2, new Function<byte[], byte[]>() { @Override public byte[] apply(byte[] s) { return Arrays.copyOf(s, 2); } })); assertTrue(Arrays.equals(new byte[]{12, 10}, map.updateForKey(key1, new Mutator<byte[], byte[]>() { @Override public byte[] update(byte[] s) { s[0]++; s[1] return Arrays.copyOf(s, 2); } }))); assertTrue(Arrays.equals(new byte[]{12, 10, 11, 11}, map.get(key1))); byte[] key3 = {3, 3, 3, 3}; byte[] value3 = {4, 4, 4, 4}; assertEquals(null, map.putLater(key3, value3).get()); assertTrue(Arrays.equals(value3, map.getLater(key3).get())); assertTrue(Arrays.equals(value3, map.removeLater(key3).get())); assertEquals(null, map.removeLater(key3).get()); } } @Test @Ignore public void testByteBufferByteBufferMap() throws ExecutionException, InterruptedException { try (ChronicleMap<ByteBuffer, ByteBuffer> map = ChronicleMapBuilder .of(ByteBuffer.class, ByteBuffer.class) // TODO .disableOversizedEntries(true) // disabled for testing purposes only. .entrySize(12) .create()) { ByteBuffer key1 = ByteBuffer.wrap(new byte[]{1, 1, 1, 1}); ByteBuffer key2 = ByteBuffer.wrap(new byte[]{2, 2, 2, 2}); ByteBuffer value1 = ByteBuffer.wrap(new byte[]{11, 11, 11, 11}); ByteBuffer value2 = ByteBuffer.wrap(new byte[]{22, 22, 22, 22}); assertNull(map.put(key1, value1)); assertBBEquals(value1, map.put(key1, value2)); assertBBEquals(value1, map.get(key1)); assertNull(map.get(key2)); final Function<ByteBuffer, ByteBuffer> function = new Function<ByteBuffer, ByteBuffer>() { @Override public ByteBuffer apply(ByteBuffer s) { ByteBuffer slice = s.slice(); slice.limit(2); return slice; } }; assertBBEquals(ByteBuffer.wrap(new byte[]{11, 11}), map.mapForKey(key1, function)); assertEquals(null, map.mapForKey(key2, function)); assertBBEquals(ByteBuffer.wrap(new byte[]{12, 10}), map.updateForKey(key1, new Mutator<ByteBuffer, ByteBuffer>() { @Override public ByteBuffer update(ByteBuffer s) { s.put(0, (byte) (s.get(0) + 1)); s.put(0, (byte) (s.get(0) - 1)); return function.apply(s); } })); assertBBEquals(ByteBuffer.wrap(new byte[]{12, 10, 11, 11}), map.get(key1)); ByteBuffer key3 = ByteBuffer.wrap(new byte[]{3, 3, 3, 3}); ByteBuffer value3 = ByteBuffer.wrap(new byte[]{4, 4, 4, 4}); assertEquals(null, map.putLater(key3, value3).get()); assertBBEquals(value3, map.getLater(key3).get()); assertBBEquals(value3, map.removeLater(key3).get()); assertEquals(null, map.removeLater(key3).get()); } } private void assertBBEquals(ByteBuffer bb1, ByteBuffer bb2) { assertEquals(bb1.remaining(), bb2.remaining()); for (int i = 0; i < bb1.remaining(); i++) assertEquals(bb1.get(bb1.position() + i), bb2.get(bb2.position() + i)); } @Test @Ignore public void testIntValueIntValueMap() { ChronicleMap<IntValue, IntValue> map = ChronicleMapBuilder.of(IntValue.class, IntValue.class).entrySize(8).create(); IntValue key1 = DataValueClasses.newDirectInstance(IntValue.class); IntValue key2 = DataValueClasses.newInstance(IntValue.class); IntValue value1 = DataValueClasses.newDirectInstance(IntValue.class); IntValue value2 = DataValueClasses.newInstance(IntValue.class); key1.setValue(1); value1.setValue(11); map.put(key1, value1); assertEquals(value1, map.get(key1)); key2.setValue(2); value2.setValue(22); map.put(key2, value2); assertEquals(value2, map.get(key2)); try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertTrue(rc.present()); assertEquals(11, value1.getValue()); } try (ReadContext rc = map.getUsingLocked(key2, value1)) { assertTrue(rc.present()); assertEquals(22, value2.getValue()); } try (ReadContext rc = map.getUsingLocked(key1, value2)) { assertTrue(rc.present()); assertEquals(11, value2.getValue()); } try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertTrue(rc.present()); assertEquals(22, value2.getValue()); } key1.setValue(3); try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertFalse(rc.present()); } key2.setValue(4); try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertFalse(rc.present()); } try (WriteContext wc = map.acquireUsingLocked(key1, value1)) { assertEquals(0, value1.getValue()); value1.addValue(123); assertEquals(123, value1.getValue()); } try (WriteContext wc = map.acquireUsingLocked(key1, value2)) { assertEquals(123, value2.getValue()); value2.addValue(1230 - 123); assertEquals(1230, value2.getValue()); } try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertTrue(rc.present()); assertEquals(1230, value1.getValue()); } try (WriteContext wc = map.acquireUsingLocked(key2, value2)) { assertEquals(0, value2.getValue()); value2.addValue(123); assertEquals(123, value2.getValue()); } try (WriteContext wc = map.acquireUsingLocked(key2, value1)) { assertEquals(123, value1.getValue()); value1.addValue(1230 - 123); assertEquals(1230, value1.getValue()); } try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertTrue(rc.present()); assertEquals(1230, value2.getValue()); } map.close(); } /** * For unsigned int -> unsigned int entries, the key can be on heap or off heap. */ @Test @Ignore public void testUnsignedIntValueUnsignedIntValueMap() { ChronicleMap<UnsignedIntValue, UnsignedIntValue> map = ChronicleMapBuilder.of(UnsignedIntValue.class, UnsignedIntValue.class).entrySize(8).create(); UnsignedIntValue key1 = DataValueClasses.newDirectInstance(UnsignedIntValue.class); UnsignedIntValue key2 = DataValueClasses.newInstance(UnsignedIntValue.class); UnsignedIntValue value1 = DataValueClasses.newDirectInstance(UnsignedIntValue.class); UnsignedIntValue value2 = DataValueClasses.newInstance(UnsignedIntValue.class); key1.setValue(1); value1.setValue(11); map.put(key1, value1); assertEquals(value1, map.get(key1)); key2.setValue(2); value2.setValue(22); map.put(key2, value2); assertEquals(value2, map.get(key2)); try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertTrue(rc.present()); assertEquals(11, value1.getValue()); } try (ReadContext rc = map.getUsingLocked(key2, value1)) { assertTrue(rc.present()); assertEquals(22, value2.getValue()); } try (ReadContext rc = map.getUsingLocked(key1, value2)) { assertTrue(rc.present()); assertEquals(11, value2.getValue()); } try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertTrue(rc.present()); assertEquals(22, value2.getValue()); } key1.setValue(3); try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertFalse(rc.present()); } key2.setValue(4); try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertFalse(rc.present()); } try (WriteContext wc = map.acquireUsingLocked(key1, value1)) { assertEquals(0, value1.getValue()); value1.addValue(123); assertEquals(123, value1.getValue()); } try (WriteContext wc = map.acquireUsingLocked(key1, value2)) { assertEquals(123, value2.getValue()); value2.addValue(1230 - 123); assertEquals(1230, value2.getValue()); } try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertTrue(rc.present()); assertEquals(1230, value1.getValue()); } try (WriteContext wc = map.acquireUsingLocked(key2, value2)) { assertEquals(0, value2.getValue()); value2.addValue(123); assertEquals(123, value2.getValue()); } try (WriteContext wc = map.acquireUsingLocked(key2, value1)) { assertEquals(123, value1.getValue()); value1.addValue(1230 - 123); assertEquals(1230, value1.getValue()); } try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertTrue(rc.present()); assertEquals(1230, value2.getValue()); } map.close(); } /** * For int values, the key can be on heap or off heap. */ @Test @Ignore public void testIntValueShortValueMap() { ChronicleMap<IntValue, ShortValue> map = ChronicleMapBuilder.of(IntValue.class, ShortValue.class).entrySize(6).create(); IntValue key1 = DataValueClasses.newDirectInstance(IntValue.class); IntValue key2 = DataValueClasses.newInstance(IntValue.class); ShortValue value1 = DataValueClasses.newDirectInstance(ShortValue.class); ShortValue value2 = DataValueClasses.newInstance(ShortValue.class); key1.setValue(1); value1.setValue((short) 11); map.put(key1, value1); assertEquals(value1, map.get(key1)); key2.setValue(2); value2.setValue((short) 22); map.put(key2, value2); assertEquals(value2, map.get(key2)); try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertTrue(rc.present()); assertEquals(11, value1.getValue()); } try (ReadContext rc = map.getUsingLocked(key2, value1)) { assertTrue(rc.present()); assertEquals(22, value2.getValue()); } try (ReadContext rc = map.getUsingLocked(key1, value2)) { assertTrue(rc.present()); assertEquals(11, value2.getValue()); } try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertTrue(rc.present()); assertEquals(22, value2.getValue()); } key1.setValue(3); try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertFalse(rc.present()); } key2.setValue(4); try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertFalse(rc.present()); } try (WriteContext wc = map.acquireUsingLocked(key1, value1)) { assertEquals(0, value1.getValue()); value1.addValue((short) 123); assertEquals(123, value1.getValue()); } try (WriteContext wc = map.acquireUsingLocked(key1, value2)) { assertEquals(123, value2.getValue()); value2.addValue((short) (1230 - 123)); assertEquals(1230, value2.getValue()); } try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertTrue(rc.present()); assertEquals(1230, value1.getValue()); } try (WriteContext wc = map.acquireUsingLocked(key2, value2)) { assertEquals(0, value2.getValue()); value2.addValue((short) 123); assertEquals(123, value2.getValue()); } try (WriteContext wc = map.acquireUsingLocked(key2, value1)) { assertEquals(123, value1.getValue()); value1.addValue((short) (1230 - 123)); assertEquals(1230, value1.getValue()); } try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertTrue(rc.present()); assertEquals(1230, value2.getValue()); } map.close(); } /** * For int -> unsigned short values, the key can be on heap or off heap. */ @Test @Ignore public void testIntValueUnsignedShortValueMap() { ChronicleMap<IntValue, UnsignedShortValue> map = ChronicleMapBuilder.of(IntValue.class, UnsignedShortValue.class).entrySize(6).create(); IntValue key1 = DataValueClasses.newDirectInstance(IntValue.class); IntValue key2 = DataValueClasses.newInstance(IntValue.class); UnsignedShortValue value1 = DataValueClasses.newDirectInstance(UnsignedShortValue.class); UnsignedShortValue value2 = DataValueClasses.newInstance(UnsignedShortValue.class); key1.setValue(1); value1.setValue(11); map.put(key1, value1); assertEquals(value1, map.get(key1)); key2.setValue(2); value2.setValue(22); map.put(key2, value2); assertEquals(value2, map.get(key2)); try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertTrue(rc.present()); assertEquals(11, value1.getValue()); } try (ReadContext rc = map.getUsingLocked(key2, value1)) { assertTrue(rc.present()); assertEquals(22, value2.getValue()); } try (ReadContext rc = map.getUsingLocked(key1, value2)) { assertTrue(rc.present()); assertEquals(11, value2.getValue()); } try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertTrue(rc.present()); assertEquals(22, value2.getValue()); } key1.setValue(3); try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertFalse(rc.present()); } key2.setValue(4); try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertFalse(rc.present()); } try (WriteContext wc = map.acquireUsingLocked(key1, value1)) { assertEquals(0, value1.getValue()); value1.addValue(123); assertEquals(123, value1.getValue()); } try (WriteContext wc = map.acquireUsingLocked(key1, value2)) { assertEquals(123, value2.getValue()); value2.addValue(1230 - 123); assertEquals(1230, value2.getValue()); } try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertTrue(rc.present()); assertEquals(1230, value1.getValue()); } try (WriteContext wc = map.acquireUsingLocked(key2, value2)) { assertEquals(0, value2.getValue()); value2.addValue(123); assertEquals(123, value2.getValue()); } try (WriteContext wc = map.acquireUsingLocked(key2, value1)) { assertEquals(123, value1.getValue()); value1.addValue(1230 - 123); assertEquals(1230, value1.getValue()); } try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertTrue(rc.present()); assertEquals(1230, value2.getValue()); } map.close(); } /** * For int values, the key can be on heap or off heap. */ @Test @Ignore public void testIntValueCharValueMap() { ChronicleMap<IntValue, CharValue> map = ChronicleMapBuilder.of(IntValue.class, CharValue.class).entrySize(6).create(); IntValue key1 = DataValueClasses.newDirectInstance(IntValue.class); IntValue key2 = DataValueClasses.newInstance(IntValue.class); CharValue value1 = DataValueClasses.newDirectInstance(CharValue.class); CharValue value2 = DataValueClasses.newInstance(CharValue.class); key1.setValue(1); value1.setValue((char) 11); map.put(key1, value1); assertEquals(value1, map.get(key1)); key2.setValue(2); value2.setValue((char) 22); map.put(key2, value2); assertEquals(value2, map.get(key2)); try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertTrue(rc.present()); assertEquals(11, value1.getValue()); } try (ReadContext rc = map.getUsingLocked(key2, value1)) { assertTrue(rc.present()); assertEquals(22, value2.getValue()); } try (ReadContext rc = map.getUsingLocked(key1, value2)) { assertTrue(rc.present()); assertEquals(11, value2.getValue()); } try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertTrue(rc.present()); assertEquals(22, value2.getValue()); } key1.setValue(3); try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertFalse(rc.present()); } key2.setValue(4); try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertFalse(rc.present()); } try (WriteContext wc = map.acquireUsingLocked(key1, value1)) { assertEquals('\0', value1.getValue()); value1.setValue('@'); assertEquals('@', value1.getValue()); } try (WriteContext wc = map.acquireUsingLocked(key1, value2)) { assertEquals('@', value2.getValue()); value2.setValue(' assertEquals('#', value2.getValue()); } try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertTrue(rc.present()); assertEquals('#', value1.getValue()); } try (WriteContext wc = map.acquireUsingLocked(key2, value2)) { assertEquals('\0', value2.getValue()); value2.setValue(';'); assertEquals(';', value2.getValue()); } try (WriteContext wc = map.acquireUsingLocked(key2, value1)) { assertEquals(';', value1.getValue()); value1.setValue('['); assertEquals('[', value1.getValue()); } try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertTrue(rc.present()); assertEquals('[', value2.getValue()); } map.close(); } /** * For int-> byte entries, the key can be on heap or off heap. */ @Test @Ignore public void testIntValueUnsignedByteMap() { ChronicleMap<IntValue, UnsignedByteValue> map = ChronicleMapBuilder.of(IntValue.class, UnsignedByteValue.class).entrySize(5).create(); IntValue key1 = DataValueClasses.newDirectInstance(IntValue.class); IntValue key2 = DataValueClasses.newInstance(IntValue.class); UnsignedByteValue value1 = DataValueClasses.newDirectInstance(UnsignedByteValue.class); UnsignedByteValue value2 = DataValueClasses.newInstance(UnsignedByteValue.class); key1.setValue(1); value1.setValue(11); map.put(key1, value1); assertEquals(value1, map.get(key1)); key2.setValue(2); value2.setValue(22); map.put(key2, value2); assertEquals(value2, map.get(key2)); try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertTrue(rc.present()); assertEquals(11, value1.getValue()); } try (ReadContext rc = map.getUsingLocked(key2, value1)) { assertTrue(rc.present()); assertEquals(22, value2.getValue()); } try (ReadContext rc = map.getUsingLocked(key1, value2)) { assertTrue(rc.present()); assertEquals(11, value2.getValue()); } try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertTrue(rc.present()); assertEquals(22, value2.getValue()); } key1.setValue(3); try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertFalse(rc.present()); } key2.setValue(4); try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertFalse(rc.present()); } try (WriteContext wc = map.acquireUsingLocked(key1, value1)) { assertEquals(0, value1.getValue()); value1.addValue(234); assertEquals(234, value1.getValue()); } try (WriteContext wc = map.acquireUsingLocked(key1, value2)) { assertEquals(234, value2.getValue()); value2.addValue(-100); assertEquals(134, value2.getValue()); } try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertTrue(rc.present()); assertEquals(134, value1.getValue()); } try (WriteContext wc = map.acquireUsingLocked(key2, value2)) { assertEquals(0, value2.getValue()); value2.addValue((byte) 123); assertEquals(123, value2.getValue()); } try (WriteContext wc = map.acquireUsingLocked(key2, value1)) { assertEquals(123, value1.getValue()); value1.addValue((byte) -111); assertEquals(12, value1.getValue()); } try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertTrue(rc.present()); assertEquals(12, value2.getValue()); } map.close(); } /** * For int values, the key can be on heap or off heap. */ @Test @Ignore public void testIntValueBooleanValueMap() { ChronicleMap<IntValue, BooleanValue> map = ChronicleMapBuilder.of(IntValue.class, BooleanValue.class).entrySize(5).create(); IntValue key1 = DataValueClasses.newDirectInstance(IntValue.class); IntValue key2 = DataValueClasses.newInstance(IntValue.class); BooleanValue value1 = DataValueClasses.newDirectInstance(BooleanValue.class); BooleanValue value2 = DataValueClasses.newInstance(BooleanValue.class); key1.setValue(1); value1.setValue(true); map.put(key1, value1); assertEquals(value1, map.get(key1)); key2.setValue(2); value2.setValue(false); map.put(key2, value2); assertEquals(value2, map.get(key2)); try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertTrue(rc.present()); assertEquals(true, value1.getValue()); } try (ReadContext rc = map.getUsingLocked(key2, value1)) { assertTrue(rc.present()); assertEquals(false, value2.getValue()); } try (ReadContext rc = map.getUsingLocked(key1, value2)) { assertTrue(rc.present()); assertEquals(true, value2.getValue()); } try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertTrue(rc.present()); assertEquals(false, value2.getValue()); } key1.setValue(3); try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertFalse(rc.present()); } key2.setValue(4); try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertFalse(rc.present()); } try (WriteContext wc = map.acquireUsingLocked(key1, value1)) { assertEquals(false, value1.getValue()); value1.setValue(true); assertEquals(true, value1.getValue()); } try (WriteContext wc = map.acquireUsingLocked(key1, value2)) { assertEquals(true, value2.getValue()); value2.setValue(false); assertEquals(false, value2.getValue()); } try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertTrue(rc.present()); assertEquals(false, value1.getValue()); } try (WriteContext wc = map.acquireUsingLocked(key2, value2)) { assertEquals(false, value2.getValue()); value2.setValue(true); assertEquals(true, value2.getValue()); } try (WriteContext wc = map.acquireUsingLocked(key2, value1)) { assertEquals(true, value1.getValue()); value1.setValue(false); assertEquals(false, value1.getValue()); } try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertTrue(rc.present()); assertEquals(false, value2.getValue()); } map.close(); } /** * For float values, the key can be on heap or off heap. */ @Test @Ignore public void testFloatValueFloatValueMap() { ChronicleMap<FloatValue, FloatValue> map = ChronicleMapBuilder.of(FloatValue.class, FloatValue.class).entrySize(8).create(); FloatValue key1 = DataValueClasses.newDirectInstance(FloatValue.class); FloatValue key2 = DataValueClasses.newInstance(FloatValue.class); FloatValue value1 = DataValueClasses.newDirectInstance(FloatValue.class); FloatValue value2 = DataValueClasses.newInstance(FloatValue.class); key1.setValue(1); value1.setValue(11); map.put(key1, value1); assertEquals(value1, map.get(key1)); key2.setValue(2); value2.setValue(22); map.put(key2, value2); assertEquals(value2, map.get(key2)); try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertTrue(rc.present()); assertEquals(11, value1.getValue(), 0); } try (ReadContext rc = map.getUsingLocked(key2, value1)) { assertTrue(rc.present()); assertEquals(22, value2.getValue(), 0); } try (ReadContext rc = map.getUsingLocked(key1, value2)) { assertTrue(rc.present()); assertEquals(11, value2.getValue(), 0); } try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertTrue(rc.present()); assertEquals(22, value2.getValue(), 0); } key1.setValue(3); try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertFalse(rc.present()); } key2.setValue(4); try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertFalse(rc.present()); } try (WriteContext wc = map.acquireUsingLocked(key1, value1)) { assertEquals(0, value1.getValue(), 0); value1.addValue(123); assertEquals(123, value1.getValue(), 0); } try (WriteContext wc = map.acquireUsingLocked(key1, value2)) { assertEquals(123, value2.getValue(), 0); value2.addValue(1230 - 123); assertEquals(1230, value2.getValue(), 0); } try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertTrue(rc.present()); assertEquals(1230, value1.getValue(), 0); } try (WriteContext wc = map.acquireUsingLocked(key2, value2)) { assertEquals(0, value2.getValue(), 0); value2.addValue(123); assertEquals(123, value2.getValue(), 0); } try (WriteContext wc = map.acquireUsingLocked(key2, value1)) { assertEquals(123, value1.getValue(), 0); value1.addValue(1230 - 123); assertEquals(1230, value1.getValue(), 0); } try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertTrue(rc.present()); assertEquals(1230, value2.getValue(), 0); } map.close(); } /** * For double values, the key can be on heap or off heap. */ @Test @Ignore public void testDoubleValueDoubleValueMap() { ChronicleMap<DoubleValue, DoubleValue> map = ChronicleMapBuilder.of(DoubleValue.class, DoubleValue.class).entrySize(16).create(); DoubleValue key1 = DataValueClasses.newDirectInstance(DoubleValue.class); DoubleValue key2 = DataValueClasses.newInstance(DoubleValue.class); DoubleValue value1 = DataValueClasses.newDirectInstance(DoubleValue.class); DoubleValue value2 = DataValueClasses.newInstance(DoubleValue.class); key1.setValue(1); value1.setValue(11); assertEquals(value1, map.get(key1)); key2.setValue(2); value2.setValue(22); map.put(key2, value2); assertEquals(value2, map.get(key2)); try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertTrue(rc.present()); assertEquals(11, value1.getValue(), 0); } try (ReadContext rc = map.getUsingLocked(key2, value1)) { assertTrue(rc.present()); assertEquals(22, value2.getValue(), 0); } try (ReadContext rc = map.getUsingLocked(key1, value2)) { assertTrue(rc.present()); assertEquals(11, value2.getValue(), 0); } try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertTrue(rc.present()); assertEquals(22, value2.getValue(), 0); } key1.setValue(3); try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertFalse(rc.present()); } key2.setValue(4); try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertFalse(rc.present()); } try (WriteContext wc = map.acquireUsingLocked(key1, value1)) { assertEquals(0, value1.getValue(), 0); value1.addValue(123); assertEquals(123, value1.getValue(), 0); } try (WriteContext wc = map.acquireUsingLocked(key1, value2)) { assertEquals(123, value2.getValue(), 0); value2.addValue(1230 - 123); assertEquals(1230, value2.getValue(), 0); } try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertTrue(rc.present()); assertEquals(1230, value1.getValue(), 0); } try (WriteContext wc = map.acquireUsingLocked(key2, value2)) { assertEquals(0, value2.getValue(), 0); value2.addValue(123); assertEquals(123, value2.getValue(), 0); } try (WriteContext wc = map.acquireUsingLocked(key2, value1)) { assertEquals(123, value1.getValue(), 0); value1.addValue(1230 - 123); assertEquals(1230, value1.getValue(), 0); } try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertTrue(rc.present()); assertEquals(1230, value2.getValue(), 0); } map.close(); } /** * For long values, the key can be on heap or off heap. */ @Test @Ignore public void testLongValueLongValueMap() { ChronicleMap<LongValue, LongValue> map = ChronicleMapBuilder.of(LongValue.class, LongValue.class).entrySize(16).create(); LongValue key1 = DataValueClasses.newDirectInstance(LongValue.class); LongValue key2 = DataValueClasses.newInstance(LongValue.class); LongValue value1 = DataValueClasses.newDirectInstance(LongValue.class); LongValue value2 = DataValueClasses.newInstance(LongValue.class); key1.setValue(1); value1.setValue(11); assertEquals(value1, map.get(key1)); key2.setValue(2); value2.setValue(22); map.put(key2, value2); assertEquals(value2, map.get(key2)); try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertTrue(rc.present()); assertEquals(11, value1.getValue()); } try (ReadContext rc = map.getUsingLocked(key2, value1)) { assertTrue(rc.present()); assertEquals(22, value2.getValue()); } try (ReadContext rc = map.getUsingLocked(key1, value2)) { assertTrue(rc.present()); assertEquals(11, value2.getValue()); } try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertTrue(rc.present()); assertEquals(22, value2.getValue()); } key1.setValue(3); try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertFalse(rc.present()); } key2.setValue(4); try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertFalse(rc.present()); } try (WriteContext wc = map.acquireUsingLocked(key1, value1)) { assertEquals(0, value1.getValue()); value1.addValue(123); assertEquals(123, value1.getValue()); } try (WriteContext wc = map.acquireUsingLocked(key1, value2)) { assertEquals(123, value2.getValue()); value2.addValue(1230 - 123); assertEquals(1230, value2.getValue()); } try (ReadContext rc = map.getUsingLocked(key1, value1)) { assertTrue(rc.present()); assertEquals(1230, value1.getValue()); } try (WriteContext wc = map.acquireUsingLocked(key2, value2)) { assertEquals(0, value2.getValue()); value2.addValue(123); assertEquals(123, value2.getValue()); } try (WriteContext wc = map.acquireUsingLocked(key2, value1)) { assertEquals(123, value1.getValue()); value1.addValue(1230 - 123); assertEquals(1230, value1.getValue()); } try (ReadContext rc = map.getUsingLocked(key2, value2)) { assertTrue(rc.present()); assertEquals(1230, value2.getValue()); } map.close(); } /** * For beans, the key can be on heap or off heap as long as the bean is not variable length. */ @Test public void testBeanBeanMap() { } @Test @Ignore public void testListValue() { ChronicleMap<String, List<String>> map = ChronicleMapBuilder.of(String.class, (Class<List<String>>) (Class) List.class).create(); map.put("1", Collections.<String>emptyList()); map.put("2", Arrays.asList("one")); List<String> list1 = new ArrayList<>(); try (WriteContext wc = map.acquireUsingLocked("1", list1)) { list1.add("two"); assertEquals(Arrays.asList("two"), list1); } List<String> list2 = new ArrayList<>(); try (ReadContext rc = map.getUsingLocked("1", list2)) { assertTrue(rc.present()); assertEquals(Arrays.asList("two"), list2); } try (WriteContext wc = map.acquireUsingLocked("2", list1)) { list1.add("three"); assertEquals(Arrays.asList("three"), list1); } try (ReadContext rc = map.getUsingLocked("2", list2)) { assertTrue(rc.present()); assertEquals(Arrays.asList("one", "three"), list2); } map.close(); } @Test @Ignore public void testSetValue() { ChronicleMap<String, Set<String>> map = ChronicleMapBuilder.of(String.class, (Class<Set<String>>) (Class) Set.class).create(); map.put("1", Collections.<String>emptySet()); map.put("2", new LinkedHashSet<String>(Arrays.asList("one"))); Set<String> list1 = new LinkedHashSet<>(); try (WriteContext wc = map.acquireUsingLocked("1", list1)) { list1.add("two"); assertEquals(new LinkedHashSet<String>(Arrays.asList("two")), list1); } Set<String> list2 = new LinkedHashSet<>(); try (ReadContext rc = map.getUsingLocked("1", list2)) { assertTrue(rc.present()); assertEquals(new LinkedHashSet<String>(Arrays.asList("two")), list2); } try (WriteContext wc = map.acquireUsingLocked("2", list1)) { list1.add("three"); assertEquals(new LinkedHashSet<String>(Arrays.asList("three")), list1); } try (ReadContext rc = map.getUsingLocked("2", list2)) { assertTrue(rc.present()); assertEquals(new LinkedHashSet<String>(Arrays.asList("one", "three")), list2); } map.close(); } @Test @Ignore public void testMapStringStringValue() { ChronicleMap<String, Map<String, String>> map = ChronicleMapBuilder.of(String.class, (Class<Map<String, String>>) (Class) Map.class).create(); map.put("1", Collections.<String, String>emptyMap()); map.put("2", mapOf("one", "uni")); Map<String, String> map1 = new LinkedHashMap<>(); try (WriteContext wc = map.acquireUsingLocked("1", map1)) { map1.put("two", "bi"); assertEquals(mapOf("two", "bi"), map1); } Map<String, String> map2 = new LinkedHashMap<>(); try (ReadContext rc = map.getUsingLocked("1", map2)) { assertTrue(rc.present()); assertEquals(mapOf("two", "bi"), map2); } try (WriteContext wc = map.acquireUsingLocked("2", map1)) { map1.put("three", "tri"); assertEquals(mapOf("one", "uni", "three", "tri"), map1); } try (ReadContext rc = map.getUsingLocked("2", map2)) { assertTrue(rc.present()); assertEquals(mapOf("one", "uni", "three", "tri"), map2); } map.close(); } @Test @Ignore public void testMapStringIntegerValue() { ChronicleMap<String, Map<String, Integer>> map = ChronicleMapBuilder.of(String.class, (Class<Map<String, Integer>>) (Class) Map.class).create(); map.put("1", Collections.<String, Integer>emptyMap()); map.put("2", mapOf("one", 1)); Map<String, Integer> map1 = new LinkedHashMap<>(); try (WriteContext wc = map.acquireUsingLocked("1", map1)) { map1.put("two", 2); assertEquals(mapOf("two", 2), map1); } Map<String, Integer> map2 = new LinkedHashMap<>(); try (ReadContext rc = map.getUsingLocked("1", map2)) { assertTrue(rc.present()); assertEquals(mapOf("two", 2), map2); } try (WriteContext wc = map.acquireUsingLocked("2", map1)) { map1.put("three", 3); assertEquals(mapOf("one", 1, "three", 3), map1); } try (ReadContext rc = map.getUsingLocked("2", map2)) { assertTrue(rc.present()); assertEquals(mapOf("one", 1, "three", 3), map2); } map.close(); } public static <K, V> Map<K, V> mapOf(K k, V v, Object... keysAndValues) { Map<K, V> ret = new LinkedHashMap<>(); ret.put(k, v); for (int i = 0; i < keysAndValues.length - 1; i += 2) { Object key = keysAndValues[i]; Object value = keysAndValues[i + 1]; ret.put((K) key, (V) value); } return ret; } } enum ToString implements Function<Object, String> { INSTANCE; @Override public String apply(Object o) { return String.valueOf(o); } } /* interface IBean { long getLong(); void setLong(long num); double getDouble(); void setDouble(double d); int getInt(); void setInt(int i); } */
package org.arachb.arachadmin; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.util.Set; import org.apache.log4j.Logger; import org.junit.Before; import org.junit.Test; public class TestParticipantBean { private static Logger log = Logger.getLogger(TestParticipantBean.class); private AbstractConnection testConnection; private ClaimBean testClaim1; private ClaimBean testClaim26; @Before public void setUp() throws Exception { if (DBConnection.testConnection()){ log.info("Testing with live connection"); testConnection = DBConnection.getTestConnection(); } else{ log.info("Testing with mock connection"); testConnection = DBConnection.getMockConnection(); } testClaim1 = testConnection.getClaim(1); testClaim26 = testConnection.getClaim(26); } @Test public void testFill() throws Exception { Set<ParticipantBean> pbs1 = testConnection.getParticipants(testClaim1); assertEquals(1, pbs1.size()); for (ParticipantBean pb : pbs1){ assertEquals(1, pb.getId()); assertEquals("some",pb.getQuantification()); assertEquals("",pb.getLabel()); //should improve this assertEquals(null,pb.getGeneratedId()); //improve ?? assertEquals(306,pb.getProperty()); assertEquals("Tetragnatha straminea", pb.getPublicationTaxon()); assertEquals("", pb.getPublicationAnatomy()); assertEquals(0, pb.getSubstrate()); assertEquals(1, pb.getHeadElement()); } Set<ParticipantBean> pbs29 = testConnection.getParticipants(testClaim26); assertEquals(1, pbs29.size()); for (ParticipantBean pb : pbs29){ assertEquals(29, pb.getId()); assertEquals("individual",pb.getQuantification()); assertEquals("female",pb.getLabel()); //should improve this assertEquals("http://arachb.org/arachb/ARACHB_0000349",pb.getGeneratedId()); //improve ?? assertEquals(306,pb.getProperty()); assertEquals("Leucauge mariana", pb.getPublicationTaxon()); assertEquals("female", pb.getPublicationAnatomy()); assertEquals(0, pb.getSubstrate()); assertEquals(62, pb.getHeadElement()); } } @Test public void testLoadElements() throws Exception { final Set<ParticipantBean> pbs1 = testConnection.getParticipants(testClaim1); assertEquals(1, pbs1.size()); for (ParticipantBean pb : pbs1){ assertNull(pb.getElementBean(1)); pb.loadElements(testConnection); assertNotNull(pb.getElementBean(1)); } Set<ParticipantBean> pbs29 = testConnection.getParticipants(testClaim26); assertEquals(1, pbs29.size()); for (ParticipantBean pb : pbs29){ assertNull(pb.getElementBean(1)); pb.loadElements(testConnection); assertNotNull(pb.getElementBean(61)); } } }
package se.sunet.mm.service.api; import com.google.gson.Gson; import org.eclipse.jetty.server.Server; import org.testng.annotations.Test; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.*; import java.util.HashMap; import static org.testng.Assert.assertEquals; public class UserReachableTest extends SetupCommon { private final Gson gson = new Gson(); @Test public void testUserRechable() throws Exception { Server server = embeddedServer.getServer(); String servletPath = "/user/reachable"; // Load Mina Meddelanden test response data //UserReachable.Response expectedResponse = new UserReachable.Response(Boolean.TRUE, // ServiceAddress changed for the test data unexpectedly UserReachable.Response expectedResponse = new UserReachable.Response(Boolean.TRUE, "Secure", "https://notarealhost.skatteverket.se/webservice/accao/Service"); Client client = ClientBuilder.newClient(); WebTarget target = client.target(server.getURI()).path(servletPath); HashMap<String, String> data = new HashMap<>(); data.put("identity_number", TEST_PERSON_NIN); Entity entity = Entity.entity(gson.toJson(data), MediaType.APPLICATION_JSON); Response response = target.request(MediaType.APPLICATION_JSON).post(entity); UserReachable.Response jsonResponse = gson.fromJson(response.readEntity(String.class), UserReachable.Response.class); assertEquals(jsonResponse.getSenderAccepted(), expectedResponse.getSenderAccepted()); assertEquals(jsonResponse.getAccountStatus().getType(), expectedResponse.getAccountStatus().getType()); assertEquals(jsonResponse.getAccountStatus().getServiceSupplier().getServiceAddress(), expectedResponse.getAccountStatus().getServiceSupplier().getServiceAddress()); } }
package watodo.time.parser; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; //@@author A0143873Y public class TimeParserSelectorTest { @Test public void applicableTimeFormat() { StandardDateTimeParser standard = new StandardDateTimeParser(); ISODateTimeParser iso = new ISODateTimeParser(); TodayTimeParser today = new TodayTimeParser(); TomorrowTimeParser tmr = new TomorrowTimeParser(); //valid format assertTrue(standard.applyTo("16 Oct 2016 5.00pm")); assertTrue(standard.applyTo("30 jan 2017 1.59pm")); assertTrue(iso.applyTo("2017-09-23 8.00am")); assertTrue(iso.applyTo("1996-01-07 1.00am")); assertTrue(today.applyTo("today 12.01am")); assertTrue(today.applyTo("today 11.59pm")); assertTrue(tmr.applyTo("tmr 10.00am")); assertTrue(tmr.applyTo("tmr 4.00pm")); //invalid formats assertFalse(standard.applyTo("16-Oct-2016 5.00pm")); assertFalse(standard.applyTo("30 january 2017 1.59pm")); assertFalse(standard.applyTo("30 jan 2017 01:59")); assertFalse(standard.applyTo("30 jan 2017 00:09")); assertFalse(iso.applyTo("2017/09/23 8.00am")); assertFalse(iso.applyTo("1996-01-07 1:00")); assertFalse(today.applyTo("today 12:01")); assertFalse(today.applyTo("today 13.59pm")); assertFalse(tmr.applyTo("tmr 1000")); assertFalse(tmr.applyTo("tmr 16:00")); } }
package org.jenetics; import org.jscience.mathematics.number.LargeInteger; final class BitUtils { private BitUtils() { } public static byte[] toByteArray(final LargeInteger value) { final int byteLength = value.bitLength()/8 + 1; byte[] array = new byte[byteLength]; value.toByteArray(array, 0); return array; } public static LargeInteger toLargeInteger(final byte[] array) { return LargeInteger.valueOf(array, 0, array.length); } /** * Shifting all bits in the given <code>data</code> array the given <code>bits</code> * to the right. The bits on the left side are filled with zeros. * * @param data the data bits to shift. * @param bits the number of bits to shift. * @return the given <code>data</code> array. */ public static byte[] shiftRight(final byte[] data, final int bits) { if (bits <= 0) { return data; } int d = 0; if (data.length == 1) { if (bits <= 8) { d = data[0] & 0xFF; d >>>= bits; data[0] = (byte)d; } else { data[0] = 0; } } else if (data.length > 1) { int carry = 0; if (bits < 8) { for (int i = data.length - 1; i > 0; --i) { carry = data[i - 1] & (1 << (bits - 1)); carry = carry << (8 - bits); d = data[i] & 0xFF; d >>>= bits; d |= carry; data[i] = (byte)d; } d = data[0] & 0xFF; d >>>= bits; data[0] = (byte)d ; } else { for (int i = data.length - 1; i > 0; --i) { data[i] = data[i - 1]; } data[0] = 0; shiftRight(data, bits - 8); } } return data; } /** * Shifting all bits in the given <code>data</code> array the given <code>bits</code> * to the left. The bits on the right side are filled with zeros. * * @param data the data bits to shift. * @param bits the number of bits to shift. * @return the given <code>data</code> array. */ public static byte[] shiftLeft(final byte[] data, final int bits) { if (bits <= 0) { return data; } int d = 0; if (data.length == 1) { if (bits <= 8) { d = data[0] & 0xFF; d <<= bits; data[0] = (byte)d; } else { data[0] = 0; } } else if (data.length > 1) { int carry = 0; if (bits < 8) { for (int i = 0; i < data.length - 1; ++i) { carry = data[i + 1] & (1 >>> (8 - bits)); d = data[i] & 0xFF; d <<= bits; d |= carry; data[i] = (byte)d; } d = data[data.length - 1] & 0xFF; d <<= bits; data[data.length - 1] = (byte)d ; } else { for (int i = 0; i < data.length - 1; ++i) { data[i] = data[i + 1]; } data[data.length - 1] = 0; shiftLeft(data, bits - 8); } } return data; } /** * Increment the given <code>data</code> array. * * @param data the given <code>data</code> array. * @return the given <code>data</code> array. */ public static byte[] increment(final byte[] data) { if (data.length == 0) { return data; } int d = 0; int pos = data.length - 1; do { d = data[pos] & 0xFF; ++d; data[pos] = (byte)d; --pos; } while (pos >= 0 && data[pos + 1] == 0); return data; } /** * Invert the given <code>data</code> array. * * @param data the given <code>data</code> array. * @return the given <code>data</code> array. */ public static byte[] invert(final byte[] data) { int d = 0; for (int i = 0; i < data.length; ++i) { d = data[i] & 0xFF; d = ~d; data[i] = (byte)d; } return data; } /** * Make the two's complement of the given <code>data</code> array. * * @param data the given <code>data</code> array. * @return the given <code>data</code> array. */ public static byte[] complement(final byte[] data) { return increment(invert(data)); } public static byte[] setBit(final byte[] data, final int index, final boolean value) { if (data.length == 0) { return data; } final int MAX = data.length*8; if (index >= MAX || index < 0) { throw new IndexOutOfBoundsException("Index out of bounds: " + index); } final int pos = data.length - index/8 - 1; final int bitPos = index%8; int d = data[pos] & 0xFF; if (value) { d = d | (1 << bitPos); } else { d = d & ~(1 << bitPos); } data[pos] = (byte)d; return data; } public static boolean getBit(final byte[] data, final int index) { if (data.length == 0) { return false; } final int MAX = data.length*8; if (index >= MAX || index < 0) { throw new IndexOutOfBoundsException("Index out of bounds: " + index); } final int pos = data.length - index/8 - 1; final int bitPos = index%8; final int d = data[pos] & 0xFF; return (d & (1 << bitPos)) != 0; } /* * \\TODO: Handle possible overflow */ static long ulpDistance(final double a, final double b) { return Math.abs(ulpPosition(a) - ulpPosition(b)); } static long ulpPosition(final double a) { long t = Double.doubleToLongBits(a); if (t < 0) { t = Long.MIN_VALUE - t; } return t; } public static String toString(final long n) { final StringBuilder out = new StringBuilder(); for (int i = 63; i >= 0; --i) { out.append((n >>> i) & 1); } return out.toString(); } public static String toString(final byte... data) { final StringBuilder out = new StringBuilder(); for (int i = 0; i < data.length; ++i) { for (int j = 7; j >= 0; --j) { out.append((data[i] >>> j) & 1); } out.append('|'); } return out.toString(); } }
// $Id: List.java,v 1.2 2003/11/21 06:36:03 belaban Exp $ package org.jgroups.util; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Enumeration; import java.util.NoSuchElementException; import java.util.Vector; /** * Doubly-linked list. Elements can be added at head or tail and removed from head/tail. * This class is tuned for element access at either head or tail, random access to elements * is not very fast; in this case use Vector. Concurrent access is supported: a thread is blocked * while another thread adds/removes an object. When no objects are available, removal returns null. * @author Bela Ban */ public class List implements Externalizable, Cloneable { protected Element head=null, tail=null; protected int size=0; protected Object mutex=new Object(); class Element { Object obj=null; Element next=null; Element prev=null; Element(Object o) { obj=o; } } public List() { } /** Adds an object at the tail of the list. */ public void add(Object obj) { Element el=new Element(obj); synchronized(mutex) { if(head == null) { head=el; tail=head; size=1; } else { el.prev=tail; tail.next=el; tail=el; size++; } } } /** Adds an object at the head of the list. */ public void addAtHead(Object obj) { Element el=new Element(obj); synchronized(mutex) { if(head == null) { head=el; tail=head; size=1; } else { el.next=head; head.prev=el; head=el; size++; } } } /** Removes an object from the tail of the list. Returns null if no elements available */ public Object remove() { Element retval=null; synchronized(mutex) { if(tail == null) return null; retval=tail; if(head == tail) { // last element head=null; tail=null; } else { tail.prev.next=null; tail=tail.prev; retval.prev=null; } size } return retval.obj; } /** Removes an object from the head of the list. Returns null if no elements available */ public Object removeFromHead() { Element retval=null; synchronized(mutex) { if(head == null) return null; retval=head; if(head == tail) { // last element head=null; tail=null; } else { head=head.next; head.prev=null; retval.next=null; } size } return retval.obj; } /** Returns element at the tail (if present), but does not remove it from list. */ public Object peek() { synchronized(mutex) { return tail != null ? tail.obj : null; } } /** Returns element at the head (if present), but does not remove it from list. */ public Object peekAtHead() { synchronized(mutex) { return head != null ? head.obj : null; } } /** Removes element <code>obj</code> from the list, checking for equality using the <code>equals</code> operator. Only the first duplicate object is removed. Returns the removed object. */ public Object removeElement(Object obj) { Element el=null; Object retval=null; synchronized(mutex) { el=head; while(el != null) { if(el.obj.equals(obj)) { retval=el.obj; if(head == tail) { // only 1 element left in the list head=null; tail=null; } else if(el.prev == null) { // we're at the head head=el.next; head.prev=null; el.next=null; } else if(el.next == null) { // we're at the tail tail=el.prev; tail.next=null; el.prev=null; } else { // we're somewhere in the middle of the list el.prev.next=el.next; el.next.prev=el.prev; el.next=null; el.prev=null; } size break; } el=el.next; } } return retval; } public void removeAll() { synchronized(mutex) { size=0; head=null; tail=null; } } public int size() { return size; } public String toString() { StringBuffer ret=new StringBuffer("["); Element el=head; while(el != null) { if(el.obj != null) ret.append(el.obj + " "); el=el.next; } ret.append("]"); return ret.toString(); } public String dump() { StringBuffer ret=new StringBuffer("["); for(Element el=head; el != null; el=el.next) ret.append(el.obj + " "); return ret.toString() + "]"; } public Vector getContents() { Vector retval=new Vector(size); Element el; synchronized(mutex) { el=head; while(el != null) { retval.addElement(el.obj); el=el.next; } } return retval; } public Enumeration elements() { return new ListEnumerator(head); } public boolean contains(Object obj) { Element el=head; while(el != null) { if(el.obj != null && el.obj.equals(obj)) return true; el=el.next; } return false; } public List copy() { List retval=new List(); synchronized(mutex) { for(Element el=head; el != null; el=el.next) retval.add(el.obj); } return retval; } protected Object clone() { return copy(); } public void writeExternal(ObjectOutput out) throws IOException { Element el; synchronized(mutex) { el=head; out.writeInt(size); for(int i=0; i < size; i++) { out.writeObject(el.obj); el=el.next; } } } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { Object obj; int new_size=in.readInt(); if(new_size == 0) return; for(int i=0; i < new_size; i++) { obj=in.readObject(); add(obj); } } class ListEnumerator implements Enumeration { Element curr=null; ListEnumerator(Element start) { curr=start; } public boolean hasMoreElements() { return curr != null; } public Object nextElement() { Object retval; if(curr == null) throw new NoSuchElementException(); retval=curr.obj; curr=curr.next; return retval; } } // public static void main(String args[]) { // List l=new List(); // l.add("Bela"); // l.add("Janet"); // l.add("Marco"); // l.add("Ralph"); // for(Enumeration e=l.elements(); e.hasMoreElements();) { // System.out.println(e.nextElement()); // System.out.println(l + ".contains(\"Bela\"): " + l.contains("Bela")); // l.add(new Integer(1)); // l.add(new Integer(2)); // l.add(new Integer(5)); // l.add(new Integer(6)); // System.out.println(l + ".contains(2): " + l.contains(new Integer(2))); public static void main(String[] args) { List l=new List(); Long n; l.addAtHead(new Integer(1)); l.addAtHead(new Integer(2)); l.addAtHead(new Integer(3)); l.addAtHead(new Integer(4)); l.addAtHead(new Integer(5)); System.out.println("Removed from head: " + l.removeFromHead()); System.out.println("Removed from head: " + l.removeFromHead()); System.out.println("Removed from head: " + l.removeFromHead()); System.out.println("Removed from head: " + l.removeFromHead()); System.out.println("Removed from head: " + l.removeFromHead()); System.out.println("Removed from head: " + l.removeFromHead()); System.out.println("Removed from head: " + l.removeFromHead()); System.out.print("Adding 50000 numbers:"); for(long i=0; i < 50000; i++) { n=new Long(i); if(i % 2 == 0) { l.addAtHead(n); } else { l.add(n); } } System.out.println(" OK"); long num=0; Object obj; System.out.print("Removing all elements: "); while((obj=l.remove()) != null) num++; System.out.println("OK, removed " + num + " objects"); } // public static void main(String[] args) { // byte[] buf; // List l=new List(), l2, l3; // try { // for(int i=0; i < 10; i++) // l.add(new Integer(i)); // System.out.println(l.getContents()); // buf=Util.objectToByteBuffer(l); // l2=(List)Util.objectFromByteBuffer(buf); // System.out.println(l2.getContents()); // l3=new List(); l3.add("Bela"); l3.add("Janet"); // l2.add(new Integer(300)); // FileOutputStream outstream=new FileOutputStream("list.out"); // ObjectOutputStream out=new ObjectOutputStream(outstream); // out.writeObject(l2); out.writeObject(l3); // FileInputStream instream=new FileInputStream("list.out"); // ObjectInputStream in=new ObjectInputStream(instream); // l=(List)in.readObject(); // System.out.println(l.getContents()); // l=(List)in.readObject(); // System.out.println(l.getContents()); // //l=(List)in.readObject(); // //System.out.println(l.getContents()); // catch(Exception e) { }
package org.jgroups.util; import org.apache.commons.logging.LogFactory; import org.jgroups.*; import org.jgroups.auth.AuthToken; import org.jgroups.conf.ClassConfigurator; import org.jgroups.protocols.FD; import org.jgroups.protocols.PingHeader; import org.jgroups.protocols.UdpHeader; import org.jgroups.protocols.pbcast.NakAckHeader; import org.jgroups.stack.IpAddress; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import java.io.*; import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.net.*; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; import java.security.MessageDigest; import java.text.NumberFormat; import java.util.*; /** * Collection of various utility routines that can not be assigned to other classes. * @author Bela Ban * @version $Id: Util.java,v 1.132 2007/08/21 08:52:39 belaban Exp $ */ public class Util { private static final ByteArrayOutputStream out_stream=new ByteArrayOutputStream(512); private static NumberFormat f; private static Map PRIMITIVE_TYPES=new HashMap(10); private static final byte TYPE_NULL = 0; private static final byte TYPE_STREAMABLE = 1; private static final byte TYPE_SERIALIZABLE = 2; private static final byte TYPE_BOOLEAN = 10; private static final byte TYPE_BYTE = 11; private static final byte TYPE_CHAR = 12; private static final byte TYPE_DOUBLE = 13; private static final byte TYPE_FLOAT = 14; private static final byte TYPE_INT = 15; private static final byte TYPE_LONG = 16; private static final byte TYPE_SHORT = 17; private static final byte TYPE_STRING = 18; // constants public static final int MAX_PORT=65535; // highest port allocatable static boolean resolve_dns=false; static boolean JGROUPS_COMPAT=false; /** * Global thread group to which all (most!) JGroups threads belong */ private static ThreadGroup GLOBAL_GROUP=new ThreadGroup("JGroups") { public void uncaughtException(Thread t, Throwable e) { LogFactory.getLog("org.jgroups").error("uncaught exception in " + t + " (thread group=" + GLOBAL_GROUP + " )", e); } }; public static ThreadGroup getGlobalThreadGroup() { return GLOBAL_GROUP; } static { try { resolve_dns=Boolean.valueOf(System.getProperty("resolve.dns", "false")).booleanValue(); } catch (SecurityException ex){ resolve_dns=false; } f=NumberFormat.getNumberInstance(); f.setGroupingUsed(false); f.setMaximumFractionDigits(2); try { String tmp=Util.getProperty(new String[]{Global.MARSHALLING_COMPAT}, null, null, false, "false"); JGROUPS_COMPAT=Boolean.valueOf(tmp).booleanValue(); } catch (SecurityException ex){ } PRIMITIVE_TYPES.put(Boolean.class, new Byte(TYPE_BOOLEAN)); PRIMITIVE_TYPES.put(Byte.class, new Byte(TYPE_BYTE)); PRIMITIVE_TYPES.put(Character.class, new Byte(TYPE_CHAR)); PRIMITIVE_TYPES.put(Double.class, new Byte(TYPE_DOUBLE)); PRIMITIVE_TYPES.put(Float.class, new Byte(TYPE_FLOAT)); PRIMITIVE_TYPES.put(Integer.class, new Byte(TYPE_INT)); PRIMITIVE_TYPES.put(Long.class, new Byte(TYPE_LONG)); PRIMITIVE_TYPES.put(Short.class, new Byte(TYPE_SHORT)); PRIMITIVE_TYPES.put(String.class, new Byte(TYPE_STRING)); } /** * Verifies that val is <= max memory * @param buf_name * @param val */ public static void checkBufferSize(String buf_name, long val) { // sanity check that max_credits doesn't exceed memory allocated to VM by -Xmx long max_mem=Runtime.getRuntime().maxMemory(); if(val > max_mem) { throw new IllegalArgumentException(buf_name + "(" + Util.printBytes(val) + ") exceeds max memory allocated to VM (" + Util.printBytes(max_mem) + ")"); } } public static void close(InputStream inp) { if(inp != null) try {inp.close();} catch(IOException e) {} } public static void close(OutputStream out) { if(out != null) { try {out.close();} catch(IOException e) {} } } public static void close(Socket s) { if(s != null) { try {s.close();} catch(Exception ex) {} } } public static void close(DatagramSocket my_sock) { if(my_sock != null) { try {my_sock.close();} catch(Throwable t) {} } } /** * Creates an object from a byte buffer */ public static Object objectFromByteBuffer(byte[] buffer) throws Exception { if(buffer == null) return null; if(JGROUPS_COMPAT) return oldObjectFromByteBuffer(buffer); return objectFromByteBuffer(buffer, 0, buffer.length); } public static Object objectFromByteBuffer(byte[] buffer, int offset, int length) throws Exception { if(buffer == null) return null; if(JGROUPS_COMPAT) return oldObjectFromByteBuffer(buffer, offset, length); Object retval=null; InputStream in=null; ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer, offset, length); byte b=(byte)in_stream.read(); try { switch(b) { case TYPE_NULL: return null; case TYPE_STREAMABLE: in=new DataInputStream(in_stream); retval=readGenericStreamable((DataInputStream)in); break; case TYPE_SERIALIZABLE: // the object is Externalizable or Serializable in=new ContextObjectInputStream(in_stream); // changed Nov 29 2004 (bela) retval=((ContextObjectInputStream)in).readObject(); break; case TYPE_BOOLEAN: in=new DataInputStream(in_stream); retval=Boolean.valueOf(((DataInputStream)in).readBoolean()); break; case TYPE_BYTE: in=new DataInputStream(in_stream); retval=new Byte(((DataInputStream)in).readByte()); break; case TYPE_CHAR: in=new DataInputStream(in_stream); retval=new Character(((DataInputStream)in).readChar()); break; case TYPE_DOUBLE: in=new DataInputStream(in_stream); retval=new Double(((DataInputStream)in).readDouble()); break; case TYPE_FLOAT: in=new DataInputStream(in_stream); retval=new Float(((DataInputStream)in).readFloat()); break; case TYPE_INT: in=new DataInputStream(in_stream); retval=new Integer(((DataInputStream)in).readInt()); break; case TYPE_LONG: in=new DataInputStream(in_stream); retval=new Long(((DataInputStream)in).readLong()); break; case TYPE_SHORT: in=new DataInputStream(in_stream); retval=new Short(((DataInputStream)in).readShort()); break; case TYPE_STRING: in=new DataInputStream(in_stream); if(((DataInputStream)in).readBoolean()) { // large string ObjectInputStream ois=new ObjectInputStream(in); try { return ois.readObject(); } finally { ois.close(); } } else { retval=((DataInputStream)in).readUTF(); } break; default: throw new IllegalArgumentException("type " + b + " is invalid"); } return retval; } finally { Util.close(in); } } /** * Serializes/Streams an object into a byte buffer. * The object has to implement interface Serializable or Externalizable * or Streamable. Only Streamable objects are interoperable w/ jgroups-me */ public static byte[] objectToByteBuffer(Object obj) throws Exception { if(JGROUPS_COMPAT) return oldObjectToByteBuffer(obj); byte[] result=null; synchronized(out_stream) { out_stream.reset(); if(obj == null) { out_stream.write(TYPE_NULL); out_stream.flush(); return out_stream.toByteArray(); } OutputStream out=null; Byte type; try { if(obj instanceof Streamable) { // use Streamable if we can out_stream.write(TYPE_STREAMABLE); out=new DataOutputStream(out_stream); writeGenericStreamable((Streamable)obj, (DataOutputStream)out); } else if((type=(Byte)PRIMITIVE_TYPES.get(obj.getClass())) != null) { out_stream.write(type.byteValue()); out=new DataOutputStream(out_stream); switch(type.byteValue()) { case TYPE_BOOLEAN: ((DataOutputStream)out).writeBoolean(((Boolean)obj).booleanValue()); break; case TYPE_BYTE: ((DataOutputStream)out).writeByte(((Byte)obj).byteValue()); break; case TYPE_CHAR: ((DataOutputStream)out).writeChar(((Character)obj).charValue()); break; case TYPE_DOUBLE: ((DataOutputStream)out).writeDouble(((Double)obj).doubleValue()); break; case TYPE_FLOAT: ((DataOutputStream)out).writeFloat(((Float)obj).floatValue()); break; case TYPE_INT: ((DataOutputStream)out).writeInt(((Integer)obj).intValue()); break; case TYPE_LONG: ((DataOutputStream)out).writeLong(((Long)obj).longValue()); break; case TYPE_SHORT: ((DataOutputStream)out).writeShort(((Short)obj).shortValue()); break; case TYPE_STRING: String str=(String)obj; if(str.length() > Short.MAX_VALUE) { ((DataOutputStream)out).writeBoolean(true); ObjectOutputStream oos=new ObjectOutputStream(out); try { oos.writeObject(str); } finally { oos.close(); } } else { ((DataOutputStream)out).writeBoolean(false); ((DataOutputStream)out).writeUTF(str); } break; default: throw new IllegalArgumentException("type " + type + " is invalid"); } } else { // will throw an exception if object is not serializable out_stream.write(TYPE_SERIALIZABLE); out=new ObjectOutputStream(out_stream); ((ObjectOutputStream)out).writeObject(obj); } } finally { Util.close(out); } result=out_stream.toByteArray(); } return result; } /** For backward compatibility in JBoss 4.0.2 */ public static Object oldObjectFromByteBuffer(byte[] buffer) throws Exception { if(buffer == null) return null; return oldObjectFromByteBuffer(buffer, 0, buffer.length); } public static Object oldObjectFromByteBuffer(byte[] buffer, int offset, int length) throws Exception { if(buffer == null) return null; Object retval=null; try { // to read the object as an Externalizable ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer, offset, length); ObjectInputStream in=new ContextObjectInputStream(in_stream); // changed Nov 29 2004 (bela) retval=in.readObject(); in.close(); } catch(StreamCorruptedException sce) { try { // is it Streamable? ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer, offset, length); DataInputStream in=new DataInputStream(in_stream); retval=readGenericStreamable(in); in.close(); } catch(Exception ee) { IOException tmp=new IOException("unmarshalling failed"); tmp.initCause(ee); throw tmp; } } if(retval == null) return null; return retval; } /** * Serializes/Streams an object into a byte buffer. * The object has to implement interface Serializable or Externalizable * or Streamable. Only Streamable objects are interoperable w/ jgroups-me */ public static byte[] oldObjectToByteBuffer(Object obj) throws Exception { byte[] result=null; synchronized(out_stream) { out_stream.reset(); if(obj instanceof Streamable) { // use Streamable if we can DataOutputStream out=new DataOutputStream(out_stream); writeGenericStreamable((Streamable)obj, out); out.close(); } else { ObjectOutputStream out=new ObjectOutputStream(out_stream); out.writeObject(obj); out.close(); } result=out_stream.toByteArray(); } return result; } public static Streamable streamableFromByteBuffer(Class cl, byte[] buffer) throws Exception { if(buffer == null) return null; Streamable retval=null; ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer); DataInputStream in=new DataInputStream(in_stream); // changed Nov 29 2004 (bela) retval=(Streamable)cl.newInstance(); retval.readFrom(in); in.close(); return retval; } public static Streamable streamableFromByteBuffer(Class cl, byte[] buffer, int offset, int length) throws Exception { if(buffer == null) return null; Streamable retval=null; ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer, offset, length); DataInputStream in=new DataInputStream(in_stream); // changed Nov 29 2004 (bela) retval=(Streamable)cl.newInstance(); retval.readFrom(in); in.close(); return retval; } public static byte[] streamableToByteBuffer(Streamable obj) throws Exception { byte[] result=null; synchronized(out_stream) { out_stream.reset(); DataOutputStream out=new DataOutputStream(out_stream); obj.writeTo(out); result=out_stream.toByteArray(); out.close(); } return result; } public static byte[] collectionToByteBuffer(Collection c) throws Exception { byte[] result=null; synchronized(out_stream) { out_stream.reset(); DataOutputStream out=new DataOutputStream(out_stream); Util.writeAddresses(c, out); result=out_stream.toByteArray(); out.close(); } return result; } public static int size(Address addr) { int retval=Global.BYTE_SIZE; // presence byte if(addr != null) retval+=addr.size() + Global.BYTE_SIZE; // plus type of address return retval; } public static void writeAuthToken(AuthToken token, DataOutputStream out) throws IOException{ Util.writeString(token.getName(), out); token.writeTo(out); } public static AuthToken readAuthToken(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException { try{ String type = Util.readString(in); Object obj = Class.forName(type).newInstance(); AuthToken token = (AuthToken) obj; token.readFrom(in); return token; } catch(ClassNotFoundException cnfe){ return null; } } public static void writeAddress(Address addr, DataOutputStream out) throws IOException { if(addr == null) { out.writeBoolean(false); return; } out.writeBoolean(true); if(addr instanceof IpAddress) { // regular case, we don't need to include class information about the type of Address, e.g. JmsAddress out.writeBoolean(true); addr.writeTo(out); } else { out.writeBoolean(false); writeOtherAddress(addr, out); } } public static Address readAddress(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException { Address addr=null; if(in.readBoolean() == false) return null; if(in.readBoolean()) { addr=new IpAddress(); addr.readFrom(in); } else { addr=readOtherAddress(in); } return addr; } private static Address readOtherAddress(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException { ClassConfigurator conf; try { conf=ClassConfigurator.getInstance(false); } catch(ChannelException e) { IllegalAccessException new_ex=new IllegalAccessException(); new_ex.initCause(e); throw new_ex; } int b=in.read(); short magic_number; String classname; Class cl=null; Address addr; if(b == 1) { magic_number=in.readShort(); cl=conf.get(magic_number); } else { classname=in.readUTF(); cl=conf.get(classname); } addr=(Address)cl.newInstance(); addr.readFrom(in); return addr; } private static void writeOtherAddress(Address addr, DataOutputStream out) throws IOException { ClassConfigurator conf=null; try { conf=ClassConfigurator.getInstance(false); } catch(ChannelException e) { IOException new_ex=new IOException(); new_ex.initCause(e); throw new_ex; } short magic_number=conf != null? conf.getMagicNumber(addr.getClass()) : -1; // write the class info if(magic_number == -1) { out.write(0); out.writeUTF(addr.getClass().getName()); } else { out.write(1); out.writeShort(magic_number); } // write the data itself addr.writeTo(out); } /** * Writes a Vector of Addresses. Can contain 65K addresses at most * @param v A Collection<Address> * @param out * @throws IOException */ public static void writeAddresses(Collection v, DataOutputStream out) throws IOException { if(v == null) { out.writeShort(-1); return; } out.writeShort(v.size()); Address addr; for(Iterator it=v.iterator(); it.hasNext();) { addr=(Address)it.next(); Util.writeAddress(addr, out); } } public static Collection<Address> readAddresses(DataInputStream in, Class cl) throws IOException, IllegalAccessException, InstantiationException { short length=in.readShort(); if(length < 0) return null; Collection<Address> retval=(Collection<Address>)cl.newInstance(); Address addr; for(int i=0; i < length; i++) { addr=Util.readAddress(in); retval.add(addr); } return retval; } /** * Returns the marshalled size of a Collection of Addresses. * <em>Assumes elements are of the same type !</em> * @param addrs Collection<Address> * @return long size */ public static long size(Collection addrs) { int retval=Global.SHORT_SIZE; // number of elements if(addrs != null && !addrs.isEmpty()) { Address addr=(Address)addrs.iterator().next(); retval+=size(addr) * addrs.size(); } return retval; } public static void writeStreamable(Streamable obj, DataOutputStream out) throws IOException { if(obj == null) { out.writeBoolean(false); return; } out.writeBoolean(true); obj.writeTo(out); } public static Streamable readStreamable(Class clazz, DataInputStream in) throws IOException, IllegalAccessException, InstantiationException { Streamable retval=null; if(in.readBoolean() == false) return null; retval=(Streamable)clazz.newInstance(); retval.readFrom(in); return retval; } public static void writeGenericStreamable(Streamable obj, DataOutputStream out) throws IOException { short magic_number; String classname; if(obj == null) { out.write(0); return; } try { out.write(1); magic_number=ClassConfigurator.getInstance(false).getMagicNumber(obj.getClass()); // write the magic number or the class name if(magic_number == -1) { out.writeBoolean(false); classname=obj.getClass().getName(); out.writeUTF(classname); } else { out.writeBoolean(true); out.writeShort(magic_number); } // write the contents obj.writeTo(out); } catch(ChannelException e) { throw new IOException("failed writing object of type " + obj.getClass() + " to stream: " + e.toString()); } } public static Streamable readGenericStreamable(DataInputStream in) throws IOException { Streamable retval=null; int b=in.read(); if(b == 0) return null; boolean use_magic_number=in.readBoolean(); String classname; Class clazz; try { if(use_magic_number) { short magic_number=in.readShort(); clazz=ClassConfigurator.getInstance(false).get(magic_number); if (clazz==null) { throw new ClassNotFoundException("Class for magic number "+magic_number+" cannot be found."); } } else { classname=in.readUTF(); clazz=ClassConfigurator.getInstance(false).get(classname); if (clazz==null) { throw new ClassNotFoundException(classname); } } retval=(Streamable)clazz.newInstance(); retval.readFrom(in); return retval; } catch(Exception ex) { throw new IOException("failed reading object: " + ex.toString()); } } public static void writeObject(Object obj, DataOutputStream out) throws Exception { if(obj == null || !(obj instanceof Streamable)) { byte[] buf=objectToByteBuffer(obj); out.writeShort(buf.length); out.write(buf, 0, buf.length); } else { out.writeShort(-1); writeGenericStreamable((Streamable)obj, out); } } public static Object readObject(DataInputStream in) throws Exception { short len=in.readShort(); Object retval=null; if(len == -1) { retval=readGenericStreamable(in); } else { byte[] buf=new byte[len]; in.readFully(buf, 0, len); retval=objectFromByteBuffer(buf); } return retval; } public static void writeString(String s, DataOutputStream out) throws IOException { if(s != null) { out.write(1); out.writeUTF(s); } else { out.write(0); } } public static String readString(DataInputStream in) throws IOException { int b=in.read(); if(b == 1) return in.readUTF(); return null; } public static void writeByteBuffer(byte[] buf, DataOutputStream out) throws IOException { if(buf != null) { out.write(1); out.writeInt(buf.length); out.write(buf, 0, buf.length); } else { out.write(0); } } public static byte[] readByteBuffer(DataInputStream in) throws IOException { int b=in.read(); if(b == 1) { b=in.readInt(); byte[] buf=new byte[b]; in.read(buf, 0, buf.length); return buf; } return null; } public static Buffer messageToByteBuffer(Message msg) throws IOException { ExposedByteArrayOutputStream output=new ExposedByteArrayOutputStream(512); DataOutputStream out=new DataOutputStream(output); out.writeBoolean(msg != null); if(msg != null) msg.writeTo(out); out.flush(); Buffer retval=new Buffer(output.getRawBuffer(), 0, output.size()); out.close(); output.close(); return retval; } public static Message byteBufferToMessage(byte[] buffer, int offset, int length) throws Exception { ByteArrayInputStream input=new ByteArrayInputStream(buffer, offset, length); DataInputStream in=new DataInputStream(input); if(!in.readBoolean()) return null; Message msg=new Message(false); // don't create headers, readFrom() will do this msg.readFrom(in); return msg; } /** * Marshalls a list of messages. * @param xmit_list LinkedList<Message> * @return Buffer * @throws IOException */ public static Buffer msgListToByteBuffer(List<Message> xmit_list) throws IOException { ExposedByteArrayOutputStream output=new ExposedByteArrayOutputStream(512); DataOutputStream out=new DataOutputStream(output); Buffer retval=null; out.writeInt(xmit_list.size()); for(Message msg: xmit_list) { msg.writeTo(out); } out.flush(); retval=new Buffer(output.getRawBuffer(), 0, output.size()); out.close(); output.close(); return retval; } public static List<Message> byteBufferToMessageList(byte[] buffer, int offset, int length) throws Exception { List<Message> retval=null; ByteArrayInputStream input=new ByteArrayInputStream(buffer, offset, length); DataInputStream in=new DataInputStream(input); int size=in.readInt(); if(size == 0) return null; Message msg; retval=new LinkedList<Message>(); for(int i=0; i < size; i++) { msg=new Message(false); // don't create headers, readFrom() will do this msg.readFrom(in); retval.add(msg); } return retval; } public static boolean match(Object obj1, Object obj2) { if(obj1 == null && obj2 == null) return true; if(obj1 != null) return obj1.equals(obj2); else return obj2.equals(obj1); } public static boolean match(long[] a1, long[] a2) { if(a1 == null && a2 == null) return true; if(a1 == null || a2 == null) return false; if(a1 == a2) // identity return true; // at this point, a1 != null and a2 != null if(a1.length != a2.length) return false; for(int i=0; i < a1.length; i++) { if(a1[i] != a2[i]) return false; } return true; } /** Sleep for timeout msecs. Returns when timeout has elapsed or thread was interrupted */ public static void sleep(long timeout) { try { Thread.sleep(timeout); } catch(Throwable e) { } } public static void sleep(long timeout, int nanos) { try { Thread.sleep(timeout, nanos); } catch(Throwable e) { } } /** * On most UNIX systems, the minimum sleep time is 10-20ms. Even if we specify sleep(1), the thread will * sleep for at least 10-20ms. On Windows, sleep() seems to be implemented as a busy sleep, that is the * thread never relinquishes control and therefore the sleep(x) is exactly x ms long. */ public static void sleep(long msecs, boolean busy_sleep) { if(!busy_sleep) { sleep(msecs); return; } long start=System.currentTimeMillis(); long stop=start + msecs; while(stop > start) { start=System.currentTimeMillis(); } } /** Returns a random value in the range [1 - range] */ public static long random(long range) { return (long)((Math.random() * 100000) % range) + 1; } /** Sleeps between 1 and timeout milliseconds, chosen randomly. Timeout must be > 1 */ public static void sleepRandom(long timeout) { if(timeout <= 0) { return; } long r=(int)((Math.random() * 100000) % timeout) + 1; sleep(r); } /** Tosses a coin weighted with probability and returns true or false. Example: if probability=0.8, chances are that in 80% of all cases, true will be returned and false in 20%. */ public static boolean tossWeightedCoin(double probability) { long r=random(100); long cutoff=(long)(probability * 100); return r < cutoff; } public static String getHostname() { try { return InetAddress.getLocalHost().getHostName(); } catch(Exception ex) { } return "localhost"; } public static void dumpStack(boolean exit) { try { throw new Exception("Dumping stack:"); } catch(Exception e) { e.printStackTrace(); if(exit) System.exit(0); } } public static String dumpThreads() { StringBuilder sb=new StringBuilder(); ThreadMXBean bean=ManagementFactory.getThreadMXBean(); long[] ids=bean.getAllThreadIds(); ThreadInfo[] threads=bean.getThreadInfo(ids, 20); for(int i=0; i < threads.length; i++) { ThreadInfo info=threads[i]; if(info == null) continue; sb.append(info.getThreadName()).append(":\n"); StackTraceElement[] stack_trace=info.getStackTrace(); for(int j=0; j < stack_trace.length; j++) { StackTraceElement el=stack_trace[j]; sb.append("at ").append(el.getClassName()).append(".").append(el.getMethodName()); sb.append("(").append(el.getFileName()).append(":").append(el.getLineNumber()).append(")"); sb.append("\n"); } sb.append("\n\n"); } return sb.toString(); } public static boolean interruptAndWaitToDie(Thread t) { return interruptAndWaitToDie(t, Global.THREAD_SHUTDOWN_WAIT_TIME); } public static boolean interruptAndWaitToDie(Thread t, long timeout) { if(t == null) throw new IllegalArgumentException("Thread can not be null"); t.interrupt(); // interrupts the sleep() try { t.join(timeout); } catch(InterruptedException e){ Thread.currentThread().interrupt(); // set interrupt flag again } return t.isAlive(); } /** * Debugging method used to dump the content of a protocol queue in a * condensed form. Useful to follow the evolution of the queue's content in * time. */ public static String dumpQueue(Queue q) { StringBuilder sb=new StringBuilder(); LinkedList values=q.values(); if(values.isEmpty()) { sb.append("empty"); } else { for(Iterator it=values.iterator(); it.hasNext();) { Object o=it.next(); String s=null; if(o instanceof Event) { Event event=(Event)o; int type=event.getType(); s=Event.type2String(type); if(type == Event.VIEW_CHANGE) s+=" " + event.getArg(); if(type == Event.MSG) s+=" " + event.getArg(); if(type == Event.MSG) { s+="["; Message m=(Message)event.getArg(); Map headers=new HashMap(m.getHeaders()); for(Iterator i=headers.keySet().iterator(); i.hasNext();) { Object headerKey=i.next(); Object value=headers.get(headerKey); String headerToString=null; if(value instanceof FD.FdHeader) { headerToString=value.toString(); } else if(value instanceof PingHeader) { headerToString=headerKey + "-"; if(((PingHeader)value).type == PingHeader.GET_MBRS_REQ) { headerToString+="GMREQ"; } else if(((PingHeader)value).type == PingHeader.GET_MBRS_RSP) { headerToString+="GMRSP"; } else { headerToString+="UNKNOWN"; } } else { headerToString=headerKey + "-" + (value == null ? "null" : value.toString()); } s+=headerToString; if(i.hasNext()) { s+=","; } } s+="]"; } } else { s=o.toString(); } sb.append(s).append("\n"); } } return sb.toString(); } /** * Use with caution: lots of overhead */ public static String printStackTrace(Throwable t) { StringWriter s=new StringWriter(); PrintWriter p=new PrintWriter(s); t.printStackTrace(p); return s.toString(); } public static String getStackTrace(Throwable t) { return printStackTrace(t); } public static String print(Throwable t) { return printStackTrace(t); } public static void crash() { System.exit(-1); } public static String printEvent(Event evt) { Message msg; if(evt.getType() == Event.MSG) { msg=(Message)evt.getArg(); if(msg != null) { if(msg.getLength() > 0) return printMessage(msg); else return msg.printObjectHeaders(); } } return evt.toString(); } /** Tries to read an object from the message's buffer and prints it */ public static String printMessage(Message msg) { if(msg == null) return ""; if(msg.getLength() == 0) return null; try { return msg.getObject().toString(); } catch(Exception e) { // it is not an object return ""; } } /** Tries to read a <code>MethodCall</code> object from the message's buffer and prints it. Returns empty string if object is not a method call */ public static String printMethodCall(Message msg) { Object obj; if(msg == null) return ""; if(msg.getLength() == 0) return ""; try { obj=msg.getObject(); return obj.toString(); } catch(Exception e) { // it is not an object return ""; } } public static void printThreads() { Thread threads[]=new Thread[Thread.activeCount()]; Thread.enumerate(threads); System.out.println(" for(int i=0; i < threads.length; i++) { System.out.println("#" + i + ": " + threads[i]); } System.out.println(" } public static String activeThreads() { StringBuilder sb=new StringBuilder(); Thread threads[]=new Thread[Thread.activeCount()]; Thread.enumerate(threads); sb.append(" for(int i=0; i < threads.length; i++) { sb.append("#").append(i).append(": ").append(threads[i]).append('\n'); } sb.append(" return sb.toString(); } public static String printBytes(long bytes) { double tmp; if(bytes < 1000) return bytes + "b"; if(bytes < 1000000) { tmp=bytes / 1000.0; return f.format(tmp) + "KB"; } if(bytes < 1000000000) { tmp=bytes / 1000000.0; return f.format(tmp) + "MB"; } else { tmp=bytes / 1000000000.0; return f.format(tmp) + "GB"; } } public static String printBytes(double bytes) { double tmp; if(bytes < 1000) return bytes + "b"; if(bytes < 1000000) { tmp=bytes / 1000.0; return f.format(tmp) + "KB"; } if(bytes < 1000000000) { tmp=bytes / 1000000.0; return f.format(tmp) + "MB"; } else { tmp=bytes / 1000000000.0; return f.format(tmp) + "GB"; } } /** Fragments a byte buffer into smaller fragments of (max.) frag_size. Example: a byte buffer of 1024 bytes and a frag_size of 248 gives 4 fragments of 248 bytes each and 1 fragment of 32 bytes. @return An array of byte buffers (<code>byte[]</code>). */ public static byte[][] fragmentBuffer(byte[] buf, int frag_size, final int length) { byte[] retval[]; int accumulated_size=0; byte[] fragment; int tmp_size=0; int num_frags; int index=0; num_frags=length % frag_size == 0 ? length / frag_size : length / frag_size + 1; retval=new byte[num_frags][]; while(accumulated_size < length) { if(accumulated_size + frag_size <= length) tmp_size=frag_size; else tmp_size=length - accumulated_size; fragment=new byte[tmp_size]; System.arraycopy(buf, accumulated_size, fragment, 0, tmp_size); retval[index++]=fragment; accumulated_size+=tmp_size; } return retval; } public static byte[][] fragmentBuffer(byte[] buf, int frag_size) { return fragmentBuffer(buf, frag_size, buf.length); } /** * Given a buffer and a fragmentation size, compute a list of fragmentation offset/length pairs, and * return them in a list. Example:<br/> * Buffer is 10 bytes, frag_size is 4 bytes. Return value will be ({0,4}, {4,4}, {8,2}). * This is a total of 3 fragments: the first fragment starts at 0, and has a length of 4 bytes, the second fragment * starts at offset 4 and has a length of 4 bytes, and the last fragment starts at offset 8 and has a length * of 2 bytes. * @param frag_size * @return List. A List<Range> of offset/length pairs */ public static java.util.List computeFragOffsets(int offset, int length, int frag_size) { java.util.List retval=new ArrayList(); long total_size=length + offset; int index=offset; int tmp_size=0; Range r; while(index < total_size) { if(index + frag_size <= total_size) tmp_size=frag_size; else tmp_size=(int)(total_size - index); r=new Range(index, tmp_size); retval.add(r); index+=tmp_size; } return retval; } public static java.util.List computeFragOffsets(byte[] buf, int frag_size) { return computeFragOffsets(0, buf.length, frag_size); } /** Concatenates smaller fragments into entire buffers. @param fragments An array of byte buffers (<code>byte[]</code>) @return A byte buffer */ public static byte[] defragmentBuffer(byte[] fragments[]) { int total_length=0; byte[] ret; int index=0; if(fragments == null) return null; for(int i=0; i < fragments.length; i++) { if(fragments[i] == null) continue; total_length+=fragments[i].length; } ret=new byte[total_length]; for(int i=0; i < fragments.length; i++) { if(fragments[i] == null) continue; System.arraycopy(fragments[i], 0, ret, index, fragments[i].length); index+=fragments[i].length; } return ret; } public static void printFragments(byte[] frags[]) { for(int i=0; i < frags.length; i++) System.out.println('\'' + new String(frags[i]) + '\''); } public static <T> String printListWithDelimiter(Collection<T> list, String delimiter) { boolean first=true; StringBuilder sb=new StringBuilder(); for(T el: list) { if(first) { first=false; } else { sb.append(delimiter); } sb.append(el); } return sb.toString(); } // /** // Peeks for view on the channel until n views have been received or timeout has elapsed. // Used to determine the view in which we want to start work. Usually, we start as only // member in our own view (1st view) and the next view (2nd view) will be the full view // of all members, or a timeout if we're the first member. If a non-view (a message or // block) is received, the method returns immediately. // @param channel The channel used to peek for views. Has to be operational. // @param number_of_views The number of views to wait for. 2 is a good number to ensure that, // if there are other members, we start working with them included in our view. // @param timeout Number of milliseconds to wait until view is forced to return. A value // of <= 0 means wait forever. // */ // public static View peekViews(Channel channel, int number_of_views, long timeout) { // View retval=null; // Object obj=null; // int num=0; // long start_time=System.currentTimeMillis(); // if(timeout <= 0) { // while(true) { // try { // obj=channel.peek(0); // if(obj == null || !(obj instanceof View)) // break; // else { // retval=(View)channel.receive(0); // num++; // if(num >= number_of_views) // break; // catch(Exception ex) { // break; // else { // while(timeout > 0) { // try { // obj=channel.peek(timeout); // if(obj == null || !(obj instanceof View)) // break; // else { // retval=(View)channel.receive(timeout); // num++; // if(num >= number_of_views) // break; // catch(Exception ex) { // break; // timeout=timeout - (System.currentTimeMillis() - start_time); // return retval; public static String array2String(long[] array) { StringBuilder ret=new StringBuilder("["); if(array != null) { for(int i=0; i < array.length; i++) ret.append(array[i]).append(" "); } ret.append(']'); return ret.toString(); } public static String array2String(short[] array) { StringBuilder ret=new StringBuilder("["); if(array != null) { for(int i=0; i < array.length; i++) ret.append(array[i]).append(" "); } ret.append(']'); return ret.toString(); } public static String array2String(int[] array) { StringBuilder ret=new StringBuilder("["); if(array != null) { for(int i=0; i < array.length; i++) ret.append(array[i]).append(" "); } ret.append(']'); return ret.toString(); } public static String array2String(boolean[] array) { StringBuilder ret=new StringBuilder("["); if(array != null) { for(int i=0; i < array.length; i++) ret.append(array[i]).append(" "); } ret.append(']'); return ret.toString(); } public static String array2String(Object[] array) { StringBuilder ret=new StringBuilder("["); if(array != null) { for(int i=0; i < array.length; i++) ret.append(array[i]).append(" "); } ret.append(']'); return ret.toString(); } /** Returns true if all elements of c match obj */ public static boolean all(Collection c, Object obj) { for(Iterator iterator=c.iterator(); iterator.hasNext();) { Object o=iterator.next(); if(!o.equals(obj)) return false; } return true; } /** * Selects a random subset of members according to subset_percentage and returns them. * Picks no member twice from the same membership. If the percentage is smaller than 1 -> picks 1 member. */ public static Vector pickSubset(Vector members, double subset_percentage) { Vector ret=new Vector(), tmp_mbrs; int num_mbrs=members.size(), subset_size, index; if(num_mbrs == 0) return ret; subset_size=(int)Math.ceil(num_mbrs * subset_percentage); tmp_mbrs=(Vector)members.clone(); for(int i=subset_size; i > 0 && !tmp_mbrs.isEmpty(); i index=(int)((Math.random() * num_mbrs) % tmp_mbrs.size()); ret.addElement(tmp_mbrs.elementAt(index)); tmp_mbrs.removeElementAt(index); } return ret; } public static Object pickRandomElement(List list) { if(list == null) return null; int size=list.size(); int index=(int)((Math.random() * size * 10) % size); return list.get(index); } /** * Returns all members that left between 2 views. All members that are element of old_mbrs but not element of * new_mbrs are returned. */ public static Vector<Address> determineLeftMembers(Vector<Address> old_mbrs, Vector<Address> new_mbrs) { Vector<Address> retval=new Vector<Address>(); Address mbr; if(old_mbrs == null || new_mbrs == null) return retval; for(int i=0; i < old_mbrs.size(); i++) { mbr=old_mbrs.elementAt(i); if(!new_mbrs.contains(mbr)) retval.addElement(mbr); } return retval; } public static String printMembers(Vector v) { StringBuilder sb=new StringBuilder("("); boolean first=true; Object el; if(v != null) { for(int i=0; i < v.size(); i++) { if(!first) sb.append(", "); else first=false; el=v.elementAt(i); sb.append(el); } } sb.append(')'); return sb.toString(); } /** Makes sure that we detect when a peer connection is in the closed state (not closed while we send data, but before we send data). Two writes ensure that, if the peer closed the connection, the first write will send the peer from FIN to RST state, and the second will cause a signal (IOException). */ public static void doubleWrite(byte[] buf, OutputStream out) throws Exception { if(buf.length > 1) { out.write(buf, 0, 1); out.write(buf, 1, buf.length - 1); } else { out.write(buf, 0, 0); out.write(buf); } } /** Makes sure that we detect when a peer connection is in the closed state (not closed while we send data, but before we send data). Two writes ensure that, if the peer closed the connection, the first write will send the peer from FIN to RST state, and the second will cause a signal (IOException). */ public static void doubleWrite(byte[] buf, int offset, int length, OutputStream out) throws Exception { if(length > 1) { out.write(buf, offset, 1); out.write(buf, offset+1, length - 1); } else { out.write(buf, offset, 0); out.write(buf, offset, length); } } /** * if we were to register for OP_WRITE and send the remaining data on * readyOps for this channel we have to either block the caller thread or * queue the message buffers that may arrive while waiting for OP_WRITE. * Instead of the above approach this method will continuously write to the * channel until the buffer sent fully. */ public static void writeFully(ByteBuffer buf, WritableByteChannel out) throws IOException { int written = 0; int toWrite = buf.limit(); while (written < toWrite) { written += out.write(buf); } } // /* double writes are not required.*/ // public static void doubleWriteBuffer( // ByteBuffer buf, // WritableByteChannel out) // throws Exception // if (buf.limit() > 1) // int actualLimit = buf.limit(); // buf.limit(1); // writeFully(buf,out); // buf.limit(actualLimit); // writeFully(buf,out); // else // buf.limit(0); // writeFully(buf,out); // buf.limit(1); // writeFully(buf,out); public static long sizeOf(String classname) { Object inst; byte[] data; try { inst=Util.loadClass(classname, null).newInstance(); data=Util.objectToByteBuffer(inst); return data.length; } catch(Exception ex) { return -1; } } public static long sizeOf(Object inst) { byte[] data; try { data=Util.objectToByteBuffer(inst); return data.length; } catch(Exception ex) { return -1; } } public static int sizeOf(Streamable inst) { byte[] data; ByteArrayOutputStream output; DataOutputStream out; try { output=new ByteArrayOutputStream(); out=new DataOutputStream(output); inst.writeTo(out); out.flush(); data=output.toByteArray(); return data.length; } catch(Exception ex) { return -1; } } /** * Tries to load the class from the current thread's context class loader. If * not successful, tries to load the class from the current instance. * @param classname Desired class. * @param clazz Class object used to obtain a class loader * if no context class loader is available. * @return Class, or null on failure. */ public static Class loadClass(String classname, Class clazz) throws ClassNotFoundException { ClassLoader loader; try { loader=Thread.currentThread().getContextClassLoader(); if(loader != null) { return loader.loadClass(classname); } } catch(Throwable t) { } if(clazz != null) { try { loader=clazz.getClassLoader(); if(loader != null) { return loader.loadClass(classname); } } catch(Throwable t) { } } try { loader=ClassLoader.getSystemClassLoader(); if(loader != null) { return loader.loadClass(classname); } } catch(Throwable t) { } throw new ClassNotFoundException(classname); } public static InputStream getResourceAsStream(String name, Class clazz) { ClassLoader loader; InputStream retval=null; try { loader=Thread.currentThread().getContextClassLoader(); if(loader != null) { retval=loader.getResourceAsStream(name); if(retval != null) return retval; } } catch(Throwable t) { } if(clazz != null) { try { loader=clazz.getClassLoader(); if(loader != null) { retval=loader.getResourceAsStream(name); if(retval != null) return retval; } } catch(Throwable t) { } } try { loader=ClassLoader.getSystemClassLoader(); if(loader != null) { return loader.getResourceAsStream(name); } } catch(Throwable t) { } return retval; } /** Checks whether 2 Addresses are on the same host */ public static boolean sameHost(Address one, Address two) { InetAddress a, b; String host_a, host_b; if(one == null || two == null) return false; if(!(one instanceof IpAddress) || !(two instanceof IpAddress)) { return false; } a=((IpAddress)one).getIpAddress(); b=((IpAddress)two).getIpAddress(); if(a == null || b == null) return false; host_a=a.getHostAddress(); host_b=b.getHostAddress(); // System.out.println("host_a=" + host_a + ", host_b=" + host_b); return host_a.equals(host_b); } public static boolean fileExists(String fname) { return (new File(fname)).exists(); } /** * Parses comma-delimited longs; e.g., 2000,4000,8000. * Returns array of long, or null. */ public static long[] parseCommaDelimitedLongs(String s) { StringTokenizer tok; Vector v=new Vector(); Long l; long[] retval=null; if(s == null) return null; tok=new StringTokenizer(s, ","); while(tok.hasMoreTokens()) { l=new Long(tok.nextToken()); v.addElement(l); } if(v.isEmpty()) return null; retval=new long[v.size()]; for(int i=0; i < v.size(); i++) retval[i]=((Long)v.elementAt(i)).longValue(); return retval; } /** e.g. "bela,jeannette,michelle" --> List{"bela", "jeannette", "michelle"} */ public static java.util.List parseCommaDelimitedStrings(String l) { return parseStringList(l, ","); } public static List parseStringList(String l, String separator) { List tmp=new LinkedList(); StringTokenizer tok=new StringTokenizer(l, separator); String t; while(tok.hasMoreTokens()) { t=tok.nextToken(); tmp.add(t.trim()); } return tmp; } public static int parseInt(Properties props,String property,int defaultValue) { int result = defaultValue; String str=props.getProperty(property); if(str != null) { result=Integer.parseInt(str); props.remove(property); } return result; } public static long parseLong(Properties props,String property,long defaultValue) { long result = defaultValue; String str=props.getProperty(property); if(str != null) { result=Integer.parseInt(str); props.remove(property); } return result; } public static boolean parseBoolean(Properties props,String property,boolean defaultValue) { boolean result = defaultValue; String str=props.getProperty(property); if(str != null) { result=str.equalsIgnoreCase("true"); props.remove(property); } return result; } public static InetAddress parseBindAddress(Properties props, String property) throws UnknownHostException { InetAddress bind_addr=null; boolean ignore_systemprops=Util.isBindAddressPropertyIgnored(); String str=Util.getProperty(new String[]{Global.BIND_ADDR, Global.BIND_ADDR_OLD}, props, "bind_addr", ignore_systemprops, null); if(str != null) { bind_addr=InetAddress.getByName(str); props.remove(property); } return bind_addr; } /** * * @param s * @return List<NetworkInterface> */ public static List<NetworkInterface> parseInterfaceList(String s) throws Exception { List<NetworkInterface> interfaces=new ArrayList<NetworkInterface>(10); if(s == null) return null; StringTokenizer tok=new StringTokenizer(s, ","); String interface_name; NetworkInterface intf; while(tok.hasMoreTokens()) { interface_name=tok.nextToken(); // try by name first (e.g. (eth0") intf=NetworkInterface.getByName(interface_name); // next try by IP address or symbolic name if(intf == null) intf=NetworkInterface.getByInetAddress(InetAddress.getByName(interface_name)); if(intf == null) throw new Exception("interface " + interface_name + " not found"); if(!interfaces.contains(intf)) { interfaces.add(intf); } } return interfaces; } public static String print(List<NetworkInterface> interfaces) { StringBuilder sb=new StringBuilder(); boolean first=true; for(NetworkInterface intf: interfaces) { if(first) { first=false; } else { sb.append(", "); } sb.append(intf.getName()); } return sb.toString(); } public static String shortName(String hostname) { int index; StringBuilder sb=new StringBuilder(); if(hostname == null) return null; index=hostname.indexOf('.'); if(index > 0 && !Character.isDigit(hostname.charAt(0))) sb.append(hostname.substring(0, index)); else sb.append(hostname); return sb.toString(); } public static String shortName(InetAddress hostname) { if(hostname == null) return null; StringBuilder sb=new StringBuilder(); if(resolve_dns) sb.append(hostname.getHostName()); else sb.append(hostname.getHostAddress()); return sb.toString(); } /** Finds first available port starting at start_port and returns server socket */ public static ServerSocket createServerSocket(int start_port) { ServerSocket ret=null; while(true) { try { ret=new ServerSocket(start_port); } catch(BindException bind_ex) { start_port++; continue; } catch(IOException io_ex) { } break; } return ret; } public static ServerSocket createServerSocket(InetAddress bind_addr, int start_port) { ServerSocket ret=null; while(true) { try { ret=new ServerSocket(start_port, 50, bind_addr); } catch(BindException bind_ex) { start_port++; continue; } catch(IOException io_ex) { } break; } return ret; } /** * Creates a DatagramSocket bound to addr. If addr is null, socket won't be bound. If address is already in use, * start_port will be incremented until a socket can be created. * @param addr The InetAddress to which the socket should be bound. If null, the socket will not be bound. * @param port The port which the socket should use. If 0, a random port will be used. If > 0, but port is already * in use, it will be incremented until an unused port is found, or until MAX_PORT is reached. */ public static DatagramSocket createDatagramSocket(InetAddress addr, int port) throws Exception { DatagramSocket sock=null; if(addr == null) { if(port == 0) { return new DatagramSocket(); } else { while(port < MAX_PORT) { try { return new DatagramSocket(port); } catch(BindException bind_ex) { // port already used port++; } catch(Exception ex) { throw ex; } } } } else { if(port == 0) port=1024; while(port < MAX_PORT) { try { return new DatagramSocket(port, addr); } catch(BindException bind_ex) { // port already used port++; } catch(Exception ex) { throw ex; } } } return sock; // will never be reached, but the stupid compiler didn't figure it out... } /** * Returns the address of the interface to use defined by bind_addr and bind_interface * @param props * @return * @throws UnknownHostException * @throws SocketException */ public static InetAddress getBindAddress(Properties props) throws UnknownHostException, SocketException { boolean ignore_systemprops=Util.isBindAddressPropertyIgnored(); String bind_addr=Util.getProperty(new String[]{Global.BIND_ADDR, Global.BIND_ADDR_OLD}, props, "bind_addr", ignore_systemprops, null); String bind_interface=Util.getProperty(new String[]{Global.BIND_INTERFACE, null}, props, "bind_interface", ignore_systemprops, null); InetAddress retval=null, bind_addr_host=null; if(bind_addr != null) { try { bind_addr_host=InetAddress.getByName(bind_addr); } catch(UnknownHostException e) { } } if(bind_interface != null) { NetworkInterface intf=NetworkInterface.getByName(bind_interface); if(intf != null) { for(Enumeration<InetAddress> addresses=intf.getInetAddresses(); addresses.hasMoreElements();) { InetAddress addr=addresses.nextElement(); if(bind_addr == null) { retval=addr; break; } else { if(bind_addr_host != null) { if(bind_addr_host.equals(addr)) { retval=addr; break; } } else if(addr.getHostAddress().trim().equalsIgnoreCase(bind_addr)) { retval=addr; break; } } } } else { throw new UnknownHostException("network interface " + bind_interface + " not found"); } } if(retval == null) { retval=bind_addr != null? InetAddress.getByName(bind_addr) : InetAddress.getLocalHost(); } props.remove("bind_addr"); props.remove("bind_interface"); return retval; } public static boolean checkForLinux() { String os=System.getProperty("os.name"); return os != null && os.toLowerCase().startsWith("linux"); } public static boolean checkForSolaris() { String os=System.getProperty("os.name"); return os != null && os.toLowerCase().startsWith("sun"); } public static boolean checkForWindows() { String os=System.getProperty("os.name"); return os != null && os.toLowerCase().startsWith("win"); } public static void prompt(String s) { System.out.println(s); System.out.flush(); try { while(System.in.available() > 0) System.in.read(); System.in.read(); } catch(IOException e) { e.printStackTrace(); } } public static int getJavaVersion() { String version=System.getProperty("java.version"); int retval=0; if(version != null) { if(version.startsWith("1.2")) return 12; if(version.startsWith("1.3")) return 13; if(version.startsWith("1.4")) return 14; if(version.startsWith("1.5")) return 15; if(version.startsWith("5")) return 15; if(version.startsWith("1.6")) return 16; if(version.startsWith("6")) return 16; } return retval; } public static <T> Vector<T> unmodifiableVector(Vector<? extends T> v) { if(v == null) return null; return new UnmodifiableVector(v); } public static String memStats(boolean gc) { StringBuilder sb=new StringBuilder(); Runtime rt=Runtime.getRuntime(); if(gc) rt.gc(); long free_mem, total_mem, used_mem; free_mem=rt.freeMemory(); total_mem=rt.totalMemory(); used_mem=total_mem - free_mem; sb.append("Free mem: ").append(free_mem).append("\nUsed mem: ").append(used_mem); sb.append("\nTotal mem: ").append(total_mem); return sb.toString(); } // public static InetAddress getFirstNonLoopbackAddress() throws SocketException { // Enumeration en=NetworkInterface.getNetworkInterfaces(); // while(en.hasMoreElements()) { // NetworkInterface i=(NetworkInterface)en.nextElement(); // for(Enumeration en2=i.getInetAddresses(); en2.hasMoreElements();) { // InetAddress addr=(InetAddress)en2.nextElement(); // if(!addr.isLoopbackAddress()) // return addr; // return null; public static InetAddress getFirstNonLoopbackAddress() throws SocketException { Enumeration en=NetworkInterface.getNetworkInterfaces(); boolean preferIpv4=Boolean.getBoolean("java.net.preferIPv4Stack"); boolean preferIPv6=Boolean.getBoolean("java.net.preferIPv6Addresses"); while(en.hasMoreElements()) { NetworkInterface i=(NetworkInterface)en.nextElement(); for(Enumeration en2=i.getInetAddresses(); en2.hasMoreElements();) { InetAddress addr=(InetAddress)en2.nextElement(); if(!addr.isLoopbackAddress()) { if(addr instanceof Inet4Address) { if(preferIPv6) continue; return addr; } if(addr instanceof Inet6Address) { if(preferIpv4) continue; return addr; } } } } return null; } public static InetAddress getFirstNonLoopbackIPv6Address() throws SocketException { Enumeration en=NetworkInterface.getNetworkInterfaces(); while(en.hasMoreElements()) { NetworkInterface i=(NetworkInterface)en.nextElement(); for(Enumeration en2=i.getInetAddresses(); en2.hasMoreElements();) { InetAddress addr=(InetAddress)en2.nextElement(); if(!addr.isLoopbackAddress()) { if(addr instanceof Inet4Address) { continue; } if(addr instanceof Inet6Address) { return addr; } } } } return null; } public static List<NetworkInterface> getAllAvailableInterfaces() throws SocketException { List retval=new ArrayList(10); NetworkInterface intf; for(Enumeration en=NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { intf=(NetworkInterface)en.nextElement(); retval.add(intf); } return retval; } /** * Returns a value associated wither with one or more system properties, or found in the props map * @param system_props * @param props List of properties read from the configuration file * @param prop_name The name of the property, will be removed from props if found * @param ignore_sysprops If true, system properties are not used and the values will only be retrieved from * props (not system_props) * @param default_value Used to return a default value if the properties or system properties didn't have the value * @return The value, or null if not found */ public static String getProperty(String[] system_props, Properties props, String prop_name, boolean ignore_sysprops, String default_value) { String retval=null; if(props != null && prop_name != null) { retval=props.getProperty(prop_name); props.remove(prop_name); } if(!ignore_sysprops) { String tmp, prop; if(system_props != null) { for(int i=0; i < system_props.length; i++) { prop=system_props[i]; if(prop != null) { try { tmp=System.getProperty(prop); if(tmp != null) return tmp; // system properties override config file definitions } catch(SecurityException ex) {} } } } } if(retval == null) return default_value; return retval; } public static boolean isBindAddressPropertyIgnored() { try { String tmp=System.getProperty(Global.IGNORE_BIND_ADDRESS_PROPERTY); if(tmp == null) { tmp=System.getProperty(Global.IGNORE_BIND_ADDRESS_PROPERTY_OLD); if(tmp == null) return false; } tmp=tmp.trim().toLowerCase(); return !(tmp.equals("false") || tmp.equals("no") || tmp.equals("off")) && (tmp.equals("true") || tmp.equals("yes") || tmp.equals("on")); } catch(SecurityException ex) { return false; } } public static MBeanServer getMBeanServer() { ArrayList servers=MBeanServerFactory.findMBeanServer(null); if(servers == null || servers.isEmpty()) return null; // return 'jboss' server if available for(int i=0; i < servers.size(); i++) { MBeanServer srv=(MBeanServer)servers.get(i); if("jboss".equalsIgnoreCase(srv.getDefaultDomain())) return srv; } // return first available server return (MBeanServer)servers.get(0); } /* public static void main(String[] args) { DatagramSocket sock; InetAddress addr=null; int port=0; for(int i=0; i < args.length; i++) { if(args[i].equals("-help")) { System.out.println("Util [-help] [-addr] [-port]"); return; } if(args[i].equals("-addr")) { try { addr=InetAddress.getByName(args[++i]); continue; } catch(Exception ex) { log.error(ex); return; } } if(args[i].equals("-port")) { port=Integer.parseInt(args[++i]); continue; } System.out.println("Util [-help] [-addr] [-port]"); return; } try { sock=createDatagramSocket(addr, port); System.out.println("sock: local address is " + sock.getLocalAddress() + ":" + sock.getLocalPort() + ", remote address is " + sock.getInetAddress() + ":" + sock.getPort()); System.in.read(); } catch(Exception ex) { log.error(ex); } } */ public static void main(String args[]) throws Exception { ClassConfigurator.getInstance(true); Message msg=new Message(null, new IpAddress("127.0.0.1", 4444), "Bela"); int size=Util.sizeOf(msg); System.out.println("size=" + msg.size() + ", streamable size=" + size); msg.putHeader("belaban", new NakAckHeader((byte)1, 23, 34)); size=Util.sizeOf(msg); System.out.println("size=" + msg.size() + ", streamable size=" + size); msg.putHeader("bla", new UdpHeader("groupname")); size=Util.sizeOf(msg); System.out.println("size=" + msg.size() + ", streamable size=" + size); IpAddress a1=new IpAddress(1234), a2=new IpAddress("127.0.0.1", 3333); a1.setAdditionalData("Bela".getBytes()); size=Util.sizeOf(a1); System.out.println("size=" + a1.size() + ", streamable size of a1=" + size); size=Util.sizeOf(a2); System.out.println("size=" + a2.size() + ", streamable size of a2=" + size); // System.out.println("Check for Linux: " + checkForLinux()); // System.out.println("Check for Solaris: " + checkForSolaris()); // System.out.println("Check for Windows: " + checkForWindows()); } public static String generateList(Collection c, String separator) { if(c == null) return null; StringBuilder sb=new StringBuilder(); boolean first=true; for(Iterator it=c.iterator(); it.hasNext();) { if(first) { first=false; } else { sb.append(separator); } sb.append(it.next()); } return sb.toString(); } /** * Replaces variables of ${var:default} with System.getProperty(var, default). If no variables are found, returns * the same string, otherwise a copy of the string with variables substituted * @param val * @return A string with vars replaced, or the same string if no vars found */ public static String substituteVariable(String val) { if(val == null) return val; String retval=val, prev; while(retval.contains("${")) { // handle multiple variables in val prev=retval; retval=_substituteVar(retval); if(retval.equals(prev)) break; } return retval; } private static String _substituteVar(String val) { int start_index, end_index; start_index=val.indexOf("${"); if(start_index == -1) return val; end_index=val.indexOf("}", start_index+2); if(end_index == -1) throw new IllegalArgumentException("missing \"}\" in " + val); String tmp=getProperty(val.substring(start_index +2, end_index)); if(tmp == null) return val; StringBuilder sb=new StringBuilder(); sb.append(val.substring(0, start_index)); sb.append(tmp); sb.append(val.substring(end_index+1)); return sb.toString(); } private static String getProperty(String s) { String var, default_val, retval=null; int index=s.indexOf(":"); if(index >= 0) { var=s.substring(0, index); default_val=s.substring(index+1); retval=System.getProperty(var, default_val); } else { var=s; retval=System.getProperty(var); } return retval; } /** * Used to convert a byte array in to a java.lang.String object * @param bytes the bytes to be converted * @return the String representation */ private static String getString(byte[] bytes) { StringBuilder sb=new StringBuilder(); for (int i = 0; i < bytes.length; i++) { byte b = bytes[i]; sb.append(0x00FF & b); if (i + 1 < bytes.length) { sb.append("-"); } } return sb.toString(); } /** * Converts a java.lang.String in to a MD5 hashed String * @param source the source String * @return the MD5 hashed version of the string */ public static String md5(String source) { try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] bytes = md.digest(source.getBytes()); return getString(bytes); } catch (Exception e) { return null; } } /** * Converts a java.lang.String in to a SHA hashed String * @param source the source String * @return the MD5 hashed version of the string */ public static String sha(String source) { try { MessageDigest md = MessageDigest.getInstance("SHA"); byte[] bytes = md.digest(source.getBytes()); return getString(bytes); } catch (Exception e) { e.printStackTrace(); return null; } } }
package com.diozero.api; import java.io.Closeable; import java.nio.ByteBuffer; import java.nio.ByteOrder; import org.pmw.tinylog.Logger; import com.diozero.internal.DeviceFactoryHelper; import com.diozero.internal.spi.I2CDeviceFactoryInterface; import com.diozero.internal.spi.I2CDeviceInterface; import com.diozero.util.IOUtil; import com.diozero.util.RuntimeIOException; /** * Utility class reading / writing to I2C devices. */ public class I2CDevice implements Closeable, I2CConstants { private I2CDeviceInterface device; private int controller; private int address; private int addressSize; private int clockFrequency; private ByteOrder order; /** * @param controller * I2C bus. * @param address * I2C device address. * @param addressSize * I2C device address size. Can be 7 or 10. * @param clockFrequency * I2C clock frequency. * @throws RuntimeIOException * If an I/O error occurred. */ public I2CDevice(int controller, int address, int addressSize, int clockFrequency) throws RuntimeIOException { this(DeviceFactoryHelper.getNativeDeviceFactory(), controller, address, addressSize, clockFrequency, IOUtil.DEFAULT_BYTE_ORDER); } /** * @param controller * I2C bus. * @param address * I2C device address. * @param addressSize * I2C device address size. Can be 7 or 10. * @param clockFrequency * I2C clock frequency. * @param order * Default byte order for this device * @throws RuntimeIOException * If an I/O error occurred. */ public I2CDevice(int controller, int address, int addressSize, int clockFrequency, ByteOrder order) throws RuntimeIOException { this(DeviceFactoryHelper.getNativeDeviceFactory(), controller, address, addressSize, clockFrequency, order); } /** * @param deviceFactory * Device factory to use to provision this device. * @param controller * I2C bus. * @param address * I2C device address. * @param addressSize * I2C device address size. Can be 7 or 10. * @param clockFrequency * I2C clock frequency. * @param order * Default byte order for this device * @throws RuntimeIOException * If an I/O error occurred. */ public I2CDevice(I2CDeviceFactoryInterface deviceFactory, int controller, int address, int addressSize, int clockFrequency, ByteOrder order) throws RuntimeIOException { device = deviceFactory.provisionI2CDevice(controller, address, addressSize, clockFrequency); this.controller = controller; this.address = address; this.addressSize = addressSize; this.clockFrequency = clockFrequency; this.order = order; } public int getController() { return controller; } public int getAddress() { return address; } public int getAddressSize() { return addressSize; } public int getClockFrequency() { return clockFrequency; } @Override public void close() throws RuntimeIOException { Logger.debug("close()"); device.close(); } public final boolean isOpen() { return device.isOpen(); } /** * Writes a single byte to a register * * @param register * Register to write * @param subAddressSize * sub-address size in bytes (1 or 2) * @param value * Bytes to be written * @throws RuntimeIOException * if an I/O error occurs */ public void write(int register, int subAddressSize, byte[] value) throws RuntimeIOException { device.writeI2CBlockData(register, subAddressSize, ByteBuffer.wrap(value)); } public void writeShort(int regAddr, short val) throws RuntimeIOException { ByteBuffer buffer = ByteBuffer.allocateDirect(2); buffer.putShort(val); buffer.flip(); device.writeI2CBlockData(regAddr, SUB_ADDRESS_SIZE_1_BYTE, buffer); } public ByteBuffer read(int address, int count) { ByteBuffer buffer = ByteBuffer.allocateDirect(count); read(address, buffer); return buffer; } public void read(int address, ByteBuffer dst) throws RuntimeException { read(address, SUB_ADDRESS_SIZE_1_BYTE, dst); } public void read(int address, int subAddressSize, ByteBuffer buffer) throws RuntimeIOException { device.readI2CBlockData(address, subAddressSize, buffer); buffer.rewind(); buffer.order(order); } public byte[] read(int address, int subAddressSize, int count) throws RuntimeIOException { ByteBuffer buffer = ByteBuffer.allocateDirect(subAddressSize * count); read(address, subAddressSize, buffer); byte[] data = new byte[count]; buffer.get(data); return data; } /** * Read single byte from an 8-bit device register. * * @param regAddr * Register regAddr to read from * @throws RuntimeIOException * if an I/O error occurs * @return the byte read */ public byte readByte(int regAddr) throws RuntimeIOException { // int8_t I2Cdev::readByte(uint8_t devAddr, uint8_t regAddr, uint8_t // *data, uint16_t timeout) return device.readByteData(regAddr); } public short readUByte(int regAddr) throws RuntimeIOException { return (short) (readByte(regAddr) & 0xff); } public byte readByte(int register, int subAddressSize) throws RuntimeIOException { return device.readByteData(register); } public short readShort(int address) throws RuntimeIOException { return readShort(address, I2CConstants.SUB_ADDRESS_SIZE_1_BYTE, order); } public short readShort(int address, int subAddressSize) throws RuntimeIOException { return readShort(address, subAddressSize, order); } public short readShort(int address, int subAddressSize, ByteOrder order) throws RuntimeIOException { ByteBuffer buffer = ByteBuffer.allocateDirect(2); read(address, subAddressSize, buffer); return buffer.getShort(); } public int readUShort(int address) throws RuntimeIOException { return readUShort(address, I2CConstants.SUB_ADDRESS_SIZE_1_BYTE, order); } public int readUShort(int address, int subAddressSize) throws RuntimeIOException { return readUShort(address, subAddressSize, order); } public int readUShort(int address, int subAddressSize, ByteOrder order) throws RuntimeIOException { return readShort(address, subAddressSize, order) & 0xffff; } public long readUInt(int address, int subAddressSize, int bytes) throws RuntimeIOException { return readUInt(address, subAddressSize, bytes, order); } public long readUInt(int address, int subAddressSize, int length, ByteOrder order) throws RuntimeIOException { if (length > 4) { throw new IllegalArgumentException("Can't create an int for " + length + " bytes, max length is 4"); } ByteBuffer buffer = ByteBuffer.allocateDirect(length); read(address, subAddressSize, buffer); return IOUtil.getUInt(buffer, length, order); } // From /** * Read a single bit from an 8-bit device register. * * @param regAddr * Register regAddr to read from * @param bitNum * Bit position to read (0-7) * @return bit on/off value * @throws RuntimeIOException * if an I/O error occurs */ public boolean readBit(int regAddr, int bitNum) throws RuntimeIOException { // int8_t I2Cdev::readBit(uint8_t devAddr, uint8_t regAddr, uint8_t // bitNum, uint8_t *data, uint16_t timeout) byte b = readByte(regAddr); return (b & (1 << bitNum)) != 0; } /** * Read multiple bits from an 8-bit device register. * * @param regAddr * Register regAddr to read from * @param bitStart * First bit position to read (0-7) * @param length * Number of bits to read (not more than 8) * @return the byte read * @throws RuntimeIOException * if an I/O error occurs */ public byte readBits(int regAddr, int bitStart, int length) throws RuntimeIOException { // int8_t I2Cdev::readBits(uint8_t devAddr, uint8_t regAddr, uint8_t // bitStart, uint8_t length, uint8_t *data, uint16_t timeout) byte b = readByte(regAddr); int mask = ((1 << length) - 1) << (bitStart - length + 1); b &= mask; b >>= (bitStart - length + 1); return b; } /** * Read multiple bytes from an 8-bit device register. * * @param regAddr * First register regAddr to read from * @param length * Number of bytes to read * @throws RuntimeIOException * if an I/O error occurs * @return the bytes read */ public byte[] readBytes(int regAddr, int length) throws RuntimeIOException { // int8_t I2Cdev::readBytes(uint8_t devAddr, uint8_t regAddr, uint8_t // length, uint8_t *data, uint16_t timeout) return read(regAddr, SUB_ADDRESS_SIZE_1_BYTE, length); } /** * write a single bit in an 8-bit device register. * * @param regAddr * Register regAddr to write to * @param bitNum * Bit position to write (0-7) * @param value * New bit value to write * @throws RuntimeIOException * if an I/O error occurs */ public void writeBit(int regAddr, int bitNum, int value) throws RuntimeIOException { // bool I2Cdev::writeBit(uint8_t devAddr, uint8_t regAddr, uint8_t // bitNum, uint8_t data) writeBit(regAddr, bitNum, value != 0); } /** * write a single bit in an 8-bit device register. * * @param regAddr * Register regAddr to write to * @param bitNum * Bit position to write (0-7) * @param value * New bit value to write * @throws RuntimeIOException * if an I/O error occurs */ public void writeBit(int regAddr, int bitNum, boolean value) throws RuntimeIOException { // bool I2Cdev::writeBit(uint8_t devAddr, uint8_t regAddr, uint8_t // bitNum, uint8_t data) byte b = readByte(regAddr); b = (byte) (value ? (b | (1 << bitNum)) : (b & ~(1 << bitNum))); writeByte(regAddr, b); } /** * Write multiple bits in an 8-bit device register. * * @param regAddr * Register regAddr to write to * @param bitStart * First bit position to write (0-7) * @param length * Number of bits to write (not more than 8) * @param data * Right-aligned value to write * @throws RuntimeIOException * if an I/O error occurs */ public void writeBits(int regAddr, int bitStart, int length, int data) throws RuntimeIOException { // bool I2Cdev::writeBits(uint8_t devAddr, uint8_t regAddr, uint8_t // bitStart, uint8_t length, uint8_t data) // 010 value to write // 76543210 bit numbers // xxx args: bitStart=4, length=3 // 00011100 mask byte // 10101111 original value (sample) // 10100011 original & ~mask // 10101011 masked | value int b = readByte(regAddr); int value = data; if (b != 0) { int mask = ((1 << length) - 1) << (bitStart - length + 1); value <<= (bitStart - length + 1); // shift data into correct // position value &= mask; // zero all non-important bits in data b &= ~(mask); // zero all important bits in existing byte b |= value; // combine data with existing byte writeByte(regAddr, b); } } /** * Writes a single byte to a register * * @param register * Register to write * @param subAddressSize * sub-address size in bytes (1 or 2) * @param value * Byte to be written * @throws RuntimeIOException * if an I/O error occurs */ public void write(int register, int subAddressSize, byte value) throws RuntimeIOException { device.writeByteData(register, value); } /** * Write single byte to an 8-bit device register. * * @param regAddr * Register address to write to * @param data * New byte value to write * @throws RuntimeIOException * if an I/O error occurs */ public void writeByte(int regAddr, int data) throws RuntimeIOException { // bool I2Cdev::writeByte(uint8_t devAddr, uint8_t regAddr, uint8_t // data) device.writeByteData(regAddr, (byte) data); } /** * Write single byte to an 8-bit device register. * * @param regAddr * Register address to write to * @param data * New byte value to write * @throws RuntimeIOException * if an I/O error occurs */ public void writeByte(int regAddr, byte data) throws RuntimeIOException { // bool I2Cdev::writeByte(uint8_t devAddr, uint8_t regAddr, uint8_t // data) device.writeByteData(regAddr, data); } /** * Write single word to a 16-bit device register. * * @param regAddr * Register address to write to * @param data * New word value to write * @throws RuntimeIOException * if an I/O error occurs */ public void writeWord(int regAddr, int data) throws RuntimeIOException { // bool I2Cdev::writeWord(uint8_t devAddr, uint8_t regAddr, uint16_t // data) ByteBuffer buffer = ByteBuffer.allocateDirect(2); buffer.order(order); buffer.putShort((short) data); buffer.flip(); byte[] array = new byte[buffer.remaining()]; buffer.get(array); write(regAddr, SUB_ADDRESS_SIZE_2_BYTES, array); } /** * Write multiple bytes to an 8-bit device register. * * @param regAddr * First register address to write to * @param length * Number of bytes to write * @param data * Buffer to copy new data from * @throws RuntimeIOException * if an I/O error occurs */ public void writeBytes(int regAddr, int length, byte[] data) throws RuntimeIOException { writeBytes(regAddr, length, data, 0); } public void writeBytes(int regAddr, int length, byte[] data, int offset) throws RuntimeIOException { /* * if (I2CDEV_SERIAL_DEBUG) { System.out.format( * "I2C (0x%x) writing %d bytes to 0x%x...%n", devAddr, length, * regAddr); } */ byte[] dest = new byte[length]; System.arraycopy(data, offset, dest, 0, length); write(regAddr, SUB_ADDRESS_SIZE_1_BYTE, dest); } public void read(ByteBuffer dst) throws RuntimeException { dst.order(order); device.read(dst); dst.rewind(); } public byte readByte() throws RuntimeIOException { return device.readByte(); } public byte[] read(int count) throws RuntimeException { ByteBuffer buffer = ByteBuffer.allocateDirect(count); read(buffer); byte[] data = new byte[count]; buffer.get(data); return data; } public void write(byte[] data) throws RuntimeException { write(data, order); } public void write(byte[] data, ByteOrder order) throws RuntimeException { ByteBuffer buffer = ByteBuffer.wrap(data); buffer.order(order); device.write(buffer); } public void write(ByteBuffer buffer, int payloadLength, ByteOrder order) throws RuntimeException { buffer.rewind(); int lim = buffer.limit(); if (payloadLength <= lim) { buffer.limit(payloadLength); } buffer.order(order); device.write(buffer); buffer.limit(lim); } public void write(ByteBuffer buffer, int payloadLength) throws RuntimeException { write(buffer, payloadLength, order); } public void write(int registerAddress, int addressSize, ByteBuffer buffer, int payloadLength, ByteOrder order) throws RuntimeException { buffer.rewind(); int lim = buffer.limit(); if (payloadLength <= lim) { buffer.limit(payloadLength); } buffer.order(order); device.writeI2CBlockData(registerAddress, addressSize, buffer); buffer.limit(lim); } public void write(int registerAddress, ByteBuffer buffer, int payloadLength) throws RuntimeException { write(registerAddress, SUB_ADDRESS_SIZE_1_BYTE, buffer, payloadLength, order); } public void writeByte(byte data) throws RuntimeException { device.writeByte(data); } }
package org.jgroups.util; import org.jgroups.*; import org.jgroups.auth.AuthToken; import org.jgroups.blocks.Connection; import org.jgroups.conf.ClassConfigurator; import org.jgroups.jmx.JmxConfigurator; import org.jgroups.logging.Log; import org.jgroups.logging.LogFactory; import org.jgroups.protocols.*; import org.jgroups.protocols.pbcast.FLUSH; import org.jgroups.protocols.pbcast.GMS; import org.jgroups.stack.IpAddress; import org.jgroups.stack.Protocol; import org.jgroups.stack.ProtocolStack; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import java.io.*; import java.lang.annotation.Annotation; import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.*; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; import java.security.MessageDigest; import java.text.NumberFormat; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Collection of various utility routines that can not be assigned to other classes. * @author Bela Ban */ public class Util { private static NumberFormat f; private static Map<Class,Byte> PRIMITIVE_TYPES=new HashMap<Class,Byte>(15); private static final byte TYPE_NULL = 0; private static final byte TYPE_STREAMABLE = 1; private static final byte TYPE_SERIALIZABLE = 2; private static final byte TYPE_BOOLEAN = 10; private static final byte TYPE_BYTE = 11; private static final byte TYPE_CHAR = 12; private static final byte TYPE_DOUBLE = 13; private static final byte TYPE_FLOAT = 14; private static final byte TYPE_INT = 15; private static final byte TYPE_LONG = 16; private static final byte TYPE_SHORT = 17; private static final byte TYPE_STRING = 18; private static final byte TYPE_BYTEARRAY = 19; // constants public static final int MAX_PORT=65535; // highest port allocatable static boolean resolve_dns=false; private static short COUNTER=1; private static Pattern METHOD_NAME_TO_ATTR_NAME_PATTERN=Pattern.compile("[A-Z]+"); private static Pattern ATTR_NAME_TO_METHOD_NAME_PATTERN=Pattern.compile("_."); protected static int CCHM_INITIAL_CAPACITY=16; protected static float CCHM_LOAD_FACTOR=0.75f; protected static int CCHM_CONCURRENCY_LEVEL=16; /** * Global thread group to which all (most!) JGroups threads belong */ private static ThreadGroup GLOBAL_GROUP=new ThreadGroup("JGroups") { public void uncaughtException(Thread t, Throwable e) { LogFactory.getLog("org.jgroups").error("uncaught exception in " + t + " (thread group=" + GLOBAL_GROUP + " )", e); final ThreadGroup tgParent = getParent(); if(tgParent != null) { tgParent.uncaughtException(t,e); } } }; public static ThreadGroup getGlobalThreadGroup() { return GLOBAL_GROUP; } public static enum AddressScope {GLOBAL, SITE_LOCAL, LINK_LOCAL, LOOPBACK, NON_LOOPBACK}; private static StackType ip_stack_type=_getIpStackType(); static { try { resolve_dns=Boolean.valueOf(System.getProperty("resolve.dns", "false")).booleanValue(); } catch (SecurityException ex){ resolve_dns=false; } f=NumberFormat.getNumberInstance(); f.setGroupingUsed(false); // f.setMinimumFractionDigits(2); f.setMaximumFractionDigits(2); PRIMITIVE_TYPES.put(Boolean.class, new Byte(TYPE_BOOLEAN)); PRIMITIVE_TYPES.put(Byte.class, new Byte(TYPE_BYTE)); PRIMITIVE_TYPES.put(Character.class, new Byte(TYPE_CHAR)); PRIMITIVE_TYPES.put(Double.class, new Byte(TYPE_DOUBLE)); PRIMITIVE_TYPES.put(Float.class, new Byte(TYPE_FLOAT)); PRIMITIVE_TYPES.put(Integer.class, new Byte(TYPE_INT)); PRIMITIVE_TYPES.put(Long.class, new Byte(TYPE_LONG)); PRIMITIVE_TYPES.put(Short.class, new Byte(TYPE_SHORT)); PRIMITIVE_TYPES.put(String.class, new Byte(TYPE_STRING)); PRIMITIVE_TYPES.put(byte[].class, new Byte(TYPE_BYTEARRAY)); if(ip_stack_type == StackType.Unknown) ip_stack_type=StackType.IPv6; try { String cchm_initial_capacity=System.getProperty(Global.CCHM_INITIAL_CAPACITY); if(cchm_initial_capacity != null) CCHM_INITIAL_CAPACITY=Integer.valueOf(cchm_initial_capacity); } catch(SecurityException ex) {} try { String cchm_load_factor=System.getProperty(Global.CCHM_LOAD_FACTOR); if(cchm_load_factor != null) CCHM_LOAD_FACTOR=Float.valueOf(cchm_load_factor); } catch(SecurityException ex) {} try { String cchm_concurrency_level=System.getProperty(Global.CCHM_CONCURRENCY_LEVEL); if(cchm_concurrency_level != null) CCHM_CONCURRENCY_LEVEL=Integer.valueOf(cchm_concurrency_level); } catch(SecurityException ex) {} } public static void assertTrue(boolean condition) { assert condition; } public static void assertTrue(String message, boolean condition) { if(message != null) assert condition : message; else assert condition; } public static void assertFalse(boolean condition) { assertFalse(null, condition); } public static void assertFalse(String message, boolean condition) { if(message != null) assert !condition : message; else assert !condition; } public static void assertEquals(String message, Object val1, Object val2) { if(message != null) { assert val1.equals(val2) : message; } else { assert val1.equals(val2); } } public static void assertEquals(Object val1, Object val2) { assertEquals(null, val1, val2); } public static void assertNotNull(String message, Object val) { if(message != null) assert val != null : message; else assert val != null; } public static void assertNotNull(Object val) { assertNotNull(null, val); } public static void assertNull(String message, Object val) { if(message != null) assert val == null : message; else assert val == null; } /** * Blocks until all channels have the same view * @param timeout How long to wait (max in ms) * @param interval Check every interval ms * @param channels The channels which should form the view. The expected view size is channels.length. * Must be non-null */ public static void blockUntilViewsReceived(long timeout, long interval, Channel ... channels) throws TimeoutException { final int expected_size=channels.length; if(interval > timeout) throw new IllegalArgumentException("interval needs to be smaller than timeout"); final long end_time=System.currentTimeMillis() + timeout; while(System.currentTimeMillis() < end_time) { boolean all_ok=true; for(Channel ch: channels) { View view=ch.getView(); if(view == null || view.size() != expected_size) { all_ok=false; break; } } if(all_ok) return; Util.sleep(interval); } throw new TimeoutException(); } public static void addFlush(Channel ch, FLUSH flush) { if(ch == null || flush == null) throw new IllegalArgumentException("ch and flush have to be non-null"); ProtocolStack stack=ch.getProtocolStack(); stack.insertProtocolAtTop(flush); } public static void setScope(Message msg, short scope) { SCOPE.ScopeHeader hdr=SCOPE.ScopeHeader.createMessageHeader(scope); msg.putHeader(Global.SCOPE_ID, hdr); msg.setFlag(Message.SCOPED); } public static short getScope(Message msg) { SCOPE.ScopeHeader hdr=(SCOPE.ScopeHeader)msg.getHeader(Global.SCOPE_ID); return hdr != null? hdr.getScope() : 0; } /** * Utility method. If the dest address is IPv6, convert scoped link-local addrs into unscoped ones * @param sock * @param dest * @param sock_conn_timeout * @throws IOException */ public static void connect(Socket sock, SocketAddress dest, int sock_conn_timeout) throws IOException { if(dest instanceof InetSocketAddress) { InetAddress addr=((InetSocketAddress)dest).getAddress(); if(addr instanceof Inet6Address) { Inet6Address tmp=(Inet6Address)addr; if(tmp.getScopeId() != 0) { dest=new InetSocketAddress(InetAddress.getByAddress(tmp.getAddress()), ((InetSocketAddress)dest).getPort()); } } } sock.connect(dest, sock_conn_timeout); } public static void close(InputStream inp) { if(inp != null) try {inp.close();} catch(IOException e) {} } public static void close(OutputStream out) { if(out != null) { try {out.close();} catch(IOException e) {} } } public static void close(Socket s) { if(s != null) { try {s.close();} catch(Exception ex) {} } } public static void close(ServerSocket s) { if(s != null) { try {s.close();} catch(Exception ex) {} } } public static void close(DatagramSocket my_sock) { if(my_sock != null) { try {my_sock.close();} catch(Throwable t) {} } } public static void close(Channel ch) { if(ch != null) { try {ch.close();} catch(Throwable t) {} } } public static void close(Channel ... channels) { if(channels != null) { for(Channel ch: channels) Util.close(ch); } } public static void close(Connection conn) { if(conn != null) { try {conn.close();} catch(Throwable t) {} } } /** Drops messages to/from other members and then closes the channel. Note that this member won't get excluded from * the view until failure detection has kicked in and the new coord installed the new view */ public static void shutdown(Channel ch) throws Exception { DISCARD discard=new DISCARD(); discard.setLocalAddress(ch.getAddress()); discard.setDiscardAll(true); ProtocolStack stack=ch.getProtocolStack(); TP transport=stack.getTransport(); stack.insertProtocol(discard, ProtocolStack.ABOVE, transport.getClass()); //abruptly shutdown FD_SOCK just as in real life when member gets killed non gracefully FD_SOCK fd = (FD_SOCK) ch.getProtocolStack().findProtocol("FD_SOCK"); if(fd != null) fd.stopServerSocket(false); View view=ch.getView(); if (view != null) { ViewId vid = view.getViewId(); List<Address> members = Arrays.asList(ch.getAddress()); ViewId new_vid = new ViewId(ch.getAddress(), vid.getId() + 1); View new_view = new View(new_vid, members); // inject view in which the shut down member is the only element GMS gms = (GMS) stack.findProtocol(GMS.class); gms.installView(new_view); } Util.close(ch); } public static byte setFlag(byte bits, byte flag) { return bits |= flag; } public static boolean isFlagSet(byte bits, byte flag) { return (bits & flag) == flag; } public static byte clearFlags(byte bits, byte flag) { return bits &= ~flag; } /** * Creates an object from a byte buffer */ public static Object objectFromByteBuffer(byte[] buffer) throws Exception { if(buffer == null) return null; return objectFromByteBuffer(buffer, 0, buffer.length); } public static Object objectFromByteBuffer(byte[] buffer, int offset, int length) throws Exception { if(buffer == null) return null; Object retval=null; byte type=buffer[offset]; switch(type) { case TYPE_NULL: return null; case TYPE_STREAMABLE: ByteArrayInputStream in_stream=new ExposedByteArrayInputStream(buffer, offset+1, length-1); InputStream in=new DataInputStream(in_stream); retval=readGenericStreamable((DataInputStream)in); break; case TYPE_SERIALIZABLE: // the object is Externalizable or Serializable in_stream=new ExposedByteArrayInputStream(buffer, offset+1, length-1); in=new ObjectInputStream(in_stream); // changed Nov 29 2004 (bela) try { retval=((ObjectInputStream)in).readObject(); } finally { Util.close(in); } break; case TYPE_BOOLEAN: return ByteBuffer.wrap(buffer, offset + 1, length - 1).get() == 1; case TYPE_BYTE: return ByteBuffer.wrap(buffer, offset + 1, length - 1).get(); case TYPE_CHAR: return ByteBuffer.wrap(buffer, offset + 1, length - 1).getChar(); case TYPE_DOUBLE: return ByteBuffer.wrap(buffer, offset + 1, length - 1).getDouble(); case TYPE_FLOAT: return ByteBuffer.wrap(buffer, offset + 1, length - 1).getFloat(); case TYPE_INT: return ByteBuffer.wrap(buffer, offset + 1, length - 1).getInt(); case TYPE_LONG: return ByteBuffer.wrap(buffer, offset + 1, length - 1).getLong(); case TYPE_SHORT: return ByteBuffer.wrap(buffer, offset + 1, length - 1).getShort(); case TYPE_STRING: byte[] tmp=new byte[length -1]; System.arraycopy(buffer, offset +1, tmp, 0, length -1); return new String(tmp); case TYPE_BYTEARRAY: tmp=new byte[length -1]; System.arraycopy(buffer, offset +1, tmp, 0, length -1); return tmp; default: throw new IllegalArgumentException("type " + type + " is invalid"); } return retval; } /** * Serializes/Streams an object into a byte buffer. * The object has to implement interface Serializable or Externalizable or Streamable. */ public static byte[] objectToByteBuffer(Object obj) throws Exception { if(obj == null) return ByteBuffer.allocate(Global.BYTE_SIZE).put(TYPE_NULL).array(); if(obj instanceof Streamable) { final ExposedByteArrayOutputStream out_stream=new ExposedByteArrayOutputStream(128); final ExposedDataOutputStream out=new ExposedDataOutputStream(out_stream); out_stream.write(TYPE_STREAMABLE); writeGenericStreamable((Streamable)obj, out); return out_stream.toByteArray(); } Byte type=PRIMITIVE_TYPES.get(obj.getClass()); if(type == null) { // will throw an exception if object is not serializable final ExposedByteArrayOutputStream out_stream=new ExposedByteArrayOutputStream(128); out_stream.write(TYPE_SERIALIZABLE); ObjectOutputStream out=new ObjectOutputStream(out_stream); out.writeObject(obj); out.close(); return out_stream.toByteArray(); } switch(type.byteValue()) { case TYPE_BOOLEAN: return ByteBuffer.allocate(Global.BYTE_SIZE * 2).put(TYPE_BOOLEAN) .put(((Boolean)obj).booleanValue()? (byte)1 : (byte)0).array(); case TYPE_BYTE: return ByteBuffer.allocate(Global.BYTE_SIZE *2).put(TYPE_BYTE).put(((Byte)obj).byteValue()).array(); case TYPE_CHAR: return ByteBuffer.allocate(Global.BYTE_SIZE *3).put(TYPE_CHAR).putChar(((Character)obj).charValue()).array(); case TYPE_DOUBLE: return ByteBuffer.allocate(Global.BYTE_SIZE + Global.DOUBLE_SIZE).put(TYPE_DOUBLE) .putDouble(((Double)obj).doubleValue()).array(); case TYPE_FLOAT: return ByteBuffer.allocate(Global.BYTE_SIZE + Global.FLOAT_SIZE).put(TYPE_FLOAT) .putFloat(((Float)obj).floatValue()).array(); case TYPE_INT: return ByteBuffer.allocate(Global.BYTE_SIZE + Global.INT_SIZE).put(TYPE_INT) .putInt(((Integer)obj).intValue()).array(); case TYPE_LONG: return ByteBuffer.allocate(Global.BYTE_SIZE + Global.LONG_SIZE).put(TYPE_LONG) .putLong(((Long)obj).longValue()).array(); case TYPE_SHORT: return ByteBuffer.allocate(Global.BYTE_SIZE + Global.SHORT_SIZE).put(TYPE_SHORT) .putShort(((Short)obj).shortValue()).array(); case TYPE_STRING: String str=(String)obj; byte[] buf=new byte[str.length()]; for(int i=0; i < buf.length; i++) buf[i]=(byte)str.charAt(i); return ByteBuffer.allocate(Global.BYTE_SIZE + buf.length).put(TYPE_STRING).put(buf, 0, buf.length).array(); case TYPE_BYTEARRAY: buf=(byte[])obj; return ByteBuffer.allocate(Global.BYTE_SIZE + buf.length).put(TYPE_BYTEARRAY) .put(buf, 0, buf.length).array(); default: throw new IllegalArgumentException("type " + type + " is invalid"); } } public static void objectToStream(Object obj, DataOutput out) throws Exception { if(obj == null) { out.write(TYPE_NULL); return; } Byte type; if(obj instanceof Streamable) { // use Streamable if we can out.write(TYPE_STREAMABLE); writeGenericStreamable((Streamable)obj, out); } else if((type=PRIMITIVE_TYPES.get(obj.getClass())) != null) { out.write(type.byteValue()); switch(type.byteValue()) { case TYPE_BOOLEAN: out.writeBoolean(((Boolean)obj).booleanValue()); break; case TYPE_BYTE: out.writeByte(((Byte)obj).byteValue()); break; case TYPE_CHAR: out.writeChar(((Character)obj).charValue()); break; case TYPE_DOUBLE: out.writeDouble(((Double)obj).doubleValue()); break; case TYPE_FLOAT: out.writeFloat(((Float)obj).floatValue()); break; case TYPE_INT: out.writeInt(((Integer)obj).intValue()); break; case TYPE_LONG: out.writeLong(((Long)obj).longValue()); break; case TYPE_SHORT: out.writeShort(((Short)obj).shortValue()); break; case TYPE_STRING: String str=(String)obj; if(str.length() > Short.MAX_VALUE) { out.writeBoolean(true); ObjectOutputStream oos=new ObjectOutputStream((OutputStream)out); try { oos.writeObject(str); } finally { oos.close(); } } else { out.writeBoolean(false); out.writeUTF(str); } break; case TYPE_BYTEARRAY: byte[] buf=(byte[])obj; out.writeInt(buf.length); out.write(buf, 0, buf.length); break; default: throw new IllegalArgumentException("type " + type + " is invalid"); } } else { // will throw an exception if object is not serializable out.write(TYPE_SERIALIZABLE); ObjectOutputStream tmp=new ObjectOutputStream((OutputStream)out); tmp.writeObject(obj); } } public static Object objectFromStream(DataInput in) throws Exception { if(in == null) return null; Object retval=null; byte b=in.readByte(); switch(b) { case TYPE_NULL: return null; case TYPE_STREAMABLE: retval=readGenericStreamable(in); break; case TYPE_SERIALIZABLE: // the object is Externalizable or Serializable ObjectInputStream tmp=new ObjectInputStream((InputStream)in); retval=tmp.readObject(); break; case TYPE_BOOLEAN: retval=Boolean.valueOf(in.readBoolean()); break; case TYPE_BYTE: retval=Byte.valueOf(in.readByte()); break; case TYPE_CHAR: retval=Character.valueOf(in.readChar()); break; case TYPE_DOUBLE: retval=Double.valueOf(in.readDouble()); break; case TYPE_FLOAT: retval=Float.valueOf(in.readFloat()); break; case TYPE_INT: retval=Integer.valueOf(in.readInt()); break; case TYPE_LONG: retval=Long.valueOf(in.readLong()); break; case TYPE_SHORT: retval=Short.valueOf(in.readShort()); break; case TYPE_STRING: if(in.readBoolean()) { // large string ObjectInputStream ois=new ObjectInputStream((InputStream)in); try { retval=ois.readObject(); } finally { ois.close(); } } else { retval=in.readUTF(); } break; case TYPE_BYTEARRAY: int len=in.readInt(); byte[] tmpbuf=new byte[len]; in.readFully(tmpbuf, 0, tmpbuf.length); retval=tmpbuf; break; default: throw new IllegalArgumentException("type " + b + " is invalid"); } return retval; } public static Streamable streamableFromByteBuffer(Class cl, byte[] buffer) throws Exception { if(buffer == null) return null; Streamable retval=null; ByteArrayInputStream in_stream=new ExposedByteArrayInputStream(buffer); DataInputStream in=new DataInputStream(in_stream); // changed Nov 29 2004 (bela) retval=(Streamable)cl.newInstance(); retval.readFrom(in); in.close(); return retval; } public static Streamable streamableFromByteBuffer(Class cl, byte[] buffer, int offset, int length) throws Exception { if(buffer == null) return null; Streamable retval=null; ByteArrayInputStream in_stream=new ExposedByteArrayInputStream(buffer, offset, length); DataInputStream in=new DataInputStream(in_stream); // changed Nov 29 2004 (bela) retval=(Streamable)cl.newInstance(); retval.readFrom(in); in.close(); return retval; } public static byte[] streamableToByteBuffer(Streamable obj) throws Exception { byte[] result=null; final ByteArrayOutputStream out_stream=new ExposedByteArrayOutputStream(512); DataOutputStream out=new ExposedDataOutputStream(out_stream); obj.writeTo(out); result=out_stream.toByteArray(); out.close(); return result; } public static byte[] collectionToByteBuffer(Collection<Address> c) throws Exception { byte[] result=null; final ByteArrayOutputStream out_stream=new ExposedByteArrayOutputStream(512); DataOutputStream out=new ExposedDataOutputStream(out_stream); Util.writeAddresses(c, out); result=out_stream.toByteArray(); out.close(); return result; } public static void writeAuthToken(AuthToken token, DataOutput out) throws IOException{ Util.writeString(token.getName(), out); token.writeTo(out); } public static AuthToken readAuthToken(DataInput in) throws IOException, IllegalAccessException, InstantiationException { try{ String type = Util.readString(in); Object obj = Class.forName(type).newInstance(); AuthToken token = (AuthToken) obj; token.readFrom(in); return token; } catch(ClassNotFoundException cnfe){ return null; } } public static void writeView(View view, DataOutput out) throws IOException { if(view == null) { out.writeBoolean(false); return; } out.writeBoolean(true); out.writeBoolean(view instanceof MergeView); view.writeTo(out); } public static View readView(DataInput in) throws IOException, InstantiationException, IllegalAccessException { if(in.readBoolean() == false) return null; boolean isMergeView=in.readBoolean(); View view; if(isMergeView) view=new MergeView(); else view=new View(); view.readFrom(in); return view; } public static void writeAddress(Address addr, DataOutput out) throws IOException { byte flags=0; boolean streamable_addr=true; if(addr == null) { flags=Util.setFlag(flags, Address.NULL); out.writeByte(flags); return; } Class clazz=addr.getClass(); if(clazz.equals(UUID.class)) { flags=Util.setFlag(flags, Address.UUID_ADDR); } else if(clazz.equals(IpAddress.class)) { flags=Util.setFlag(flags, Address.IP_ADDR); } else { streamable_addr=false; } out.writeByte(flags); if(streamable_addr) addr.writeTo(out); else writeOtherAddress(addr, out); } public static Address readAddress(DataInput in) throws IOException, IllegalAccessException, InstantiationException { byte flags=in.readByte(); if(Util.isFlagSet(flags, Address.NULL)) return null; Address addr; if(Util.isFlagSet(flags, Address.UUID_ADDR)) { addr=new UUID(); addr.readFrom(in); } else if(Util.isFlagSet(flags, Address.IP_ADDR)) { addr=new IpAddress(); addr.readFrom(in); } else { addr=readOtherAddress(in); } return addr; } public static int size(Address addr) { int retval=Global.BYTE_SIZE; // flags if(addr != null) { if(addr instanceof UUID || addr instanceof IpAddress) retval+=addr.size(); else { retval+=Global.SHORT_SIZE; // magic number retval+=addr.size(); } } return retval; } public static int size(View view) { int retval=Global.BYTE_SIZE; // presence if(view != null) retval+=view.serializedSize() + Global.BYTE_SIZE; // merge view or regular view return retval; } private static Address readOtherAddress(DataInput in) throws IOException, IllegalAccessException, InstantiationException { short magic_number=in.readShort(); Class cl=ClassConfigurator.get(magic_number); if(cl == null) throw new RuntimeException("class for magic number " + magic_number + " not found"); Address addr=(Address)cl.newInstance(); addr.readFrom(in); return addr; } private static void writeOtherAddress(Address addr, DataOutput out) throws IOException { short magic_number=ClassConfigurator.getMagicNumber(addr.getClass()); // write the class info if(magic_number == -1) throw new RuntimeException("magic number " + magic_number + " not found"); out.writeShort(magic_number); addr.writeTo(out); } /** * Writes a Vector of Addresses. Can contain 65K addresses at most * * @param v A Collection<Address> * @param out * @throws IOException */ public static void writeAddresses(Collection<? extends Address> v, DataOutput out) throws IOException { if(v == null) { out.writeShort(-1); return; } out.writeShort(v.size()); for(Address addr: v) { Util.writeAddress(addr, out); } } public static Collection<? extends Address> readAddresses(DataInput in, Class cl) throws IOException, IllegalAccessException, InstantiationException { short length=in.readShort(); if(length < 0) return null; Collection<Address> retval=(Collection<Address>)cl.newInstance(); Address addr; for(int i=0; i < length; i++) { addr=Util.readAddress(in); retval.add(addr); } return retval; } /** * Returns the marshalled size of a Collection of Addresses. * <em>Assumes elements are of the same type !</em> * @param addrs Collection<Address> * @return long size */ public static long size(Collection<? extends Address> addrs) { int retval=Global.SHORT_SIZE; // number of elements if(addrs != null && !addrs.isEmpty()) { Address addr=addrs.iterator().next(); retval+=size(addr) * addrs.size(); } return retval; } public static void writeStreamable(Streamable obj, DataOutput out) throws IOException { if(obj == null) { out.writeBoolean(false); return; } out.writeBoolean(true); obj.writeTo(out); } public static Streamable readStreamable(Class clazz, DataInput in) throws IOException, IllegalAccessException, InstantiationException { Streamable retval=null; if(in.readBoolean() == false) return null; retval=(Streamable)clazz.newInstance(); retval.readFrom(in); return retval; } public static void writeGenericStreamable(Streamable obj, DataOutput out) throws IOException { short magic_number; String classname; if(obj == null) { out.write(0); return; } out.write(1); magic_number=ClassConfigurator.getMagicNumber(obj.getClass()); // write the magic number or the class name if(magic_number == -1) { out.writeBoolean(false); classname=obj.getClass().getName(); out.writeUTF(classname); } else { out.writeBoolean(true); out.writeShort(magic_number); } // write the contents obj.writeTo(out); } public static Streamable readGenericStreamable(DataInput in) throws IOException { Streamable retval=null; int b=in.readByte(); if(b == 0) return null; boolean use_magic_number=in.readBoolean(); String classname; Class clazz; try { if(use_magic_number) { short magic_number=in.readShort(); clazz=ClassConfigurator.get(magic_number); if (clazz==null) { throw new ClassNotFoundException("Class for magic number "+magic_number+" cannot be found."); } } else { classname=in.readUTF(); clazz=ClassConfigurator.get(classname); if (clazz==null) { throw new ClassNotFoundException(classname); } } retval=(Streamable)clazz.newInstance(); retval.readFrom(in); return retval; } catch(Exception ex) { throw new IOException("failed reading object: " + ex.toString()); } } public static void writeClass(Class<?> classObject, DataOutput out) throws IOException { short magic_number=ClassConfigurator.getMagicNumber(classObject); // write the magic number or the class name if(magic_number == -1) { out.writeBoolean(false); out.writeUTF(classObject.getName()); } else { out.writeBoolean(true); out.writeShort(magic_number); } } public static Class<?> readClass(DataInput in) throws IOException, ClassNotFoundException { Class<?> clazz; boolean use_magic_number = in.readBoolean(); if(use_magic_number) { short magic_number=in.readShort(); clazz=ClassConfigurator.get(magic_number); if (clazz==null) { throw new ClassNotFoundException("Class for magic number "+magic_number+" cannot be found."); } } else { String classname=in.readUTF(); clazz=ClassConfigurator.get(classname); if (clazz==null) { throw new ClassNotFoundException(classname); } } return clazz; } public static void writeObject(Object obj, DataOutput out) throws Exception { if(obj instanceof Streamable) { out.writeInt(-1); writeGenericStreamable((Streamable)obj, out); } else { byte[] buf=objectToByteBuffer(obj); out.writeInt(buf.length); out.write(buf, 0, buf.length); } } public static Object readObject(DataInput in) throws Exception { int len=in.readInt(); if(len == -1) return readGenericStreamable(in); byte[] buf=new byte[len]; in.readFully(buf, 0, len); return objectFromByteBuffer(buf); } public static void writeString(String s, DataOutput out) throws IOException { if(s != null) { out.write(1); out.writeUTF(s); } else { out.write(0); } } public static String readString(DataInput in) throws IOException { int b=in.readByte(); if(b == 1) return in.readUTF(); return null; } public static String parseString(DataInput in) { StringBuilder sb=new StringBuilder(); int ch; // read white space while(true) { try { ch=in.readByte(); if(ch == -1) { return null; // eof } if(Character.isWhitespace(ch)) { if(false && ch == '\n') return null; } else { sb.append((char)ch); break; } } catch(EOFException eof) { return null; } catch(IOException e) { break; } } while(true) { try { ch=in.readByte(); if(ch == -1) break; if(Character.isWhitespace(ch)) break; else { sb.append((char)ch); } } catch(IOException e) { break; } } return sb.toString(); } public static String readStringFromStdin(String message) throws Exception { System.out.print(message); System.out.flush(); System.in.skip(System.in.available()); BufferedReader reader=new BufferedReader(new InputStreamReader(System.in)); return reader.readLine().trim(); } public static long readLongFromStdin(String message) throws Exception { String tmp=readStringFromStdin(message); return Long.parseLong(tmp); } public static double readDoubleFromStdin(String message) throws Exception { String tmp=readStringFromStdin(message); return Double.parseDouble(tmp); } public static int readIntFromStdin(String message) throws Exception { String tmp=readStringFromStdin(message); return Integer.parseInt(tmp); } public static void writeByteBuffer(byte[] buf, DataOutput out) throws IOException { writeByteBuffer(buf, 0, buf.length, out); } public static void writeByteBuffer(byte[] buf, int offset, int length, DataOutput out) throws IOException { if(buf != null) { out.write(1); out.writeInt(length); out.write(buf, offset, length); } else { out.write(0); } } public static byte[] readByteBuffer(DataInput in) throws IOException { int b=in.readByte(); if(b == 1) { b=in.readInt(); byte[] buf=new byte[b]; in.readFully(buf, 0, buf.length); return buf; } return null; } public static Buffer messageToByteBuffer(Message msg) throws IOException { ExposedByteArrayOutputStream output=new ExposedByteArrayOutputStream(512); DataOutputStream out=new ExposedDataOutputStream(output); out.writeBoolean(msg != null); if(msg != null) msg.writeTo(out); out.flush(); Buffer retval=new Buffer(output.getRawBuffer(), 0, output.size()); out.close(); output.close(); return retval; } public static Message byteBufferToMessage(byte[] buffer, int offset, int length) throws Exception { ByteArrayInputStream input=new ExposedByteArrayInputStream(buffer, offset, length); DataInputStream in=new DataInputStream(input); if(!in.readBoolean()) return null; Message msg=new Message(false); // don't create headers, readFrom() will do this msg.readFrom(in); return msg; } /** * Marshalls a list of messages. * @param xmit_list LinkedList<Message> * @return Buffer * @throws IOException */ public static Buffer msgListToByteBuffer(List<Message> xmit_list) throws IOException { ExposedByteArrayOutputStream output=new ExposedByteArrayOutputStream(512); DataOutputStream out=new ExposedDataOutputStream(output); Buffer retval=null; out.writeInt(xmit_list.size()); for(Message msg: xmit_list) { msg.writeTo(out); } out.flush(); retval=new Buffer(output.getRawBuffer(), 0, output.size()); out.close(); output.close(); return retval; } public static boolean match(Object obj1, Object obj2) { if(obj1 == null && obj2 == null) return true; if(obj1 != null) return obj1.equals(obj2); else return obj2.equals(obj1); } public static boolean sameViewId(ViewId one, ViewId two) { return one.getId() == two.getId() && one.getCoordAddress().equals(two.getCoordAddress()); } public static boolean match(long[] a1, long[] a2) { if(a1 == null && a2 == null) return true; if(a1 == null || a2 == null) return false; if(a1 == a2) // identity return true; // at this point, a1 != null and a2 != null if(a1.length != a2.length) return false; for(int i=0; i < a1.length; i++) { if(a1[i] != a2[i]) return false; } return true; } /** Sleep for timeout msecs. Returns when timeout has elapsed or thread was interrupted */ public static void sleep(long timeout) { try { Thread.sleep(timeout); } catch(InterruptedException e) { Thread.currentThread().interrupt(); } } public static void sleep(long timeout, int nanos) { try { Thread.sleep(timeout,nanos); } catch(InterruptedException e) { Thread.currentThread().interrupt(); } } /** * On most UNIX systems, the minimum sleep time is 10-20ms. Even if we specify sleep(1), the thread will * sleep for at least 10-20ms. On Windows, sleep() seems to be implemented as a busy sleep, that is the * thread never relinquishes control and therefore the sleep(x) is exactly x ms long. */ public static void sleep(long msecs, boolean busy_sleep) { if(!busy_sleep) { sleep(msecs); return; } long start=System.currentTimeMillis(); long stop=start + msecs; while(stop > start) { start=System.currentTimeMillis(); } } public static int keyPress(String msg) { System.out.println(msg); try { int ret=System.in.read(); System.in.skip(System.in.available()); return ret; } catch(IOException e) { return 0; } } /** Returns a random value in the range [1 - range] */ public static long random(long range) { return (long)((Math.random() * range) % range) + 1; } /** Sleeps between floor and ceiling milliseconds, chosen randomly */ public static void sleepRandom(long floor, long ceiling) { if(ceiling - floor<= 0) { return; } long diff = ceiling - floor; long r=(int)((Math.random() * 100000) % diff) + floor; sleep(r); } /** Tosses a coin weighted with probability and returns true or false. Example: if probability=0.8, chances are that in 80% of all cases, true will be returned and false in 20%. */ public static boolean tossWeightedCoin(double probability) { long r=random(100); long cutoff=(long)(probability * 100); return r < cutoff; } public static String dumpThreads() { StringBuilder sb=new StringBuilder(); ThreadMXBean bean=ManagementFactory.getThreadMXBean(); long[] ids=bean.getAllThreadIds(); _printThreads(bean, ids, sb); long[] deadlocks=bean.findDeadlockedThreads(); if(deadlocks != null && deadlocks.length > 0) { sb.append("deadlocked threads:\n"); _printThreads(bean, deadlocks, sb); } deadlocks=bean.findMonitorDeadlockedThreads(); if(deadlocks != null && deadlocks.length > 0) { sb.append("monitor deadlocked threads:\n"); _printThreads(bean, deadlocks, sb); } return sb.toString(); } protected static void _printThreads(ThreadMXBean bean, long[] ids, StringBuilder sb) { ThreadInfo[] threads=bean.getThreadInfo(ids, 20); for(int i=0; i < threads.length; i++) { ThreadInfo info=threads[i]; if(info == null) continue; sb.append(info.getThreadName()).append(":\n"); StackTraceElement[] stack_trace=info.getStackTrace(); for(int j=0; j < stack_trace.length; j++) { StackTraceElement el=stack_trace[j]; sb.append(" at ").append(el.getClassName()).append(".").append(el.getMethodName()); sb.append("(").append(el.getFileName()).append(":").append(el.getLineNumber()).append(")"); sb.append("\n"); } sb.append("\n\n"); } } public static boolean interruptAndWaitToDie(Thread t) { return interruptAndWaitToDie(t, Global.THREAD_SHUTDOWN_WAIT_TIME); } public static boolean interruptAndWaitToDie(Thread t, long timeout) { if(t == null) throw new IllegalArgumentException("Thread can not be null"); t.interrupt(); // interrupts the sleep() try { t.join(timeout); } catch(InterruptedException e){ Thread.currentThread().interrupt(); // set interrupt flag again } return t.isAlive(); } /** * Debugging method used to dump the content of a protocol queue in a * condensed form. Useful to follow the evolution of the queue's content in * time. */ public static String dumpQueue(Queue q) { StringBuilder sb=new StringBuilder(); LinkedList values=q.values(); if(values.isEmpty()) { sb.append("empty"); } else { for(Object o: values) { String s=null; if(o instanceof Event) { Event event=(Event)o; int type=event.getType(); s=Event.type2String(type); if(type == Event.VIEW_CHANGE) s+=" " + event.getArg(); if(type == Event.MSG) s+=" " + event.getArg(); if(type == Event.MSG) { s+="["; Message m=(Message)event.getArg(); Map<Short,Header> headers=new HashMap<Short,Header>(m.getHeaders()); for(Map.Entry<Short,Header> entry: headers.entrySet()) { short id=entry.getKey(); Header value=entry.getValue(); String headerToString=null; if(value instanceof FD.FdHeader) { headerToString=value.toString(); } else if(value instanceof PingHeader) { headerToString=ClassConfigurator.getProtocol(id) + "-"; if(((PingHeader)value).type == PingHeader.GET_MBRS_REQ) { headerToString+="GMREQ"; } else if(((PingHeader)value).type == PingHeader.GET_MBRS_RSP) { headerToString+="GMRSP"; } else { headerToString+="UNKNOWN"; } } else { headerToString=ClassConfigurator.getProtocol(id) + "-" + (value == null ? "null" : value.toString()); } s+=headerToString; s+=" "; } s+="]"; } } else { s=o.toString(); } sb.append(s).append("\n"); } } return sb.toString(); } /** * Use with caution: lots of overhead */ public static String printStackTrace(Throwable t) { StringWriter s=new StringWriter(); PrintWriter p=new PrintWriter(s); t.printStackTrace(p); return s.toString(); } public static String getStackTrace(Throwable t) { return printStackTrace(t); } public static String print(Throwable t) { return printStackTrace(t); } public static void crash() { System.exit(-1); } public static String printEvent(Event evt) { Message msg; if(evt.getType() == Event.MSG) { msg=(Message)evt.getArg(); if(msg != null) { if(msg.getLength() > 0) return printMessage(msg); else return msg.printObjectHeaders(); } } return evt.toString(); } /** Tries to read an object from the message's buffer and prints it */ public static String printMessage(Message msg) { if(msg == null) return ""; if(msg.getLength() == 0) return null; try { return msg.getObject().toString(); } catch(Exception e) { // it is not an object return ""; } } public static String mapToString(Map<? extends Object,? extends Object> map) { if(map == null) return "null"; StringBuilder sb=new StringBuilder(); for(Map.Entry<? extends Object,? extends Object> entry: map.entrySet()) { Object key=entry.getKey(); Object val=entry.getValue(); sb.append(key).append("="); if(val == null) sb.append("null"); else sb.append(val); sb.append("\n"); } return sb.toString(); } public static void printThreads() { Thread threads[]=new Thread[Thread.activeCount()]; Thread.enumerate(threads); System.out.println(" for(int i=0; i < threads.length; i++) { System.out.println("#" + i + ": " + threads[i]); } System.out.println(" } public static String activeThreads() { StringBuilder sb=new StringBuilder(); Thread threads[]=new Thread[Thread.activeCount()]; Thread.enumerate(threads); sb.append(" for(int i=0; i < threads.length; i++) { sb.append("#").append(i).append(": ").append(threads[i]).append('\n'); } sb.append(" return sb.toString(); } public static String printBytes(long bytes) { double tmp; if(bytes < 1000) return bytes + "b"; if(bytes < 1000000) { tmp=bytes / 1000.0; return f.format(tmp) + "KB"; } if(bytes < 1000000000) { tmp=bytes / 1000000.0; return f.format(tmp) + "MB"; } else { tmp=bytes / 1000000000.0; return f.format(tmp) + "GB"; } } public static String printTime(long time, TimeUnit unit) { long ns=TimeUnit.NANOSECONDS.convert(time, unit); long us=TimeUnit.MICROSECONDS.convert(time, unit); long ms=TimeUnit.MILLISECONDS.convert(time, unit); long secs=TimeUnit.SECONDS.convert(time, unit); if(secs > 0) return secs + "s"; if(ms > 0) return ms + "ms"; if(us > 0) return us + " us"; return ns + "ns"; } public static String format(double value) { return f.format(value); } public static long readBytesLong(String input) { Tuple<String,Long> tuple=readBytes(input); double num=Double.parseDouble(tuple.getVal1()); return (long)(num * tuple.getVal2()); } public static int readBytesInteger(String input) { Tuple<String,Long> tuple=readBytes(input); double num=Double.parseDouble(tuple.getVal1()); return (int)(num * tuple.getVal2()); } public static double readBytesDouble(String input) { Tuple<String,Long> tuple=readBytes(input); double num=Double.parseDouble(tuple.getVal1()); return num * tuple.getVal2(); } private static Tuple<String,Long> readBytes(String input) { input=input.trim().toLowerCase(); int index=-1; long factor=1; if((index=input.indexOf("k")) != -1) factor=1000; else if((index=input.indexOf("kb")) != -1) factor=1000; else if((index=input.indexOf("m")) != -1) factor=1000000; else if((index=input.indexOf("mb")) != -1) factor=1000000; else if((index=input.indexOf("g")) != -1) factor=1000000000; else if((index=input.indexOf("gb")) != -1) factor=1000000000; String str=index != -1? input.substring(0, index) : input; return new Tuple<String,Long>(str, factor); } public static String printBytes(double bytes) { double tmp; if(bytes < 1000) return bytes + "b"; if(bytes < 1000000) { tmp=bytes / 1000.0; return f.format(tmp) + "KB"; } if(bytes < 1000000000) { tmp=bytes / 1000000.0; return f.format(tmp) + "MB"; } else { tmp=bytes / 1000000000.0; return f.format(tmp) + "GB"; } } public static List<String> split(String input, int separator) { List<String> retval=new ArrayList<String>(); if(input == null) return retval; int index=0, end; while(true) { index=input.indexOf(separator, index); if(index == -1) break; index++; end=input.indexOf(separator, index); if(end == -1) retval.add(input.substring(index)); else retval.add(input.substring(index, end)); } return retval; } /* public static String[] components(String path, String separator) { if(path == null || path.length() == 0) return null; String[] tmp=path.split(separator + "+"); // multiple separators could be present if(tmp == null) return null; if(tmp.length == 0) return null; if(tmp[0].length() == 0) { tmp[0]=separator; if(tmp.length > 1) { String[] retval=new String[tmp.length -1]; retval[0]=tmp[0] + tmp[1]; System.arraycopy(tmp, 2, retval, 1, tmp.length-2); return retval; } return tmp; } return tmp; }*/ public static String[] components(String path, String separator) { if(path == null || path.length() == 0) return null; String[] tmp=path.split(separator + "+"); // multiple separators could be present if(tmp == null) return null; if(tmp.length == 0) return null; if(tmp[0].length() == 0) tmp[0]=separator; return tmp; } /** Fragments a byte buffer into smaller fragments of (max.) frag_size. Example: a byte buffer of 1024 bytes and a frag_size of 248 gives 4 fragments of 248 bytes each and 1 fragment of 32 bytes. @return An array of byte buffers (<code>byte[]</code>). */ public static byte[][] fragmentBuffer(byte[] buf, int frag_size, final int length) { byte[] retval[]; int accumulated_size=0; byte[] fragment; int tmp_size=0; int num_frags; int index=0; num_frags=length % frag_size == 0 ? length / frag_size : length / frag_size + 1; retval=new byte[num_frags][]; while(accumulated_size < length) { if(accumulated_size + frag_size <= length) tmp_size=frag_size; else tmp_size=length - accumulated_size; fragment=new byte[tmp_size]; System.arraycopy(buf, accumulated_size, fragment, 0, tmp_size); retval[index++]=fragment; accumulated_size+=tmp_size; } return retval; } public static byte[][] fragmentBuffer(byte[] buf, int frag_size) { return fragmentBuffer(buf, frag_size, buf.length); } /** * Given a buffer and a fragmentation size, compute a list of fragmentation offset/length pairs, and * return them in a list. Example:<br/> * Buffer is 10 bytes, frag_size is 4 bytes. Return value will be ({0,4}, {4,4}, {8,2}). * This is a total of 3 fragments: the first fragment starts at 0, and has a length of 4 bytes, the second fragment * starts at offset 4 and has a length of 4 bytes, and the last fragment starts at offset 8 and has a length * of 2 bytes. * @param frag_size * @return List. A List<Range> of offset/length pairs */ public static List<Range> computeFragOffsets(int offset, int length, int frag_size) { List<Range> retval=new ArrayList<Range>(); long total_size=length + offset; int index=offset; int tmp_size=0; Range r; while(index < total_size) { if(index + frag_size <= total_size) tmp_size=frag_size; else tmp_size=(int)(total_size - index); r=new Range(index, tmp_size); retval.add(r); index+=tmp_size; } return retval; } public static List<Range> computeFragOffsets(byte[] buf, int frag_size) { return computeFragOffsets(0, buf.length, frag_size); } /** Concatenates smaller fragments into entire buffers. @param fragments An array of byte buffers (<code>byte[]</code>) @return A byte buffer */ public static byte[] defragmentBuffer(byte[] fragments[]) { int total_length=0; byte[] ret; int index=0; if(fragments == null) return null; for(int i=0; i < fragments.length; i++) { if(fragments[i] == null) continue; total_length+=fragments[i].length; } ret=new byte[total_length]; for(int i=0; i < fragments.length; i++) { if(fragments[i] == null) continue; System.arraycopy(fragments[i], 0, ret, index, fragments[i].length); index+=fragments[i].length; } return ret; } public static void printFragments(byte[] frags[]) { for(int i=0; i < frags.length; i++) System.out.println('\'' + new String(frags[i]) + '\''); } public static <T> String printListWithDelimiter(Collection<T> list, String delimiter) { boolean first=true; StringBuilder sb=new StringBuilder(); for(T el: list) { if(first) { first=false; } else { sb.append(delimiter); } sb.append(el); } return sb.toString(); } public static <T> String printMapWithDelimiter(Map<T,T> map, String delimiter) { boolean first=true; StringBuilder sb=new StringBuilder(); for(Map.Entry<T,T> entry: map.entrySet()) { if(first) first=false; else sb.append(delimiter); sb.append(entry.getKey()).append("=").append(entry.getValue()); } return sb.toString(); } public static String array2String(long[] array) { StringBuilder ret=new StringBuilder("["); if(array != null) { for(int i=0; i < array.length; i++) ret.append(array[i]).append(" "); } ret.append(']'); return ret.toString(); } public static String array2String(short[] array) { StringBuilder ret=new StringBuilder("["); if(array != null) { for(int i=0; i < array.length; i++) ret.append(array[i]).append(" "); } ret.append(']'); return ret.toString(); } public static String array2String(int[] array) { StringBuilder ret=new StringBuilder("["); if(array != null) { for(int i=0; i < array.length; i++) ret.append(array[i]).append(" "); } ret.append(']'); return ret.toString(); } public static String array2String(boolean[] array) { StringBuilder ret=new StringBuilder("["); if(array != null) { for(int i=0; i < array.length; i++) ret.append(array[i]).append(" "); } ret.append(']'); return ret.toString(); } public static String array2String(Object[] array) { return Arrays.toString(array); } /** Returns true if all elements of c match obj */ public static boolean all(Collection c, Object obj) { for(Iterator iterator=c.iterator(); iterator.hasNext();) { Object o=iterator.next(); if(!o.equals(obj)) return false; } return true; } /** * Returns a list of members which left from view one to two * @param one * @param two * @return */ public static List<Address> leftMembers(View one, View two) { if(one == null || two == null) return null; List<Address> retval=new ArrayList<Address>(one.getMembers()); retval.removeAll(two.getMembers()); return retval; } public static List<Address> leftMembers(Collection<Address> old_list, Collection<Address> new_list) { if(old_list == null || new_list == null) return null; List<Address> retval=new ArrayList<Address>(old_list); retval.removeAll(new_list); return retval; } public static List<Address> newMembers(List<Address> old_list, List<Address> new_list) { if(old_list == null || new_list == null) return null; List<Address> retval=new ArrayList<Address>(new_list); retval.removeAll(old_list); return retval; } /** * Selects a random subset of members according to subset_percentage and returns them. * Picks no member twice from the same membership. If the percentage is smaller than 1 -> picks 1 member. */ public static List<Address> pickSubset(List<Address> members, double subset_percentage) { List<Address> ret=new ArrayList<Address>(), tmp_mbrs; int num_mbrs=members.size(), subset_size, index; if(num_mbrs == 0) return ret; subset_size=(int)Math.ceil(num_mbrs * subset_percentage); tmp_mbrs=new ArrayList<Address>(members); for(int i=subset_size; i > 0 && !tmp_mbrs.isEmpty(); i index=(int)((Math.random() * num_mbrs) % tmp_mbrs.size()); ret.add(tmp_mbrs.get(index)); tmp_mbrs.remove(index); } return ret; } public static boolean containsViewId(Collection<View> views, ViewId vid) { for(View view: views) { ViewId tmp=view.getVid(); if(Util.sameViewId(vid, tmp)) return true; } return false; } /** * Determines the members which take part in a merge. The resulting list consists of all merge coordinators * plus members outside a merge partition, e.g. for views A={B,A,C}, B={B,C} and C={B,C}, the merge coordinator * is B, but the merge participants are B and A. * @param map * @return */ public static Collection<Address> determineMergeParticipants(Map<Address,View> map) { Set<Address> coords=new HashSet<Address>(); Set<Address> all_addrs=new HashSet<Address>(); if(map == null) return Collections.emptyList(); for(View view: map.values()) all_addrs.addAll(view.getMembers()); for(View view: map.values()) { Address coord=view.getCreator(); if(coord != null) coords.add(coord); } for(Address coord: coords) { View view=map.get(coord); Collection<Address> mbrs=view != null? view.getMembers() : null; if(mbrs != null) all_addrs.removeAll(mbrs); } coords.addAll(all_addrs); return coords; } /** * This is the same or a subset of {@link #determineMergeParticipants(java.util.Map)} and contains only members * which are currently sub-partition coordinators. * @param map * @return */ public static Collection<Address> determineMergeCoords(Map<Address,View> map) { Set<Address> retval=new HashSet<Address>(); if(map != null) { for(View view: map.values()) { Address coord=view.getCreator(); if(coord != null) retval.add(coord); } } return retval; } public static int getRank(View view, Address addr) { if(view == null || addr == null) return 0; List<Address> members=view.getMembers(); for(int i=0; i < members.size(); i++) { Address mbr=members.get(i); if(mbr.equals(addr)) return i+1; } return 0; } public static Object pickRandomElement(List list) { if(list == null) return null; int size=list.size(); int index=(int)((Math.random() * size * 10) % size); return list.get(index); } public static Object pickRandomElement(Object[] array) { if(array == null) return null; int size=array.length; int index=(int)((Math.random() * size * 10) % size); return array[index]; } /** * Returns the object next to element in list * @param list * @param obj * @param <T> * @return */ public static <T> T pickNext(List<T> list, T obj) { if(list == null || obj == null) return null; Object[] array=list.toArray(); for(int i=0; i < array.length; i++) { T tmp=(T)array[i]; if(tmp != null && tmp.equals(obj)) return (T)array[(i+1) % array.length]; } return null; } /** Returns the next min(N,list.size()) elements after obj */ public static <T> List<T> pickNext(List<T> list, T obj, int num) { List<T> retval=new ArrayList<T>(); if(list == null || list.size() < 2) return retval; int index=list.indexOf(obj); if(index != -1) { for(int i=1; i <= num && i < list.size(); i++) { T tmp=list.get((index +i) % list.size()); if(!retval.contains(tmp)) retval.add(tmp); } } return retval; } public static View createView(Address coord, long id, Address ... members) { Vector<Address> mbrs=new Vector<Address>(); mbrs.addAll(Arrays.asList(members)); return new View(coord, id, mbrs); } public static JChannel createChannel(Protocol... prots) throws Exception { JChannel ch=new JChannel(false); ProtocolStack stack=new ProtocolStack(); ch.setProtocolStack(stack); for(Protocol prot: prots) stack.addProtocol(prot); stack.init(); return ch; } public static Address createRandomAddress() { return createRandomAddress(generateLocalName()); } public static Address createRandomAddress(String name) { UUID retval=UUID.randomUUID(); UUID.add(retval, name); return retval; } public static Object[][] createTimer() { return new Object[][] { {new DefaultTimeScheduler(5)}, {new TimeScheduler2()}, {new HashedTimingWheel(5)} }; } /** * Returns all members that left between 2 views. All members that are element of old_mbrs but not element of * new_mbrs are returned. */ public static List<Address> determineLeftMembers(List<Address> old_mbrs, List<Address> new_mbrs) { List<Address> retval=new ArrayList<Address>(); if(old_mbrs == null || new_mbrs == null) return retval; for(int i=0; i < old_mbrs.size(); i++) { Address mbr=old_mbrs.get(i); if(!new_mbrs.contains(mbr)) retval.add(mbr); } return retval; } /** * Returns the members which joined between 2 subsequent views * @param old_mbrs * @param new_mbrs * @return */ public static List<Address> determineNewMembers(List<Address> old_mbrs, List<Address> new_mbrs) { if(old_mbrs == null || new_mbrs == null) return new ArrayList<Address>(); List<Address> retval=new ArrayList<Address>(new_mbrs); retval.removeAll(old_mbrs); return retval; } public static String printViews(Collection<View> views) { StringBuilder sb=new StringBuilder(); boolean first=true; for(View view: views) { if(first) first=false; else sb.append(", "); sb.append(view.getVid()); } return sb.toString(); } public static <T> String print(Collection<T> objs) { StringBuilder sb=new StringBuilder(); boolean first=true; for(T obj: objs) { if(first) first=false; else sb.append(", "); sb.append(obj); } return sb.toString(); } public static <T> String print(Map<T,T> map) { StringBuilder sb=new StringBuilder(); boolean first=true; for(Map.Entry<T,T> entry: map.entrySet()) { if(first) first=false; else sb.append(", "); sb.append(entry.getKey()).append("=").append(entry.getValue()); } return sb.toString(); } public static String printPingData(List<PingData> rsps) { StringBuilder sb=new StringBuilder(); if(rsps != null) { int total=rsps.size(); int servers=0, clients=0, coords=0; for(PingData rsp: rsps) { if(rsp.isCoord()) coords++; if(rsp.isServer()) servers++; else clients++; } sb.append(total + " total (" + servers + " servers (" + coords + " coord), " + clients + " clients)"); } return sb.toString(); } /** Makes sure that we detect when a peer connection is in the closed state (not closed while we send data, but before we send data). Two writes ensure that, if the peer closed the connection, the first write will send the peer from FIN to RST state, and the second will cause a signal (IOException). */ public static void doubleWrite(byte[] buf, OutputStream out) throws Exception { if(buf.length > 1) { out.write(buf, 0, 1); out.write(buf, 1, buf.length - 1); } else { out.write(buf, 0, 0); out.write(buf); } } /** Makes sure that we detect when a peer connection is in the closed state (not closed while we send data, but before we send data). Two writes ensure that, if the peer closed the connection, the first write will send the peer from FIN to RST state, and the second will cause a signal (IOException). */ public static void doubleWrite(byte[] buf, int offset, int length, OutputStream out) throws Exception { if(length > 1) { out.write(buf, offset, 1); out.write(buf, offset+1, length - 1); } else { out.write(buf, offset, 0); out.write(buf, offset, length); } } /** * if we were to register for OP_WRITE and send the remaining data on * readyOps for this channel we have to either block the caller thread or * queue the message buffers that may arrive while waiting for OP_WRITE. * Instead of the above approach this method will continuously write to the * channel until the buffer sent fully. */ public static void writeFully(ByteBuffer buf, WritableByteChannel out) throws IOException { int written = 0; int toWrite = buf.limit(); while (written < toWrite) { written += out.write(buf); } } public static long sizeOf(String classname) { Object inst; byte[] data; try { inst=Util.loadClass(classname, null).newInstance(); data=Util.objectToByteBuffer(inst); return data.length; } catch(Exception ex) { return -1; } } public static long sizeOf(Object inst) { byte[] data; try { data=Util.objectToByteBuffer(inst); return data.length; } catch(Exception ex) { return -1; } } public static int sizeOf(Streamable inst) { try { ByteArrayOutputStream output=new ExposedByteArrayOutputStream(); DataOutputStream out=new ExposedDataOutputStream(output); inst.writeTo(out); out.flush(); byte[] data=output.toByteArray(); return data.length; } catch(Exception ex) { return -1; } } /** * Tries to load the class from the current thread's context class loader. If * not successful, tries to load the class from the current instance. * @param classname Desired class. * @param clazz Class object used to obtain a class loader * if no context class loader is available. * @return Class, or null on failure. */ public static Class loadClass(String classname, Class clazz) throws ClassNotFoundException { ClassLoader loader; try { loader=Thread.currentThread().getContextClassLoader(); if(loader != null) { return loader.loadClass(classname); } } catch(Throwable t) { } if(clazz != null) { try { loader=clazz.getClassLoader(); if(loader != null) { return loader.loadClass(classname); } } catch(Throwable t) { } } try { loader=ClassLoader.getSystemClassLoader(); if(loader != null) { return loader.loadClass(classname); } } catch(Throwable t) { } throw new ClassNotFoundException(classname); } public static Field[] getAllDeclaredFields(final Class clazz) { return getAllDeclaredFieldsWithAnnotations(clazz); } public static Field[] getAllDeclaredFieldsWithAnnotations(final Class clazz, Class<? extends Annotation> ... annotations) { List<Field> list=new ArrayList<Field>(30); for(Class curr=clazz; curr != null; curr=curr.getSuperclass()) { Field[] fields=curr.getDeclaredFields(); if(fields != null) { for(Field field: fields) { if(annotations != null && annotations.length > 0) { for(Class<? extends Annotation> annotation: annotations) { if(field.isAnnotationPresent(annotation)) list.add(field); } } else list.add(field); } } } Field[] retval=new Field[list.size()]; for(int i=0; i < list.size(); i++) retval[i]=list.get(i); return retval; } public static Method[] getAllDeclaredMethods(final Class clazz) { return getAllDeclaredMethodsWithAnnotations(clazz); } public static Method[] getAllDeclaredMethodsWithAnnotations(final Class clazz, Class<? extends Annotation> ... annotations) { List<Method> list=new ArrayList<Method>(30); for(Class curr=clazz; curr != null; curr=curr.getSuperclass()) { Method[] methods=curr.getDeclaredMethods(); if(methods != null) { for(Method method: methods) { if(annotations != null && annotations.length > 0) { for(Class<? extends Annotation> annotation: annotations) { if(method.isAnnotationPresent(annotation)) list.add(method); } } else list.add(method); } } } Method[] retval=new Method[list.size()]; for(int i=0; i < list.size(); i++) retval[i]=list.get(i); return retval; } public static Field getField(final Class clazz, String field_name) { if(clazz == null || field_name == null) return null; Field field=null; for(Class curr=clazz; curr != null; curr=curr.getSuperclass()) { try { return curr.getDeclaredField(field_name); } catch(NoSuchFieldException e) { } } return field; } public static InputStream getResourceAsStream(String name, Class clazz) { ClassLoader loader; InputStream retval=null; try { loader=Thread.currentThread().getContextClassLoader(); if(loader != null) { retval=loader.getResourceAsStream(name); if(retval != null) return retval; } } catch(Throwable t) { } if(clazz != null) { try { loader=clazz.getClassLoader(); if(loader != null) { retval=loader.getResourceAsStream(name); if(retval != null) return retval; } } catch(Throwable t) { } } try { loader=ClassLoader.getSystemClassLoader(); if(loader != null) { return loader.getResourceAsStream(name); } } catch(Throwable t) { } return retval; } /** Checks whether 2 Addresses are on the same host */ public static boolean sameHost(Address one, Address two) { InetAddress a, b; String host_a, host_b; if(one == null || two == null) return false; if(!(one instanceof IpAddress) || !(two instanceof IpAddress)) { return false; } a=((IpAddress)one).getIpAddress(); b=((IpAddress)two).getIpAddress(); if(a == null || b == null) return false; host_a=a.getHostAddress(); host_b=b.getHostAddress(); // System.out.println("host_a=" + host_a + ", host_b=" + host_b); return host_a.equals(host_b); } public static boolean fileExists(String fname) { return (new File(fname)).exists(); } /** * Parses comma-delimited longs; e.g., 2000,4000,8000. * Returns array of long, or null. */ public static long[] parseCommaDelimitedLongs(String s) { StringTokenizer tok; Vector<Long> v=new Vector<Long>(); Long l; long[] retval=null; if(s == null) return null; tok=new StringTokenizer(s, ","); while(tok.hasMoreTokens()) { l=new Long(tok.nextToken()); v.addElement(l); } if(v.isEmpty()) return null; retval=new long[v.size()]; for(int i=0; i < v.size(); i++) retval[i]=v.elementAt(i).longValue(); return retval; } /** e.g. "bela,jeannette,michelle" --> List{"bela", "jeannette", "michelle"} */ public static List<String> parseCommaDelimitedStrings(String l) { return parseStringList(l, ","); } /** * Input is "daddy[8880],sindhu[8880],camille[5555]. Returns a list of IpAddresses */ public static List<IpAddress> parseCommaDelimitedHosts(String hosts, int port_range) throws UnknownHostException { StringTokenizer tok=new StringTokenizer(hosts, ","); String t; IpAddress addr; Set<IpAddress> retval=new HashSet<IpAddress>(); while(tok.hasMoreTokens()) { t=tok.nextToken().trim(); String host=t.substring(0, t.indexOf('[')); host=host.trim(); int port=Integer.parseInt(t.substring(t.indexOf('[') + 1, t.indexOf(']'))); for(int i=port;i <= port + port_range;i++) { addr=new IpAddress(host, i); retval.add(addr); } } return Collections.unmodifiableList(new LinkedList<IpAddress>(retval)); } /** * Input is "daddy[8880],sindhu[8880],camille[5555]. Return List of * InetSocketAddress */ public static List<InetSocketAddress> parseCommaDelimitedHosts2(String hosts, int port_range) { StringTokenizer tok=new StringTokenizer(hosts, ","); String t; InetSocketAddress addr; Set<InetSocketAddress> retval=new HashSet<InetSocketAddress>(); while(tok.hasMoreTokens()) { t=tok.nextToken().trim(); String host=t.substring(0, t.indexOf('[')); host=host.trim(); int port=Integer.parseInt(t.substring(t.indexOf('[') + 1, t.indexOf(']'))); for(int i=port;i < port + port_range;i++) { addr=new InetSocketAddress(host, i); retval.add(addr); } } return Collections.unmodifiableList(new LinkedList<InetSocketAddress>(retval)); } public static List<String> parseStringList(String l, String separator) { List<String> tmp=new LinkedList<String>(); StringTokenizer tok=new StringTokenizer(l, separator); String t; while(tok.hasMoreTokens()) { t=tok.nextToken(); tmp.add(t.trim()); } return tmp; } public static String parseString(ByteBuffer buf) { return parseString(buf, true); } public static String parseString(ByteBuffer buf, boolean discard_whitespace) { StringBuilder sb=new StringBuilder(); char ch; // read white space while(buf.remaining() > 0) { ch=(char)buf.get(); if(!Character.isWhitespace(ch)) { buf.position(buf.position() -1); break; } } if(buf.remaining() == 0) return null; while(buf.remaining() > 0) { ch=(char)buf.get(); if(!Character.isWhitespace(ch)) { sb.append(ch); } else break; } // read white space if(discard_whitespace) { while(buf.remaining() > 0) { ch=(char)buf.get(); if(!Character.isWhitespace(ch)) { buf.position(buf.position() -1); break; } } } return sb.toString(); } public static int readNewLine(ByteBuffer buf) { char ch; int num=0; while(buf.remaining() > 0) { ch=(char)buf.get(); num++; if(ch == '\n') break; } return num; } /** * Reads and discards all characters from the input stream until a \r\n or EOF is encountered * @param in * @return */ public static int discardUntilNewLine(InputStream in) { int ch; int num=0; while(true) { try { ch=in.read(); if(ch == -1) break; num++; if(ch == '\n') break; } catch(IOException e) { break; } } return num; } /** * Reads a line of text. A line is considered to be terminated by any one * of a line feed ('\n'), a carriage return ('\r'), or a carriage return * followed immediately by a linefeed. * * @return A String containing the contents of the line, not including * any line-termination characters, or null if the end of the * stream has been reached * * @exception IOException If an I/O error occurs */ public static String readLine(InputStream in) throws IOException { StringBuilder sb=new StringBuilder(35); int ch; while(true) { ch=in.read(); if(ch == -1) return null; if(ch == '\r') { ; } else { if(ch == '\n') break; else { sb.append((char)ch); } } } return sb.toString(); } public static void writeString(ByteBuffer buf, String s) { for(int i=0; i < s.length(); i++) buf.put((byte)s.charAt(i)); } /** * * @param s * @return List<NetworkInterface> */ public static List<NetworkInterface> parseInterfaceList(String s) throws Exception { List<NetworkInterface> interfaces=new ArrayList<NetworkInterface>(10); if(s == null) return null; StringTokenizer tok=new StringTokenizer(s, ","); String interface_name; NetworkInterface intf; while(tok.hasMoreTokens()) { interface_name=tok.nextToken(); // try by name first (e.g. (eth0") intf=NetworkInterface.getByName(interface_name); // next try by IP address or symbolic name if(intf == null) intf=NetworkInterface.getByInetAddress(InetAddress.getByName(interface_name)); if(intf == null) throw new Exception("interface " + interface_name + " not found"); if(!interfaces.contains(intf)) { interfaces.add(intf); } } return interfaces; } public static String print(List<NetworkInterface> interfaces) { StringBuilder sb=new StringBuilder(); boolean first=true; for(NetworkInterface intf: interfaces) { if(first) { first=false; } else { sb.append(", "); } sb.append(intf.getName()); } return sb.toString(); } public static String shortName(String hostname) { if(hostname == null) return null; int index=hostname.indexOf('.'); if(index > 0 && !Character.isDigit(hostname.charAt(0))) return hostname.substring(0, index); else return hostname; } public static boolean startFlush(Channel c, List<Address> flushParticipants, int numberOfAttempts, long randomSleepTimeoutFloor,long randomSleepTimeoutCeiling) { boolean successfulFlush = false; int attemptCount = 0; while(attemptCount < numberOfAttempts){ successfulFlush = c.startFlush(flushParticipants, false); if(successfulFlush) break; Util.sleepRandom(randomSleepTimeoutFloor,randomSleepTimeoutCeiling); attemptCount++; } return successfulFlush; } public static boolean startFlush(Channel c, List<Address> flushParticipants) { return startFlush(c,flushParticipants,4,1000,5000); } public static boolean startFlush(Channel c, int numberOfAttempts, long randomSleepTimeoutFloor,long randomSleepTimeoutCeiling) { boolean successfulFlush = false; int attemptCount = 0; while(attemptCount < numberOfAttempts){ successfulFlush = c.startFlush(false); if(successfulFlush) break; Util.sleepRandom(randomSleepTimeoutFloor,randomSleepTimeoutCeiling); attemptCount++; } return successfulFlush; } public static boolean startFlush(Channel c) { return startFlush(c,4,1000,5000); } public static String shortName(InetAddress hostname) { if(hostname == null) return null; StringBuilder sb=new StringBuilder(); if(resolve_dns) sb.append(hostname.getHostName()); else sb.append(hostname.getHostAddress()); return sb.toString(); } public static String generateLocalName() { String retval=null; try { retval=shortName(InetAddress.getLocalHost().getHostName()); } catch(UnknownHostException e) { retval="localhost"; } long counter=Util.random(Short.MAX_VALUE *2); return retval + "-" + counter; } public synchronized static short incrCounter() { short retval=COUNTER++; if(COUNTER >= Short.MAX_VALUE) COUNTER=1; return retval; } public static <K,V> ConcurrentMap<K,V> createConcurrentMap(int initial_capacity, float load_factor, int concurrency_level) { return new ConcurrentHashMap<K,V>(initial_capacity, load_factor, concurrency_level); } public static <K,V> ConcurrentMap<K,V> createConcurrentMap(int initial_capacity) { return new ConcurrentHashMap<K,V>(initial_capacity); } public static <K,V> ConcurrentMap<K,V> createConcurrentMap() { return new ConcurrentHashMap<K,V>(CCHM_INITIAL_CAPACITY, CCHM_LOAD_FACTOR, CCHM_CONCURRENCY_LEVEL); } public static <K,V> Map<K,V> createHashMap() { return new HashMap<K,V>(CCHM_INITIAL_CAPACITY, CCHM_LOAD_FACTOR); } /** Finds first available port starting at start_port and returns server socket */ public static ServerSocket createServerSocket(SocketFactory factory, String service_name, int start_port) { ServerSocket ret=null; while(true) { try { ret=factory.createServerSocket(service_name, start_port); } catch(BindException bind_ex) { start_port++; continue; } catch(IOException io_ex) { } break; } return ret; } public static ServerSocket createServerSocket(SocketFactory factory, String service_name, InetAddress bind_addr, int start_port) { ServerSocket ret=null; while(true) { try { ret=factory.createServerSocket(service_name, start_port, 50, bind_addr); } catch(BindException bind_ex) { start_port++; continue; } catch(IOException io_ex) { } break; } return ret; } /** * Finds first available port starting at start_port and returns server * socket. Will not bind to port >end_port. Sets srv_port */ public static ServerSocket createServerSocket(SocketFactory factory, String service_name, InetAddress bind_addr, int start_port, int end_port) throws Exception { ServerSocket ret=null; int original_start_port=start_port; while(true) { try { if(bind_addr == null) ret=factory.createServerSocket(service_name, start_port); else { // changed (bela Sept 7 2007): we accept connections on all NICs ret=factory.createServerSocket(service_name, start_port, 50, bind_addr); } } catch(BindException bind_ex) { if(start_port == end_port) throw new BindException("No available port to bind to in range [" + original_start_port + " .. " + end_port + "]"); if(bind_addr != null && !bind_addr.isLoopbackAddress()) { NetworkInterface nic=NetworkInterface.getByInetAddress(bind_addr); if(nic == null) throw new BindException("bind_addr " + bind_addr + " is not a valid interface: " + bind_ex); } start_port++; continue; } break; } return ret; } /** * Creates a DatagramSocket bound to addr. If addr is null, socket won't be bound. If address is already in use, * start_port will be incremented until a socket can be created. * @param addr The InetAddress to which the socket should be bound. If null, the socket will not be bound. * @param port The port which the socket should use. If 0, a random port will be used. If > 0, but port is already * in use, it will be incremented until an unused port is found, or until MAX_PORT is reached. */ public static DatagramSocket createDatagramSocket(SocketFactory factory, String service_name, InetAddress addr, int port) throws Exception { DatagramSocket sock=null; if(addr == null) { if(port == 0) { return factory.createDatagramSocket(service_name); } else { while(port < MAX_PORT) { try { return factory.createDatagramSocket(service_name, port); } catch(BindException bind_ex) { // port already used port++; } } } } else { if(port == 0) port=1024; while(port < MAX_PORT) { try { return factory.createDatagramSocket(service_name, port, addr); } catch(BindException bind_ex) { // port already used port++; } } } return sock; // will never be reached, but the stupid compiler didn't figure it out... } public static MulticastSocket createMulticastSocket(SocketFactory factory, String service_name, InetAddress mcast_addr, int port, Log log) throws IOException { if(mcast_addr != null && !mcast_addr.isMulticastAddress()) throw new IllegalArgumentException("mcast_addr (" + mcast_addr + ") is not a valid multicast address"); SocketAddress saddr=new InetSocketAddress(mcast_addr, port); MulticastSocket retval=null; try { retval=factory.createMulticastSocket(service_name, saddr); } catch(IOException ex) { if(log != null && log.isWarnEnabled()) { StringBuilder sb=new StringBuilder(); String type=mcast_addr != null ? mcast_addr instanceof Inet4Address? "IPv4" : "IPv6" : "n/a"; sb.append("could not bind to " + mcast_addr + " (" + type + " address)"); sb.append("; make sure your mcast_addr is of the same type as the preferred IP stack (IPv4 or IPv6)"); sb.append(" by checking the value of the system properties java.net.preferIPv4Stack and java.net.preferIPv6Addresses."); sb.append("\nWill ignore mcast_addr, but this may lead to cross talking " + "(see http: sb.append("\nException was: " + ex); log.warn(sb.toString()); } } if(retval == null) retval=factory.createMulticastSocket(service_name, port); return retval; } /** * Returns the address of the interface to use defined by bind_addr and bind_interface * @param props * @return * @throws UnknownHostException * @throws SocketException */ public static InetAddress getBindAddress(Properties props) throws UnknownHostException, SocketException { // determine the desired values for bind_addr_str and bind_interface_str boolean ignore_systemprops=Util.isBindAddressPropertyIgnored(); String bind_addr_str =Util.getProperty(new String[]{Global.BIND_ADDR}, props, "bind_addr", ignore_systemprops, null); String bind_interface_str =Util.getProperty(new String[]{Global.BIND_INTERFACE, null}, props, "bind_interface", ignore_systemprops, null); InetAddress bind_addr=null; NetworkInterface bind_intf=null; StackType ip_version=Util.getIpStackType(); // 1. if bind_addr_str specified, get bind_addr and check version if(bind_addr_str != null) { bind_addr=InetAddress.getByName(bind_addr_str); // check that bind_addr_host has correct IP version boolean hasCorrectVersion = ((bind_addr instanceof Inet4Address && ip_version == StackType.IPv4) || (bind_addr instanceof Inet6Address && ip_version == StackType.IPv6)) ; if (!hasCorrectVersion) throw new IllegalArgumentException("bind_addr " + bind_addr_str + " has incorrect IP version") ; } // 2. if bind_interface_str specified, get interface and check that it has correct version if(bind_interface_str != null) { bind_intf=NetworkInterface.getByName(bind_interface_str); if(bind_intf != null) { // check that the interface supports the IP version boolean supportsVersion = interfaceHasIPAddresses(bind_intf, ip_version) ; if (!supportsVersion) throw new IllegalArgumentException("bind_interface " + bind_interface_str + " has incorrect IP version") ; } else { // (bind_intf == null) throw new UnknownHostException("network interface " + bind_interface_str + " not found"); } } // 3. intf and bind_addr are both are specified, bind_addr needs to be on intf if (bind_intf != null && bind_addr != null) { boolean hasAddress = false ; // get all the InetAddresses defined on the interface Enumeration addresses = bind_intf.getInetAddresses() ; while (addresses != null && addresses.hasMoreElements()) { // get the next InetAddress for the current interface InetAddress address = (InetAddress) addresses.nextElement() ; // check if address is on interface if (bind_addr.equals(address)) { hasAddress = true ; break ; } } if (!hasAddress) { throw new IllegalArgumentException("network interface " + bind_interface_str + " does not contain address " + bind_addr_str); } } // 4. if only interface is specified, get first non-loopback address on that interface, else if (bind_intf != null) { bind_addr = getAddress(bind_intf, AddressScope.NON_LOOPBACK) ; } // 5. if neither bind address nor bind interface is specified, get the first non-loopback // address on any interface else if (bind_addr == null) { bind_addr = getNonLoopbackAddress() ; } // if we reach here, if bind_addr == null, we have tried to obtain a bind_addr but were not successful // in such a case, using a loopback address of the correct version is our only option boolean localhost = false; if (bind_addr == null) { bind_addr = getLocalhost(ip_version); localhost = true; } //check all bind_address against NetworkInterface.getByInetAddress() to see if it exists on the machine //in some Linux setups NetworkInterface.getByInetAddress(InetAddress.getLocalHost()) returns null, so skip //the check in that case if(!localhost && NetworkInterface.getByInetAddress(bind_addr) == null) { throw new UnknownHostException("Invalid bind address " + bind_addr); } if(props != null) { props.remove("bind_addr"); props.remove("bind_interface"); } return bind_addr; } /** * Method used by PropertyConverters.BindInterface to check that a bind_address is * consistent with a specified interface * * Idea: * 1. We are passed a bind_addr, which may be null * 2. If non-null, check that bind_addr is on bind_interface - if not, throw exception, * otherwise, return the original bind_addr * 3. If null, get first non-loopback address on bind_interface, using stack preference to * get the IP version. If no non-loopback address, then just return null (i.e. the * bind_interface did not influence the decision). * */ public static InetAddress validateBindAddressFromInterface(InetAddress bind_addr, String bind_interface_str) throws UnknownHostException, SocketException { NetworkInterface bind_intf=null; if(bind_addr != null && bind_addr.isLoopbackAddress()) return bind_addr; // 1. if bind_interface_str is null, or empty, no constraint on bind_addr if (bind_interface_str == null || bind_interface_str.trim().length() == 0) return bind_addr; // 2. get the preferred IP version for the JVM - it will be IPv4 or IPv6 StackType ip_version = getIpStackType(); // 3. if bind_interface_str specified, get interface and check that it has correct version bind_intf=NetworkInterface.getByName(bind_interface_str); if(bind_intf != null) { // check that the interface supports the IP version boolean supportsVersion = interfaceHasIPAddresses(bind_intf, ip_version) ; if (!supportsVersion) throw new IllegalArgumentException("bind_interface " + bind_interface_str + " has incorrect IP version") ; } else { // (bind_intf == null) throw new UnknownHostException("network interface " + bind_interface_str + " not found"); } // 3. intf and bind_addr are both are specified, bind_addr needs to be on intf if (bind_addr != null) { boolean hasAddress = false ; // get all the InetAddresses defined on the interface Enumeration addresses = bind_intf.getInetAddresses() ; while (addresses != null && addresses.hasMoreElements()) { // get the next InetAddress for the current interface InetAddress address = (InetAddress) addresses.nextElement() ; // check if address is on interface if (bind_addr.equals(address)) { hasAddress = true ; break ; } } if (!hasAddress) { String bind_addr_str = bind_addr.getHostAddress(); throw new IllegalArgumentException("network interface " + bind_interface_str + " does not contain address " + bind_addr_str); } } // 4. if only interface is specified, get first non-loopback address on that interface, else { bind_addr = getAddress(bind_intf, AddressScope.NON_LOOPBACK) ; } //check all bind_address against NetworkInterface.getByInetAddress() to see if it exists on the machine //in some Linux setups NetworkInterface.getByInetAddress(InetAddress.getLocalHost()) returns null, so skip //the check in that case if(bind_addr != null && NetworkInterface.getByInetAddress(bind_addr) == null) { throw new UnknownHostException("Invalid bind address " + bind_addr); } // if bind_addr == null, we have tried to obtain a bind_addr but were not successful // in such a case, return the original value of null so the default will be applied return bind_addr; } public static boolean checkForLinux() { return checkForPresence("os.name", "linux"); } public static boolean checkForHp() { return checkForPresence("os.name", "hp"); } public static boolean checkForSolaris() { return checkForPresence("os.name", "sun"); } public static boolean checkForWindows() { return checkForPresence("os.name", "win"); } public static boolean checkForMac() { return checkForPresence("os.name", "mac"); } private static boolean checkForPresence(String key, String value) { try { String tmp=System.getProperty(key); return tmp != null && tmp.trim().toLowerCase().startsWith(value); } catch(Throwable t) { return false; } } public static void prompt(String s) { System.out.println(s); System.out.flush(); try { while(System.in.available() > 0) System.in.read(); System.in.read(); } catch(IOException e) { e.printStackTrace(); } } /** IP related utilities */ public static InetAddress getLocalhost(StackType ip_version) throws UnknownHostException { if (ip_version == StackType.IPv4) return InetAddress.getByName("127.0.0.1") ; else return InetAddress.getByName("::1") ; } /** * Returns the first non-loopback address on any interface on the current host. */ public static InetAddress getNonLoopbackAddress() throws SocketException { return getAddress(AddressScope.NON_LOOPBACK); } /** * Returns the first address on any interface of the current host, which satisfies scope */ public static InetAddress getAddress(AddressScope scope) throws SocketException { InetAddress address=null ; Enumeration intfs=NetworkInterface.getNetworkInterfaces(); while(intfs.hasMoreElements()) { NetworkInterface intf=(NetworkInterface)intfs.nextElement(); try { if(intf.isUp()) { address=getAddress(intf, scope) ; if(address != null) return address; } } catch (SocketException e) { } } return null ; } /** * Returns the first address on the given interface on the current host, which satisfies scope * * @param intf the interface to be checked */ public static InetAddress getAddress(NetworkInterface intf, AddressScope scope) { StackType ip_version=Util.getIpStackType(); for(Enumeration addresses=intf.getInetAddresses(); addresses.hasMoreElements();) { InetAddress addr=(InetAddress)addresses.nextElement(); boolean match; switch(scope) { case GLOBAL: match=!addr.isLoopbackAddress() && !addr.isLinkLocalAddress() && !addr.isSiteLocalAddress(); break; case SITE_LOCAL: match=addr.isSiteLocalAddress(); break; case LINK_LOCAL: match=addr.isLinkLocalAddress(); break; case LOOPBACK: match=addr.isLoopbackAddress(); break; case NON_LOOPBACK: match=!addr.isLoopbackAddress(); break; default: throw new IllegalArgumentException("scope " + scope + " is unknown"); } if(match) { if((addr instanceof Inet4Address && ip_version == StackType.IPv4) || (addr instanceof Inet6Address && ip_version == StackType.IPv6)) return addr; } } return null ; } /** * A function to check if an interface supports an IP version (i.e has addresses * defined for that IP version). * * @param intf * @return */ public static boolean interfaceHasIPAddresses(NetworkInterface intf, StackType ip_version) throws UnknownHostException { boolean supportsVersion = false ; if (intf != null) { // get all the InetAddresses defined on the interface Enumeration addresses = intf.getInetAddresses() ; while (addresses != null && addresses.hasMoreElements()) { // get the next InetAddress for the current interface InetAddress address = (InetAddress) addresses.nextElement() ; // check if we find an address of correct version if ((address instanceof Inet4Address && (ip_version == StackType.IPv4)) || (address instanceof Inet6Address && (ip_version == StackType.IPv6))) { supportsVersion = true ; break ; } } } else { throw new UnknownHostException("network interface " + intf + " not found") ; } return supportsVersion ; } public static StackType getIpStackType() { return ip_stack_type; } /** * Tries to determine the type of IP stack from the available interfaces and their addresses and from the * system properties (java.net.preferIPv4Stack and java.net.preferIPv6Addresses) * @return StackType.IPv4 for an IPv4 only stack, StackYTypeIPv6 for an IPv6 only stack, and StackType.Unknown * if the type cannot be detected */ private static StackType _getIpStackType() { boolean isIPv4StackAvailable = isStackAvailable(true) ; boolean isIPv6StackAvailable = isStackAvailable(false) ; // if only IPv4 stack available if (isIPv4StackAvailable && !isIPv6StackAvailable) { return StackType.IPv4; } // if only IPv6 stack available else if (isIPv6StackAvailable && !isIPv4StackAvailable) { return StackType.IPv6; } // if dual stack else if (isIPv4StackAvailable && isIPv6StackAvailable) { // get the System property which records user preference for a stack on a dual stack machine if(Boolean.getBoolean(Global.IPv4)) // has preference over java.net.preferIPv6Addresses return StackType.IPv4; if(Boolean.getBoolean(Global.IPv6)) return StackType.IPv6; return StackType.IPv6; } return StackType.Unknown; } public static boolean isStackAvailable(boolean ipv4) { Collection<InetAddress> all_addrs=getAllAvailableAddresses(); for(InetAddress addr: all_addrs) if(ipv4 && addr instanceof Inet4Address || (!ipv4 && addr instanceof Inet6Address)) return true; return false; } public static List<NetworkInterface> getAllAvailableInterfaces() throws SocketException { List<NetworkInterface> retval=new ArrayList<NetworkInterface>(10); NetworkInterface intf; for(Enumeration en=NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { intf=(NetworkInterface)en.nextElement(); retval.add(intf); } return retval; } public static Collection<InetAddress> getAllAvailableAddresses() { Set<InetAddress> retval=new HashSet<InetAddress>(); Enumeration en; try { en=NetworkInterface.getNetworkInterfaces(); if(en == null) return retval; while(en.hasMoreElements()) { NetworkInterface intf=(NetworkInterface)en.nextElement(); Enumeration<InetAddress> addrs=intf.getInetAddresses(); while(addrs.hasMoreElements()) retval.add(addrs.nextElement()); } } catch(SocketException e) { e.printStackTrace(); } return retval; } public static void checkIfValidAddress(InetAddress bind_addr, String prot_name) throws Exception { if(bind_addr.isAnyLocalAddress() || bind_addr.isLoopbackAddress()) return; Collection<InetAddress> addrs=getAllAvailableAddresses(); for(InetAddress addr: addrs) { if(addr.equals(bind_addr)) return; } throw new BindException("[" + prot_name + "] " + bind_addr + " is not a valid address on any local network interface"); } /** * Returns a value associated wither with one or more system properties, or found in the props map * @param system_props * @param props List of properties read from the configuration file * @param prop_name The name of the property, will be removed from props if found * @param ignore_sysprops If true, system properties are not used and the values will only be retrieved from * props (not system_props) * @param default_value Used to return a default value if the properties or system properties didn't have the value * @return The value, or null if not found */ public static String getProperty(String[] system_props, Properties props, String prop_name, boolean ignore_sysprops, String default_value) { String retval=null; if(props != null && prop_name != null) { retval=props.getProperty(prop_name); props.remove(prop_name); } if(!ignore_sysprops) { String tmp, prop; if(system_props != null) { for(int i=0; i < system_props.length; i++) { prop=system_props[i]; if(prop != null) { try { tmp=System.getProperty(prop); if(tmp != null) return tmp; // system properties override config file definitions } catch(SecurityException ex) {} } } } } if(retval == null) return default_value; return retval; } public static boolean isBindAddressPropertyIgnored() { try { String tmp=System.getProperty(Global.IGNORE_BIND_ADDRESS_PROPERTY); if(tmp == null) return false; tmp=tmp.trim().toLowerCase(); return !(tmp.equals("false") || tmp.equals("no") || tmp.equals("off")) && (tmp.equals("true") || tmp.equals("yes") || tmp.equals("on")); } catch(SecurityException ex) { return false; } } public static boolean isCoordinator(JChannel ch) { return isCoordinator(ch.getView(), ch.getAddress()); } public static boolean isCoordinator(View view, Address local_addr) { if(view == null || local_addr == null) return false; List<Address> mbrs=view.getMembers(); return !(mbrs == null || mbrs.isEmpty()) && local_addr.equals(mbrs.iterator().next()); } public static MBeanServer getMBeanServer() { ArrayList servers = MBeanServerFactory.findMBeanServer(null); if (servers != null && !servers.isEmpty()) { // return 'jboss' server if available for (int i = 0; i < servers.size(); i++) { MBeanServer srv = (MBeanServer) servers.get(i); if ("jboss".equalsIgnoreCase(srv.getDefaultDomain())) return srv; } // return first available server return (MBeanServer) servers.get(0); } else { //if it all fails, create a default return MBeanServerFactory.createMBeanServer(); } } public static void registerChannel(JChannel channel, String name) { MBeanServer server=Util.getMBeanServer(); if(server != null) { try { JmxConfigurator.registerChannel(channel, server, (name != null? name : "jgroups"), channel.getClusterName(), true); } catch(Exception e) { e.printStackTrace(); } } } public static String generateList(Collection c, String separator) { if(c == null) return null; StringBuilder sb=new StringBuilder(); boolean first=true; for(Iterator it=c.iterator(); it.hasNext();) { if(first) { first=false; } else { sb.append(separator); } sb.append(it.next()); } return sb.toString(); } /** * Go through the input string and replace any occurance of ${p} with the * props.getProperty(p) value. If there is no such property p defined, then * the ${p} reference will remain unchanged. * * If the property reference is of the form ${p:v} and there is no such * property p, then the default value v will be returned. * * If the property reference is of the form ${p1,p2} or ${p1,p2:v} then the * primary and the secondary properties will be tried in turn, before * returning either the unchanged input, or the default value. * * The property ${/} is replaced with System.getProperty("file.separator") * value and the property ${:} is replaced with * System.getProperty("path.separator"). * * @param string - * the string with possible ${} references * @param props - * the source for ${x} property ref values, null means use * System.getProperty() * @return the input string with all property references replaced if any. If * there are no valid references the input string will be returned. * @throws {@link java.security.AccessControlException} * when not authorised to retrieved system properties */ public static String replaceProperties(final String string, final Properties props) { /** File separator value */ final String FILE_SEPARATOR=File.separator; /** Path separator value */ final String PATH_SEPARATOR=File.pathSeparator; /** File separator alias */ final String FILE_SEPARATOR_ALIAS="/"; /** Path separator alias */ final String PATH_SEPARATOR_ALIAS=":"; // States used in property parsing final int NORMAL=0; final int SEEN_DOLLAR=1; final int IN_BRACKET=2; final char[] chars=string.toCharArray(); StringBuilder buffer=new StringBuilder(); boolean properties=false; int state=NORMAL; int start=0; for(int i=0;i < chars.length;++i) { char c=chars[i]; // Dollar sign outside brackets if(c == '$' && state != IN_BRACKET) state=SEEN_DOLLAR; // Open bracket immediatley after dollar else if(c == '{' && state == SEEN_DOLLAR) { buffer.append(string.substring(start, i - 1)); state=IN_BRACKET; start=i - 1; } // No open bracket after dollar else if(state == SEEN_DOLLAR) state=NORMAL; // Closed bracket after open bracket else if(c == '}' && state == IN_BRACKET) { // No content if(start + 2 == i) { buffer.append("${}"); // REVIEW: Correct? } else // Collect the system property { String value=null; String key=string.substring(start + 2, i); // check for alias if(FILE_SEPARATOR_ALIAS.equals(key)) { value=FILE_SEPARATOR; } else if(PATH_SEPARATOR_ALIAS.equals(key)) { value=PATH_SEPARATOR; } else { // check from the properties if(props != null) value=props.getProperty(key); else value=System.getProperty(key); if(value == null) { // Check for a default value ${key:default} int colon=key.indexOf(':'); if(colon > 0) { String realKey=key.substring(0, colon); if(props != null) value=props.getProperty(realKey); else value=System.getProperty(realKey); if(value == null) { // Check for a composite key, "key1,key2" value=resolveCompositeKey(realKey, props); // Not a composite key either, use the specified default if(value == null) value=key.substring(colon + 1); } } else { // No default, check for a composite key, "key1,key2" value=resolveCompositeKey(key, props); } } } if(value != null) { properties=true; buffer.append(value); } } start=i + 1; state=NORMAL; } } // No properties if(properties == false) return string; // Collect the trailing characters if(start != chars.length) buffer.append(string.substring(start, chars.length)); // Done return buffer.toString(); } /** * Try to resolve a "key" from the provided properties by checking if it is * actually a "key1,key2", in which case try first "key1", then "key2". If * all fails, return null. * * It also accepts "key1," and ",key2". * * @param key * the key to resolve * @param props * the properties to use * @return the resolved key or null */ private static String resolveCompositeKey(String key, Properties props) { String value=null; // Look for the comma int comma=key.indexOf(','); if(comma > -1) { // If we have a first part, try resolve it if(comma > 0) { // Check the first part String key1=key.substring(0, comma); if(props != null) value=props.getProperty(key1); else value=System.getProperty(key1); } // Check the second part, if there is one and first lookup failed if(value == null && comma < key.length() - 1) { String key2=key.substring(comma + 1); if(props != null) value=props.getProperty(key2); else value=System.getProperty(key2); } } // Return whatever we've found or null return value; } // /** // * Replaces variables with values from system properties. If a system property is not found, the property is // * removed from the output string // * @param input // * @return // */ // public static String substituteVariables(String input) throws Exception { // Collection<Configurator.ProtocolConfiguration> configs=Configurator.parseConfigurations(input); // for(Configurator.ProtocolConfiguration config: configs) { // for(Iterator<Map.Entry<String,String>> it=config.getProperties().entrySet().iterator(); it.hasNext();) { // Map.Entry<String,String> entry=it.next(); // return null; /** * Replaces variables of ${var:default} with System.getProperty(var, default). If no variables are found, returns * the same string, otherwise a copy of the string with variables substituted * @param val * @return A string with vars replaced, or the same string if no vars found */ public static String substituteVariable(String val) { if(val == null) return val; String retval=val, prev; while(retval.contains("${")) { // handle multiple variables in val prev=retval; retval=_substituteVar(retval); if(retval.equals(prev)) break; } return retval; } private static String _substituteVar(String val) { int start_index, end_index; start_index=val.indexOf("${"); if(start_index == -1) return val; end_index=val.indexOf("}", start_index+2); if(end_index == -1) throw new IllegalArgumentException("missing \"}\" in " + val); String tmp=getProperty(val.substring(start_index +2, end_index)); if(tmp == null) return val; StringBuilder sb=new StringBuilder(); sb.append(val.substring(0, start_index)); sb.append(tmp); sb.append(val.substring(end_index+1)); return sb.toString(); } public static String getProperty(String s) { String var, default_val, retval=null; int index=s.indexOf(":"); if(index >= 0) { var=s.substring(0, index); default_val=s.substring(index+1); if(default_val != null && default_val.length() > 0) default_val=default_val.trim(); // retval=System.getProperty(var, default_val); retval=_getProperty(var, default_val); } else { var=s; // retval=System.getProperty(var); retval=_getProperty(var, null); } return retval; } /** * Parses a var which might be comma delimited, e.g. bla,foo:1000: if 'bla' is set, return its value. Else, * if 'foo' is set, return its value, else return "1000" * @param var * @param default_value * @return */ private static String _getProperty(String var, String default_value) { if(var == null) return null; List<String> list=parseCommaDelimitedStrings(var); if(list == null || list.isEmpty()) { list=new ArrayList<String>(1); list.add(var); } String retval=null; for(String prop: list) { try { retval=System.getProperty(prop); if(retval != null) return retval; } catch(Throwable e) { } } return default_value; } /** * Used to convert a byte array in to a java.lang.String object * @param bytes the bytes to be converted * @return the String representation */ private static String getString(byte[] bytes) { StringBuilder sb=new StringBuilder(); for (int i = 0; i < bytes.length; i++) { byte b = bytes[i]; sb.append(0x00FF & b); if (i + 1 < bytes.length) { sb.append("-"); } } return sb.toString(); } /** * Converts a java.lang.String in to a MD5 hashed String * @param source the source String * @return the MD5 hashed version of the string */ public static String md5(String source) { try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] bytes = md.digest(source.getBytes()); return getString(bytes); } catch (Exception e) { return null; } } /** * Converts a java.lang.String in to a SHA hashed String * @param source the source String * @return the MD5 hashed version of the string */ public static String sha(String source) { try { MessageDigest md = MessageDigest.getInstance("SHA"); byte[] bytes = md.digest(source.getBytes()); return getString(bytes); } catch (Exception e) { e.printStackTrace(); return null; } } public static String methodNameToAttributeName(String methodName) { methodName=methodName.startsWith("get") || methodName.startsWith("set")? methodName.substring(3): methodName; methodName=methodName.startsWith("is")? methodName.substring(2) : methodName; // Pattern p=Pattern.compile("[A-Z]+"); Matcher m=METHOD_NAME_TO_ATTR_NAME_PATTERN.matcher(methodName); StringBuffer sb=new StringBuffer(); while(m.find()) { int start=m.start(), end=m.end(); String str=methodName.substring(start, end).toLowerCase(); if(str.length() > 1) { String tmp1=str.substring(0, str.length() -1); String tmp2=str.substring(str.length() -1); str=tmp1 + "_" + tmp2; } if(start == 0) { m.appendReplacement(sb, str); } else m.appendReplacement(sb, "_" + str); } m.appendTail(sb); return sb.toString(); } public static String attributeNameToMethodName(String attr_name) { if(attr_name.contains("_")) { // Pattern p=Pattern.compile("_."); Matcher m=ATTR_NAME_TO_METHOD_NAME_PATTERN.matcher(attr_name); StringBuffer sb=new StringBuffer(); while(m.find()) { m.appendReplacement(sb, attr_name.substring(m.end() - 1, m.end()).toUpperCase()); } m.appendTail(sb); char first=sb.charAt(0); if(Character.isLowerCase(first)) { sb.setCharAt(0, Character.toUpperCase(first)); } return sb.toString(); } else { if(Character.isLowerCase(attr_name.charAt(0))) { return attr_name.substring(0, 1).toUpperCase() + attr_name.substring(1); } else { return attr_name; } } } /** * Runs a task on a separate thread * @param task * @param factory * @param group * @param thread_name */ public static void runAsync(Runnable task, ThreadFactory factory, ThreadGroup group, String thread_name) { Thread thread=factory.newThread(group, task, thread_name); thread.start(); } }
package org.objectweb.proactive.core.body; import java.io.IOException; import java.io.Serializable; import org.apache.log4j.Logger; import org.objectweb.proactive.Job; import org.objectweb.proactive.core.UniqueID; import org.objectweb.proactive.core.body.ft.internalmsg.FTMessage; import org.objectweb.proactive.core.body.reply.Reply; import org.objectweb.proactive.core.body.request.Request; import org.objectweb.proactive.core.component.request.Shortcut; import org.objectweb.proactive.core.gc.GCMessage; import org.objectweb.proactive.core.gc.GCResponse; import org.objectweb.proactive.core.remoteobject.exception.UnknownProtocolException; import org.objectweb.proactive.core.security.SecurityEntity; import org.objectweb.proactive.core.security.exceptions.RenegotiateSessionException; import org.objectweb.proactive.core.util.log.Loggers; import org.objectweb.proactive.core.util.log.ProActiveLogger; /** * An object implementing this interface provides the minimum service a body offers * remotely or locally. This interface is the generic version that is used remotely * and locally. A body accessed from the same JVM offers all services of this interface, * plus the services defined in the Body interface. * * @author The ProActive Team * @version 1.0, 2001/10/23 * @since ProActive 0.9 * @see org.objectweb.proactive.Body * @see org.objectweb.proactive.core.body.rmi.RmiBodyAdapter */ public interface UniversalBody extends Job, Serializable, SecurityEntity { public static Logger bodyLogger = ProActiveLogger.getLogger(Loggers.BODY); public static Logger sendReplyExceptionsLogger = ProActiveLogger.getLogger(Loggers.EXCEPTIONS_SEND_REPLY); /** * Receives a request for later processing. The call to this method is non blocking * unless the body cannot temporary receive the request. * @param request the request to process * @exception java.io.IOException if the request cannot be accepted * @return value for fault-tolerance protocol */ public int receiveRequest(Request request) throws java.io.IOException, RenegotiateSessionException; /** * Receives a reply in response to a former request. * @param r the reply received * @exception java.io.IOException if the reply cannot be accepted * @return value for fault-tolerance procotol */ public int receiveReply(Reply r) throws java.io.IOException; /** * Returns the url of the node this body is associated to * The url of the node can change if the active object migrates * @return the url of the node this body is associated to */ public String getNodeURL(); /** * Returns the UniqueID of this body * This identifier is unique accross all JVMs * @return the UniqueID of this body */ public UniqueID getID(); /** * Signals to this body that the body identified by id is now to a new * remote location. The body given in parameter is a new stub pointing * to this new location. This call is a way for a body to signal to his * peer that it has migrated to a new location * @param id the id of the body * @param body the stub to the new location * @exception java.io.IOException if a pb occurs during this method call */ public void updateLocation(UniqueID id, UniversalBody body) throws java.io.IOException; /** * similar to the {@link UniversalBody#updateLocation(org.objectweb.proactive.core.UniqueID, UniversalBody)} method, * it allows direct communication to the target of a functional call, accross membranes of composite components. * @param shortcut the shortcut to create * @exception java.io.IOException if a pb occurs during this method call */ public void createShortcut(Shortcut shortcut) throws java.io.IOException; /** * Returns the remote friendly version of this body * @return the remote friendly version of this body */ public UniversalBody getRemoteAdapter(); /** * Returns the name of the class of the reified object * @return the name of the class of the reified object */ public String getReifiedClassName(); /** * Enables automatic continuation mechanism for this body * @exception java.io.IOException if a pb occurs during this method call */ public void enableAC() throws java.io.IOException; /** * Disables automatic continuation mechanism for this body * @exception java.io.IOException if a pb occurs during this method call */ public void disableAC() throws java.io.IOException; // FAULT TOLERANCE /** * For sending a non fonctional message to the FTManager linked to this object. * @param ev the message to send * @return depends on the message meaning * @exception java.io.IOException if a pb occurs during this method call */ public Object receiveFTMessage(FTMessage ev) throws IOException; /** * The DGC broadcasting method, called every GarbageCollector.TTB between * referenced active objects. The GC{Message,Response} may actually be * composed of many GCSimple{Message,Response}. * * @param toSend the message * @return its associated response * @throws IOException if a pb occurs during this method call */ public GCResponse receiveGCMessage(GCMessage toSend) throws IOException; /** * Inform the DGC that an active object is pinned somewhere so cannot * be garbage collected until being unregistered. * @param registered true for a registration, false for an unregistration * @throws IOException if a pb occurs during this method call */ public void setRegistered(boolean registered) throws IOException; /** * Allow to specify an url where to register the active object. * @param url the url where to bind the active object * @throws IOException * @throws UnknownProtocolException thrown if the protocol is not supported by * the current active object */ public void register(String url) throws IOException, UnknownProtocolException; }
package org.jgroups.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jgroups.*; import org.jgroups.auth.AuthToken; import org.jgroups.conf.ClassConfigurator; import org.jgroups.protocols.FD; import org.jgroups.protocols.PingHeader; import org.jgroups.stack.IpAddress; import org.jgroups.stack.Protocol; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import java.io.*; import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.net.*; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; import java.security.MessageDigest; import java.text.NumberFormat; import java.util.*; /** * Collection of various utility routines that can not be assigned to other classes. * @author Bela Ban * @version $Id: Util.java,v 1.141 2008/01/24 13:52:11 belaban Exp $ */ public class Util { private static NumberFormat f; private static Map PRIMITIVE_TYPES=new HashMap(10); private static final byte TYPE_NULL = 0; private static final byte TYPE_STREAMABLE = 1; private static final byte TYPE_SERIALIZABLE = 2; private static final byte TYPE_BOOLEAN = 10; private static final byte TYPE_BYTE = 11; private static final byte TYPE_CHAR = 12; private static final byte TYPE_DOUBLE = 13; private static final byte TYPE_FLOAT = 14; private static final byte TYPE_INT = 15; private static final byte TYPE_LONG = 16; private static final byte TYPE_SHORT = 17; private static final byte TYPE_STRING = 18; // constants public static final int MAX_PORT=65535; // highest port allocatable static boolean resolve_dns=false; static boolean JGROUPS_COMPAT=false; /** * Global thread group to which all (most!) JGroups threads belong */ private static ThreadGroup GLOBAL_GROUP=new ThreadGroup("JGroups") { public void uncaughtException(Thread t, Throwable e) { LogFactory.getLog("org.jgroups").error("uncaught exception in " + t + " (thread group=" + GLOBAL_GROUP + " )", e); } }; public static ThreadGroup getGlobalThreadGroup() { return GLOBAL_GROUP; } static { try { resolve_dns=Boolean.valueOf(System.getProperty("resolve.dns", "false")).booleanValue(); } catch (SecurityException ex){ resolve_dns=false; } f=NumberFormat.getNumberInstance(); f.setGroupingUsed(false); f.setMaximumFractionDigits(2); try { String tmp=Util.getProperty(new String[]{Global.MARSHALLING_COMPAT}, null, null, false, "false"); JGROUPS_COMPAT=Boolean.valueOf(tmp).booleanValue(); } catch (SecurityException ex){ } PRIMITIVE_TYPES.put(Boolean.class, new Byte(TYPE_BOOLEAN)); PRIMITIVE_TYPES.put(Byte.class, new Byte(TYPE_BYTE)); PRIMITIVE_TYPES.put(Character.class, new Byte(TYPE_CHAR)); PRIMITIVE_TYPES.put(Double.class, new Byte(TYPE_DOUBLE)); PRIMITIVE_TYPES.put(Float.class, new Byte(TYPE_FLOAT)); PRIMITIVE_TYPES.put(Integer.class, new Byte(TYPE_INT)); PRIMITIVE_TYPES.put(Long.class, new Byte(TYPE_LONG)); PRIMITIVE_TYPES.put(Short.class, new Byte(TYPE_SHORT)); PRIMITIVE_TYPES.put(String.class, new Byte(TYPE_STRING)); } /** * Verifies that val is <= max memory * @param buf_name * @param val */ public static void checkBufferSize(String buf_name, long val) { // sanity check that max_credits doesn't exceed memory allocated to VM by -Xmx long max_mem=Runtime.getRuntime().maxMemory(); if(val > max_mem) { throw new IllegalArgumentException(buf_name + "(" + Util.printBytes(val) + ") exceeds max memory allocated to VM (" + Util.printBytes(max_mem) + ")"); } } public static void close(InputStream inp) { if(inp != null) try {inp.close();} catch(IOException e) {} } public static void close(OutputStream out) { if(out != null) { try {out.close();} catch(IOException e) {} } } public static void close(Socket s) { if(s != null) { try {s.close();} catch(Exception ex) {} } } public static void close(DatagramSocket my_sock) { if(my_sock != null) { try {my_sock.close();} catch(Throwable t) {} } } /** * Creates an object from a byte buffer */ public static Object objectFromByteBuffer(byte[] buffer) throws Exception { if(buffer == null) return null; if(JGROUPS_COMPAT) return oldObjectFromByteBuffer(buffer); return objectFromByteBuffer(buffer, 0, buffer.length); } public static Object objectFromByteBuffer(byte[] buffer, int offset, int length) throws Exception { if(buffer == null) return null; if(JGROUPS_COMPAT) return oldObjectFromByteBuffer(buffer, offset, length); Object retval=null; InputStream in=null; ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer, offset, length); byte b=(byte)in_stream.read(); try { switch(b) { case TYPE_NULL: return null; case TYPE_STREAMABLE: in=new DataInputStream(in_stream); retval=readGenericStreamable((DataInputStream)in); break; case TYPE_SERIALIZABLE: // the object is Externalizable or Serializable in=new ContextObjectInputStream(in_stream); // changed Nov 29 2004 (bela) retval=((ContextObjectInputStream)in).readObject(); break; case TYPE_BOOLEAN: in=new DataInputStream(in_stream); retval=Boolean.valueOf(((DataInputStream)in).readBoolean()); break; case TYPE_BYTE: in=new DataInputStream(in_stream); retval=new Byte(((DataInputStream)in).readByte()); break; case TYPE_CHAR: in=new DataInputStream(in_stream); retval=new Character(((DataInputStream)in).readChar()); break; case TYPE_DOUBLE: in=new DataInputStream(in_stream); retval=new Double(((DataInputStream)in).readDouble()); break; case TYPE_FLOAT: in=new DataInputStream(in_stream); retval=new Float(((DataInputStream)in).readFloat()); break; case TYPE_INT: in=new DataInputStream(in_stream); retval=new Integer(((DataInputStream)in).readInt()); break; case TYPE_LONG: in=new DataInputStream(in_stream); retval=new Long(((DataInputStream)in).readLong()); break; case TYPE_SHORT: in=new DataInputStream(in_stream); retval=new Short(((DataInputStream)in).readShort()); break; case TYPE_STRING: in=new DataInputStream(in_stream); if(((DataInputStream)in).readBoolean()) { // large string ObjectInputStream ois=new ObjectInputStream(in); try { return ois.readObject(); } finally { ois.close(); } } else { retval=((DataInputStream)in).readUTF(); } break; default: throw new IllegalArgumentException("type " + b + " is invalid"); } return retval; } finally { Util.close(in); } } /** * Serializes/Streams an object into a byte buffer. * The object has to implement interface Serializable or Externalizable * or Streamable. Only Streamable objects are interoperable w/ jgroups-me */ public static byte[] objectToByteBuffer(Object obj) throws Exception { if(JGROUPS_COMPAT) return oldObjectToByteBuffer(obj); byte[] result=null; final ByteArrayOutputStream out_stream=new ByteArrayOutputStream(512); if(obj == null) { out_stream.write(TYPE_NULL); out_stream.flush(); return out_stream.toByteArray(); } OutputStream out=null; Byte type; try { if(obj instanceof Streamable) { // use Streamable if we can out_stream.write(TYPE_STREAMABLE); out=new DataOutputStream(out_stream); writeGenericStreamable((Streamable)obj, (DataOutputStream)out); } else if((type=(Byte)PRIMITIVE_TYPES.get(obj.getClass())) != null) { out_stream.write(type.byteValue()); out=new DataOutputStream(out_stream); switch(type.byteValue()) { case TYPE_BOOLEAN: ((DataOutputStream)out).writeBoolean(((Boolean)obj).booleanValue()); break; case TYPE_BYTE: ((DataOutputStream)out).writeByte(((Byte)obj).byteValue()); break; case TYPE_CHAR: ((DataOutputStream)out).writeChar(((Character)obj).charValue()); break; case TYPE_DOUBLE: ((DataOutputStream)out).writeDouble(((Double)obj).doubleValue()); break; case TYPE_FLOAT: ((DataOutputStream)out).writeFloat(((Float)obj).floatValue()); break; case TYPE_INT: ((DataOutputStream)out).writeInt(((Integer)obj).intValue()); break; case TYPE_LONG: ((DataOutputStream)out).writeLong(((Long)obj).longValue()); break; case TYPE_SHORT: ((DataOutputStream)out).writeShort(((Short)obj).shortValue()); break; case TYPE_STRING: String str=(String)obj; if(str.length() > Short.MAX_VALUE) { ((DataOutputStream)out).writeBoolean(true); ObjectOutputStream oos=new ObjectOutputStream(out); try { oos.writeObject(str); } finally { oos.close(); } } else { ((DataOutputStream)out).writeBoolean(false); ((DataOutputStream)out).writeUTF(str); } break; default: throw new IllegalArgumentException("type " + type + " is invalid"); } } else { // will throw an exception if object is not serializable out_stream.write(TYPE_SERIALIZABLE); out=new ObjectOutputStream(out_stream); ((ObjectOutputStream)out).writeObject(obj); } } finally { Util.close(out); } result=out_stream.toByteArray(); return result; } /** For backward compatibility in JBoss 4.0.2 */ public static Object oldObjectFromByteBuffer(byte[] buffer) throws Exception { if(buffer == null) return null; return oldObjectFromByteBuffer(buffer, 0, buffer.length); } public static Object oldObjectFromByteBuffer(byte[] buffer, int offset, int length) throws Exception { if(buffer == null) return null; Object retval=null; try { // to read the object as an Externalizable ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer, offset, length); ObjectInputStream in=new ContextObjectInputStream(in_stream); // changed Nov 29 2004 (bela) retval=in.readObject(); in.close(); } catch(StreamCorruptedException sce) { try { // is it Streamable? ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer, offset, length); DataInputStream in=new DataInputStream(in_stream); retval=readGenericStreamable(in); in.close(); } catch(Exception ee) { IOException tmp=new IOException("unmarshalling failed"); tmp.initCause(ee); throw tmp; } } if(retval == null) return null; return retval; } /** * Serializes/Streams an object into a byte buffer. * The object has to implement interface Serializable or Externalizable * or Streamable. Only Streamable objects are interoperable w/ jgroups-me */ public static byte[] oldObjectToByteBuffer(Object obj) throws Exception { byte[] result=null; final ByteArrayOutputStream out_stream=new ByteArrayOutputStream(512); if(obj instanceof Streamable) { // use Streamable if we can DataOutputStream out=new DataOutputStream(out_stream); writeGenericStreamable((Streamable)obj, out); out.close(); } else { ObjectOutputStream out=new ObjectOutputStream(out_stream); out.writeObject(obj); out.close(); } result=out_stream.toByteArray(); return result; } public static Streamable streamableFromByteBuffer(Class cl, byte[] buffer) throws Exception { if(buffer == null) return null; Streamable retval=null; ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer); DataInputStream in=new DataInputStream(in_stream); // changed Nov 29 2004 (bela) retval=(Streamable)cl.newInstance(); retval.readFrom(in); in.close(); return retval; } public static Streamable streamableFromByteBuffer(Class cl, byte[] buffer, int offset, int length) throws Exception { if(buffer == null) return null; Streamable retval=null; ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer, offset, length); DataInputStream in=new DataInputStream(in_stream); // changed Nov 29 2004 (bela) retval=(Streamable)cl.newInstance(); retval.readFrom(in); in.close(); return retval; } public static byte[] streamableToByteBuffer(Streamable obj) throws Exception { byte[] result=null; final ByteArrayOutputStream out_stream=new ByteArrayOutputStream(512); DataOutputStream out=new DataOutputStream(out_stream); obj.writeTo(out); result=out_stream.toByteArray(); out.close(); return result; } public static byte[] collectionToByteBuffer(Collection c) throws Exception { byte[] result=null; final ByteArrayOutputStream out_stream=new ByteArrayOutputStream(512); DataOutputStream out=new DataOutputStream(out_stream); Util.writeAddresses(c, out); result=out_stream.toByteArray(); out.close(); return result; } public static int size(Address addr) { int retval=Global.BYTE_SIZE; // presence byte if(addr != null) retval+=addr.size() + Global.BYTE_SIZE; // plus type of address return retval; } public static void writeAuthToken(AuthToken token, DataOutputStream out) throws IOException{ Util.writeString(token.getName(), out); token.writeTo(out); } public static AuthToken readAuthToken(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException { try{ String type = Util.readString(in); Object obj = Class.forName(type).newInstance(); AuthToken token = (AuthToken) obj; token.readFrom(in); return token; } catch(ClassNotFoundException cnfe){ return null; } } public static void writeAddress(Address addr, DataOutputStream out) throws IOException { if(addr == null) { out.writeBoolean(false); return; } out.writeBoolean(true); if(addr instanceof IpAddress) { // regular case, we don't need to include class information about the type of Address, e.g. JmsAddress out.writeBoolean(true); addr.writeTo(out); } else { out.writeBoolean(false); writeOtherAddress(addr, out); } } public static Address readAddress(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException { Address addr=null; if(in.readBoolean() == false) return null; if(in.readBoolean()) { addr=new IpAddress(); addr.readFrom(in); } else { addr=readOtherAddress(in); } return addr; } private static Address readOtherAddress(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException { ClassConfigurator conf; try { conf=ClassConfigurator.getInstance(false); } catch(ChannelException e) { IllegalAccessException new_ex=new IllegalAccessException(); new_ex.initCause(e); throw new_ex; } int b=in.read(); short magic_number; String classname; Class cl=null; Address addr; if(b == 1) { magic_number=in.readShort(); cl=conf.get(magic_number); } else { classname=in.readUTF(); cl=conf.get(classname); } addr=(Address)cl.newInstance(); addr.readFrom(in); return addr; } private static void writeOtherAddress(Address addr, DataOutputStream out) throws IOException { ClassConfigurator conf=null; try { conf=ClassConfigurator.getInstance(false); } catch(ChannelException e) { IOException new_ex=new IOException(); new_ex.initCause(e); throw new_ex; } short magic_number=conf != null? conf.getMagicNumber(addr.getClass()) : -1; // write the class info if(magic_number == -1) { out.write(0); out.writeUTF(addr.getClass().getName()); } else { out.write(1); out.writeShort(magic_number); } // write the data itself addr.writeTo(out); } /** * Writes a Vector of Addresses. Can contain 65K addresses at most * @param v A Collection<Address> * @param out * @throws IOException */ public static void writeAddresses(Collection v, DataOutputStream out) throws IOException { if(v == null) { out.writeShort(-1); return; } out.writeShort(v.size()); Address addr; for(Iterator it=v.iterator(); it.hasNext();) { addr=(Address)it.next(); Util.writeAddress(addr, out); } } public static Collection<Address> readAddresses(DataInputStream in, Class cl) throws IOException, IllegalAccessException, InstantiationException { short length=in.readShort(); if(length < 0) return null; Collection<Address> retval=(Collection<Address>)cl.newInstance(); Address addr; for(int i=0; i < length; i++) { addr=Util.readAddress(in); retval.add(addr); } return retval; } /** * Returns the marshalled size of a Collection of Addresses. * <em>Assumes elements are of the same type !</em> * @param addrs Collection<Address> * @return long size */ public static long size(Collection addrs) { int retval=Global.SHORT_SIZE; // number of elements if(addrs != null && !addrs.isEmpty()) { Address addr=(Address)addrs.iterator().next(); retval+=size(addr) * addrs.size(); } return retval; } public static void writeStreamable(Streamable obj, DataOutputStream out) throws IOException { if(obj == null) { out.writeBoolean(false); return; } out.writeBoolean(true); obj.writeTo(out); } public static Streamable readStreamable(Class clazz, DataInputStream in) throws IOException, IllegalAccessException, InstantiationException { Streamable retval=null; if(in.readBoolean() == false) return null; retval=(Streamable)clazz.newInstance(); retval.readFrom(in); return retval; } public static void writeGenericStreamable(Streamable obj, DataOutputStream out) throws IOException { short magic_number; String classname; if(obj == null) { out.write(0); return; } try { out.write(1); magic_number=ClassConfigurator.getInstance(false).getMagicNumber(obj.getClass()); // write the magic number or the class name if(magic_number == -1) { out.writeBoolean(false); classname=obj.getClass().getName(); out.writeUTF(classname); } else { out.writeBoolean(true); out.writeShort(magic_number); } // write the contents obj.writeTo(out); } catch(ChannelException e) { throw new IOException("failed writing object of type " + obj.getClass() + " to stream: " + e.toString()); } } public static Streamable readGenericStreamable(DataInputStream in) throws IOException { Streamable retval=null; int b=in.read(); if(b == 0) return null; boolean use_magic_number=in.readBoolean(); String classname; Class clazz; try { if(use_magic_number) { short magic_number=in.readShort(); clazz=ClassConfigurator.getInstance(false).get(magic_number); if (clazz==null) { throw new ClassNotFoundException("Class for magic number "+magic_number+" cannot be found."); } } else { classname=in.readUTF(); clazz=ClassConfigurator.getInstance(false).get(classname); if (clazz==null) { throw new ClassNotFoundException(classname); } } retval=(Streamable)clazz.newInstance(); retval.readFrom(in); return retval; } catch(Exception ex) { throw new IOException("failed reading object: " + ex.toString()); } } public static void writeObject(Object obj, DataOutputStream out) throws Exception { if(obj == null || !(obj instanceof Streamable)) { byte[] buf=objectToByteBuffer(obj); out.writeShort(buf.length); out.write(buf, 0, buf.length); } else { out.writeShort(-1); writeGenericStreamable((Streamable)obj, out); } } public static Object readObject(DataInputStream in) throws Exception { short len=in.readShort(); Object retval=null; if(len == -1) { retval=readGenericStreamable(in); } else { byte[] buf=new byte[len]; in.readFully(buf, 0, len); retval=objectFromByteBuffer(buf); } return retval; } public static void writeString(String s, DataOutputStream out) throws IOException { if(s != null) { out.write(1); out.writeUTF(s); } else { out.write(0); } } public static String readString(DataInputStream in) throws IOException { int b=in.read(); if(b == 1) return in.readUTF(); return null; } public static void writeByteBuffer(byte[] buf, DataOutputStream out) throws IOException { if(buf != null) { out.write(1); out.writeInt(buf.length); out.write(buf, 0, buf.length); } else { out.write(0); } } public static byte[] readByteBuffer(DataInputStream in) throws IOException { int b=in.read(); if(b == 1) { b=in.readInt(); byte[] buf=new byte[b]; in.read(buf, 0, buf.length); return buf; } return null; } public static Buffer messageToByteBuffer(Message msg) throws IOException { ExposedByteArrayOutputStream output=new ExposedByteArrayOutputStream(512); DataOutputStream out=new DataOutputStream(output); out.writeBoolean(msg != null); if(msg != null) msg.writeTo(out); out.flush(); Buffer retval=new Buffer(output.getRawBuffer(), 0, output.size()); out.close(); output.close(); return retval; } public static Message byteBufferToMessage(byte[] buffer, int offset, int length) throws Exception { ByteArrayInputStream input=new ByteArrayInputStream(buffer, offset, length); DataInputStream in=new DataInputStream(input); if(!in.readBoolean()) return null; Message msg=new Message(false); // don't create headers, readFrom() will do this msg.readFrom(in); return msg; } /** * Marshalls a list of messages. * @param xmit_list LinkedList<Message> * @return Buffer * @throws IOException */ public static Buffer msgListToByteBuffer(List<Message> xmit_list) throws IOException { ExposedByteArrayOutputStream output=new ExposedByteArrayOutputStream(512); DataOutputStream out=new DataOutputStream(output); Buffer retval=null; out.writeInt(xmit_list.size()); for(Message msg: xmit_list) { msg.writeTo(out); } out.flush(); retval=new Buffer(output.getRawBuffer(), 0, output.size()); out.close(); output.close(); return retval; } public static List<Message> byteBufferToMessageList(byte[] buffer, int offset, int length) throws Exception { List<Message> retval=null; ByteArrayInputStream input=new ByteArrayInputStream(buffer, offset, length); DataInputStream in=new DataInputStream(input); int size=in.readInt(); if(size == 0) return null; Message msg; retval=new LinkedList<Message>(); for(int i=0; i < size; i++) { msg=new Message(false); // don't create headers, readFrom() will do this msg.readFrom(in); retval.add(msg); } return retval; } public static boolean match(Object obj1, Object obj2) { if(obj1 == null && obj2 == null) return true; if(obj1 != null) return obj1.equals(obj2); else return obj2.equals(obj1); } public static boolean match(long[] a1, long[] a2) { if(a1 == null && a2 == null) return true; if(a1 == null || a2 == null) return false; if(a1 == a2) // identity return true; // at this point, a1 != null and a2 != null if(a1.length != a2.length) return false; for(int i=0; i < a1.length; i++) { if(a1[i] != a2[i]) return false; } return true; } /** Sleep for timeout msecs. Returns when timeout has elapsed or thread was interrupted */ public static void sleep(long timeout) { try { Thread.sleep(timeout); } catch(Throwable e) { } } public static void sleep(long timeout, int nanos) { try { Thread.sleep(timeout, nanos); } catch(Throwable e) { } } /** * On most UNIX systems, the minimum sleep time is 10-20ms. Even if we specify sleep(1), the thread will * sleep for at least 10-20ms. On Windows, sleep() seems to be implemented as a busy sleep, that is the * thread never relinquishes control and therefore the sleep(x) is exactly x ms long. */ public static void sleep(long msecs, boolean busy_sleep) { if(!busy_sleep) { sleep(msecs); return; } long start=System.currentTimeMillis(); long stop=start + msecs; while(stop > start) { start=System.currentTimeMillis(); } } /** Returns a random value in the range [1 - range] */ public static long random(long range) { return (long)((Math.random() * 100000) % range) + 1; } /** Sleeps between 1 and timeout milliseconds, chosen randomly. Timeout must be > 1 */ public static void sleepRandom(long timeout) { if(timeout <= 0) { return; } long r=(int)((Math.random() * 100000) % timeout) + 1; sleep(r); } /** Tosses a coin weighted with probability and returns true or false. Example: if probability=0.8, chances are that in 80% of all cases, true will be returned and false in 20%. */ public static boolean tossWeightedCoin(double probability) { long r=random(100); long cutoff=(long)(probability * 100); return r < cutoff; } public static String getHostname() { try { return InetAddress.getLocalHost().getHostName(); } catch(Exception ex) { } return "localhost"; } public static void dumpStack(boolean exit) { try { throw new Exception("Dumping stack:"); } catch(Exception e) { e.printStackTrace(); if(exit) System.exit(0); } } public static String dumpThreads() { StringBuilder sb=new StringBuilder(); ThreadMXBean bean=ManagementFactory.getThreadMXBean(); long[] ids=bean.getAllThreadIds(); ThreadInfo[] threads=bean.getThreadInfo(ids, 20); for(int i=0; i < threads.length; i++) { ThreadInfo info=threads[i]; if(info == null) continue; sb.append(info.getThreadName()).append(":\n"); StackTraceElement[] stack_trace=info.getStackTrace(); for(int j=0; j < stack_trace.length; j++) { StackTraceElement el=stack_trace[j]; sb.append("at ").append(el.getClassName()).append(".").append(el.getMethodName()); sb.append("(").append(el.getFileName()).append(":").append(el.getLineNumber()).append(")"); sb.append("\n"); } sb.append("\n\n"); } return sb.toString(); } public static boolean interruptAndWaitToDie(Thread t) { return interruptAndWaitToDie(t, Global.THREAD_SHUTDOWN_WAIT_TIME); } public static boolean interruptAndWaitToDie(Thread t, long timeout) { if(t == null) throw new IllegalArgumentException("Thread can not be null"); t.interrupt(); // interrupts the sleep() try { t.join(timeout); } catch(InterruptedException e){ Thread.currentThread().interrupt(); // set interrupt flag again } return t.isAlive(); } /** * Debugging method used to dump the content of a protocol queue in a * condensed form. Useful to follow the evolution of the queue's content in * time. */ public static String dumpQueue(Queue q) { StringBuilder sb=new StringBuilder(); LinkedList values=q.values(); if(values.isEmpty()) { sb.append("empty"); } else { for(Iterator it=values.iterator(); it.hasNext();) { Object o=it.next(); String s=null; if(o instanceof Event) { Event event=(Event)o; int type=event.getType(); s=Event.type2String(type); if(type == Event.VIEW_CHANGE) s+=" " + event.getArg(); if(type == Event.MSG) s+=" " + event.getArg(); if(type == Event.MSG) { s+="["; Message m=(Message)event.getArg(); Map headers=new HashMap(m.getHeaders()); for(Iterator i=headers.keySet().iterator(); i.hasNext();) { Object headerKey=i.next(); Object value=headers.get(headerKey); String headerToString=null; if(value instanceof FD.FdHeader) { headerToString=value.toString(); } else if(value instanceof PingHeader) { headerToString=headerKey + "-"; if(((PingHeader)value).type == PingHeader.GET_MBRS_REQ) { headerToString+="GMREQ"; } else if(((PingHeader)value).type == PingHeader.GET_MBRS_RSP) { headerToString+="GMRSP"; } else { headerToString+="UNKNOWN"; } } else { headerToString=headerKey + "-" + (value == null ? "null" : value.toString()); } s+=headerToString; if(i.hasNext()) { s+=","; } } s+="]"; } } else { s=o.toString(); } sb.append(s).append("\n"); } } return sb.toString(); } /** * Use with caution: lots of overhead */ public static String printStackTrace(Throwable t) { StringWriter s=new StringWriter(); PrintWriter p=new PrintWriter(s); t.printStackTrace(p); return s.toString(); } public static String getStackTrace(Throwable t) { return printStackTrace(t); } public static String print(Throwable t) { return printStackTrace(t); } public static void crash() { System.exit(-1); } public static String printEvent(Event evt) { Message msg; if(evt.getType() == Event.MSG) { msg=(Message)evt.getArg(); if(msg != null) { if(msg.getLength() > 0) return printMessage(msg); else return msg.printObjectHeaders(); } } return evt.toString(); } /** Tries to read an object from the message's buffer and prints it */ public static String printMessage(Message msg) { if(msg == null) return ""; if(msg.getLength() == 0) return null; try { return msg.getObject().toString(); } catch(Exception e) { // it is not an object return ""; } } /** Tries to read a <code>MethodCall</code> object from the message's buffer and prints it. Returns empty string if object is not a method call */ public static String printMethodCall(Message msg) { Object obj; if(msg == null) return ""; if(msg.getLength() == 0) return ""; try { obj=msg.getObject(); return obj.toString(); } catch(Exception e) { // it is not an object return ""; } } public static void printThreads() { Thread threads[]=new Thread[Thread.activeCount()]; Thread.enumerate(threads); System.out.println(" for(int i=0; i < threads.length; i++) { System.out.println("#" + i + ": " + threads[i]); } System.out.println(" } public static String activeThreads() { StringBuilder sb=new StringBuilder(); Thread threads[]=new Thread[Thread.activeCount()]; Thread.enumerate(threads); sb.append(" for(int i=0; i < threads.length; i++) { sb.append("#").append(i).append(": ").append(threads[i]).append('\n'); } sb.append(" return sb.toString(); } public static String printBytes(long bytes) { double tmp; if(bytes < 1000) return bytes + "b"; if(bytes < 1000000) { tmp=bytes / 1000.0; return f.format(tmp) + "KB"; } if(bytes < 1000000000) { tmp=bytes / 1000000.0; return f.format(tmp) + "MB"; } else { tmp=bytes / 1000000000.0; return f.format(tmp) + "GB"; } } public static String printBytes(double bytes) { double tmp; if(bytes < 1000) return bytes + "b"; if(bytes < 1000000) { tmp=bytes / 1000.0; return f.format(tmp) + "KB"; } if(bytes < 1000000000) { tmp=bytes / 1000000.0; return f.format(tmp) + "MB"; } else { tmp=bytes / 1000000000.0; return f.format(tmp) + "GB"; } } /** Fragments a byte buffer into smaller fragments of (max.) frag_size. Example: a byte buffer of 1024 bytes and a frag_size of 248 gives 4 fragments of 248 bytes each and 1 fragment of 32 bytes. @return An array of byte buffers (<code>byte[]</code>). */ public static byte[][] fragmentBuffer(byte[] buf, int frag_size, final int length) { byte[] retval[]; int accumulated_size=0; byte[] fragment; int tmp_size=0; int num_frags; int index=0; num_frags=length % frag_size == 0 ? length / frag_size : length / frag_size + 1; retval=new byte[num_frags][]; while(accumulated_size < length) { if(accumulated_size + frag_size <= length) tmp_size=frag_size; else tmp_size=length - accumulated_size; fragment=new byte[tmp_size]; System.arraycopy(buf, accumulated_size, fragment, 0, tmp_size); retval[index++]=fragment; accumulated_size+=tmp_size; } return retval; } public static byte[][] fragmentBuffer(byte[] buf, int frag_size) { return fragmentBuffer(buf, frag_size, buf.length); } /** * Given a buffer and a fragmentation size, compute a list of fragmentation offset/length pairs, and * return them in a list. Example:<br/> * Buffer is 10 bytes, frag_size is 4 bytes. Return value will be ({0,4}, {4,4}, {8,2}). * This is a total of 3 fragments: the first fragment starts at 0, and has a length of 4 bytes, the second fragment * starts at offset 4 and has a length of 4 bytes, and the last fragment starts at offset 8 and has a length * of 2 bytes. * @param frag_size * @return List. A List<Range> of offset/length pairs */ public static java.util.List computeFragOffsets(int offset, int length, int frag_size) { java.util.List retval=new ArrayList(); long total_size=length + offset; int index=offset; int tmp_size=0; Range r; while(index < total_size) { if(index + frag_size <= total_size) tmp_size=frag_size; else tmp_size=(int)(total_size - index); r=new Range(index, tmp_size); retval.add(r); index+=tmp_size; } return retval; } public static java.util.List computeFragOffsets(byte[] buf, int frag_size) { return computeFragOffsets(0, buf.length, frag_size); } /** Concatenates smaller fragments into entire buffers. @param fragments An array of byte buffers (<code>byte[]</code>) @return A byte buffer */ public static byte[] defragmentBuffer(byte[] fragments[]) { int total_length=0; byte[] ret; int index=0; if(fragments == null) return null; for(int i=0; i < fragments.length; i++) { if(fragments[i] == null) continue; total_length+=fragments[i].length; } ret=new byte[total_length]; for(int i=0; i < fragments.length; i++) { if(fragments[i] == null) continue; System.arraycopy(fragments[i], 0, ret, index, fragments[i].length); index+=fragments[i].length; } return ret; } public static void printFragments(byte[] frags[]) { for(int i=0; i < frags.length; i++) System.out.println('\'' + new String(frags[i]) + '\''); } public static <T> String printListWithDelimiter(Collection<T> list, String delimiter) { boolean first=true; StringBuilder sb=new StringBuilder(); for(T el: list) { if(first) { first=false; } else { sb.append(delimiter); } sb.append(el); } return sb.toString(); } // /** // Peeks for view on the channel until n views have been received or timeout has elapsed. // Used to determine the view in which we want to start work. Usually, we start as only // member in our own view (1st view) and the next view (2nd view) will be the full view // of all members, or a timeout if we're the first member. If a non-view (a message or // block) is received, the method returns immediately. // @param channel The channel used to peek for views. Has to be operational. // @param number_of_views The number of views to wait for. 2 is a good number to ensure that, // if there are other members, we start working with them included in our view. // @param timeout Number of milliseconds to wait until view is forced to return. A value // of <= 0 means wait forever. // */ // public static View peekViews(Channel channel, int number_of_views, long timeout) { // View retval=null; // Object obj=null; // int num=0; // long start_time=System.currentTimeMillis(); // if(timeout <= 0) { // while(true) { // try { // obj=channel.peek(0); // if(obj == null || !(obj instanceof View)) // break; // else { // retval=(View)channel.receive(0); // num++; // if(num >= number_of_views) // break; // catch(Exception ex) { // break; // else { // while(timeout > 0) { // try { // obj=channel.peek(timeout); // if(obj == null || !(obj instanceof View)) // break; // else { // retval=(View)channel.receive(timeout); // num++; // if(num >= number_of_views) // break; // catch(Exception ex) { // break; // timeout=timeout - (System.currentTimeMillis() - start_time); // return retval; public static String array2String(long[] array) { StringBuilder ret=new StringBuilder("["); if(array != null) { for(int i=0; i < array.length; i++) ret.append(array[i]).append(" "); } ret.append(']'); return ret.toString(); } public static String array2String(short[] array) { StringBuilder ret=new StringBuilder("["); if(array != null) { for(int i=0; i < array.length; i++) ret.append(array[i]).append(" "); } ret.append(']'); return ret.toString(); } public static String array2String(int[] array) { StringBuilder ret=new StringBuilder("["); if(array != null) { for(int i=0; i < array.length; i++) ret.append(array[i]).append(" "); } ret.append(']'); return ret.toString(); } public static String array2String(boolean[] array) { StringBuilder ret=new StringBuilder("["); if(array != null) { for(int i=0; i < array.length; i++) ret.append(array[i]).append(" "); } ret.append(']'); return ret.toString(); } public static String array2String(Object[] array) { StringBuilder ret=new StringBuilder("["); if(array != null) { for(int i=0; i < array.length; i++) ret.append(array[i]).append(" "); } ret.append(']'); return ret.toString(); } /** Returns true if all elements of c match obj */ public static boolean all(Collection c, Object obj) { for(Iterator iterator=c.iterator(); iterator.hasNext();) { Object o=iterator.next(); if(!o.equals(obj)) return false; } return true; } /** * Selects a random subset of members according to subset_percentage and returns them. * Picks no member twice from the same membership. If the percentage is smaller than 1 -> picks 1 member. */ public static Vector pickSubset(Vector members, double subset_percentage) { Vector ret=new Vector(), tmp_mbrs; int num_mbrs=members.size(), subset_size, index; if(num_mbrs == 0) return ret; subset_size=(int)Math.ceil(num_mbrs * subset_percentage); tmp_mbrs=(Vector)members.clone(); for(int i=subset_size; i > 0 && !tmp_mbrs.isEmpty(); i index=(int)((Math.random() * num_mbrs) % tmp_mbrs.size()); ret.addElement(tmp_mbrs.elementAt(index)); tmp_mbrs.removeElementAt(index); } return ret; } public static Object pickRandomElement(List list) { if(list == null) return null; int size=list.size(); int index=(int)((Math.random() * size * 10) % size); return list.get(index); } public static Object pickRandomElement(Object[] array) { if(array == null) return null; int size=array.length; int index=(int)((Math.random() * size * 10) % size); return array[index]; } /** * Returns all members that left between 2 views. All members that are element of old_mbrs but not element of * new_mbrs are returned. */ public static Vector<Address> determineLeftMembers(Vector<Address> old_mbrs, Vector<Address> new_mbrs) { Vector<Address> retval=new Vector<Address>(); Address mbr; if(old_mbrs == null || new_mbrs == null) return retval; for(int i=0; i < old_mbrs.size(); i++) { mbr=old_mbrs.elementAt(i); if(!new_mbrs.contains(mbr)) retval.addElement(mbr); } return retval; } public static String printMembers(Vector v) { StringBuilder sb=new StringBuilder("("); boolean first=true; Object el; if(v != null) { for(int i=0; i < v.size(); i++) { if(!first) sb.append(", "); else first=false; el=v.elementAt(i); sb.append(el); } } sb.append(')'); return sb.toString(); } /** Makes sure that we detect when a peer connection is in the closed state (not closed while we send data, but before we send data). Two writes ensure that, if the peer closed the connection, the first write will send the peer from FIN to RST state, and the second will cause a signal (IOException). */ public static void doubleWrite(byte[] buf, OutputStream out) throws Exception { if(buf.length > 1) { out.write(buf, 0, 1); out.write(buf, 1, buf.length - 1); } else { out.write(buf, 0, 0); out.write(buf); } } /** Makes sure that we detect when a peer connection is in the closed state (not closed while we send data, but before we send data). Two writes ensure that, if the peer closed the connection, the first write will send the peer from FIN to RST state, and the second will cause a signal (IOException). */ public static void doubleWrite(byte[] buf, int offset, int length, OutputStream out) throws Exception { if(length > 1) { out.write(buf, offset, 1); out.write(buf, offset+1, length - 1); } else { out.write(buf, offset, 0); out.write(buf, offset, length); } } /** * if we were to register for OP_WRITE and send the remaining data on * readyOps for this channel we have to either block the caller thread or * queue the message buffers that may arrive while waiting for OP_WRITE. * Instead of the above approach this method will continuously write to the * channel until the buffer sent fully. */ public static void writeFully(ByteBuffer buf, WritableByteChannel out) throws IOException { int written = 0; int toWrite = buf.limit(); while (written < toWrite) { written += out.write(buf); } } // /* double writes are not required.*/ // public static void doubleWriteBuffer( // ByteBuffer buf, // WritableByteChannel out) // throws Exception // if (buf.limit() > 1) // int actualLimit = buf.limit(); // buf.limit(1); // writeFully(buf,out); // buf.limit(actualLimit); // writeFully(buf,out); // else // buf.limit(0); // writeFully(buf,out); // buf.limit(1); // writeFully(buf,out); public static long sizeOf(String classname) { Object inst; byte[] data; try { inst=Util.loadClass(classname, null).newInstance(); data=Util.objectToByteBuffer(inst); return data.length; } catch(Exception ex) { return -1; } } public static long sizeOf(Object inst) { byte[] data; try { data=Util.objectToByteBuffer(inst); return data.length; } catch(Exception ex) { return -1; } } public static int sizeOf(Streamable inst) { byte[] data; ByteArrayOutputStream output; DataOutputStream out; try { output=new ByteArrayOutputStream(); out=new DataOutputStream(output); inst.writeTo(out); out.flush(); data=output.toByteArray(); return data.length; } catch(Exception ex) { return -1; } } /** * Tries to load the class from the current thread's context class loader. If * not successful, tries to load the class from the current instance. * @param classname Desired class. * @param clazz Class object used to obtain a class loader * if no context class loader is available. * @return Class, or null on failure. */ public static Class loadClass(String classname, Class clazz) throws ClassNotFoundException { ClassLoader loader; try { loader=Thread.currentThread().getContextClassLoader(); if(loader != null) { return loader.loadClass(classname); } } catch(Throwable t) { } if(clazz != null) { try { loader=clazz.getClassLoader(); if(loader != null) { return loader.loadClass(classname); } } catch(Throwable t) { } } try { loader=ClassLoader.getSystemClassLoader(); if(loader != null) { return loader.loadClass(classname); } } catch(Throwable t) { } throw new ClassNotFoundException(classname); } public static InputStream getResourceAsStream(String name, Class clazz) { ClassLoader loader; InputStream retval=null; try { loader=Thread.currentThread().getContextClassLoader(); if(loader != null) { retval=loader.getResourceAsStream(name); if(retval != null) return retval; } } catch(Throwable t) { } if(clazz != null) { try { loader=clazz.getClassLoader(); if(loader != null) { retval=loader.getResourceAsStream(name); if(retval != null) return retval; } } catch(Throwable t) { } } try { loader=ClassLoader.getSystemClassLoader(); if(loader != null) { return loader.getResourceAsStream(name); } } catch(Throwable t) { } return retval; } /** Checks whether 2 Addresses are on the same host */ public static boolean sameHost(Address one, Address two) { InetAddress a, b; String host_a, host_b; if(one == null || two == null) return false; if(!(one instanceof IpAddress) || !(two instanceof IpAddress)) { return false; } a=((IpAddress)one).getIpAddress(); b=((IpAddress)two).getIpAddress(); if(a == null || b == null) return false; host_a=a.getHostAddress(); host_b=b.getHostAddress(); // System.out.println("host_a=" + host_a + ", host_b=" + host_b); return host_a.equals(host_b); } public static boolean fileExists(String fname) { return (new File(fname)).exists(); } /** * Parses comma-delimited longs; e.g., 2000,4000,8000. * Returns array of long, or null. */ public static long[] parseCommaDelimitedLongs(String s) { StringTokenizer tok; Vector v=new Vector(); Long l; long[] retval=null; if(s == null) return null; tok=new StringTokenizer(s, ","); while(tok.hasMoreTokens()) { l=new Long(tok.nextToken()); v.addElement(l); } if(v.isEmpty()) return null; retval=new long[v.size()]; for(int i=0; i < v.size(); i++) retval[i]=((Long)v.elementAt(i)).longValue(); return retval; } /** e.g. "bela,jeannette,michelle" --> List{"bela", "jeannette", "michelle"} */ public static List<String> parseCommaDelimitedStrings(String l) { return parseStringList(l, ","); } public static List<String> parseStringList(String l, String separator) { List<String> tmp=new LinkedList<String>(); StringTokenizer tok=new StringTokenizer(l, separator); String t; while(tok.hasMoreTokens()) { t=tok.nextToken(); tmp.add(t.trim()); } return tmp; } public static int parseInt(Properties props,String property,int defaultValue) { int result = defaultValue; String str=props.getProperty(property); if(str != null) { result=Integer.parseInt(str); props.remove(property); } return result; } public static long parseLong(Properties props,String property,long defaultValue) { long result = defaultValue; String str=props.getProperty(property); if(str != null) { result=Integer.parseInt(str); props.remove(property); } return result; } public static boolean parseBoolean(Properties props,String property,boolean defaultValue) { boolean result = defaultValue; String str=props.getProperty(property); if(str != null) { result=str.equalsIgnoreCase("true"); props.remove(property); } return result; } public static InetAddress parseBindAddress(Properties props, String property) throws UnknownHostException { InetAddress bind_addr=null; boolean ignore_systemprops=Util.isBindAddressPropertyIgnored(); String str=Util.getProperty(new String[]{Global.BIND_ADDR, Global.BIND_ADDR_OLD}, props, "bind_addr", ignore_systemprops, null); if(str != null) { bind_addr=InetAddress.getByName(str); props.remove(property); } return bind_addr; } /** * * @param s * @return List<NetworkInterface> */ public static List<NetworkInterface> parseInterfaceList(String s) throws Exception { List<NetworkInterface> interfaces=new ArrayList<NetworkInterface>(10); if(s == null) return null; StringTokenizer tok=new StringTokenizer(s, ","); String interface_name; NetworkInterface intf; while(tok.hasMoreTokens()) { interface_name=tok.nextToken(); // try by name first (e.g. (eth0") intf=NetworkInterface.getByName(interface_name); // next try by IP address or symbolic name if(intf == null) intf=NetworkInterface.getByInetAddress(InetAddress.getByName(interface_name)); if(intf == null) throw new Exception("interface " + interface_name + " not found"); if(!interfaces.contains(intf)) { interfaces.add(intf); } } return interfaces; } public static String print(List<NetworkInterface> interfaces) { StringBuilder sb=new StringBuilder(); boolean first=true; for(NetworkInterface intf: interfaces) { if(first) { first=false; } else { sb.append(", "); } sb.append(intf.getName()); } return sb.toString(); } public static String shortName(String hostname) { int index; StringBuilder sb=new StringBuilder(); if(hostname == null) return null; index=hostname.indexOf('.'); if(index > 0 && !Character.isDigit(hostname.charAt(0))) sb.append(hostname.substring(0, index)); else sb.append(hostname); return sb.toString(); } public static String shortName(InetAddress hostname) { if(hostname == null) return null; StringBuilder sb=new StringBuilder(); if(resolve_dns) sb.append(hostname.getHostName()); else sb.append(hostname.getHostAddress()); return sb.toString(); } /** Finds first available port starting at start_port and returns server socket */ public static ServerSocket createServerSocket(int start_port) { ServerSocket ret=null; while(true) { try { ret=new ServerSocket(start_port); } catch(BindException bind_ex) { start_port++; continue; } catch(IOException io_ex) { } break; } return ret; } public static ServerSocket createServerSocket(InetAddress bind_addr, int start_port) { ServerSocket ret=null; while(true) { try { ret=new ServerSocket(start_port, 50, bind_addr); } catch(BindException bind_ex) { start_port++; continue; } catch(IOException io_ex) { } break; } return ret; } /** * Creates a DatagramSocket bound to addr. If addr is null, socket won't be bound. If address is already in use, * start_port will be incremented until a socket can be created. * @param addr The InetAddress to which the socket should be bound. If null, the socket will not be bound. * @param port The port which the socket should use. If 0, a random port will be used. If > 0, but port is already * in use, it will be incremented until an unused port is found, or until MAX_PORT is reached. */ public static DatagramSocket createDatagramSocket(InetAddress addr, int port) throws Exception { DatagramSocket sock=null; if(addr == null) { if(port == 0) { return new DatagramSocket(); } else { while(port < MAX_PORT) { try { return new DatagramSocket(port); } catch(BindException bind_ex) { // port already used port++; } } } } else { if(port == 0) port=1024; while(port < MAX_PORT) { try { return new DatagramSocket(port, addr); } catch(BindException bind_ex) { // port already used port++; } } } return sock; // will never be reached, but the stupid compiler didn't figure it out... } public static MulticastSocket createMulticastSocket(int port, Log log) throws IOException { return createMulticastSocket(null, port, null); } public static MulticastSocket createMulticastSocket(InetAddress mcast_addr, int port, Log log) throws IOException { if(mcast_addr != null && !mcast_addr.isMulticastAddress()) { if(log != null && log.isWarnEnabled()) log.warn("mcast_addr (" + mcast_addr + ") is not a multicast address, will be ignored"); return new MulticastSocket(port); } SocketAddress saddr=new InetSocketAddress(mcast_addr, port); MulticastSocket retval=null; try { retval=new MulticastSocket(saddr); } catch(IOException ex) { if(log != null && log.isWarnEnabled()) { StringBuilder sb=new StringBuilder(); sb.append("failed binding MulticastSocket to " + mcast_addr).append(", mcast_addr is an "); sb.append(mcast_addr instanceof Inet4Address? "IPv4 " : "IPv6 ").append("address, but the defined " + "stack is [IPv4=" + Util.isIPv4Stack() + ", IPv6=" + Util.isIPv6Stack()); sb.append("]. \nWill ignore mcast_addr, but this may lead to cross talking " + "(see http://wiki.jboss.org/wiki/Wiki.jsp?page=PromiscuousTraffic for details). "); sb.append("\nException was: " + ex); log.warn(sb); } } if(retval == null) retval=new MulticastSocket(port); return retval; } /** * Returns the address of the interface to use defined by bind_addr and bind_interface * @param props * @return * @throws UnknownHostException * @throws SocketException */ public static InetAddress getBindAddress(Properties props) throws UnknownHostException, SocketException { boolean ignore_systemprops=Util.isBindAddressPropertyIgnored(); String bind_addr=Util.getProperty(new String[]{Global.BIND_ADDR, Global.BIND_ADDR_OLD}, props, "bind_addr", ignore_systemprops, null); String bind_interface=Util.getProperty(new String[]{Global.BIND_INTERFACE, null}, props, "bind_interface", ignore_systemprops, null); InetAddress retval=null, bind_addr_host=null; if(bind_addr != null) { bind_addr_host=InetAddress.getByName(bind_addr); } if(bind_interface != null) { NetworkInterface intf=NetworkInterface.getByName(bind_interface); if(intf != null) { for(Enumeration<InetAddress> addresses=intf.getInetAddresses(); addresses.hasMoreElements();) { InetAddress addr=addresses.nextElement(); if(bind_addr == null) { retval=addr; break; } else { if(bind_addr_host != null) { if(bind_addr_host.equals(addr)) { retval=addr; break; } } else if(addr.getHostAddress().trim().equalsIgnoreCase(bind_addr)) { retval=addr; break; } } } } else { throw new UnknownHostException("network interface " + bind_interface + " not found"); } } if(retval == null) { retval=bind_addr != null? InetAddress.getByName(bind_addr) : InetAddress.getLocalHost(); } props.remove("bind_addr"); props.remove("bind_interface"); return retval; } public static boolean checkForLinux() { String os=System.getProperty("os.name"); return os != null && os.toLowerCase().startsWith("linux"); } public static boolean checkForSolaris() { String os=System.getProperty("os.name"); return os != null && os.toLowerCase().startsWith("sun"); } public static boolean checkForWindows() { String os=System.getProperty("os.name"); return os != null && os.toLowerCase().startsWith("win"); } public static void prompt(String s) { System.out.println(s); System.out.flush(); try { while(System.in.available() > 0) System.in.read(); System.in.read(); } catch(IOException e) { e.printStackTrace(); } } public static int getJavaVersion() { String version=System.getProperty("java.version"); int retval=0; if(version != null) { if(version.startsWith("1.2")) return 12; if(version.startsWith("1.3")) return 13; if(version.startsWith("1.4")) return 14; if(version.startsWith("1.5")) return 15; if(version.startsWith("5")) return 15; if(version.startsWith("1.6")) return 16; if(version.startsWith("6")) return 16; } return retval; } public static <T> Vector<T> unmodifiableVector(Vector<? extends T> v) { if(v == null) return null; return new UnmodifiableVector(v); } public static String memStats(boolean gc) { StringBuilder sb=new StringBuilder(); Runtime rt=Runtime.getRuntime(); if(gc) rt.gc(); long free_mem, total_mem, used_mem; free_mem=rt.freeMemory(); total_mem=rt.totalMemory(); used_mem=total_mem - free_mem; sb.append("Free mem: ").append(free_mem).append("\nUsed mem: ").append(used_mem); sb.append("\nTotal mem: ").append(total_mem); return sb.toString(); } // public static InetAddress getFirstNonLoopbackAddress() throws SocketException { // Enumeration en=NetworkInterface.getNetworkInterfaces(); // while(en.hasMoreElements()) { // NetworkInterface i=(NetworkInterface)en.nextElement(); // for(Enumeration en2=i.getInetAddresses(); en2.hasMoreElements();) { // InetAddress addr=(InetAddress)en2.nextElement(); // if(!addr.isLoopbackAddress()) // return addr; // return null; public static InetAddress getFirstNonLoopbackAddress() throws SocketException { Enumeration en=NetworkInterface.getNetworkInterfaces(); boolean preferIpv4=Boolean.getBoolean(Global.IPv4); boolean preferIPv6=Boolean.getBoolean(Global.IPv6); while(en.hasMoreElements()) { NetworkInterface i=(NetworkInterface)en.nextElement(); for(Enumeration en2=i.getInetAddresses(); en2.hasMoreElements();) { InetAddress addr=(InetAddress)en2.nextElement(); if(!addr.isLoopbackAddress()) { if(addr instanceof Inet4Address) { if(preferIPv6) continue; return addr; } if(addr instanceof Inet6Address) { if(preferIpv4) continue; return addr; } } } } return null; } public static boolean isIPv4Stack() { return getIpStack()== 4; } public static boolean isIPv6Stack() { return getIpStack() == 6; } public static short getIpStack() { short retval=4; if(Boolean.getBoolean(Global.IPv4)) { retval=4; } if(Boolean.getBoolean(Global.IPv6)) { retval=6; } return retval; } public static InetAddress getFirstNonLoopbackIPv6Address() throws SocketException { Enumeration en=NetworkInterface.getNetworkInterfaces(); while(en.hasMoreElements()) { NetworkInterface i=(NetworkInterface)en.nextElement(); for(Enumeration en2=i.getInetAddresses(); en2.hasMoreElements();) { InetAddress addr=(InetAddress)en2.nextElement(); if(!addr.isLoopbackAddress()) { if(addr instanceof Inet4Address) { continue; } if(addr instanceof Inet6Address) { return addr; } } } } return null; } public static List<NetworkInterface> getAllAvailableInterfaces() throws SocketException { List<NetworkInterface> retval=new ArrayList<NetworkInterface>(10); NetworkInterface intf; for(Enumeration en=NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { intf=(NetworkInterface)en.nextElement(); retval.add(intf); } return retval; } /** * Returns a value associated wither with one or more system properties, or found in the props map * @param system_props * @param props List of properties read from the configuration file * @param prop_name The name of the property, will be removed from props if found * @param ignore_sysprops If true, system properties are not used and the values will only be retrieved from * props (not system_props) * @param default_value Used to return a default value if the properties or system properties didn't have the value * @return The value, or null if not found */ public static String getProperty(String[] system_props, Properties props, String prop_name, boolean ignore_sysprops, String default_value) { String retval=null; if(props != null && prop_name != null) { retval=props.getProperty(prop_name); props.remove(prop_name); } if(!ignore_sysprops) { String tmp, prop; if(system_props != null) { for(int i=0; i < system_props.length; i++) { prop=system_props[i]; if(prop != null) { try { tmp=System.getProperty(prop); if(tmp != null) return tmp; // system properties override config file definitions } catch(SecurityException ex) {} } } } } if(retval == null) return default_value; return retval; } public static boolean isBindAddressPropertyIgnored() { try { String tmp=System.getProperty(Global.IGNORE_BIND_ADDRESS_PROPERTY); if(tmp == null) { tmp=System.getProperty(Global.IGNORE_BIND_ADDRESS_PROPERTY_OLD); if(tmp == null) return false; } tmp=tmp.trim().toLowerCase(); return !(tmp.equals("false") || tmp.equals("no") || tmp.equals("off")) && (tmp.equals("true") || tmp.equals("yes") || tmp.equals("on")); } catch(SecurityException ex) { return false; } } public static MBeanServer getMBeanServer() { ArrayList servers=MBeanServerFactory.findMBeanServer(null); if(servers == null || servers.isEmpty()) return null; // return 'jboss' server if available for(int i=0; i < servers.size(); i++) { MBeanServer srv=(MBeanServer)servers.get(i); if("jboss".equalsIgnoreCase(srv.getDefaultDomain())) return srv; } // return first available server return (MBeanServer)servers.get(0); } public static String getProperty(Protocol prot, String prop_name) { if(prot == null) return null; String name=prot.getProperties().getProperty(prop_name); return name == null? name : name.trim(); } /* public static void main(String[] args) { DatagramSocket sock; InetAddress addr=null; int port=0; for(int i=0; i < args.length; i++) { if(args[i].equals("-help")) { System.out.println("Util [-help] [-addr] [-port]"); return; } if(args[i].equals("-addr")) { try { addr=InetAddress.getByName(args[++i]); continue; } catch(Exception ex) { log.error(ex); return; } } if(args[i].equals("-port")) { port=Integer.parseInt(args[++i]); continue; } System.out.println("Util [-help] [-addr] [-port]"); return; } try { sock=createDatagramSocket(addr, port); System.out.println("sock: local address is " + sock.getLocalAddress() + ":" + sock.getLocalPort() + ", remote address is " + sock.getInetAddress() + ":" + sock.getPort()); System.in.read(); } catch(Exception ex) { log.error(ex); } } */ public static void main(String args[]) throws Exception { System.out.println("IPv4: " + isIPv4Stack()); System.out.println("IPv6: " + isIPv6Stack()); } public static String generateList(Collection c, String separator) { if(c == null) return null; StringBuilder sb=new StringBuilder(); boolean first=true; for(Iterator it=c.iterator(); it.hasNext();) { if(first) { first=false; } else { sb.append(separator); } sb.append(it.next()); } return sb.toString(); } /** * Replaces variables of ${var:default} with System.getProperty(var, default). If no variables are found, returns * the same string, otherwise a copy of the string with variables substituted * @param val * @return A string with vars replaced, or the same string if no vars found */ public static String substituteVariable(String val) { if(val == null) return val; String retval=val, prev; while(retval.contains("${")) { // handle multiple variables in val prev=retval; retval=_substituteVar(retval); if(retval.equals(prev)) break; } return retval; } private static String _substituteVar(String val) { int start_index, end_index; start_index=val.indexOf("${"); if(start_index == -1) return val; end_index=val.indexOf("}", start_index+2); if(end_index == -1) throw new IllegalArgumentException("missing \"}\" in " + val); String tmp=getProperty(val.substring(start_index +2, end_index)); if(tmp == null) return val; StringBuilder sb=new StringBuilder(); sb.append(val.substring(0, start_index)); sb.append(tmp); sb.append(val.substring(end_index+1)); return sb.toString(); } private static String getProperty(String s) { String var, default_val, retval=null; int index=s.indexOf(":"); if(index >= 0) { var=s.substring(0, index); default_val=s.substring(index+1); retval=System.getProperty(var, default_val); } else { var=s; retval=System.getProperty(var); } return retval; } /** * Used to convert a byte array in to a java.lang.String object * @param bytes the bytes to be converted * @return the String representation */ private static String getString(byte[] bytes) { StringBuilder sb=new StringBuilder(); for (int i = 0; i < bytes.length; i++) { byte b = bytes[i]; sb.append(0x00FF & b); if (i + 1 < bytes.length) { sb.append("-"); } } return sb.toString(); } /** * Converts a java.lang.String in to a MD5 hashed String * @param source the source String * @return the MD5 hashed version of the string */ public static String md5(String source) { try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] bytes = md.digest(source.getBytes()); return getString(bytes); } catch (Exception e) { return null; } } /** * Converts a java.lang.String in to a SHA hashed String * @param source the source String * @return the MD5 hashed version of the string */ public static String sha(String source) { try { MessageDigest md = MessageDigest.getInstance("SHA"); byte[] bytes = md.digest(source.getBytes()); return getString(bytes); } catch (Exception e) { e.printStackTrace(); return null; } } }