repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
alessandropellegrini/z64sim
simulator/src/org/z64sim/program/Program.java
// Path: simulator/src/org/z64sim/memory/Memory.java // public class Memory { // // private static MemoryTopComponent window = null; // //private static Program program = null; // private static Program program = new Program(); // aggiunto per evitare nullPointerException // // // This class cannot be instantiated // private Memory() { // } // // public static Program getProgram() { // return program; // } // // public static void setProgram(Program program) { // Memory.program = program; // } // // public static void setWindow(MemoryTopComponent w) { // Memory.window = w; // } // // public static MemoryTopComponent getWindow() { // return Memory.window; // } // // public static void redrawMemory() { // if (Memory.window != null) { // Memory.window.memoryTable.setModel(new MemoryTableModel()); // int _startRow = (int) (Memory.program._start / 8); // // // Select the row corresponding to the entry point // Memory.window.memoryTable.setRowSelectionInterval(_startRow, _startRow); // // // Scroll to that row // Memory.window.memoryTable.scrollRectToVisible(new Rectangle(Memory.window.memoryTable.getCellRect(_startRow, 0, true))); // // // Show the panel // Memory.window.requestVisible(); // } // // } // // } // // Path: simulator/src/org/z64sim/program/instructions/OperandImmediate.java // public class OperandImmediate extends Operand { // // private long value; // // public OperandImmediate(long value) { // super(32); // // Basically an immediate is 32-bit long, except when it cannot // // be represented using 32 bits (!!!) // if(value > Integer.MAX_VALUE) { // this.setSize(64); // } // // this.value = value; // } // // public long getValue() { // return value; // } // // @Override // public String toString() { // return "$" + this.value; // } // // // This call actually sums the value of the label. This is because we could // // write an instruction such as "movq $constant+10". The +10 is stored in the // // 'value' field of the object, and we have then to sum $constant. // public void relocate(long value) { // this.value += value; // } // } // // Path: simulator/src/org/z64sim/program/instructions/OperandMemory.java // public class OperandMemory extends Operand { // // private int base = -1; // private int scale = -1; // private int index = -1; // private int displacement = -1; // // // In z64 assembly you can say both (%ax) or (%rax) for example, so we must // // account fot the size of the base register as well // // On the other hand, the index is always a 64-bit register // private int base_size = -1; // // public OperandMemory(int base, int base_size, int index, int scale, int displacement, int size) { // super(size); // // this.base = base; // this.base_size = base_size; // this.index = index; // this.scale = scale; // this.displacement = displacement; // } // // public int getDisplacement() { // return displacement; // } // // public int getScale() { // return scale; // } // // public int getIndex() { // return index; // } // // public long getBase() { // return base; // } // // public int getBaseSize() { // return base_size; // } // // public void setDisplacement(int displacement) { // this.displacement = displacement; // } // // public String toString() { // String representation = ""; // // if(this.displacement != -1) { // representation = representation.concat(String.format("$%x", this.displacement)); // } // // if(this.base != -1 || this.index != -1) { // representation = representation.concat("("); // } // // if(this.base != -1) { // representation = representation.concat(Register.getRegisterName(this.base, this.base_size)); // } // // if(this.index != -1) { // representation = representation.concat(", " + Register.getRegisterName(this.index, 64)); // representation = representation.concat(", " + this.scale); // } // // if(this.base != -1 || this.index != -1) { // representation = representation.concat(")"); // } // // return representation; // } // // public void relocate(long value) { // this.displacement += value; // } // }
import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.LinkedHashMap; import java.util.Map; import org.z64sim.memory.Memory; import org.z64sim.program.instructions.OperandImmediate; import org.z64sim.program.instructions.OperandMemory;
this.data.add(val[i]); } return addr; } /** * A relocation entry. Points to the initial address of the instruction. It * is then the role of the relocate() method to account for differences in * the various instruction formats. */ private class RelocationEntry { private final long applyTo; private final String label; public RelocationEntry(long applyTo, String label) { this.applyTo = applyTo; this.label = label; } private void relocateImmediate(OperandImmediate op, Instruction insn) throws ProgramException { // Get target address of the relocation long target = findLabelAddress(this.label); if (target == -1) { throw new ProgramException("Label " + this.label + " was not defined in the program"); } op.relocate(target); }
// Path: simulator/src/org/z64sim/memory/Memory.java // public class Memory { // // private static MemoryTopComponent window = null; // //private static Program program = null; // private static Program program = new Program(); // aggiunto per evitare nullPointerException // // // This class cannot be instantiated // private Memory() { // } // // public static Program getProgram() { // return program; // } // // public static void setProgram(Program program) { // Memory.program = program; // } // // public static void setWindow(MemoryTopComponent w) { // Memory.window = w; // } // // public static MemoryTopComponent getWindow() { // return Memory.window; // } // // public static void redrawMemory() { // if (Memory.window != null) { // Memory.window.memoryTable.setModel(new MemoryTableModel()); // int _startRow = (int) (Memory.program._start / 8); // // // Select the row corresponding to the entry point // Memory.window.memoryTable.setRowSelectionInterval(_startRow, _startRow); // // // Scroll to that row // Memory.window.memoryTable.scrollRectToVisible(new Rectangle(Memory.window.memoryTable.getCellRect(_startRow, 0, true))); // // // Show the panel // Memory.window.requestVisible(); // } // // } // // } // // Path: simulator/src/org/z64sim/program/instructions/OperandImmediate.java // public class OperandImmediate extends Operand { // // private long value; // // public OperandImmediate(long value) { // super(32); // // Basically an immediate is 32-bit long, except when it cannot // // be represented using 32 bits (!!!) // if(value > Integer.MAX_VALUE) { // this.setSize(64); // } // // this.value = value; // } // // public long getValue() { // return value; // } // // @Override // public String toString() { // return "$" + this.value; // } // // // This call actually sums the value of the label. This is because we could // // write an instruction such as "movq $constant+10". The +10 is stored in the // // 'value' field of the object, and we have then to sum $constant. // public void relocate(long value) { // this.value += value; // } // } // // Path: simulator/src/org/z64sim/program/instructions/OperandMemory.java // public class OperandMemory extends Operand { // // private int base = -1; // private int scale = -1; // private int index = -1; // private int displacement = -1; // // // In z64 assembly you can say both (%ax) or (%rax) for example, so we must // // account fot the size of the base register as well // // On the other hand, the index is always a 64-bit register // private int base_size = -1; // // public OperandMemory(int base, int base_size, int index, int scale, int displacement, int size) { // super(size); // // this.base = base; // this.base_size = base_size; // this.index = index; // this.scale = scale; // this.displacement = displacement; // } // // public int getDisplacement() { // return displacement; // } // // public int getScale() { // return scale; // } // // public int getIndex() { // return index; // } // // public long getBase() { // return base; // } // // public int getBaseSize() { // return base_size; // } // // public void setDisplacement(int displacement) { // this.displacement = displacement; // } // // public String toString() { // String representation = ""; // // if(this.displacement != -1) { // representation = representation.concat(String.format("$%x", this.displacement)); // } // // if(this.base != -1 || this.index != -1) { // representation = representation.concat("("); // } // // if(this.base != -1) { // representation = representation.concat(Register.getRegisterName(this.base, this.base_size)); // } // // if(this.index != -1) { // representation = representation.concat(", " + Register.getRegisterName(this.index, 64)); // representation = representation.concat(", " + this.scale); // } // // if(this.base != -1 || this.index != -1) { // representation = representation.concat(")"); // } // // return representation; // } // // public void relocate(long value) { // this.displacement += value; // } // } // Path: simulator/src/org/z64sim/program/Program.java import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.LinkedHashMap; import java.util.Map; import org.z64sim.memory.Memory; import org.z64sim.program.instructions.OperandImmediate; import org.z64sim.program.instructions.OperandMemory; this.data.add(val[i]); } return addr; } /** * A relocation entry. Points to the initial address of the instruction. It * is then the role of the relocate() method to account for differences in * the various instruction formats. */ private class RelocationEntry { private final long applyTo; private final String label; public RelocationEntry(long applyTo, String label) { this.applyTo = applyTo; this.label = label; } private void relocateImmediate(OperandImmediate op, Instruction insn) throws ProgramException { // Get target address of the relocation long target = findLabelAddress(this.label); if (target == -1) { throw new ProgramException("Label " + this.label + " was not defined in the program"); } op.relocate(target); }
private void relocateMemory(OperandMemory op, Instruction insn) throws ProgramException {
alessandropellegrini/z64sim
simulator/src/org/z64sim/memory/window/MemoryTableModel.java
// Path: simulator/src/org/z64sim/memory/Memory.java // public class Memory { // // private static MemoryTopComponent window = null; // //private static Program program = null; // private static Program program = new Program(); // aggiunto per evitare nullPointerException // // // This class cannot be instantiated // private Memory() { // } // // public static Program getProgram() { // return program; // } // // public static void setProgram(Program program) { // Memory.program = program; // } // // public static void setWindow(MemoryTopComponent w) { // Memory.window = w; // } // // public static MemoryTopComponent getWindow() { // return Memory.window; // } // // public static void redrawMemory() { // if (Memory.window != null) { // Memory.window.memoryTable.setModel(new MemoryTableModel()); // int _startRow = (int) (Memory.program._start / 8); // // // Select the row corresponding to the entry point // Memory.window.memoryTable.setRowSelectionInterval(_startRow, _startRow); // // // Scroll to that row // Memory.window.memoryTable.scrollRectToVisible(new Rectangle(Memory.window.memoryTable.getCellRect(_startRow, 0, true))); // // // Show the panel // Memory.window.requestVisible(); // } // // } // // } // // Path: simulator/src/org/z64sim/program/Instruction.java // public abstract class Instruction { // // protected final String mnemonic; // protected final byte clas; // protected byte type; // protected int size; // protected byte[] encoding; // // public Instruction(String mnemonic, int clas) { // this.mnemonic = mnemonic; // this.clas = (byte)clas; // } // // protected static boolean skip = false; // // // toString() must be explicitly re-implemented // public static String disassemble(int address) { // if(Instruction.skip) { // Instruction.skip = false; // return ""; // } // byte opcode = 0; // opcode = (byte)(Memory.getProgram().program[address] & 0b11110000); // // switch(opcode){ // case 0: // return InstructionClass0.disassemble(address); // case 1*16: // return InstructionClass1.disassemble(address); // case 2*16: // return InstructionClass2.disassemble(address); // case 3*16: // return InstructionClass3.disassemble(address); // case 4*16: // return InstructionClass4.disassemble(address); // case 5*16: // return InstructionClass5.disassemble(address); // case 6*16: // return InstructionClass6.disassemble(address); // case 7*16: // return InstructionClass7.disassemble(address); // default : // return JOptionPane.showInputDialog(opcode); // } // } // // public byte getClas() { // return this.clas; // } // // public void setSize(int size) { // this.size = size; // } // // public int getSize() { // return this.size; // } // // public byte[] getEncoding() { // return encoding; // } // // public void setEncoding(byte[] encoding) { // this.encoding = encoding; // } // // public abstract void run(); // // public static byte[] longToBytes(long l) { // byte[] result = new byte[8]; // for (int i = 7; i >= 0; i--) { // result[i] = (byte)(l & 0xFF); // l >>= 8; // } // return result; // } // // public static long bytesToLong(byte[] b) { // ByteBuffer bb = ByteBuffer.allocate(b.length); // bb.put(b); // return bb.getLong(); // } // // public static byte byteToBits(byte b, int start, int end){ // byte mask = 0; // if(start < end || start > 7 || end < 0 ) throw new RuntimeException("No valid start || end"); // // for (int i = 7-start; i <= 7-end; i++) { // mask += 1 << 7-i; // } // byte ret = (byte) (mask & b); // for (int i = 0; i < end; i++) { // ret /= 2; // } // if (ret < 0) { // ret += Math.pow(2, start-end+1); // } // return ret; // } // // // // }
import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableModel; import org.z64sim.memory.Memory; import org.z64sim.program.Instruction; import org.z64sim.program.instructions.*;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.z64sim.memory.window; /** * * @author Alessandro Pellegrini <pellegrini@dis.uniroma1.it> */ public class MemoryTableModel extends AbstractTableModel implements TableModelListener { // These are keys in the bundle file private final String[] columnNames = {"MemoryTableModel.address", "MemoryTableModel.instruction", "MemoryTableModel.hex", "MemoryTableModel.dec"}; @Override public int getRowCount() {
// Path: simulator/src/org/z64sim/memory/Memory.java // public class Memory { // // private static MemoryTopComponent window = null; // //private static Program program = null; // private static Program program = new Program(); // aggiunto per evitare nullPointerException // // // This class cannot be instantiated // private Memory() { // } // // public static Program getProgram() { // return program; // } // // public static void setProgram(Program program) { // Memory.program = program; // } // // public static void setWindow(MemoryTopComponent w) { // Memory.window = w; // } // // public static MemoryTopComponent getWindow() { // return Memory.window; // } // // public static void redrawMemory() { // if (Memory.window != null) { // Memory.window.memoryTable.setModel(new MemoryTableModel()); // int _startRow = (int) (Memory.program._start / 8); // // // Select the row corresponding to the entry point // Memory.window.memoryTable.setRowSelectionInterval(_startRow, _startRow); // // // Scroll to that row // Memory.window.memoryTable.scrollRectToVisible(new Rectangle(Memory.window.memoryTable.getCellRect(_startRow, 0, true))); // // // Show the panel // Memory.window.requestVisible(); // } // // } // // } // // Path: simulator/src/org/z64sim/program/Instruction.java // public abstract class Instruction { // // protected final String mnemonic; // protected final byte clas; // protected byte type; // protected int size; // protected byte[] encoding; // // public Instruction(String mnemonic, int clas) { // this.mnemonic = mnemonic; // this.clas = (byte)clas; // } // // protected static boolean skip = false; // // // toString() must be explicitly re-implemented // public static String disassemble(int address) { // if(Instruction.skip) { // Instruction.skip = false; // return ""; // } // byte opcode = 0; // opcode = (byte)(Memory.getProgram().program[address] & 0b11110000); // // switch(opcode){ // case 0: // return InstructionClass0.disassemble(address); // case 1*16: // return InstructionClass1.disassemble(address); // case 2*16: // return InstructionClass2.disassemble(address); // case 3*16: // return InstructionClass3.disassemble(address); // case 4*16: // return InstructionClass4.disassemble(address); // case 5*16: // return InstructionClass5.disassemble(address); // case 6*16: // return InstructionClass6.disassemble(address); // case 7*16: // return InstructionClass7.disassemble(address); // default : // return JOptionPane.showInputDialog(opcode); // } // } // // public byte getClas() { // return this.clas; // } // // public void setSize(int size) { // this.size = size; // } // // public int getSize() { // return this.size; // } // // public byte[] getEncoding() { // return encoding; // } // // public void setEncoding(byte[] encoding) { // this.encoding = encoding; // } // // public abstract void run(); // // public static byte[] longToBytes(long l) { // byte[] result = new byte[8]; // for (int i = 7; i >= 0; i--) { // result[i] = (byte)(l & 0xFF); // l >>= 8; // } // return result; // } // // public static long bytesToLong(byte[] b) { // ByteBuffer bb = ByteBuffer.allocate(b.length); // bb.put(b); // return bb.getLong(); // } // // public static byte byteToBits(byte b, int start, int end){ // byte mask = 0; // if(start < end || start > 7 || end < 0 ) throw new RuntimeException("No valid start || end"); // // for (int i = 7-start; i <= 7-end; i++) { // mask += 1 << 7-i; // } // byte ret = (byte) (mask & b); // for (int i = 0; i < end; i++) { // ret /= 2; // } // if (ret < 0) { // ret += Math.pow(2, start-end+1); // } // return ret; // } // // // // } // Path: simulator/src/org/z64sim/memory/window/MemoryTableModel.java import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableModel; import org.z64sim.memory.Memory; import org.z64sim.program.Instruction; import org.z64sim.program.instructions.*; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.z64sim.memory.window; /** * * @author Alessandro Pellegrini <pellegrini@dis.uniroma1.it> */ public class MemoryTableModel extends AbstractTableModel implements TableModelListener { // These are keys in the bundle file private final String[] columnNames = {"MemoryTableModel.address", "MemoryTableModel.instruction", "MemoryTableModel.hex", "MemoryTableModel.dec"}; @Override public int getRowCount() {
if(Memory.getProgram().program == null)
alessandropellegrini/z64sim
simulator/src/org/z64sim/memory/window/MemoryTableModel.java
// Path: simulator/src/org/z64sim/memory/Memory.java // public class Memory { // // private static MemoryTopComponent window = null; // //private static Program program = null; // private static Program program = new Program(); // aggiunto per evitare nullPointerException // // // This class cannot be instantiated // private Memory() { // } // // public static Program getProgram() { // return program; // } // // public static void setProgram(Program program) { // Memory.program = program; // } // // public static void setWindow(MemoryTopComponent w) { // Memory.window = w; // } // // public static MemoryTopComponent getWindow() { // return Memory.window; // } // // public static void redrawMemory() { // if (Memory.window != null) { // Memory.window.memoryTable.setModel(new MemoryTableModel()); // int _startRow = (int) (Memory.program._start / 8); // // // Select the row corresponding to the entry point // Memory.window.memoryTable.setRowSelectionInterval(_startRow, _startRow); // // // Scroll to that row // Memory.window.memoryTable.scrollRectToVisible(new Rectangle(Memory.window.memoryTable.getCellRect(_startRow, 0, true))); // // // Show the panel // Memory.window.requestVisible(); // } // // } // // } // // Path: simulator/src/org/z64sim/program/Instruction.java // public abstract class Instruction { // // protected final String mnemonic; // protected final byte clas; // protected byte type; // protected int size; // protected byte[] encoding; // // public Instruction(String mnemonic, int clas) { // this.mnemonic = mnemonic; // this.clas = (byte)clas; // } // // protected static boolean skip = false; // // // toString() must be explicitly re-implemented // public static String disassemble(int address) { // if(Instruction.skip) { // Instruction.skip = false; // return ""; // } // byte opcode = 0; // opcode = (byte)(Memory.getProgram().program[address] & 0b11110000); // // switch(opcode){ // case 0: // return InstructionClass0.disassemble(address); // case 1*16: // return InstructionClass1.disassemble(address); // case 2*16: // return InstructionClass2.disassemble(address); // case 3*16: // return InstructionClass3.disassemble(address); // case 4*16: // return InstructionClass4.disassemble(address); // case 5*16: // return InstructionClass5.disassemble(address); // case 6*16: // return InstructionClass6.disassemble(address); // case 7*16: // return InstructionClass7.disassemble(address); // default : // return JOptionPane.showInputDialog(opcode); // } // } // // public byte getClas() { // return this.clas; // } // // public void setSize(int size) { // this.size = size; // } // // public int getSize() { // return this.size; // } // // public byte[] getEncoding() { // return encoding; // } // // public void setEncoding(byte[] encoding) { // this.encoding = encoding; // } // // public abstract void run(); // // public static byte[] longToBytes(long l) { // byte[] result = new byte[8]; // for (int i = 7; i >= 0; i--) { // result[i] = (byte)(l & 0xFF); // l >>= 8; // } // return result; // } // // public static long bytesToLong(byte[] b) { // ByteBuffer bb = ByteBuffer.allocate(b.length); // bb.put(b); // return bb.getLong(); // } // // public static byte byteToBits(byte b, int start, int end){ // byte mask = 0; // if(start < end || start > 7 || end < 0 ) throw new RuntimeException("No valid start || end"); // // for (int i = 7-start; i <= 7-end; i++) { // mask += 1 << 7-i; // } // byte ret = (byte) (mask & b); // for (int i = 0; i < end; i++) { // ret /= 2; // } // if (ret < 0) { // ret += Math.pow(2, start-end+1); // } // return ret; // } // // // // }
import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableModel; import org.z64sim.memory.Memory; import org.z64sim.program.Instruction; import org.z64sim.program.instructions.*;
@Override public boolean isCellEditable(int row, int col) { if(row < Memory.getProgram()._dataStart) return false; // Only the address and the mnemonic cannot be edited return col > 1; } @Override public Object getValueAt(int rowIndex, int columnIndex) { Object ret = null; int address = rowIndex * 8; // address is managed at a quadword basis byte value[] = new byte[8]; for(int i = 0; i < 8; i++) { value[i] = Memory.getProgram().program[address + i]; } ByteBuffer wrapped = ByteBuffer.wrap(value); //wrapped.order(ByteOrder.LITTLE_ENDIAN); switch(columnIndex) { case 0: // Address ret = String.format("%016x", address); break; case 1: // Mnemonic if(address < Memory.getProgram()._start || address >= Memory.getProgram()._dataStart) ret = ""; else
// Path: simulator/src/org/z64sim/memory/Memory.java // public class Memory { // // private static MemoryTopComponent window = null; // //private static Program program = null; // private static Program program = new Program(); // aggiunto per evitare nullPointerException // // // This class cannot be instantiated // private Memory() { // } // // public static Program getProgram() { // return program; // } // // public static void setProgram(Program program) { // Memory.program = program; // } // // public static void setWindow(MemoryTopComponent w) { // Memory.window = w; // } // // public static MemoryTopComponent getWindow() { // return Memory.window; // } // // public static void redrawMemory() { // if (Memory.window != null) { // Memory.window.memoryTable.setModel(new MemoryTableModel()); // int _startRow = (int) (Memory.program._start / 8); // // // Select the row corresponding to the entry point // Memory.window.memoryTable.setRowSelectionInterval(_startRow, _startRow); // // // Scroll to that row // Memory.window.memoryTable.scrollRectToVisible(new Rectangle(Memory.window.memoryTable.getCellRect(_startRow, 0, true))); // // // Show the panel // Memory.window.requestVisible(); // } // // } // // } // // Path: simulator/src/org/z64sim/program/Instruction.java // public abstract class Instruction { // // protected final String mnemonic; // protected final byte clas; // protected byte type; // protected int size; // protected byte[] encoding; // // public Instruction(String mnemonic, int clas) { // this.mnemonic = mnemonic; // this.clas = (byte)clas; // } // // protected static boolean skip = false; // // // toString() must be explicitly re-implemented // public static String disassemble(int address) { // if(Instruction.skip) { // Instruction.skip = false; // return ""; // } // byte opcode = 0; // opcode = (byte)(Memory.getProgram().program[address] & 0b11110000); // // switch(opcode){ // case 0: // return InstructionClass0.disassemble(address); // case 1*16: // return InstructionClass1.disassemble(address); // case 2*16: // return InstructionClass2.disassemble(address); // case 3*16: // return InstructionClass3.disassemble(address); // case 4*16: // return InstructionClass4.disassemble(address); // case 5*16: // return InstructionClass5.disassemble(address); // case 6*16: // return InstructionClass6.disassemble(address); // case 7*16: // return InstructionClass7.disassemble(address); // default : // return JOptionPane.showInputDialog(opcode); // } // } // // public byte getClas() { // return this.clas; // } // // public void setSize(int size) { // this.size = size; // } // // public int getSize() { // return this.size; // } // // public byte[] getEncoding() { // return encoding; // } // // public void setEncoding(byte[] encoding) { // this.encoding = encoding; // } // // public abstract void run(); // // public static byte[] longToBytes(long l) { // byte[] result = new byte[8]; // for (int i = 7; i >= 0; i--) { // result[i] = (byte)(l & 0xFF); // l >>= 8; // } // return result; // } // // public static long bytesToLong(byte[] b) { // ByteBuffer bb = ByteBuffer.allocate(b.length); // bb.put(b); // return bb.getLong(); // } // // public static byte byteToBits(byte b, int start, int end){ // byte mask = 0; // if(start < end || start > 7 || end < 0 ) throw new RuntimeException("No valid start || end"); // // for (int i = 7-start; i <= 7-end; i++) { // mask += 1 << 7-i; // } // byte ret = (byte) (mask & b); // for (int i = 0; i < end; i++) { // ret /= 2; // } // if (ret < 0) { // ret += Math.pow(2, start-end+1); // } // return ret; // } // // // // } // Path: simulator/src/org/z64sim/memory/window/MemoryTableModel.java import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableModel; import org.z64sim.memory.Memory; import org.z64sim.program.Instruction; import org.z64sim.program.instructions.*; @Override public boolean isCellEditable(int row, int col) { if(row < Memory.getProgram()._dataStart) return false; // Only the address and the mnemonic cannot be edited return col > 1; } @Override public Object getValueAt(int rowIndex, int columnIndex) { Object ret = null; int address = rowIndex * 8; // address is managed at a quadword basis byte value[] = new byte[8]; for(int i = 0; i < 8; i++) { value[i] = Memory.getProgram().program[address + i]; } ByteBuffer wrapped = ByteBuffer.wrap(value); //wrapped.order(ByteOrder.LITTLE_ENDIAN); switch(columnIndex) { case 0: // Address ret = String.format("%016x", address); break; case 1: // Mnemonic if(address < Memory.getProgram()._start || address >= Memory.getProgram()._dataStart) ret = ""; else
ret = Instruction.disassemble(address);
alessandropellegrini/z64sim
simulator/src/org/z64sim/program/instructions/InstructionClass0.java
// Path: simulator/src/org/z64sim/memory/Memory.java // public class Memory { // // private static MemoryTopComponent window = null; // //private static Program program = null; // private static Program program = new Program(); // aggiunto per evitare nullPointerException // // // This class cannot be instantiated // private Memory() { // } // // public static Program getProgram() { // return program; // } // // public static void setProgram(Program program) { // Memory.program = program; // } // // public static void setWindow(MemoryTopComponent w) { // Memory.window = w; // } // // public static MemoryTopComponent getWindow() { // return Memory.window; // } // // public static void redrawMemory() { // if (Memory.window != null) { // Memory.window.memoryTable.setModel(new MemoryTableModel()); // int _startRow = (int) (Memory.program._start / 8); // // // Select the row corresponding to the entry point // Memory.window.memoryTable.setRowSelectionInterval(_startRow, _startRow); // // // Scroll to that row // Memory.window.memoryTable.scrollRectToVisible(new Rectangle(Memory.window.memoryTable.getCellRect(_startRow, 0, true))); // // // Show the panel // Memory.window.requestVisible(); // } // // } // // } // // Path: simulator/src/org/z64sim/program/Instruction.java // public abstract class Instruction { // // protected final String mnemonic; // protected final byte clas; // protected byte type; // protected int size; // protected byte[] encoding; // // public Instruction(String mnemonic, int clas) { // this.mnemonic = mnemonic; // this.clas = (byte)clas; // } // // protected static boolean skip = false; // // // toString() must be explicitly re-implemented // public static String disassemble(int address) { // if(Instruction.skip) { // Instruction.skip = false; // return ""; // } // byte opcode = 0; // opcode = (byte)(Memory.getProgram().program[address] & 0b11110000); // // switch(opcode){ // case 0: // return InstructionClass0.disassemble(address); // case 1*16: // return InstructionClass1.disassemble(address); // case 2*16: // return InstructionClass2.disassemble(address); // case 3*16: // return InstructionClass3.disassemble(address); // case 4*16: // return InstructionClass4.disassemble(address); // case 5*16: // return InstructionClass5.disassemble(address); // case 6*16: // return InstructionClass6.disassemble(address); // case 7*16: // return InstructionClass7.disassemble(address); // default : // return JOptionPane.showInputDialog(opcode); // } // } // // public byte getClas() { // return this.clas; // } // // public void setSize(int size) { // this.size = size; // } // // public int getSize() { // return this.size; // } // // public byte[] getEncoding() { // return encoding; // } // // public void setEncoding(byte[] encoding) { // this.encoding = encoding; // } // // public abstract void run(); // // public static byte[] longToBytes(long l) { // byte[] result = new byte[8]; // for (int i = 7; i >= 0; i--) { // result[i] = (byte)(l & 0xFF); // l >>= 8; // } // return result; // } // // public static long bytesToLong(byte[] b) { // ByteBuffer bb = ByteBuffer.allocate(b.length); // bb.put(b); // return bb.getLong(); // } // // public static byte byteToBits(byte b, int start, int end){ // byte mask = 0; // if(start < end || start > 7 || end < 0 ) throw new RuntimeException("No valid start || end"); // // for (int i = 7-start; i <= 7-end; i++) { // mask += 1 << 7-i; // } // byte ret = (byte) (mask & b); // for (int i = 0; i < end; i++) { // ret /= 2; // } // if (ret < 0) { // ret += Math.pow(2, start-end+1); // } // return ret; // } // // // // }
import org.z64sim.memory.Memory; import org.z64sim.program.Instruction; import javax.swing.JOptionPane;
byte enc[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; switch (mnemonic) { case "hlt": enc[0] = 0x01; this.type = 0x01; break; case "nop": enc[0] = 0x02; this.type = 0x02; break; case "int": enc[0] = 0x03; this.type = 0x03; default: throw new RuntimeException("Unknown Class 0 instruction: " + mnemonic); } this.setEncoding(enc); } @Override public void run() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } public static String disassemble(int address) { byte b[] = new byte[8]; for(int i = 0; i < 8; i++) {
// Path: simulator/src/org/z64sim/memory/Memory.java // public class Memory { // // private static MemoryTopComponent window = null; // //private static Program program = null; // private static Program program = new Program(); // aggiunto per evitare nullPointerException // // // This class cannot be instantiated // private Memory() { // } // // public static Program getProgram() { // return program; // } // // public static void setProgram(Program program) { // Memory.program = program; // } // // public static void setWindow(MemoryTopComponent w) { // Memory.window = w; // } // // public static MemoryTopComponent getWindow() { // return Memory.window; // } // // public static void redrawMemory() { // if (Memory.window != null) { // Memory.window.memoryTable.setModel(new MemoryTableModel()); // int _startRow = (int) (Memory.program._start / 8); // // // Select the row corresponding to the entry point // Memory.window.memoryTable.setRowSelectionInterval(_startRow, _startRow); // // // Scroll to that row // Memory.window.memoryTable.scrollRectToVisible(new Rectangle(Memory.window.memoryTable.getCellRect(_startRow, 0, true))); // // // Show the panel // Memory.window.requestVisible(); // } // // } // // } // // Path: simulator/src/org/z64sim/program/Instruction.java // public abstract class Instruction { // // protected final String mnemonic; // protected final byte clas; // protected byte type; // protected int size; // protected byte[] encoding; // // public Instruction(String mnemonic, int clas) { // this.mnemonic = mnemonic; // this.clas = (byte)clas; // } // // protected static boolean skip = false; // // // toString() must be explicitly re-implemented // public static String disassemble(int address) { // if(Instruction.skip) { // Instruction.skip = false; // return ""; // } // byte opcode = 0; // opcode = (byte)(Memory.getProgram().program[address] & 0b11110000); // // switch(opcode){ // case 0: // return InstructionClass0.disassemble(address); // case 1*16: // return InstructionClass1.disassemble(address); // case 2*16: // return InstructionClass2.disassemble(address); // case 3*16: // return InstructionClass3.disassemble(address); // case 4*16: // return InstructionClass4.disassemble(address); // case 5*16: // return InstructionClass5.disassemble(address); // case 6*16: // return InstructionClass6.disassemble(address); // case 7*16: // return InstructionClass7.disassemble(address); // default : // return JOptionPane.showInputDialog(opcode); // } // } // // public byte getClas() { // return this.clas; // } // // public void setSize(int size) { // this.size = size; // } // // public int getSize() { // return this.size; // } // // public byte[] getEncoding() { // return encoding; // } // // public void setEncoding(byte[] encoding) { // this.encoding = encoding; // } // // public abstract void run(); // // public static byte[] longToBytes(long l) { // byte[] result = new byte[8]; // for (int i = 7; i >= 0; i--) { // result[i] = (byte)(l & 0xFF); // l >>= 8; // } // return result; // } // // public static long bytesToLong(byte[] b) { // ByteBuffer bb = ByteBuffer.allocate(b.length); // bb.put(b); // return bb.getLong(); // } // // public static byte byteToBits(byte b, int start, int end){ // byte mask = 0; // if(start < end || start > 7 || end < 0 ) throw new RuntimeException("No valid start || end"); // // for (int i = 7-start; i <= 7-end; i++) { // mask += 1 << 7-i; // } // byte ret = (byte) (mask & b); // for (int i = 0; i < end; i++) { // ret /= 2; // } // if (ret < 0) { // ret += Math.pow(2, start-end+1); // } // return ret; // } // // // // } // Path: simulator/src/org/z64sim/program/instructions/InstructionClass0.java import org.z64sim.memory.Memory; import org.z64sim.program.Instruction; import javax.swing.JOptionPane; byte enc[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; switch (mnemonic) { case "hlt": enc[0] = 0x01; this.type = 0x01; break; case "nop": enc[0] = 0x02; this.type = 0x02; break; case "int": enc[0] = 0x03; this.type = 0x03; default: throw new RuntimeException("Unknown Class 0 instruction: " + mnemonic); } this.setEncoding(enc); } @Override public void run() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } public static String disassemble(int address) { byte b[] = new byte[8]; for(int i = 0; i < 8; i++) {
b[i] = Memory.getProgram().program[address + i];
alessandropellegrini/z64sim
iodevice/src/org/luaj/vm2/ast/NameResolver.java
// Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class Assign extends Stat { // public final List vars; // public final List exps; // // public Assign(List vars, List exps) { // this.vars = vars; // this.exps = exps; // } // // public void accept(Visitor visitor) { // visitor.visit(this); // } // // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class FuncDef extends Stat { // public final FuncName name; // public final FuncBody body; // public FuncDef(FuncName name, FuncBody body) { // this.name = name; // this.body = body; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class GenericFor extends Stat { // public List names; // public List exps; // public Block block; // public NameScope scope; // public GenericFor(List names, List exps, Block block) { // this.names = names; // this.exps = exps; // this.block = block; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class LocalAssign extends Stat { // public final List names; // public final List values; // public LocalAssign(List names, List values) { // this.names = names; // this.values = values; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class LocalFuncDef extends Stat { // public final Name name; // public final FuncBody body; // public LocalFuncDef(String name, FuncBody body) { // this.name = new Name(name); // this.body = body; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class NumericFor extends Stat { // public final Name name; // public final Exp initial,limit,step; // public final Block block; // public NameScope scope; // public NumericFor(String name, Exp initial, Exp limit, Exp step, Block block) { // this.name = new Name(name); // this.initial = initial; // this.limit = limit; // this.step = step; // this.block = block; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // }
import java.util.List; import org.luaj.vm2.LuaValue; import org.luaj.vm2.ast.Exp.Constant; import org.luaj.vm2.ast.Exp.NameExp; import org.luaj.vm2.ast.Exp.VarExp; import org.luaj.vm2.ast.Stat.Assign; import org.luaj.vm2.ast.Stat.FuncDef; import org.luaj.vm2.ast.Stat.GenericFor; import org.luaj.vm2.ast.Stat.LocalAssign; import org.luaj.vm2.ast.Stat.LocalFuncDef; import org.luaj.vm2.ast.Stat.NumericFor;
package org.luaj.vm2.ast; /** * Visitor that resolves names to scopes. * Each Name is resolved to a NamedVarible, possibly in a NameScope * if it is a local, or in no named scope if it is a global. */ public class NameResolver extends Visitor { private NameScope scope = null; private void pushScope() { scope = new NameScope(scope); } private void popScope() { scope = scope.outerScope; } public void visit(NameScope scope) { } public void visit(Block block) { pushScope(); block.scope = scope; super.visit(block); popScope(); } public void visit(FuncBody body) { pushScope(); scope.functionNestingCount++; body.scope = scope; super.visit(body); popScope(); }
// Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class Assign extends Stat { // public final List vars; // public final List exps; // // public Assign(List vars, List exps) { // this.vars = vars; // this.exps = exps; // } // // public void accept(Visitor visitor) { // visitor.visit(this); // } // // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class FuncDef extends Stat { // public final FuncName name; // public final FuncBody body; // public FuncDef(FuncName name, FuncBody body) { // this.name = name; // this.body = body; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class GenericFor extends Stat { // public List names; // public List exps; // public Block block; // public NameScope scope; // public GenericFor(List names, List exps, Block block) { // this.names = names; // this.exps = exps; // this.block = block; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class LocalAssign extends Stat { // public final List names; // public final List values; // public LocalAssign(List names, List values) { // this.names = names; // this.values = values; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class LocalFuncDef extends Stat { // public final Name name; // public final FuncBody body; // public LocalFuncDef(String name, FuncBody body) { // this.name = new Name(name); // this.body = body; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class NumericFor extends Stat { // public final Name name; // public final Exp initial,limit,step; // public final Block block; // public NameScope scope; // public NumericFor(String name, Exp initial, Exp limit, Exp step, Block block) { // this.name = new Name(name); // this.initial = initial; // this.limit = limit; // this.step = step; // this.block = block; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // Path: iodevice/src/org/luaj/vm2/ast/NameResolver.java import java.util.List; import org.luaj.vm2.LuaValue; import org.luaj.vm2.ast.Exp.Constant; import org.luaj.vm2.ast.Exp.NameExp; import org.luaj.vm2.ast.Exp.VarExp; import org.luaj.vm2.ast.Stat.Assign; import org.luaj.vm2.ast.Stat.FuncDef; import org.luaj.vm2.ast.Stat.GenericFor; import org.luaj.vm2.ast.Stat.LocalAssign; import org.luaj.vm2.ast.Stat.LocalFuncDef; import org.luaj.vm2.ast.Stat.NumericFor; package org.luaj.vm2.ast; /** * Visitor that resolves names to scopes. * Each Name is resolved to a NamedVarible, possibly in a NameScope * if it is a local, or in no named scope if it is a global. */ public class NameResolver extends Visitor { private NameScope scope = null; private void pushScope() { scope = new NameScope(scope); } private void popScope() { scope = scope.outerScope; } public void visit(NameScope scope) { } public void visit(Block block) { pushScope(); block.scope = scope; super.visit(block); popScope(); } public void visit(FuncBody body) { pushScope(); scope.functionNestingCount++; body.scope = scope; super.visit(body); popScope(); }
public void visit(LocalFuncDef stat) {
alessandropellegrini/z64sim
iodevice/src/org/luaj/vm2/ast/NameResolver.java
// Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class Assign extends Stat { // public final List vars; // public final List exps; // // public Assign(List vars, List exps) { // this.vars = vars; // this.exps = exps; // } // // public void accept(Visitor visitor) { // visitor.visit(this); // } // // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class FuncDef extends Stat { // public final FuncName name; // public final FuncBody body; // public FuncDef(FuncName name, FuncBody body) { // this.name = name; // this.body = body; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class GenericFor extends Stat { // public List names; // public List exps; // public Block block; // public NameScope scope; // public GenericFor(List names, List exps, Block block) { // this.names = names; // this.exps = exps; // this.block = block; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class LocalAssign extends Stat { // public final List names; // public final List values; // public LocalAssign(List names, List values) { // this.names = names; // this.values = values; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class LocalFuncDef extends Stat { // public final Name name; // public final FuncBody body; // public LocalFuncDef(String name, FuncBody body) { // this.name = new Name(name); // this.body = body; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class NumericFor extends Stat { // public final Name name; // public final Exp initial,limit,step; // public final Block block; // public NameScope scope; // public NumericFor(String name, Exp initial, Exp limit, Exp step, Block block) { // this.name = new Name(name); // this.initial = initial; // this.limit = limit; // this.step = step; // this.block = block; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // }
import java.util.List; import org.luaj.vm2.LuaValue; import org.luaj.vm2.ast.Exp.Constant; import org.luaj.vm2.ast.Exp.NameExp; import org.luaj.vm2.ast.Exp.VarExp; import org.luaj.vm2.ast.Stat.Assign; import org.luaj.vm2.ast.Stat.FuncDef; import org.luaj.vm2.ast.Stat.GenericFor; import org.luaj.vm2.ast.Stat.LocalAssign; import org.luaj.vm2.ast.Stat.LocalFuncDef; import org.luaj.vm2.ast.Stat.NumericFor;
package org.luaj.vm2.ast; /** * Visitor that resolves names to scopes. * Each Name is resolved to a NamedVarible, possibly in a NameScope * if it is a local, or in no named scope if it is a global. */ public class NameResolver extends Visitor { private NameScope scope = null; private void pushScope() { scope = new NameScope(scope); } private void popScope() { scope = scope.outerScope; } public void visit(NameScope scope) { } public void visit(Block block) { pushScope(); block.scope = scope; super.visit(block); popScope(); } public void visit(FuncBody body) { pushScope(); scope.functionNestingCount++; body.scope = scope; super.visit(body); popScope(); } public void visit(LocalFuncDef stat) { defineLocalVar(stat.name); super.visit(stat); }
// Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class Assign extends Stat { // public final List vars; // public final List exps; // // public Assign(List vars, List exps) { // this.vars = vars; // this.exps = exps; // } // // public void accept(Visitor visitor) { // visitor.visit(this); // } // // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class FuncDef extends Stat { // public final FuncName name; // public final FuncBody body; // public FuncDef(FuncName name, FuncBody body) { // this.name = name; // this.body = body; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class GenericFor extends Stat { // public List names; // public List exps; // public Block block; // public NameScope scope; // public GenericFor(List names, List exps, Block block) { // this.names = names; // this.exps = exps; // this.block = block; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class LocalAssign extends Stat { // public final List names; // public final List values; // public LocalAssign(List names, List values) { // this.names = names; // this.values = values; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class LocalFuncDef extends Stat { // public final Name name; // public final FuncBody body; // public LocalFuncDef(String name, FuncBody body) { // this.name = new Name(name); // this.body = body; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class NumericFor extends Stat { // public final Name name; // public final Exp initial,limit,step; // public final Block block; // public NameScope scope; // public NumericFor(String name, Exp initial, Exp limit, Exp step, Block block) { // this.name = new Name(name); // this.initial = initial; // this.limit = limit; // this.step = step; // this.block = block; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // Path: iodevice/src/org/luaj/vm2/ast/NameResolver.java import java.util.List; import org.luaj.vm2.LuaValue; import org.luaj.vm2.ast.Exp.Constant; import org.luaj.vm2.ast.Exp.NameExp; import org.luaj.vm2.ast.Exp.VarExp; import org.luaj.vm2.ast.Stat.Assign; import org.luaj.vm2.ast.Stat.FuncDef; import org.luaj.vm2.ast.Stat.GenericFor; import org.luaj.vm2.ast.Stat.LocalAssign; import org.luaj.vm2.ast.Stat.LocalFuncDef; import org.luaj.vm2.ast.Stat.NumericFor; package org.luaj.vm2.ast; /** * Visitor that resolves names to scopes. * Each Name is resolved to a NamedVarible, possibly in a NameScope * if it is a local, or in no named scope if it is a global. */ public class NameResolver extends Visitor { private NameScope scope = null; private void pushScope() { scope = new NameScope(scope); } private void popScope() { scope = scope.outerScope; } public void visit(NameScope scope) { } public void visit(Block block) { pushScope(); block.scope = scope; super.visit(block); popScope(); } public void visit(FuncBody body) { pushScope(); scope.functionNestingCount++; body.scope = scope; super.visit(body); popScope(); } public void visit(LocalFuncDef stat) { defineLocalVar(stat.name); super.visit(stat); }
public void visit(NumericFor stat) {
alessandropellegrini/z64sim
iodevice/src/org/luaj/vm2/ast/NameResolver.java
// Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class Assign extends Stat { // public final List vars; // public final List exps; // // public Assign(List vars, List exps) { // this.vars = vars; // this.exps = exps; // } // // public void accept(Visitor visitor) { // visitor.visit(this); // } // // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class FuncDef extends Stat { // public final FuncName name; // public final FuncBody body; // public FuncDef(FuncName name, FuncBody body) { // this.name = name; // this.body = body; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class GenericFor extends Stat { // public List names; // public List exps; // public Block block; // public NameScope scope; // public GenericFor(List names, List exps, Block block) { // this.names = names; // this.exps = exps; // this.block = block; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class LocalAssign extends Stat { // public final List names; // public final List values; // public LocalAssign(List names, List values) { // this.names = names; // this.values = values; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class LocalFuncDef extends Stat { // public final Name name; // public final FuncBody body; // public LocalFuncDef(String name, FuncBody body) { // this.name = new Name(name); // this.body = body; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class NumericFor extends Stat { // public final Name name; // public final Exp initial,limit,step; // public final Block block; // public NameScope scope; // public NumericFor(String name, Exp initial, Exp limit, Exp step, Block block) { // this.name = new Name(name); // this.initial = initial; // this.limit = limit; // this.step = step; // this.block = block; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // }
import java.util.List; import org.luaj.vm2.LuaValue; import org.luaj.vm2.ast.Exp.Constant; import org.luaj.vm2.ast.Exp.NameExp; import org.luaj.vm2.ast.Exp.VarExp; import org.luaj.vm2.ast.Stat.Assign; import org.luaj.vm2.ast.Stat.FuncDef; import org.luaj.vm2.ast.Stat.GenericFor; import org.luaj.vm2.ast.Stat.LocalAssign; import org.luaj.vm2.ast.Stat.LocalFuncDef; import org.luaj.vm2.ast.Stat.NumericFor;
} public void visit(Block block) { pushScope(); block.scope = scope; super.visit(block); popScope(); } public void visit(FuncBody body) { pushScope(); scope.functionNestingCount++; body.scope = scope; super.visit(body); popScope(); } public void visit(LocalFuncDef stat) { defineLocalVar(stat.name); super.visit(stat); } public void visit(NumericFor stat) { pushScope(); stat.scope = scope; defineLocalVar(stat.name); super.visit(stat); popScope(); }
// Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class Assign extends Stat { // public final List vars; // public final List exps; // // public Assign(List vars, List exps) { // this.vars = vars; // this.exps = exps; // } // // public void accept(Visitor visitor) { // visitor.visit(this); // } // // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class FuncDef extends Stat { // public final FuncName name; // public final FuncBody body; // public FuncDef(FuncName name, FuncBody body) { // this.name = name; // this.body = body; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class GenericFor extends Stat { // public List names; // public List exps; // public Block block; // public NameScope scope; // public GenericFor(List names, List exps, Block block) { // this.names = names; // this.exps = exps; // this.block = block; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class LocalAssign extends Stat { // public final List names; // public final List values; // public LocalAssign(List names, List values) { // this.names = names; // this.values = values; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class LocalFuncDef extends Stat { // public final Name name; // public final FuncBody body; // public LocalFuncDef(String name, FuncBody body) { // this.name = new Name(name); // this.body = body; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class NumericFor extends Stat { // public final Name name; // public final Exp initial,limit,step; // public final Block block; // public NameScope scope; // public NumericFor(String name, Exp initial, Exp limit, Exp step, Block block) { // this.name = new Name(name); // this.initial = initial; // this.limit = limit; // this.step = step; // this.block = block; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // Path: iodevice/src/org/luaj/vm2/ast/NameResolver.java import java.util.List; import org.luaj.vm2.LuaValue; import org.luaj.vm2.ast.Exp.Constant; import org.luaj.vm2.ast.Exp.NameExp; import org.luaj.vm2.ast.Exp.VarExp; import org.luaj.vm2.ast.Stat.Assign; import org.luaj.vm2.ast.Stat.FuncDef; import org.luaj.vm2.ast.Stat.GenericFor; import org.luaj.vm2.ast.Stat.LocalAssign; import org.luaj.vm2.ast.Stat.LocalFuncDef; import org.luaj.vm2.ast.Stat.NumericFor; } public void visit(Block block) { pushScope(); block.scope = scope; super.visit(block); popScope(); } public void visit(FuncBody body) { pushScope(); scope.functionNestingCount++; body.scope = scope; super.visit(body); popScope(); } public void visit(LocalFuncDef stat) { defineLocalVar(stat.name); super.visit(stat); } public void visit(NumericFor stat) { pushScope(); stat.scope = scope; defineLocalVar(stat.name); super.visit(stat); popScope(); }
public void visit(GenericFor stat) {
alessandropellegrini/z64sim
iodevice/src/org/luaj/vm2/ast/NameResolver.java
// Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class Assign extends Stat { // public final List vars; // public final List exps; // // public Assign(List vars, List exps) { // this.vars = vars; // this.exps = exps; // } // // public void accept(Visitor visitor) { // visitor.visit(this); // } // // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class FuncDef extends Stat { // public final FuncName name; // public final FuncBody body; // public FuncDef(FuncName name, FuncBody body) { // this.name = name; // this.body = body; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class GenericFor extends Stat { // public List names; // public List exps; // public Block block; // public NameScope scope; // public GenericFor(List names, List exps, Block block) { // this.names = names; // this.exps = exps; // this.block = block; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class LocalAssign extends Stat { // public final List names; // public final List values; // public LocalAssign(List names, List values) { // this.names = names; // this.values = values; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class LocalFuncDef extends Stat { // public final Name name; // public final FuncBody body; // public LocalFuncDef(String name, FuncBody body) { // this.name = new Name(name); // this.body = body; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class NumericFor extends Stat { // public final Name name; // public final Exp initial,limit,step; // public final Block block; // public NameScope scope; // public NumericFor(String name, Exp initial, Exp limit, Exp step, Block block) { // this.name = new Name(name); // this.initial = initial; // this.limit = limit; // this.step = step; // this.block = block; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // }
import java.util.List; import org.luaj.vm2.LuaValue; import org.luaj.vm2.ast.Exp.Constant; import org.luaj.vm2.ast.Exp.NameExp; import org.luaj.vm2.ast.Exp.VarExp; import org.luaj.vm2.ast.Stat.Assign; import org.luaj.vm2.ast.Stat.FuncDef; import org.luaj.vm2.ast.Stat.GenericFor; import org.luaj.vm2.ast.Stat.LocalAssign; import org.luaj.vm2.ast.Stat.LocalFuncDef; import org.luaj.vm2.ast.Stat.NumericFor;
super.visit(body); popScope(); } public void visit(LocalFuncDef stat) { defineLocalVar(stat.name); super.visit(stat); } public void visit(NumericFor stat) { pushScope(); stat.scope = scope; defineLocalVar(stat.name); super.visit(stat); popScope(); } public void visit(GenericFor stat) { pushScope(); stat.scope = scope; defineLocalVars( stat.names ); super.visit(stat); popScope(); } public void visit(NameExp exp) { exp.name.variable = resolveNameReference(exp.name); super.visit(exp); }
// Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class Assign extends Stat { // public final List vars; // public final List exps; // // public Assign(List vars, List exps) { // this.vars = vars; // this.exps = exps; // } // // public void accept(Visitor visitor) { // visitor.visit(this); // } // // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class FuncDef extends Stat { // public final FuncName name; // public final FuncBody body; // public FuncDef(FuncName name, FuncBody body) { // this.name = name; // this.body = body; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class GenericFor extends Stat { // public List names; // public List exps; // public Block block; // public NameScope scope; // public GenericFor(List names, List exps, Block block) { // this.names = names; // this.exps = exps; // this.block = block; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class LocalAssign extends Stat { // public final List names; // public final List values; // public LocalAssign(List names, List values) { // this.names = names; // this.values = values; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class LocalFuncDef extends Stat { // public final Name name; // public final FuncBody body; // public LocalFuncDef(String name, FuncBody body) { // this.name = new Name(name); // this.body = body; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class NumericFor extends Stat { // public final Name name; // public final Exp initial,limit,step; // public final Block block; // public NameScope scope; // public NumericFor(String name, Exp initial, Exp limit, Exp step, Block block) { // this.name = new Name(name); // this.initial = initial; // this.limit = limit; // this.step = step; // this.block = block; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // Path: iodevice/src/org/luaj/vm2/ast/NameResolver.java import java.util.List; import org.luaj.vm2.LuaValue; import org.luaj.vm2.ast.Exp.Constant; import org.luaj.vm2.ast.Exp.NameExp; import org.luaj.vm2.ast.Exp.VarExp; import org.luaj.vm2.ast.Stat.Assign; import org.luaj.vm2.ast.Stat.FuncDef; import org.luaj.vm2.ast.Stat.GenericFor; import org.luaj.vm2.ast.Stat.LocalAssign; import org.luaj.vm2.ast.Stat.LocalFuncDef; import org.luaj.vm2.ast.Stat.NumericFor; super.visit(body); popScope(); } public void visit(LocalFuncDef stat) { defineLocalVar(stat.name); super.visit(stat); } public void visit(NumericFor stat) { pushScope(); stat.scope = scope; defineLocalVar(stat.name); super.visit(stat); popScope(); } public void visit(GenericFor stat) { pushScope(); stat.scope = scope; defineLocalVars( stat.names ); super.visit(stat); popScope(); } public void visit(NameExp exp) { exp.name.variable = resolveNameReference(exp.name); super.visit(exp); }
public void visit(FuncDef stat) {
alessandropellegrini/z64sim
iodevice/src/org/luaj/vm2/ast/NameResolver.java
// Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class Assign extends Stat { // public final List vars; // public final List exps; // // public Assign(List vars, List exps) { // this.vars = vars; // this.exps = exps; // } // // public void accept(Visitor visitor) { // visitor.visit(this); // } // // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class FuncDef extends Stat { // public final FuncName name; // public final FuncBody body; // public FuncDef(FuncName name, FuncBody body) { // this.name = name; // this.body = body; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class GenericFor extends Stat { // public List names; // public List exps; // public Block block; // public NameScope scope; // public GenericFor(List names, List exps, Block block) { // this.names = names; // this.exps = exps; // this.block = block; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class LocalAssign extends Stat { // public final List names; // public final List values; // public LocalAssign(List names, List values) { // this.names = names; // this.values = values; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class LocalFuncDef extends Stat { // public final Name name; // public final FuncBody body; // public LocalFuncDef(String name, FuncBody body) { // this.name = new Name(name); // this.body = body; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class NumericFor extends Stat { // public final Name name; // public final Exp initial,limit,step; // public final Block block; // public NameScope scope; // public NumericFor(String name, Exp initial, Exp limit, Exp step, Block block) { // this.name = new Name(name); // this.initial = initial; // this.limit = limit; // this.step = step; // this.block = block; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // }
import java.util.List; import org.luaj.vm2.LuaValue; import org.luaj.vm2.ast.Exp.Constant; import org.luaj.vm2.ast.Exp.NameExp; import org.luaj.vm2.ast.Exp.VarExp; import org.luaj.vm2.ast.Stat.Assign; import org.luaj.vm2.ast.Stat.FuncDef; import org.luaj.vm2.ast.Stat.GenericFor; import org.luaj.vm2.ast.Stat.LocalAssign; import org.luaj.vm2.ast.Stat.LocalFuncDef; import org.luaj.vm2.ast.Stat.NumericFor;
super.visit(stat); } public void visit(NumericFor stat) { pushScope(); stat.scope = scope; defineLocalVar(stat.name); super.visit(stat); popScope(); } public void visit(GenericFor stat) { pushScope(); stat.scope = scope; defineLocalVars( stat.names ); super.visit(stat); popScope(); } public void visit(NameExp exp) { exp.name.variable = resolveNameReference(exp.name); super.visit(exp); } public void visit(FuncDef stat) { stat.name.name.variable = resolveNameReference(stat.name.name); stat.name.name.variable.hasassignments = true; super.visit(stat); }
// Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class Assign extends Stat { // public final List vars; // public final List exps; // // public Assign(List vars, List exps) { // this.vars = vars; // this.exps = exps; // } // // public void accept(Visitor visitor) { // visitor.visit(this); // } // // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class FuncDef extends Stat { // public final FuncName name; // public final FuncBody body; // public FuncDef(FuncName name, FuncBody body) { // this.name = name; // this.body = body; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class GenericFor extends Stat { // public List names; // public List exps; // public Block block; // public NameScope scope; // public GenericFor(List names, List exps, Block block) { // this.names = names; // this.exps = exps; // this.block = block; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class LocalAssign extends Stat { // public final List names; // public final List values; // public LocalAssign(List names, List values) { // this.names = names; // this.values = values; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class LocalFuncDef extends Stat { // public final Name name; // public final FuncBody body; // public LocalFuncDef(String name, FuncBody body) { // this.name = new Name(name); // this.body = body; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class NumericFor extends Stat { // public final Name name; // public final Exp initial,limit,step; // public final Block block; // public NameScope scope; // public NumericFor(String name, Exp initial, Exp limit, Exp step, Block block) { // this.name = new Name(name); // this.initial = initial; // this.limit = limit; // this.step = step; // this.block = block; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // Path: iodevice/src/org/luaj/vm2/ast/NameResolver.java import java.util.List; import org.luaj.vm2.LuaValue; import org.luaj.vm2.ast.Exp.Constant; import org.luaj.vm2.ast.Exp.NameExp; import org.luaj.vm2.ast.Exp.VarExp; import org.luaj.vm2.ast.Stat.Assign; import org.luaj.vm2.ast.Stat.FuncDef; import org.luaj.vm2.ast.Stat.GenericFor; import org.luaj.vm2.ast.Stat.LocalAssign; import org.luaj.vm2.ast.Stat.LocalFuncDef; import org.luaj.vm2.ast.Stat.NumericFor; super.visit(stat); } public void visit(NumericFor stat) { pushScope(); stat.scope = scope; defineLocalVar(stat.name); super.visit(stat); popScope(); } public void visit(GenericFor stat) { pushScope(); stat.scope = scope; defineLocalVars( stat.names ); super.visit(stat); popScope(); } public void visit(NameExp exp) { exp.name.variable = resolveNameReference(exp.name); super.visit(exp); } public void visit(FuncDef stat) { stat.name.name.variable = resolveNameReference(stat.name.name); stat.name.name.variable.hasassignments = true; super.visit(stat); }
public void visit(Assign stat) {
alessandropellegrini/z64sim
iodevice/src/org/luaj/vm2/ast/NameResolver.java
// Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class Assign extends Stat { // public final List vars; // public final List exps; // // public Assign(List vars, List exps) { // this.vars = vars; // this.exps = exps; // } // // public void accept(Visitor visitor) { // visitor.visit(this); // } // // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class FuncDef extends Stat { // public final FuncName name; // public final FuncBody body; // public FuncDef(FuncName name, FuncBody body) { // this.name = name; // this.body = body; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class GenericFor extends Stat { // public List names; // public List exps; // public Block block; // public NameScope scope; // public GenericFor(List names, List exps, Block block) { // this.names = names; // this.exps = exps; // this.block = block; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class LocalAssign extends Stat { // public final List names; // public final List values; // public LocalAssign(List names, List values) { // this.names = names; // this.values = values; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class LocalFuncDef extends Stat { // public final Name name; // public final FuncBody body; // public LocalFuncDef(String name, FuncBody body) { // this.name = new Name(name); // this.body = body; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class NumericFor extends Stat { // public final Name name; // public final Exp initial,limit,step; // public final Block block; // public NameScope scope; // public NumericFor(String name, Exp initial, Exp limit, Exp step, Block block) { // this.name = new Name(name); // this.initial = initial; // this.limit = limit; // this.step = step; // this.block = block; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // }
import java.util.List; import org.luaj.vm2.LuaValue; import org.luaj.vm2.ast.Exp.Constant; import org.luaj.vm2.ast.Exp.NameExp; import org.luaj.vm2.ast.Exp.VarExp; import org.luaj.vm2.ast.Stat.Assign; import org.luaj.vm2.ast.Stat.FuncDef; import org.luaj.vm2.ast.Stat.GenericFor; import org.luaj.vm2.ast.Stat.LocalAssign; import org.luaj.vm2.ast.Stat.LocalFuncDef; import org.luaj.vm2.ast.Stat.NumericFor;
popScope(); } public void visit(GenericFor stat) { pushScope(); stat.scope = scope; defineLocalVars( stat.names ); super.visit(stat); popScope(); } public void visit(NameExp exp) { exp.name.variable = resolveNameReference(exp.name); super.visit(exp); } public void visit(FuncDef stat) { stat.name.name.variable = resolveNameReference(stat.name.name); stat.name.name.variable.hasassignments = true; super.visit(stat); } public void visit(Assign stat) { super.visit(stat); for ( int i=0, n=stat.vars.size(); i<n; i++ ) { VarExp v = (VarExp) stat.vars.get(i); v.markHasAssignment(); } }
// Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class Assign extends Stat { // public final List vars; // public final List exps; // // public Assign(List vars, List exps) { // this.vars = vars; // this.exps = exps; // } // // public void accept(Visitor visitor) { // visitor.visit(this); // } // // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class FuncDef extends Stat { // public final FuncName name; // public final FuncBody body; // public FuncDef(FuncName name, FuncBody body) { // this.name = name; // this.body = body; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class GenericFor extends Stat { // public List names; // public List exps; // public Block block; // public NameScope scope; // public GenericFor(List names, List exps, Block block) { // this.names = names; // this.exps = exps; // this.block = block; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class LocalAssign extends Stat { // public final List names; // public final List values; // public LocalAssign(List names, List values) { // this.names = names; // this.values = values; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class LocalFuncDef extends Stat { // public final Name name; // public final FuncBody body; // public LocalFuncDef(String name, FuncBody body) { // this.name = new Name(name); // this.body = body; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // // Path: iodevice/src/org/luaj/vm2/ast/Stat.java // public static class NumericFor extends Stat { // public final Name name; // public final Exp initial,limit,step; // public final Block block; // public NameScope scope; // public NumericFor(String name, Exp initial, Exp limit, Exp step, Block block) { // this.name = new Name(name); // this.initial = initial; // this.limit = limit; // this.step = step; // this.block = block; // } // // public void accept(Visitor visitor) { // visitor.visit( this ); // } // } // Path: iodevice/src/org/luaj/vm2/ast/NameResolver.java import java.util.List; import org.luaj.vm2.LuaValue; import org.luaj.vm2.ast.Exp.Constant; import org.luaj.vm2.ast.Exp.NameExp; import org.luaj.vm2.ast.Exp.VarExp; import org.luaj.vm2.ast.Stat.Assign; import org.luaj.vm2.ast.Stat.FuncDef; import org.luaj.vm2.ast.Stat.GenericFor; import org.luaj.vm2.ast.Stat.LocalAssign; import org.luaj.vm2.ast.Stat.LocalFuncDef; import org.luaj.vm2.ast.Stat.NumericFor; popScope(); } public void visit(GenericFor stat) { pushScope(); stat.scope = scope; defineLocalVars( stat.names ); super.visit(stat); popScope(); } public void visit(NameExp exp) { exp.name.variable = resolveNameReference(exp.name); super.visit(exp); } public void visit(FuncDef stat) { stat.name.name.variable = resolveNameReference(stat.name.name); stat.name.name.variable.hasassignments = true; super.visit(stat); } public void visit(Assign stat) { super.visit(stat); for ( int i=0, n=stat.vars.size(); i<n; i++ ) { VarExp v = (VarExp) stat.vars.get(i); v.markHasAssignment(); } }
public void visit(LocalAssign stat) {
alessandropellegrini/z64sim
simulator/src/org/z64sim/program/instructions/InstructionClass7.java
// Path: simulator/src/org/z64sim/memory/Memory.java // public class Memory { // // private static MemoryTopComponent window = null; // //private static Program program = null; // private static Program program = new Program(); // aggiunto per evitare nullPointerException // // // This class cannot be instantiated // private Memory() { // } // // public static Program getProgram() { // return program; // } // // public static void setProgram(Program program) { // Memory.program = program; // } // // public static void setWindow(MemoryTopComponent w) { // Memory.window = w; // } // // public static MemoryTopComponent getWindow() { // return Memory.window; // } // // public static void redrawMemory() { // if (Memory.window != null) { // Memory.window.memoryTable.setModel(new MemoryTableModel()); // int _startRow = (int) (Memory.program._start / 8); // // // Select the row corresponding to the entry point // Memory.window.memoryTable.setRowSelectionInterval(_startRow, _startRow); // // // Scroll to that row // Memory.window.memoryTable.scrollRectToVisible(new Rectangle(Memory.window.memoryTable.getCellRect(_startRow, 0, true))); // // // Show the panel // Memory.window.requestVisible(); // } // // } // // } // // Path: simulator/src/org/z64sim/program/Instruction.java // public abstract class Instruction { // // protected final String mnemonic; // protected final byte clas; // protected byte type; // protected int size; // protected byte[] encoding; // // public Instruction(String mnemonic, int clas) { // this.mnemonic = mnemonic; // this.clas = (byte)clas; // } // // protected static boolean skip = false; // // // toString() must be explicitly re-implemented // public static String disassemble(int address) { // if(Instruction.skip) { // Instruction.skip = false; // return ""; // } // byte opcode = 0; // opcode = (byte)(Memory.getProgram().program[address] & 0b11110000); // // switch(opcode){ // case 0: // return InstructionClass0.disassemble(address); // case 1*16: // return InstructionClass1.disassemble(address); // case 2*16: // return InstructionClass2.disassemble(address); // case 3*16: // return InstructionClass3.disassemble(address); // case 4*16: // return InstructionClass4.disassemble(address); // case 5*16: // return InstructionClass5.disassemble(address); // case 6*16: // return InstructionClass6.disassemble(address); // case 7*16: // return InstructionClass7.disassemble(address); // default : // return JOptionPane.showInputDialog(opcode); // } // } // // public byte getClas() { // return this.clas; // } // // public void setSize(int size) { // this.size = size; // } // // public int getSize() { // return this.size; // } // // public byte[] getEncoding() { // return encoding; // } // // public void setEncoding(byte[] encoding) { // this.encoding = encoding; // } // // public abstract void run(); // // public static byte[] longToBytes(long l) { // byte[] result = new byte[8]; // for (int i = 7; i >= 0; i--) { // result[i] = (byte)(l & 0xFF); // l >>= 8; // } // return result; // } // // public static long bytesToLong(byte[] b) { // ByteBuffer bb = ByteBuffer.allocate(b.length); // bb.put(b); // return bb.getLong(); // } // // public static byte byteToBits(byte b, int start, int end){ // byte mask = 0; // if(start < end || start > 7 || end < 0 ) throw new RuntimeException("No valid start || end"); // // for (int i = 7-start; i <= 7-end; i++) { // mask += 1 << 7-i; // } // byte ret = (byte) (mask & b); // for (int i = 0; i < end; i++) { // ret /= 2; // } // if (ret < 0) { // ret += Math.pow(2, start-end+1); // } // return ret; // } // // // // }
import org.z64sim.program.Instruction; import org.z64sim.memory.Memory;
break; case "out": this.type = 0x01; break; case "ins": this.type = 0x02; break; case "outs": this.type = 0x03; break; default: throw new RuntimeException("Unknown Class 7 instruction: " + mnemonic); } enc[0] = (byte)(enc[0] | this.type); this.setEncoding(enc); this.setSize(8); } @Override public void run() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } public static String disassemble(int address) { byte b[] = new byte[8]; for(int i = 0; i < 8; i++) {
// Path: simulator/src/org/z64sim/memory/Memory.java // public class Memory { // // private static MemoryTopComponent window = null; // //private static Program program = null; // private static Program program = new Program(); // aggiunto per evitare nullPointerException // // // This class cannot be instantiated // private Memory() { // } // // public static Program getProgram() { // return program; // } // // public static void setProgram(Program program) { // Memory.program = program; // } // // public static void setWindow(MemoryTopComponent w) { // Memory.window = w; // } // // public static MemoryTopComponent getWindow() { // return Memory.window; // } // // public static void redrawMemory() { // if (Memory.window != null) { // Memory.window.memoryTable.setModel(new MemoryTableModel()); // int _startRow = (int) (Memory.program._start / 8); // // // Select the row corresponding to the entry point // Memory.window.memoryTable.setRowSelectionInterval(_startRow, _startRow); // // // Scroll to that row // Memory.window.memoryTable.scrollRectToVisible(new Rectangle(Memory.window.memoryTable.getCellRect(_startRow, 0, true))); // // // Show the panel // Memory.window.requestVisible(); // } // // } // // } // // Path: simulator/src/org/z64sim/program/Instruction.java // public abstract class Instruction { // // protected final String mnemonic; // protected final byte clas; // protected byte type; // protected int size; // protected byte[] encoding; // // public Instruction(String mnemonic, int clas) { // this.mnemonic = mnemonic; // this.clas = (byte)clas; // } // // protected static boolean skip = false; // // // toString() must be explicitly re-implemented // public static String disassemble(int address) { // if(Instruction.skip) { // Instruction.skip = false; // return ""; // } // byte opcode = 0; // opcode = (byte)(Memory.getProgram().program[address] & 0b11110000); // // switch(opcode){ // case 0: // return InstructionClass0.disassemble(address); // case 1*16: // return InstructionClass1.disassemble(address); // case 2*16: // return InstructionClass2.disassemble(address); // case 3*16: // return InstructionClass3.disassemble(address); // case 4*16: // return InstructionClass4.disassemble(address); // case 5*16: // return InstructionClass5.disassemble(address); // case 6*16: // return InstructionClass6.disassemble(address); // case 7*16: // return InstructionClass7.disassemble(address); // default : // return JOptionPane.showInputDialog(opcode); // } // } // // public byte getClas() { // return this.clas; // } // // public void setSize(int size) { // this.size = size; // } // // public int getSize() { // return this.size; // } // // public byte[] getEncoding() { // return encoding; // } // // public void setEncoding(byte[] encoding) { // this.encoding = encoding; // } // // public abstract void run(); // // public static byte[] longToBytes(long l) { // byte[] result = new byte[8]; // for (int i = 7; i >= 0; i--) { // result[i] = (byte)(l & 0xFF); // l >>= 8; // } // return result; // } // // public static long bytesToLong(byte[] b) { // ByteBuffer bb = ByteBuffer.allocate(b.length); // bb.put(b); // return bb.getLong(); // } // // public static byte byteToBits(byte b, int start, int end){ // byte mask = 0; // if(start < end || start > 7 || end < 0 ) throw new RuntimeException("No valid start || end"); // // for (int i = 7-start; i <= 7-end; i++) { // mask += 1 << 7-i; // } // byte ret = (byte) (mask & b); // for (int i = 0; i < end; i++) { // ret /= 2; // } // if (ret < 0) { // ret += Math.pow(2, start-end+1); // } // return ret; // } // // // // } // Path: simulator/src/org/z64sim/program/instructions/InstructionClass7.java import org.z64sim.program.Instruction; import org.z64sim.memory.Memory; break; case "out": this.type = 0x01; break; case "ins": this.type = 0x02; break; case "outs": this.type = 0x03; break; default: throw new RuntimeException("Unknown Class 7 instruction: " + mnemonic); } enc[0] = (byte)(enc[0] | this.type); this.setEncoding(enc); this.setSize(8); } @Override public void run() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } public static String disassemble(int address) { byte b[] = new byte[8]; for(int i = 0; i < 8; i++) {
b[i] = Memory.getProgram().program[address + i];
alessandropellegrini/z64sim
simulator/src/org/z64sim/simulator/multicycle/SimulatorMulticycleTopComponent.java
// Path: simulator/src/org/z64sim/memory/Memory.java // public class Memory { // // private static MemoryTopComponent window = null; // //private static Program program = null; // private static Program program = new Program(); // aggiunto per evitare nullPointerException // // // This class cannot be instantiated // private Memory() { // } // // public static Program getProgram() { // return program; // } // // public static void setProgram(Program program) { // Memory.program = program; // } // // public static void setWindow(MemoryTopComponent w) { // Memory.window = w; // } // // public static MemoryTopComponent getWindow() { // return Memory.window; // } // // public static void redrawMemory() { // if (Memory.window != null) { // Memory.window.memoryTable.setModel(new MemoryTableModel()); // int _startRow = (int) (Memory.program._start / 8); // // // Select the row corresponding to the entry point // Memory.window.memoryTable.setRowSelectionInterval(_startRow, _startRow); // // // Scroll to that row // Memory.window.memoryTable.scrollRectToVisible(new Rectangle(Memory.window.memoryTable.getCellRect(_startRow, 0, true))); // // // Show the panel // Memory.window.requestVisible(); // } // // } // // } // // Path: simulator/src/org/z64sim/simulator/Simulator.java // public class Simulator { // // private static SimulatorMulticycleTopComponent multicycleWindow = null; // // private Simulator() {} // // public static synchronized void setMulticycle(SimulatorMulticycleTopComponent mc) { // Simulator.multicycleWindow = mc; // } // // public static synchronized void resetMulticycle(SimulatorMulticycleTopComponent mc) { // if(Simulator.multicycleWindow == mc) // Simulator.multicycleWindow = null; // } // // public static boolean activate() { // if(multicycleWindow != null) { // multicycleWindow.requestFocusInWindow(); // multicycleWindow.checkEnabled(); // return true; // } // return false; // } // // }
import javax.swing.JOptionPane; import org.jdesktop.beansbinding.Converter; import org.netbeans.api.settings.ConvertAsProperties; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.windows.TopComponent; import org.openide.util.NbBundle.Messages; import org.z64sim.memory.Memory; import org.z64sim.simulator.Simulator;
private javax.swing.JTextField RCX_view; private javax.swing.JLabel RDI_label; private javax.swing.JTextField RDI_view; private javax.swing.JLabel RDX_label; private javax.swing.JTextField RDX_view; private javax.swing.JLabel RIP_label; private javax.swing.JTextField RIP_view; private javax.swing.JLabel RSI_label; private javax.swing.JTextField RSI_view; private javax.swing.JLabel RSP_label; private javax.swing.JTextField RSP_view; private javax.swing.JPanel Registers; private javax.swing.JCheckBox SF; private javax.swing.JCheckBox ZF; private javax.swing.Box.Filler filler1; private javax.swing.JToolBar.Separator jSeparator1; public javax.swing.JToolBar multicycleToolbar; private javax.swing.JButton run; private javax.swing.JSlider speedSlider; private javax.swing.JLabel speedValue; private javax.swing.JLabel speed_label; private javax.swing.JButton step; private org.jdesktop.beansbinding.BindingGroup bindingGroup; // End of variables declaration//GEN-END:variables @Override public void componentOpened() { checkEnabled(); // Register this window as the current Multicycle Simulator
// Path: simulator/src/org/z64sim/memory/Memory.java // public class Memory { // // private static MemoryTopComponent window = null; // //private static Program program = null; // private static Program program = new Program(); // aggiunto per evitare nullPointerException // // // This class cannot be instantiated // private Memory() { // } // // public static Program getProgram() { // return program; // } // // public static void setProgram(Program program) { // Memory.program = program; // } // // public static void setWindow(MemoryTopComponent w) { // Memory.window = w; // } // // public static MemoryTopComponent getWindow() { // return Memory.window; // } // // public static void redrawMemory() { // if (Memory.window != null) { // Memory.window.memoryTable.setModel(new MemoryTableModel()); // int _startRow = (int) (Memory.program._start / 8); // // // Select the row corresponding to the entry point // Memory.window.memoryTable.setRowSelectionInterval(_startRow, _startRow); // // // Scroll to that row // Memory.window.memoryTable.scrollRectToVisible(new Rectangle(Memory.window.memoryTable.getCellRect(_startRow, 0, true))); // // // Show the panel // Memory.window.requestVisible(); // } // // } // // } // // Path: simulator/src/org/z64sim/simulator/Simulator.java // public class Simulator { // // private static SimulatorMulticycleTopComponent multicycleWindow = null; // // private Simulator() {} // // public static synchronized void setMulticycle(SimulatorMulticycleTopComponent mc) { // Simulator.multicycleWindow = mc; // } // // public static synchronized void resetMulticycle(SimulatorMulticycleTopComponent mc) { // if(Simulator.multicycleWindow == mc) // Simulator.multicycleWindow = null; // } // // public static boolean activate() { // if(multicycleWindow != null) { // multicycleWindow.requestFocusInWindow(); // multicycleWindow.checkEnabled(); // return true; // } // return false; // } // // } // Path: simulator/src/org/z64sim/simulator/multicycle/SimulatorMulticycleTopComponent.java import javax.swing.JOptionPane; import org.jdesktop.beansbinding.Converter; import org.netbeans.api.settings.ConvertAsProperties; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.windows.TopComponent; import org.openide.util.NbBundle.Messages; import org.z64sim.memory.Memory; import org.z64sim.simulator.Simulator; private javax.swing.JTextField RCX_view; private javax.swing.JLabel RDI_label; private javax.swing.JTextField RDI_view; private javax.swing.JLabel RDX_label; private javax.swing.JTextField RDX_view; private javax.swing.JLabel RIP_label; private javax.swing.JTextField RIP_view; private javax.swing.JLabel RSI_label; private javax.swing.JTextField RSI_view; private javax.swing.JLabel RSP_label; private javax.swing.JTextField RSP_view; private javax.swing.JPanel Registers; private javax.swing.JCheckBox SF; private javax.swing.JCheckBox ZF; private javax.swing.Box.Filler filler1; private javax.swing.JToolBar.Separator jSeparator1; public javax.swing.JToolBar multicycleToolbar; private javax.swing.JButton run; private javax.swing.JSlider speedSlider; private javax.swing.JLabel speedValue; private javax.swing.JLabel speed_label; private javax.swing.JButton step; private org.jdesktop.beansbinding.BindingGroup bindingGroup; // End of variables declaration//GEN-END:variables @Override public void componentOpened() { checkEnabled(); // Register this window as the current Multicycle Simulator
Simulator.setMulticycle(this);
alessandropellegrini/z64sim
simulator/src/org/z64sim/simulator/multicycle/SimulatorMulticycleTopComponent.java
// Path: simulator/src/org/z64sim/memory/Memory.java // public class Memory { // // private static MemoryTopComponent window = null; // //private static Program program = null; // private static Program program = new Program(); // aggiunto per evitare nullPointerException // // // This class cannot be instantiated // private Memory() { // } // // public static Program getProgram() { // return program; // } // // public static void setProgram(Program program) { // Memory.program = program; // } // // public static void setWindow(MemoryTopComponent w) { // Memory.window = w; // } // // public static MemoryTopComponent getWindow() { // return Memory.window; // } // // public static void redrawMemory() { // if (Memory.window != null) { // Memory.window.memoryTable.setModel(new MemoryTableModel()); // int _startRow = (int) (Memory.program._start / 8); // // // Select the row corresponding to the entry point // Memory.window.memoryTable.setRowSelectionInterval(_startRow, _startRow); // // // Scroll to that row // Memory.window.memoryTable.scrollRectToVisible(new Rectangle(Memory.window.memoryTable.getCellRect(_startRow, 0, true))); // // // Show the panel // Memory.window.requestVisible(); // } // // } // // } // // Path: simulator/src/org/z64sim/simulator/Simulator.java // public class Simulator { // // private static SimulatorMulticycleTopComponent multicycleWindow = null; // // private Simulator() {} // // public static synchronized void setMulticycle(SimulatorMulticycleTopComponent mc) { // Simulator.multicycleWindow = mc; // } // // public static synchronized void resetMulticycle(SimulatorMulticycleTopComponent mc) { // if(Simulator.multicycleWindow == mc) // Simulator.multicycleWindow = null; // } // // public static boolean activate() { // if(multicycleWindow != null) { // multicycleWindow.requestFocusInWindow(); // multicycleWindow.checkEnabled(); // return true; // } // return false; // } // // }
import javax.swing.JOptionPane; import org.jdesktop.beansbinding.Converter; import org.netbeans.api.settings.ConvertAsProperties; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.windows.TopComponent; import org.openide.util.NbBundle.Messages; import org.z64sim.memory.Memory; import org.z64sim.simulator.Simulator;
// End of variables declaration//GEN-END:variables @Override public void componentOpened() { checkEnabled(); // Register this window as the current Multicycle Simulator Simulator.setMulticycle(this); } @Override public void componentClosed() { // Deregister as the current Multicycle Simulator Simulator.resetMulticycle(this); } void writeProperties(java.util.Properties p) { // better to version settings since initial version as advocated at // http://wiki.apidesign.org/wiki/PropertyFiles p.setProperty("version", "1.0"); // TODO store your settings } void readProperties(java.util.Properties p) { String version = p.getProperty("version"); // TODO read your settings according to their version } public void checkEnabled() { // Check whether there is an assembled file. If not, disable 'run' buttons
// Path: simulator/src/org/z64sim/memory/Memory.java // public class Memory { // // private static MemoryTopComponent window = null; // //private static Program program = null; // private static Program program = new Program(); // aggiunto per evitare nullPointerException // // // This class cannot be instantiated // private Memory() { // } // // public static Program getProgram() { // return program; // } // // public static void setProgram(Program program) { // Memory.program = program; // } // // public static void setWindow(MemoryTopComponent w) { // Memory.window = w; // } // // public static MemoryTopComponent getWindow() { // return Memory.window; // } // // public static void redrawMemory() { // if (Memory.window != null) { // Memory.window.memoryTable.setModel(new MemoryTableModel()); // int _startRow = (int) (Memory.program._start / 8); // // // Select the row corresponding to the entry point // Memory.window.memoryTable.setRowSelectionInterval(_startRow, _startRow); // // // Scroll to that row // Memory.window.memoryTable.scrollRectToVisible(new Rectangle(Memory.window.memoryTable.getCellRect(_startRow, 0, true))); // // // Show the panel // Memory.window.requestVisible(); // } // // } // // } // // Path: simulator/src/org/z64sim/simulator/Simulator.java // public class Simulator { // // private static SimulatorMulticycleTopComponent multicycleWindow = null; // // private Simulator() {} // // public static synchronized void setMulticycle(SimulatorMulticycleTopComponent mc) { // Simulator.multicycleWindow = mc; // } // // public static synchronized void resetMulticycle(SimulatorMulticycleTopComponent mc) { // if(Simulator.multicycleWindow == mc) // Simulator.multicycleWindow = null; // } // // public static boolean activate() { // if(multicycleWindow != null) { // multicycleWindow.requestFocusInWindow(); // multicycleWindow.checkEnabled(); // return true; // } // return false; // } // // } // Path: simulator/src/org/z64sim/simulator/multicycle/SimulatorMulticycleTopComponent.java import javax.swing.JOptionPane; import org.jdesktop.beansbinding.Converter; import org.netbeans.api.settings.ConvertAsProperties; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.windows.TopComponent; import org.openide.util.NbBundle.Messages; import org.z64sim.memory.Memory; import org.z64sim.simulator.Simulator; // End of variables declaration//GEN-END:variables @Override public void componentOpened() { checkEnabled(); // Register this window as the current Multicycle Simulator Simulator.setMulticycle(this); } @Override public void componentClosed() { // Deregister as the current Multicycle Simulator Simulator.resetMulticycle(this); } void writeProperties(java.util.Properties p) { // better to version settings since initial version as advocated at // http://wiki.apidesign.org/wiki/PropertyFiles p.setProperty("version", "1.0"); // TODO store your settings } void readProperties(java.util.Properties p) { String version = p.getProperty("version"); // TODO read your settings according to their version } public void checkEnabled() { // Check whether there is an assembled file. If not, disable 'run' buttons
if (Memory.getProgram() == null || Memory.getProgram()._start == -1) { // Entry point can never be zero in a real program
antonyms/AntonymPipeline
src/edu/antonym/metric/InvertMetric.java
// Path: src/edu/antonym/prototype/Vocabulary.java // public interface Vocabulary { // public int size(); // public int OOVindex(); // public String lookupIndex(int index); // public int lookupWord(String word); // public int getVocabSize(); // } // // Path: src/edu/antonym/prototype/WordMetric.java // public interface WordMetric { // public Vocabulary getVocab(); // // public double similarity(int word1, int word2); // }
import edu.antonym.prototype.Vocabulary; import edu.antonym.prototype.WordMetric;
package edu.antonym.metric; public class InvertMetric implements WordMetric { WordMetric orig; public InvertMetric(WordMetric orig) { this.orig = orig; } @Override
// Path: src/edu/antonym/prototype/Vocabulary.java // public interface Vocabulary { // public int size(); // public int OOVindex(); // public String lookupIndex(int index); // public int lookupWord(String word); // public int getVocabSize(); // } // // Path: src/edu/antonym/prototype/WordMetric.java // public interface WordMetric { // public Vocabulary getVocab(); // // public double similarity(int word1, int word2); // } // Path: src/edu/antonym/metric/InvertMetric.java import edu.antonym.prototype.Vocabulary; import edu.antonym.prototype.WordMetric; package edu.antonym.metric; public class InvertMetric implements WordMetric { WordMetric orig; public InvertMetric(WordMetric orig) { this.orig = orig; } @Override
public Vocabulary getVocab() {
antonyms/AntonymPipeline
src/edu/antonym/test/RandomizedTestCase.java
// Path: src/edu/antonym/Util.java // public class Util { // static void saveVectors(VectorEmbedding embed, Vocabulary vocab, File out) throws FileNotFoundException { // int dim=embed.getDimension(); // // PrintStream ps=new PrintStream(out); // ps.println(dim); // for(int i=0; i<vocab.size(); i++) { // double[] vect=embed.getVectorRep(i); // for(int j=0; j<dim; j++) { // ps.print(vect[j]); // ps.print(' '); // } // ps.println(); // } // ps.close(); // } // // public static double cosineSimilarity(double[] vector1, double[] vector2) { // double dotProduct = 0.0; // double v1 = 0.0; // double v2 = 0.0; // double cosineSimilarity = 0.0; // // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // dotProduct += vector1[i] * vector2[i]; // v1 += Math.pow(vector1[i], 2); // v2 += Math.pow(vector2[i], 2); // } // // v1 = Math.sqrt(v1); // v2 = Math.sqrt(v2); // // if (v1 != 0.0 && v2 != 0.0) { // cosineSimilarity = dotProduct / (v1 * v2); // } else { // return 0; // } // return cosineSimilarity; // } // public static Random r=new Random(); // // public static double dotProd(double[] vector1, double[] vector2) { // double dotProduct = 0.0; // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // dotProduct += vector1[i] * vector2[i]; // } // return dotProduct; // } // // public static double[] elemWiseProd(double[] vector1, double[] vector2) { // double[] Product = new double[vector1.length]; // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // Product[i] = vector1[i] * vector2[i]; // } // return Product; // } // // public static int hashInteger(int i, int max) { // r.setSeed(i); // return r.nextInt(max); // } // // public static int hashIntegerPair(int i, int j, int max) { // return hashInteger(31*i+j, max); // } // // static class Pair { // int a; // int b; // static int max; // public Pair(int a, int b) { // this.a = a; // this.b = b; // } // @Override // public int hashCode() { // int aa = a > b ? a:b; // int bb = a > b ? b:a; // return aa * max + bb; // } // @Override // public boolean equals(Object o) { // Pair c = (Pair) o; // return a == c.a && b == c.b || a == c.b && b == c.a; // } // } // // // public static void main(String[] args) throws IOException{ // Thesaurus t = new ThesaurusImp(new File("data/Rogets/antonym.txt"), new File("data/Rogets/synonym.txt"), new File("data/Rogets/vocabulary.txt")); // } // } // // Path: src/edu/antonym/prototype/MetricEvaluator.java // public interface MetricEvaluator { // public double score(WordMetric metric) throws IOException; // } // // Path: src/edu/antonym/prototype/Thesaurus.java // public interface Thesaurus { // public interface Entry { // public int word1(); // public int word2(); // public boolean isAntonym(); // } // public Vocabulary getVocab(); // // //Returns the words included in the Thesaurus // public int numEntries(); // public int numSynonyms(); // public int numAntonyms(); // public Entry getEntry(int entryn); // // public int lookupEntry(int word1, int word2, boolean isAnt); // // // public boolean isAntonym(int word1, int word2); // public boolean isSynonym(int word1, int word2); // } // // Path: src/edu/antonym/prototype/Thesaurus.java // public interface Entry { // public int word1(); // public int word2(); // public boolean isAntonym(); // } // // Path: src/edu/antonym/prototype/Vocabulary.java // public interface Vocabulary { // public int size(); // public int OOVindex(); // public String lookupIndex(int index); // public int lookupWord(String word); // public int getVocabSize(); // } // // Path: src/edu/antonym/prototype/WordMetric.java // public interface WordMetric { // public Vocabulary getVocab(); // // public double similarity(int word1, int word2); // }
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.PosixParser; import edu.antonym.Util; import edu.antonym.prototype.MetricEvaluator; import edu.antonym.prototype.Thesaurus; import edu.antonym.prototype.Thesaurus.Entry; import edu.antonym.prototype.Vocabulary; import edu.antonym.prototype.WordMetric;
package edu.antonym.test; public class RandomizedTestCase implements MetricEvaluator { public Thesaurus th; public RandomizedTestCase(Thesaurus th) { this.th = th; } @Override
// Path: src/edu/antonym/Util.java // public class Util { // static void saveVectors(VectorEmbedding embed, Vocabulary vocab, File out) throws FileNotFoundException { // int dim=embed.getDimension(); // // PrintStream ps=new PrintStream(out); // ps.println(dim); // for(int i=0; i<vocab.size(); i++) { // double[] vect=embed.getVectorRep(i); // for(int j=0; j<dim; j++) { // ps.print(vect[j]); // ps.print(' '); // } // ps.println(); // } // ps.close(); // } // // public static double cosineSimilarity(double[] vector1, double[] vector2) { // double dotProduct = 0.0; // double v1 = 0.0; // double v2 = 0.0; // double cosineSimilarity = 0.0; // // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // dotProduct += vector1[i] * vector2[i]; // v1 += Math.pow(vector1[i], 2); // v2 += Math.pow(vector2[i], 2); // } // // v1 = Math.sqrt(v1); // v2 = Math.sqrt(v2); // // if (v1 != 0.0 && v2 != 0.0) { // cosineSimilarity = dotProduct / (v1 * v2); // } else { // return 0; // } // return cosineSimilarity; // } // public static Random r=new Random(); // // public static double dotProd(double[] vector1, double[] vector2) { // double dotProduct = 0.0; // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // dotProduct += vector1[i] * vector2[i]; // } // return dotProduct; // } // // public static double[] elemWiseProd(double[] vector1, double[] vector2) { // double[] Product = new double[vector1.length]; // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // Product[i] = vector1[i] * vector2[i]; // } // return Product; // } // // public static int hashInteger(int i, int max) { // r.setSeed(i); // return r.nextInt(max); // } // // public static int hashIntegerPair(int i, int j, int max) { // return hashInteger(31*i+j, max); // } // // static class Pair { // int a; // int b; // static int max; // public Pair(int a, int b) { // this.a = a; // this.b = b; // } // @Override // public int hashCode() { // int aa = a > b ? a:b; // int bb = a > b ? b:a; // return aa * max + bb; // } // @Override // public boolean equals(Object o) { // Pair c = (Pair) o; // return a == c.a && b == c.b || a == c.b && b == c.a; // } // } // // // public static void main(String[] args) throws IOException{ // Thesaurus t = new ThesaurusImp(new File("data/Rogets/antonym.txt"), new File("data/Rogets/synonym.txt"), new File("data/Rogets/vocabulary.txt")); // } // } // // Path: src/edu/antonym/prototype/MetricEvaluator.java // public interface MetricEvaluator { // public double score(WordMetric metric) throws IOException; // } // // Path: src/edu/antonym/prototype/Thesaurus.java // public interface Thesaurus { // public interface Entry { // public int word1(); // public int word2(); // public boolean isAntonym(); // } // public Vocabulary getVocab(); // // //Returns the words included in the Thesaurus // public int numEntries(); // public int numSynonyms(); // public int numAntonyms(); // public Entry getEntry(int entryn); // // public int lookupEntry(int word1, int word2, boolean isAnt); // // // public boolean isAntonym(int word1, int word2); // public boolean isSynonym(int word1, int word2); // } // // Path: src/edu/antonym/prototype/Thesaurus.java // public interface Entry { // public int word1(); // public int word2(); // public boolean isAntonym(); // } // // Path: src/edu/antonym/prototype/Vocabulary.java // public interface Vocabulary { // public int size(); // public int OOVindex(); // public String lookupIndex(int index); // public int lookupWord(String word); // public int getVocabSize(); // } // // Path: src/edu/antonym/prototype/WordMetric.java // public interface WordMetric { // public Vocabulary getVocab(); // // public double similarity(int word1, int word2); // } // Path: src/edu/antonym/test/RandomizedTestCase.java import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.PosixParser; import edu.antonym.Util; import edu.antonym.prototype.MetricEvaluator; import edu.antonym.prototype.Thesaurus; import edu.antonym.prototype.Thesaurus.Entry; import edu.antonym.prototype.Vocabulary; import edu.antonym.prototype.WordMetric; package edu.antonym.test; public class RandomizedTestCase implements MetricEvaluator { public Thesaurus th; public RandomizedTestCase(Thesaurus th) { this.th = th; } @Override
public double score(WordMetric metric) throws IOException {
antonyms/AntonymPipeline
src/org/jobimtext/example/demo/SensesViewManager.java
// Path: src/org/jobimtext/example/demo/JoBimDemo.java // public static class AnnoLabel { // public String label; // public Annotation anno; // // public AnnoLabel(String label, Annotation anno) { // this.label = label; // this.anno = anno; // } // // public String toString() { // return label; // } // }
import java.util.*; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import org.apache.uima.jcas.tcas.Annotation; import org.jobimtext.api.map.IThesaurusMap; import org.jobimtext.example.demo.JoBimDemo.AnnoLabel; import org.jobimtext.holing.extractor.JobimAnnotationExtractor; import com.ibm.bluej.util.common.*; import com.ibm.bluej.util.common.visualization.*;
package org.jobimtext.example.demo; public class SensesViewManager implements TreeSelectionListener { private BasicJTree jobimView; private BasicJTree view; private IThesaurusMap<String, String> dt; private JobimAnnotationExtractor extractor; public SensesViewManager( BasicJTree jobimView, BasicJTree view, IThesaurusMap<String, String> dt, JobimAnnotationExtractor extractor) { this.jobimView = jobimView; this.view = view; this.dt = dt; this.extractor = extractor; } public void valueChanged(TreeSelectionEvent event) { /*if (dt.getSenses() == null || dt.getPriors() == null) { view.top.removeAllChildren(); view.refresh(null); return; }*/ // remove highlights from sentence DefaultMutableTreeNode node = (DefaultMutableTreeNode) jobimView .getLastSelectedPathComponent(); // if nothing is selected if (node == null) { view.top.removeAllChildren(); view.refresh(null); return; } try {
// Path: src/org/jobimtext/example/demo/JoBimDemo.java // public static class AnnoLabel { // public String label; // public Annotation anno; // // public AnnoLabel(String label, Annotation anno) { // this.label = label; // this.anno = anno; // } // // public String toString() { // return label; // } // } // Path: src/org/jobimtext/example/demo/SensesViewManager.java import java.util.*; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import org.apache.uima.jcas.tcas.Annotation; import org.jobimtext.api.map.IThesaurusMap; import org.jobimtext.example.demo.JoBimDemo.AnnoLabel; import org.jobimtext.holing.extractor.JobimAnnotationExtractor; import com.ibm.bluej.util.common.*; import com.ibm.bluej.util.common.visualization.*; package org.jobimtext.example.demo; public class SensesViewManager implements TreeSelectionListener { private BasicJTree jobimView; private BasicJTree view; private IThesaurusMap<String, String> dt; private JobimAnnotationExtractor extractor; public SensesViewManager( BasicJTree jobimView, BasicJTree view, IThesaurusMap<String, String> dt, JobimAnnotationExtractor extractor) { this.jobimView = jobimView; this.view = view; this.dt = dt; this.extractor = extractor; } public void valueChanged(TreeSelectionEvent event) { /*if (dt.getSenses() == null || dt.getPriors() == null) { view.top.removeAllChildren(); view.refresh(null); return; }*/ // remove highlights from sentence DefaultMutableTreeNode node = (DefaultMutableTreeNode) jobimView .getLastSelectedPathComponent(); // if nothing is selected if (node == null) { view.top.removeAllChildren(); view.refresh(null); return; } try {
if (node.getUserObject() instanceof AnnoLabel) {
antonyms/AntonymPipeline
src/edu/antonym/Util.java
// Path: src/edu/antonym/prototype/Thesaurus.java // public interface Thesaurus { // public interface Entry { // public int word1(); // public int word2(); // public boolean isAntonym(); // } // public Vocabulary getVocab(); // // //Returns the words included in the Thesaurus // public int numEntries(); // public int numSynonyms(); // public int numAntonyms(); // public Entry getEntry(int entryn); // // public int lookupEntry(int word1, int word2, boolean isAnt); // // // public boolean isAntonym(int word1, int word2); // public boolean isSynonym(int word1, int word2); // } // // Path: src/edu/antonym/prototype/Thesaurus.java // public interface Entry { // public int word1(); // public int word2(); // public boolean isAntonym(); // } // // Path: src/edu/antonym/prototype/VectorEmbedding.java // public interface VectorEmbedding extends WordMetric { // // int getDimension(); // public double[] getVectorRep(int word); // public int findClosestWord(double[] vector); // Vocabulary getVocab(); // } // // Path: src/edu/antonym/prototype/Vocabulary.java // public interface Vocabulary { // public int size(); // public int OOVindex(); // public String lookupIndex(int index); // public int lookupWord(String word); // public int getVocabSize(); // }
import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; import edu.antonym.prototype.Thesaurus; import edu.antonym.prototype.Thesaurus.Entry; import edu.antonym.prototype.VectorEmbedding; import edu.antonym.prototype.Vocabulary;
return r.nextInt(max); } public static int hashIntegerPair(int i, int j, int max) { return hashInteger(31*i+j, max); } static class Pair { int a; int b; static int max; public Pair(int a, int b) { this.a = a; this.b = b; } @Override public int hashCode() { int aa = a > b ? a:b; int bb = a > b ? b:a; return aa * max + bb; } @Override public boolean equals(Object o) { Pair c = (Pair) o; return a == c.a && b == c.b || a == c.b && b == c.a; } } public static void main(String[] args) throws IOException{
// Path: src/edu/antonym/prototype/Thesaurus.java // public interface Thesaurus { // public interface Entry { // public int word1(); // public int word2(); // public boolean isAntonym(); // } // public Vocabulary getVocab(); // // //Returns the words included in the Thesaurus // public int numEntries(); // public int numSynonyms(); // public int numAntonyms(); // public Entry getEntry(int entryn); // // public int lookupEntry(int word1, int word2, boolean isAnt); // // // public boolean isAntonym(int word1, int word2); // public boolean isSynonym(int word1, int word2); // } // // Path: src/edu/antonym/prototype/Thesaurus.java // public interface Entry { // public int word1(); // public int word2(); // public boolean isAntonym(); // } // // Path: src/edu/antonym/prototype/VectorEmbedding.java // public interface VectorEmbedding extends WordMetric { // // int getDimension(); // public double[] getVectorRep(int word); // public int findClosestWord(double[] vector); // Vocabulary getVocab(); // } // // Path: src/edu/antonym/prototype/Vocabulary.java // public interface Vocabulary { // public int size(); // public int OOVindex(); // public String lookupIndex(int index); // public int lookupWord(String word); // public int getVocabSize(); // } // Path: src/edu/antonym/Util.java import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; import edu.antonym.prototype.Thesaurus; import edu.antonym.prototype.Thesaurus.Entry; import edu.antonym.prototype.VectorEmbedding; import edu.antonym.prototype.Vocabulary; return r.nextInt(max); } public static int hashIntegerPair(int i, int j, int max) { return hashInteger(31*i+j, max); } static class Pair { int a; int b; static int max; public Pair(int a, int b) { this.a = a; this.b = b; } @Override public int hashCode() { int aa = a > b ? a:b; int bb = a > b ? b:a; return aa * max + bb; } @Override public boolean equals(Object o) { Pair c = (Pair) o; return a == c.a && b == c.b || a == c.b && b == c.a; } } public static void main(String[] args) throws IOException{
Thesaurus t = new ThesaurusImp(new File("data/Rogets/antonym.txt"), new File("data/Rogets/synonym.txt"), new File("data/Rogets/vocabulary.txt"));
antonyms/AntonymPipeline
src/edu/antonym/prototype/SubThesaurus.java
// Path: src/edu/antonym/Util.java // public class Util { // static void saveVectors(VectorEmbedding embed, Vocabulary vocab, File out) throws FileNotFoundException { // int dim=embed.getDimension(); // // PrintStream ps=new PrintStream(out); // ps.println(dim); // for(int i=0; i<vocab.size(); i++) { // double[] vect=embed.getVectorRep(i); // for(int j=0; j<dim; j++) { // ps.print(vect[j]); // ps.print(' '); // } // ps.println(); // } // ps.close(); // } // // public static double cosineSimilarity(double[] vector1, double[] vector2) { // double dotProduct = 0.0; // double v1 = 0.0; // double v2 = 0.0; // double cosineSimilarity = 0.0; // // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // dotProduct += vector1[i] * vector2[i]; // v1 += Math.pow(vector1[i], 2); // v2 += Math.pow(vector2[i], 2); // } // // v1 = Math.sqrt(v1); // v2 = Math.sqrt(v2); // // if (v1 != 0.0 && v2 != 0.0) { // cosineSimilarity = dotProduct / (v1 * v2); // } else { // return 0; // } // return cosineSimilarity; // } // public static Random r=new Random(); // // public static double dotProd(double[] vector1, double[] vector2) { // double dotProduct = 0.0; // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // dotProduct += vector1[i] * vector2[i]; // } // return dotProduct; // } // // public static double[] elemWiseProd(double[] vector1, double[] vector2) { // double[] Product = new double[vector1.length]; // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // Product[i] = vector1[i] * vector2[i]; // } // return Product; // } // // public static int hashInteger(int i, int max) { // r.setSeed(i); // return r.nextInt(max); // } // // public static int hashIntegerPair(int i, int j, int max) { // return hashInteger(31*i+j, max); // } // // static class Pair { // int a; // int b; // static int max; // public Pair(int a, int b) { // this.a = a; // this.b = b; // } // @Override // public int hashCode() { // int aa = a > b ? a:b; // int bb = a > b ? b:a; // return aa * max + bb; // } // @Override // public boolean equals(Object o) { // Pair c = (Pair) o; // return a == c.a && b == c.b || a == c.b && b == c.a; // } // } // // // public static void main(String[] args) throws IOException{ // Thesaurus t = new ThesaurusImp(new File("data/Rogets/antonym.txt"), new File("data/Rogets/synonym.txt"), new File("data/Rogets/vocabulary.txt")); // } // }
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import edu.antonym.Util;
public int numEntries() { return indices.size(); } @Override public Entry getEntry(int entryn) { return parent.getEntry(indices.get(entryn)); } @Override public boolean isAntonym(int word1, int word2) { return lookupEntry(word1, word2, true)>=0; } @Override public boolean isSynonym(int word1, int word2) { return lookupEntry(word1, word2, false)>=0; } @Override public int lookupEntry(int word1, int word2, boolean isAnt) { int ent=parent.lookupEntry(word1, word2, isAnt); return Collections.binarySearch(indices, ent); } //Samples a subthesaurus with n entries public static Thesaurus SampleThesaurus(Thesaurus th, int n) { int thsize=th.numEntries(); List<Integer> sample=new ArrayList<Integer>(n); for(int i=0; i<n; i++) {
// Path: src/edu/antonym/Util.java // public class Util { // static void saveVectors(VectorEmbedding embed, Vocabulary vocab, File out) throws FileNotFoundException { // int dim=embed.getDimension(); // // PrintStream ps=new PrintStream(out); // ps.println(dim); // for(int i=0; i<vocab.size(); i++) { // double[] vect=embed.getVectorRep(i); // for(int j=0; j<dim; j++) { // ps.print(vect[j]); // ps.print(' '); // } // ps.println(); // } // ps.close(); // } // // public static double cosineSimilarity(double[] vector1, double[] vector2) { // double dotProduct = 0.0; // double v1 = 0.0; // double v2 = 0.0; // double cosineSimilarity = 0.0; // // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // dotProduct += vector1[i] * vector2[i]; // v1 += Math.pow(vector1[i], 2); // v2 += Math.pow(vector2[i], 2); // } // // v1 = Math.sqrt(v1); // v2 = Math.sqrt(v2); // // if (v1 != 0.0 && v2 != 0.0) { // cosineSimilarity = dotProduct / (v1 * v2); // } else { // return 0; // } // return cosineSimilarity; // } // public static Random r=new Random(); // // public static double dotProd(double[] vector1, double[] vector2) { // double dotProduct = 0.0; // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // dotProduct += vector1[i] * vector2[i]; // } // return dotProduct; // } // // public static double[] elemWiseProd(double[] vector1, double[] vector2) { // double[] Product = new double[vector1.length]; // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // Product[i] = vector1[i] * vector2[i]; // } // return Product; // } // // public static int hashInteger(int i, int max) { // r.setSeed(i); // return r.nextInt(max); // } // // public static int hashIntegerPair(int i, int j, int max) { // return hashInteger(31*i+j, max); // } // // static class Pair { // int a; // int b; // static int max; // public Pair(int a, int b) { // this.a = a; // this.b = b; // } // @Override // public int hashCode() { // int aa = a > b ? a:b; // int bb = a > b ? b:a; // return aa * max + bb; // } // @Override // public boolean equals(Object o) { // Pair c = (Pair) o; // return a == c.a && b == c.b || a == c.b && b == c.a; // } // } // // // public static void main(String[] args) throws IOException{ // Thesaurus t = new ThesaurusImp(new File("data/Rogets/antonym.txt"), new File("data/Rogets/synonym.txt"), new File("data/Rogets/vocabulary.txt")); // } // } // Path: src/edu/antonym/prototype/SubThesaurus.java import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import edu.antonym.Util; public int numEntries() { return indices.size(); } @Override public Entry getEntry(int entryn) { return parent.getEntry(indices.get(entryn)); } @Override public boolean isAntonym(int word1, int word2) { return lookupEntry(word1, word2, true)>=0; } @Override public boolean isSynonym(int word1, int word2) { return lookupEntry(word1, word2, false)>=0; } @Override public int lookupEntry(int word1, int word2, boolean isAnt) { int ent=parent.lookupEntry(word1, word2, isAnt); return Collections.binarySearch(indices, ent); } //Samples a subthesaurus with n entries public static Thesaurus SampleThesaurus(Thesaurus th, int n) { int thsize=th.numEntries(); List<Integer> sample=new ArrayList<Integer>(n); for(int i=0; i<n; i++) {
sample.add(Util.r.nextInt(thsize));
antonyms/AntonymPipeline
src/org/jobimtext/example/demo/CustomViewManager.java
// Path: src/org/jobimtext/example/demo/JoBimDemo.java // public static class AnnoLabel { // public String label; // public Annotation anno; // // public AnnoLabel(String label, Annotation anno) { // this.label = label; // this.anno = anno; // } // // public String toString() { // return label; // } // }
import java.util.ArrayList; import java.util.Map; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import org.apache.uima.jcas.tcas.Annotation; import org.jobimtext.api.map.IThesaurusMap; import org.jobimtext.example.demo.JoBimDemo.AnnoLabel; import org.jobimtext.holing.extractor.JobimAnnotationExtractor; import org.jobimtext.holing.type.JoBim; import com.ibm.bluej.util.common.visualization.BasicJTree;
package org.jobimtext.example.demo; public abstract class CustomViewManager implements TreeSelectionListener { public abstract String getTabName();
// Path: src/org/jobimtext/example/demo/JoBimDemo.java // public static class AnnoLabel { // public String label; // public Annotation anno; // // public AnnoLabel(String label, Annotation anno) { // this.label = label; // this.anno = anno; // } // // public String toString() { // return label; // } // } // Path: src/org/jobimtext/example/demo/CustomViewManager.java import java.util.ArrayList; import java.util.Map; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import org.apache.uima.jcas.tcas.Annotation; import org.jobimtext.api.map.IThesaurusMap; import org.jobimtext.example.demo.JoBimDemo.AnnoLabel; import org.jobimtext.holing.extractor.JobimAnnotationExtractor; import org.jobimtext.holing.type.JoBim; import com.ibm.bluej.util.common.visualization.BasicJTree; package org.jobimtext.example.demo; public abstract class CustomViewManager implements TreeSelectionListener { public abstract String getTabName();
public abstract void changedSelectedJo(AnnoLabel a);
antonyms/AntonymPipeline
src/edu/antonym/ThesaurusImp.java
// Path: src/edu/antonym/prototype/Thesaurus.java // public interface Thesaurus { // public interface Entry { // public int word1(); // public int word2(); // public boolean isAntonym(); // } // public Vocabulary getVocab(); // // //Returns the words included in the Thesaurus // public int numEntries(); // public int numSynonyms(); // public int numAntonyms(); // public Entry getEntry(int entryn); // // public int lookupEntry(int word1, int word2, boolean isAnt); // // // public boolean isAntonym(int word1, int word2); // public boolean isSynonym(int word1, int word2); // } // // Path: src/edu/antonym/prototype/Vocabulary.java // public interface Vocabulary { // public int size(); // public int OOVindex(); // public String lookupIndex(int index); // public int lookupWord(String word); // public int getVocabSize(); // }
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; import edu.antonym.prototype.Thesaurus; import edu.antonym.prototype.Vocabulary;
package edu.antonym; public class ThesaurusImp implements Thesaurus{ Map<Integer, List<Integer>> lookUpAntonym; Map<Integer, List<Integer>> lookUpSynonym; List<Integer> entries;
// Path: src/edu/antonym/prototype/Thesaurus.java // public interface Thesaurus { // public interface Entry { // public int word1(); // public int word2(); // public boolean isAntonym(); // } // public Vocabulary getVocab(); // // //Returns the words included in the Thesaurus // public int numEntries(); // public int numSynonyms(); // public int numAntonyms(); // public Entry getEntry(int entryn); // // public int lookupEntry(int word1, int word2, boolean isAnt); // // // public boolean isAntonym(int word1, int word2); // public boolean isSynonym(int word1, int word2); // } // // Path: src/edu/antonym/prototype/Vocabulary.java // public interface Vocabulary { // public int size(); // public int OOVindex(); // public String lookupIndex(int index); // public int lookupWord(String word); // public int getVocabSize(); // } // Path: src/edu/antonym/ThesaurusImp.java import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.Set; import edu.antonym.prototype.Thesaurus; import edu.antonym.prototype.Vocabulary; package edu.antonym; public class ThesaurusImp implements Thesaurus{ Map<Integer, List<Integer>> lookUpAntonym; Map<Integer, List<Integer>> lookUpSynonym; List<Integer> entries;
Vocabulary vocab;
antonyms/AntonymPipeline
src/edu/antonym/test/TestCase2.java
// Path: src/edu/antonym/Util.java // public class Util { // static void saveVectors(VectorEmbedding embed, Vocabulary vocab, File out) throws FileNotFoundException { // int dim=embed.getDimension(); // // PrintStream ps=new PrintStream(out); // ps.println(dim); // for(int i=0; i<vocab.size(); i++) { // double[] vect=embed.getVectorRep(i); // for(int j=0; j<dim; j++) { // ps.print(vect[j]); // ps.print(' '); // } // ps.println(); // } // ps.close(); // } // // public static double cosineSimilarity(double[] vector1, double[] vector2) { // double dotProduct = 0.0; // double v1 = 0.0; // double v2 = 0.0; // double cosineSimilarity = 0.0; // // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // dotProduct += vector1[i] * vector2[i]; // v1 += Math.pow(vector1[i], 2); // v2 += Math.pow(vector2[i], 2); // } // // v1 = Math.sqrt(v1); // v2 = Math.sqrt(v2); // // if (v1 != 0.0 && v2 != 0.0) { // cosineSimilarity = dotProduct / (v1 * v2); // } else { // return 0; // } // return cosineSimilarity; // } // public static Random r=new Random(); // // public static double dotProd(double[] vector1, double[] vector2) { // double dotProduct = 0.0; // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // dotProduct += vector1[i] * vector2[i]; // } // return dotProduct; // } // // public static double[] elemWiseProd(double[] vector1, double[] vector2) { // double[] Product = new double[vector1.length]; // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // Product[i] = vector1[i] * vector2[i]; // } // return Product; // } // // public static int hashInteger(int i, int max) { // r.setSeed(i); // return r.nextInt(max); // } // // public static int hashIntegerPair(int i, int j, int max) { // return hashInteger(31*i+j, max); // } // // static class Pair { // int a; // int b; // static int max; // public Pair(int a, int b) { // this.a = a; // this.b = b; // } // @Override // public int hashCode() { // int aa = a > b ? a:b; // int bb = a > b ? b:a; // return aa * max + bb; // } // @Override // public boolean equals(Object o) { // Pair c = (Pair) o; // return a == c.a && b == c.b || a == c.b && b == c.a; // } // } // // // public static void main(String[] args) throws IOException{ // Thesaurus t = new ThesaurusImp(new File("data/Rogets/antonym.txt"), new File("data/Rogets/synonym.txt"), new File("data/Rogets/vocabulary.txt")); // } // } // // Path: src/edu/antonym/prototype/MetricEvaluator.java // public interface MetricEvaluator { // public double score(WordMetric metric) throws IOException; // } // // Path: src/edu/antonym/prototype/VectorEmbedding.java // public interface VectorEmbedding extends WordMetric { // // int getDimension(); // public double[] getVectorRep(int word); // public int findClosestWord(double[] vector); // Vocabulary getVocab(); // } // // Path: src/edu/antonym/prototype/Vocabulary.java // public interface Vocabulary { // public int size(); // public int OOVindex(); // public String lookupIndex(int index); // public int lookupWord(String word); // public int getVocabSize(); // } // // Path: src/edu/antonym/prototype/WordMetric.java // public interface WordMetric { // public Vocabulary getVocab(); // // public double similarity(int word1, int word2); // }
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import edu.antonym.Util; import edu.antonym.prototype.MetricEvaluator; import edu.antonym.prototype.VectorEmbedding; import edu.antonym.prototype.Vocabulary; import edu.antonym.prototype.WordMetric;
package edu.antonym.test; /** * This is the test case for synonyms, syn0.txt and syn1.txt. Each line * represents one single test. Each two words of a line are compared. Mean * squared error of synonym is also measured at the last. syn: 1 * */ public class TestCase2 implements MetricEvaluator { @Override
// Path: src/edu/antonym/Util.java // public class Util { // static void saveVectors(VectorEmbedding embed, Vocabulary vocab, File out) throws FileNotFoundException { // int dim=embed.getDimension(); // // PrintStream ps=new PrintStream(out); // ps.println(dim); // for(int i=0; i<vocab.size(); i++) { // double[] vect=embed.getVectorRep(i); // for(int j=0; j<dim; j++) { // ps.print(vect[j]); // ps.print(' '); // } // ps.println(); // } // ps.close(); // } // // public static double cosineSimilarity(double[] vector1, double[] vector2) { // double dotProduct = 0.0; // double v1 = 0.0; // double v2 = 0.0; // double cosineSimilarity = 0.0; // // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // dotProduct += vector1[i] * vector2[i]; // v1 += Math.pow(vector1[i], 2); // v2 += Math.pow(vector2[i], 2); // } // // v1 = Math.sqrt(v1); // v2 = Math.sqrt(v2); // // if (v1 != 0.0 && v2 != 0.0) { // cosineSimilarity = dotProduct / (v1 * v2); // } else { // return 0; // } // return cosineSimilarity; // } // public static Random r=new Random(); // // public static double dotProd(double[] vector1, double[] vector2) { // double dotProduct = 0.0; // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // dotProduct += vector1[i] * vector2[i]; // } // return dotProduct; // } // // public static double[] elemWiseProd(double[] vector1, double[] vector2) { // double[] Product = new double[vector1.length]; // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // Product[i] = vector1[i] * vector2[i]; // } // return Product; // } // // public static int hashInteger(int i, int max) { // r.setSeed(i); // return r.nextInt(max); // } // // public static int hashIntegerPair(int i, int j, int max) { // return hashInteger(31*i+j, max); // } // // static class Pair { // int a; // int b; // static int max; // public Pair(int a, int b) { // this.a = a; // this.b = b; // } // @Override // public int hashCode() { // int aa = a > b ? a:b; // int bb = a > b ? b:a; // return aa * max + bb; // } // @Override // public boolean equals(Object o) { // Pair c = (Pair) o; // return a == c.a && b == c.b || a == c.b && b == c.a; // } // } // // // public static void main(String[] args) throws IOException{ // Thesaurus t = new ThesaurusImp(new File("data/Rogets/antonym.txt"), new File("data/Rogets/synonym.txt"), new File("data/Rogets/vocabulary.txt")); // } // } // // Path: src/edu/antonym/prototype/MetricEvaluator.java // public interface MetricEvaluator { // public double score(WordMetric metric) throws IOException; // } // // Path: src/edu/antonym/prototype/VectorEmbedding.java // public interface VectorEmbedding extends WordMetric { // // int getDimension(); // public double[] getVectorRep(int word); // public int findClosestWord(double[] vector); // Vocabulary getVocab(); // } // // Path: src/edu/antonym/prototype/Vocabulary.java // public interface Vocabulary { // public int size(); // public int OOVindex(); // public String lookupIndex(int index); // public int lookupWord(String word); // public int getVocabSize(); // } // // Path: src/edu/antonym/prototype/WordMetric.java // public interface WordMetric { // public Vocabulary getVocab(); // // public double similarity(int word1, int word2); // } // Path: src/edu/antonym/test/TestCase2.java import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import edu.antonym.Util; import edu.antonym.prototype.MetricEvaluator; import edu.antonym.prototype.VectorEmbedding; import edu.antonym.prototype.Vocabulary; import edu.antonym.prototype.WordMetric; package edu.antonym.test; /** * This is the test case for synonyms, syn0.txt and syn1.txt. Each line * represents one single test. Each two words of a line are compared. Mean * squared error of synonym is also measured at the last. syn: 1 * */ public class TestCase2 implements MetricEvaluator { @Override
public double score(WordMetric metric) throws IOException {
antonyms/AntonymPipeline
src/edu/antonym/test/TestCase2.java
// Path: src/edu/antonym/Util.java // public class Util { // static void saveVectors(VectorEmbedding embed, Vocabulary vocab, File out) throws FileNotFoundException { // int dim=embed.getDimension(); // // PrintStream ps=new PrintStream(out); // ps.println(dim); // for(int i=0; i<vocab.size(); i++) { // double[] vect=embed.getVectorRep(i); // for(int j=0; j<dim; j++) { // ps.print(vect[j]); // ps.print(' '); // } // ps.println(); // } // ps.close(); // } // // public static double cosineSimilarity(double[] vector1, double[] vector2) { // double dotProduct = 0.0; // double v1 = 0.0; // double v2 = 0.0; // double cosineSimilarity = 0.0; // // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // dotProduct += vector1[i] * vector2[i]; // v1 += Math.pow(vector1[i], 2); // v2 += Math.pow(vector2[i], 2); // } // // v1 = Math.sqrt(v1); // v2 = Math.sqrt(v2); // // if (v1 != 0.0 && v2 != 0.0) { // cosineSimilarity = dotProduct / (v1 * v2); // } else { // return 0; // } // return cosineSimilarity; // } // public static Random r=new Random(); // // public static double dotProd(double[] vector1, double[] vector2) { // double dotProduct = 0.0; // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // dotProduct += vector1[i] * vector2[i]; // } // return dotProduct; // } // // public static double[] elemWiseProd(double[] vector1, double[] vector2) { // double[] Product = new double[vector1.length]; // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // Product[i] = vector1[i] * vector2[i]; // } // return Product; // } // // public static int hashInteger(int i, int max) { // r.setSeed(i); // return r.nextInt(max); // } // // public static int hashIntegerPair(int i, int j, int max) { // return hashInteger(31*i+j, max); // } // // static class Pair { // int a; // int b; // static int max; // public Pair(int a, int b) { // this.a = a; // this.b = b; // } // @Override // public int hashCode() { // int aa = a > b ? a:b; // int bb = a > b ? b:a; // return aa * max + bb; // } // @Override // public boolean equals(Object o) { // Pair c = (Pair) o; // return a == c.a && b == c.b || a == c.b && b == c.a; // } // } // // // public static void main(String[] args) throws IOException{ // Thesaurus t = new ThesaurusImp(new File("data/Rogets/antonym.txt"), new File("data/Rogets/synonym.txt"), new File("data/Rogets/vocabulary.txt")); // } // } // // Path: src/edu/antonym/prototype/MetricEvaluator.java // public interface MetricEvaluator { // public double score(WordMetric metric) throws IOException; // } // // Path: src/edu/antonym/prototype/VectorEmbedding.java // public interface VectorEmbedding extends WordMetric { // // int getDimension(); // public double[] getVectorRep(int word); // public int findClosestWord(double[] vector); // Vocabulary getVocab(); // } // // Path: src/edu/antonym/prototype/Vocabulary.java // public interface Vocabulary { // public int size(); // public int OOVindex(); // public String lookupIndex(int index); // public int lookupWord(String word); // public int getVocabSize(); // } // // Path: src/edu/antonym/prototype/WordMetric.java // public interface WordMetric { // public Vocabulary getVocab(); // // public double similarity(int word1, int word2); // }
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import edu.antonym.Util; import edu.antonym.prototype.MetricEvaluator; import edu.antonym.prototype.VectorEmbedding; import edu.antonym.prototype.Vocabulary; import edu.antonym.prototype.WordMetric;
package edu.antonym.test; /** * This is the test case for synonyms, syn0.txt and syn1.txt. Each line * represents one single test. Each two words of a line are compared. Mean * squared error of synonym is also measured at the last. syn: 1 * */ public class TestCase2 implements MetricEvaluator { @Override public double score(WordMetric metric) throws IOException { String test_folder = "data/test-data/"; String result_folder = "data/result-data/"; new File(result_folder).mkdirs(); String syn0 = "syn0.txt"; String syn1 = "syn1.txt"; ArrayList<String> syns = new ArrayList<String>(); double acc = 0.0d; syns.add(syn0); syns.add(syn1); // add more file if needed
// Path: src/edu/antonym/Util.java // public class Util { // static void saveVectors(VectorEmbedding embed, Vocabulary vocab, File out) throws FileNotFoundException { // int dim=embed.getDimension(); // // PrintStream ps=new PrintStream(out); // ps.println(dim); // for(int i=0; i<vocab.size(); i++) { // double[] vect=embed.getVectorRep(i); // for(int j=0; j<dim; j++) { // ps.print(vect[j]); // ps.print(' '); // } // ps.println(); // } // ps.close(); // } // // public static double cosineSimilarity(double[] vector1, double[] vector2) { // double dotProduct = 0.0; // double v1 = 0.0; // double v2 = 0.0; // double cosineSimilarity = 0.0; // // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // dotProduct += vector1[i] * vector2[i]; // v1 += Math.pow(vector1[i], 2); // v2 += Math.pow(vector2[i], 2); // } // // v1 = Math.sqrt(v1); // v2 = Math.sqrt(v2); // // if (v1 != 0.0 && v2 != 0.0) { // cosineSimilarity = dotProduct / (v1 * v2); // } else { // return 0; // } // return cosineSimilarity; // } // public static Random r=new Random(); // // public static double dotProd(double[] vector1, double[] vector2) { // double dotProduct = 0.0; // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // dotProduct += vector1[i] * vector2[i]; // } // return dotProduct; // } // // public static double[] elemWiseProd(double[] vector1, double[] vector2) { // double[] Product = new double[vector1.length]; // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // Product[i] = vector1[i] * vector2[i]; // } // return Product; // } // // public static int hashInteger(int i, int max) { // r.setSeed(i); // return r.nextInt(max); // } // // public static int hashIntegerPair(int i, int j, int max) { // return hashInteger(31*i+j, max); // } // // static class Pair { // int a; // int b; // static int max; // public Pair(int a, int b) { // this.a = a; // this.b = b; // } // @Override // public int hashCode() { // int aa = a > b ? a:b; // int bb = a > b ? b:a; // return aa * max + bb; // } // @Override // public boolean equals(Object o) { // Pair c = (Pair) o; // return a == c.a && b == c.b || a == c.b && b == c.a; // } // } // // // public static void main(String[] args) throws IOException{ // Thesaurus t = new ThesaurusImp(new File("data/Rogets/antonym.txt"), new File("data/Rogets/synonym.txt"), new File("data/Rogets/vocabulary.txt")); // } // } // // Path: src/edu/antonym/prototype/MetricEvaluator.java // public interface MetricEvaluator { // public double score(WordMetric metric) throws IOException; // } // // Path: src/edu/antonym/prototype/VectorEmbedding.java // public interface VectorEmbedding extends WordMetric { // // int getDimension(); // public double[] getVectorRep(int word); // public int findClosestWord(double[] vector); // Vocabulary getVocab(); // } // // Path: src/edu/antonym/prototype/Vocabulary.java // public interface Vocabulary { // public int size(); // public int OOVindex(); // public String lookupIndex(int index); // public int lookupWord(String word); // public int getVocabSize(); // } // // Path: src/edu/antonym/prototype/WordMetric.java // public interface WordMetric { // public Vocabulary getVocab(); // // public double similarity(int word1, int word2); // } // Path: src/edu/antonym/test/TestCase2.java import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import edu.antonym.Util; import edu.antonym.prototype.MetricEvaluator; import edu.antonym.prototype.VectorEmbedding; import edu.antonym.prototype.Vocabulary; import edu.antonym.prototype.WordMetric; package edu.antonym.test; /** * This is the test case for synonyms, syn0.txt and syn1.txt. Each line * represents one single test. Each two words of a line are compared. Mean * squared error of synonym is also measured at the last. syn: 1 * */ public class TestCase2 implements MetricEvaluator { @Override public double score(WordMetric metric) throws IOException { String test_folder = "data/test-data/"; String result_folder = "data/result-data/"; new File(result_folder).mkdirs(); String syn0 = "syn0.txt"; String syn1 = "syn1.txt"; ArrayList<String> syns = new ArrayList<String>(); double acc = 0.0d; syns.add(syn0); syns.add(syn1); // add more file if needed
Vocabulary vocab = metric.getVocab();
antonyms/AntonymPipeline
src/edu/antonym/test/TestCaseMCMC.java
// Path: src/edu/antonym/prototype/MetricEvaluator.java // public interface MetricEvaluator { // public double score(WordMetric metric) throws IOException; // } // // Path: src/edu/antonym/prototype/Vocabulary.java // public interface Vocabulary { // public int size(); // public int OOVindex(); // public String lookupIndex(int index); // public int lookupWord(String word); // public int getVocabSize(); // } // // Path: src/edu/antonym/prototype/WordMetric.java // public interface WordMetric { // public Vocabulary getVocab(); // // public double similarity(int word1, int word2); // }
import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; import edu.antonym.prototype.MetricEvaluator; import edu.antonym.prototype.Vocabulary; import edu.antonym.prototype.WordMetric;
package edu.antonym.test; public class TestCaseMCMC implements MetricEvaluator { /* * important notes: adjust n or gamma if you want the algorithm to go faster * * Example usage: * TestCaseMCMC n = new TestCaseMCMC(input); * ArrayList<ArrayList<String>> r = n.get2cluster(metric); * // print out result cluster 1, cluster 2, word not found * for(int i=0;i<r.size();i++){ * for(int j=0;j<r.get(i).size();j++){ * System.out.print(r.get(i).get(j)+" "); * } * System.out.println(); * } */ public ArrayList<String> wordsense = new ArrayList<String>(); public TestCaseMCMC(ArrayList<String> input){ wordsense = new ArrayList<String>(input); } @Override
// Path: src/edu/antonym/prototype/MetricEvaluator.java // public interface MetricEvaluator { // public double score(WordMetric metric) throws IOException; // } // // Path: src/edu/antonym/prototype/Vocabulary.java // public interface Vocabulary { // public int size(); // public int OOVindex(); // public String lookupIndex(int index); // public int lookupWord(String word); // public int getVocabSize(); // } // // Path: src/edu/antonym/prototype/WordMetric.java // public interface WordMetric { // public Vocabulary getVocab(); // // public double similarity(int word1, int word2); // } // Path: src/edu/antonym/test/TestCaseMCMC.java import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; import edu.antonym.prototype.MetricEvaluator; import edu.antonym.prototype.Vocabulary; import edu.antonym.prototype.WordMetric; package edu.antonym.test; public class TestCaseMCMC implements MetricEvaluator { /* * important notes: adjust n or gamma if you want the algorithm to go faster * * Example usage: * TestCaseMCMC n = new TestCaseMCMC(input); * ArrayList<ArrayList<String>> r = n.get2cluster(metric); * // print out result cluster 1, cluster 2, word not found * for(int i=0;i<r.size();i++){ * for(int j=0;j<r.get(i).size();j++){ * System.out.print(r.get(i).get(j)+" "); * } * System.out.println(); * } */ public ArrayList<String> wordsense = new ArrayList<String>(); public TestCaseMCMC(ArrayList<String> input){ wordsense = new ArrayList<String>(input); } @Override
public double score(WordMetric metric) throws IOException {
antonyms/AntonymPipeline
src/edu/antonym/test/TestCaseMCMC.java
// Path: src/edu/antonym/prototype/MetricEvaluator.java // public interface MetricEvaluator { // public double score(WordMetric metric) throws IOException; // } // // Path: src/edu/antonym/prototype/Vocabulary.java // public interface Vocabulary { // public int size(); // public int OOVindex(); // public String lookupIndex(int index); // public int lookupWord(String word); // public int getVocabSize(); // } // // Path: src/edu/antonym/prototype/WordMetric.java // public interface WordMetric { // public Vocabulary getVocab(); // // public double similarity(int word1, int word2); // }
import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; import edu.antonym.prototype.MetricEvaluator; import edu.antonym.prototype.Vocabulary; import edu.antonym.prototype.WordMetric;
package edu.antonym.test; public class TestCaseMCMC implements MetricEvaluator { /* * important notes: adjust n or gamma if you want the algorithm to go faster * * Example usage: * TestCaseMCMC n = new TestCaseMCMC(input); * ArrayList<ArrayList<String>> r = n.get2cluster(metric); * // print out result cluster 1, cluster 2, word not found * for(int i=0;i<r.size();i++){ * for(int j=0;j<r.get(i).size();j++){ * System.out.print(r.get(i).get(j)+" "); * } * System.out.println(); * } */ public ArrayList<String> wordsense = new ArrayList<String>(); public TestCaseMCMC(ArrayList<String> input){ wordsense = new ArrayList<String>(input); } @Override public double score(WordMetric metric) throws IOException { // TODO Auto-generated method stub return 0; } public ArrayList<ArrayList<String>> get2cluster(WordMetric metric) throws IOException{
// Path: src/edu/antonym/prototype/MetricEvaluator.java // public interface MetricEvaluator { // public double score(WordMetric metric) throws IOException; // } // // Path: src/edu/antonym/prototype/Vocabulary.java // public interface Vocabulary { // public int size(); // public int OOVindex(); // public String lookupIndex(int index); // public int lookupWord(String word); // public int getVocabSize(); // } // // Path: src/edu/antonym/prototype/WordMetric.java // public interface WordMetric { // public Vocabulary getVocab(); // // public double similarity(int word1, int word2); // } // Path: src/edu/antonym/test/TestCaseMCMC.java import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; import edu.antonym.prototype.MetricEvaluator; import edu.antonym.prototype.Vocabulary; import edu.antonym.prototype.WordMetric; package edu.antonym.test; public class TestCaseMCMC implements MetricEvaluator { /* * important notes: adjust n or gamma if you want the algorithm to go faster * * Example usage: * TestCaseMCMC n = new TestCaseMCMC(input); * ArrayList<ArrayList<String>> r = n.get2cluster(metric); * // print out result cluster 1, cluster 2, word not found * for(int i=0;i<r.size();i++){ * for(int j=0;j<r.get(i).size();j++){ * System.out.print(r.get(i).get(j)+" "); * } * System.out.println(); * } */ public ArrayList<String> wordsense = new ArrayList<String>(); public TestCaseMCMC(ArrayList<String> input){ wordsense = new ArrayList<String>(input); } @Override public double score(WordMetric metric) throws IOException { // TODO Auto-generated method stub return 0; } public ArrayList<ArrayList<String>> get2cluster(WordMetric metric) throws IOException{
Vocabulary vocab = metric.getVocab();
antonyms/AntonymPipeline
src/edu/antonym/test/TestCase.java
// Path: src/edu/antonym/prototype/MetricEvaluator.java // public interface MetricEvaluator { // public double score(WordMetric metric) throws IOException; // } // // Path: src/edu/antonym/prototype/Vocabulary.java // public interface Vocabulary { // public int size(); // public int OOVindex(); // public String lookupIndex(int index); // public int lookupWord(String word); // public int getVocabSize(); // } // // Path: src/edu/antonym/prototype/WordMetric.java // public interface WordMetric { // public Vocabulary getVocab(); // // public double similarity(int word1, int word2); // }
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.PosixParser; import edu.antonym.prototype.MetricEvaluator; import edu.antonym.prototype.Vocabulary; import edu.antonym.prototype.WordMetric;
} } } if(cmd.hasOption("a")){ String path[] = cmd.getOptionValues("a"); for(int j=0;j<path.length;j++){ try{ FileInputStream f = new FileInputStream(path[j]); antfiles.add(path[j]); }catch(FileNotFoundException e){ System.out.println("File not found, exit"); System.exit(0); } } } if(cmd.hasOption("h")){ showHelp(options); } if((!cmd.hasOption("h"))&&(!cmd.hasOption("a"))&&(!cmd.hasOption("s"))){ showHelp(options); } } catch (Exception e) { e.printStackTrace(); showHelp(options); } } @Override
// Path: src/edu/antonym/prototype/MetricEvaluator.java // public interface MetricEvaluator { // public double score(WordMetric metric) throws IOException; // } // // Path: src/edu/antonym/prototype/Vocabulary.java // public interface Vocabulary { // public int size(); // public int OOVindex(); // public String lookupIndex(int index); // public int lookupWord(String word); // public int getVocabSize(); // } // // Path: src/edu/antonym/prototype/WordMetric.java // public interface WordMetric { // public Vocabulary getVocab(); // // public double similarity(int word1, int word2); // } // Path: src/edu/antonym/test/TestCase.java import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.PosixParser; import edu.antonym.prototype.MetricEvaluator; import edu.antonym.prototype.Vocabulary; import edu.antonym.prototype.WordMetric; } } } if(cmd.hasOption("a")){ String path[] = cmd.getOptionValues("a"); for(int j=0;j<path.length;j++){ try{ FileInputStream f = new FileInputStream(path[j]); antfiles.add(path[j]); }catch(FileNotFoundException e){ System.out.println("File not found, exit"); System.exit(0); } } } if(cmd.hasOption("h")){ showHelp(options); } if((!cmd.hasOption("h"))&&(!cmd.hasOption("a"))&&(!cmd.hasOption("s"))){ showHelp(options); } } catch (Exception e) { e.printStackTrace(); showHelp(options); } } @Override
public double score(WordMetric metric) throws IOException {
antonyms/AntonymPipeline
src/edu/antonym/test/TestCase.java
// Path: src/edu/antonym/prototype/MetricEvaluator.java // public interface MetricEvaluator { // public double score(WordMetric metric) throws IOException; // } // // Path: src/edu/antonym/prototype/Vocabulary.java // public interface Vocabulary { // public int size(); // public int OOVindex(); // public String lookupIndex(int index); // public int lookupWord(String word); // public int getVocabSize(); // } // // Path: src/edu/antonym/prototype/WordMetric.java // public interface WordMetric { // public Vocabulary getVocab(); // // public double similarity(int word1, int word2); // }
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.PosixParser; import edu.antonym.prototype.MetricEvaluator; import edu.antonym.prototype.Vocabulary; import edu.antonym.prototype.WordMetric;
antfiles.add(path[j]); }catch(FileNotFoundException e){ System.out.println("File not found, exit"); System.exit(0); } } } if(cmd.hasOption("h")){ showHelp(options); } if((!cmd.hasOption("h"))&&(!cmd.hasOption("a"))&&(!cmd.hasOption("s"))){ showHelp(options); } } catch (Exception e) { e.printStackTrace(); showHelp(options); } } @Override public double score(WordMetric metric) throws IOException { String result_folder = "data/result-data/"; new File(result_folder).mkdirs(); double acc = 0.0d; if(!antfiles.isEmpty()){
// Path: src/edu/antonym/prototype/MetricEvaluator.java // public interface MetricEvaluator { // public double score(WordMetric metric) throws IOException; // } // // Path: src/edu/antonym/prototype/Vocabulary.java // public interface Vocabulary { // public int size(); // public int OOVindex(); // public String lookupIndex(int index); // public int lookupWord(String word); // public int getVocabSize(); // } // // Path: src/edu/antonym/prototype/WordMetric.java // public interface WordMetric { // public Vocabulary getVocab(); // // public double similarity(int word1, int word2); // } // Path: src/edu/antonym/test/TestCase.java import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.PosixParser; import edu.antonym.prototype.MetricEvaluator; import edu.antonym.prototype.Vocabulary; import edu.antonym.prototype.WordMetric; antfiles.add(path[j]); }catch(FileNotFoundException e){ System.out.println("File not found, exit"); System.exit(0); } } } if(cmd.hasOption("h")){ showHelp(options); } if((!cmd.hasOption("h"))&&(!cmd.hasOption("a"))&&(!cmd.hasOption("s"))){ showHelp(options); } } catch (Exception e) { e.printStackTrace(); showHelp(options); } } @Override public double score(WordMetric metric) throws IOException { String result_folder = "data/result-data/"; new File(result_folder).mkdirs(); double acc = 0.0d; if(!antfiles.isEmpty()){
Vocabulary vocab = metric.getVocab();
antonyms/AntonymPipeline
src/org/jobimtext/example/demo/ExpansionsViewManager.java
// Path: src/org/jobimtext/example/demo/JoBimDemo.java // public static class AnnoLabel { // public String label; // public Annotation anno; // // public AnnoLabel(String label, Annotation anno) { // this.label = label; // this.anno = anno; // } // // public String toString() { // return label; // } // }
import java.util.ArrayList; import java.util.Map; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import org.apache.uima.jcas.tcas.Annotation; import org.jobimtext.api.map.IThesaurusMap; import org.jobimtext.example.demo.JoBimDemo.AnnoLabel; import org.jobimtext.holing.extractor.JobimAnnotationExtractor; import com.ibm.bluej.util.common.*; import com.ibm.bluej.util.common.visualization.*;
package org.jobimtext.example.demo; public class ExpansionsViewManager implements TreeSelectionListener { private BasicJTree jobimView; private BasicJTree view; /*private DistributionalSemanticsAPI distSim;*/ private JobimAnnotationExtractor extractor; private IThesaurusMap<String, String> dt; public ExpansionsViewManager( BasicJTree jobimView, BasicJTree view, IThesaurusMap<String, String> dt, JobimAnnotationExtractor extractor) { this.jobimView = jobimView; this.view = view; this.dt = dt; this.extractor = extractor; } public void valueChanged(TreeSelectionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) jobimView .getLastSelectedPathComponent(); // if nothing is selected if (node == null) { view.top.removeAllChildren(); view.refresh(null); return; }
// Path: src/org/jobimtext/example/demo/JoBimDemo.java // public static class AnnoLabel { // public String label; // public Annotation anno; // // public AnnoLabel(String label, Annotation anno) { // this.label = label; // this.anno = anno; // } // // public String toString() { // return label; // } // } // Path: src/org/jobimtext/example/demo/ExpansionsViewManager.java import java.util.ArrayList; import java.util.Map; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import org.apache.uima.jcas.tcas.Annotation; import org.jobimtext.api.map.IThesaurusMap; import org.jobimtext.example.demo.JoBimDemo.AnnoLabel; import org.jobimtext.holing.extractor.JobimAnnotationExtractor; import com.ibm.bluej.util.common.*; import com.ibm.bluej.util.common.visualization.*; package org.jobimtext.example.demo; public class ExpansionsViewManager implements TreeSelectionListener { private BasicJTree jobimView; private BasicJTree view; /*private DistributionalSemanticsAPI distSim;*/ private JobimAnnotationExtractor extractor; private IThesaurusMap<String, String> dt; public ExpansionsViewManager( BasicJTree jobimView, BasicJTree view, IThesaurusMap<String, String> dt, JobimAnnotationExtractor extractor) { this.jobimView = jobimView; this.view = view; this.dt = dt; this.extractor = extractor; } public void valueChanged(TreeSelectionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) jobimView .getLastSelectedPathComponent(); // if nothing is selected if (node == null) { view.top.removeAllChildren(); view.refresh(null); return; }
if (node.getUserObject() instanceof AnnoLabel) {
antonyms/AntonymPipeline
src/edu/antonym/metric/LinearVectorMetric.java
// Path: src/edu/antonym/Util.java // public class Util { // static void saveVectors(VectorEmbedding embed, Vocabulary vocab, File out) throws FileNotFoundException { // int dim=embed.getDimension(); // // PrintStream ps=new PrintStream(out); // ps.println(dim); // for(int i=0; i<vocab.size(); i++) { // double[] vect=embed.getVectorRep(i); // for(int j=0; j<dim; j++) { // ps.print(vect[j]); // ps.print(' '); // } // ps.println(); // } // ps.close(); // } // // public static double cosineSimilarity(double[] vector1, double[] vector2) { // double dotProduct = 0.0; // double v1 = 0.0; // double v2 = 0.0; // double cosineSimilarity = 0.0; // // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // dotProduct += vector1[i] * vector2[i]; // v1 += Math.pow(vector1[i], 2); // v2 += Math.pow(vector2[i], 2); // } // // v1 = Math.sqrt(v1); // v2 = Math.sqrt(v2); // // if (v1 != 0.0 && v2 != 0.0) { // cosineSimilarity = dotProduct / (v1 * v2); // } else { // return 0; // } // return cosineSimilarity; // } // public static Random r=new Random(); // // public static double dotProd(double[] vector1, double[] vector2) { // double dotProduct = 0.0; // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // dotProduct += vector1[i] * vector2[i]; // } // return dotProduct; // } // // public static double[] elemWiseProd(double[] vector1, double[] vector2) { // double[] Product = new double[vector1.length]; // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // Product[i] = vector1[i] * vector2[i]; // } // return Product; // } // // public static int hashInteger(int i, int max) { // r.setSeed(i); // return r.nextInt(max); // } // // public static int hashIntegerPair(int i, int j, int max) { // return hashInteger(31*i+j, max); // } // // static class Pair { // int a; // int b; // static int max; // public Pair(int a, int b) { // this.a = a; // this.b = b; // } // @Override // public int hashCode() { // int aa = a > b ? a:b; // int bb = a > b ? b:a; // return aa * max + bb; // } // @Override // public boolean equals(Object o) { // Pair c = (Pair) o; // return a == c.a && b == c.b || a == c.b && b == c.a; // } // } // // // public static void main(String[] args) throws IOException{ // Thesaurus t = new ThesaurusImp(new File("data/Rogets/antonym.txt"), new File("data/Rogets/synonym.txt"), new File("data/Rogets/vocabulary.txt")); // } // } // // Path: src/edu/antonym/prototype/Thesaurus.java // public interface Entry { // public int word1(); // public int word2(); // public boolean isAntonym(); // } // // Path: src/edu/antonym/prototype/WordMetric.java // public interface WordMetric { // public Vocabulary getVocab(); // // public double similarity(int word1, int word2); // } // // Path: src/edu/antonym/prototype/NormalizedVectorEmbedding.java // public interface NormalizedVectorEmbedding extends VectorEmbedding { // // } // // Path: src/edu/antonym/prototype/Thesaurus.java // public interface Thesaurus { // public interface Entry { // public int word1(); // public int word2(); // public boolean isAntonym(); // } // public Vocabulary getVocab(); // // //Returns the words included in the Thesaurus // public int numEntries(); // public int numSynonyms(); // public int numAntonyms(); // public Entry getEntry(int entryn); // // public int lookupEntry(int word1, int word2, boolean isAnt); // // // public boolean isAntonym(int word1, int word2); // public boolean isSynonym(int word1, int word2); // } // // Path: src/edu/antonym/prototype/VectorEmbedding.java // public interface VectorEmbedding extends WordMetric { // // int getDimension(); // public double[] getVectorRep(int word); // public int findClosestWord(double[] vector); // Vocabulary getVocab(); // } // // Path: src/edu/antonym/prototype/Vocabulary.java // public interface Vocabulary { // public int size(); // public int OOVindex(); // public String lookupIndex(int index); // public int lookupWord(String word); // public int getVocabSize(); // }
import java.util.Arrays; import java.util.List; import org.hamcrest.core.IsAnything; import cc.mallet.optimize.Optimizable; import cc.mallet.types.MatrixOps; import edu.antonym.Util; import edu.antonym.prototype.Thesaurus.Entry; import edu.antonym.prototype.WordMetric; import edu.antonym.prototype.NormalizedVectorEmbedding; import edu.antonym.prototype.Thesaurus; import edu.antonym.prototype.VectorEmbedding; import edu.antonym.prototype.Vocabulary;
package edu.antonym.metric; public class LinearVectorMetric implements Optimizable.ByGradientValue, WordMetric {
// Path: src/edu/antonym/Util.java // public class Util { // static void saveVectors(VectorEmbedding embed, Vocabulary vocab, File out) throws FileNotFoundException { // int dim=embed.getDimension(); // // PrintStream ps=new PrintStream(out); // ps.println(dim); // for(int i=0; i<vocab.size(); i++) { // double[] vect=embed.getVectorRep(i); // for(int j=0; j<dim; j++) { // ps.print(vect[j]); // ps.print(' '); // } // ps.println(); // } // ps.close(); // } // // public static double cosineSimilarity(double[] vector1, double[] vector2) { // double dotProduct = 0.0; // double v1 = 0.0; // double v2 = 0.0; // double cosineSimilarity = 0.0; // // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // dotProduct += vector1[i] * vector2[i]; // v1 += Math.pow(vector1[i], 2); // v2 += Math.pow(vector2[i], 2); // } // // v1 = Math.sqrt(v1); // v2 = Math.sqrt(v2); // // if (v1 != 0.0 && v2 != 0.0) { // cosineSimilarity = dotProduct / (v1 * v2); // } else { // return 0; // } // return cosineSimilarity; // } // public static Random r=new Random(); // // public static double dotProd(double[] vector1, double[] vector2) { // double dotProduct = 0.0; // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // dotProduct += vector1[i] * vector2[i]; // } // return dotProduct; // } // // public static double[] elemWiseProd(double[] vector1, double[] vector2) { // double[] Product = new double[vector1.length]; // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // Product[i] = vector1[i] * vector2[i]; // } // return Product; // } // // public static int hashInteger(int i, int max) { // r.setSeed(i); // return r.nextInt(max); // } // // public static int hashIntegerPair(int i, int j, int max) { // return hashInteger(31*i+j, max); // } // // static class Pair { // int a; // int b; // static int max; // public Pair(int a, int b) { // this.a = a; // this.b = b; // } // @Override // public int hashCode() { // int aa = a > b ? a:b; // int bb = a > b ? b:a; // return aa * max + bb; // } // @Override // public boolean equals(Object o) { // Pair c = (Pair) o; // return a == c.a && b == c.b || a == c.b && b == c.a; // } // } // // // public static void main(String[] args) throws IOException{ // Thesaurus t = new ThesaurusImp(new File("data/Rogets/antonym.txt"), new File("data/Rogets/synonym.txt"), new File("data/Rogets/vocabulary.txt")); // } // } // // Path: src/edu/antonym/prototype/Thesaurus.java // public interface Entry { // public int word1(); // public int word2(); // public boolean isAntonym(); // } // // Path: src/edu/antonym/prototype/WordMetric.java // public interface WordMetric { // public Vocabulary getVocab(); // // public double similarity(int word1, int word2); // } // // Path: src/edu/antonym/prototype/NormalizedVectorEmbedding.java // public interface NormalizedVectorEmbedding extends VectorEmbedding { // // } // // Path: src/edu/antonym/prototype/Thesaurus.java // public interface Thesaurus { // public interface Entry { // public int word1(); // public int word2(); // public boolean isAntonym(); // } // public Vocabulary getVocab(); // // //Returns the words included in the Thesaurus // public int numEntries(); // public int numSynonyms(); // public int numAntonyms(); // public Entry getEntry(int entryn); // // public int lookupEntry(int word1, int word2, boolean isAnt); // // // public boolean isAntonym(int word1, int word2); // public boolean isSynonym(int word1, int word2); // } // // Path: src/edu/antonym/prototype/VectorEmbedding.java // public interface VectorEmbedding extends WordMetric { // // int getDimension(); // public double[] getVectorRep(int word); // public int findClosestWord(double[] vector); // Vocabulary getVocab(); // } // // Path: src/edu/antonym/prototype/Vocabulary.java // public interface Vocabulary { // public int size(); // public int OOVindex(); // public String lookupIndex(int index); // public int lookupWord(String word); // public int getVocabSize(); // } // Path: src/edu/antonym/metric/LinearVectorMetric.java import java.util.Arrays; import java.util.List; import org.hamcrest.core.IsAnything; import cc.mallet.optimize.Optimizable; import cc.mallet.types.MatrixOps; import edu.antonym.Util; import edu.antonym.prototype.Thesaurus.Entry; import edu.antonym.prototype.WordMetric; import edu.antonym.prototype.NormalizedVectorEmbedding; import edu.antonym.prototype.Thesaurus; import edu.antonym.prototype.VectorEmbedding; import edu.antonym.prototype.Vocabulary; package edu.antonym.metric; public class LinearVectorMetric implements Optimizable.ByGradientValue, WordMetric {
Thesaurus th;
antonyms/AntonymPipeline
src/edu/antonym/metric/LinearVectorMetric.java
// Path: src/edu/antonym/Util.java // public class Util { // static void saveVectors(VectorEmbedding embed, Vocabulary vocab, File out) throws FileNotFoundException { // int dim=embed.getDimension(); // // PrintStream ps=new PrintStream(out); // ps.println(dim); // for(int i=0; i<vocab.size(); i++) { // double[] vect=embed.getVectorRep(i); // for(int j=0; j<dim; j++) { // ps.print(vect[j]); // ps.print(' '); // } // ps.println(); // } // ps.close(); // } // // public static double cosineSimilarity(double[] vector1, double[] vector2) { // double dotProduct = 0.0; // double v1 = 0.0; // double v2 = 0.0; // double cosineSimilarity = 0.0; // // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // dotProduct += vector1[i] * vector2[i]; // v1 += Math.pow(vector1[i], 2); // v2 += Math.pow(vector2[i], 2); // } // // v1 = Math.sqrt(v1); // v2 = Math.sqrt(v2); // // if (v1 != 0.0 && v2 != 0.0) { // cosineSimilarity = dotProduct / (v1 * v2); // } else { // return 0; // } // return cosineSimilarity; // } // public static Random r=new Random(); // // public static double dotProd(double[] vector1, double[] vector2) { // double dotProduct = 0.0; // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // dotProduct += vector1[i] * vector2[i]; // } // return dotProduct; // } // // public static double[] elemWiseProd(double[] vector1, double[] vector2) { // double[] Product = new double[vector1.length]; // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // Product[i] = vector1[i] * vector2[i]; // } // return Product; // } // // public static int hashInteger(int i, int max) { // r.setSeed(i); // return r.nextInt(max); // } // // public static int hashIntegerPair(int i, int j, int max) { // return hashInteger(31*i+j, max); // } // // static class Pair { // int a; // int b; // static int max; // public Pair(int a, int b) { // this.a = a; // this.b = b; // } // @Override // public int hashCode() { // int aa = a > b ? a:b; // int bb = a > b ? b:a; // return aa * max + bb; // } // @Override // public boolean equals(Object o) { // Pair c = (Pair) o; // return a == c.a && b == c.b || a == c.b && b == c.a; // } // } // // // public static void main(String[] args) throws IOException{ // Thesaurus t = new ThesaurusImp(new File("data/Rogets/antonym.txt"), new File("data/Rogets/synonym.txt"), new File("data/Rogets/vocabulary.txt")); // } // } // // Path: src/edu/antonym/prototype/Thesaurus.java // public interface Entry { // public int word1(); // public int word2(); // public boolean isAntonym(); // } // // Path: src/edu/antonym/prototype/WordMetric.java // public interface WordMetric { // public Vocabulary getVocab(); // // public double similarity(int word1, int word2); // } // // Path: src/edu/antonym/prototype/NormalizedVectorEmbedding.java // public interface NormalizedVectorEmbedding extends VectorEmbedding { // // } // // Path: src/edu/antonym/prototype/Thesaurus.java // public interface Thesaurus { // public interface Entry { // public int word1(); // public int word2(); // public boolean isAntonym(); // } // public Vocabulary getVocab(); // // //Returns the words included in the Thesaurus // public int numEntries(); // public int numSynonyms(); // public int numAntonyms(); // public Entry getEntry(int entryn); // // public int lookupEntry(int word1, int word2, boolean isAnt); // // // public boolean isAntonym(int word1, int word2); // public boolean isSynonym(int word1, int word2); // } // // Path: src/edu/antonym/prototype/VectorEmbedding.java // public interface VectorEmbedding extends WordMetric { // // int getDimension(); // public double[] getVectorRep(int word); // public int findClosestWord(double[] vector); // Vocabulary getVocab(); // } // // Path: src/edu/antonym/prototype/Vocabulary.java // public interface Vocabulary { // public int size(); // public int OOVindex(); // public String lookupIndex(int index); // public int lookupWord(String word); // public int getVocabSize(); // }
import java.util.Arrays; import java.util.List; import org.hamcrest.core.IsAnything; import cc.mallet.optimize.Optimizable; import cc.mallet.types.MatrixOps; import edu.antonym.Util; import edu.antonym.prototype.Thesaurus.Entry; import edu.antonym.prototype.WordMetric; import edu.antonym.prototype.NormalizedVectorEmbedding; import edu.antonym.prototype.Thesaurus; import edu.antonym.prototype.VectorEmbedding; import edu.antonym.prototype.Vocabulary;
package edu.antonym.metric; public class LinearVectorMetric implements Optimizable.ByGradientValue, WordMetric { Thesaurus th;
// Path: src/edu/antonym/Util.java // public class Util { // static void saveVectors(VectorEmbedding embed, Vocabulary vocab, File out) throws FileNotFoundException { // int dim=embed.getDimension(); // // PrintStream ps=new PrintStream(out); // ps.println(dim); // for(int i=0; i<vocab.size(); i++) { // double[] vect=embed.getVectorRep(i); // for(int j=0; j<dim; j++) { // ps.print(vect[j]); // ps.print(' '); // } // ps.println(); // } // ps.close(); // } // // public static double cosineSimilarity(double[] vector1, double[] vector2) { // double dotProduct = 0.0; // double v1 = 0.0; // double v2 = 0.0; // double cosineSimilarity = 0.0; // // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // dotProduct += vector1[i] * vector2[i]; // v1 += Math.pow(vector1[i], 2); // v2 += Math.pow(vector2[i], 2); // } // // v1 = Math.sqrt(v1); // v2 = Math.sqrt(v2); // // if (v1 != 0.0 && v2 != 0.0) { // cosineSimilarity = dotProduct / (v1 * v2); // } else { // return 0; // } // return cosineSimilarity; // } // public static Random r=new Random(); // // public static double dotProd(double[] vector1, double[] vector2) { // double dotProduct = 0.0; // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // dotProduct += vector1[i] * vector2[i]; // } // return dotProduct; // } // // public static double[] elemWiseProd(double[] vector1, double[] vector2) { // double[] Product = new double[vector1.length]; // for (int i = 0; i < vector1.length; i++) //vector1 and vector2 must be of same length // { // Product[i] = vector1[i] * vector2[i]; // } // return Product; // } // // public static int hashInteger(int i, int max) { // r.setSeed(i); // return r.nextInt(max); // } // // public static int hashIntegerPair(int i, int j, int max) { // return hashInteger(31*i+j, max); // } // // static class Pair { // int a; // int b; // static int max; // public Pair(int a, int b) { // this.a = a; // this.b = b; // } // @Override // public int hashCode() { // int aa = a > b ? a:b; // int bb = a > b ? b:a; // return aa * max + bb; // } // @Override // public boolean equals(Object o) { // Pair c = (Pair) o; // return a == c.a && b == c.b || a == c.b && b == c.a; // } // } // // // public static void main(String[] args) throws IOException{ // Thesaurus t = new ThesaurusImp(new File("data/Rogets/antonym.txt"), new File("data/Rogets/synonym.txt"), new File("data/Rogets/vocabulary.txt")); // } // } // // Path: src/edu/antonym/prototype/Thesaurus.java // public interface Entry { // public int word1(); // public int word2(); // public boolean isAntonym(); // } // // Path: src/edu/antonym/prototype/WordMetric.java // public interface WordMetric { // public Vocabulary getVocab(); // // public double similarity(int word1, int word2); // } // // Path: src/edu/antonym/prototype/NormalizedVectorEmbedding.java // public interface NormalizedVectorEmbedding extends VectorEmbedding { // // } // // Path: src/edu/antonym/prototype/Thesaurus.java // public interface Thesaurus { // public interface Entry { // public int word1(); // public int word2(); // public boolean isAntonym(); // } // public Vocabulary getVocab(); // // //Returns the words included in the Thesaurus // public int numEntries(); // public int numSynonyms(); // public int numAntonyms(); // public Entry getEntry(int entryn); // // public int lookupEntry(int word1, int word2, boolean isAnt); // // // public boolean isAntonym(int word1, int word2); // public boolean isSynonym(int word1, int word2); // } // // Path: src/edu/antonym/prototype/VectorEmbedding.java // public interface VectorEmbedding extends WordMetric { // // int getDimension(); // public double[] getVectorRep(int word); // public int findClosestWord(double[] vector); // Vocabulary getVocab(); // } // // Path: src/edu/antonym/prototype/Vocabulary.java // public interface Vocabulary { // public int size(); // public int OOVindex(); // public String lookupIndex(int index); // public int lookupWord(String word); // public int getVocabSize(); // } // Path: src/edu/antonym/metric/LinearVectorMetric.java import java.util.Arrays; import java.util.List; import org.hamcrest.core.IsAnything; import cc.mallet.optimize.Optimizable; import cc.mallet.types.MatrixOps; import edu.antonym.Util; import edu.antonym.prototype.Thesaurus.Entry; import edu.antonym.prototype.WordMetric; import edu.antonym.prototype.NormalizedVectorEmbedding; import edu.antonym.prototype.Thesaurus; import edu.antonym.prototype.VectorEmbedding; import edu.antonym.prototype.Vocabulary; package edu.antonym.metric; public class LinearVectorMetric implements Optimizable.ByGradientValue, WordMetric { Thesaurus th;
VectorEmbedding orig;
antonyms/AntonymPipeline
src/edu/antonym/SimpleThesaurus.java
// Path: src/edu/antonym/prototype/Thesaurus.java // public interface Thesaurus { // public interface Entry { // public int word1(); // public int word2(); // public boolean isAntonym(); // } // public Vocabulary getVocab(); // // //Returns the words included in the Thesaurus // public int numEntries(); // public int numSynonyms(); // public int numAntonyms(); // public Entry getEntry(int entryn); // // public int lookupEntry(int word1, int word2, boolean isAnt); // // // public boolean isAntonym(int word1, int word2); // public boolean isSynonym(int word1, int word2); // } // // Path: src/edu/antonym/prototype/Vocabulary.java // public interface Vocabulary { // public int size(); // public int OOVindex(); // public String lookupIndex(int index); // public int lookupWord(String word); // public int getVocabSize(); // }
import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import javax.swing.event.ListSelectionEvent; import edu.antonym.prototype.Thesaurus; import edu.antonym.prototype.Vocabulary;
return compare; } @Override public boolean equals(Object obj) { if (obj instanceof ThesaurusEntry) { ThesaurusEntry other = ((ThesaurusEntry) obj); return word1 == other.word1 && isAntonym == other.isAntonym && this.word2 == other.word2; } return false; } @Override public int word1() { return word1; } @Override public int word2() { return word2; } @Override public boolean isAntonym() { return isAntonym; } }
// Path: src/edu/antonym/prototype/Thesaurus.java // public interface Thesaurus { // public interface Entry { // public int word1(); // public int word2(); // public boolean isAntonym(); // } // public Vocabulary getVocab(); // // //Returns the words included in the Thesaurus // public int numEntries(); // public int numSynonyms(); // public int numAntonyms(); // public Entry getEntry(int entryn); // // public int lookupEntry(int word1, int word2, boolean isAnt); // // // public boolean isAntonym(int word1, int word2); // public boolean isSynonym(int word1, int word2); // } // // Path: src/edu/antonym/prototype/Vocabulary.java // public interface Vocabulary { // public int size(); // public int OOVindex(); // public String lookupIndex(int index); // public int lookupWord(String word); // public int getVocabSize(); // } // Path: src/edu/antonym/SimpleThesaurus.java import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import javax.swing.event.ListSelectionEvent; import edu.antonym.prototype.Thesaurus; import edu.antonym.prototype.Vocabulary; return compare; } @Override public boolean equals(Object obj) { if (obj instanceof ThesaurusEntry) { ThesaurusEntry other = ((ThesaurusEntry) obj); return word1 == other.word1 && isAntonym == other.isAntonym && this.word2 == other.word2; } return false; } @Override public int word1() { return word1; } @Override public int word2() { return word2; } @Override public boolean isAntonym() { return isAntonym; } }
Vocabulary vocab;
thx/RAP
src/main/java/com/taobao/rigel/rap/auto/generate/contract/Generator.java
// Path: src/main/java/com/taobao/rigel/rap/auto/generate/bo/GenerateUtils.java // public enum GeneratorType {EXPORT_FILE} // // Path: src/main/java/com/taobao/rigel/rap/auto/generate/bo/GenerateUtils.java // public enum TargetObjectType {PROJECT, MODULE, PAGE, ACTION} // // Path: src/main/java/com/taobao/rigel/rap/project/bo/Project.java // public enum STAGE_TYPE {DESIGNING, DEVELOPING, DEBUGING}
import com.taobao.rigel.rap.auto.generate.bo.GenerateUtils.GeneratorType; import com.taobao.rigel.rap.auto.generate.bo.GenerateUtils.TargetObjectType; import com.taobao.rigel.rap.project.bo.Project.STAGE_TYPE;
package com.taobao.rigel.rap.auto.generate.contract; /** * generator interface, all generator class should * implement this interface * * @author Bosn */ public interface Generator { /** * is available on specific stage * * @param stage * @return */ boolean isAvailable(STAGE_TYPE stage); /** * get generator type * * @return */
// Path: src/main/java/com/taobao/rigel/rap/auto/generate/bo/GenerateUtils.java // public enum GeneratorType {EXPORT_FILE} // // Path: src/main/java/com/taobao/rigel/rap/auto/generate/bo/GenerateUtils.java // public enum TargetObjectType {PROJECT, MODULE, PAGE, ACTION} // // Path: src/main/java/com/taobao/rigel/rap/project/bo/Project.java // public enum STAGE_TYPE {DESIGNING, DEVELOPING, DEBUGING} // Path: src/main/java/com/taobao/rigel/rap/auto/generate/contract/Generator.java import com.taobao.rigel.rap.auto.generate.bo.GenerateUtils.GeneratorType; import com.taobao.rigel.rap.auto.generate.bo.GenerateUtils.TargetObjectType; import com.taobao.rigel.rap.project.bo.Project.STAGE_TYPE; package com.taobao.rigel.rap.auto.generate.contract; /** * generator interface, all generator class should * implement this interface * * @author Bosn */ public interface Generator { /** * is available on specific stage * * @param stage * @return */ boolean isAvailable(STAGE_TYPE stage); /** * get generator type * * @return */
GeneratorType getGeneratorType();
thx/RAP
src/main/java/com/taobao/rigel/rap/auto/generate/contract/Generator.java
// Path: src/main/java/com/taobao/rigel/rap/auto/generate/bo/GenerateUtils.java // public enum GeneratorType {EXPORT_FILE} // // Path: src/main/java/com/taobao/rigel/rap/auto/generate/bo/GenerateUtils.java // public enum TargetObjectType {PROJECT, MODULE, PAGE, ACTION} // // Path: src/main/java/com/taobao/rigel/rap/project/bo/Project.java // public enum STAGE_TYPE {DESIGNING, DEVELOPING, DEBUGING}
import com.taobao.rigel.rap.auto.generate.bo.GenerateUtils.GeneratorType; import com.taobao.rigel.rap.auto.generate.bo.GenerateUtils.TargetObjectType; import com.taobao.rigel.rap.project.bo.Project.STAGE_TYPE;
package com.taobao.rigel.rap.auto.generate.contract; /** * generator interface, all generator class should * implement this interface * * @author Bosn */ public interface Generator { /** * is available on specific stage * * @param stage * @return */ boolean isAvailable(STAGE_TYPE stage); /** * get generator type * * @return */ GeneratorType getGeneratorType(); /** * get author * * @return author */ String getAuthor(); /** * get introduction of generator * * @return */ String getIntroduction(); /** * get target object type * * @return */
// Path: src/main/java/com/taobao/rigel/rap/auto/generate/bo/GenerateUtils.java // public enum GeneratorType {EXPORT_FILE} // // Path: src/main/java/com/taobao/rigel/rap/auto/generate/bo/GenerateUtils.java // public enum TargetObjectType {PROJECT, MODULE, PAGE, ACTION} // // Path: src/main/java/com/taobao/rigel/rap/project/bo/Project.java // public enum STAGE_TYPE {DESIGNING, DEVELOPING, DEBUGING} // Path: src/main/java/com/taobao/rigel/rap/auto/generate/contract/Generator.java import com.taobao.rigel.rap.auto.generate.bo.GenerateUtils.GeneratorType; import com.taobao.rigel.rap.auto.generate.bo.GenerateUtils.TargetObjectType; import com.taobao.rigel.rap.project.bo.Project.STAGE_TYPE; package com.taobao.rigel.rap.auto.generate.contract; /** * generator interface, all generator class should * implement this interface * * @author Bosn */ public interface Generator { /** * is available on specific stage * * @param stage * @return */ boolean isAvailable(STAGE_TYPE stage); /** * get generator type * * @return */ GeneratorType getGeneratorType(); /** * get author * * @return author */ String getAuthor(); /** * get introduction of generator * * @return */ String getIntroduction(); /** * get target object type * * @return */
TargetObjectType getTargetObjectType();
thx/RAP
src/main/java/com/taobao/rigel/rap/common/utils/JedisFactory.java
// Path: src/main/java/com/taobao/rigel/rap/common/config/SystemConstant.java // public class SystemConstant { // private static final Logger logger = LogManager.getFormatterLogger(SystemConstant.class); // public static final int DEFAULT_PAGE_SIZE = 12; // public static final int ACCOUNT_LENGTH_MIN = 6; // public static final int ACCOUNT_LENGTH_MAX = 32; // public static final int NAME_LENGTH_MIN = 1; // public static final int NAME_LENGTH_MAX = 32; // public static final String ALI_LOGIN_URL = "login" + ".ali" + "ba" + "ba" + "-in" + "c.com"; // public static final String NODE_SERVER = "localhost:7429"; // public static String README_PATH = ""; // public static String ROOT = ""; // public static String DOMAIN_URL = ""; // public static boolean serviceInitialized = false; // public static SimpleSSOUser user = null; // private static String domainURL = ""; // // public static String getAliLoginUrl() { // return ALI_LOGIN_URL; // } // // public static String getDOMAIN_URL() { // return domainURL; // } // // public static void setDOMAIN_URL(String domainURL) { // SystemConstant.domainURL = domainURL; // } // // private static Properties config; // // private static void loadConfig() { // if (config == null) { // config = new Properties(); // ClassLoader loader = Thread.currentThread().getContextClassLoader(); // try { // config.load(loader.getResourceAsStream("config.properties")); // } catch (IOException e) { // e.printStackTrace(); // logger.error(e.getMessage()); // } // } // } // // public static String getConfig(String key) { // if (config == null) { // loadConfig(); // } // return config.getProperty(key); // } // // // }
import com.taobao.rigel.rap.common.config.SystemConstant; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import java.io.IOException;
package com.taobao.rigel.rap.common.utils; class JedisFactory { private static JedisPool jedisPool; private static JedisFactory instance = null; public JedisFactory() { JedisPoolConfig poolConfig = new JedisPoolConfig();
// Path: src/main/java/com/taobao/rigel/rap/common/config/SystemConstant.java // public class SystemConstant { // private static final Logger logger = LogManager.getFormatterLogger(SystemConstant.class); // public static final int DEFAULT_PAGE_SIZE = 12; // public static final int ACCOUNT_LENGTH_MIN = 6; // public static final int ACCOUNT_LENGTH_MAX = 32; // public static final int NAME_LENGTH_MIN = 1; // public static final int NAME_LENGTH_MAX = 32; // public static final String ALI_LOGIN_URL = "login" + ".ali" + "ba" + "ba" + "-in" + "c.com"; // public static final String NODE_SERVER = "localhost:7429"; // public static String README_PATH = ""; // public static String ROOT = ""; // public static String DOMAIN_URL = ""; // public static boolean serviceInitialized = false; // public static SimpleSSOUser user = null; // private static String domainURL = ""; // // public static String getAliLoginUrl() { // return ALI_LOGIN_URL; // } // // public static String getDOMAIN_URL() { // return domainURL; // } // // public static void setDOMAIN_URL(String domainURL) { // SystemConstant.domainURL = domainURL; // } // // private static Properties config; // // private static void loadConfig() { // if (config == null) { // config = new Properties(); // ClassLoader loader = Thread.currentThread().getContextClassLoader(); // try { // config.load(loader.getResourceAsStream("config.properties")); // } catch (IOException e) { // e.printStackTrace(); // logger.error(e.getMessage()); // } // } // } // // public static String getConfig(String key) { // if (config == null) { // loadConfig(); // } // return config.getProperty(key); // } // // // } // Path: src/main/java/com/taobao/rigel/rap/common/utils/JedisFactory.java import com.taobao.rigel.rap.common.config.SystemConstant; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import java.io.IOException; package com.taobao.rigel.rap.common.utils; class JedisFactory { private static JedisPool jedisPool; private static JedisFactory instance = null; public JedisFactory() { JedisPoolConfig poolConfig = new JedisPoolConfig();
String host = SystemConstant.getConfig("redis.host");
thx/RAP
src/main/java/Tester.java
// Path: src/main/java/com/taobao/rigel/rap/common/utils/MockjsRunner.java // public class MockjsRunner { // // private static String MOCKJS_PATH = SystemConstant.ROOT + // FileUtils.concatFilePath(new String[]{"stat", "js", "util", "mock-min.js"}); // private static String jsCode; // private Context ct; // private Scriptable scope; // private static final Logger logger = LogManager.getLogger(MockjsRunner.class); // // public MockjsRunner() { // this.ct = Context.enter(); // this.scope = ct.initStandardObjects(); // this.ct.setOptimizationLevel(-1); // this.initMockjs(ct, scope); // } // // public static String getMockjsCode() { // try { // byte[] encoded = Files.readAllBytes(Paths.get(MOCKJS_PATH)); // String result = new String(encoded, StandardCharsets.UTF_8); // return result; // } catch (Exception e) { // e.printStackTrace(); // return "\"ERROR\""; // } finally { // } // } // // public static String renderMockjsRule(String mockRule) { // return new MockjsRunner().doRenderMockJsRule(mockRule); // } // // public static void main(String[] args) { // } // // public Context getContext() { // return this.ct; // } // // public Scriptable getScope() { // return this.scope; // } // // private void initMockjs(Context ct, Scriptable scope) { // if (jsCode == null) { // jsCode = getMockjsCode(); // } // try { // ct.evaluateString(scope, jsCode, null, 1, null); // ct.evaluateString(scope, "", null, 1, null); // } catch (Exception e) { // e.printStackTrace(); // } // } // // private String doRenderMockJsRule(String mockRule) { // String returnVal = "JS_ERROR"; // try { // StringBuilder code = new StringBuilder(); // code // .append("var result = {};") // .append("try {") // // .append("var obj = Mock.mock(JSON.parse(\"" + StringUtils.escapeInJ(mockRule.replaceAll("\\'", "'")) + "\"));") // .append("var obj = Mock.mock(" + mockRule + ");") // .append("result = JSON.stringify(obj.__root__ != undefined ? obj.__root__ : obj, null, 4);") // .append("} catch(ex) {result.errMsg = ex.message;result.isOk=false;result = JSON.stringify(result);}") // .append("result;"); // // Object result = ct.evaluateString(scope, code.toString(), null, 1, // null); // returnVal = result.toString(); // } catch (Exception e) { // e.printStackTrace(); // } finally { // ct.exit(); // } // return returnVal; // } // }
import com.taobao.rigel.rap.common.utils.MockjsRunner; import redis.clients.jedis.Jedis;
/** * Created by Bosn on 2014/8/16. */ public class Tester { public static void main(String[] args) { String code= "1";
// Path: src/main/java/com/taobao/rigel/rap/common/utils/MockjsRunner.java // public class MockjsRunner { // // private static String MOCKJS_PATH = SystemConstant.ROOT + // FileUtils.concatFilePath(new String[]{"stat", "js", "util", "mock-min.js"}); // private static String jsCode; // private Context ct; // private Scriptable scope; // private static final Logger logger = LogManager.getLogger(MockjsRunner.class); // // public MockjsRunner() { // this.ct = Context.enter(); // this.scope = ct.initStandardObjects(); // this.ct.setOptimizationLevel(-1); // this.initMockjs(ct, scope); // } // // public static String getMockjsCode() { // try { // byte[] encoded = Files.readAllBytes(Paths.get(MOCKJS_PATH)); // String result = new String(encoded, StandardCharsets.UTF_8); // return result; // } catch (Exception e) { // e.printStackTrace(); // return "\"ERROR\""; // } finally { // } // } // // public static String renderMockjsRule(String mockRule) { // return new MockjsRunner().doRenderMockJsRule(mockRule); // } // // public static void main(String[] args) { // } // // public Context getContext() { // return this.ct; // } // // public Scriptable getScope() { // return this.scope; // } // // private void initMockjs(Context ct, Scriptable scope) { // if (jsCode == null) { // jsCode = getMockjsCode(); // } // try { // ct.evaluateString(scope, jsCode, null, 1, null); // ct.evaluateString(scope, "", null, 1, null); // } catch (Exception e) { // e.printStackTrace(); // } // } // // private String doRenderMockJsRule(String mockRule) { // String returnVal = "JS_ERROR"; // try { // StringBuilder code = new StringBuilder(); // code // .append("var result = {};") // .append("try {") // // .append("var obj = Mock.mock(JSON.parse(\"" + StringUtils.escapeInJ(mockRule.replaceAll("\\'", "'")) + "\"));") // .append("var obj = Mock.mock(" + mockRule + ");") // .append("result = JSON.stringify(obj.__root__ != undefined ? obj.__root__ : obj, null, 4);") // .append("} catch(ex) {result.errMsg = ex.message;result.isOk=false;result = JSON.stringify(result);}") // .append("result;"); // // Object result = ct.evaluateString(scope, code.toString(), null, 1, // null); // returnVal = result.toString(); // } catch (Exception e) { // e.printStackTrace(); // } finally { // ct.exit(); // } // return returnVal; // } // } // Path: src/main/java/Tester.java import com.taobao.rigel.rap.common.utils.MockjsRunner; import redis.clients.jedis.Jedis; /** * Created by Bosn on 2014/8/16. */ public class Tester { public static void main(String[] args) { String code= "1";
String result = MockjsRunner.renderMockjsRule(code);
thx/RAP
src/main/java/org/apache/struts2/views/velocity/VelocityManager.java
// Path: src/main/java/com/taobao/rigel/rap/common/config/SystemConstant.java // public class SystemConstant { // private static final Logger logger = LogManager.getFormatterLogger(SystemConstant.class); // public static final int DEFAULT_PAGE_SIZE = 12; // public static final int ACCOUNT_LENGTH_MIN = 6; // public static final int ACCOUNT_LENGTH_MAX = 32; // public static final int NAME_LENGTH_MIN = 1; // public static final int NAME_LENGTH_MAX = 32; // public static final String ALI_LOGIN_URL = "login" + ".ali" + "ba" + "ba" + "-in" + "c.com"; // public static final String NODE_SERVER = "localhost:7429"; // public static String README_PATH = ""; // public static String ROOT = ""; // public static String DOMAIN_URL = ""; // public static boolean serviceInitialized = false; // public static SimpleSSOUser user = null; // private static String domainURL = ""; // // public static String getAliLoginUrl() { // return ALI_LOGIN_URL; // } // // public static String getDOMAIN_URL() { // return domainURL; // } // // public static void setDOMAIN_URL(String domainURL) { // SystemConstant.domainURL = domainURL; // } // // private static Properties config; // // private static void loadConfig() { // if (config == null) { // config = new Properties(); // ClassLoader loader = Thread.currentThread().getContextClassLoader(); // try { // config.load(loader.getResourceAsStream("config.properties")); // } catch (IOException e) { // e.printStackTrace(); // logger.error(e.getMessage()); // } // } // } // // public static String getConfig(String key) { // if (config == null) { // loadConfig(); // } // return config.getProperty(key); // } // // // }
import com.opensymphony.xwork2.ObjectFactory; import com.opensymphony.xwork2.inject.Container; import com.opensymphony.xwork2.inject.Inject; import com.opensymphony.xwork2.util.ValueStack; import com.opensymphony.xwork2.util.logging.Logger; import com.opensymphony.xwork2.util.logging.LoggerFactory; import com.taobao.rigel.rap.common.config.SystemConstant; import com.taobao.rigel.rap.common.utils.DateUtils; import com.taobao.rigel.rap.common.utils.SystemVisitorLog; import org.apache.commons.lang3.StringUtils; import org.apache.struts2.ServletActionContext; import org.apache.struts2.StrutsConstants; import org.apache.struts2.StrutsException; import org.apache.struts2.util.VelocityStrutsUtil; import org.apache.struts2.views.TagLibrary; import org.apache.struts2.views.TagLibraryDirectiveProvider; import org.apache.struts2.views.jsp.ui.OgnlTool; import org.apache.struts2.views.util.ContextUtil; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.context.Context; import org.apache.velocity.tools.view.ToolboxManager; import org.apache.velocity.tools.view.context.ChainedContext; import org.apache.velocity.tools.view.servlet.ServletToolboxManager; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.*;
} /** * This method is responsible for creating the standard VelocityContext used by all WW2 velocity views. The * following context parameters are defined: * <p/> * <ul> * <li><strong>request</strong> - the current HttpServletRequest</li> * <li><strong>response</strong> - the current HttpServletResponse</li> * <li><strong>stack</strong> - the current {@link ValueStack}</li> * <li><strong>ognl</strong> - an {@link OgnlTool}</li> * <li><strong>struts</strong> - an instance of {@link org.apache.struts2.util.StrutsUtil}</li> * <li><strong>action</strong> - the current Struts action</li> * </ul> * * @return a new StrutsVelocityContext */ public Context createContext(ValueStack stack, HttpServletRequest req, HttpServletResponse res) { Context result = null; VelocityContext[] chainedContexts = prepareChainedContexts(req, res, stack.getContext()); StrutsVelocityContext context = new StrutsVelocityContext(chainedContexts, stack); Map standardMap = ContextUtil.getStandardContext(stack, req, res); for (Iterator iterator = standardMap.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry entry = (Map.Entry) iterator.next(); context.put((String) entry.getKey(), entry.getValue()); } context.put("utils", new com.taobao.rigel.rap.common.utils.StringUtils()); context.put("dateUtils", new DateUtils());
// Path: src/main/java/com/taobao/rigel/rap/common/config/SystemConstant.java // public class SystemConstant { // private static final Logger logger = LogManager.getFormatterLogger(SystemConstant.class); // public static final int DEFAULT_PAGE_SIZE = 12; // public static final int ACCOUNT_LENGTH_MIN = 6; // public static final int ACCOUNT_LENGTH_MAX = 32; // public static final int NAME_LENGTH_MIN = 1; // public static final int NAME_LENGTH_MAX = 32; // public static final String ALI_LOGIN_URL = "login" + ".ali" + "ba" + "ba" + "-in" + "c.com"; // public static final String NODE_SERVER = "localhost:7429"; // public static String README_PATH = ""; // public static String ROOT = ""; // public static String DOMAIN_URL = ""; // public static boolean serviceInitialized = false; // public static SimpleSSOUser user = null; // private static String domainURL = ""; // // public static String getAliLoginUrl() { // return ALI_LOGIN_URL; // } // // public static String getDOMAIN_URL() { // return domainURL; // } // // public static void setDOMAIN_URL(String domainURL) { // SystemConstant.domainURL = domainURL; // } // // private static Properties config; // // private static void loadConfig() { // if (config == null) { // config = new Properties(); // ClassLoader loader = Thread.currentThread().getContextClassLoader(); // try { // config.load(loader.getResourceAsStream("config.properties")); // } catch (IOException e) { // e.printStackTrace(); // logger.error(e.getMessage()); // } // } // } // // public static String getConfig(String key) { // if (config == null) { // loadConfig(); // } // return config.getProperty(key); // } // // // } // Path: src/main/java/org/apache/struts2/views/velocity/VelocityManager.java import com.opensymphony.xwork2.ObjectFactory; import com.opensymphony.xwork2.inject.Container; import com.opensymphony.xwork2.inject.Inject; import com.opensymphony.xwork2.util.ValueStack; import com.opensymphony.xwork2.util.logging.Logger; import com.opensymphony.xwork2.util.logging.LoggerFactory; import com.taobao.rigel.rap.common.config.SystemConstant; import com.taobao.rigel.rap.common.utils.DateUtils; import com.taobao.rigel.rap.common.utils.SystemVisitorLog; import org.apache.commons.lang3.StringUtils; import org.apache.struts2.ServletActionContext; import org.apache.struts2.StrutsConstants; import org.apache.struts2.StrutsException; import org.apache.struts2.util.VelocityStrutsUtil; import org.apache.struts2.views.TagLibrary; import org.apache.struts2.views.TagLibraryDirectiveProvider; import org.apache.struts2.views.jsp.ui.OgnlTool; import org.apache.struts2.views.util.ContextUtil; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.context.Context; import org.apache.velocity.tools.view.ToolboxManager; import org.apache.velocity.tools.view.context.ChainedContext; import org.apache.velocity.tools.view.servlet.ServletToolboxManager; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.*; } /** * This method is responsible for creating the standard VelocityContext used by all WW2 velocity views. The * following context parameters are defined: * <p/> * <ul> * <li><strong>request</strong> - the current HttpServletRequest</li> * <li><strong>response</strong> - the current HttpServletResponse</li> * <li><strong>stack</strong> - the current {@link ValueStack}</li> * <li><strong>ognl</strong> - an {@link OgnlTool}</li> * <li><strong>struts</strong> - an instance of {@link org.apache.struts2.util.StrutsUtil}</li> * <li><strong>action</strong> - the current Struts action</li> * </ul> * * @return a new StrutsVelocityContext */ public Context createContext(ValueStack stack, HttpServletRequest req, HttpServletResponse res) { Context result = null; VelocityContext[] chainedContexts = prepareChainedContexts(req, res, stack.getContext()); StrutsVelocityContext context = new StrutsVelocityContext(chainedContexts, stack); Map standardMap = ContextUtil.getStandardContext(stack, req, res); for (Iterator iterator = standardMap.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry entry = (Map.Entry) iterator.next(); context.put((String) entry.getKey(), entry.getValue()); } context.put("utils", new com.taobao.rigel.rap.common.utils.StringUtils()); context.put("dateUtils", new DateUtils());
context.put("consts", new SystemConstant());
xpush/lib-xpush-android
sample/src/main/java/io/xpush/sampleChat/activities/SettingsActivity.java
// Path: lib/src/main/java/io/xpush/chat/view/activities/AppCompatPreferenceActivity.java // public abstract class AppCompatPreferenceActivity extends PreferenceActivity { // private AppCompatDelegate mDelegate; // @Override // protected void onCreate(Bundle savedInstanceState) { // getDelegate().installViewFactory(); // getDelegate().onCreate(savedInstanceState); // super.onCreate(savedInstanceState); // } // @Override // protected void onPostCreate(Bundle savedInstanceState) { // super.onPostCreate(savedInstanceState); // getDelegate().onPostCreate(savedInstanceState); // } // public ActionBar getSupportActionBar() { // return getDelegate().getSupportActionBar(); // } // public void setSupportActionBar(@Nullable Toolbar toolbar) { // getDelegate().setSupportActionBar(toolbar); // } // @Override // public MenuInflater getMenuInflater() { // return getDelegate().getMenuInflater(); // } // @Override // public void setContentView(@LayoutRes int layoutResID) { // getDelegate().setContentView(layoutResID); // } // @Override // public void setContentView(View view) { // getDelegate().setContentView(view); // } // @Override // public void setContentView(View view, ViewGroup.LayoutParams params) { // getDelegate().setContentView(view, params); // } // @Override // public void addContentView(View view, ViewGroup.LayoutParams params) { // getDelegate().addContentView(view, params); // } // @Override // protected void onPostResume() { // super.onPostResume(); // getDelegate().onPostResume(); // } // @Override // protected void onTitleChanged(CharSequence title, int color) { // super.onTitleChanged(title, color); // getDelegate().setTitle(title); // } // @Override // public void onConfigurationChanged(Configuration newConfig) { // super.onConfigurationChanged(newConfig); // getDelegate().onConfigurationChanged(newConfig); // } // @Override // protected void onStop() { // super.onStop(); // getDelegate().onStop(); // } // @Override // protected void onDestroy() { // super.onDestroy(); // getDelegate().onDestroy(); // } // public void invalidateOptionsMenu() { // getDelegate().invalidateOptionsMenu(); // } // private AppCompatDelegate getDelegate() { // if (mDelegate == null) { // mDelegate = AppCompatDelegate.create(this, null); // } // return mDelegate; // } // } // // Path: sample/src/main/java/io/xpush/sampleChat/fragments/SettingsFragment.java // public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener { // // private String TAG = SettingsFragment.class.getSimpleName(); // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // addPreferencesFromResource(R.xml.settings); // // for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) { // pickPreferenceObject(getPreferenceScreen().getPreference(i)); // } // } // // private void pickPreferenceObject(Preference p) { // if (p instanceof PreferenceCategory) { // PreferenceCategory category = (PreferenceCategory) p; // for (int i = 0; i < category.getPreferenceCount(); i++) { // pickPreferenceObject(category.getPreference(i)); // } // } else { // initSummary(p); // } // } // // private void initSummary(Preference p) { // // if (p instanceof EditTextPreference) { // EditTextPreference editTextPref = (EditTextPreference) p; // p.setSummary(editTextPref.getText()); // } // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // // View layout = inflater.inflate(R.layout.activity_settings, container, false); // if (layout != null) { // AppCompatPreferenceActivity activity = (AppCompatPreferenceActivity) getActivity(); // Toolbar toolbar = (Toolbar) layout.findViewById(R.id.toolbar); // activity.setSupportActionBar(toolbar); // // ActionBar bar = activity.getSupportActionBar(); // bar.setHomeButtonEnabled(true); // bar.setDisplayHomeAsUpEnabled(true); // bar.setDisplayShowTitleEnabled(true); // } // return layout; // } // // // @Override // public void onResume() { // super.onResume(); // // if (getView() != null) { // View frame = (View) getView().getParent(); // if (frame != null) // frame.setPadding(0, 0, 0, 0); // } // // getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); // } // // @Override // public void onPause() { // super.onPause(); // getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); // } // // // @Override // public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { // // if (key.equals("username")) { // Preference pref = findPreference(key); // pref.setSummary(sharedPreferences.getString(key, "")); // } else if (key.equals("email")) { // Preference pref = findPreference(key); // pref.setSummary(sharedPreferences.getString(key, "")); // } // } // }
import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import java.util.List; import io.xpush.chat.view.activities.AppCompatPreferenceActivity; import io.xpush.sampleChat.R; import io.xpush.sampleChat.fragments.SettingsFragment;
package io.xpush.sampleChat.activities; public class SettingsActivity extends AppCompatPreferenceActivity { @Override public void onBuildHeaders(List<Header> target) { } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings);
// Path: lib/src/main/java/io/xpush/chat/view/activities/AppCompatPreferenceActivity.java // public abstract class AppCompatPreferenceActivity extends PreferenceActivity { // private AppCompatDelegate mDelegate; // @Override // protected void onCreate(Bundle savedInstanceState) { // getDelegate().installViewFactory(); // getDelegate().onCreate(savedInstanceState); // super.onCreate(savedInstanceState); // } // @Override // protected void onPostCreate(Bundle savedInstanceState) { // super.onPostCreate(savedInstanceState); // getDelegate().onPostCreate(savedInstanceState); // } // public ActionBar getSupportActionBar() { // return getDelegate().getSupportActionBar(); // } // public void setSupportActionBar(@Nullable Toolbar toolbar) { // getDelegate().setSupportActionBar(toolbar); // } // @Override // public MenuInflater getMenuInflater() { // return getDelegate().getMenuInflater(); // } // @Override // public void setContentView(@LayoutRes int layoutResID) { // getDelegate().setContentView(layoutResID); // } // @Override // public void setContentView(View view) { // getDelegate().setContentView(view); // } // @Override // public void setContentView(View view, ViewGroup.LayoutParams params) { // getDelegate().setContentView(view, params); // } // @Override // public void addContentView(View view, ViewGroup.LayoutParams params) { // getDelegate().addContentView(view, params); // } // @Override // protected void onPostResume() { // super.onPostResume(); // getDelegate().onPostResume(); // } // @Override // protected void onTitleChanged(CharSequence title, int color) { // super.onTitleChanged(title, color); // getDelegate().setTitle(title); // } // @Override // public void onConfigurationChanged(Configuration newConfig) { // super.onConfigurationChanged(newConfig); // getDelegate().onConfigurationChanged(newConfig); // } // @Override // protected void onStop() { // super.onStop(); // getDelegate().onStop(); // } // @Override // protected void onDestroy() { // super.onDestroy(); // getDelegate().onDestroy(); // } // public void invalidateOptionsMenu() { // getDelegate().invalidateOptionsMenu(); // } // private AppCompatDelegate getDelegate() { // if (mDelegate == null) { // mDelegate = AppCompatDelegate.create(this, null); // } // return mDelegate; // } // } // // Path: sample/src/main/java/io/xpush/sampleChat/fragments/SettingsFragment.java // public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener { // // private String TAG = SettingsFragment.class.getSimpleName(); // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // addPreferencesFromResource(R.xml.settings); // // for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) { // pickPreferenceObject(getPreferenceScreen().getPreference(i)); // } // } // // private void pickPreferenceObject(Preference p) { // if (p instanceof PreferenceCategory) { // PreferenceCategory category = (PreferenceCategory) p; // for (int i = 0; i < category.getPreferenceCount(); i++) { // pickPreferenceObject(category.getPreference(i)); // } // } else { // initSummary(p); // } // } // // private void initSummary(Preference p) { // // if (p instanceof EditTextPreference) { // EditTextPreference editTextPref = (EditTextPreference) p; // p.setSummary(editTextPref.getText()); // } // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // // View layout = inflater.inflate(R.layout.activity_settings, container, false); // if (layout != null) { // AppCompatPreferenceActivity activity = (AppCompatPreferenceActivity) getActivity(); // Toolbar toolbar = (Toolbar) layout.findViewById(R.id.toolbar); // activity.setSupportActionBar(toolbar); // // ActionBar bar = activity.getSupportActionBar(); // bar.setHomeButtonEnabled(true); // bar.setDisplayHomeAsUpEnabled(true); // bar.setDisplayShowTitleEnabled(true); // } // return layout; // } // // // @Override // public void onResume() { // super.onResume(); // // if (getView() != null) { // View frame = (View) getView().getParent(); // if (frame != null) // frame.setPadding(0, 0, 0, 0); // } // // getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); // } // // @Override // public void onPause() { // super.onPause(); // getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); // } // // // @Override // public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { // // if (key.equals("username")) { // Preference pref = findPreference(key); // pref.setSummary(sharedPreferences.getString(key, "")); // } else if (key.equals("email")) { // Preference pref = findPreference(key); // pref.setSummary(sharedPreferences.getString(key, "")); // } // } // } // Path: sample/src/main/java/io/xpush/sampleChat/activities/SettingsActivity.java import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import java.util.List; import io.xpush.chat.view.activities.AppCompatPreferenceActivity; import io.xpush.sampleChat.R; import io.xpush.sampleChat.fragments.SettingsFragment; package io.xpush.sampleChat.activities; public class SettingsActivity extends AppCompatPreferenceActivity { @Override public void onBuildHeaders(List<Header> target) { } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings);
SettingsFragment f = new SettingsFragment();
xpush/lib-xpush-android
lib/src/main/java/io/xpush/chat/models/XPushMessage.java
// Path: lib/src/main/java/io/xpush/chat/persist/MessageTable.java // public class MessageTable { // // public static final String KEY_ROWID = "_id"; // public static final String KEY_ID = "id"; // public static final String KEY_CHANNEL = "channel"; // public static final String KEY_SENDER = "sender"; // public static final String KEY_IMAGE = "image"; // public static final String KEY_COUNT = "count"; // public static final String KEY_MESSAGE = "message"; // public static final String KEY_TYPE = "type"; // public static final String KEY_METADATA = "metadata"; // public static final String KEY_UPDATED = "received"; // public static String SQLITE_TABLE; // // public static final String[] ALL_PROJECTION = { // MessageTable.KEY_CHANNEL, // MessageTable.KEY_ID, // MessageTable.KEY_SENDER , // MessageTable.KEY_IMAGE , // MessageTable.KEY_COUNT , // MessageTable.KEY_MESSAGE , // MessageTable.KEY_TYPE , // MessageTable.KEY_METADATA , // MessageTable.KEY_UPDATED }; // // public static void onCreate(SQLiteDatabase db, String tableName) { // SQLITE_TABLE = tableName; // // db.execSQL("DROP TABLE IF EXISTS " + tableName); // // String DATABASE_CREATE = // "CREATE TABLE if not exists " + tableName + " (" + // KEY_ROWID + " integer PRIMARY KEY autoincrement," + // KEY_CHANNEL + ", " + // KEY_ID + "," + // KEY_SENDER + "," + // KEY_IMAGE + "," + // KEY_COUNT + " integer ," + // KEY_MESSAGE + "," + // KEY_TYPE + " integer , " + // KEY_METADATA + " ,"+ // KEY_UPDATED + " integer );"; // // db.execSQL(DATABASE_CREATE); // } // // public static void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion, String tableName) { // SQLITE_TABLE = tableName; // // db.execSQL("DROP TABLE IF EXISTS " + tableName); // onCreate(db, tableName); // } // }
import android.database.Cursor; import org.json.JSONException; import org.json.JSONObject; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Arrays; import io.xpush.chat.persist.MessageTable;
this.type = TYPE_IMAGE; } } // Message Metadata if( data.has("MD") ){ this.metadata = data.getJSONObject("MD"); } this.channel = data.getString("C"); if( data.has("US") ){ String usersStr = data.getString("US"); this.users = new ArrayList<String>(Arrays.asList(usersStr.split("@!@"))); } else if( this.channel != null && this.channel.indexOf("@!@") > -1 && this.channel.lastIndexOf("^") > 0 ){ String usersStr = this.channel.substring( 0, this.channel.lastIndexOf("^") ); this.users = new ArrayList<String>(Arrays.asList(usersStr.split("@!@"))); } this.message = URLDecoder.decode( data.getString("MG"), "UTF-8"); this.updated = data.getLong("TS"); this.id = channel +"_" + updated; } catch (Exception e) { e.printStackTrace(); } } public XPushMessage(Cursor cursor){
// Path: lib/src/main/java/io/xpush/chat/persist/MessageTable.java // public class MessageTable { // // public static final String KEY_ROWID = "_id"; // public static final String KEY_ID = "id"; // public static final String KEY_CHANNEL = "channel"; // public static final String KEY_SENDER = "sender"; // public static final String KEY_IMAGE = "image"; // public static final String KEY_COUNT = "count"; // public static final String KEY_MESSAGE = "message"; // public static final String KEY_TYPE = "type"; // public static final String KEY_METADATA = "metadata"; // public static final String KEY_UPDATED = "received"; // public static String SQLITE_TABLE; // // public static final String[] ALL_PROJECTION = { // MessageTable.KEY_CHANNEL, // MessageTable.KEY_ID, // MessageTable.KEY_SENDER , // MessageTable.KEY_IMAGE , // MessageTable.KEY_COUNT , // MessageTable.KEY_MESSAGE , // MessageTable.KEY_TYPE , // MessageTable.KEY_METADATA , // MessageTable.KEY_UPDATED }; // // public static void onCreate(SQLiteDatabase db, String tableName) { // SQLITE_TABLE = tableName; // // db.execSQL("DROP TABLE IF EXISTS " + tableName); // // String DATABASE_CREATE = // "CREATE TABLE if not exists " + tableName + " (" + // KEY_ROWID + " integer PRIMARY KEY autoincrement," + // KEY_CHANNEL + ", " + // KEY_ID + "," + // KEY_SENDER + "," + // KEY_IMAGE + "," + // KEY_COUNT + " integer ," + // KEY_MESSAGE + "," + // KEY_TYPE + " integer , " + // KEY_METADATA + " ,"+ // KEY_UPDATED + " integer );"; // // db.execSQL(DATABASE_CREATE); // } // // public static void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion, String tableName) { // SQLITE_TABLE = tableName; // // db.execSQL("DROP TABLE IF EXISTS " + tableName); // onCreate(db, tableName); // } // } // Path: lib/src/main/java/io/xpush/chat/models/XPushMessage.java import android.database.Cursor; import org.json.JSONException; import org.json.JSONObject; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Arrays; import io.xpush.chat.persist.MessageTable; this.type = TYPE_IMAGE; } } // Message Metadata if( data.has("MD") ){ this.metadata = data.getJSONObject("MD"); } this.channel = data.getString("C"); if( data.has("US") ){ String usersStr = data.getString("US"); this.users = new ArrayList<String>(Arrays.asList(usersStr.split("@!@"))); } else if( this.channel != null && this.channel.indexOf("@!@") > -1 && this.channel.lastIndexOf("^") > 0 ){ String usersStr = this.channel.substring( 0, this.channel.lastIndexOf("^") ); this.users = new ArrayList<String>(Arrays.asList(usersStr.split("@!@"))); } this.message = URLDecoder.decode( data.getString("MG"), "UTF-8"); this.updated = data.getLong("TS"); this.id = channel +"_" + updated; } catch (Exception e) { e.printStackTrace(); } } public XPushMessage(Cursor cursor){
this.rowId= cursor.getString(cursor.getColumnIndexOrThrow(MessageTable.KEY_MESSAGE));
xpush/lib-xpush-android
sample/src/main/java/io/xpush/sampleChat/fragments/SettingsFragment.java
// Path: lib/src/main/java/io/xpush/chat/view/activities/AppCompatPreferenceActivity.java // public abstract class AppCompatPreferenceActivity extends PreferenceActivity { // private AppCompatDelegate mDelegate; // @Override // protected void onCreate(Bundle savedInstanceState) { // getDelegate().installViewFactory(); // getDelegate().onCreate(savedInstanceState); // super.onCreate(savedInstanceState); // } // @Override // protected void onPostCreate(Bundle savedInstanceState) { // super.onPostCreate(savedInstanceState); // getDelegate().onPostCreate(savedInstanceState); // } // public ActionBar getSupportActionBar() { // return getDelegate().getSupportActionBar(); // } // public void setSupportActionBar(@Nullable Toolbar toolbar) { // getDelegate().setSupportActionBar(toolbar); // } // @Override // public MenuInflater getMenuInflater() { // return getDelegate().getMenuInflater(); // } // @Override // public void setContentView(@LayoutRes int layoutResID) { // getDelegate().setContentView(layoutResID); // } // @Override // public void setContentView(View view) { // getDelegate().setContentView(view); // } // @Override // public void setContentView(View view, ViewGroup.LayoutParams params) { // getDelegate().setContentView(view, params); // } // @Override // public void addContentView(View view, ViewGroup.LayoutParams params) { // getDelegate().addContentView(view, params); // } // @Override // protected void onPostResume() { // super.onPostResume(); // getDelegate().onPostResume(); // } // @Override // protected void onTitleChanged(CharSequence title, int color) { // super.onTitleChanged(title, color); // getDelegate().setTitle(title); // } // @Override // public void onConfigurationChanged(Configuration newConfig) { // super.onConfigurationChanged(newConfig); // getDelegate().onConfigurationChanged(newConfig); // } // @Override // protected void onStop() { // super.onStop(); // getDelegate().onStop(); // } // @Override // protected void onDestroy() { // super.onDestroy(); // getDelegate().onDestroy(); // } // public void invalidateOptionsMenu() { // getDelegate().invalidateOptionsMenu(); // } // private AppCompatDelegate getDelegate() { // if (mDelegate == null) { // mDelegate = AppCompatDelegate.create(this, null); // } // return mDelegate; // } // }
import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.EditTextPreference; import android.preference.Preference; import android.preference.PreferenceCategory; import android.preference.PreferenceFragment; import android.support.v7.app.ActionBar; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import io.xpush.chat.view.activities.AppCompatPreferenceActivity; import io.xpush.sampleChat.R;
for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) { pickPreferenceObject(getPreferenceScreen().getPreference(i)); } } private void pickPreferenceObject(Preference p) { if (p instanceof PreferenceCategory) { PreferenceCategory category = (PreferenceCategory) p; for (int i = 0; i < category.getPreferenceCount(); i++) { pickPreferenceObject(category.getPreference(i)); } } else { initSummary(p); } } private void initSummary(Preference p) { if (p instanceof EditTextPreference) { EditTextPreference editTextPref = (EditTextPreference) p; p.setSummary(editTextPref.getText()); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View layout = inflater.inflate(R.layout.activity_settings, container, false); if (layout != null) {
// Path: lib/src/main/java/io/xpush/chat/view/activities/AppCompatPreferenceActivity.java // public abstract class AppCompatPreferenceActivity extends PreferenceActivity { // private AppCompatDelegate mDelegate; // @Override // protected void onCreate(Bundle savedInstanceState) { // getDelegate().installViewFactory(); // getDelegate().onCreate(savedInstanceState); // super.onCreate(savedInstanceState); // } // @Override // protected void onPostCreate(Bundle savedInstanceState) { // super.onPostCreate(savedInstanceState); // getDelegate().onPostCreate(savedInstanceState); // } // public ActionBar getSupportActionBar() { // return getDelegate().getSupportActionBar(); // } // public void setSupportActionBar(@Nullable Toolbar toolbar) { // getDelegate().setSupportActionBar(toolbar); // } // @Override // public MenuInflater getMenuInflater() { // return getDelegate().getMenuInflater(); // } // @Override // public void setContentView(@LayoutRes int layoutResID) { // getDelegate().setContentView(layoutResID); // } // @Override // public void setContentView(View view) { // getDelegate().setContentView(view); // } // @Override // public void setContentView(View view, ViewGroup.LayoutParams params) { // getDelegate().setContentView(view, params); // } // @Override // public void addContentView(View view, ViewGroup.LayoutParams params) { // getDelegate().addContentView(view, params); // } // @Override // protected void onPostResume() { // super.onPostResume(); // getDelegate().onPostResume(); // } // @Override // protected void onTitleChanged(CharSequence title, int color) { // super.onTitleChanged(title, color); // getDelegate().setTitle(title); // } // @Override // public void onConfigurationChanged(Configuration newConfig) { // super.onConfigurationChanged(newConfig); // getDelegate().onConfigurationChanged(newConfig); // } // @Override // protected void onStop() { // super.onStop(); // getDelegate().onStop(); // } // @Override // protected void onDestroy() { // super.onDestroy(); // getDelegate().onDestroy(); // } // public void invalidateOptionsMenu() { // getDelegate().invalidateOptionsMenu(); // } // private AppCompatDelegate getDelegate() { // if (mDelegate == null) { // mDelegate = AppCompatDelegate.create(this, null); // } // return mDelegate; // } // } // Path: sample/src/main/java/io/xpush/sampleChat/fragments/SettingsFragment.java import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.EditTextPreference; import android.preference.Preference; import android.preference.PreferenceCategory; import android.preference.PreferenceFragment; import android.support.v7.app.ActionBar; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import io.xpush.chat.view.activities.AppCompatPreferenceActivity; import io.xpush.sampleChat.R; for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) { pickPreferenceObject(getPreferenceScreen().getPreference(i)); } } private void pickPreferenceObject(Preference p) { if (p instanceof PreferenceCategory) { PreferenceCategory category = (PreferenceCategory) p; for (int i = 0; i < category.getPreferenceCount(); i++) { pickPreferenceObject(category.getPreference(i)); } } else { initSummary(p); } } private void initSummary(Preference p) { if (p instanceof EditTextPreference) { EditTextPreference editTextPref = (EditTextPreference) p; p.setSummary(editTextPref.getText()); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View layout = inflater.inflate(R.layout.activity_settings, container, false); if (layout != null) {
AppCompatPreferenceActivity activity = (AppCompatPreferenceActivity) getActivity();
xpush/lib-xpush-android
lib/src/main/java/io/xpush/chat/services/RegistrationIntentService.java
// Path: lib/src/main/java/io/xpush/chat/ApplicationController.java // public class ApplicationController extends Application { // // public static final String TAG = ApplicationController.class.getSimpleName(); // private static ApplicationController mInstance; // // public static synchronized ApplicationController getInstance() { // return mInstance; // } // // @Override // public void onCreate() { // super.onCreate(); // mInstance = this; // XPushCore.initialize(this); // } // } // // Path: lib/src/main/java/io/xpush/chat/network/StringRequest.java // public class StringRequest extends Request<JSONObject> { // // public static final String TAG = StringRequest.class.getSimpleName(); // // private final Response.Listener<JSONObject> mListener; // // private Map<String, String> params; // // private String mUrl; // // // public StringRequest(String url, Response.Listener<JSONObject> listener, // Response.ErrorListener errorListener) { // super(Method.GET, url, errorListener); // this.mListener = listener; // this.params = null; // // } // // public StringRequest(String url, Map<String,String> params, Response.Listener<JSONObject> listener, // Response.ErrorListener errorListener) { // super(Method.POST, url, errorListener); // this.mListener = listener; // this.params = params; // // } // // @Override // protected void deliverResponse(JSONObject response) { // mListener.onResponse(response); // } // // @Override // protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) { // JSONObject parsed; // try { // parsed = new JSONObject( new String(response.data) ); // } catch (JSONException e) { // parsed = null; // } // // return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response)); // } // // @Override // protected Map<String,String> getParams(){ // return this.params; // } // } // // Path: lib/src/main/java/io/xpush/chat/persist/QuickstartPreferences.java // public class QuickstartPreferences { // // public static final String SENT_TOKEN_TO_SERVER = "sentTokenToServer"; // public static final String REGISTRATION_COMPLETE = "registrationComplete"; // // }
import android.app.IntentService; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.Volley; import com.google.android.gms.gcm.GcmPubSub; import com.google.android.gms.gcm.GoogleCloudMessaging; import com.google.android.gms.iid.InstanceID; import org.json.JSONObject; import java.io.IOException; import java.util.HashMap; import java.util.Map; import io.xpush.chat.ApplicationController; import io.xpush.chat.R; import io.xpush.chat.network.StringRequest; import io.xpush.chat.persist.QuickstartPreferences;
package io.xpush.chat.services; public class RegistrationIntentService extends IntentService { private static final String TAG = "RegIntentService"; private static final String[] TOPICS = {"global"}; public RegistrationIntentService() { super(TAG); } @Override protected void onHandleIntent(Intent intent) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); try { // In the (unlikely) event that multiple refresh operations occur simultaneously, // ensure that they are processed sequentially. synchronized (TAG) { // [START register_for_gcm] // Initially this call goes out to the network to retrieve the token, subsequent calls // are local. // [START get_token] InstanceID instanceID = InstanceID.getInstance(this); String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); // [END get_token] Log.i(TAG, "GCM Registration Token: " + token); sendRegistrationToServer(token); // Subscribe to topic channels subscribeTopics(token); // You should store a boolean that indicates whether the generated token has been // sent to your server. If the boolean is false, send the token to your server, // otherwise your server should have already received the token.
// Path: lib/src/main/java/io/xpush/chat/ApplicationController.java // public class ApplicationController extends Application { // // public static final String TAG = ApplicationController.class.getSimpleName(); // private static ApplicationController mInstance; // // public static synchronized ApplicationController getInstance() { // return mInstance; // } // // @Override // public void onCreate() { // super.onCreate(); // mInstance = this; // XPushCore.initialize(this); // } // } // // Path: lib/src/main/java/io/xpush/chat/network/StringRequest.java // public class StringRequest extends Request<JSONObject> { // // public static final String TAG = StringRequest.class.getSimpleName(); // // private final Response.Listener<JSONObject> mListener; // // private Map<String, String> params; // // private String mUrl; // // // public StringRequest(String url, Response.Listener<JSONObject> listener, // Response.ErrorListener errorListener) { // super(Method.GET, url, errorListener); // this.mListener = listener; // this.params = null; // // } // // public StringRequest(String url, Map<String,String> params, Response.Listener<JSONObject> listener, // Response.ErrorListener errorListener) { // super(Method.POST, url, errorListener); // this.mListener = listener; // this.params = params; // // } // // @Override // protected void deliverResponse(JSONObject response) { // mListener.onResponse(response); // } // // @Override // protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) { // JSONObject parsed; // try { // parsed = new JSONObject( new String(response.data) ); // } catch (JSONException e) { // parsed = null; // } // // return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response)); // } // // @Override // protected Map<String,String> getParams(){ // return this.params; // } // } // // Path: lib/src/main/java/io/xpush/chat/persist/QuickstartPreferences.java // public class QuickstartPreferences { // // public static final String SENT_TOKEN_TO_SERVER = "sentTokenToServer"; // public static final String REGISTRATION_COMPLETE = "registrationComplete"; // // } // Path: lib/src/main/java/io/xpush/chat/services/RegistrationIntentService.java import android.app.IntentService; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.Volley; import com.google.android.gms.gcm.GcmPubSub; import com.google.android.gms.gcm.GoogleCloudMessaging; import com.google.android.gms.iid.InstanceID; import org.json.JSONObject; import java.io.IOException; import java.util.HashMap; import java.util.Map; import io.xpush.chat.ApplicationController; import io.xpush.chat.R; import io.xpush.chat.network.StringRequest; import io.xpush.chat.persist.QuickstartPreferences; package io.xpush.chat.services; public class RegistrationIntentService extends IntentService { private static final String TAG = "RegIntentService"; private static final String[] TOPICS = {"global"}; public RegistrationIntentService() { super(TAG); } @Override protected void onHandleIntent(Intent intent) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); try { // In the (unlikely) event that multiple refresh operations occur simultaneously, // ensure that they are processed sequentially. synchronized (TAG) { // [START register_for_gcm] // Initially this call goes out to the network to retrieve the token, subsequent calls // are local. // [START get_token] InstanceID instanceID = InstanceID.getInstance(this); String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); // [END get_token] Log.i(TAG, "GCM Registration Token: " + token); sendRegistrationToServer(token); // Subscribe to topic channels subscribeTopics(token); // You should store a boolean that indicates whether the generated token has been // sent to your server. If the boolean is false, send the token to your server, // otherwise your server should have already received the token.
sharedPreferences.edit().putBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, true).apply();
xpush/lib-xpush-android
sample/src/main/java/io/xpush/sampleChat/activities/SearchUserActivity.java
// Path: sample/src/main/java/io/xpush/sampleChat/fragments/SearchUserFragment.java // public class SearchUserFragment extends Fragment { // // private static final String TAG = SearchUserFragment.class.getSimpleName(); // private static final int PAGE_SIZE = 50; // // private List<XPushUser> mXpushUsers = new ArrayList<XPushUser>(); // private SearchUserListAdapter mAdapter; // // private Activity mActivity; // private String mSearchKey = ""; // private int mViewPage; // // private LinearLayoutManager mLayoutManager; // // private RecyclerOnScrollListener mOnScrollListener; // private LoadMoreHandler mHandler; // // @Bind(R.id.tvMessage) // TextView mTvMessage; // // @Bind(R.id.listView) // RecyclerView mRecyclerView; // // @Bind(R.id.editSearch) // EditText mEditSearch; // // @Bind(R.id.iconSearch) // ImageView mIconSearch; // // @Override // public void onAttach(Activity activity) { // super.onAttach(activity); // mAdapter = new SearchUserListAdapter(this, mXpushUsers); // } // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // mActivity = getActivity(); // // View view = inflater.inflate(R.layout.fragment_search_users, container, false); // ButterKnife.bind(this, view); // // mEditSearch.addTextChangedListener(new TextWatcher() { // // @Override // public void afterTextChanged(Editable arg0) { // } // // @Override // public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // } // // @Override // public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // } // }); // // mEditSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() { // @Override // public boolean onEditorAction(TextView v, int id, KeyEvent event) { // if (id == R.id.search || id == EditorInfo.IME_NULL) { // search(); // return true; // } // return false; // } // }); // // mHandler = new LoadMoreHandler(); // return view; // } // // @Override // public void onViewCreated(View view, Bundle savedInstanceState) { // super.onViewCreated(view, savedInstanceState); // // mViewPage = 1; // displayListView(); // } // // @Override // public void onResume() { // super.onResume(); // } // // @OnClick(R.id.iconSearch) // public void search() { // mViewPage = 1; // mSearchKey = mEditSearch.getText().toString(); // searchUsers(mViewPage, true); // } // // private void displayListView() { // mRecyclerView.setAdapter(mAdapter); // mLayoutManager = new LinearLayoutManager(getActivity()); // mRecyclerView.setLayoutManager(mLayoutManager); // // mOnScrollListener = new RecyclerOnScrollListener(mLayoutManager, RecyclerOnScrollListener.RecylclerDirection.DOWN) { // @Override // public void onLoadMore(int currentPage) { // Log.d(TAG, " onLoadMore : " + currentPage); // searchUsers(++mViewPage, false); // } // }; // // mRecyclerView.addOnScrollListener(mOnScrollListener); // } // // public void searchUsers(int page, final boolean resetFlag) { // XPushCore.searchUser(getActivity(), mSearchKey, page, PAGE_SIZE, new CallbackEvent() { // // @Override // public void call(Object... args) { // if (args[0] instanceof ArrayList) { // ArrayList<XPushUser> users = (ArrayList<XPushUser>) args[0]; // // if (resetFlag) { // mXpushUsers.clear(); // } // // if (users.size() > 0) { // mXpushUsers.addAll(users); // mHandler.sendEmptyMessage(0); // } else { // mXpushUsers.clear(); // mHandler.sendEmptyMessage(1); // } // } // } // }); // } // // public void addFriend(final XPushUser user){ // XPushCore.addFriend( mActivity, user, new CallbackEvent(){ // @Override // public void call(Object... args) { // if( args == null || args.length == 0 ){ // mActivity.finish(); // } // } // }); // } // // // Handler 클래스 // class LoadMoreHandler extends Handler { // // @Override // public void handleMessage(Message msg) { // super.handleMessage(msg); // // switch (msg.what) { // case 0: // mTvMessage.setVisibility(View.INVISIBLE); // mAdapter.notifyDataSetChanged(); // break; // case 1: // mTvMessage.setVisibility(View.VISIBLE); // mTvMessage.setText(R.string.message_no_search_user); // mAdapter.notifyDataSetChanged(); // break; // } // } // }; // }
import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import io.xpush.sampleChat.R; import io.xpush.sampleChat.fragments.SearchUserFragment;
package io.xpush.sampleChat.activities; public class SearchUserActivity extends AppCompatActivity { public static final String TAG = SearchUserActivity.class.getSimpleName();
// Path: sample/src/main/java/io/xpush/sampleChat/fragments/SearchUserFragment.java // public class SearchUserFragment extends Fragment { // // private static final String TAG = SearchUserFragment.class.getSimpleName(); // private static final int PAGE_SIZE = 50; // // private List<XPushUser> mXpushUsers = new ArrayList<XPushUser>(); // private SearchUserListAdapter mAdapter; // // private Activity mActivity; // private String mSearchKey = ""; // private int mViewPage; // // private LinearLayoutManager mLayoutManager; // // private RecyclerOnScrollListener mOnScrollListener; // private LoadMoreHandler mHandler; // // @Bind(R.id.tvMessage) // TextView mTvMessage; // // @Bind(R.id.listView) // RecyclerView mRecyclerView; // // @Bind(R.id.editSearch) // EditText mEditSearch; // // @Bind(R.id.iconSearch) // ImageView mIconSearch; // // @Override // public void onAttach(Activity activity) { // super.onAttach(activity); // mAdapter = new SearchUserListAdapter(this, mXpushUsers); // } // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // } // // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // mActivity = getActivity(); // // View view = inflater.inflate(R.layout.fragment_search_users, container, false); // ButterKnife.bind(this, view); // // mEditSearch.addTextChangedListener(new TextWatcher() { // // @Override // public void afterTextChanged(Editable arg0) { // } // // @Override // public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // } // // @Override // public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // } // }); // // mEditSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() { // @Override // public boolean onEditorAction(TextView v, int id, KeyEvent event) { // if (id == R.id.search || id == EditorInfo.IME_NULL) { // search(); // return true; // } // return false; // } // }); // // mHandler = new LoadMoreHandler(); // return view; // } // // @Override // public void onViewCreated(View view, Bundle savedInstanceState) { // super.onViewCreated(view, savedInstanceState); // // mViewPage = 1; // displayListView(); // } // // @Override // public void onResume() { // super.onResume(); // } // // @OnClick(R.id.iconSearch) // public void search() { // mViewPage = 1; // mSearchKey = mEditSearch.getText().toString(); // searchUsers(mViewPage, true); // } // // private void displayListView() { // mRecyclerView.setAdapter(mAdapter); // mLayoutManager = new LinearLayoutManager(getActivity()); // mRecyclerView.setLayoutManager(mLayoutManager); // // mOnScrollListener = new RecyclerOnScrollListener(mLayoutManager, RecyclerOnScrollListener.RecylclerDirection.DOWN) { // @Override // public void onLoadMore(int currentPage) { // Log.d(TAG, " onLoadMore : " + currentPage); // searchUsers(++mViewPage, false); // } // }; // // mRecyclerView.addOnScrollListener(mOnScrollListener); // } // // public void searchUsers(int page, final boolean resetFlag) { // XPushCore.searchUser(getActivity(), mSearchKey, page, PAGE_SIZE, new CallbackEvent() { // // @Override // public void call(Object... args) { // if (args[0] instanceof ArrayList) { // ArrayList<XPushUser> users = (ArrayList<XPushUser>) args[0]; // // if (resetFlag) { // mXpushUsers.clear(); // } // // if (users.size() > 0) { // mXpushUsers.addAll(users); // mHandler.sendEmptyMessage(0); // } else { // mXpushUsers.clear(); // mHandler.sendEmptyMessage(1); // } // } // } // }); // } // // public void addFriend(final XPushUser user){ // XPushCore.addFriend( mActivity, user, new CallbackEvent(){ // @Override // public void call(Object... args) { // if( args == null || args.length == 0 ){ // mActivity.finish(); // } // } // }); // } // // // Handler 클래스 // class LoadMoreHandler extends Handler { // // @Override // public void handleMessage(Message msg) { // super.handleMessage(msg); // // switch (msg.what) { // case 0: // mTvMessage.setVisibility(View.INVISIBLE); // mAdapter.notifyDataSetChanged(); // break; // case 1: // mTvMessage.setVisibility(View.VISIBLE); // mTvMessage.setText(R.string.message_no_search_user); // mAdapter.notifyDataSetChanged(); // break; // } // } // }; // } // Path: sample/src/main/java/io/xpush/sampleChat/activities/SearchUserActivity.java import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import io.xpush.sampleChat.R; import io.xpush.sampleChat.fragments.SearchUserFragment; package io.xpush.sampleChat.activities; public class SearchUserActivity extends AppCompatActivity { public static final String TAG = SearchUserActivity.class.getSimpleName();
private SearchUserFragment f;
xpush/lib-xpush-android
lib/src/main/java/io/xpush/chat/models/XPushUser.java
// Path: lib/src/main/java/io/xpush/chat/persist/UserTable.java // public class UserTable { // // public static final String KEY_ROWID = "_id"; // public static final String KEY_ID = "id"; // public static final String KEY_NAME = "name"; // public static final String KEY_IMAGE = "image"; // public static final String KEY_MESSAGE = "message"; // public static final String KEY_UPDATED = "updated"; // public static final String KEY_TYPE = "type"; // public static String SQLITE_TABLE; // // public static void onCreate(SQLiteDatabase db, String tableName) { // SQLITE_TABLE = tableName; // // db.execSQL("DROP TABLE IF EXISTS " + tableName); // // String DATABASE_CREATE = // "CREATE TABLE if not exists " + tableName + " (" + // KEY_ROWID + " integer PRIMARY KEY autoincrement," + // KEY_ID + " unique ," + // KEY_NAME + "," + // KEY_IMAGE + "," + // KEY_MESSAGE + "," + // KEY_TYPE +" integer," + // KEY_UPDATED + " integer );"; // // db.execSQL(DATABASE_CREATE); // } // // public static void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion, String tableName) { // SQLITE_TABLE = tableName; // // db.execSQL("DROP TABLE IF EXISTS " + tableName); // onCreate(db, tableName); // } // }
import android.database.Cursor; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import org.json.JSONObject; import io.xpush.chat.persist.UserTable;
} public void setMessage(String message) { this.message = message; } public int getType() { return type; } public void setType(int type) { this.type = type; } public long getUpdated() { return updated; } public void setUpdated(long updated) { this.updated = updated; } public XPushUser(){ } public XPushUser(Parcel in) { readFromParcel(in); } public XPushUser(Cursor cursor){
// Path: lib/src/main/java/io/xpush/chat/persist/UserTable.java // public class UserTable { // // public static final String KEY_ROWID = "_id"; // public static final String KEY_ID = "id"; // public static final String KEY_NAME = "name"; // public static final String KEY_IMAGE = "image"; // public static final String KEY_MESSAGE = "message"; // public static final String KEY_UPDATED = "updated"; // public static final String KEY_TYPE = "type"; // public static String SQLITE_TABLE; // // public static void onCreate(SQLiteDatabase db, String tableName) { // SQLITE_TABLE = tableName; // // db.execSQL("DROP TABLE IF EXISTS " + tableName); // // String DATABASE_CREATE = // "CREATE TABLE if not exists " + tableName + " (" + // KEY_ROWID + " integer PRIMARY KEY autoincrement," + // KEY_ID + " unique ," + // KEY_NAME + "," + // KEY_IMAGE + "," + // KEY_MESSAGE + "," + // KEY_TYPE +" integer," + // KEY_UPDATED + " integer );"; // // db.execSQL(DATABASE_CREATE); // } // // public static void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion, String tableName) { // SQLITE_TABLE = tableName; // // db.execSQL("DROP TABLE IF EXISTS " + tableName); // onCreate(db, tableName); // } // } // Path: lib/src/main/java/io/xpush/chat/models/XPushUser.java import android.database.Cursor; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import org.json.JSONObject; import io.xpush.chat.persist.UserTable; } public void setMessage(String message) { this.message = message; } public int getType() { return type; } public void setType(int type) { this.type = type; } public long getUpdated() { return updated; } public void setUpdated(long updated) { this.updated = updated; } public XPushUser(){ } public XPushUser(Parcel in) { readFromParcel(in); } public XPushUser(Cursor cursor){
this.rowId= cursor.getString(cursor.getColumnIndexOrThrow(UserTable.KEY_ROWID));
xpush/lib-xpush-android
lib/src/main/java/io/xpush/chat/services/BadgeIntentService.java
// Path: lib/src/main/java/io/xpush/chat/persist/ChannelTable.java // public class ChannelTable { // // public static final String KEY_ROWID = "_id"; // public static final String KEY_ID = "id"; // public static final String KEY_NAME = "name"; // public static final String KEY_USERS = "users"; // public static final String KEY_IMAGE = "image"; // public static final String KEY_COUNT = "count"; // public static final String KEY_MESSAGE = "message"; // public static final String KEY_MESSAGE_TYPE = "message_type"; // public static final String KEY_UPDATED = "updated"; // public static String SQLITE_TABLE; // // public static final String[] ALL_PROJECTION = { // KEY_ROWID, // KEY_ID, // KEY_NAME, // KEY_USERS, // KEY_IMAGE, // KEY_COUNT, // KEY_MESSAGE, // KEY_MESSAGE_TYPE, // KEY_UPDATED // }; // // public static void onCreate(SQLiteDatabase db, String tableName) { // SQLITE_TABLE = tableName; // // db.execSQL("DROP TABLE IF EXISTS " + tableName); // // String DATABASE_CREATE = // "CREATE TABLE if not exists " + tableName + " (" + // KEY_ROWID + " integer PRIMARY KEY autoincrement," + // KEY_ID + " unique ," + // KEY_NAME + "," + // KEY_USERS + "," + // KEY_IMAGE + "," + // KEY_COUNT + " integer ," + // KEY_MESSAGE + "," + // KEY_MESSAGE_TYPE + " integer ,"+ // KEY_UPDATED + " integer );"; // // db.execSQL(DATABASE_CREATE); // } // // public static void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion, String tableName) { // SQLITE_TABLE = tableName; // // db.execSQL("DROP TABLE IF EXISTS " + tableName); // onCreate(db, tableName); // } // } // // Path: lib/src/main/java/io/xpush/chat/persist/DBHelper.java // public class DBHelper extends SQLiteOpenHelper { // // private static final String DATABASE_NAME = "xpush.db"; // private static final int DATABASE_VERSION = 2; // private String CHANNEL_TABLE_NAME; // private String MESSAGE_TABLE_NAME; // private String USER_TABLE_NAME; // // public DBHelper(Context context) { // super(context, DATABASE_NAME, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); // CHANNEL_TABLE_NAME = context.getString(R.string.channel_table_name); // MESSAGE_TABLE_NAME = context.getString(R.string.message_table_name); // USER_TABLE_NAME = context.getString(R.string.user_table_name); // } // // @Override // public void onCreate(SQLiteDatabase db) { // MessageTable.onCreate(db, MESSAGE_TABLE_NAME); // ChannelTable.onCreate(db, CHANNEL_TABLE_NAME); // UserTable.onCreate(db,USER_TABLE_NAME); // } // // @Override // public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // MessageTable.onUpgrade(db, oldVersion, newVersion, MESSAGE_TABLE_NAME); // ChannelTable.onUpgrade(db, oldVersion, newVersion, CHANNEL_TABLE_NAME); // UserTable.onUpgrade(db, oldVersion, newVersion, USER_TABLE_NAME); // } // }
import android.app.IntentService; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import io.xpush.chat.R; import io.xpush.chat.persist.ChannelTable; import io.xpush.chat.persist.DBHelper; import me.leolin.shortcutbadger.ShortcutBadger;
/** * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.xpush.chat.services; public class BadgeIntentService extends IntentService { private static final String TAG = BadgeIntentService.class.getSimpleName(); public BadgeIntentService() { super(TAG); } @Override protected void onHandleIntent(Intent intent) {
// Path: lib/src/main/java/io/xpush/chat/persist/ChannelTable.java // public class ChannelTable { // // public static final String KEY_ROWID = "_id"; // public static final String KEY_ID = "id"; // public static final String KEY_NAME = "name"; // public static final String KEY_USERS = "users"; // public static final String KEY_IMAGE = "image"; // public static final String KEY_COUNT = "count"; // public static final String KEY_MESSAGE = "message"; // public static final String KEY_MESSAGE_TYPE = "message_type"; // public static final String KEY_UPDATED = "updated"; // public static String SQLITE_TABLE; // // public static final String[] ALL_PROJECTION = { // KEY_ROWID, // KEY_ID, // KEY_NAME, // KEY_USERS, // KEY_IMAGE, // KEY_COUNT, // KEY_MESSAGE, // KEY_MESSAGE_TYPE, // KEY_UPDATED // }; // // public static void onCreate(SQLiteDatabase db, String tableName) { // SQLITE_TABLE = tableName; // // db.execSQL("DROP TABLE IF EXISTS " + tableName); // // String DATABASE_CREATE = // "CREATE TABLE if not exists " + tableName + " (" + // KEY_ROWID + " integer PRIMARY KEY autoincrement," + // KEY_ID + " unique ," + // KEY_NAME + "," + // KEY_USERS + "," + // KEY_IMAGE + "," + // KEY_COUNT + " integer ," + // KEY_MESSAGE + "," + // KEY_MESSAGE_TYPE + " integer ,"+ // KEY_UPDATED + " integer );"; // // db.execSQL(DATABASE_CREATE); // } // // public static void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion, String tableName) { // SQLITE_TABLE = tableName; // // db.execSQL("DROP TABLE IF EXISTS " + tableName); // onCreate(db, tableName); // } // } // // Path: lib/src/main/java/io/xpush/chat/persist/DBHelper.java // public class DBHelper extends SQLiteOpenHelper { // // private static final String DATABASE_NAME = "xpush.db"; // private static final int DATABASE_VERSION = 2; // private String CHANNEL_TABLE_NAME; // private String MESSAGE_TABLE_NAME; // private String USER_TABLE_NAME; // // public DBHelper(Context context) { // super(context, DATABASE_NAME, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); // CHANNEL_TABLE_NAME = context.getString(R.string.channel_table_name); // MESSAGE_TABLE_NAME = context.getString(R.string.message_table_name); // USER_TABLE_NAME = context.getString(R.string.user_table_name); // } // // @Override // public void onCreate(SQLiteDatabase db) { // MessageTable.onCreate(db, MESSAGE_TABLE_NAME); // ChannelTable.onCreate(db, CHANNEL_TABLE_NAME); // UserTable.onCreate(db,USER_TABLE_NAME); // } // // @Override // public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // MessageTable.onUpgrade(db, oldVersion, newVersion, MESSAGE_TABLE_NAME); // ChannelTable.onUpgrade(db, oldVersion, newVersion, CHANNEL_TABLE_NAME); // UserTable.onUpgrade(db, oldVersion, newVersion, USER_TABLE_NAME); // } // } // Path: lib/src/main/java/io/xpush/chat/services/BadgeIntentService.java import android.app.IntentService; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import io.xpush.chat.R; import io.xpush.chat.persist.ChannelTable; import io.xpush.chat.persist.DBHelper; import me.leolin.shortcutbadger.ShortcutBadger; /** * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.xpush.chat.services; public class BadgeIntentService extends IntentService { private static final String TAG = BadgeIntentService.class.getSimpleName(); public BadgeIntentService() { super(TAG); } @Override protected void onHandleIntent(Intent intent) {
DBHelper mDbHelper = new DBHelper(getApplicationContext());
xpush/lib-xpush-android
lib/src/main/java/io/xpush/chat/services/BadgeIntentService.java
// Path: lib/src/main/java/io/xpush/chat/persist/ChannelTable.java // public class ChannelTable { // // public static final String KEY_ROWID = "_id"; // public static final String KEY_ID = "id"; // public static final String KEY_NAME = "name"; // public static final String KEY_USERS = "users"; // public static final String KEY_IMAGE = "image"; // public static final String KEY_COUNT = "count"; // public static final String KEY_MESSAGE = "message"; // public static final String KEY_MESSAGE_TYPE = "message_type"; // public static final String KEY_UPDATED = "updated"; // public static String SQLITE_TABLE; // // public static final String[] ALL_PROJECTION = { // KEY_ROWID, // KEY_ID, // KEY_NAME, // KEY_USERS, // KEY_IMAGE, // KEY_COUNT, // KEY_MESSAGE, // KEY_MESSAGE_TYPE, // KEY_UPDATED // }; // // public static void onCreate(SQLiteDatabase db, String tableName) { // SQLITE_TABLE = tableName; // // db.execSQL("DROP TABLE IF EXISTS " + tableName); // // String DATABASE_CREATE = // "CREATE TABLE if not exists " + tableName + " (" + // KEY_ROWID + " integer PRIMARY KEY autoincrement," + // KEY_ID + " unique ," + // KEY_NAME + "," + // KEY_USERS + "," + // KEY_IMAGE + "," + // KEY_COUNT + " integer ," + // KEY_MESSAGE + "," + // KEY_MESSAGE_TYPE + " integer ,"+ // KEY_UPDATED + " integer );"; // // db.execSQL(DATABASE_CREATE); // } // // public static void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion, String tableName) { // SQLITE_TABLE = tableName; // // db.execSQL("DROP TABLE IF EXISTS " + tableName); // onCreate(db, tableName); // } // } // // Path: lib/src/main/java/io/xpush/chat/persist/DBHelper.java // public class DBHelper extends SQLiteOpenHelper { // // private static final String DATABASE_NAME = "xpush.db"; // private static final int DATABASE_VERSION = 2; // private String CHANNEL_TABLE_NAME; // private String MESSAGE_TABLE_NAME; // private String USER_TABLE_NAME; // // public DBHelper(Context context) { // super(context, DATABASE_NAME, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); // CHANNEL_TABLE_NAME = context.getString(R.string.channel_table_name); // MESSAGE_TABLE_NAME = context.getString(R.string.message_table_name); // USER_TABLE_NAME = context.getString(R.string.user_table_name); // } // // @Override // public void onCreate(SQLiteDatabase db) { // MessageTable.onCreate(db, MESSAGE_TABLE_NAME); // ChannelTable.onCreate(db, CHANNEL_TABLE_NAME); // UserTable.onCreate(db,USER_TABLE_NAME); // } // // @Override // public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // MessageTable.onUpgrade(db, oldVersion, newVersion, MESSAGE_TABLE_NAME); // ChannelTable.onUpgrade(db, oldVersion, newVersion, CHANNEL_TABLE_NAME); // UserTable.onUpgrade(db, oldVersion, newVersion, USER_TABLE_NAME); // } // }
import android.app.IntentService; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import io.xpush.chat.R; import io.xpush.chat.persist.ChannelTable; import io.xpush.chat.persist.DBHelper; import me.leolin.shortcutbadger.ShortcutBadger;
/** * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.xpush.chat.services; public class BadgeIntentService extends IntentService { private static final String TAG = BadgeIntentService.class.getSimpleName(); public BadgeIntentService() { super(TAG); } @Override protected void onHandleIntent(Intent intent) { DBHelper mDbHelper = new DBHelper(getApplicationContext()); SQLiteDatabase mDatabase = mDbHelper.getReadableDatabase();
// Path: lib/src/main/java/io/xpush/chat/persist/ChannelTable.java // public class ChannelTable { // // public static final String KEY_ROWID = "_id"; // public static final String KEY_ID = "id"; // public static final String KEY_NAME = "name"; // public static final String KEY_USERS = "users"; // public static final String KEY_IMAGE = "image"; // public static final String KEY_COUNT = "count"; // public static final String KEY_MESSAGE = "message"; // public static final String KEY_MESSAGE_TYPE = "message_type"; // public static final String KEY_UPDATED = "updated"; // public static String SQLITE_TABLE; // // public static final String[] ALL_PROJECTION = { // KEY_ROWID, // KEY_ID, // KEY_NAME, // KEY_USERS, // KEY_IMAGE, // KEY_COUNT, // KEY_MESSAGE, // KEY_MESSAGE_TYPE, // KEY_UPDATED // }; // // public static void onCreate(SQLiteDatabase db, String tableName) { // SQLITE_TABLE = tableName; // // db.execSQL("DROP TABLE IF EXISTS " + tableName); // // String DATABASE_CREATE = // "CREATE TABLE if not exists " + tableName + " (" + // KEY_ROWID + " integer PRIMARY KEY autoincrement," + // KEY_ID + " unique ," + // KEY_NAME + "," + // KEY_USERS + "," + // KEY_IMAGE + "," + // KEY_COUNT + " integer ," + // KEY_MESSAGE + "," + // KEY_MESSAGE_TYPE + " integer ,"+ // KEY_UPDATED + " integer );"; // // db.execSQL(DATABASE_CREATE); // } // // public static void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion, String tableName) { // SQLITE_TABLE = tableName; // // db.execSQL("DROP TABLE IF EXISTS " + tableName); // onCreate(db, tableName); // } // } // // Path: lib/src/main/java/io/xpush/chat/persist/DBHelper.java // public class DBHelper extends SQLiteOpenHelper { // // private static final String DATABASE_NAME = "xpush.db"; // private static final int DATABASE_VERSION = 2; // private String CHANNEL_TABLE_NAME; // private String MESSAGE_TABLE_NAME; // private String USER_TABLE_NAME; // // public DBHelper(Context context) { // super(context, DATABASE_NAME, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); // CHANNEL_TABLE_NAME = context.getString(R.string.channel_table_name); // MESSAGE_TABLE_NAME = context.getString(R.string.message_table_name); // USER_TABLE_NAME = context.getString(R.string.user_table_name); // } // // @Override // public void onCreate(SQLiteDatabase db) { // MessageTable.onCreate(db, MESSAGE_TABLE_NAME); // ChannelTable.onCreate(db, CHANNEL_TABLE_NAME); // UserTable.onCreate(db,USER_TABLE_NAME); // } // // @Override // public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // MessageTable.onUpgrade(db, oldVersion, newVersion, MESSAGE_TABLE_NAME); // ChannelTable.onUpgrade(db, oldVersion, newVersion, CHANNEL_TABLE_NAME); // UserTable.onUpgrade(db, oldVersion, newVersion, USER_TABLE_NAME); // } // } // Path: lib/src/main/java/io/xpush/chat/services/BadgeIntentService.java import android.app.IntentService; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import io.xpush.chat.R; import io.xpush.chat.persist.ChannelTable; import io.xpush.chat.persist.DBHelper; import me.leolin.shortcutbadger.ShortcutBadger; /** * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.xpush.chat.services; public class BadgeIntentService extends IntentService { private static final String TAG = BadgeIntentService.class.getSimpleName(); public BadgeIntentService() { super(TAG); } @Override protected void onHandleIntent(Intent intent) { DBHelper mDbHelper = new DBHelper(getApplicationContext()); SQLiteDatabase mDatabase = mDbHelper.getReadableDatabase();
Cursor mCount = mDatabase.rawQuery("select sum(" + ChannelTable.KEY_COUNT + ") from " + getApplicationContext().getString(R.string.channel_table_name), null);
xpush/lib-xpush-android
lib/src/main/java/io/xpush/chat/models/XPushChannel.java
// Path: lib/src/main/java/io/xpush/chat/persist/ChannelTable.java // public class ChannelTable { // // public static final String KEY_ROWID = "_id"; // public static final String KEY_ID = "id"; // public static final String KEY_NAME = "name"; // public static final String KEY_USERS = "users"; // public static final String KEY_IMAGE = "image"; // public static final String KEY_COUNT = "count"; // public static final String KEY_MESSAGE = "message"; // public static final String KEY_MESSAGE_TYPE = "message_type"; // public static final String KEY_UPDATED = "updated"; // public static String SQLITE_TABLE; // // public static final String[] ALL_PROJECTION = { // KEY_ROWID, // KEY_ID, // KEY_NAME, // KEY_USERS, // KEY_IMAGE, // KEY_COUNT, // KEY_MESSAGE, // KEY_MESSAGE_TYPE, // KEY_UPDATED // }; // // public static void onCreate(SQLiteDatabase db, String tableName) { // SQLITE_TABLE = tableName; // // db.execSQL("DROP TABLE IF EXISTS " + tableName); // // String DATABASE_CREATE = // "CREATE TABLE if not exists " + tableName + " (" + // KEY_ROWID + " integer PRIMARY KEY autoincrement," + // KEY_ID + " unique ," + // KEY_NAME + "," + // KEY_USERS + "," + // KEY_IMAGE + "," + // KEY_COUNT + " integer ," + // KEY_MESSAGE + "," + // KEY_MESSAGE_TYPE + " integer ,"+ // KEY_UPDATED + " integer );"; // // db.execSQL(DATABASE_CREATE); // } // // public static void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion, String tableName) { // SQLITE_TABLE = tableName; // // db.execSQL("DROP TABLE IF EXISTS " + tableName); // onCreate(db, tableName); // } // }
import android.database.Cursor; import android.os.Bundle; import java.util.ArrayList; import java.util.Arrays; import io.xpush.chat.persist.ChannelTable;
} public long getUpdated() { return updated; } public void setUpdated(long updated) { this.updated = updated; } public int getMessageType(){ return messageType; } public void setMessageType(int messageType){ this.messageType = messageType; } public ArrayList<String> getUserNames() { return userNames; } public void setUserNames(ArrayList<String> userNames) { this.userNames = userNames; } public XPushChannel(){ } public XPushChannel(Cursor cursor){
// Path: lib/src/main/java/io/xpush/chat/persist/ChannelTable.java // public class ChannelTable { // // public static final String KEY_ROWID = "_id"; // public static final String KEY_ID = "id"; // public static final String KEY_NAME = "name"; // public static final String KEY_USERS = "users"; // public static final String KEY_IMAGE = "image"; // public static final String KEY_COUNT = "count"; // public static final String KEY_MESSAGE = "message"; // public static final String KEY_MESSAGE_TYPE = "message_type"; // public static final String KEY_UPDATED = "updated"; // public static String SQLITE_TABLE; // // public static final String[] ALL_PROJECTION = { // KEY_ROWID, // KEY_ID, // KEY_NAME, // KEY_USERS, // KEY_IMAGE, // KEY_COUNT, // KEY_MESSAGE, // KEY_MESSAGE_TYPE, // KEY_UPDATED // }; // // public static void onCreate(SQLiteDatabase db, String tableName) { // SQLITE_TABLE = tableName; // // db.execSQL("DROP TABLE IF EXISTS " + tableName); // // String DATABASE_CREATE = // "CREATE TABLE if not exists " + tableName + " (" + // KEY_ROWID + " integer PRIMARY KEY autoincrement," + // KEY_ID + " unique ," + // KEY_NAME + "," + // KEY_USERS + "," + // KEY_IMAGE + "," + // KEY_COUNT + " integer ," + // KEY_MESSAGE + "," + // KEY_MESSAGE_TYPE + " integer ,"+ // KEY_UPDATED + " integer );"; // // db.execSQL(DATABASE_CREATE); // } // // public static void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion, String tableName) { // SQLITE_TABLE = tableName; // // db.execSQL("DROP TABLE IF EXISTS " + tableName); // onCreate(db, tableName); // } // } // Path: lib/src/main/java/io/xpush/chat/models/XPushChannel.java import android.database.Cursor; import android.os.Bundle; import java.util.ArrayList; import java.util.Arrays; import io.xpush.chat.persist.ChannelTable; } public long getUpdated() { return updated; } public void setUpdated(long updated) { this.updated = updated; } public int getMessageType(){ return messageType; } public void setMessageType(int messageType){ this.messageType = messageType; } public ArrayList<String> getUserNames() { return userNames; } public void setUserNames(ArrayList<String> userNames) { this.userNames = userNames; } public XPushChannel(){ } public XPushChannel(Cursor cursor){
this.rowId= cursor.getString(cursor.getColumnIndexOrThrow(ChannelTable.KEY_ROWID));
msgpack-rpc/msgpack-rpc-java
src/main/java/org/msgpack/rpc/builder/DefaultDispatcherBuilder.java
// Path: src/main/java/org/msgpack/rpc/reflect/Reflect.java // public class Reflect { // /* // * private static final Reflect instance = new Reflect(); // * // * public static <T> Proxy<T> reflectProxy(Class<T> iface) { return // * instance.getProxy(iface); } // * // * public static Invoker reflectInvoker(Method method) { return // * instance.getInvoker(method); } // */ // // private Map<Class<?>, Proxy<?>> proxyCache = new HashMap<Class<?>, Proxy<?>>(); // // private Map<Method, Invoker> invokerCache = new HashMap<Method, Invoker>(); // // private InvokerBuilder invokerBuilder; // private ProxyBuilder proxyBuilder; // // public Reflect(MessagePack messagePack) { // invokerBuilder = new ReflectionInvokerBuilder(messagePack); // proxyBuilder = new ReflectionProxyBuilder(messagePack); // } // // public Reflect( InvokerBuilder invokerBuilder,ProxyBuilder proxyBuilder) { // this.invokerBuilder = invokerBuilder; // this.proxyBuilder = proxyBuilder; // } // // public synchronized <T> Proxy<T> getProxy(Class<T> iface) { // Proxy<?> proxy = proxyCache.get(iface); // if (proxy == null) { // proxy = proxyBuilder.buildProxy(iface);// ProxyBuilder.build(iface); // proxyCache.put(iface, proxy); // } // return (Proxy<T>) proxy; // } // // public synchronized Invoker getInvoker(Method method) { // Invoker invoker = invokerCache.get(method); // if (invoker == null) { // invoker = invokerBuilder.buildInvoker(method); // invokerCache.put(method, invoker); // } // return invoker; // } // }
import org.msgpack.MessagePack; import org.msgpack.rpc.dispatcher.Dispatcher; import org.msgpack.rpc.dispatcher.MethodDispatcher; import org.msgpack.rpc.reflect.Reflect;
package org.msgpack.rpc.builder; /** * User: takeshita * Create: 12/06/15 1:16 */ public class DefaultDispatcherBuilder implements DispatcherBuilder { public Dispatcher build(Object handler, MessagePack messagePack) { return new MethodDispatcher(
// Path: src/main/java/org/msgpack/rpc/reflect/Reflect.java // public class Reflect { // /* // * private static final Reflect instance = new Reflect(); // * // * public static <T> Proxy<T> reflectProxy(Class<T> iface) { return // * instance.getProxy(iface); } // * // * public static Invoker reflectInvoker(Method method) { return // * instance.getInvoker(method); } // */ // // private Map<Class<?>, Proxy<?>> proxyCache = new HashMap<Class<?>, Proxy<?>>(); // // private Map<Method, Invoker> invokerCache = new HashMap<Method, Invoker>(); // // private InvokerBuilder invokerBuilder; // private ProxyBuilder proxyBuilder; // // public Reflect(MessagePack messagePack) { // invokerBuilder = new ReflectionInvokerBuilder(messagePack); // proxyBuilder = new ReflectionProxyBuilder(messagePack); // } // // public Reflect( InvokerBuilder invokerBuilder,ProxyBuilder proxyBuilder) { // this.invokerBuilder = invokerBuilder; // this.proxyBuilder = proxyBuilder; // } // // public synchronized <T> Proxy<T> getProxy(Class<T> iface) { // Proxy<?> proxy = proxyCache.get(iface); // if (proxy == null) { // proxy = proxyBuilder.buildProxy(iface);// ProxyBuilder.build(iface); // proxyCache.put(iface, proxy); // } // return (Proxy<T>) proxy; // } // // public synchronized Invoker getInvoker(Method method) { // Invoker invoker = invokerCache.get(method); // if (invoker == null) { // invoker = invokerBuilder.buildInvoker(method); // invokerCache.put(method, invoker); // } // return invoker; // } // } // Path: src/main/java/org/msgpack/rpc/builder/DefaultDispatcherBuilder.java import org.msgpack.MessagePack; import org.msgpack.rpc.dispatcher.Dispatcher; import org.msgpack.rpc.dispatcher.MethodDispatcher; import org.msgpack.rpc.reflect.Reflect; package org.msgpack.rpc.builder; /** * User: takeshita * Create: 12/06/15 1:16 */ public class DefaultDispatcherBuilder implements DispatcherBuilder { public Dispatcher build(Object handler, MessagePack messagePack) { return new MethodDispatcher(
new Reflect(messagePack), handler);
msgpack-rpc/msgpack-rpc-java
src/main/java/org/msgpack/rpc/reflect/JavassistInvokerBuilder.java
// Path: src/main/java/org/msgpack/rpc/Request.java // public class Request implements Callback<Object> { // private MessageSendable channel; // TODO #SF synchronized? // private int msgid; // private String method; // private Value args; // // public Request(MessageSendable channel, int msgid, String method, Value args) { // this.channel = channel; // this.msgid = msgid; // this.method = method; // this.args = args; // } // // public Request(String method, Value args) { // this.channel = null; // this.msgid = 0; // this.method = method; // this.args = args; // } // // public String getMethodName() { // return method; // } // // public Value getArguments() { // return args; // } // // public int getMessageID() { // return msgid; // } // // public void sendResult(Object result) { // sendResponse(result, null); // } // // public void sendError(Object error) { // sendResponse(null, error); // } // // public void sendError(Object error, Object data) { // sendResponse(data, error); // } // // public synchronized void sendResponse(Object result, Object error) { // if (channel == null) { // return; // } // ResponseMessage msg = new ResponseMessage(msgid, error, result); // channel.sendMessage(msg); // channel = null; // } // } // // Path: src/main/java/org/msgpack/rpc/reflect/ReflectionInvokerBuilder.java // static abstract class ReflectionArgumentEntry extends ArgumentEntry { // ReflectionArgumentEntry(ArgumentEntry e) { // super(e); // } // // public abstract void convert(Object[] params, Value obj) throws MessageTypeException; // // public void setNull(Object[] params) { // params[getIndex()] = null; // } // }
import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Type; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtConstructor; import javassist.CtMethod; import javassist.CtNewConstructor; import javassist.CtNewMethod; import javassist.LoaderClassPath; import javassist.NotFoundException; import org.msgpack.MessagePack; import org.msgpack.type.Value; import org.msgpack.MessageTypeException; import org.msgpack.template.Template; import org.msgpack.rpc.Request; import org.msgpack.rpc.reflect.ReflectionInvokerBuilder.ReflectionArgumentEntry; import org.msgpack.template.TemplateRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
// // MessagePack-RPC for Java // // Copyright (C) 2010 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package org.msgpack.rpc.reflect; public class JavassistInvokerBuilder extends InvokerBuilder { private static Logger LOG = LoggerFactory.getLogger(JavassistInvokerBuilder.class); protected abstract static class AbstractInvoker implements Invoker { protected Method method; protected int parameterLength;
// Path: src/main/java/org/msgpack/rpc/Request.java // public class Request implements Callback<Object> { // private MessageSendable channel; // TODO #SF synchronized? // private int msgid; // private String method; // private Value args; // // public Request(MessageSendable channel, int msgid, String method, Value args) { // this.channel = channel; // this.msgid = msgid; // this.method = method; // this.args = args; // } // // public Request(String method, Value args) { // this.channel = null; // this.msgid = 0; // this.method = method; // this.args = args; // } // // public String getMethodName() { // return method; // } // // public Value getArguments() { // return args; // } // // public int getMessageID() { // return msgid; // } // // public void sendResult(Object result) { // sendResponse(result, null); // } // // public void sendError(Object error) { // sendResponse(null, error); // } // // public void sendError(Object error, Object data) { // sendResponse(data, error); // } // // public synchronized void sendResponse(Object result, Object error) { // if (channel == null) { // return; // } // ResponseMessage msg = new ResponseMessage(msgid, error, result); // channel.sendMessage(msg); // channel = null; // } // } // // Path: src/main/java/org/msgpack/rpc/reflect/ReflectionInvokerBuilder.java // static abstract class ReflectionArgumentEntry extends ArgumentEntry { // ReflectionArgumentEntry(ArgumentEntry e) { // super(e); // } // // public abstract void convert(Object[] params, Value obj) throws MessageTypeException; // // public void setNull(Object[] params) { // params[getIndex()] = null; // } // } // Path: src/main/java/org/msgpack/rpc/reflect/JavassistInvokerBuilder.java import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Type; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtConstructor; import javassist.CtMethod; import javassist.CtNewConstructor; import javassist.CtNewMethod; import javassist.LoaderClassPath; import javassist.NotFoundException; import org.msgpack.MessagePack; import org.msgpack.type.Value; import org.msgpack.MessageTypeException; import org.msgpack.template.Template; import org.msgpack.rpc.Request; import org.msgpack.rpc.reflect.ReflectionInvokerBuilder.ReflectionArgumentEntry; import org.msgpack.template.TemplateRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; // // MessagePack-RPC for Java // // Copyright (C) 2010 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package org.msgpack.rpc.reflect; public class JavassistInvokerBuilder extends InvokerBuilder { private static Logger LOG = LoggerFactory.getLogger(JavassistInvokerBuilder.class); protected abstract static class AbstractInvoker implements Invoker { protected Method method; protected int parameterLength;
protected ReflectionArgumentEntry[] entries;
msgpack-rpc/msgpack-rpc-java
src/main/java/org/msgpack/rpc/reflect/JavassistInvokerBuilder.java
// Path: src/main/java/org/msgpack/rpc/Request.java // public class Request implements Callback<Object> { // private MessageSendable channel; // TODO #SF synchronized? // private int msgid; // private String method; // private Value args; // // public Request(MessageSendable channel, int msgid, String method, Value args) { // this.channel = channel; // this.msgid = msgid; // this.method = method; // this.args = args; // } // // public Request(String method, Value args) { // this.channel = null; // this.msgid = 0; // this.method = method; // this.args = args; // } // // public String getMethodName() { // return method; // } // // public Value getArguments() { // return args; // } // // public int getMessageID() { // return msgid; // } // // public void sendResult(Object result) { // sendResponse(result, null); // } // // public void sendError(Object error) { // sendResponse(null, error); // } // // public void sendError(Object error, Object data) { // sendResponse(data, error); // } // // public synchronized void sendResponse(Object result, Object error) { // if (channel == null) { // return; // } // ResponseMessage msg = new ResponseMessage(msgid, error, result); // channel.sendMessage(msg); // channel = null; // } // } // // Path: src/main/java/org/msgpack/rpc/reflect/ReflectionInvokerBuilder.java // static abstract class ReflectionArgumentEntry extends ArgumentEntry { // ReflectionArgumentEntry(ArgumentEntry e) { // super(e); // } // // public abstract void convert(Object[] params, Value obj) throws MessageTypeException; // // public void setNull(Object[] params) { // params[getIndex()] = null; // } // }
import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Type; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtConstructor; import javassist.CtMethod; import javassist.CtNewConstructor; import javassist.CtNewMethod; import javassist.LoaderClassPath; import javassist.NotFoundException; import org.msgpack.MessagePack; import org.msgpack.type.Value; import org.msgpack.MessageTypeException; import org.msgpack.template.Template; import org.msgpack.rpc.Request; import org.msgpack.rpc.reflect.ReflectionInvokerBuilder.ReflectionArgumentEntry; import org.msgpack.template.TemplateRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
// // MessagePack-RPC for Java // // Copyright (C) 2010 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package org.msgpack.rpc.reflect; public class JavassistInvokerBuilder extends InvokerBuilder { private static Logger LOG = LoggerFactory.getLogger(JavassistInvokerBuilder.class); protected abstract static class AbstractInvoker implements Invoker { protected Method method; protected int parameterLength; protected ReflectionArgumentEntry[] entries; protected int minimumArrayLength; boolean async; public AbstractInvoker(Method method, ReflectionArgumentEntry[] entries, boolean async) { this.method = method; this.parameterLength = method.getParameterTypes().length; this.entries = entries; this.async = async; this.minimumArrayLength = 0; for(int i=0; i < entries.length; i++) { ReflectionArgumentEntry e = entries[i]; if(!e.isOptional()){//e.isRequired() || e.isNullable()) { this.minimumArrayLength = i+1; } } }
// Path: src/main/java/org/msgpack/rpc/Request.java // public class Request implements Callback<Object> { // private MessageSendable channel; // TODO #SF synchronized? // private int msgid; // private String method; // private Value args; // // public Request(MessageSendable channel, int msgid, String method, Value args) { // this.channel = channel; // this.msgid = msgid; // this.method = method; // this.args = args; // } // // public Request(String method, Value args) { // this.channel = null; // this.msgid = 0; // this.method = method; // this.args = args; // } // // public String getMethodName() { // return method; // } // // public Value getArguments() { // return args; // } // // public int getMessageID() { // return msgid; // } // // public void sendResult(Object result) { // sendResponse(result, null); // } // // public void sendError(Object error) { // sendResponse(null, error); // } // // public void sendError(Object error, Object data) { // sendResponse(data, error); // } // // public synchronized void sendResponse(Object result, Object error) { // if (channel == null) { // return; // } // ResponseMessage msg = new ResponseMessage(msgid, error, result); // channel.sendMessage(msg); // channel = null; // } // } // // Path: src/main/java/org/msgpack/rpc/reflect/ReflectionInvokerBuilder.java // static abstract class ReflectionArgumentEntry extends ArgumentEntry { // ReflectionArgumentEntry(ArgumentEntry e) { // super(e); // } // // public abstract void convert(Object[] params, Value obj) throws MessageTypeException; // // public void setNull(Object[] params) { // params[getIndex()] = null; // } // } // Path: src/main/java/org/msgpack/rpc/reflect/JavassistInvokerBuilder.java import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Type; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtConstructor; import javassist.CtMethod; import javassist.CtNewConstructor; import javassist.CtNewMethod; import javassist.LoaderClassPath; import javassist.NotFoundException; import org.msgpack.MessagePack; import org.msgpack.type.Value; import org.msgpack.MessageTypeException; import org.msgpack.template.Template; import org.msgpack.rpc.Request; import org.msgpack.rpc.reflect.ReflectionInvokerBuilder.ReflectionArgumentEntry; import org.msgpack.template.TemplateRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; // // MessagePack-RPC for Java // // Copyright (C) 2010 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package org.msgpack.rpc.reflect; public class JavassistInvokerBuilder extends InvokerBuilder { private static Logger LOG = LoggerFactory.getLogger(JavassistInvokerBuilder.class); protected abstract static class AbstractInvoker implements Invoker { protected Method method; protected int parameterLength; protected ReflectionArgumentEntry[] entries; protected int minimumArrayLength; boolean async; public AbstractInvoker(Method method, ReflectionArgumentEntry[] entries, boolean async) { this.method = method; this.parameterLength = method.getParameterTypes().length; this.entries = entries; this.async = async; this.minimumArrayLength = 0; for(int i=0; i < entries.length; i++) { ReflectionArgumentEntry e = entries[i]; if(!e.isOptional()){//e.isRequired() || e.isNullable()) { this.minimumArrayLength = i+1; } } }
public void invoke(Object target, Request request) throws Exception {
msgpack-rpc/msgpack-rpc-java
src/test/java/org/msgpack/rpc/ServerErrorTest.java
// Path: src/main/java/org/msgpack/rpc/builder/StopWatchDispatcherBuilder.java // public class StopWatchDispatcherBuilder implements DispatcherBuilder { // // protected DispatcherBuilder baseBuilder; // protected boolean verbose = false; // // public boolean isVerbose() { // return verbose; // } // // public void setVerbose(boolean verbose) { // this.verbose = verbose; // } // // public StopWatchDispatcherBuilder withVerboseOutput(boolean verbose){ // this.verbose = verbose; // return this; // } // // public StopWatchDispatcherBuilder(DispatcherBuilder baseBuilder){ // this.baseBuilder = baseBuilder; // } // // public Dispatcher decorate(Dispatcher innerDispatcher) { // StopWatchDispatcher disp = new StopWatchDispatcher(innerDispatcher); // disp.setVerbose(verbose); // return disp; // } // // public Dispatcher build(Object handler, MessagePack messagePack) { // return decorate(baseBuilder.build(handler,messagePack)); // } // } // // Path: src/main/java/org/msgpack/rpc/error/RemoteError.java // public class RemoteError extends RPCError implements MessagePackable { // private static final long serialVersionUID = 1L; // // private Value data; // // public RemoteError() { // super(); // this.data = ValueFactory.createArrayValue( // new Value[] { ValueFactory.createRawValue("unknown error") }); // } // // public RemoteError(String message) { // super(message); // this.data = ValueFactory.createArrayValue( // new Value[] { ValueFactory.createRawValue(message) }); // } // // public RemoteError(Value data) { // super(loadMessage(data)); // this.data = data; // } // // public Value getData() { // return data; // } // // public void messagePack(Packer pk) throws IOException { // pk.write(data); // } // // private static String loadMessage(Value data) { // try { // if (data.isRawValue()) { // return data.asRawValue().getString(); // } else { // return data.asArrayValue().getElementArray()[0].asRawValue().getString(); // } // } catch (MessageTypeException e) { // return "unknown error: " + data; // } // } // // public void writeTo(Packer pk) throws IOException { // pk.write(data); // } // // public void readFrom(Unpacker u) throws IOException { // data = u.readValue(); // } // // public static final String CODE = "RemoteError"; // // @Override // public String getCode() { // return CODE; // } // } // // Path: src/main/java/org/msgpack/rpc/error/TimeoutError.java // public class TimeoutError extends RPCError { // private static final long serialVersionUID = 1L; // // public TimeoutError(String message) { // super(message); // } // // public static final String CODE = "TimeoutError"; // // @Override // public String getCode() { // return CODE; // } // }
import junit.framework.TestCase; import org.apache.log4j.BasicConfigurator; import org.junit.Test; import org.msgpack.MessageTypeException; import org.msgpack.rpc.builder.StopWatchDispatcherBuilder; import org.msgpack.rpc.error.NoMethodError; import org.msgpack.rpc.error.RemoteError; import org.msgpack.rpc.error.TimeoutError; import org.msgpack.rpc.loop.EventLoop; import org.msgpack.type.Value; import java.util.Date;
void call( CallFunc func) throws Exception{ BasicConfigurator.configure(); EventLoop loop = EventLoop.start(); Server svr = new Server(loop); Client c = new Client("127.0.0.1", 19850, loop); c.setRequestTimeout(1); try { svr.serve(new TestServer()); svr.listen(19850); func.apply(c); } finally { svr.close(); c.close(); loop.shutdown(); } } @Test public void testNormalException() throws Exception { call( new CallFunc(){ public void apply(Client client) { String message = "Normal exception"; try{ client.callApply("throwException",new Object[]{message}); fail("Must throw exception");
// Path: src/main/java/org/msgpack/rpc/builder/StopWatchDispatcherBuilder.java // public class StopWatchDispatcherBuilder implements DispatcherBuilder { // // protected DispatcherBuilder baseBuilder; // protected boolean verbose = false; // // public boolean isVerbose() { // return verbose; // } // // public void setVerbose(boolean verbose) { // this.verbose = verbose; // } // // public StopWatchDispatcherBuilder withVerboseOutput(boolean verbose){ // this.verbose = verbose; // return this; // } // // public StopWatchDispatcherBuilder(DispatcherBuilder baseBuilder){ // this.baseBuilder = baseBuilder; // } // // public Dispatcher decorate(Dispatcher innerDispatcher) { // StopWatchDispatcher disp = new StopWatchDispatcher(innerDispatcher); // disp.setVerbose(verbose); // return disp; // } // // public Dispatcher build(Object handler, MessagePack messagePack) { // return decorate(baseBuilder.build(handler,messagePack)); // } // } // // Path: src/main/java/org/msgpack/rpc/error/RemoteError.java // public class RemoteError extends RPCError implements MessagePackable { // private static final long serialVersionUID = 1L; // // private Value data; // // public RemoteError() { // super(); // this.data = ValueFactory.createArrayValue( // new Value[] { ValueFactory.createRawValue("unknown error") }); // } // // public RemoteError(String message) { // super(message); // this.data = ValueFactory.createArrayValue( // new Value[] { ValueFactory.createRawValue(message) }); // } // // public RemoteError(Value data) { // super(loadMessage(data)); // this.data = data; // } // // public Value getData() { // return data; // } // // public void messagePack(Packer pk) throws IOException { // pk.write(data); // } // // private static String loadMessage(Value data) { // try { // if (data.isRawValue()) { // return data.asRawValue().getString(); // } else { // return data.asArrayValue().getElementArray()[0].asRawValue().getString(); // } // } catch (MessageTypeException e) { // return "unknown error: " + data; // } // } // // public void writeTo(Packer pk) throws IOException { // pk.write(data); // } // // public void readFrom(Unpacker u) throws IOException { // data = u.readValue(); // } // // public static final String CODE = "RemoteError"; // // @Override // public String getCode() { // return CODE; // } // } // // Path: src/main/java/org/msgpack/rpc/error/TimeoutError.java // public class TimeoutError extends RPCError { // private static final long serialVersionUID = 1L; // // public TimeoutError(String message) { // super(message); // } // // public static final String CODE = "TimeoutError"; // // @Override // public String getCode() { // return CODE; // } // } // Path: src/test/java/org/msgpack/rpc/ServerErrorTest.java import junit.framework.TestCase; import org.apache.log4j.BasicConfigurator; import org.junit.Test; import org.msgpack.MessageTypeException; import org.msgpack.rpc.builder.StopWatchDispatcherBuilder; import org.msgpack.rpc.error.NoMethodError; import org.msgpack.rpc.error.RemoteError; import org.msgpack.rpc.error.TimeoutError; import org.msgpack.rpc.loop.EventLoop; import org.msgpack.type.Value; import java.util.Date; void call( CallFunc func) throws Exception{ BasicConfigurator.configure(); EventLoop loop = EventLoop.start(); Server svr = new Server(loop); Client c = new Client("127.0.0.1", 19850, loop); c.setRequestTimeout(1); try { svr.serve(new TestServer()); svr.listen(19850); func.apply(c); } finally { svr.close(); c.close(); loop.shutdown(); } } @Test public void testNormalException() throws Exception { call( new CallFunc(){ public void apply(Client client) { String message = "Normal exception"; try{ client.callApply("throwException",new Object[]{message}); fail("Must throw exception");
}catch(RemoteError e){
msgpack-rpc/msgpack-rpc-java
src/main/java/org/msgpack/rpc/Client.java
// Path: src/main/java/org/msgpack/rpc/address/Address.java // public abstract class Address { // abstract public SocketAddress getSocketAddress(); // } // // Path: src/main/java/org/msgpack/rpc/address/IPAddress.java // public class IPAddress extends Address { // private byte[] address; // private int port; // // public IPAddress(String host, int port) throws UnknownHostException { // this.address = InetAddress.getByName(host).getAddress(); // this.port = port; // } // // public IPAddress(int port) { // this.address = new InetSocketAddress(port).getAddress().getAddress(); // this.port = port; // } // // public IPAddress(InetSocketAddress addr) { // this.address = addr.getAddress().getAddress(); // this.port = addr.getPort(); // } // // public IPAddress(InetAddress addr, int port) throws UnknownHostException { // this.address = addr.getAddress(); // this.port = port; // } // // public InetSocketAddress getInetSocketAddress() { // try { // return new InetSocketAddress(InetAddress.getByAddress(address), // port); // } catch (UnknownHostException e) { // throw new RuntimeException(e.getMessage()); // } // } // // public SocketAddress getSocketAddress() { // return getInetSocketAddress(); // } // } // // Path: src/main/java/org/msgpack/rpc/config/ClientConfig.java // public abstract class ClientConfig { // private Map<String, Object> options = new HashMap<String, Object>(); // protected int requestTimeout = 30; // FIXME default timeout time // // public void setRequestTimeout(int sec) { // this.requestTimeout = sec; // } // // public int getRequestTimeout() { // return this.requestTimeout; // } // // public Object getOption(String key) { // return options.get(key); // } // // public Map<String, Object> getOptions() { // return options; // } // // public void setOption(String key, Object value) { // options.put(key, value); // } // } // // Path: src/main/java/org/msgpack/rpc/config/TcpClientConfig.java // public class TcpClientConfig extends StreamClientConfig { // public TcpClientConfig() { // } // } // // Path: src/main/java/org/msgpack/rpc/reflect/Reflect.java // public class Reflect { // /* // * private static final Reflect instance = new Reflect(); // * // * public static <T> Proxy<T> reflectProxy(Class<T> iface) { return // * instance.getProxy(iface); } // * // * public static Invoker reflectInvoker(Method method) { return // * instance.getInvoker(method); } // */ // // private Map<Class<?>, Proxy<?>> proxyCache = new HashMap<Class<?>, Proxy<?>>(); // // private Map<Method, Invoker> invokerCache = new HashMap<Method, Invoker>(); // // private InvokerBuilder invokerBuilder; // private ProxyBuilder proxyBuilder; // // public Reflect(MessagePack messagePack) { // invokerBuilder = new ReflectionInvokerBuilder(messagePack); // proxyBuilder = new ReflectionProxyBuilder(messagePack); // } // // public Reflect( InvokerBuilder invokerBuilder,ProxyBuilder proxyBuilder) { // this.invokerBuilder = invokerBuilder; // this.proxyBuilder = proxyBuilder; // } // // public synchronized <T> Proxy<T> getProxy(Class<T> iface) { // Proxy<?> proxy = proxyCache.get(iface); // if (proxy == null) { // proxy = proxyBuilder.buildProxy(iface);// ProxyBuilder.build(iface); // proxyCache.put(iface, proxy); // } // return (Proxy<T>) proxy; // } // // public synchronized Invoker getInvoker(Method method) { // Invoker invoker = invokerCache.get(method); // if (invoker == null) { // invoker = invokerBuilder.buildInvoker(method); // invokerCache.put(method, invoker); // } // return invoker; // } // }
import java.io.Closeable; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.msgpack.rpc.loop.EventLoop; import org.msgpack.rpc.address.Address; import org.msgpack.rpc.address.IPAddress; import org.msgpack.rpc.config.ClientConfig; import org.msgpack.rpc.config.TcpClientConfig; import org.msgpack.rpc.reflect.Reflect;
// // MessagePack-RPC for Java // // Copyright (C) 2010 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package org.msgpack.rpc; public class Client extends Session implements Closeable { private ScheduledFuture<?> timer; public Client(String host, int port) throws UnknownHostException {
// Path: src/main/java/org/msgpack/rpc/address/Address.java // public abstract class Address { // abstract public SocketAddress getSocketAddress(); // } // // Path: src/main/java/org/msgpack/rpc/address/IPAddress.java // public class IPAddress extends Address { // private byte[] address; // private int port; // // public IPAddress(String host, int port) throws UnknownHostException { // this.address = InetAddress.getByName(host).getAddress(); // this.port = port; // } // // public IPAddress(int port) { // this.address = new InetSocketAddress(port).getAddress().getAddress(); // this.port = port; // } // // public IPAddress(InetSocketAddress addr) { // this.address = addr.getAddress().getAddress(); // this.port = addr.getPort(); // } // // public IPAddress(InetAddress addr, int port) throws UnknownHostException { // this.address = addr.getAddress(); // this.port = port; // } // // public InetSocketAddress getInetSocketAddress() { // try { // return new InetSocketAddress(InetAddress.getByAddress(address), // port); // } catch (UnknownHostException e) { // throw new RuntimeException(e.getMessage()); // } // } // // public SocketAddress getSocketAddress() { // return getInetSocketAddress(); // } // } // // Path: src/main/java/org/msgpack/rpc/config/ClientConfig.java // public abstract class ClientConfig { // private Map<String, Object> options = new HashMap<String, Object>(); // protected int requestTimeout = 30; // FIXME default timeout time // // public void setRequestTimeout(int sec) { // this.requestTimeout = sec; // } // // public int getRequestTimeout() { // return this.requestTimeout; // } // // public Object getOption(String key) { // return options.get(key); // } // // public Map<String, Object> getOptions() { // return options; // } // // public void setOption(String key, Object value) { // options.put(key, value); // } // } // // Path: src/main/java/org/msgpack/rpc/config/TcpClientConfig.java // public class TcpClientConfig extends StreamClientConfig { // public TcpClientConfig() { // } // } // // Path: src/main/java/org/msgpack/rpc/reflect/Reflect.java // public class Reflect { // /* // * private static final Reflect instance = new Reflect(); // * // * public static <T> Proxy<T> reflectProxy(Class<T> iface) { return // * instance.getProxy(iface); } // * // * public static Invoker reflectInvoker(Method method) { return // * instance.getInvoker(method); } // */ // // private Map<Class<?>, Proxy<?>> proxyCache = new HashMap<Class<?>, Proxy<?>>(); // // private Map<Method, Invoker> invokerCache = new HashMap<Method, Invoker>(); // // private InvokerBuilder invokerBuilder; // private ProxyBuilder proxyBuilder; // // public Reflect(MessagePack messagePack) { // invokerBuilder = new ReflectionInvokerBuilder(messagePack); // proxyBuilder = new ReflectionProxyBuilder(messagePack); // } // // public Reflect( InvokerBuilder invokerBuilder,ProxyBuilder proxyBuilder) { // this.invokerBuilder = invokerBuilder; // this.proxyBuilder = proxyBuilder; // } // // public synchronized <T> Proxy<T> getProxy(Class<T> iface) { // Proxy<?> proxy = proxyCache.get(iface); // if (proxy == null) { // proxy = proxyBuilder.buildProxy(iface);// ProxyBuilder.build(iface); // proxyCache.put(iface, proxy); // } // return (Proxy<T>) proxy; // } // // public synchronized Invoker getInvoker(Method method) { // Invoker invoker = invokerCache.get(method); // if (invoker == null) { // invoker = invokerBuilder.buildInvoker(method); // invokerCache.put(method, invoker); // } // return invoker; // } // } // Path: src/main/java/org/msgpack/rpc/Client.java import java.io.Closeable; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.msgpack.rpc.loop.EventLoop; import org.msgpack.rpc.address.Address; import org.msgpack.rpc.address.IPAddress; import org.msgpack.rpc.config.ClientConfig; import org.msgpack.rpc.config.TcpClientConfig; import org.msgpack.rpc.reflect.Reflect; // // MessagePack-RPC for Java // // Copyright (C) 2010 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package org.msgpack.rpc; public class Client extends Session implements Closeable { private ScheduledFuture<?> timer; public Client(String host, int port) throws UnknownHostException {
this(new IPAddress(host, port), new TcpClientConfig(), EventLoop.defaultEventLoop());
msgpack-rpc/msgpack-rpc-java
src/main/java/org/msgpack/rpc/Client.java
// Path: src/main/java/org/msgpack/rpc/address/Address.java // public abstract class Address { // abstract public SocketAddress getSocketAddress(); // } // // Path: src/main/java/org/msgpack/rpc/address/IPAddress.java // public class IPAddress extends Address { // private byte[] address; // private int port; // // public IPAddress(String host, int port) throws UnknownHostException { // this.address = InetAddress.getByName(host).getAddress(); // this.port = port; // } // // public IPAddress(int port) { // this.address = new InetSocketAddress(port).getAddress().getAddress(); // this.port = port; // } // // public IPAddress(InetSocketAddress addr) { // this.address = addr.getAddress().getAddress(); // this.port = addr.getPort(); // } // // public IPAddress(InetAddress addr, int port) throws UnknownHostException { // this.address = addr.getAddress(); // this.port = port; // } // // public InetSocketAddress getInetSocketAddress() { // try { // return new InetSocketAddress(InetAddress.getByAddress(address), // port); // } catch (UnknownHostException e) { // throw new RuntimeException(e.getMessage()); // } // } // // public SocketAddress getSocketAddress() { // return getInetSocketAddress(); // } // } // // Path: src/main/java/org/msgpack/rpc/config/ClientConfig.java // public abstract class ClientConfig { // private Map<String, Object> options = new HashMap<String, Object>(); // protected int requestTimeout = 30; // FIXME default timeout time // // public void setRequestTimeout(int sec) { // this.requestTimeout = sec; // } // // public int getRequestTimeout() { // return this.requestTimeout; // } // // public Object getOption(String key) { // return options.get(key); // } // // public Map<String, Object> getOptions() { // return options; // } // // public void setOption(String key, Object value) { // options.put(key, value); // } // } // // Path: src/main/java/org/msgpack/rpc/config/TcpClientConfig.java // public class TcpClientConfig extends StreamClientConfig { // public TcpClientConfig() { // } // } // // Path: src/main/java/org/msgpack/rpc/reflect/Reflect.java // public class Reflect { // /* // * private static final Reflect instance = new Reflect(); // * // * public static <T> Proxy<T> reflectProxy(Class<T> iface) { return // * instance.getProxy(iface); } // * // * public static Invoker reflectInvoker(Method method) { return // * instance.getInvoker(method); } // */ // // private Map<Class<?>, Proxy<?>> proxyCache = new HashMap<Class<?>, Proxy<?>>(); // // private Map<Method, Invoker> invokerCache = new HashMap<Method, Invoker>(); // // private InvokerBuilder invokerBuilder; // private ProxyBuilder proxyBuilder; // // public Reflect(MessagePack messagePack) { // invokerBuilder = new ReflectionInvokerBuilder(messagePack); // proxyBuilder = new ReflectionProxyBuilder(messagePack); // } // // public Reflect( InvokerBuilder invokerBuilder,ProxyBuilder proxyBuilder) { // this.invokerBuilder = invokerBuilder; // this.proxyBuilder = proxyBuilder; // } // // public synchronized <T> Proxy<T> getProxy(Class<T> iface) { // Proxy<?> proxy = proxyCache.get(iface); // if (proxy == null) { // proxy = proxyBuilder.buildProxy(iface);// ProxyBuilder.build(iface); // proxyCache.put(iface, proxy); // } // return (Proxy<T>) proxy; // } // // public synchronized Invoker getInvoker(Method method) { // Invoker invoker = invokerCache.get(method); // if (invoker == null) { // invoker = invokerBuilder.buildInvoker(method); // invokerCache.put(method, invoker); // } // return invoker; // } // }
import java.io.Closeable; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.msgpack.rpc.loop.EventLoop; import org.msgpack.rpc.address.Address; import org.msgpack.rpc.address.IPAddress; import org.msgpack.rpc.config.ClientConfig; import org.msgpack.rpc.config.TcpClientConfig; import org.msgpack.rpc.reflect.Reflect;
// // MessagePack-RPC for Java // // Copyright (C) 2010 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package org.msgpack.rpc; public class Client extends Session implements Closeable { private ScheduledFuture<?> timer; public Client(String host, int port) throws UnknownHostException {
// Path: src/main/java/org/msgpack/rpc/address/Address.java // public abstract class Address { // abstract public SocketAddress getSocketAddress(); // } // // Path: src/main/java/org/msgpack/rpc/address/IPAddress.java // public class IPAddress extends Address { // private byte[] address; // private int port; // // public IPAddress(String host, int port) throws UnknownHostException { // this.address = InetAddress.getByName(host).getAddress(); // this.port = port; // } // // public IPAddress(int port) { // this.address = new InetSocketAddress(port).getAddress().getAddress(); // this.port = port; // } // // public IPAddress(InetSocketAddress addr) { // this.address = addr.getAddress().getAddress(); // this.port = addr.getPort(); // } // // public IPAddress(InetAddress addr, int port) throws UnknownHostException { // this.address = addr.getAddress(); // this.port = port; // } // // public InetSocketAddress getInetSocketAddress() { // try { // return new InetSocketAddress(InetAddress.getByAddress(address), // port); // } catch (UnknownHostException e) { // throw new RuntimeException(e.getMessage()); // } // } // // public SocketAddress getSocketAddress() { // return getInetSocketAddress(); // } // } // // Path: src/main/java/org/msgpack/rpc/config/ClientConfig.java // public abstract class ClientConfig { // private Map<String, Object> options = new HashMap<String, Object>(); // protected int requestTimeout = 30; // FIXME default timeout time // // public void setRequestTimeout(int sec) { // this.requestTimeout = sec; // } // // public int getRequestTimeout() { // return this.requestTimeout; // } // // public Object getOption(String key) { // return options.get(key); // } // // public Map<String, Object> getOptions() { // return options; // } // // public void setOption(String key, Object value) { // options.put(key, value); // } // } // // Path: src/main/java/org/msgpack/rpc/config/TcpClientConfig.java // public class TcpClientConfig extends StreamClientConfig { // public TcpClientConfig() { // } // } // // Path: src/main/java/org/msgpack/rpc/reflect/Reflect.java // public class Reflect { // /* // * private static final Reflect instance = new Reflect(); // * // * public static <T> Proxy<T> reflectProxy(Class<T> iface) { return // * instance.getProxy(iface); } // * // * public static Invoker reflectInvoker(Method method) { return // * instance.getInvoker(method); } // */ // // private Map<Class<?>, Proxy<?>> proxyCache = new HashMap<Class<?>, Proxy<?>>(); // // private Map<Method, Invoker> invokerCache = new HashMap<Method, Invoker>(); // // private InvokerBuilder invokerBuilder; // private ProxyBuilder proxyBuilder; // // public Reflect(MessagePack messagePack) { // invokerBuilder = new ReflectionInvokerBuilder(messagePack); // proxyBuilder = new ReflectionProxyBuilder(messagePack); // } // // public Reflect( InvokerBuilder invokerBuilder,ProxyBuilder proxyBuilder) { // this.invokerBuilder = invokerBuilder; // this.proxyBuilder = proxyBuilder; // } // // public synchronized <T> Proxy<T> getProxy(Class<T> iface) { // Proxy<?> proxy = proxyCache.get(iface); // if (proxy == null) { // proxy = proxyBuilder.buildProxy(iface);// ProxyBuilder.build(iface); // proxyCache.put(iface, proxy); // } // return (Proxy<T>) proxy; // } // // public synchronized Invoker getInvoker(Method method) { // Invoker invoker = invokerCache.get(method); // if (invoker == null) { // invoker = invokerBuilder.buildInvoker(method); // invokerCache.put(method, invoker); // } // return invoker; // } // } // Path: src/main/java/org/msgpack/rpc/Client.java import java.io.Closeable; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.msgpack.rpc.loop.EventLoop; import org.msgpack.rpc.address.Address; import org.msgpack.rpc.address.IPAddress; import org.msgpack.rpc.config.ClientConfig; import org.msgpack.rpc.config.TcpClientConfig; import org.msgpack.rpc.reflect.Reflect; // // MessagePack-RPC for Java // // Copyright (C) 2010 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package org.msgpack.rpc; public class Client extends Session implements Closeable { private ScheduledFuture<?> timer; public Client(String host, int port) throws UnknownHostException {
this(new IPAddress(host, port), new TcpClientConfig(), EventLoop.defaultEventLoop());
msgpack-rpc/msgpack-rpc-java
src/main/java/org/msgpack/rpc/Client.java
// Path: src/main/java/org/msgpack/rpc/address/Address.java // public abstract class Address { // abstract public SocketAddress getSocketAddress(); // } // // Path: src/main/java/org/msgpack/rpc/address/IPAddress.java // public class IPAddress extends Address { // private byte[] address; // private int port; // // public IPAddress(String host, int port) throws UnknownHostException { // this.address = InetAddress.getByName(host).getAddress(); // this.port = port; // } // // public IPAddress(int port) { // this.address = new InetSocketAddress(port).getAddress().getAddress(); // this.port = port; // } // // public IPAddress(InetSocketAddress addr) { // this.address = addr.getAddress().getAddress(); // this.port = addr.getPort(); // } // // public IPAddress(InetAddress addr, int port) throws UnknownHostException { // this.address = addr.getAddress(); // this.port = port; // } // // public InetSocketAddress getInetSocketAddress() { // try { // return new InetSocketAddress(InetAddress.getByAddress(address), // port); // } catch (UnknownHostException e) { // throw new RuntimeException(e.getMessage()); // } // } // // public SocketAddress getSocketAddress() { // return getInetSocketAddress(); // } // } // // Path: src/main/java/org/msgpack/rpc/config/ClientConfig.java // public abstract class ClientConfig { // private Map<String, Object> options = new HashMap<String, Object>(); // protected int requestTimeout = 30; // FIXME default timeout time // // public void setRequestTimeout(int sec) { // this.requestTimeout = sec; // } // // public int getRequestTimeout() { // return this.requestTimeout; // } // // public Object getOption(String key) { // return options.get(key); // } // // public Map<String, Object> getOptions() { // return options; // } // // public void setOption(String key, Object value) { // options.put(key, value); // } // } // // Path: src/main/java/org/msgpack/rpc/config/TcpClientConfig.java // public class TcpClientConfig extends StreamClientConfig { // public TcpClientConfig() { // } // } // // Path: src/main/java/org/msgpack/rpc/reflect/Reflect.java // public class Reflect { // /* // * private static final Reflect instance = new Reflect(); // * // * public static <T> Proxy<T> reflectProxy(Class<T> iface) { return // * instance.getProxy(iface); } // * // * public static Invoker reflectInvoker(Method method) { return // * instance.getInvoker(method); } // */ // // private Map<Class<?>, Proxy<?>> proxyCache = new HashMap<Class<?>, Proxy<?>>(); // // private Map<Method, Invoker> invokerCache = new HashMap<Method, Invoker>(); // // private InvokerBuilder invokerBuilder; // private ProxyBuilder proxyBuilder; // // public Reflect(MessagePack messagePack) { // invokerBuilder = new ReflectionInvokerBuilder(messagePack); // proxyBuilder = new ReflectionProxyBuilder(messagePack); // } // // public Reflect( InvokerBuilder invokerBuilder,ProxyBuilder proxyBuilder) { // this.invokerBuilder = invokerBuilder; // this.proxyBuilder = proxyBuilder; // } // // public synchronized <T> Proxy<T> getProxy(Class<T> iface) { // Proxy<?> proxy = proxyCache.get(iface); // if (proxy == null) { // proxy = proxyBuilder.buildProxy(iface);// ProxyBuilder.build(iface); // proxyCache.put(iface, proxy); // } // return (Proxy<T>) proxy; // } // // public synchronized Invoker getInvoker(Method method) { // Invoker invoker = invokerCache.get(method); // if (invoker == null) { // invoker = invokerBuilder.buildInvoker(method); // invokerCache.put(method, invoker); // } // return invoker; // } // }
import java.io.Closeable; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.msgpack.rpc.loop.EventLoop; import org.msgpack.rpc.address.Address; import org.msgpack.rpc.address.IPAddress; import org.msgpack.rpc.config.ClientConfig; import org.msgpack.rpc.config.TcpClientConfig; import org.msgpack.rpc.reflect.Reflect;
// // MessagePack-RPC for Java // // Copyright (C) 2010 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package org.msgpack.rpc; public class Client extends Session implements Closeable { private ScheduledFuture<?> timer; public Client(String host, int port) throws UnknownHostException { this(new IPAddress(host, port), new TcpClientConfig(), EventLoop.defaultEventLoop()); }
// Path: src/main/java/org/msgpack/rpc/address/Address.java // public abstract class Address { // abstract public SocketAddress getSocketAddress(); // } // // Path: src/main/java/org/msgpack/rpc/address/IPAddress.java // public class IPAddress extends Address { // private byte[] address; // private int port; // // public IPAddress(String host, int port) throws UnknownHostException { // this.address = InetAddress.getByName(host).getAddress(); // this.port = port; // } // // public IPAddress(int port) { // this.address = new InetSocketAddress(port).getAddress().getAddress(); // this.port = port; // } // // public IPAddress(InetSocketAddress addr) { // this.address = addr.getAddress().getAddress(); // this.port = addr.getPort(); // } // // public IPAddress(InetAddress addr, int port) throws UnknownHostException { // this.address = addr.getAddress(); // this.port = port; // } // // public InetSocketAddress getInetSocketAddress() { // try { // return new InetSocketAddress(InetAddress.getByAddress(address), // port); // } catch (UnknownHostException e) { // throw new RuntimeException(e.getMessage()); // } // } // // public SocketAddress getSocketAddress() { // return getInetSocketAddress(); // } // } // // Path: src/main/java/org/msgpack/rpc/config/ClientConfig.java // public abstract class ClientConfig { // private Map<String, Object> options = new HashMap<String, Object>(); // protected int requestTimeout = 30; // FIXME default timeout time // // public void setRequestTimeout(int sec) { // this.requestTimeout = sec; // } // // public int getRequestTimeout() { // return this.requestTimeout; // } // // public Object getOption(String key) { // return options.get(key); // } // // public Map<String, Object> getOptions() { // return options; // } // // public void setOption(String key, Object value) { // options.put(key, value); // } // } // // Path: src/main/java/org/msgpack/rpc/config/TcpClientConfig.java // public class TcpClientConfig extends StreamClientConfig { // public TcpClientConfig() { // } // } // // Path: src/main/java/org/msgpack/rpc/reflect/Reflect.java // public class Reflect { // /* // * private static final Reflect instance = new Reflect(); // * // * public static <T> Proxy<T> reflectProxy(Class<T> iface) { return // * instance.getProxy(iface); } // * // * public static Invoker reflectInvoker(Method method) { return // * instance.getInvoker(method); } // */ // // private Map<Class<?>, Proxy<?>> proxyCache = new HashMap<Class<?>, Proxy<?>>(); // // private Map<Method, Invoker> invokerCache = new HashMap<Method, Invoker>(); // // private InvokerBuilder invokerBuilder; // private ProxyBuilder proxyBuilder; // // public Reflect(MessagePack messagePack) { // invokerBuilder = new ReflectionInvokerBuilder(messagePack); // proxyBuilder = new ReflectionProxyBuilder(messagePack); // } // // public Reflect( InvokerBuilder invokerBuilder,ProxyBuilder proxyBuilder) { // this.invokerBuilder = invokerBuilder; // this.proxyBuilder = proxyBuilder; // } // // public synchronized <T> Proxy<T> getProxy(Class<T> iface) { // Proxy<?> proxy = proxyCache.get(iface); // if (proxy == null) { // proxy = proxyBuilder.buildProxy(iface);// ProxyBuilder.build(iface); // proxyCache.put(iface, proxy); // } // return (Proxy<T>) proxy; // } // // public synchronized Invoker getInvoker(Method method) { // Invoker invoker = invokerCache.get(method); // if (invoker == null) { // invoker = invokerBuilder.buildInvoker(method); // invokerCache.put(method, invoker); // } // return invoker; // } // } // Path: src/main/java/org/msgpack/rpc/Client.java import java.io.Closeable; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.msgpack.rpc.loop.EventLoop; import org.msgpack.rpc.address.Address; import org.msgpack.rpc.address.IPAddress; import org.msgpack.rpc.config.ClientConfig; import org.msgpack.rpc.config.TcpClientConfig; import org.msgpack.rpc.reflect.Reflect; // // MessagePack-RPC for Java // // Copyright (C) 2010 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package org.msgpack.rpc; public class Client extends Session implements Closeable { private ScheduledFuture<?> timer; public Client(String host, int port) throws UnknownHostException { this(new IPAddress(host, port), new TcpClientConfig(), EventLoop.defaultEventLoop()); }
public Client(String host, int port, ClientConfig config)
msgpack-rpc/msgpack-rpc-java
src/main/java/org/msgpack/rpc/Client.java
// Path: src/main/java/org/msgpack/rpc/address/Address.java // public abstract class Address { // abstract public SocketAddress getSocketAddress(); // } // // Path: src/main/java/org/msgpack/rpc/address/IPAddress.java // public class IPAddress extends Address { // private byte[] address; // private int port; // // public IPAddress(String host, int port) throws UnknownHostException { // this.address = InetAddress.getByName(host).getAddress(); // this.port = port; // } // // public IPAddress(int port) { // this.address = new InetSocketAddress(port).getAddress().getAddress(); // this.port = port; // } // // public IPAddress(InetSocketAddress addr) { // this.address = addr.getAddress().getAddress(); // this.port = addr.getPort(); // } // // public IPAddress(InetAddress addr, int port) throws UnknownHostException { // this.address = addr.getAddress(); // this.port = port; // } // // public InetSocketAddress getInetSocketAddress() { // try { // return new InetSocketAddress(InetAddress.getByAddress(address), // port); // } catch (UnknownHostException e) { // throw new RuntimeException(e.getMessage()); // } // } // // public SocketAddress getSocketAddress() { // return getInetSocketAddress(); // } // } // // Path: src/main/java/org/msgpack/rpc/config/ClientConfig.java // public abstract class ClientConfig { // private Map<String, Object> options = new HashMap<String, Object>(); // protected int requestTimeout = 30; // FIXME default timeout time // // public void setRequestTimeout(int sec) { // this.requestTimeout = sec; // } // // public int getRequestTimeout() { // return this.requestTimeout; // } // // public Object getOption(String key) { // return options.get(key); // } // // public Map<String, Object> getOptions() { // return options; // } // // public void setOption(String key, Object value) { // options.put(key, value); // } // } // // Path: src/main/java/org/msgpack/rpc/config/TcpClientConfig.java // public class TcpClientConfig extends StreamClientConfig { // public TcpClientConfig() { // } // } // // Path: src/main/java/org/msgpack/rpc/reflect/Reflect.java // public class Reflect { // /* // * private static final Reflect instance = new Reflect(); // * // * public static <T> Proxy<T> reflectProxy(Class<T> iface) { return // * instance.getProxy(iface); } // * // * public static Invoker reflectInvoker(Method method) { return // * instance.getInvoker(method); } // */ // // private Map<Class<?>, Proxy<?>> proxyCache = new HashMap<Class<?>, Proxy<?>>(); // // private Map<Method, Invoker> invokerCache = new HashMap<Method, Invoker>(); // // private InvokerBuilder invokerBuilder; // private ProxyBuilder proxyBuilder; // // public Reflect(MessagePack messagePack) { // invokerBuilder = new ReflectionInvokerBuilder(messagePack); // proxyBuilder = new ReflectionProxyBuilder(messagePack); // } // // public Reflect( InvokerBuilder invokerBuilder,ProxyBuilder proxyBuilder) { // this.invokerBuilder = invokerBuilder; // this.proxyBuilder = proxyBuilder; // } // // public synchronized <T> Proxy<T> getProxy(Class<T> iface) { // Proxy<?> proxy = proxyCache.get(iface); // if (proxy == null) { // proxy = proxyBuilder.buildProxy(iface);// ProxyBuilder.build(iface); // proxyCache.put(iface, proxy); // } // return (Proxy<T>) proxy; // } // // public synchronized Invoker getInvoker(Method method) { // Invoker invoker = invokerCache.get(method); // if (invoker == null) { // invoker = invokerBuilder.buildInvoker(method); // invokerCache.put(method, invoker); // } // return invoker; // } // }
import java.io.Closeable; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.msgpack.rpc.loop.EventLoop; import org.msgpack.rpc.address.Address; import org.msgpack.rpc.address.IPAddress; import org.msgpack.rpc.config.ClientConfig; import org.msgpack.rpc.config.TcpClientConfig; import org.msgpack.rpc.reflect.Reflect;
// // MessagePack-RPC for Java // // Copyright (C) 2010 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package org.msgpack.rpc; public class Client extends Session implements Closeable { private ScheduledFuture<?> timer; public Client(String host, int port) throws UnknownHostException { this(new IPAddress(host, port), new TcpClientConfig(), EventLoop.defaultEventLoop()); } public Client(String host, int port, ClientConfig config) throws UnknownHostException { this(new IPAddress(host, port), config, EventLoop.defaultEventLoop()); } public Client(String host, int port, EventLoop loop) throws UnknownHostException { this(new IPAddress(host, port), new TcpClientConfig(), loop); }
// Path: src/main/java/org/msgpack/rpc/address/Address.java // public abstract class Address { // abstract public SocketAddress getSocketAddress(); // } // // Path: src/main/java/org/msgpack/rpc/address/IPAddress.java // public class IPAddress extends Address { // private byte[] address; // private int port; // // public IPAddress(String host, int port) throws UnknownHostException { // this.address = InetAddress.getByName(host).getAddress(); // this.port = port; // } // // public IPAddress(int port) { // this.address = new InetSocketAddress(port).getAddress().getAddress(); // this.port = port; // } // // public IPAddress(InetSocketAddress addr) { // this.address = addr.getAddress().getAddress(); // this.port = addr.getPort(); // } // // public IPAddress(InetAddress addr, int port) throws UnknownHostException { // this.address = addr.getAddress(); // this.port = port; // } // // public InetSocketAddress getInetSocketAddress() { // try { // return new InetSocketAddress(InetAddress.getByAddress(address), // port); // } catch (UnknownHostException e) { // throw new RuntimeException(e.getMessage()); // } // } // // public SocketAddress getSocketAddress() { // return getInetSocketAddress(); // } // } // // Path: src/main/java/org/msgpack/rpc/config/ClientConfig.java // public abstract class ClientConfig { // private Map<String, Object> options = new HashMap<String, Object>(); // protected int requestTimeout = 30; // FIXME default timeout time // // public void setRequestTimeout(int sec) { // this.requestTimeout = sec; // } // // public int getRequestTimeout() { // return this.requestTimeout; // } // // public Object getOption(String key) { // return options.get(key); // } // // public Map<String, Object> getOptions() { // return options; // } // // public void setOption(String key, Object value) { // options.put(key, value); // } // } // // Path: src/main/java/org/msgpack/rpc/config/TcpClientConfig.java // public class TcpClientConfig extends StreamClientConfig { // public TcpClientConfig() { // } // } // // Path: src/main/java/org/msgpack/rpc/reflect/Reflect.java // public class Reflect { // /* // * private static final Reflect instance = new Reflect(); // * // * public static <T> Proxy<T> reflectProxy(Class<T> iface) { return // * instance.getProxy(iface); } // * // * public static Invoker reflectInvoker(Method method) { return // * instance.getInvoker(method); } // */ // // private Map<Class<?>, Proxy<?>> proxyCache = new HashMap<Class<?>, Proxy<?>>(); // // private Map<Method, Invoker> invokerCache = new HashMap<Method, Invoker>(); // // private InvokerBuilder invokerBuilder; // private ProxyBuilder proxyBuilder; // // public Reflect(MessagePack messagePack) { // invokerBuilder = new ReflectionInvokerBuilder(messagePack); // proxyBuilder = new ReflectionProxyBuilder(messagePack); // } // // public Reflect( InvokerBuilder invokerBuilder,ProxyBuilder proxyBuilder) { // this.invokerBuilder = invokerBuilder; // this.proxyBuilder = proxyBuilder; // } // // public synchronized <T> Proxy<T> getProxy(Class<T> iface) { // Proxy<?> proxy = proxyCache.get(iface); // if (proxy == null) { // proxy = proxyBuilder.buildProxy(iface);// ProxyBuilder.build(iface); // proxyCache.put(iface, proxy); // } // return (Proxy<T>) proxy; // } // // public synchronized Invoker getInvoker(Method method) { // Invoker invoker = invokerCache.get(method); // if (invoker == null) { // invoker = invokerBuilder.buildInvoker(method); // invokerCache.put(method, invoker); // } // return invoker; // } // } // Path: src/main/java/org/msgpack/rpc/Client.java import java.io.Closeable; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.msgpack.rpc.loop.EventLoop; import org.msgpack.rpc.address.Address; import org.msgpack.rpc.address.IPAddress; import org.msgpack.rpc.config.ClientConfig; import org.msgpack.rpc.config.TcpClientConfig; import org.msgpack.rpc.reflect.Reflect; // // MessagePack-RPC for Java // // Copyright (C) 2010 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package org.msgpack.rpc; public class Client extends Session implements Closeable { private ScheduledFuture<?> timer; public Client(String host, int port) throws UnknownHostException { this(new IPAddress(host, port), new TcpClientConfig(), EventLoop.defaultEventLoop()); } public Client(String host, int port, ClientConfig config) throws UnknownHostException { this(new IPAddress(host, port), config, EventLoop.defaultEventLoop()); } public Client(String host, int port, EventLoop loop) throws UnknownHostException { this(new IPAddress(host, port), new TcpClientConfig(), loop); }
public Client(String host, int port, EventLoop loop,Reflect reflect)
msgpack-rpc/msgpack-rpc-java
src/main/java/org/msgpack/rpc/Client.java
// Path: src/main/java/org/msgpack/rpc/address/Address.java // public abstract class Address { // abstract public SocketAddress getSocketAddress(); // } // // Path: src/main/java/org/msgpack/rpc/address/IPAddress.java // public class IPAddress extends Address { // private byte[] address; // private int port; // // public IPAddress(String host, int port) throws UnknownHostException { // this.address = InetAddress.getByName(host).getAddress(); // this.port = port; // } // // public IPAddress(int port) { // this.address = new InetSocketAddress(port).getAddress().getAddress(); // this.port = port; // } // // public IPAddress(InetSocketAddress addr) { // this.address = addr.getAddress().getAddress(); // this.port = addr.getPort(); // } // // public IPAddress(InetAddress addr, int port) throws UnknownHostException { // this.address = addr.getAddress(); // this.port = port; // } // // public InetSocketAddress getInetSocketAddress() { // try { // return new InetSocketAddress(InetAddress.getByAddress(address), // port); // } catch (UnknownHostException e) { // throw new RuntimeException(e.getMessage()); // } // } // // public SocketAddress getSocketAddress() { // return getInetSocketAddress(); // } // } // // Path: src/main/java/org/msgpack/rpc/config/ClientConfig.java // public abstract class ClientConfig { // private Map<String, Object> options = new HashMap<String, Object>(); // protected int requestTimeout = 30; // FIXME default timeout time // // public void setRequestTimeout(int sec) { // this.requestTimeout = sec; // } // // public int getRequestTimeout() { // return this.requestTimeout; // } // // public Object getOption(String key) { // return options.get(key); // } // // public Map<String, Object> getOptions() { // return options; // } // // public void setOption(String key, Object value) { // options.put(key, value); // } // } // // Path: src/main/java/org/msgpack/rpc/config/TcpClientConfig.java // public class TcpClientConfig extends StreamClientConfig { // public TcpClientConfig() { // } // } // // Path: src/main/java/org/msgpack/rpc/reflect/Reflect.java // public class Reflect { // /* // * private static final Reflect instance = new Reflect(); // * // * public static <T> Proxy<T> reflectProxy(Class<T> iface) { return // * instance.getProxy(iface); } // * // * public static Invoker reflectInvoker(Method method) { return // * instance.getInvoker(method); } // */ // // private Map<Class<?>, Proxy<?>> proxyCache = new HashMap<Class<?>, Proxy<?>>(); // // private Map<Method, Invoker> invokerCache = new HashMap<Method, Invoker>(); // // private InvokerBuilder invokerBuilder; // private ProxyBuilder proxyBuilder; // // public Reflect(MessagePack messagePack) { // invokerBuilder = new ReflectionInvokerBuilder(messagePack); // proxyBuilder = new ReflectionProxyBuilder(messagePack); // } // // public Reflect( InvokerBuilder invokerBuilder,ProxyBuilder proxyBuilder) { // this.invokerBuilder = invokerBuilder; // this.proxyBuilder = proxyBuilder; // } // // public synchronized <T> Proxy<T> getProxy(Class<T> iface) { // Proxy<?> proxy = proxyCache.get(iface); // if (proxy == null) { // proxy = proxyBuilder.buildProxy(iface);// ProxyBuilder.build(iface); // proxyCache.put(iface, proxy); // } // return (Proxy<T>) proxy; // } // // public synchronized Invoker getInvoker(Method method) { // Invoker invoker = invokerCache.get(method); // if (invoker == null) { // invoker = invokerBuilder.buildInvoker(method); // invokerCache.put(method, invoker); // } // return invoker; // } // }
import java.io.Closeable; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.msgpack.rpc.loop.EventLoop; import org.msgpack.rpc.address.Address; import org.msgpack.rpc.address.IPAddress; import org.msgpack.rpc.config.ClientConfig; import org.msgpack.rpc.config.TcpClientConfig; import org.msgpack.rpc.reflect.Reflect;
} public Client(String host, int port, EventLoop loop,Reflect reflect) throws UnknownHostException { this(new IPAddress(host, port), new TcpClientConfig(), loop,reflect); } public Client(String host, int port, ClientConfig config, EventLoop loop) throws UnknownHostException { this(new IPAddress(host, port), config, loop); } public Client(InetSocketAddress address) { this(new IPAddress(address), new TcpClientConfig(), EventLoop.defaultEventLoop()); } public Client(InetSocketAddress address, ClientConfig config) { this(new IPAddress(address), config, EventLoop.defaultEventLoop()); } public Client(InetSocketAddress address, EventLoop loop) { this(new IPAddress(address), new TcpClientConfig(), loop); } public Client(InetSocketAddress address, ClientConfig config, EventLoop loop) { this(new IPAddress(address), config, loop); } public Client(InetSocketAddress address, ClientConfig config, EventLoop loop,Reflect reflect) { this(new IPAddress(address), config, loop,reflect); }
// Path: src/main/java/org/msgpack/rpc/address/Address.java // public abstract class Address { // abstract public SocketAddress getSocketAddress(); // } // // Path: src/main/java/org/msgpack/rpc/address/IPAddress.java // public class IPAddress extends Address { // private byte[] address; // private int port; // // public IPAddress(String host, int port) throws UnknownHostException { // this.address = InetAddress.getByName(host).getAddress(); // this.port = port; // } // // public IPAddress(int port) { // this.address = new InetSocketAddress(port).getAddress().getAddress(); // this.port = port; // } // // public IPAddress(InetSocketAddress addr) { // this.address = addr.getAddress().getAddress(); // this.port = addr.getPort(); // } // // public IPAddress(InetAddress addr, int port) throws UnknownHostException { // this.address = addr.getAddress(); // this.port = port; // } // // public InetSocketAddress getInetSocketAddress() { // try { // return new InetSocketAddress(InetAddress.getByAddress(address), // port); // } catch (UnknownHostException e) { // throw new RuntimeException(e.getMessage()); // } // } // // public SocketAddress getSocketAddress() { // return getInetSocketAddress(); // } // } // // Path: src/main/java/org/msgpack/rpc/config/ClientConfig.java // public abstract class ClientConfig { // private Map<String, Object> options = new HashMap<String, Object>(); // protected int requestTimeout = 30; // FIXME default timeout time // // public void setRequestTimeout(int sec) { // this.requestTimeout = sec; // } // // public int getRequestTimeout() { // return this.requestTimeout; // } // // public Object getOption(String key) { // return options.get(key); // } // // public Map<String, Object> getOptions() { // return options; // } // // public void setOption(String key, Object value) { // options.put(key, value); // } // } // // Path: src/main/java/org/msgpack/rpc/config/TcpClientConfig.java // public class TcpClientConfig extends StreamClientConfig { // public TcpClientConfig() { // } // } // // Path: src/main/java/org/msgpack/rpc/reflect/Reflect.java // public class Reflect { // /* // * private static final Reflect instance = new Reflect(); // * // * public static <T> Proxy<T> reflectProxy(Class<T> iface) { return // * instance.getProxy(iface); } // * // * public static Invoker reflectInvoker(Method method) { return // * instance.getInvoker(method); } // */ // // private Map<Class<?>, Proxy<?>> proxyCache = new HashMap<Class<?>, Proxy<?>>(); // // private Map<Method, Invoker> invokerCache = new HashMap<Method, Invoker>(); // // private InvokerBuilder invokerBuilder; // private ProxyBuilder proxyBuilder; // // public Reflect(MessagePack messagePack) { // invokerBuilder = new ReflectionInvokerBuilder(messagePack); // proxyBuilder = new ReflectionProxyBuilder(messagePack); // } // // public Reflect( InvokerBuilder invokerBuilder,ProxyBuilder proxyBuilder) { // this.invokerBuilder = invokerBuilder; // this.proxyBuilder = proxyBuilder; // } // // public synchronized <T> Proxy<T> getProxy(Class<T> iface) { // Proxy<?> proxy = proxyCache.get(iface); // if (proxy == null) { // proxy = proxyBuilder.buildProxy(iface);// ProxyBuilder.build(iface); // proxyCache.put(iface, proxy); // } // return (Proxy<T>) proxy; // } // // public synchronized Invoker getInvoker(Method method) { // Invoker invoker = invokerCache.get(method); // if (invoker == null) { // invoker = invokerBuilder.buildInvoker(method); // invokerCache.put(method, invoker); // } // return invoker; // } // } // Path: src/main/java/org/msgpack/rpc/Client.java import java.io.Closeable; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.msgpack.rpc.loop.EventLoop; import org.msgpack.rpc.address.Address; import org.msgpack.rpc.address.IPAddress; import org.msgpack.rpc.config.ClientConfig; import org.msgpack.rpc.config.TcpClientConfig; import org.msgpack.rpc.reflect.Reflect; } public Client(String host, int port, EventLoop loop,Reflect reflect) throws UnknownHostException { this(new IPAddress(host, port), new TcpClientConfig(), loop,reflect); } public Client(String host, int port, ClientConfig config, EventLoop loop) throws UnknownHostException { this(new IPAddress(host, port), config, loop); } public Client(InetSocketAddress address) { this(new IPAddress(address), new TcpClientConfig(), EventLoop.defaultEventLoop()); } public Client(InetSocketAddress address, ClientConfig config) { this(new IPAddress(address), config, EventLoop.defaultEventLoop()); } public Client(InetSocketAddress address, EventLoop loop) { this(new IPAddress(address), new TcpClientConfig(), loop); } public Client(InetSocketAddress address, ClientConfig config, EventLoop loop) { this(new IPAddress(address), config, loop); } public Client(InetSocketAddress address, ClientConfig config, EventLoop loop,Reflect reflect) { this(new IPAddress(address), config, loop,reflect); }
Client(Address address, ClientConfig config, EventLoop loop) {
msgpack-rpc/msgpack-rpc-java
src/main/java/org/msgpack/rpc/builder/StopWatchDispatcherBuilder.java
// Path: src/main/java/org/msgpack/rpc/dispatcher/StopWatchDispatcher.java // public class StopWatchDispatcher implements Dispatcher { // // Dispatcher innerDispatcher; // // private final static Logger logger = LoggerFactory.getLogger(StopWatchDispatcher.class); // // private boolean verbose = true; // // public boolean isVerbose() { // return verbose; // } // // public void setVerbose(boolean verbose) { // this.verbose = verbose; // } // // public StopWatchDispatcher(Dispatcher inner) { // this.innerDispatcher = inner; // } // // public void dispatch(Request request) throws Exception { // if(verbose){ // logger.info(String.format( "Begin dispatching %s with args %s",request.getMethodName(),request.getArguments().toString())); // } // long start = System.currentTimeMillis(); // try{ // innerDispatcher.dispatch(request); // long diff = System.currentTimeMillis() - start; // logger.info(String.format("Dispatch %s in %s msecs",request.getMethodName(),diff)); // }catch(Exception e){ // long diff = System.currentTimeMillis() - start; // logger.info(String.format("%s : %s while dispatching %s,(in %s msecs)",e.getClass().getSimpleName(), e.getMessage(), request.getMethodName(),diff)); // throw e; // } // } // }
import org.msgpack.MessagePack; import org.msgpack.rpc.dispatcher.Dispatcher; import org.msgpack.rpc.dispatcher.StopWatchDispatcher;
package org.msgpack.rpc.builder; /** * User: takeshita * Create: 12/06/15 1:23 */ public class StopWatchDispatcherBuilder implements DispatcherBuilder { protected DispatcherBuilder baseBuilder; protected boolean verbose = false; public boolean isVerbose() { return verbose; } public void setVerbose(boolean verbose) { this.verbose = verbose; } public StopWatchDispatcherBuilder withVerboseOutput(boolean verbose){ this.verbose = verbose; return this; } public StopWatchDispatcherBuilder(DispatcherBuilder baseBuilder){ this.baseBuilder = baseBuilder; } public Dispatcher decorate(Dispatcher innerDispatcher) {
// Path: src/main/java/org/msgpack/rpc/dispatcher/StopWatchDispatcher.java // public class StopWatchDispatcher implements Dispatcher { // // Dispatcher innerDispatcher; // // private final static Logger logger = LoggerFactory.getLogger(StopWatchDispatcher.class); // // private boolean verbose = true; // // public boolean isVerbose() { // return verbose; // } // // public void setVerbose(boolean verbose) { // this.verbose = verbose; // } // // public StopWatchDispatcher(Dispatcher inner) { // this.innerDispatcher = inner; // } // // public void dispatch(Request request) throws Exception { // if(verbose){ // logger.info(String.format( "Begin dispatching %s with args %s",request.getMethodName(),request.getArguments().toString())); // } // long start = System.currentTimeMillis(); // try{ // innerDispatcher.dispatch(request); // long diff = System.currentTimeMillis() - start; // logger.info(String.format("Dispatch %s in %s msecs",request.getMethodName(),diff)); // }catch(Exception e){ // long diff = System.currentTimeMillis() - start; // logger.info(String.format("%s : %s while dispatching %s,(in %s msecs)",e.getClass().getSimpleName(), e.getMessage(), request.getMethodName(),diff)); // throw e; // } // } // } // Path: src/main/java/org/msgpack/rpc/builder/StopWatchDispatcherBuilder.java import org.msgpack.MessagePack; import org.msgpack.rpc.dispatcher.Dispatcher; import org.msgpack.rpc.dispatcher.StopWatchDispatcher; package org.msgpack.rpc.builder; /** * User: takeshita * Create: 12/06/15 1:23 */ public class StopWatchDispatcherBuilder implements DispatcherBuilder { protected DispatcherBuilder baseBuilder; protected boolean verbose = false; public boolean isVerbose() { return verbose; } public void setVerbose(boolean verbose) { this.verbose = verbose; } public StopWatchDispatcherBuilder withVerboseOutput(boolean verbose){ this.verbose = verbose; return this; } public StopWatchDispatcherBuilder(DispatcherBuilder baseBuilder){ this.baseBuilder = baseBuilder; } public Dispatcher decorate(Dispatcher innerDispatcher) {
StopWatchDispatcher disp = new StopWatchDispatcher(innerDispatcher);
msgpack-rpc/msgpack-rpc-java
src/main/java/org/msgpack/rpc/SessionPool.java
// Path: src/main/java/org/msgpack/rpc/address/Address.java // public abstract class Address { // abstract public SocketAddress getSocketAddress(); // } // // Path: src/main/java/org/msgpack/rpc/address/IPAddress.java // public class IPAddress extends Address { // private byte[] address; // private int port; // // public IPAddress(String host, int port) throws UnknownHostException { // this.address = InetAddress.getByName(host).getAddress(); // this.port = port; // } // // public IPAddress(int port) { // this.address = new InetSocketAddress(port).getAddress().getAddress(); // this.port = port; // } // // public IPAddress(InetSocketAddress addr) { // this.address = addr.getAddress().getAddress(); // this.port = addr.getPort(); // } // // public IPAddress(InetAddress addr, int port) throws UnknownHostException { // this.address = addr.getAddress(); // this.port = port; // } // // public InetSocketAddress getInetSocketAddress() { // try { // return new InetSocketAddress(InetAddress.getByAddress(address), // port); // } catch (UnknownHostException e) { // throw new RuntimeException(e.getMessage()); // } // } // // public SocketAddress getSocketAddress() { // return getInetSocketAddress(); // } // } // // Path: src/main/java/org/msgpack/rpc/config/ClientConfig.java // public abstract class ClientConfig { // private Map<String, Object> options = new HashMap<String, Object>(); // protected int requestTimeout = 30; // FIXME default timeout time // // public void setRequestTimeout(int sec) { // this.requestTimeout = sec; // } // // public int getRequestTimeout() { // return this.requestTimeout; // } // // public Object getOption(String key) { // return options.get(key); // } // // public Map<String, Object> getOptions() { // return options; // } // // public void setOption(String key, Object value) { // options.put(key, value); // } // } // // Path: src/main/java/org/msgpack/rpc/config/TcpClientConfig.java // public class TcpClientConfig extends StreamClientConfig { // public TcpClientConfig() { // } // }
import java.io.Closeable; import java.util.Map; import java.util.HashMap; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.msgpack.rpc.loop.EventLoop; import org.msgpack.rpc.address.Address; import org.msgpack.rpc.address.IPAddress; import org.msgpack.rpc.config.ClientConfig; import org.msgpack.rpc.config.TcpClientConfig;
// // MessagePack-RPC for Java // // Copyright (C) 2010 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package org.msgpack.rpc; public class SessionPool implements Closeable { private ClientConfig config; private EventLoop loop;
// Path: src/main/java/org/msgpack/rpc/address/Address.java // public abstract class Address { // abstract public SocketAddress getSocketAddress(); // } // // Path: src/main/java/org/msgpack/rpc/address/IPAddress.java // public class IPAddress extends Address { // private byte[] address; // private int port; // // public IPAddress(String host, int port) throws UnknownHostException { // this.address = InetAddress.getByName(host).getAddress(); // this.port = port; // } // // public IPAddress(int port) { // this.address = new InetSocketAddress(port).getAddress().getAddress(); // this.port = port; // } // // public IPAddress(InetSocketAddress addr) { // this.address = addr.getAddress().getAddress(); // this.port = addr.getPort(); // } // // public IPAddress(InetAddress addr, int port) throws UnknownHostException { // this.address = addr.getAddress(); // this.port = port; // } // // public InetSocketAddress getInetSocketAddress() { // try { // return new InetSocketAddress(InetAddress.getByAddress(address), // port); // } catch (UnknownHostException e) { // throw new RuntimeException(e.getMessage()); // } // } // // public SocketAddress getSocketAddress() { // return getInetSocketAddress(); // } // } // // Path: src/main/java/org/msgpack/rpc/config/ClientConfig.java // public abstract class ClientConfig { // private Map<String, Object> options = new HashMap<String, Object>(); // protected int requestTimeout = 30; // FIXME default timeout time // // public void setRequestTimeout(int sec) { // this.requestTimeout = sec; // } // // public int getRequestTimeout() { // return this.requestTimeout; // } // // public Object getOption(String key) { // return options.get(key); // } // // public Map<String, Object> getOptions() { // return options; // } // // public void setOption(String key, Object value) { // options.put(key, value); // } // } // // Path: src/main/java/org/msgpack/rpc/config/TcpClientConfig.java // public class TcpClientConfig extends StreamClientConfig { // public TcpClientConfig() { // } // } // Path: src/main/java/org/msgpack/rpc/SessionPool.java import java.io.Closeable; import java.util.Map; import java.util.HashMap; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.msgpack.rpc.loop.EventLoop; import org.msgpack.rpc.address.Address; import org.msgpack.rpc.address.IPAddress; import org.msgpack.rpc.config.ClientConfig; import org.msgpack.rpc.config.TcpClientConfig; // // MessagePack-RPC for Java // // Copyright (C) 2010 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package org.msgpack.rpc; public class SessionPool implements Closeable { private ClientConfig config; private EventLoop loop;
private Map<Address, Session> pool = new HashMap<Address, Session>();
msgpack-rpc/msgpack-rpc-java
src/main/java/org/msgpack/rpc/SessionPool.java
// Path: src/main/java/org/msgpack/rpc/address/Address.java // public abstract class Address { // abstract public SocketAddress getSocketAddress(); // } // // Path: src/main/java/org/msgpack/rpc/address/IPAddress.java // public class IPAddress extends Address { // private byte[] address; // private int port; // // public IPAddress(String host, int port) throws UnknownHostException { // this.address = InetAddress.getByName(host).getAddress(); // this.port = port; // } // // public IPAddress(int port) { // this.address = new InetSocketAddress(port).getAddress().getAddress(); // this.port = port; // } // // public IPAddress(InetSocketAddress addr) { // this.address = addr.getAddress().getAddress(); // this.port = addr.getPort(); // } // // public IPAddress(InetAddress addr, int port) throws UnknownHostException { // this.address = addr.getAddress(); // this.port = port; // } // // public InetSocketAddress getInetSocketAddress() { // try { // return new InetSocketAddress(InetAddress.getByAddress(address), // port); // } catch (UnknownHostException e) { // throw new RuntimeException(e.getMessage()); // } // } // // public SocketAddress getSocketAddress() { // return getInetSocketAddress(); // } // } // // Path: src/main/java/org/msgpack/rpc/config/ClientConfig.java // public abstract class ClientConfig { // private Map<String, Object> options = new HashMap<String, Object>(); // protected int requestTimeout = 30; // FIXME default timeout time // // public void setRequestTimeout(int sec) { // this.requestTimeout = sec; // } // // public int getRequestTimeout() { // return this.requestTimeout; // } // // public Object getOption(String key) { // return options.get(key); // } // // public Map<String, Object> getOptions() { // return options; // } // // public void setOption(String key, Object value) { // options.put(key, value); // } // } // // Path: src/main/java/org/msgpack/rpc/config/TcpClientConfig.java // public class TcpClientConfig extends StreamClientConfig { // public TcpClientConfig() { // } // }
import java.io.Closeable; import java.util.Map; import java.util.HashMap; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.msgpack.rpc.loop.EventLoop; import org.msgpack.rpc.address.Address; import org.msgpack.rpc.address.IPAddress; import org.msgpack.rpc.config.ClientConfig; import org.msgpack.rpc.config.TcpClientConfig;
// // MessagePack-RPC for Java // // Copyright (C) 2010 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package org.msgpack.rpc; public class SessionPool implements Closeable { private ClientConfig config; private EventLoop loop; private Map<Address, Session> pool = new HashMap<Address, Session>(); private ScheduledFuture<?> timer; public SessionPool() {
// Path: src/main/java/org/msgpack/rpc/address/Address.java // public abstract class Address { // abstract public SocketAddress getSocketAddress(); // } // // Path: src/main/java/org/msgpack/rpc/address/IPAddress.java // public class IPAddress extends Address { // private byte[] address; // private int port; // // public IPAddress(String host, int port) throws UnknownHostException { // this.address = InetAddress.getByName(host).getAddress(); // this.port = port; // } // // public IPAddress(int port) { // this.address = new InetSocketAddress(port).getAddress().getAddress(); // this.port = port; // } // // public IPAddress(InetSocketAddress addr) { // this.address = addr.getAddress().getAddress(); // this.port = addr.getPort(); // } // // public IPAddress(InetAddress addr, int port) throws UnknownHostException { // this.address = addr.getAddress(); // this.port = port; // } // // public InetSocketAddress getInetSocketAddress() { // try { // return new InetSocketAddress(InetAddress.getByAddress(address), // port); // } catch (UnknownHostException e) { // throw new RuntimeException(e.getMessage()); // } // } // // public SocketAddress getSocketAddress() { // return getInetSocketAddress(); // } // } // // Path: src/main/java/org/msgpack/rpc/config/ClientConfig.java // public abstract class ClientConfig { // private Map<String, Object> options = new HashMap<String, Object>(); // protected int requestTimeout = 30; // FIXME default timeout time // // public void setRequestTimeout(int sec) { // this.requestTimeout = sec; // } // // public int getRequestTimeout() { // return this.requestTimeout; // } // // public Object getOption(String key) { // return options.get(key); // } // // public Map<String, Object> getOptions() { // return options; // } // // public void setOption(String key, Object value) { // options.put(key, value); // } // } // // Path: src/main/java/org/msgpack/rpc/config/TcpClientConfig.java // public class TcpClientConfig extends StreamClientConfig { // public TcpClientConfig() { // } // } // Path: src/main/java/org/msgpack/rpc/SessionPool.java import java.io.Closeable; import java.util.Map; import java.util.HashMap; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.msgpack.rpc.loop.EventLoop; import org.msgpack.rpc.address.Address; import org.msgpack.rpc.address.IPAddress; import org.msgpack.rpc.config.ClientConfig; import org.msgpack.rpc.config.TcpClientConfig; // // MessagePack-RPC for Java // // Copyright (C) 2010 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package org.msgpack.rpc; public class SessionPool implements Closeable { private ClientConfig config; private EventLoop loop; private Map<Address, Session> pool = new HashMap<Address, Session>(); private ScheduledFuture<?> timer; public SessionPool() {
this(new TcpClientConfig());
msgpack-rpc/msgpack-rpc-java
src/main/java/org/msgpack/rpc/SessionPool.java
// Path: src/main/java/org/msgpack/rpc/address/Address.java // public abstract class Address { // abstract public SocketAddress getSocketAddress(); // } // // Path: src/main/java/org/msgpack/rpc/address/IPAddress.java // public class IPAddress extends Address { // private byte[] address; // private int port; // // public IPAddress(String host, int port) throws UnknownHostException { // this.address = InetAddress.getByName(host).getAddress(); // this.port = port; // } // // public IPAddress(int port) { // this.address = new InetSocketAddress(port).getAddress().getAddress(); // this.port = port; // } // // public IPAddress(InetSocketAddress addr) { // this.address = addr.getAddress().getAddress(); // this.port = addr.getPort(); // } // // public IPAddress(InetAddress addr, int port) throws UnknownHostException { // this.address = addr.getAddress(); // this.port = port; // } // // public InetSocketAddress getInetSocketAddress() { // try { // return new InetSocketAddress(InetAddress.getByAddress(address), // port); // } catch (UnknownHostException e) { // throw new RuntimeException(e.getMessage()); // } // } // // public SocketAddress getSocketAddress() { // return getInetSocketAddress(); // } // } // // Path: src/main/java/org/msgpack/rpc/config/ClientConfig.java // public abstract class ClientConfig { // private Map<String, Object> options = new HashMap<String, Object>(); // protected int requestTimeout = 30; // FIXME default timeout time // // public void setRequestTimeout(int sec) { // this.requestTimeout = sec; // } // // public int getRequestTimeout() { // return this.requestTimeout; // } // // public Object getOption(String key) { // return options.get(key); // } // // public Map<String, Object> getOptions() { // return options; // } // // public void setOption(String key, Object value) { // options.put(key, value); // } // } // // Path: src/main/java/org/msgpack/rpc/config/TcpClientConfig.java // public class TcpClientConfig extends StreamClientConfig { // public TcpClientConfig() { // } // }
import java.io.Closeable; import java.util.Map; import java.util.HashMap; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.msgpack.rpc.loop.EventLoop; import org.msgpack.rpc.address.Address; import org.msgpack.rpc.address.IPAddress; import org.msgpack.rpc.config.ClientConfig; import org.msgpack.rpc.config.TcpClientConfig;
// // MessagePack-RPC for Java // // Copyright (C) 2010 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package org.msgpack.rpc; public class SessionPool implements Closeable { private ClientConfig config; private EventLoop loop; private Map<Address, Session> pool = new HashMap<Address, Session>(); private ScheduledFuture<?> timer; public SessionPool() { this(new TcpClientConfig()); } public SessionPool(ClientConfig config) { this(config, EventLoop.defaultEventLoop()); } public SessionPool(EventLoop loop) { this(new TcpClientConfig(), loop); } public SessionPool(ClientConfig config, EventLoop loop) { this.config = config; this.loop = loop; startTimer(); } // FIXME EventLoopHolder interface? public EventLoop getEventLoop() { return loop; } public Session getSession(String host, int port) throws UnknownHostException {
// Path: src/main/java/org/msgpack/rpc/address/Address.java // public abstract class Address { // abstract public SocketAddress getSocketAddress(); // } // // Path: src/main/java/org/msgpack/rpc/address/IPAddress.java // public class IPAddress extends Address { // private byte[] address; // private int port; // // public IPAddress(String host, int port) throws UnknownHostException { // this.address = InetAddress.getByName(host).getAddress(); // this.port = port; // } // // public IPAddress(int port) { // this.address = new InetSocketAddress(port).getAddress().getAddress(); // this.port = port; // } // // public IPAddress(InetSocketAddress addr) { // this.address = addr.getAddress().getAddress(); // this.port = addr.getPort(); // } // // public IPAddress(InetAddress addr, int port) throws UnknownHostException { // this.address = addr.getAddress(); // this.port = port; // } // // public InetSocketAddress getInetSocketAddress() { // try { // return new InetSocketAddress(InetAddress.getByAddress(address), // port); // } catch (UnknownHostException e) { // throw new RuntimeException(e.getMessage()); // } // } // // public SocketAddress getSocketAddress() { // return getInetSocketAddress(); // } // } // // Path: src/main/java/org/msgpack/rpc/config/ClientConfig.java // public abstract class ClientConfig { // private Map<String, Object> options = new HashMap<String, Object>(); // protected int requestTimeout = 30; // FIXME default timeout time // // public void setRequestTimeout(int sec) { // this.requestTimeout = sec; // } // // public int getRequestTimeout() { // return this.requestTimeout; // } // // public Object getOption(String key) { // return options.get(key); // } // // public Map<String, Object> getOptions() { // return options; // } // // public void setOption(String key, Object value) { // options.put(key, value); // } // } // // Path: src/main/java/org/msgpack/rpc/config/TcpClientConfig.java // public class TcpClientConfig extends StreamClientConfig { // public TcpClientConfig() { // } // } // Path: src/main/java/org/msgpack/rpc/SessionPool.java import java.io.Closeable; import java.util.Map; import java.util.HashMap; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.msgpack.rpc.loop.EventLoop; import org.msgpack.rpc.address.Address; import org.msgpack.rpc.address.IPAddress; import org.msgpack.rpc.config.ClientConfig; import org.msgpack.rpc.config.TcpClientConfig; // // MessagePack-RPC for Java // // Copyright (C) 2010 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package org.msgpack.rpc; public class SessionPool implements Closeable { private ClientConfig config; private EventLoop loop; private Map<Address, Session> pool = new HashMap<Address, Session>(); private ScheduledFuture<?> timer; public SessionPool() { this(new TcpClientConfig()); } public SessionPool(ClientConfig config) { this(config, EventLoop.defaultEventLoop()); } public SessionPool(EventLoop loop) { this(new TcpClientConfig(), loop); } public SessionPool(ClientConfig config, EventLoop loop) { this.config = config; this.loop = loop; startTimer(); } // FIXME EventLoopHolder interface? public EventLoop getEventLoop() { return loop; } public Session getSession(String host, int port) throws UnknownHostException {
return getSession(new IPAddress(host, port));
msgpack-rpc/msgpack-rpc-java
src/test/java/org/msgpack/rpc/DecoratorTest.java
// Path: src/main/java/org/msgpack/rpc/builder/StopWatchDispatcherBuilder.java // public class StopWatchDispatcherBuilder implements DispatcherBuilder { // // protected DispatcherBuilder baseBuilder; // protected boolean verbose = false; // // public boolean isVerbose() { // return verbose; // } // // public void setVerbose(boolean verbose) { // this.verbose = verbose; // } // // public StopWatchDispatcherBuilder withVerboseOutput(boolean verbose){ // this.verbose = verbose; // return this; // } // // public StopWatchDispatcherBuilder(DispatcherBuilder baseBuilder){ // this.baseBuilder = baseBuilder; // } // // public Dispatcher decorate(Dispatcher innerDispatcher) { // StopWatchDispatcher disp = new StopWatchDispatcher(innerDispatcher); // disp.setVerbose(verbose); // return disp; // } // // public Dispatcher build(Object handler, MessagePack messagePack) { // return decorate(baseBuilder.build(handler,messagePack)); // } // }
import junit.framework.TestCase; import org.apache.log4j.BasicConfigurator; import org.junit.Test; import org.msgpack.MessageTypeException; import org.msgpack.rpc.builder.StopWatchDispatcherBuilder; import org.msgpack.rpc.loop.EventLoop; import org.msgpack.type.Value;
package org.msgpack.rpc; /** * User: takeshita * Create: 12/06/15 1:51 */ public class DecoratorTest extends TestCase { public static class TestServer{ public String success() { return "ok"; } public String throwError(String errorMessage) throws Exception{ throw new MessageTypeException(errorMessage); } } /** * Test any Exception is not thrown. * @throws Exception */ @Test public void testDecorateStopWatch() throws Exception { BasicConfigurator.configure(); EventLoop loop = EventLoop.start(); Server svr = new Server(loop); svr.setDispatcherBuilder(
// Path: src/main/java/org/msgpack/rpc/builder/StopWatchDispatcherBuilder.java // public class StopWatchDispatcherBuilder implements DispatcherBuilder { // // protected DispatcherBuilder baseBuilder; // protected boolean verbose = false; // // public boolean isVerbose() { // return verbose; // } // // public void setVerbose(boolean verbose) { // this.verbose = verbose; // } // // public StopWatchDispatcherBuilder withVerboseOutput(boolean verbose){ // this.verbose = verbose; // return this; // } // // public StopWatchDispatcherBuilder(DispatcherBuilder baseBuilder){ // this.baseBuilder = baseBuilder; // } // // public Dispatcher decorate(Dispatcher innerDispatcher) { // StopWatchDispatcher disp = new StopWatchDispatcher(innerDispatcher); // disp.setVerbose(verbose); // return disp; // } // // public Dispatcher build(Object handler, MessagePack messagePack) { // return decorate(baseBuilder.build(handler,messagePack)); // } // } // Path: src/test/java/org/msgpack/rpc/DecoratorTest.java import junit.framework.TestCase; import org.apache.log4j.BasicConfigurator; import org.junit.Test; import org.msgpack.MessageTypeException; import org.msgpack.rpc.builder.StopWatchDispatcherBuilder; import org.msgpack.rpc.loop.EventLoop; import org.msgpack.type.Value; package org.msgpack.rpc; /** * User: takeshita * Create: 12/06/15 1:51 */ public class DecoratorTest extends TestCase { public static class TestServer{ public String success() { return "ok"; } public String throwError(String errorMessage) throws Exception{ throw new MessageTypeException(errorMessage); } } /** * Test any Exception is not thrown. * @throws Exception */ @Test public void testDecorateStopWatch() throws Exception { BasicConfigurator.configure(); EventLoop loop = EventLoop.start(); Server svr = new Server(loop); svr.setDispatcherBuilder(
new StopWatchDispatcherBuilder(svr.getDispatcherBuilder()).
msgpack-rpc/msgpack-rpc-java
src/main/java/org/msgpack/rpc/dispatcher/StopWatchDispatcher.java
// Path: src/main/java/org/msgpack/rpc/Request.java // public class Request implements Callback<Object> { // private MessageSendable channel; // TODO #SF synchronized? // private int msgid; // private String method; // private Value args; // // public Request(MessageSendable channel, int msgid, String method, Value args) { // this.channel = channel; // this.msgid = msgid; // this.method = method; // this.args = args; // } // // public Request(String method, Value args) { // this.channel = null; // this.msgid = 0; // this.method = method; // this.args = args; // } // // public String getMethodName() { // return method; // } // // public Value getArguments() { // return args; // } // // public int getMessageID() { // return msgid; // } // // public void sendResult(Object result) { // sendResponse(result, null); // } // // public void sendError(Object error) { // sendResponse(null, error); // } // // public void sendError(Object error, Object data) { // sendResponse(data, error); // } // // public synchronized void sendResponse(Object result, Object error) { // if (channel == null) { // return; // } // ResponseMessage msg = new ResponseMessage(msgid, error, result); // channel.sendMessage(msg); // channel = null; // } // }
import org.msgpack.rpc.Request; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package org.msgpack.rpc.dispatcher; /** * For debug. * Measures dispatch time. * * User: takeshita * Create: 12/06/15 0:53 */ public class StopWatchDispatcher implements Dispatcher { Dispatcher innerDispatcher; private final static Logger logger = LoggerFactory.getLogger(StopWatchDispatcher.class); private boolean verbose = true; public boolean isVerbose() { return verbose; } public void setVerbose(boolean verbose) { this.verbose = verbose; } public StopWatchDispatcher(Dispatcher inner) { this.innerDispatcher = inner; }
// Path: src/main/java/org/msgpack/rpc/Request.java // public class Request implements Callback<Object> { // private MessageSendable channel; // TODO #SF synchronized? // private int msgid; // private String method; // private Value args; // // public Request(MessageSendable channel, int msgid, String method, Value args) { // this.channel = channel; // this.msgid = msgid; // this.method = method; // this.args = args; // } // // public Request(String method, Value args) { // this.channel = null; // this.msgid = 0; // this.method = method; // this.args = args; // } // // public String getMethodName() { // return method; // } // // public Value getArguments() { // return args; // } // // public int getMessageID() { // return msgid; // } // // public void sendResult(Object result) { // sendResponse(result, null); // } // // public void sendError(Object error) { // sendResponse(null, error); // } // // public void sendError(Object error, Object data) { // sendResponse(data, error); // } // // public synchronized void sendResponse(Object result, Object error) { // if (channel == null) { // return; // } // ResponseMessage msg = new ResponseMessage(msgid, error, result); // channel.sendMessage(msg); // channel = null; // } // } // Path: src/main/java/org/msgpack/rpc/dispatcher/StopWatchDispatcher.java import org.msgpack.rpc.Request; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package org.msgpack.rpc.dispatcher; /** * For debug. * Measures dispatch time. * * User: takeshita * Create: 12/06/15 0:53 */ public class StopWatchDispatcher implements Dispatcher { Dispatcher innerDispatcher; private final static Logger logger = LoggerFactory.getLogger(StopWatchDispatcher.class); private boolean verbose = true; public boolean isVerbose() { return verbose; } public void setVerbose(boolean verbose) { this.verbose = verbose; } public StopWatchDispatcher(Dispatcher inner) { this.innerDispatcher = inner; }
public void dispatch(Request request) throws Exception {
StrikerX3/JXInput
src/main/java/com/github/strikerx3/jxinput/listener/SimpleXInputDeviceListener.java
// Path: src/main/java/com/github/strikerx3/jxinput/enums/XInputButton.java // public enum XInputButton { // A, B, X, Y, // BACK, START, // LEFT_SHOULDER, RIGHT_SHOULDER, // LEFT_THUMBSTICK, RIGHT_THUMBSTICK, // DPAD_UP, DPAD_DOWN, DPAD_LEFT, DPAD_RIGHT, // GUIDE_BUTTON, UNKNOWN; // }
import com.github.strikerx3.jxinput.enums.XInputButton;
package com.github.strikerx3.jxinput.listener; /** * Provides empty implementations of all {@link XInputDeviceListener} methods for easier subclassing. * * @author Ivan "StrikerX3" Oliveira */ public class SimpleXInputDeviceListener implements XInputDeviceListener { @Override public void connected() { } @Override public void disconnected() { } @Override
// Path: src/main/java/com/github/strikerx3/jxinput/enums/XInputButton.java // public enum XInputButton { // A, B, X, Y, // BACK, START, // LEFT_SHOULDER, RIGHT_SHOULDER, // LEFT_THUMBSTICK, RIGHT_THUMBSTICK, // DPAD_UP, DPAD_DOWN, DPAD_LEFT, DPAD_RIGHT, // GUIDE_BUTTON, UNKNOWN; // } // Path: src/main/java/com/github/strikerx3/jxinput/listener/SimpleXInputDeviceListener.java import com.github.strikerx3.jxinput.enums.XInputButton; package com.github.strikerx3.jxinput.listener; /** * Provides empty implementations of all {@link XInputDeviceListener} methods for easier subclassing. * * @author Ivan "StrikerX3" Oliveira */ public class SimpleXInputDeviceListener implements XInputDeviceListener { @Override public void connected() { } @Override public void disconnected() { } @Override
public void buttonChanged(final XInputButton button, final boolean pressed) {
StrikerX3/JXInput
src/main/java/com/github/strikerx3/jxinput/XInputAxesDelta.java
// Path: src/main/java/com/github/strikerx3/jxinput/enums/XInputAxis.java // public enum XInputAxis { // LEFT_THUMBSTICK_X, LEFT_THUMBSTICK_Y, // RIGHT_THUMBSTICK_X, RIGHT_THUMBSTICK_Y, // LEFT_TRIGGER, RIGHT_TRIGGER, // DPAD; // }
import com.github.strikerx3.jxinput.enums.XInputAxis;
return lastAxes.ryRaw - axes.ryRaw; } /** * Returns the difference of the raw value of the Left Trigger axis between two consecutive polls. A positive value means * the trigger was pressed, while a negative value indicates that the trigger was released. * * @return the delta of the raw value of the Left Trigger axis */ public int getLTRawDelta() { return lastAxes.ltRaw - axes.ltRaw; } /** * Returns the difference of the raw value of the Right Trigger axis between two consecutive polls. A positive value * means the trigger was pressed, while a negative value indicates that the trigger was released. * * @return the delta of the raw value of the Right Trigger axis */ public int getRTRawDelta() { return lastAxes.rtRaw - axes.rtRaw; } /** * Returns the difference of the specified axis between two consecutive polls. Refer to the other methods of this class * to learn what positive and negative value means for each axis. * * @param axis the axis the get the delta from * @return the delta for the specified axis */
// Path: src/main/java/com/github/strikerx3/jxinput/enums/XInputAxis.java // public enum XInputAxis { // LEFT_THUMBSTICK_X, LEFT_THUMBSTICK_Y, // RIGHT_THUMBSTICK_X, RIGHT_THUMBSTICK_Y, // LEFT_TRIGGER, RIGHT_TRIGGER, // DPAD; // } // Path: src/main/java/com/github/strikerx3/jxinput/XInputAxesDelta.java import com.github.strikerx3.jxinput.enums.XInputAxis; return lastAxes.ryRaw - axes.ryRaw; } /** * Returns the difference of the raw value of the Left Trigger axis between two consecutive polls. A positive value means * the trigger was pressed, while a negative value indicates that the trigger was released. * * @return the delta of the raw value of the Left Trigger axis */ public int getLTRawDelta() { return lastAxes.ltRaw - axes.ltRaw; } /** * Returns the difference of the raw value of the Right Trigger axis between two consecutive polls. A positive value * means the trigger was pressed, while a negative value indicates that the trigger was released. * * @return the delta of the raw value of the Right Trigger axis */ public int getRTRawDelta() { return lastAxes.rtRaw - axes.rtRaw; } /** * Returns the difference of the specified axis between two consecutive polls. Refer to the other methods of this class * to learn what positive and negative value means for each axis. * * @param axis the axis the get the delta from * @return the delta for the specified axis */
public float getDelta(final XInputAxis axis) {
StrikerX3/JXInput
src/main/java/com/github/strikerx3/jxinput/listener/XInputDeviceListener.java
// Path: src/main/java/com/github/strikerx3/jxinput/enums/XInputButton.java // public enum XInputButton { // A, B, X, Y, // BACK, START, // LEFT_SHOULDER, RIGHT_SHOULDER, // LEFT_THUMBSTICK, RIGHT_THUMBSTICK, // DPAD_UP, DPAD_DOWN, DPAD_LEFT, DPAD_RIGHT, // GUIDE_BUTTON, UNKNOWN; // }
import com.github.strikerx3.jxinput.enums.XInputButton;
package com.github.strikerx3.jxinput.listener; /** * Listens to all XInput events. * The {@link SimpleXInputDeviceListener} class provides empty implementations of the methods in this interface * for easier subclassing. * * @author Ivan "StrikerX3" Oliveira */ public interface XInputDeviceListener { /** * Called when the device is connected. */ void connected(); /** * Called when the device is disconnected. */ void disconnected(); /** * Called when a button is pressed or released. * * @param button the button * @param pressed <code>true</code> if the button was pressed, <code>false</code> if released. */
// Path: src/main/java/com/github/strikerx3/jxinput/enums/XInputButton.java // public enum XInputButton { // A, B, X, Y, // BACK, START, // LEFT_SHOULDER, RIGHT_SHOULDER, // LEFT_THUMBSTICK, RIGHT_THUMBSTICK, // DPAD_UP, DPAD_DOWN, DPAD_LEFT, DPAD_RIGHT, // GUIDE_BUTTON, UNKNOWN; // } // Path: src/main/java/com/github/strikerx3/jxinput/listener/XInputDeviceListener.java import com.github.strikerx3.jxinput.enums.XInputButton; package com.github.strikerx3.jxinput.listener; /** * Listens to all XInput events. * The {@link SimpleXInputDeviceListener} class provides empty implementations of the methods in this interface * for easier subclassing. * * @author Ivan "StrikerX3" Oliveira */ public interface XInputDeviceListener { /** * Called when the device is connected. */ void connected(); /** * Called when the device is disconnected. */ void disconnected(); /** * Called when a button is pressed or released. * * @param button the button * @param pressed <code>true</code> if the button was pressed, <code>false</code> if released. */
void buttonChanged(final XInputButton button, final boolean pressed);
StrikerX3/JXInput
src/main/java/com/github/strikerx3/jxinput/enums/XInputBatteryLevel.java
// Path: src/main/java/com/github/strikerx3/jxinput/natives/XInputConstants.java // public final class XInputConstants { // private XInputConstants() {} // // // ------------- // // XInput // // public static final int MAX_PLAYERS = 4; // // // Controller button masks // public static final short XINPUT_GAMEPAD_DPAD_UP = 0x0001; // public static final short XINPUT_GAMEPAD_DPAD_DOWN = 0x0002; // public static final short XINPUT_GAMEPAD_DPAD_LEFT = 0x0004; // public static final short XINPUT_GAMEPAD_DPAD_RIGHT = 0x0008; // public static final short XINPUT_GAMEPAD_START = 0x0010; // public static final short XINPUT_GAMEPAD_BACK = 0x0020; // public static final short XINPUT_GAMEPAD_LEFT_THUMB = 0x0040; // public static final short XINPUT_GAMEPAD_RIGHT_THUMB = 0x0080; // public static final short XINPUT_GAMEPAD_LEFT_SHOULDER = 0x0100; // public static final short XINPUT_GAMEPAD_RIGHT_SHOULDER = 0x0200; // public static final short XINPUT_GAMEPAD_GUIDE_BUTTON = 0x0400;// undocumented // public static final short XINPUT_GAMEPAD_UNKNOWN = 0x0800;// undocumented // public static final short XINPUT_GAMEPAD_A = 0x1000; // public static final short XINPUT_GAMEPAD_B = 0x2000; // public static final short XINPUT_GAMEPAD_X = 0x4000; // public static final short XINPUT_GAMEPAD_Y = (short) 0x8000; // // // Device types // public static final byte XINPUT_DEVTYPE_GAMEPAD = 0x01; // // public static final byte XINPUT_DEVSUBTYPE_UNKNOWN = 0x00; // public static final byte XINPUT_DEVSUBTYPE_GAMEPAD = 0x01; // public static final byte XINPUT_DEVSUBTYPE_WHEEL = 0x02; // public static final byte XINPUT_DEVSUBTYPE_ARCADE_STICK = 0x03; // public static final byte XINPUT_DEVSUBTYPE_FLIGHT_STICK = 0x04; // public static final byte XINPUT_DEVSUBTYPE_DANCE_PAD = 0x05; // public static final byte XINPUT_DEVSUBTYPE_GUITAR = 0x06; // public static final byte XINPUT_DEVSUBTYPE_GUITAR_ALTERNATE = 0x07; // public static final byte XINPUT_DEVSUBTYPE_DRUM_KIT = 0x08; // public static final byte XINPUT_DEVSUBTYPE_GUITAR_BASS = 0x0B; // public static final byte XINPUT_DEVSUBTYPE_ARCADE_PAD = 0x13; // // public static final byte BATTERY_DEVTYPE_GAMEPAD = 0x00; // public static final byte BATTERY_DEVTYPE_HEADSET = 0x01; // // // Capability flags // public static final byte XINPUT_CAPS_FFB_SUPPORTED = 0x0001; // public static final byte XINPUT_CAPS_WIRELESS = 0x0002; // public static final byte XINPUT_CAPS_VOICE_SUPPORTED = 0x0004; // public static final byte XINPUT_CAPS_PMD_SUPPORTED = 0x0008; // public static final byte XINPUT_CAPS_NO_NAVIGATION = 0x0010; // // // Battery types // public static final byte BATTERY_TYPE_DISCONNECTED = 0x00;// This device is not connected // public static final byte BATTERY_TYPE_WIRED = 0x01;// Wired device, no battery // public static final byte BATTERY_TYPE_ALKALINE = 0x02;// Alkaline battery source // public static final byte BATTERY_TYPE_NIMH = 0x03;// Nickel Metal Hydride battery source // public static final byte BATTERY_TYPE_UNKNOWN = (byte) 0xFF;// Cannot determine the battery type // // // Battery levels // public static final byte BATTERY_LEVEL_EMPTY = 0x00; // public static final byte BATTERY_LEVEL_LOW = 0x01; // public static final byte BATTERY_LEVEL_MEDIUM = 0x02; // public static final byte BATTERY_LEVEL_FULL = 0x03; // // // Keystroke flags // public static final short XINPUT_KEYSTROKE_KEYDOWN = 0x0001; // public static final short XINPUT_KEYSTROKE_KEYUP = 0x0002; // public static final short XINPUT_KEYSTROKE_REPEAT = 0x0004; // // // Device flags // public static final int XINPUT_FLAG_GAMEPAD = 0x00000001; // // // ------------- // // Windows // // // Error codes // public static final int ERROR_SUCCESS = 0; // public static final int ERROR_EMPTY = 4306; // public static final int ERROR_DEVICE_NOT_CONNECTED = 1167; // }
import com.github.strikerx3.jxinput.natives.XInputConstants;
package com.github.strikerx3.jxinput.enums; /** * Enumerates all XInput battery levels. * * @author Ivan "StrikerX3" Oliveira */ public enum XInputBatteryLevel { EMPTY, LOW, MEDIUM, FULL; /** * Retrieves the appropriate enum value from the native value. * * @param value the native value * @return the corresponding enum constant * @throws IllegalArgumentException if the given native value does not correspond * to an enum value */ public static XInputBatteryLevel fromNative(final byte value) { switch (value) {
// Path: src/main/java/com/github/strikerx3/jxinput/natives/XInputConstants.java // public final class XInputConstants { // private XInputConstants() {} // // // ------------- // // XInput // // public static final int MAX_PLAYERS = 4; // // // Controller button masks // public static final short XINPUT_GAMEPAD_DPAD_UP = 0x0001; // public static final short XINPUT_GAMEPAD_DPAD_DOWN = 0x0002; // public static final short XINPUT_GAMEPAD_DPAD_LEFT = 0x0004; // public static final short XINPUT_GAMEPAD_DPAD_RIGHT = 0x0008; // public static final short XINPUT_GAMEPAD_START = 0x0010; // public static final short XINPUT_GAMEPAD_BACK = 0x0020; // public static final short XINPUT_GAMEPAD_LEFT_THUMB = 0x0040; // public static final short XINPUT_GAMEPAD_RIGHT_THUMB = 0x0080; // public static final short XINPUT_GAMEPAD_LEFT_SHOULDER = 0x0100; // public static final short XINPUT_GAMEPAD_RIGHT_SHOULDER = 0x0200; // public static final short XINPUT_GAMEPAD_GUIDE_BUTTON = 0x0400;// undocumented // public static final short XINPUT_GAMEPAD_UNKNOWN = 0x0800;// undocumented // public static final short XINPUT_GAMEPAD_A = 0x1000; // public static final short XINPUT_GAMEPAD_B = 0x2000; // public static final short XINPUT_GAMEPAD_X = 0x4000; // public static final short XINPUT_GAMEPAD_Y = (short) 0x8000; // // // Device types // public static final byte XINPUT_DEVTYPE_GAMEPAD = 0x01; // // public static final byte XINPUT_DEVSUBTYPE_UNKNOWN = 0x00; // public static final byte XINPUT_DEVSUBTYPE_GAMEPAD = 0x01; // public static final byte XINPUT_DEVSUBTYPE_WHEEL = 0x02; // public static final byte XINPUT_DEVSUBTYPE_ARCADE_STICK = 0x03; // public static final byte XINPUT_DEVSUBTYPE_FLIGHT_STICK = 0x04; // public static final byte XINPUT_DEVSUBTYPE_DANCE_PAD = 0x05; // public static final byte XINPUT_DEVSUBTYPE_GUITAR = 0x06; // public static final byte XINPUT_DEVSUBTYPE_GUITAR_ALTERNATE = 0x07; // public static final byte XINPUT_DEVSUBTYPE_DRUM_KIT = 0x08; // public static final byte XINPUT_DEVSUBTYPE_GUITAR_BASS = 0x0B; // public static final byte XINPUT_DEVSUBTYPE_ARCADE_PAD = 0x13; // // public static final byte BATTERY_DEVTYPE_GAMEPAD = 0x00; // public static final byte BATTERY_DEVTYPE_HEADSET = 0x01; // // // Capability flags // public static final byte XINPUT_CAPS_FFB_SUPPORTED = 0x0001; // public static final byte XINPUT_CAPS_WIRELESS = 0x0002; // public static final byte XINPUT_CAPS_VOICE_SUPPORTED = 0x0004; // public static final byte XINPUT_CAPS_PMD_SUPPORTED = 0x0008; // public static final byte XINPUT_CAPS_NO_NAVIGATION = 0x0010; // // // Battery types // public static final byte BATTERY_TYPE_DISCONNECTED = 0x00;// This device is not connected // public static final byte BATTERY_TYPE_WIRED = 0x01;// Wired device, no battery // public static final byte BATTERY_TYPE_ALKALINE = 0x02;// Alkaline battery source // public static final byte BATTERY_TYPE_NIMH = 0x03;// Nickel Metal Hydride battery source // public static final byte BATTERY_TYPE_UNKNOWN = (byte) 0xFF;// Cannot determine the battery type // // // Battery levels // public static final byte BATTERY_LEVEL_EMPTY = 0x00; // public static final byte BATTERY_LEVEL_LOW = 0x01; // public static final byte BATTERY_LEVEL_MEDIUM = 0x02; // public static final byte BATTERY_LEVEL_FULL = 0x03; // // // Keystroke flags // public static final short XINPUT_KEYSTROKE_KEYDOWN = 0x0001; // public static final short XINPUT_KEYSTROKE_KEYUP = 0x0002; // public static final short XINPUT_KEYSTROKE_REPEAT = 0x0004; // // // Device flags // public static final int XINPUT_FLAG_GAMEPAD = 0x00000001; // // // ------------- // // Windows // // // Error codes // public static final int ERROR_SUCCESS = 0; // public static final int ERROR_EMPTY = 4306; // public static final int ERROR_DEVICE_NOT_CONNECTED = 1167; // } // Path: src/main/java/com/github/strikerx3/jxinput/enums/XInputBatteryLevel.java import com.github.strikerx3.jxinput.natives.XInputConstants; package com.github.strikerx3.jxinput.enums; /** * Enumerates all XInput battery levels. * * @author Ivan "StrikerX3" Oliveira */ public enum XInputBatteryLevel { EMPTY, LOW, MEDIUM, FULL; /** * Retrieves the appropriate enum value from the native value. * * @param value the native value * @return the corresponding enum constant * @throws IllegalArgumentException if the given native value does not correspond * to an enum value */ public static XInputBatteryLevel fromNative(final byte value) { switch (value) {
case XInputConstants.BATTERY_LEVEL_EMPTY:
StrikerX3/JXInput
src/main/java/com/github/strikerx3/jxinput/XInputBatteryInformation.java
// Path: src/main/java/com/github/strikerx3/jxinput/enums/XInputBatteryLevel.java // public enum XInputBatteryLevel { // EMPTY, LOW, MEDIUM, FULL; // // /** // * Retrieves the appropriate enum value from the native value. // * // * @param value the native value // * @return the corresponding enum constant // * @throws IllegalArgumentException if the given native value does not correspond // * to an enum value // */ // public static XInputBatteryLevel fromNative(final byte value) { // switch (value) { // case XInputConstants.BATTERY_LEVEL_EMPTY: // return EMPTY; // case XInputConstants.BATTERY_LEVEL_LOW: // return LOW; // case XInputConstants.BATTERY_LEVEL_MEDIUM: // return MEDIUM; // case XInputConstants.BATTERY_LEVEL_FULL: // return FULL; // default: // throw new IllegalArgumentException("Invalid native value " + value); // } // } // } // // Path: src/main/java/com/github/strikerx3/jxinput/enums/XInputBatteryType.java // public enum XInputBatteryType { // DISCONNECTED, WIRED, ALKALINE, NIMH, UNKNOWN; // // /** // * Retrieves the appropriate enum value from the native value. // * // * @param value the native value // * @return the corresponding enum constant // * @throws IllegalArgumentException if the given native value does not correspond // * to an enum value // */ // public static XInputBatteryType fromNative(final byte value) { // switch (value) { // case XInputConstants.BATTERY_TYPE_DISCONNECTED: // return DISCONNECTED; // case XInputConstants.BATTERY_TYPE_WIRED: // return WIRED; // case XInputConstants.BATTERY_TYPE_ALKALINE: // return ALKALINE; // case XInputConstants.BATTERY_TYPE_NIMH: // return NIMH; // case XInputConstants.BATTERY_TYPE_UNKNOWN: // return UNKNOWN; // default: // throw new IllegalArgumentException("Invalid native value " + value); // } // } // }
import java.nio.ByteBuffer; import com.github.strikerx3.jxinput.enums.XInputBatteryLevel; import com.github.strikerx3.jxinput.enums.XInputBatteryType;
package com.github.strikerx3.jxinput; /** * Contains information about the device's battery. * * @author Ivan "StrikerX3" Oliveira */ public class XInputBatteryInformation { private final XInputBatteryType type;
// Path: src/main/java/com/github/strikerx3/jxinput/enums/XInputBatteryLevel.java // public enum XInputBatteryLevel { // EMPTY, LOW, MEDIUM, FULL; // // /** // * Retrieves the appropriate enum value from the native value. // * // * @param value the native value // * @return the corresponding enum constant // * @throws IllegalArgumentException if the given native value does not correspond // * to an enum value // */ // public static XInputBatteryLevel fromNative(final byte value) { // switch (value) { // case XInputConstants.BATTERY_LEVEL_EMPTY: // return EMPTY; // case XInputConstants.BATTERY_LEVEL_LOW: // return LOW; // case XInputConstants.BATTERY_LEVEL_MEDIUM: // return MEDIUM; // case XInputConstants.BATTERY_LEVEL_FULL: // return FULL; // default: // throw new IllegalArgumentException("Invalid native value " + value); // } // } // } // // Path: src/main/java/com/github/strikerx3/jxinput/enums/XInputBatteryType.java // public enum XInputBatteryType { // DISCONNECTED, WIRED, ALKALINE, NIMH, UNKNOWN; // // /** // * Retrieves the appropriate enum value from the native value. // * // * @param value the native value // * @return the corresponding enum constant // * @throws IllegalArgumentException if the given native value does not correspond // * to an enum value // */ // public static XInputBatteryType fromNative(final byte value) { // switch (value) { // case XInputConstants.BATTERY_TYPE_DISCONNECTED: // return DISCONNECTED; // case XInputConstants.BATTERY_TYPE_WIRED: // return WIRED; // case XInputConstants.BATTERY_TYPE_ALKALINE: // return ALKALINE; // case XInputConstants.BATTERY_TYPE_NIMH: // return NIMH; // case XInputConstants.BATTERY_TYPE_UNKNOWN: // return UNKNOWN; // default: // throw new IllegalArgumentException("Invalid native value " + value); // } // } // } // Path: src/main/java/com/github/strikerx3/jxinput/XInputBatteryInformation.java import java.nio.ByteBuffer; import com.github.strikerx3.jxinput.enums.XInputBatteryLevel; import com.github.strikerx3.jxinput.enums.XInputBatteryType; package com.github.strikerx3.jxinput; /** * Contains information about the device's battery. * * @author Ivan "StrikerX3" Oliveira */ public class XInputBatteryInformation { private final XInputBatteryType type;
private final XInputBatteryLevel level;
StrikerX3/JXInput
src/main/java/com/github/strikerx3/jxinput/XInputAxes.java
// Path: src/main/java/com/github/strikerx3/jxinput/enums/XInputAxis.java // public enum XInputAxis { // LEFT_THUMBSTICK_X, LEFT_THUMBSTICK_Y, // RIGHT_THUMBSTICK_X, RIGHT_THUMBSTICK_Y, // LEFT_TRIGGER, RIGHT_TRIGGER, // DPAD; // }
import com.github.strikerx3.jxinput.enums.XInputAxis;
package com.github.strikerx3.jxinput; /** * Contains the states of all XInput axes. * * @author Ivan "StrikerX3" Oliveira */ public class XInputAxes { public int lxRaw, lyRaw; public int rxRaw, ryRaw; public int ltRaw, rtRaw; public float lx, ly; public float rx, ry; public float lt, rt; public int dpad; public static final int DPAD_CENTER = -1; public static final int DPAD_UP_LEFT = 0; public static final int DPAD_UP = 1; public static final int DPAD_UP_RIGHT = 2; public static final int DPAD_RIGHT = 3; public static final int DPAD_DOWN_RIGHT = 4; public static final int DPAD_DOWN = 5; public static final int DPAD_DOWN_LEFT = 6; public static final int DPAD_LEFT = 7; protected XInputAxes() { reset(); } /** * Gets the value from the specified axis. * * @param axis the axis * @return the value of the axis */
// Path: src/main/java/com/github/strikerx3/jxinput/enums/XInputAxis.java // public enum XInputAxis { // LEFT_THUMBSTICK_X, LEFT_THUMBSTICK_Y, // RIGHT_THUMBSTICK_X, RIGHT_THUMBSTICK_Y, // LEFT_TRIGGER, RIGHT_TRIGGER, // DPAD; // } // Path: src/main/java/com/github/strikerx3/jxinput/XInputAxes.java import com.github.strikerx3.jxinput.enums.XInputAxis; package com.github.strikerx3.jxinput; /** * Contains the states of all XInput axes. * * @author Ivan "StrikerX3" Oliveira */ public class XInputAxes { public int lxRaw, lyRaw; public int rxRaw, ryRaw; public int ltRaw, rtRaw; public float lx, ly; public float rx, ry; public float lt, rt; public int dpad; public static final int DPAD_CENTER = -1; public static final int DPAD_UP_LEFT = 0; public static final int DPAD_UP = 1; public static final int DPAD_UP_RIGHT = 2; public static final int DPAD_RIGHT = 3; public static final int DPAD_DOWN_RIGHT = 4; public static final int DPAD_DOWN = 5; public static final int DPAD_DOWN_LEFT = 6; public static final int DPAD_LEFT = 7; protected XInputAxes() { reset(); } /** * Gets the value from the specified axis. * * @param axis the axis * @return the value of the axis */
public float get(final XInputAxis axis) {
StrikerX3/JXInput
src/main/java/com/github/strikerx3/jxinput/XInputButtonsDelta.java
// Path: src/main/java/com/github/strikerx3/jxinput/enums/XInputButton.java // public enum XInputButton { // A, B, X, Y, // BACK, START, // LEFT_SHOULDER, RIGHT_SHOULDER, // LEFT_THUMBSTICK, RIGHT_THUMBSTICK, // DPAD_UP, DPAD_DOWN, DPAD_LEFT, DPAD_RIGHT, // GUIDE_BUTTON, UNKNOWN; // }
import com.github.strikerx3.jxinput.enums.XInputButton;
package com.github.strikerx3.jxinput; /** * Represents the delta (change) of the buttons between two successive polls. * * @author Ivan "StrikerX3" Oliveira */ public class XInputButtonsDelta { private final XInputButtons lastButtons; private final XInputButtons buttons; protected XInputButtonsDelta(final XInputButtons lastButtons, final XInputButtons buttons) { this.lastButtons = lastButtons; this.buttons = buttons; } /** * Returns <code>true</code> if the button was pressed (i.e. changed from released to pressed between two consecutive polls). * * @param button the button * @return <code>true</code> if the button was pressed, <code>false</code> otherwise */
// Path: src/main/java/com/github/strikerx3/jxinput/enums/XInputButton.java // public enum XInputButton { // A, B, X, Y, // BACK, START, // LEFT_SHOULDER, RIGHT_SHOULDER, // LEFT_THUMBSTICK, RIGHT_THUMBSTICK, // DPAD_UP, DPAD_DOWN, DPAD_LEFT, DPAD_RIGHT, // GUIDE_BUTTON, UNKNOWN; // } // Path: src/main/java/com/github/strikerx3/jxinput/XInputButtonsDelta.java import com.github.strikerx3.jxinput.enums.XInputButton; package com.github.strikerx3.jxinput; /** * Represents the delta (change) of the buttons between two successive polls. * * @author Ivan "StrikerX3" Oliveira */ public class XInputButtonsDelta { private final XInputButtons lastButtons; private final XInputButtons buttons; protected XInputButtonsDelta(final XInputButtons lastButtons, final XInputButtons buttons) { this.lastButtons = lastButtons; this.buttons = buttons; } /** * Returns <code>true</code> if the button was pressed (i.e. changed from released to pressed between two consecutive polls). * * @param button the button * @return <code>true</code> if the button was pressed, <code>false</code> otherwise */
public boolean isPressed(final XInputButton button) {
StrikerX3/JXInput
src/main/java/com/github/strikerx3/jxinput/enums/XInputBatteryType.java
// Path: src/main/java/com/github/strikerx3/jxinput/natives/XInputConstants.java // public final class XInputConstants { // private XInputConstants() {} // // // ------------- // // XInput // // public static final int MAX_PLAYERS = 4; // // // Controller button masks // public static final short XINPUT_GAMEPAD_DPAD_UP = 0x0001; // public static final short XINPUT_GAMEPAD_DPAD_DOWN = 0x0002; // public static final short XINPUT_GAMEPAD_DPAD_LEFT = 0x0004; // public static final short XINPUT_GAMEPAD_DPAD_RIGHT = 0x0008; // public static final short XINPUT_GAMEPAD_START = 0x0010; // public static final short XINPUT_GAMEPAD_BACK = 0x0020; // public static final short XINPUT_GAMEPAD_LEFT_THUMB = 0x0040; // public static final short XINPUT_GAMEPAD_RIGHT_THUMB = 0x0080; // public static final short XINPUT_GAMEPAD_LEFT_SHOULDER = 0x0100; // public static final short XINPUT_GAMEPAD_RIGHT_SHOULDER = 0x0200; // public static final short XINPUT_GAMEPAD_GUIDE_BUTTON = 0x0400;// undocumented // public static final short XINPUT_GAMEPAD_UNKNOWN = 0x0800;// undocumented // public static final short XINPUT_GAMEPAD_A = 0x1000; // public static final short XINPUT_GAMEPAD_B = 0x2000; // public static final short XINPUT_GAMEPAD_X = 0x4000; // public static final short XINPUT_GAMEPAD_Y = (short) 0x8000; // // // Device types // public static final byte XINPUT_DEVTYPE_GAMEPAD = 0x01; // // public static final byte XINPUT_DEVSUBTYPE_UNKNOWN = 0x00; // public static final byte XINPUT_DEVSUBTYPE_GAMEPAD = 0x01; // public static final byte XINPUT_DEVSUBTYPE_WHEEL = 0x02; // public static final byte XINPUT_DEVSUBTYPE_ARCADE_STICK = 0x03; // public static final byte XINPUT_DEVSUBTYPE_FLIGHT_STICK = 0x04; // public static final byte XINPUT_DEVSUBTYPE_DANCE_PAD = 0x05; // public static final byte XINPUT_DEVSUBTYPE_GUITAR = 0x06; // public static final byte XINPUT_DEVSUBTYPE_GUITAR_ALTERNATE = 0x07; // public static final byte XINPUT_DEVSUBTYPE_DRUM_KIT = 0x08; // public static final byte XINPUT_DEVSUBTYPE_GUITAR_BASS = 0x0B; // public static final byte XINPUT_DEVSUBTYPE_ARCADE_PAD = 0x13; // // public static final byte BATTERY_DEVTYPE_GAMEPAD = 0x00; // public static final byte BATTERY_DEVTYPE_HEADSET = 0x01; // // // Capability flags // public static final byte XINPUT_CAPS_FFB_SUPPORTED = 0x0001; // public static final byte XINPUT_CAPS_WIRELESS = 0x0002; // public static final byte XINPUT_CAPS_VOICE_SUPPORTED = 0x0004; // public static final byte XINPUT_CAPS_PMD_SUPPORTED = 0x0008; // public static final byte XINPUT_CAPS_NO_NAVIGATION = 0x0010; // // // Battery types // public static final byte BATTERY_TYPE_DISCONNECTED = 0x00;// This device is not connected // public static final byte BATTERY_TYPE_WIRED = 0x01;// Wired device, no battery // public static final byte BATTERY_TYPE_ALKALINE = 0x02;// Alkaline battery source // public static final byte BATTERY_TYPE_NIMH = 0x03;// Nickel Metal Hydride battery source // public static final byte BATTERY_TYPE_UNKNOWN = (byte) 0xFF;// Cannot determine the battery type // // // Battery levels // public static final byte BATTERY_LEVEL_EMPTY = 0x00; // public static final byte BATTERY_LEVEL_LOW = 0x01; // public static final byte BATTERY_LEVEL_MEDIUM = 0x02; // public static final byte BATTERY_LEVEL_FULL = 0x03; // // // Keystroke flags // public static final short XINPUT_KEYSTROKE_KEYDOWN = 0x0001; // public static final short XINPUT_KEYSTROKE_KEYUP = 0x0002; // public static final short XINPUT_KEYSTROKE_REPEAT = 0x0004; // // // Device flags // public static final int XINPUT_FLAG_GAMEPAD = 0x00000001; // // // ------------- // // Windows // // // Error codes // public static final int ERROR_SUCCESS = 0; // public static final int ERROR_EMPTY = 4306; // public static final int ERROR_DEVICE_NOT_CONNECTED = 1167; // }
import com.github.strikerx3.jxinput.natives.XInputConstants;
package com.github.strikerx3.jxinput.enums; /** * Enumerates all XInput battery types. * * @author Ivan "StrikerX3" Oliveira */ public enum XInputBatteryType { DISCONNECTED, WIRED, ALKALINE, NIMH, UNKNOWN; /** * Retrieves the appropriate enum value from the native value. * * @param value the native value * @return the corresponding enum constant * @throws IllegalArgumentException if the given native value does not correspond * to an enum value */ public static XInputBatteryType fromNative(final byte value) { switch (value) {
// Path: src/main/java/com/github/strikerx3/jxinput/natives/XInputConstants.java // public final class XInputConstants { // private XInputConstants() {} // // // ------------- // // XInput // // public static final int MAX_PLAYERS = 4; // // // Controller button masks // public static final short XINPUT_GAMEPAD_DPAD_UP = 0x0001; // public static final short XINPUT_GAMEPAD_DPAD_DOWN = 0x0002; // public static final short XINPUT_GAMEPAD_DPAD_LEFT = 0x0004; // public static final short XINPUT_GAMEPAD_DPAD_RIGHT = 0x0008; // public static final short XINPUT_GAMEPAD_START = 0x0010; // public static final short XINPUT_GAMEPAD_BACK = 0x0020; // public static final short XINPUT_GAMEPAD_LEFT_THUMB = 0x0040; // public static final short XINPUT_GAMEPAD_RIGHT_THUMB = 0x0080; // public static final short XINPUT_GAMEPAD_LEFT_SHOULDER = 0x0100; // public static final short XINPUT_GAMEPAD_RIGHT_SHOULDER = 0x0200; // public static final short XINPUT_GAMEPAD_GUIDE_BUTTON = 0x0400;// undocumented // public static final short XINPUT_GAMEPAD_UNKNOWN = 0x0800;// undocumented // public static final short XINPUT_GAMEPAD_A = 0x1000; // public static final short XINPUT_GAMEPAD_B = 0x2000; // public static final short XINPUT_GAMEPAD_X = 0x4000; // public static final short XINPUT_GAMEPAD_Y = (short) 0x8000; // // // Device types // public static final byte XINPUT_DEVTYPE_GAMEPAD = 0x01; // // public static final byte XINPUT_DEVSUBTYPE_UNKNOWN = 0x00; // public static final byte XINPUT_DEVSUBTYPE_GAMEPAD = 0x01; // public static final byte XINPUT_DEVSUBTYPE_WHEEL = 0x02; // public static final byte XINPUT_DEVSUBTYPE_ARCADE_STICK = 0x03; // public static final byte XINPUT_DEVSUBTYPE_FLIGHT_STICK = 0x04; // public static final byte XINPUT_DEVSUBTYPE_DANCE_PAD = 0x05; // public static final byte XINPUT_DEVSUBTYPE_GUITAR = 0x06; // public static final byte XINPUT_DEVSUBTYPE_GUITAR_ALTERNATE = 0x07; // public static final byte XINPUT_DEVSUBTYPE_DRUM_KIT = 0x08; // public static final byte XINPUT_DEVSUBTYPE_GUITAR_BASS = 0x0B; // public static final byte XINPUT_DEVSUBTYPE_ARCADE_PAD = 0x13; // // public static final byte BATTERY_DEVTYPE_GAMEPAD = 0x00; // public static final byte BATTERY_DEVTYPE_HEADSET = 0x01; // // // Capability flags // public static final byte XINPUT_CAPS_FFB_SUPPORTED = 0x0001; // public static final byte XINPUT_CAPS_WIRELESS = 0x0002; // public static final byte XINPUT_CAPS_VOICE_SUPPORTED = 0x0004; // public static final byte XINPUT_CAPS_PMD_SUPPORTED = 0x0008; // public static final byte XINPUT_CAPS_NO_NAVIGATION = 0x0010; // // // Battery types // public static final byte BATTERY_TYPE_DISCONNECTED = 0x00;// This device is not connected // public static final byte BATTERY_TYPE_WIRED = 0x01;// Wired device, no battery // public static final byte BATTERY_TYPE_ALKALINE = 0x02;// Alkaline battery source // public static final byte BATTERY_TYPE_NIMH = 0x03;// Nickel Metal Hydride battery source // public static final byte BATTERY_TYPE_UNKNOWN = (byte) 0xFF;// Cannot determine the battery type // // // Battery levels // public static final byte BATTERY_LEVEL_EMPTY = 0x00; // public static final byte BATTERY_LEVEL_LOW = 0x01; // public static final byte BATTERY_LEVEL_MEDIUM = 0x02; // public static final byte BATTERY_LEVEL_FULL = 0x03; // // // Keystroke flags // public static final short XINPUT_KEYSTROKE_KEYDOWN = 0x0001; // public static final short XINPUT_KEYSTROKE_KEYUP = 0x0002; // public static final short XINPUT_KEYSTROKE_REPEAT = 0x0004; // // // Device flags // public static final int XINPUT_FLAG_GAMEPAD = 0x00000001; // // // ------------- // // Windows // // // Error codes // public static final int ERROR_SUCCESS = 0; // public static final int ERROR_EMPTY = 4306; // public static final int ERROR_DEVICE_NOT_CONNECTED = 1167; // } // Path: src/main/java/com/github/strikerx3/jxinput/enums/XInputBatteryType.java import com.github.strikerx3.jxinput.natives.XInputConstants; package com.github.strikerx3.jxinput.enums; /** * Enumerates all XInput battery types. * * @author Ivan "StrikerX3" Oliveira */ public enum XInputBatteryType { DISCONNECTED, WIRED, ALKALINE, NIMH, UNKNOWN; /** * Retrieves the appropriate enum value from the native value. * * @param value the native value * @return the corresponding enum constant * @throws IllegalArgumentException if the given native value does not correspond * to an enum value */ public static XInputBatteryType fromNative(final byte value) { switch (value) {
case XInputConstants.BATTERY_TYPE_DISCONNECTED:
commonsguy/cwac-netsecurity
netsecurity/src/main/java/com/commonsware/cwac/netsecurity/config/DirectoryCertificateSource.java
// Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/conscrypt/Hex.java // public class Hex { // private Hex() {} // // private final static char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; // // public static String bytesToHexString(byte[] bytes) { // char[] buf = new char[bytes.length * 2]; // int c = 0; // for (byte b : bytes) { // buf[c++] = DIGITS[(b >> 4) & 0xf]; // buf[c++] = DIGITS[b & 0xf]; // } // return new String(buf); // } // // public static String intToHexString(int i, int minWidth) { // int bufLen = 8; // Max number of hex digits in an int // char[] buf = new char[bufLen]; // int cursor = bufLen; // // do { // buf[--cursor] = DIGITS[i & 0xf]; // } while ((i >>>= 4) != 0 || (bufLen - cursor < minWidth)); // // return new String(buf, cursor, bufLen - cursor); // } // // }
import java.util.Collections; import java.util.HashSet; import java.util.Set; import javax.security.auth.x500.X500Principal; import com.commonsware.cwac.netsecurity.conscrypt.Hex; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate;
} certs.add(cert); } } return certs != null ? certs : Collections.<X509Certificate>emptySet(); } private X509Certificate findCert(X500Principal subj, CertSelector selector) { String hash = getHash(subj); for (int index = 0; index >= 0; index++) { String fileName = hash + "." + index; if (!new File(mDir, fileName).exists()) { break; } if (isCertMarkedAsRemoved(fileName)) { continue; } X509Certificate cert = readCertificate(fileName); if (!subj.equals(cert.getSubjectX500Principal())) { continue; } if (selector.match(cert)) { return cert; } } return null; } private String getHash(X500Principal name) { int hash = /* NativeCrypto. */X509_NAME_hash_old(name);
// Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/conscrypt/Hex.java // public class Hex { // private Hex() {} // // private final static char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; // // public static String bytesToHexString(byte[] bytes) { // char[] buf = new char[bytes.length * 2]; // int c = 0; // for (byte b : bytes) { // buf[c++] = DIGITS[(b >> 4) & 0xf]; // buf[c++] = DIGITS[b & 0xf]; // } // return new String(buf); // } // // public static String intToHexString(int i, int minWidth) { // int bufLen = 8; // Max number of hex digits in an int // char[] buf = new char[bufLen]; // int cursor = bufLen; // // do { // buf[--cursor] = DIGITS[i & 0xf]; // } while ((i >>>= 4) != 0 || (bufLen - cursor < minWidth)); // // return new String(buf, cursor, bufLen - cursor); // } // // } // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/config/DirectoryCertificateSource.java import java.util.Collections; import java.util.HashSet; import java.util.Set; import javax.security.auth.x500.X500Principal; import com.commonsware.cwac.netsecurity.conscrypt.Hex; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; } certs.add(cert); } } return certs != null ? certs : Collections.<X509Certificate>emptySet(); } private X509Certificate findCert(X500Principal subj, CertSelector selector) { String hash = getHash(subj); for (int index = 0; index >= 0; index++) { String fileName = hash + "." + index; if (!new File(mDir, fileName).exists()) { break; } if (isCertMarkedAsRemoved(fileName)) { continue; } X509Certificate cert = readCertificate(fileName); if (!subj.equals(cert.getSubjectX500Principal())) { continue; } if (selector.match(cert)) { return cert; } } return null; } private String getHash(X500Principal name) { int hash = /* NativeCrypto. */X509_NAME_hash_old(name);
return Hex.intToHexString(hash, 8);
commonsguy/cwac-netsecurity
netsecurity/src/test/java/com/commonsware/cwac/netsecurity/test/DomainMatchRuleTests.java
// Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule allOf(DomainMatchRule... rules) { // return(new Composite(false, rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule anyOf(DomainMatchRule... rules) { // return(new Composite(true, rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule blacklist(String... globs) { // List<DomainMatchRule> rules=new ArrayList<>(); // // for (String glob : globs) { // rules.add(not(is(glob))); // } // // return(allOf(rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule is(Pattern pattern) { // return(new Regex(pattern)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule not(DomainMatchRule rule) { // return(new Not(rule)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule whitelist(String... globs) { // List<DomainMatchRule> rules=new ArrayList<>(); // // for (String glob : globs) { // rules.add(is(glob)); // } // // return(anyOf(rules)); // }
import org.junit.Test; import java.util.regex.Pattern; import static com.commonsware.cwac.netsecurity.DomainMatchRule.allOf; import static com.commonsware.cwac.netsecurity.DomainMatchRule.anyOf; import static com.commonsware.cwac.netsecurity.DomainMatchRule.blacklist; import static com.commonsware.cwac.netsecurity.DomainMatchRule.is; import static com.commonsware.cwac.netsecurity.DomainMatchRule.not; import static com.commonsware.cwac.netsecurity.DomainMatchRule.whitelist; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue;
/*** Copyright (c) 2017 CommonsWare, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License _is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.commonsware.cwac.netsecurity.test; public class DomainMatchRuleTests { @Test public void _is() {
// Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule allOf(DomainMatchRule... rules) { // return(new Composite(false, rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule anyOf(DomainMatchRule... rules) { // return(new Composite(true, rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule blacklist(String... globs) { // List<DomainMatchRule> rules=new ArrayList<>(); // // for (String glob : globs) { // rules.add(not(is(glob))); // } // // return(allOf(rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule is(Pattern pattern) { // return(new Regex(pattern)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule not(DomainMatchRule rule) { // return(new Not(rule)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule whitelist(String... globs) { // List<DomainMatchRule> rules=new ArrayList<>(); // // for (String glob : globs) { // rules.add(is(glob)); // } // // return(anyOf(rules)); // } // Path: netsecurity/src/test/java/com/commonsware/cwac/netsecurity/test/DomainMatchRuleTests.java import org.junit.Test; import java.util.regex.Pattern; import static com.commonsware.cwac.netsecurity.DomainMatchRule.allOf; import static com.commonsware.cwac.netsecurity.DomainMatchRule.anyOf; import static com.commonsware.cwac.netsecurity.DomainMatchRule.blacklist; import static com.commonsware.cwac.netsecurity.DomainMatchRule.is; import static com.commonsware.cwac.netsecurity.DomainMatchRule.not; import static com.commonsware.cwac.netsecurity.DomainMatchRule.whitelist; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /*** Copyright (c) 2017 CommonsWare, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License _is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.commonsware.cwac.netsecurity.test; public class DomainMatchRuleTests { @Test public void _is() {
assertTrue(is("foo.com").matches("foo.com"));
commonsguy/cwac-netsecurity
netsecurity/src/test/java/com/commonsware/cwac/netsecurity/test/DomainMatchRuleTests.java
// Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule allOf(DomainMatchRule... rules) { // return(new Composite(false, rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule anyOf(DomainMatchRule... rules) { // return(new Composite(true, rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule blacklist(String... globs) { // List<DomainMatchRule> rules=new ArrayList<>(); // // for (String glob : globs) { // rules.add(not(is(glob))); // } // // return(allOf(rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule is(Pattern pattern) { // return(new Regex(pattern)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule not(DomainMatchRule rule) { // return(new Not(rule)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule whitelist(String... globs) { // List<DomainMatchRule> rules=new ArrayList<>(); // // for (String glob : globs) { // rules.add(is(glob)); // } // // return(anyOf(rules)); // }
import org.junit.Test; import java.util.regex.Pattern; import static com.commonsware.cwac.netsecurity.DomainMatchRule.allOf; import static com.commonsware.cwac.netsecurity.DomainMatchRule.anyOf; import static com.commonsware.cwac.netsecurity.DomainMatchRule.blacklist; import static com.commonsware.cwac.netsecurity.DomainMatchRule.is; import static com.commonsware.cwac.netsecurity.DomainMatchRule.not; import static com.commonsware.cwac.netsecurity.DomainMatchRule.whitelist; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue;
/*** Copyright (c) 2017 CommonsWare, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License _is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.commonsware.cwac.netsecurity.test; public class DomainMatchRuleTests { @Test public void _is() { assertTrue(is("foo.com").matches("foo.com")); assertFalse(is("*.foo.com").matches("foo.com")); assertTrue(is("*.foo.com").matches("www.foo.com")); assertTrue(is("*.foo.com").matches("www.bar.foo.com")); assertTrue(is(Pattern.compile("[a-z]+\\.com")).matches("foo.com")); assertFalse(is(Pattern.compile("[a-z]+\\.com")).matches("www.foo.com")); } @Test public void _not() {
// Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule allOf(DomainMatchRule... rules) { // return(new Composite(false, rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule anyOf(DomainMatchRule... rules) { // return(new Composite(true, rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule blacklist(String... globs) { // List<DomainMatchRule> rules=new ArrayList<>(); // // for (String glob : globs) { // rules.add(not(is(glob))); // } // // return(allOf(rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule is(Pattern pattern) { // return(new Regex(pattern)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule not(DomainMatchRule rule) { // return(new Not(rule)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule whitelist(String... globs) { // List<DomainMatchRule> rules=new ArrayList<>(); // // for (String glob : globs) { // rules.add(is(glob)); // } // // return(anyOf(rules)); // } // Path: netsecurity/src/test/java/com/commonsware/cwac/netsecurity/test/DomainMatchRuleTests.java import org.junit.Test; import java.util.regex.Pattern; import static com.commonsware.cwac.netsecurity.DomainMatchRule.allOf; import static com.commonsware.cwac.netsecurity.DomainMatchRule.anyOf; import static com.commonsware.cwac.netsecurity.DomainMatchRule.blacklist; import static com.commonsware.cwac.netsecurity.DomainMatchRule.is; import static com.commonsware.cwac.netsecurity.DomainMatchRule.not; import static com.commonsware.cwac.netsecurity.DomainMatchRule.whitelist; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /*** Copyright (c) 2017 CommonsWare, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License _is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.commonsware.cwac.netsecurity.test; public class DomainMatchRuleTests { @Test public void _is() { assertTrue(is("foo.com").matches("foo.com")); assertFalse(is("*.foo.com").matches("foo.com")); assertTrue(is("*.foo.com").matches("www.foo.com")); assertTrue(is("*.foo.com").matches("www.bar.foo.com")); assertTrue(is(Pattern.compile("[a-z]+\\.com")).matches("foo.com")); assertFalse(is(Pattern.compile("[a-z]+\\.com")).matches("www.foo.com")); } @Test public void _not() {
assertFalse(not(is("foo.com")).matches("foo.com"));
commonsguy/cwac-netsecurity
netsecurity/src/test/java/com/commonsware/cwac/netsecurity/test/DomainMatchRuleTests.java
// Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule allOf(DomainMatchRule... rules) { // return(new Composite(false, rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule anyOf(DomainMatchRule... rules) { // return(new Composite(true, rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule blacklist(String... globs) { // List<DomainMatchRule> rules=new ArrayList<>(); // // for (String glob : globs) { // rules.add(not(is(glob))); // } // // return(allOf(rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule is(Pattern pattern) { // return(new Regex(pattern)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule not(DomainMatchRule rule) { // return(new Not(rule)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule whitelist(String... globs) { // List<DomainMatchRule> rules=new ArrayList<>(); // // for (String glob : globs) { // rules.add(is(glob)); // } // // return(anyOf(rules)); // }
import org.junit.Test; import java.util.regex.Pattern; import static com.commonsware.cwac.netsecurity.DomainMatchRule.allOf; import static com.commonsware.cwac.netsecurity.DomainMatchRule.anyOf; import static com.commonsware.cwac.netsecurity.DomainMatchRule.blacklist; import static com.commonsware.cwac.netsecurity.DomainMatchRule.is; import static com.commonsware.cwac.netsecurity.DomainMatchRule.not; import static com.commonsware.cwac.netsecurity.DomainMatchRule.whitelist; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue;
/*** Copyright (c) 2017 CommonsWare, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License _is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.commonsware.cwac.netsecurity.test; public class DomainMatchRuleTests { @Test public void _is() { assertTrue(is("foo.com").matches("foo.com")); assertFalse(is("*.foo.com").matches("foo.com")); assertTrue(is("*.foo.com").matches("www.foo.com")); assertTrue(is("*.foo.com").matches("www.bar.foo.com")); assertTrue(is(Pattern.compile("[a-z]+\\.com")).matches("foo.com")); assertFalse(is(Pattern.compile("[a-z]+\\.com")).matches("www.foo.com")); } @Test public void _not() { assertFalse(not(is("foo.com")).matches("foo.com")); assertTrue(not(is("*.foo.com")).matches("foo.com")); assertFalse(not(is("*.foo.com")).matches("www.foo.com")); assertFalse(not(is(Pattern.compile("[a-z]+\\.com"))).matches("foo.com")); assertTrue(not(is(Pattern.compile("[a-z]+\\.com"))).matches("www.foo.com")); } @Test public void _anyOf() {
// Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule allOf(DomainMatchRule... rules) { // return(new Composite(false, rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule anyOf(DomainMatchRule... rules) { // return(new Composite(true, rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule blacklist(String... globs) { // List<DomainMatchRule> rules=new ArrayList<>(); // // for (String glob : globs) { // rules.add(not(is(glob))); // } // // return(allOf(rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule is(Pattern pattern) { // return(new Regex(pattern)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule not(DomainMatchRule rule) { // return(new Not(rule)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule whitelist(String... globs) { // List<DomainMatchRule> rules=new ArrayList<>(); // // for (String glob : globs) { // rules.add(is(glob)); // } // // return(anyOf(rules)); // } // Path: netsecurity/src/test/java/com/commonsware/cwac/netsecurity/test/DomainMatchRuleTests.java import org.junit.Test; import java.util.regex.Pattern; import static com.commonsware.cwac.netsecurity.DomainMatchRule.allOf; import static com.commonsware.cwac.netsecurity.DomainMatchRule.anyOf; import static com.commonsware.cwac.netsecurity.DomainMatchRule.blacklist; import static com.commonsware.cwac.netsecurity.DomainMatchRule.is; import static com.commonsware.cwac.netsecurity.DomainMatchRule.not; import static com.commonsware.cwac.netsecurity.DomainMatchRule.whitelist; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /*** Copyright (c) 2017 CommonsWare, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License _is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.commonsware.cwac.netsecurity.test; public class DomainMatchRuleTests { @Test public void _is() { assertTrue(is("foo.com").matches("foo.com")); assertFalse(is("*.foo.com").matches("foo.com")); assertTrue(is("*.foo.com").matches("www.foo.com")); assertTrue(is("*.foo.com").matches("www.bar.foo.com")); assertTrue(is(Pattern.compile("[a-z]+\\.com")).matches("foo.com")); assertFalse(is(Pattern.compile("[a-z]+\\.com")).matches("www.foo.com")); } @Test public void _not() { assertFalse(not(is("foo.com")).matches("foo.com")); assertTrue(not(is("*.foo.com")).matches("foo.com")); assertFalse(not(is("*.foo.com")).matches("www.foo.com")); assertFalse(not(is(Pattern.compile("[a-z]+\\.com"))).matches("foo.com")); assertTrue(not(is(Pattern.compile("[a-z]+\\.com"))).matches("www.foo.com")); } @Test public void _anyOf() {
assertTrue(anyOf(is("foo.com")).matches("foo.com"));
commonsguy/cwac-netsecurity
netsecurity/src/test/java/com/commonsware/cwac/netsecurity/test/DomainMatchRuleTests.java
// Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule allOf(DomainMatchRule... rules) { // return(new Composite(false, rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule anyOf(DomainMatchRule... rules) { // return(new Composite(true, rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule blacklist(String... globs) { // List<DomainMatchRule> rules=new ArrayList<>(); // // for (String glob : globs) { // rules.add(not(is(glob))); // } // // return(allOf(rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule is(Pattern pattern) { // return(new Regex(pattern)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule not(DomainMatchRule rule) { // return(new Not(rule)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule whitelist(String... globs) { // List<DomainMatchRule> rules=new ArrayList<>(); // // for (String glob : globs) { // rules.add(is(glob)); // } // // return(anyOf(rules)); // }
import org.junit.Test; import java.util.regex.Pattern; import static com.commonsware.cwac.netsecurity.DomainMatchRule.allOf; import static com.commonsware.cwac.netsecurity.DomainMatchRule.anyOf; import static com.commonsware.cwac.netsecurity.DomainMatchRule.blacklist; import static com.commonsware.cwac.netsecurity.DomainMatchRule.is; import static com.commonsware.cwac.netsecurity.DomainMatchRule.not; import static com.commonsware.cwac.netsecurity.DomainMatchRule.whitelist; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue;
assertTrue(is(Pattern.compile("[a-z]+\\.com")).matches("foo.com")); assertFalse(is(Pattern.compile("[a-z]+\\.com")).matches("www.foo.com")); } @Test public void _not() { assertFalse(not(is("foo.com")).matches("foo.com")); assertTrue(not(is("*.foo.com")).matches("foo.com")); assertFalse(not(is("*.foo.com")).matches("www.foo.com")); assertFalse(not(is(Pattern.compile("[a-z]+\\.com"))).matches("foo.com")); assertTrue(not(is(Pattern.compile("[a-z]+\\.com"))).matches("www.foo.com")); } @Test public void _anyOf() { assertTrue(anyOf(is("foo.com")).matches("foo.com")); assertFalse(anyOf(is("*.foo.com")).matches("foo.com")); assertTrue(anyOf(is("*.foo.com")).matches("www.foo.com")); assertTrue(anyOf(is("foo.com"), is("bar.com")).matches("foo.com")); assertFalse(anyOf(is("*.foo.com"), is("bar.com")).matches("foo.com")); assertTrue(anyOf(is("*.foo.com"), is("bar.com")).matches("www.foo.com")); assertTrue(anyOf(is("goo.com"), is("foo.com"), is("bar.com")).matches("foo.com")); assertFalse(anyOf(is("goo.com"), is("*.foo.com"), is("bar.com")).matches("foo.com")); assertTrue(anyOf(is("goo.com"), is("*.foo.com"), is("bar.com")).matches("www.foo.com")); } @Test public void _allOf() {
// Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule allOf(DomainMatchRule... rules) { // return(new Composite(false, rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule anyOf(DomainMatchRule... rules) { // return(new Composite(true, rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule blacklist(String... globs) { // List<DomainMatchRule> rules=new ArrayList<>(); // // for (String glob : globs) { // rules.add(not(is(glob))); // } // // return(allOf(rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule is(Pattern pattern) { // return(new Regex(pattern)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule not(DomainMatchRule rule) { // return(new Not(rule)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule whitelist(String... globs) { // List<DomainMatchRule> rules=new ArrayList<>(); // // for (String glob : globs) { // rules.add(is(glob)); // } // // return(anyOf(rules)); // } // Path: netsecurity/src/test/java/com/commonsware/cwac/netsecurity/test/DomainMatchRuleTests.java import org.junit.Test; import java.util.regex.Pattern; import static com.commonsware.cwac.netsecurity.DomainMatchRule.allOf; import static com.commonsware.cwac.netsecurity.DomainMatchRule.anyOf; import static com.commonsware.cwac.netsecurity.DomainMatchRule.blacklist; import static com.commonsware.cwac.netsecurity.DomainMatchRule.is; import static com.commonsware.cwac.netsecurity.DomainMatchRule.not; import static com.commonsware.cwac.netsecurity.DomainMatchRule.whitelist; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; assertTrue(is(Pattern.compile("[a-z]+\\.com")).matches("foo.com")); assertFalse(is(Pattern.compile("[a-z]+\\.com")).matches("www.foo.com")); } @Test public void _not() { assertFalse(not(is("foo.com")).matches("foo.com")); assertTrue(not(is("*.foo.com")).matches("foo.com")); assertFalse(not(is("*.foo.com")).matches("www.foo.com")); assertFalse(not(is(Pattern.compile("[a-z]+\\.com"))).matches("foo.com")); assertTrue(not(is(Pattern.compile("[a-z]+\\.com"))).matches("www.foo.com")); } @Test public void _anyOf() { assertTrue(anyOf(is("foo.com")).matches("foo.com")); assertFalse(anyOf(is("*.foo.com")).matches("foo.com")); assertTrue(anyOf(is("*.foo.com")).matches("www.foo.com")); assertTrue(anyOf(is("foo.com"), is("bar.com")).matches("foo.com")); assertFalse(anyOf(is("*.foo.com"), is("bar.com")).matches("foo.com")); assertTrue(anyOf(is("*.foo.com"), is("bar.com")).matches("www.foo.com")); assertTrue(anyOf(is("goo.com"), is("foo.com"), is("bar.com")).matches("foo.com")); assertFalse(anyOf(is("goo.com"), is("*.foo.com"), is("bar.com")).matches("foo.com")); assertTrue(anyOf(is("goo.com"), is("*.foo.com"), is("bar.com")).matches("www.foo.com")); } @Test public void _allOf() {
assertTrue(allOf(is("foo.com")).matches("foo.com"));
commonsguy/cwac-netsecurity
netsecurity/src/test/java/com/commonsware/cwac/netsecurity/test/DomainMatchRuleTests.java
// Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule allOf(DomainMatchRule... rules) { // return(new Composite(false, rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule anyOf(DomainMatchRule... rules) { // return(new Composite(true, rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule blacklist(String... globs) { // List<DomainMatchRule> rules=new ArrayList<>(); // // for (String glob : globs) { // rules.add(not(is(glob))); // } // // return(allOf(rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule is(Pattern pattern) { // return(new Regex(pattern)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule not(DomainMatchRule rule) { // return(new Not(rule)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule whitelist(String... globs) { // List<DomainMatchRule> rules=new ArrayList<>(); // // for (String glob : globs) { // rules.add(is(glob)); // } // // return(anyOf(rules)); // }
import org.junit.Test; import java.util.regex.Pattern; import static com.commonsware.cwac.netsecurity.DomainMatchRule.allOf; import static com.commonsware.cwac.netsecurity.DomainMatchRule.anyOf; import static com.commonsware.cwac.netsecurity.DomainMatchRule.blacklist; import static com.commonsware.cwac.netsecurity.DomainMatchRule.is; import static com.commonsware.cwac.netsecurity.DomainMatchRule.not; import static com.commonsware.cwac.netsecurity.DomainMatchRule.whitelist; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue;
assertTrue(anyOf(is("foo.com")).matches("foo.com")); assertFalse(anyOf(is("*.foo.com")).matches("foo.com")); assertTrue(anyOf(is("*.foo.com")).matches("www.foo.com")); assertTrue(anyOf(is("foo.com"), is("bar.com")).matches("foo.com")); assertFalse(anyOf(is("*.foo.com"), is("bar.com")).matches("foo.com")); assertTrue(anyOf(is("*.foo.com"), is("bar.com")).matches("www.foo.com")); assertTrue(anyOf(is("goo.com"), is("foo.com"), is("bar.com")).matches("foo.com")); assertFalse(anyOf(is("goo.com"), is("*.foo.com"), is("bar.com")).matches("foo.com")); assertTrue(anyOf(is("goo.com"), is("*.foo.com"), is("bar.com")).matches("www.foo.com")); } @Test public void _allOf() { assertTrue(allOf(is("foo.com")).matches("foo.com")); assertFalse(allOf(is("*.foo.com")).matches("foo.com")); assertTrue(allOf(is("*.foo.com")).matches("www.foo.com")); assertFalse(allOf(is("foo.com"), is("bar.com")).matches("foo.com")); assertFalse(allOf(is("*.foo.com"), is("bar.com")).matches("foo.com")); assertFalse(allOf(is("*.foo.com"), is("bar.com")).matches("www.foo.com")); assertFalse(allOf(is("goo.com"), is("foo.com"), is("bar.com")).matches("foo.com")); assertFalse(allOf(is("goo.com"), is("*.foo.com"), is("bar.com")).matches("foo.com")); assertFalse(allOf(is("goo.com"), is("*.foo.com"), is("bar.com")).matches("www.foo.com")); } @Test public void _whitelist() {
// Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule allOf(DomainMatchRule... rules) { // return(new Composite(false, rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule anyOf(DomainMatchRule... rules) { // return(new Composite(true, rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule blacklist(String... globs) { // List<DomainMatchRule> rules=new ArrayList<>(); // // for (String glob : globs) { // rules.add(not(is(glob))); // } // // return(allOf(rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule is(Pattern pattern) { // return(new Regex(pattern)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule not(DomainMatchRule rule) { // return(new Not(rule)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule whitelist(String... globs) { // List<DomainMatchRule> rules=new ArrayList<>(); // // for (String glob : globs) { // rules.add(is(glob)); // } // // return(anyOf(rules)); // } // Path: netsecurity/src/test/java/com/commonsware/cwac/netsecurity/test/DomainMatchRuleTests.java import org.junit.Test; import java.util.regex.Pattern; import static com.commonsware.cwac.netsecurity.DomainMatchRule.allOf; import static com.commonsware.cwac.netsecurity.DomainMatchRule.anyOf; import static com.commonsware.cwac.netsecurity.DomainMatchRule.blacklist; import static com.commonsware.cwac.netsecurity.DomainMatchRule.is; import static com.commonsware.cwac.netsecurity.DomainMatchRule.not; import static com.commonsware.cwac.netsecurity.DomainMatchRule.whitelist; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; assertTrue(anyOf(is("foo.com")).matches("foo.com")); assertFalse(anyOf(is("*.foo.com")).matches("foo.com")); assertTrue(anyOf(is("*.foo.com")).matches("www.foo.com")); assertTrue(anyOf(is("foo.com"), is("bar.com")).matches("foo.com")); assertFalse(anyOf(is("*.foo.com"), is("bar.com")).matches("foo.com")); assertTrue(anyOf(is("*.foo.com"), is("bar.com")).matches("www.foo.com")); assertTrue(anyOf(is("goo.com"), is("foo.com"), is("bar.com")).matches("foo.com")); assertFalse(anyOf(is("goo.com"), is("*.foo.com"), is("bar.com")).matches("foo.com")); assertTrue(anyOf(is("goo.com"), is("*.foo.com"), is("bar.com")).matches("www.foo.com")); } @Test public void _allOf() { assertTrue(allOf(is("foo.com")).matches("foo.com")); assertFalse(allOf(is("*.foo.com")).matches("foo.com")); assertTrue(allOf(is("*.foo.com")).matches("www.foo.com")); assertFalse(allOf(is("foo.com"), is("bar.com")).matches("foo.com")); assertFalse(allOf(is("*.foo.com"), is("bar.com")).matches("foo.com")); assertFalse(allOf(is("*.foo.com"), is("bar.com")).matches("www.foo.com")); assertFalse(allOf(is("goo.com"), is("foo.com"), is("bar.com")).matches("foo.com")); assertFalse(allOf(is("goo.com"), is("*.foo.com"), is("bar.com")).matches("foo.com")); assertFalse(allOf(is("goo.com"), is("*.foo.com"), is("bar.com")).matches("www.foo.com")); } @Test public void _whitelist() {
assertTrue(whitelist("foo.com").matches("foo.com"));
commonsguy/cwac-netsecurity
netsecurity/src/test/java/com/commonsware/cwac/netsecurity/test/DomainMatchRuleTests.java
// Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule allOf(DomainMatchRule... rules) { // return(new Composite(false, rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule anyOf(DomainMatchRule... rules) { // return(new Composite(true, rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule blacklist(String... globs) { // List<DomainMatchRule> rules=new ArrayList<>(); // // for (String glob : globs) { // rules.add(not(is(glob))); // } // // return(allOf(rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule is(Pattern pattern) { // return(new Regex(pattern)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule not(DomainMatchRule rule) { // return(new Not(rule)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule whitelist(String... globs) { // List<DomainMatchRule> rules=new ArrayList<>(); // // for (String glob : globs) { // rules.add(is(glob)); // } // // return(anyOf(rules)); // }
import org.junit.Test; import java.util.regex.Pattern; import static com.commonsware.cwac.netsecurity.DomainMatchRule.allOf; import static com.commonsware.cwac.netsecurity.DomainMatchRule.anyOf; import static com.commonsware.cwac.netsecurity.DomainMatchRule.blacklist; import static com.commonsware.cwac.netsecurity.DomainMatchRule.is; import static com.commonsware.cwac.netsecurity.DomainMatchRule.not; import static com.commonsware.cwac.netsecurity.DomainMatchRule.whitelist; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue;
assertTrue(allOf(is("foo.com")).matches("foo.com")); assertFalse(allOf(is("*.foo.com")).matches("foo.com")); assertTrue(allOf(is("*.foo.com")).matches("www.foo.com")); assertFalse(allOf(is("foo.com"), is("bar.com")).matches("foo.com")); assertFalse(allOf(is("*.foo.com"), is("bar.com")).matches("foo.com")); assertFalse(allOf(is("*.foo.com"), is("bar.com")).matches("www.foo.com")); assertFalse(allOf(is("goo.com"), is("foo.com"), is("bar.com")).matches("foo.com")); assertFalse(allOf(is("goo.com"), is("*.foo.com"), is("bar.com")).matches("foo.com")); assertFalse(allOf(is("goo.com"), is("*.foo.com"), is("bar.com")).matches("www.foo.com")); } @Test public void _whitelist() { assertTrue(whitelist("foo.com").matches("foo.com")); assertFalse(whitelist("*.foo.com").matches("foo.com")); assertTrue(whitelist("*.foo.com").matches("www.foo.com")); assertTrue(whitelist("foo.com", "bar.com").matches("foo.com")); assertFalse(whitelist("*.foo.com", "bar.com").matches("foo.com")); assertTrue(whitelist("*.foo.com", "bar.com").matches("www.foo.com")); assertTrue(whitelist("goo.com", "foo.com", "bar.com").matches("foo.com")); assertFalse(whitelist("goo.com", "*.foo.com", "bar.com").matches("foo.com")); assertTrue(whitelist("goo.com", "*.foo.com", "bar.com").matches("www.foo.com")); } @Test public void _blacklist() {
// Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule allOf(DomainMatchRule... rules) { // return(new Composite(false, rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule anyOf(DomainMatchRule... rules) { // return(new Composite(true, rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule blacklist(String... globs) { // List<DomainMatchRule> rules=new ArrayList<>(); // // for (String glob : globs) { // rules.add(not(is(glob))); // } // // return(allOf(rules)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule is(Pattern pattern) { // return(new Regex(pattern)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule not(DomainMatchRule rule) { // return(new Not(rule)); // } // // Path: netsecurity/src/main/java/com/commonsware/cwac/netsecurity/DomainMatchRule.java // public static DomainMatchRule whitelist(String... globs) { // List<DomainMatchRule> rules=new ArrayList<>(); // // for (String glob : globs) { // rules.add(is(glob)); // } // // return(anyOf(rules)); // } // Path: netsecurity/src/test/java/com/commonsware/cwac/netsecurity/test/DomainMatchRuleTests.java import org.junit.Test; import java.util.regex.Pattern; import static com.commonsware.cwac.netsecurity.DomainMatchRule.allOf; import static com.commonsware.cwac.netsecurity.DomainMatchRule.anyOf; import static com.commonsware.cwac.netsecurity.DomainMatchRule.blacklist; import static com.commonsware.cwac.netsecurity.DomainMatchRule.is; import static com.commonsware.cwac.netsecurity.DomainMatchRule.not; import static com.commonsware.cwac.netsecurity.DomainMatchRule.whitelist; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; assertTrue(allOf(is("foo.com")).matches("foo.com")); assertFalse(allOf(is("*.foo.com")).matches("foo.com")); assertTrue(allOf(is("*.foo.com")).matches("www.foo.com")); assertFalse(allOf(is("foo.com"), is("bar.com")).matches("foo.com")); assertFalse(allOf(is("*.foo.com"), is("bar.com")).matches("foo.com")); assertFalse(allOf(is("*.foo.com"), is("bar.com")).matches("www.foo.com")); assertFalse(allOf(is("goo.com"), is("foo.com"), is("bar.com")).matches("foo.com")); assertFalse(allOf(is("goo.com"), is("*.foo.com"), is("bar.com")).matches("foo.com")); assertFalse(allOf(is("goo.com"), is("*.foo.com"), is("bar.com")).matches("www.foo.com")); } @Test public void _whitelist() { assertTrue(whitelist("foo.com").matches("foo.com")); assertFalse(whitelist("*.foo.com").matches("foo.com")); assertTrue(whitelist("*.foo.com").matches("www.foo.com")); assertTrue(whitelist("foo.com", "bar.com").matches("foo.com")); assertFalse(whitelist("*.foo.com", "bar.com").matches("foo.com")); assertTrue(whitelist("*.foo.com", "bar.com").matches("www.foo.com")); assertTrue(whitelist("goo.com", "foo.com", "bar.com").matches("foo.com")); assertFalse(whitelist("goo.com", "*.foo.com", "bar.com").matches("foo.com")); assertTrue(whitelist("goo.com", "*.foo.com", "bar.com").matches("www.foo.com")); } @Test public void _blacklist() {
assertFalse(blacklist("foo.com").matches("foo.com"));
MrBlobman/SpigotCommandLib
src/main/java/io/github/mrblobman/spigotcommandlib/registry/HandleInvoker.java
// Path: src/main/java/io/github/mrblobman/spigotcommandlib/args/CommandParameter.java // public class CommandParameter<T> { // private final CommandParameterKind kind; // private final ArgumentFormatter<T> formatter; // private final Class type; // // private final String name; // private final List<String> desc; // // public CommandParameter(CommandParameterKind kind, ArgumentFormatter<T> formatter, Class argClass, String name, List<String> desc) { // this.kind = kind; // this.formatter = formatter; // this.type = argClass; // this.name = name; // // if (desc == null) { // this.desc = new ArrayList<>(formatter.getTypeDesc().length + 1); // this.desc.add(ChatColor.YELLOW + formatter.getTypeName()); // Arrays.stream(formatter.getTypeDesc()) // .map(s -> ChatColor.GRAY + s) // .forEachOrdered(this.desc::add); // } else { // this.desc = desc.stream() // .map(s -> ChatColor.translateAlternateColorCodes('&', s)) // .collect(Collectors.toList()); // } // } // // public CommandParameter(CommandParameterKind kind, ArgumentFormatter<T> formatter, Class argClass, String name) { // this(kind, formatter, argClass, name, null); // } // // /** // * The name of the argument. Each argument should have a unique name. // * // * @return the name of this argument. // */ // public String getName() { // return this.name; // } // // /** // * A descriptive name is a name that implies additional // * information about the argument. For example [argname] vs &lt;argname&gt;. // * // * @return the descriptive name for this argument // */ // public String getDescriptiveName() { // return this.kind.formatNameInArgPattern(this.getName()); // } // // /** // * Get a description of the use of the parameter. This // * explains the value for the argument. // * // * @return the description of the parameter. // */ // public List<String> getDescription() { // return this.desc; // } // // /** // * Get the {@link ArgumentFormatter} for this parameter. It can // * be used to check if an argument can be parsed for this // * parameter as well as actually doing the parsing. // * // * @return the argument formatter for this parameter. // */ // public ArgumentFormatter<T> getFormatter() { // return this.formatter; // } // // /** // * Get the type that this argument is declared as. // * // * @return the type this argument is declared as // */ // public Class getArgumentType() { // return this.type; // } // // /** // * Check if this parameter is an argument of varying length. // * // * @return true iff this parameter is of varying length, false otherwise. // */ // public boolean isVarArgs() { // return this.kind.isVarArgs(); // } // // /** // * Check if this parameter is optional or not. // * if {@link #isVarArgs()} returns true, isOptional() will also return true // * // * @return true iff this parameter is optional, false otherwise. // */ // public boolean isOptional() { // return this.kind.isOptional(); // } // // public CommandParameterKind getKind() { // return this.kind; // } // // @Override // public String toString() { // return "CommandParameter{" + // "formatter=" + this.formatter + // ", name='" + this.name + '\'' + // ", desc=" + this.desc + // ", kind=" + this.kind + // '}'; // } // } // // Path: src/main/java/io/github/mrblobman/spigotcommandlib/args/ParseException.java // public class ParseException extends RuntimeException { // public ParseException() { // } // // public ParseException(String message) { // super(message); // } // // public ParseException(String message, Throwable cause) { // super(message, cause); // } // // public ParseException(Throwable cause) { // super(cause); // } // // public ParseException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // }
import net.md_5.bungee.api.chat.*; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.google.common.base.Defaults; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import io.github.mrblobman.spigotcommandlib.args.CommandParameter; import io.github.mrblobman.spigotcommandlib.args.ParseException; import net.md_5.bungee.api.ChatColor;
/* * The MIT License (MIT) * * Copyright (c) 2018 MrBlobman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.github.mrblobman.spigotcommandlib.registry; public class HandleInvoker implements Invoker { protected SubCommand subCommand; protected String cmdDesc; protected Object invocationTarget; protected Method method; protected Class<?> senderType;
// Path: src/main/java/io/github/mrblobman/spigotcommandlib/args/CommandParameter.java // public class CommandParameter<T> { // private final CommandParameterKind kind; // private final ArgumentFormatter<T> formatter; // private final Class type; // // private final String name; // private final List<String> desc; // // public CommandParameter(CommandParameterKind kind, ArgumentFormatter<T> formatter, Class argClass, String name, List<String> desc) { // this.kind = kind; // this.formatter = formatter; // this.type = argClass; // this.name = name; // // if (desc == null) { // this.desc = new ArrayList<>(formatter.getTypeDesc().length + 1); // this.desc.add(ChatColor.YELLOW + formatter.getTypeName()); // Arrays.stream(formatter.getTypeDesc()) // .map(s -> ChatColor.GRAY + s) // .forEachOrdered(this.desc::add); // } else { // this.desc = desc.stream() // .map(s -> ChatColor.translateAlternateColorCodes('&', s)) // .collect(Collectors.toList()); // } // } // // public CommandParameter(CommandParameterKind kind, ArgumentFormatter<T> formatter, Class argClass, String name) { // this(kind, formatter, argClass, name, null); // } // // /** // * The name of the argument. Each argument should have a unique name. // * // * @return the name of this argument. // */ // public String getName() { // return this.name; // } // // /** // * A descriptive name is a name that implies additional // * information about the argument. For example [argname] vs &lt;argname&gt;. // * // * @return the descriptive name for this argument // */ // public String getDescriptiveName() { // return this.kind.formatNameInArgPattern(this.getName()); // } // // /** // * Get a description of the use of the parameter. This // * explains the value for the argument. // * // * @return the description of the parameter. // */ // public List<String> getDescription() { // return this.desc; // } // // /** // * Get the {@link ArgumentFormatter} for this parameter. It can // * be used to check if an argument can be parsed for this // * parameter as well as actually doing the parsing. // * // * @return the argument formatter for this parameter. // */ // public ArgumentFormatter<T> getFormatter() { // return this.formatter; // } // // /** // * Get the type that this argument is declared as. // * // * @return the type this argument is declared as // */ // public Class getArgumentType() { // return this.type; // } // // /** // * Check if this parameter is an argument of varying length. // * // * @return true iff this parameter is of varying length, false otherwise. // */ // public boolean isVarArgs() { // return this.kind.isVarArgs(); // } // // /** // * Check if this parameter is optional or not. // * if {@link #isVarArgs()} returns true, isOptional() will also return true // * // * @return true iff this parameter is optional, false otherwise. // */ // public boolean isOptional() { // return this.kind.isOptional(); // } // // public CommandParameterKind getKind() { // return this.kind; // } // // @Override // public String toString() { // return "CommandParameter{" + // "formatter=" + this.formatter + // ", name='" + this.name + '\'' + // ", desc=" + this.desc + // ", kind=" + this.kind + // '}'; // } // } // // Path: src/main/java/io/github/mrblobman/spigotcommandlib/args/ParseException.java // public class ParseException extends RuntimeException { // public ParseException() { // } // // public ParseException(String message) { // super(message); // } // // public ParseException(String message, Throwable cause) { // super(message, cause); // } // // public ParseException(Throwable cause) { // super(cause); // } // // public ParseException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // Path: src/main/java/io/github/mrblobman/spigotcommandlib/registry/HandleInvoker.java import net.md_5.bungee.api.chat.*; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.google.common.base.Defaults; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import io.github.mrblobman.spigotcommandlib.args.CommandParameter; import io.github.mrblobman.spigotcommandlib.args.ParseException; import net.md_5.bungee.api.ChatColor; /* * The MIT License (MIT) * * Copyright (c) 2018 MrBlobman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.github.mrblobman.spigotcommandlib.registry; public class HandleInvoker implements Invoker { protected SubCommand subCommand; protected String cmdDesc; protected Object invocationTarget; protected Method method; protected Class<?> senderType;
protected List<CommandParameter<?>> commandParameters;
MrBlobman/SpigotCommandLib
src/main/java/io/github/mrblobman/spigotcommandlib/registry/HandleInvoker.java
// Path: src/main/java/io/github/mrblobman/spigotcommandlib/args/CommandParameter.java // public class CommandParameter<T> { // private final CommandParameterKind kind; // private final ArgumentFormatter<T> formatter; // private final Class type; // // private final String name; // private final List<String> desc; // // public CommandParameter(CommandParameterKind kind, ArgumentFormatter<T> formatter, Class argClass, String name, List<String> desc) { // this.kind = kind; // this.formatter = formatter; // this.type = argClass; // this.name = name; // // if (desc == null) { // this.desc = new ArrayList<>(formatter.getTypeDesc().length + 1); // this.desc.add(ChatColor.YELLOW + formatter.getTypeName()); // Arrays.stream(formatter.getTypeDesc()) // .map(s -> ChatColor.GRAY + s) // .forEachOrdered(this.desc::add); // } else { // this.desc = desc.stream() // .map(s -> ChatColor.translateAlternateColorCodes('&', s)) // .collect(Collectors.toList()); // } // } // // public CommandParameter(CommandParameterKind kind, ArgumentFormatter<T> formatter, Class argClass, String name) { // this(kind, formatter, argClass, name, null); // } // // /** // * The name of the argument. Each argument should have a unique name. // * // * @return the name of this argument. // */ // public String getName() { // return this.name; // } // // /** // * A descriptive name is a name that implies additional // * information about the argument. For example [argname] vs &lt;argname&gt;. // * // * @return the descriptive name for this argument // */ // public String getDescriptiveName() { // return this.kind.formatNameInArgPattern(this.getName()); // } // // /** // * Get a description of the use of the parameter. This // * explains the value for the argument. // * // * @return the description of the parameter. // */ // public List<String> getDescription() { // return this.desc; // } // // /** // * Get the {@link ArgumentFormatter} for this parameter. It can // * be used to check if an argument can be parsed for this // * parameter as well as actually doing the parsing. // * // * @return the argument formatter for this parameter. // */ // public ArgumentFormatter<T> getFormatter() { // return this.formatter; // } // // /** // * Get the type that this argument is declared as. // * // * @return the type this argument is declared as // */ // public Class getArgumentType() { // return this.type; // } // // /** // * Check if this parameter is an argument of varying length. // * // * @return true iff this parameter is of varying length, false otherwise. // */ // public boolean isVarArgs() { // return this.kind.isVarArgs(); // } // // /** // * Check if this parameter is optional or not. // * if {@link #isVarArgs()} returns true, isOptional() will also return true // * // * @return true iff this parameter is optional, false otherwise. // */ // public boolean isOptional() { // return this.kind.isOptional(); // } // // public CommandParameterKind getKind() { // return this.kind; // } // // @Override // public String toString() { // return "CommandParameter{" + // "formatter=" + this.formatter + // ", name='" + this.name + '\'' + // ", desc=" + this.desc + // ", kind=" + this.kind + // '}'; // } // } // // Path: src/main/java/io/github/mrblobman/spigotcommandlib/args/ParseException.java // public class ParseException extends RuntimeException { // public ParseException() { // } // // public ParseException(String message) { // super(message); // } // // public ParseException(String message, Throwable cause) { // super(message, cause); // } // // public ParseException(Throwable cause) { // super(cause); // } // // public ParseException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // }
import net.md_5.bungee.api.chat.*; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.google.common.base.Defaults; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import io.github.mrblobman.spigotcommandlib.args.CommandParameter; import io.github.mrblobman.spigotcommandlib.args.ParseException; import net.md_5.bungee.api.ChatColor;
sendIncorrectSenderMessage(sender); return true; } List<Object> params = buildMethodParams(sender, args); if (params == null) return true; int i = 0; Object[] callParams = new Object[params.size() + 1]; callParams[i++] = sender; for (Object param : params) { callParams[i++] = param; } method.invoke(invocationTarget, callParams); return true; } protected List<Object> buildMethodParams(CommandSender sender, String[] args) { if (args.length < minArgsRequired) { // Not enough args, send usage sendUsage(sender); return null; } List<Object> params = new ArrayList<>(); // Parse all required for (int i = 0; i < minArgsRequired; i++) { CommandParameter<?> cmdParam = this.commandParameters.get(i); if (cmdParam.getFormatter().canBeParsedFrom(args[i])) { try { params.add(cmdParam.getFormatter().parse(args[i]));
// Path: src/main/java/io/github/mrblobman/spigotcommandlib/args/CommandParameter.java // public class CommandParameter<T> { // private final CommandParameterKind kind; // private final ArgumentFormatter<T> formatter; // private final Class type; // // private final String name; // private final List<String> desc; // // public CommandParameter(CommandParameterKind kind, ArgumentFormatter<T> formatter, Class argClass, String name, List<String> desc) { // this.kind = kind; // this.formatter = formatter; // this.type = argClass; // this.name = name; // // if (desc == null) { // this.desc = new ArrayList<>(formatter.getTypeDesc().length + 1); // this.desc.add(ChatColor.YELLOW + formatter.getTypeName()); // Arrays.stream(formatter.getTypeDesc()) // .map(s -> ChatColor.GRAY + s) // .forEachOrdered(this.desc::add); // } else { // this.desc = desc.stream() // .map(s -> ChatColor.translateAlternateColorCodes('&', s)) // .collect(Collectors.toList()); // } // } // // public CommandParameter(CommandParameterKind kind, ArgumentFormatter<T> formatter, Class argClass, String name) { // this(kind, formatter, argClass, name, null); // } // // /** // * The name of the argument. Each argument should have a unique name. // * // * @return the name of this argument. // */ // public String getName() { // return this.name; // } // // /** // * A descriptive name is a name that implies additional // * information about the argument. For example [argname] vs &lt;argname&gt;. // * // * @return the descriptive name for this argument // */ // public String getDescriptiveName() { // return this.kind.formatNameInArgPattern(this.getName()); // } // // /** // * Get a description of the use of the parameter. This // * explains the value for the argument. // * // * @return the description of the parameter. // */ // public List<String> getDescription() { // return this.desc; // } // // /** // * Get the {@link ArgumentFormatter} for this parameter. It can // * be used to check if an argument can be parsed for this // * parameter as well as actually doing the parsing. // * // * @return the argument formatter for this parameter. // */ // public ArgumentFormatter<T> getFormatter() { // return this.formatter; // } // // /** // * Get the type that this argument is declared as. // * // * @return the type this argument is declared as // */ // public Class getArgumentType() { // return this.type; // } // // /** // * Check if this parameter is an argument of varying length. // * // * @return true iff this parameter is of varying length, false otherwise. // */ // public boolean isVarArgs() { // return this.kind.isVarArgs(); // } // // /** // * Check if this parameter is optional or not. // * if {@link #isVarArgs()} returns true, isOptional() will also return true // * // * @return true iff this parameter is optional, false otherwise. // */ // public boolean isOptional() { // return this.kind.isOptional(); // } // // public CommandParameterKind getKind() { // return this.kind; // } // // @Override // public String toString() { // return "CommandParameter{" + // "formatter=" + this.formatter + // ", name='" + this.name + '\'' + // ", desc=" + this.desc + // ", kind=" + this.kind + // '}'; // } // } // // Path: src/main/java/io/github/mrblobman/spigotcommandlib/args/ParseException.java // public class ParseException extends RuntimeException { // public ParseException() { // } // // public ParseException(String message) { // super(message); // } // // public ParseException(String message, Throwable cause) { // super(message, cause); // } // // public ParseException(Throwable cause) { // super(cause); // } // // public ParseException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // } // Path: src/main/java/io/github/mrblobman/spigotcommandlib/registry/HandleInvoker.java import net.md_5.bungee.api.chat.*; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.google.common.base.Defaults; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import io.github.mrblobman.spigotcommandlib.args.CommandParameter; import io.github.mrblobman.spigotcommandlib.args.ParseException; import net.md_5.bungee.api.ChatColor; sendIncorrectSenderMessage(sender); return true; } List<Object> params = buildMethodParams(sender, args); if (params == null) return true; int i = 0; Object[] callParams = new Object[params.size() + 1]; callParams[i++] = sender; for (Object param : params) { callParams[i++] = param; } method.invoke(invocationTarget, callParams); return true; } protected List<Object> buildMethodParams(CommandSender sender, String[] args) { if (args.length < minArgsRequired) { // Not enough args, send usage sendUsage(sender); return null; } List<Object> params = new ArrayList<>(); // Parse all required for (int i = 0; i < minArgsRequired; i++) { CommandParameter<?> cmdParam = this.commandParameters.get(i); if (cmdParam.getFormatter().canBeParsedFrom(args[i])) { try { params.add(cmdParam.getFormatter().parse(args[i]));
} catch (ParseException e) {
MrBlobman/SpigotCommandLib
src/main/java/io/github/mrblobman/spigotcommandlib/registry/FragmentBundle.java
// Path: src/main/java/io/github/mrblobman/spigotcommandlib/FragmentExecutionContext.java // public class FragmentExecutionContext { // public static final int DEFAULT_STATE = 0; // // private int state; // // public FragmentExecutionContext() { // this.state = 0; // } // // /** // * Get the current state that the executor bound to // * this context is in. // * <p> // * The executor must be in the correct state in order for // * execution of a fragment command to occur. // * // * @return the state of the executor bound to this context. // */ // public final int getState() { // return this.state; // } // // /** // * Set the current state that the executor bound to this context // * is in. // * // * @param state the new state for this executor's context. // */ // public final void setState(int state) { // this.state = state; // } // } // // Path: src/main/java/io/github/mrblobman/spigotcommandlib/FragmentedCommandContextSupplier.java // public interface FragmentedCommandContextSupplier<T> { // /** // * Create a new command context for passing between commands. // * // * @return the new context created for a sender in state 0 // * of a fragmented command. // */ // T get(); // } // // Path: src/main/java/io/github/mrblobman/spigotcommandlib/FragmentedCommandHandler.java // public interface FragmentedCommandHandler<T extends FragmentExecutionContext> { // // /** // * This method is invoked when the context for the sender // * with the given UUID is being removed from the context // * handler. Do not count on this method executing immediately // * on timeout, the cleanup time is arbitrary but this hook allows // * you to be notified of the context's removal from memory. // * // * @param id the UUID of the sender // * @param context their execution context // */ // void onCleanup(UUID id, T context); // }
import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.*; import java.util.concurrent.TimeUnit; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.RemovalNotification; import io.github.mrblobman.spigotcommandlib.FragmentExecutionContext; import io.github.mrblobman.spigotcommandlib.FragmentedCommandContextSupplier; import io.github.mrblobman.spigotcommandlib.FragmentedCommandHandler; import net.md_5.bungee.api.ChatColor;
/* * The MIT License (MIT) * * Copyright (c) 2018 MrBlobman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.github.mrblobman.spigotcommandlib.registry; public class FragmentBundle<T extends FragmentExecutionContext> implements Invoker { private static final int CACHE_SPEC_CONCURRENCY_LEVEL = 1; /* The term cache may be a little bit misleading, we really just need a time based evicting map and this lib is bundled with spigot. */ //name -> context private Cache<UUID, T> openContexts;
// Path: src/main/java/io/github/mrblobman/spigotcommandlib/FragmentExecutionContext.java // public class FragmentExecutionContext { // public static final int DEFAULT_STATE = 0; // // private int state; // // public FragmentExecutionContext() { // this.state = 0; // } // // /** // * Get the current state that the executor bound to // * this context is in. // * <p> // * The executor must be in the correct state in order for // * execution of a fragment command to occur. // * // * @return the state of the executor bound to this context. // */ // public final int getState() { // return this.state; // } // // /** // * Set the current state that the executor bound to this context // * is in. // * // * @param state the new state for this executor's context. // */ // public final void setState(int state) { // this.state = state; // } // } // // Path: src/main/java/io/github/mrblobman/spigotcommandlib/FragmentedCommandContextSupplier.java // public interface FragmentedCommandContextSupplier<T> { // /** // * Create a new command context for passing between commands. // * // * @return the new context created for a sender in state 0 // * of a fragmented command. // */ // T get(); // } // // Path: src/main/java/io/github/mrblobman/spigotcommandlib/FragmentedCommandHandler.java // public interface FragmentedCommandHandler<T extends FragmentExecutionContext> { // // /** // * This method is invoked when the context for the sender // * with the given UUID is being removed from the context // * handler. Do not count on this method executing immediately // * on timeout, the cleanup time is arbitrary but this hook allows // * you to be notified of the context's removal from memory. // * // * @param id the UUID of the sender // * @param context their execution context // */ // void onCleanup(UUID id, T context); // } // Path: src/main/java/io/github/mrblobman/spigotcommandlib/registry/FragmentBundle.java import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.*; import java.util.concurrent.TimeUnit; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.RemovalNotification; import io.github.mrblobman.spigotcommandlib.FragmentExecutionContext; import io.github.mrblobman.spigotcommandlib.FragmentedCommandContextSupplier; import io.github.mrblobman.spigotcommandlib.FragmentedCommandHandler; import net.md_5.bungee.api.ChatColor; /* * The MIT License (MIT) * * Copyright (c) 2018 MrBlobman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.github.mrblobman.spigotcommandlib.registry; public class FragmentBundle<T extends FragmentExecutionContext> implements Invoker { private static final int CACHE_SPEC_CONCURRENCY_LEVEL = 1; /* The term cache may be a little bit misleading, we really just need a time based evicting map and this lib is bundled with spigot. */ //name -> context private Cache<UUID, T> openContexts;
private FragmentedCommandContextSupplier<T> contextGenerator;
MrBlobman/SpigotCommandLib
src/main/java/io/github/mrblobman/spigotcommandlib/registry/FragmentBundle.java
// Path: src/main/java/io/github/mrblobman/spigotcommandlib/FragmentExecutionContext.java // public class FragmentExecutionContext { // public static final int DEFAULT_STATE = 0; // // private int state; // // public FragmentExecutionContext() { // this.state = 0; // } // // /** // * Get the current state that the executor bound to // * this context is in. // * <p> // * The executor must be in the correct state in order for // * execution of a fragment command to occur. // * // * @return the state of the executor bound to this context. // */ // public final int getState() { // return this.state; // } // // /** // * Set the current state that the executor bound to this context // * is in. // * // * @param state the new state for this executor's context. // */ // public final void setState(int state) { // this.state = state; // } // } // // Path: src/main/java/io/github/mrblobman/spigotcommandlib/FragmentedCommandContextSupplier.java // public interface FragmentedCommandContextSupplier<T> { // /** // * Create a new command context for passing between commands. // * // * @return the new context created for a sender in state 0 // * of a fragmented command. // */ // T get(); // } // // Path: src/main/java/io/github/mrblobman/spigotcommandlib/FragmentedCommandHandler.java // public interface FragmentedCommandHandler<T extends FragmentExecutionContext> { // // /** // * This method is invoked when the context for the sender // * with the given UUID is being removed from the context // * handler. Do not count on this method executing immediately // * on timeout, the cleanup time is arbitrary but this hook allows // * you to be notified of the context's removal from memory. // * // * @param id the UUID of the sender // * @param context their execution context // */ // void onCleanup(UUID id, T context); // }
import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.*; import java.util.concurrent.TimeUnit; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.RemovalNotification; import io.github.mrblobman.spigotcommandlib.FragmentExecutionContext; import io.github.mrblobman.spigotcommandlib.FragmentedCommandContextSupplier; import io.github.mrblobman.spigotcommandlib.FragmentedCommandHandler; import net.md_5.bungee.api.ChatColor;
/* * The MIT License (MIT) * * Copyright (c) 2018 MrBlobman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.github.mrblobman.spigotcommandlib.registry; public class FragmentBundle<T extends FragmentExecutionContext> implements Invoker { private static final int CACHE_SPEC_CONCURRENCY_LEVEL = 1; /* The term cache may be a little bit misleading, we really just need a time based evicting map and this lib is bundled with spigot. */ //name -> context private Cache<UUID, T> openContexts; private FragmentedCommandContextSupplier<T> contextGenerator; private Map<SubCommand, FragmentHandleInvoker[]> invokers; private Set<SubCommand> hasDefaultStateHandler;
// Path: src/main/java/io/github/mrblobman/spigotcommandlib/FragmentExecutionContext.java // public class FragmentExecutionContext { // public static final int DEFAULT_STATE = 0; // // private int state; // // public FragmentExecutionContext() { // this.state = 0; // } // // /** // * Get the current state that the executor bound to // * this context is in. // * <p> // * The executor must be in the correct state in order for // * execution of a fragment command to occur. // * // * @return the state of the executor bound to this context. // */ // public final int getState() { // return this.state; // } // // /** // * Set the current state that the executor bound to this context // * is in. // * // * @param state the new state for this executor's context. // */ // public final void setState(int state) { // this.state = state; // } // } // // Path: src/main/java/io/github/mrblobman/spigotcommandlib/FragmentedCommandContextSupplier.java // public interface FragmentedCommandContextSupplier<T> { // /** // * Create a new command context for passing between commands. // * // * @return the new context created for a sender in state 0 // * of a fragmented command. // */ // T get(); // } // // Path: src/main/java/io/github/mrblobman/spigotcommandlib/FragmentedCommandHandler.java // public interface FragmentedCommandHandler<T extends FragmentExecutionContext> { // // /** // * This method is invoked when the context for the sender // * with the given UUID is being removed from the context // * handler. Do not count on this method executing immediately // * on timeout, the cleanup time is arbitrary but this hook allows // * you to be notified of the context's removal from memory. // * // * @param id the UUID of the sender // * @param context their execution context // */ // void onCleanup(UUID id, T context); // } // Path: src/main/java/io/github/mrblobman/spigotcommandlib/registry/FragmentBundle.java import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.*; import java.util.concurrent.TimeUnit; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.RemovalNotification; import io.github.mrblobman.spigotcommandlib.FragmentExecutionContext; import io.github.mrblobman.spigotcommandlib.FragmentedCommandContextSupplier; import io.github.mrblobman.spigotcommandlib.FragmentedCommandHandler; import net.md_5.bungee.api.ChatColor; /* * The MIT License (MIT) * * Copyright (c) 2018 MrBlobman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.github.mrblobman.spigotcommandlib.registry; public class FragmentBundle<T extends FragmentExecutionContext> implements Invoker { private static final int CACHE_SPEC_CONCURRENCY_LEVEL = 1; /* The term cache may be a little bit misleading, we really just need a time based evicting map and this lib is bundled with spigot. */ //name -> context private Cache<UUID, T> openContexts; private FragmentedCommandContextSupplier<T> contextGenerator; private Map<SubCommand, FragmentHandleInvoker[]> invokers; private Set<SubCommand> hasDefaultStateHandler;
private FragmentedCommandHandler<T> handler;
MrBlobman/SpigotCommandLib
src/main/java/io/github/mrblobman/spigotcommandlib/CommandHandle.java
// Path: src/main/java/io/github/mrblobman/spigotcommandlib/registry/CommandLib.java // public class CommandLib { // public static final String NO_PERMISSION = ""; // public static final int NO_TIMEOUT = 0; // // private CommandRegistry registry; // private Plugin hook; // // public CommandLib(Plugin hook) throws IllegalStateException { // this.hook = hook; // try { // this.registry = new CommandRegistry(this); // } catch (InstantiationException e) { // throw new IllegalStateException("Could not retrieve the bukkit command map. It is likely that this instance is being constructed before a server is available."); // } // } // // /** // * Register a new handler. Methods that handle specific commands must // * be flagged with the {@code @CommandHandle} annotation. // * // * @param handler the command handler // * // * @see CommandMethodHandle // */ // public void registerCommandHandler(CommandHandler handler) throws HandlerCompilationException { // registry.register(handler); // } // // /** // * Register a new handler. Methods that handle specific commands must // * be flagged with the {@code @SubCommandHandle} annotation. // * // * @param handler the command handler // * @param cmdPrefix the sub required in addition to the sub command for the handle // * // * @see SubCommandHandle // */ // public void registerSubCommandHandler(SubCommandHandler handler, String[] cmdPrefix) throws HandlerCompilationException { // registry.register(handler, cmdPrefix); // } // // /** // * Register a new handler. Methods that handle specific commands must // * be flagged with the {@code @SubCommandHandle} annotation. // * // * @param handler the command handler // * @param permission the permission required to execute all methods in this sub handler if // * not overridden in the annotation // * @param cmdPrefix the sub required in addition to the sub command for the handle // * // * @see SubCommandHandle // */ // public void registerSubCommandHandler(SubCommandHandler handler, String permission, String[] cmdPrefix) throws HandlerCompilationException { // registry.register(handler, permission, cmdPrefix); // } // // /** // * Register a new handler. Methods handling specific commands must // * be flagged with the {@code #FragmentCommandHandle} annotation. // * // * @param handler the command handler // * @param permission the permission required to execute the command. See: {@link #NO_PERMISSION} // * @param timeout the time to keep any context instances loaded. See: {@link #NO_TIMEOUT} // * @param supplier a supplier to generate new context's when needed // * @param cmdPrefix the sub required in addition to the sub command for the handle // * @param <T> the type of the context // * // * @see FragmentedCommandHandle // */ // public <T extends FragmentExecutionContext> void registerFragmentedCommandHandler(FragmentedCommandHandler<T> handler, String permission, long timeout, FragmentedCommandContextSupplier<T> supplier, String... cmdPrefix) throws HandlerCompilationException { // registry.register(handler, permission, timeout, supplier, cmdPrefix); // } // // /** // * Register a new handler. Methods handling specific commands must // * be flagged with the {@code #FragmentCommandHandle} annotation. // * This uses the default command context. // * // * @param handler the command handler // * @param permission the permission required to execute the command. See: {@link #NO_PERMISSION} // * @param timeout the time to keep any context instances loaded.. See: {@link #NO_TIMEOUT} // * @param cmdPrefix the sub required in addition to the sub command for the handle // * // * @see FragmentedCommandHandle // */ // public void registerFragmentedCommandHandler(FragmentedCommandHandler<FragmentExecutionContext> handler, String permission, long timeout, String... cmdPrefix) throws HandlerCompilationException { // registry.register(handler, permission, timeout, FragmentExecutionContext::new, cmdPrefix); // } // // /** // * @return the plugin using this instance of the lib. // */ // public Plugin getHook() { // return this.hook; // } // // protected boolean execute(CommandSender sender, String[] command) throws CommandException { // return registry.handleCommand(sender, command); // } // // protected List<String> tabComplete(CommandSender sender, String[] command) { // return registry.getPossibleSubCommands(command); // } // // public void sendHelpMessage(CommandSender sender, String... searchQuery) { // this.registry.displayHelp(sender, searchQuery); // } // }
import io.github.mrblobman.spigotcommandlib.registry.CommandLib; import java.lang.annotation.*;
/* * The MIT License (MIT) * * Copyright (c) 2018 MrBlobman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.github.mrblobman.spigotcommandlib; /** * Marks the annotated method as a method that should be registered as a * command. Methods marked with this method should belong to a class * implementing {@link CommandHandler}. */ @Documented @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface CommandHandle { /** * Specifies the sub command that this method handles. * Ex: /baseCommand subCmd1 subCmd2 = <code>new String[] {"baseCommand|baseAlias1", "subCmd1|alias1|alias2", * "subCmd2"}</code> * * @return a string array containing the full sub command that this method handles */ String[] command(); /** * Specifies the permission required by the executer to successfully * execute this sub command. * Ex: my.subcommands.permission * * @return the String representation of the required permission */
// Path: src/main/java/io/github/mrblobman/spigotcommandlib/registry/CommandLib.java // public class CommandLib { // public static final String NO_PERMISSION = ""; // public static final int NO_TIMEOUT = 0; // // private CommandRegistry registry; // private Plugin hook; // // public CommandLib(Plugin hook) throws IllegalStateException { // this.hook = hook; // try { // this.registry = new CommandRegistry(this); // } catch (InstantiationException e) { // throw new IllegalStateException("Could not retrieve the bukkit command map. It is likely that this instance is being constructed before a server is available."); // } // } // // /** // * Register a new handler. Methods that handle specific commands must // * be flagged with the {@code @CommandHandle} annotation. // * // * @param handler the command handler // * // * @see CommandMethodHandle // */ // public void registerCommandHandler(CommandHandler handler) throws HandlerCompilationException { // registry.register(handler); // } // // /** // * Register a new handler. Methods that handle specific commands must // * be flagged with the {@code @SubCommandHandle} annotation. // * // * @param handler the command handler // * @param cmdPrefix the sub required in addition to the sub command for the handle // * // * @see SubCommandHandle // */ // public void registerSubCommandHandler(SubCommandHandler handler, String[] cmdPrefix) throws HandlerCompilationException { // registry.register(handler, cmdPrefix); // } // // /** // * Register a new handler. Methods that handle specific commands must // * be flagged with the {@code @SubCommandHandle} annotation. // * // * @param handler the command handler // * @param permission the permission required to execute all methods in this sub handler if // * not overridden in the annotation // * @param cmdPrefix the sub required in addition to the sub command for the handle // * // * @see SubCommandHandle // */ // public void registerSubCommandHandler(SubCommandHandler handler, String permission, String[] cmdPrefix) throws HandlerCompilationException { // registry.register(handler, permission, cmdPrefix); // } // // /** // * Register a new handler. Methods handling specific commands must // * be flagged with the {@code #FragmentCommandHandle} annotation. // * // * @param handler the command handler // * @param permission the permission required to execute the command. See: {@link #NO_PERMISSION} // * @param timeout the time to keep any context instances loaded. See: {@link #NO_TIMEOUT} // * @param supplier a supplier to generate new context's when needed // * @param cmdPrefix the sub required in addition to the sub command for the handle // * @param <T> the type of the context // * // * @see FragmentedCommandHandle // */ // public <T extends FragmentExecutionContext> void registerFragmentedCommandHandler(FragmentedCommandHandler<T> handler, String permission, long timeout, FragmentedCommandContextSupplier<T> supplier, String... cmdPrefix) throws HandlerCompilationException { // registry.register(handler, permission, timeout, supplier, cmdPrefix); // } // // /** // * Register a new handler. Methods handling specific commands must // * be flagged with the {@code #FragmentCommandHandle} annotation. // * This uses the default command context. // * // * @param handler the command handler // * @param permission the permission required to execute the command. See: {@link #NO_PERMISSION} // * @param timeout the time to keep any context instances loaded.. See: {@link #NO_TIMEOUT} // * @param cmdPrefix the sub required in addition to the sub command for the handle // * // * @see FragmentedCommandHandle // */ // public void registerFragmentedCommandHandler(FragmentedCommandHandler<FragmentExecutionContext> handler, String permission, long timeout, String... cmdPrefix) throws HandlerCompilationException { // registry.register(handler, permission, timeout, FragmentExecutionContext::new, cmdPrefix); // } // // /** // * @return the plugin using this instance of the lib. // */ // public Plugin getHook() { // return this.hook; // } // // protected boolean execute(CommandSender sender, String[] command) throws CommandException { // return registry.handleCommand(sender, command); // } // // protected List<String> tabComplete(CommandSender sender, String[] command) { // return registry.getPossibleSubCommands(command); // } // // public void sendHelpMessage(CommandSender sender, String... searchQuery) { // this.registry.displayHelp(sender, searchQuery); // } // } // Path: src/main/java/io/github/mrblobman/spigotcommandlib/CommandHandle.java import io.github.mrblobman.spigotcommandlib.registry.CommandLib; import java.lang.annotation.*; /* * The MIT License (MIT) * * Copyright (c) 2018 MrBlobman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.github.mrblobman.spigotcommandlib; /** * Marks the annotated method as a method that should be registered as a * command. Methods marked with this method should belong to a class * implementing {@link CommandHandler}. */ @Documented @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface CommandHandle { /** * Specifies the sub command that this method handles. * Ex: /baseCommand subCmd1 subCmd2 = <code>new String[] {"baseCommand|baseAlias1", "subCmd1|alias1|alias2", * "subCmd2"}</code> * * @return a string array containing the full sub command that this method handles */ String[] command(); /** * Specifies the permission required by the executer to successfully * execute this sub command. * Ex: my.subcommands.permission * * @return the String representation of the required permission */
String permission() default CommandLib.NO_PERMISSION;
minhhai2209/jira-plugin-converter
src/main/java/minhhai2209/jirapluginconverter/plugin/render/ParameterContextBuilder.java
// Path: src/main/java/minhhai2209/jirapluginconverter/utils/ExceptionUtils.java // public class ExceptionUtils { // // public static void throwUnchecked(Exception e) { // throw new IllegalStateException(e); // } // // public static String getStackTrace(Exception e) { // return Throwables.getStackTraceAsString(e); // } // }
import com.atlassian.jira.component.ComponentAccessor; import com.atlassian.jira.issue.Issue; import com.atlassian.jira.issue.IssueManager; import com.atlassian.jira.issue.MutableIssue; import com.atlassian.jira.project.Project; import com.atlassian.jira.project.ProjectManager; import com.atlassian.jira.project.browse.BrowseContext; import minhhai2209.jirapluginconverter.utils.ExceptionUtils; import org.apache.commons.lang.text.StrSubstitutor; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; import javax.servlet.http.HttpServletRequest; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map;
Issue issue = (Issue) o; acContext.put("issue.key", issue.getKey()); acContext.put("issue.id", issue.getId().toString()); acContext.put("issuetype.id", issue.getIssueTypeId()); } } o = contextParams.get("project"); if (o != null) { if (o instanceof Project) { Project project = (Project) o; acContext.put("project.key", project.getKey()); acContext.put("project.id", project.getId().toString()); } } o = contextParams.get("postFunctionId"); if (o != null) { acContext.put("postFunction.id", (String) o); } o = contextParams.get("postFunctionConfig"); if (o != null) { acContext.put("postFunction.config", URLEncoder.encode((String) o, "UTF-8")); } else { acContext.put("postFunction.config", ""); } } catch (Exception e) {
// Path: src/main/java/minhhai2209/jirapluginconverter/utils/ExceptionUtils.java // public class ExceptionUtils { // // public static void throwUnchecked(Exception e) { // throw new IllegalStateException(e); // } // // public static String getStackTrace(Exception e) { // return Throwables.getStackTraceAsString(e); // } // } // Path: src/main/java/minhhai2209/jirapluginconverter/plugin/render/ParameterContextBuilder.java import com.atlassian.jira.component.ComponentAccessor; import com.atlassian.jira.issue.Issue; import com.atlassian.jira.issue.IssueManager; import com.atlassian.jira.issue.MutableIssue; import com.atlassian.jira.project.Project; import com.atlassian.jira.project.ProjectManager; import com.atlassian.jira.project.browse.BrowseContext; import minhhai2209.jirapluginconverter.utils.ExceptionUtils; import org.apache.commons.lang.text.StrSubstitutor; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; import javax.servlet.http.HttpServletRequest; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; Issue issue = (Issue) o; acContext.put("issue.key", issue.getKey()); acContext.put("issue.id", issue.getId().toString()); acContext.put("issuetype.id", issue.getIssueTypeId()); } } o = contextParams.get("project"); if (o != null) { if (o instanceof Project) { Project project = (Project) o; acContext.put("project.key", project.getKey()); acContext.put("project.id", project.getId().toString()); } } o = contextParams.get("postFunctionId"); if (o != null) { acContext.put("postFunction.id", (String) o); } o = contextParams.get("postFunctionConfig"); if (o != null) { acContext.put("postFunction.config", URLEncoder.encode((String) o, "UTF-8")); } else { acContext.put("postFunction.config", ""); } } catch (Exception e) {
ExceptionUtils.throwUnchecked(e);
minhhai2209/jira-plugin-converter
src/main/java/minhhai2209/jirapluginconverter/plugin/setting/WebItemUtils.java
// Path: src/main/java/minhhai2209/jirapluginconverter/connect/descriptor/webitem/WebItemTarget.java // @JsonIgnoreProperties(ignoreUnknown=true) // public class WebItemTarget { // // public static enum Type { // PAGE, DIALOG, INLINEDIALOG, page, dialog, inlinedialog; // } // // private Type type; // // private Map<String, Object> options; // // public Type getType() { // return type; // } // // public void setType(Type type) { // this.type = type; // } // // public Map<String, Object> getOptions() { // return options; // } // // public void setOptions(Map<String, Object> options) { // this.options = options; // } // // } // // Path: src/main/java/minhhai2209/jirapluginconverter/connect/descriptor/webitem/WebItemTarget.java // public static enum Type { // PAGE, DIALOG, INLINEDIALOG, page, dialog, inlinedialog; // } // // Path: src/main/java/minhhai2209/jirapluginconverter/plugin/utils/EnumUtils.java // public class EnumUtils { // // public static boolean equals(Enum<?> left, Enum<?> right) { // return left.name().equalsIgnoreCase(right.name()); // } // }
import java.util.HashMap; import java.util.List; import java.util.Map; import minhhai2209.jirapluginconverter.connect.descriptor.Context; import minhhai2209.jirapluginconverter.connect.descriptor.Modules; import minhhai2209.jirapluginconverter.connect.descriptor.webitem.WebItem; import minhhai2209.jirapluginconverter.connect.descriptor.webitem.WebItemTarget; import minhhai2209.jirapluginconverter.connect.descriptor.webitem.WebItemTarget.Type; import minhhai2209.jirapluginconverter.plugin.utils.EnumUtils;
package minhhai2209.jirapluginconverter.plugin.setting; public class WebItemUtils { private static Map<String, WebItem> webItemLookup; public static void buildWebItemLookup() { Modules modules = PluginSetting.getModules(); List<WebItem> webItems = modules.getWebItems(); webItemLookup = new HashMap<String, WebItem>(); if (webItems != null) { for (WebItem webItem : webItems) { String key = webItem.getKey(); webItemLookup.put(key, webItem); } } } public static String getFullUrl(WebItem webItem) { String webItemUrl = webItem.getUrl(); if (webItemUrl.startsWith("http://") || webItemUrl.startsWith("https://")) { return webItemUrl; } Context context = webItem.getContext(); if (context == null) { context = Context.addon; }
// Path: src/main/java/minhhai2209/jirapluginconverter/connect/descriptor/webitem/WebItemTarget.java // @JsonIgnoreProperties(ignoreUnknown=true) // public class WebItemTarget { // // public static enum Type { // PAGE, DIALOG, INLINEDIALOG, page, dialog, inlinedialog; // } // // private Type type; // // private Map<String, Object> options; // // public Type getType() { // return type; // } // // public void setType(Type type) { // this.type = type; // } // // public Map<String, Object> getOptions() { // return options; // } // // public void setOptions(Map<String, Object> options) { // this.options = options; // } // // } // // Path: src/main/java/minhhai2209/jirapluginconverter/connect/descriptor/webitem/WebItemTarget.java // public static enum Type { // PAGE, DIALOG, INLINEDIALOG, page, dialog, inlinedialog; // } // // Path: src/main/java/minhhai2209/jirapluginconverter/plugin/utils/EnumUtils.java // public class EnumUtils { // // public static boolean equals(Enum<?> left, Enum<?> right) { // return left.name().equalsIgnoreCase(right.name()); // } // } // Path: src/main/java/minhhai2209/jirapluginconverter/plugin/setting/WebItemUtils.java import java.util.HashMap; import java.util.List; import java.util.Map; import minhhai2209.jirapluginconverter.connect.descriptor.Context; import minhhai2209.jirapluginconverter.connect.descriptor.Modules; import minhhai2209.jirapluginconverter.connect.descriptor.webitem.WebItem; import minhhai2209.jirapluginconverter.connect.descriptor.webitem.WebItemTarget; import minhhai2209.jirapluginconverter.connect.descriptor.webitem.WebItemTarget.Type; import minhhai2209.jirapluginconverter.plugin.utils.EnumUtils; package minhhai2209.jirapluginconverter.plugin.setting; public class WebItemUtils { private static Map<String, WebItem> webItemLookup; public static void buildWebItemLookup() { Modules modules = PluginSetting.getModules(); List<WebItem> webItems = modules.getWebItems(); webItemLookup = new HashMap<String, WebItem>(); if (webItems != null) { for (WebItem webItem : webItems) { String key = webItem.getKey(); webItemLookup.put(key, webItem); } } } public static String getFullUrl(WebItem webItem) { String webItemUrl = webItem.getUrl(); if (webItemUrl.startsWith("http://") || webItemUrl.startsWith("https://")) { return webItemUrl; } Context context = webItem.getContext(); if (context == null) { context = Context.addon; }
WebItemTarget target = webItem.getTarget();
minhhai2209/jira-plugin-converter
src/main/java/minhhai2209/jirapluginconverter/plugin/setting/WebItemUtils.java
// Path: src/main/java/minhhai2209/jirapluginconverter/connect/descriptor/webitem/WebItemTarget.java // @JsonIgnoreProperties(ignoreUnknown=true) // public class WebItemTarget { // // public static enum Type { // PAGE, DIALOG, INLINEDIALOG, page, dialog, inlinedialog; // } // // private Type type; // // private Map<String, Object> options; // // public Type getType() { // return type; // } // // public void setType(Type type) { // this.type = type; // } // // public Map<String, Object> getOptions() { // return options; // } // // public void setOptions(Map<String, Object> options) { // this.options = options; // } // // } // // Path: src/main/java/minhhai2209/jirapluginconverter/connect/descriptor/webitem/WebItemTarget.java // public static enum Type { // PAGE, DIALOG, INLINEDIALOG, page, dialog, inlinedialog; // } // // Path: src/main/java/minhhai2209/jirapluginconverter/plugin/utils/EnumUtils.java // public class EnumUtils { // // public static boolean equals(Enum<?> left, Enum<?> right) { // return left.name().equalsIgnoreCase(right.name()); // } // }
import java.util.HashMap; import java.util.List; import java.util.Map; import minhhai2209.jirapluginconverter.connect.descriptor.Context; import minhhai2209.jirapluginconverter.connect.descriptor.Modules; import minhhai2209.jirapluginconverter.connect.descriptor.webitem.WebItem; import minhhai2209.jirapluginconverter.connect.descriptor.webitem.WebItemTarget; import minhhai2209.jirapluginconverter.connect.descriptor.webitem.WebItemTarget.Type; import minhhai2209.jirapluginconverter.plugin.utils.EnumUtils;
package minhhai2209.jirapluginconverter.plugin.setting; public class WebItemUtils { private static Map<String, WebItem> webItemLookup; public static void buildWebItemLookup() { Modules modules = PluginSetting.getModules(); List<WebItem> webItems = modules.getWebItems(); webItemLookup = new HashMap<String, WebItem>(); if (webItems != null) { for (WebItem webItem : webItems) { String key = webItem.getKey(); webItemLookup.put(key, webItem); } } } public static String getFullUrl(WebItem webItem) { String webItemUrl = webItem.getUrl(); if (webItemUrl.startsWith("http://") || webItemUrl.startsWith("https://")) { return webItemUrl; } Context context = webItem.getContext(); if (context == null) { context = Context.addon; } WebItemTarget target = webItem.getTarget();
// Path: src/main/java/minhhai2209/jirapluginconverter/connect/descriptor/webitem/WebItemTarget.java // @JsonIgnoreProperties(ignoreUnknown=true) // public class WebItemTarget { // // public static enum Type { // PAGE, DIALOG, INLINEDIALOG, page, dialog, inlinedialog; // } // // private Type type; // // private Map<String, Object> options; // // public Type getType() { // return type; // } // // public void setType(Type type) { // this.type = type; // } // // public Map<String, Object> getOptions() { // return options; // } // // public void setOptions(Map<String, Object> options) { // this.options = options; // } // // } // // Path: src/main/java/minhhai2209/jirapluginconverter/connect/descriptor/webitem/WebItemTarget.java // public static enum Type { // PAGE, DIALOG, INLINEDIALOG, page, dialog, inlinedialog; // } // // Path: src/main/java/minhhai2209/jirapluginconverter/plugin/utils/EnumUtils.java // public class EnumUtils { // // public static boolean equals(Enum<?> left, Enum<?> right) { // return left.name().equalsIgnoreCase(right.name()); // } // } // Path: src/main/java/minhhai2209/jirapluginconverter/plugin/setting/WebItemUtils.java import java.util.HashMap; import java.util.List; import java.util.Map; import minhhai2209.jirapluginconverter.connect.descriptor.Context; import minhhai2209.jirapluginconverter.connect.descriptor.Modules; import minhhai2209.jirapluginconverter.connect.descriptor.webitem.WebItem; import minhhai2209.jirapluginconverter.connect.descriptor.webitem.WebItemTarget; import minhhai2209.jirapluginconverter.connect.descriptor.webitem.WebItemTarget.Type; import minhhai2209.jirapluginconverter.plugin.utils.EnumUtils; package minhhai2209.jirapluginconverter.plugin.setting; public class WebItemUtils { private static Map<String, WebItem> webItemLookup; public static void buildWebItemLookup() { Modules modules = PluginSetting.getModules(); List<WebItem> webItems = modules.getWebItems(); webItemLookup = new HashMap<String, WebItem>(); if (webItems != null) { for (WebItem webItem : webItems) { String key = webItem.getKey(); webItemLookup.put(key, webItem); } } } public static String getFullUrl(WebItem webItem) { String webItemUrl = webItem.getUrl(); if (webItemUrl.startsWith("http://") || webItemUrl.startsWith("https://")) { return webItemUrl; } Context context = webItem.getContext(); if (context == null) { context = Context.addon; } WebItemTarget target = webItem.getTarget();
Type type;
minhhai2209/jira-plugin-converter
src/main/java/minhhai2209/jirapluginconverter/plugin/setting/WebItemUtils.java
// Path: src/main/java/minhhai2209/jirapluginconverter/connect/descriptor/webitem/WebItemTarget.java // @JsonIgnoreProperties(ignoreUnknown=true) // public class WebItemTarget { // // public static enum Type { // PAGE, DIALOG, INLINEDIALOG, page, dialog, inlinedialog; // } // // private Type type; // // private Map<String, Object> options; // // public Type getType() { // return type; // } // // public void setType(Type type) { // this.type = type; // } // // public Map<String, Object> getOptions() { // return options; // } // // public void setOptions(Map<String, Object> options) { // this.options = options; // } // // } // // Path: src/main/java/minhhai2209/jirapluginconverter/connect/descriptor/webitem/WebItemTarget.java // public static enum Type { // PAGE, DIALOG, INLINEDIALOG, page, dialog, inlinedialog; // } // // Path: src/main/java/minhhai2209/jirapluginconverter/plugin/utils/EnumUtils.java // public class EnumUtils { // // public static boolean equals(Enum<?> left, Enum<?> right) { // return left.name().equalsIgnoreCase(right.name()); // } // }
import java.util.HashMap; import java.util.List; import java.util.Map; import minhhai2209.jirapluginconverter.connect.descriptor.Context; import minhhai2209.jirapluginconverter.connect.descriptor.Modules; import minhhai2209.jirapluginconverter.connect.descriptor.webitem.WebItem; import minhhai2209.jirapluginconverter.connect.descriptor.webitem.WebItemTarget; import minhhai2209.jirapluginconverter.connect.descriptor.webitem.WebItemTarget.Type; import minhhai2209.jirapluginconverter.plugin.utils.EnumUtils;
List<WebItem> webItems = modules.getWebItems(); webItemLookup = new HashMap<String, WebItem>(); if (webItems != null) { for (WebItem webItem : webItems) { String key = webItem.getKey(); webItemLookup.put(key, webItem); } } } public static String getFullUrl(WebItem webItem) { String webItemUrl = webItem.getUrl(); if (webItemUrl.startsWith("http://") || webItemUrl.startsWith("https://")) { return webItemUrl; } Context context = webItem.getContext(); if (context == null) { context = Context.addon; } WebItemTarget target = webItem.getTarget(); Type type; if (target == null) { type = Type.page; } else { type = target.getType(); } if (type == null) { type = Type.page; } String baseUrl;
// Path: src/main/java/minhhai2209/jirapluginconverter/connect/descriptor/webitem/WebItemTarget.java // @JsonIgnoreProperties(ignoreUnknown=true) // public class WebItemTarget { // // public static enum Type { // PAGE, DIALOG, INLINEDIALOG, page, dialog, inlinedialog; // } // // private Type type; // // private Map<String, Object> options; // // public Type getType() { // return type; // } // // public void setType(Type type) { // this.type = type; // } // // public Map<String, Object> getOptions() { // return options; // } // // public void setOptions(Map<String, Object> options) { // this.options = options; // } // // } // // Path: src/main/java/minhhai2209/jirapluginconverter/connect/descriptor/webitem/WebItemTarget.java // public static enum Type { // PAGE, DIALOG, INLINEDIALOG, page, dialog, inlinedialog; // } // // Path: src/main/java/minhhai2209/jirapluginconverter/plugin/utils/EnumUtils.java // public class EnumUtils { // // public static boolean equals(Enum<?> left, Enum<?> right) { // return left.name().equalsIgnoreCase(right.name()); // } // } // Path: src/main/java/minhhai2209/jirapluginconverter/plugin/setting/WebItemUtils.java import java.util.HashMap; import java.util.List; import java.util.Map; import minhhai2209.jirapluginconverter.connect.descriptor.Context; import minhhai2209.jirapluginconverter.connect.descriptor.Modules; import minhhai2209.jirapluginconverter.connect.descriptor.webitem.WebItem; import minhhai2209.jirapluginconverter.connect.descriptor.webitem.WebItemTarget; import minhhai2209.jirapluginconverter.connect.descriptor.webitem.WebItemTarget.Type; import minhhai2209.jirapluginconverter.plugin.utils.EnumUtils; List<WebItem> webItems = modules.getWebItems(); webItemLookup = new HashMap<String, WebItem>(); if (webItems != null) { for (WebItem webItem : webItems) { String key = webItem.getKey(); webItemLookup.put(key, webItem); } } } public static String getFullUrl(WebItem webItem) { String webItemUrl = webItem.getUrl(); if (webItemUrl.startsWith("http://") || webItemUrl.startsWith("https://")) { return webItemUrl; } Context context = webItem.getContext(); if (context == null) { context = Context.addon; } WebItemTarget target = webItem.getTarget(); Type type; if (target == null) { type = Type.page; } else { type = target.getType(); } if (type == null) { type = Type.page; } String baseUrl;
if (EnumUtils.equals(type, Type.page)) {
minhhai2209/jira-plugin-converter
src/main/java/minhhai2209/jirapluginconverter/plugin/jwt/JwtComposer.java
// Path: src/main/java/minhhai2209/jirapluginconverter/utils/ExceptionUtils.java // public class ExceptionUtils { // // public static void throwUnchecked(Exception e) { // throw new IllegalStateException(e); // } // // public static String getStackTrace(Exception e) { // return Throwables.getStackTraceAsString(e); // } // }
import com.atlassian.jwt.SigningAlgorithm; import com.atlassian.jwt.core.writer.JsonSmartJwtJsonBuilder; import com.atlassian.jwt.core.writer.JwtClaimsBuilder; import com.atlassian.jwt.core.writer.NimbusJwtWriterFactory; import com.atlassian.jwt.httpclient.CanonicalHttpUriRequest; import com.atlassian.jwt.writer.JwtJsonBuilder; import com.atlassian.jwt.writer.JwtWriter; import com.atlassian.jwt.writer.JwtWriterFactory; import minhhai2209.jirapluginconverter.utils.ExceptionUtils; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URIBuilder; import java.util.List; import java.util.Map;
package minhhai2209.jirapluginconverter.plugin.jwt; public class JwtComposer { public static String compose( String key, String sharedSecret, String method, String apiPath, List<NameValuePair> pairs, JwtContext context) { try { long issuedAt = System.currentTimeMillis() / 1000L; long expiresAt = issuedAt + 1800L; JwtJsonBuilder jwtJsonBuilder = new JsonSmartJwtJsonBuilder() .issuedAt(issuedAt) .expirationTime(expiresAt) .issuer(key) .claim("context", context); Map<String, List<String>> parameters = JwtHelper.getParameters(pairs); Map<String, String[]> parameterMap = JwtHelper.getParameterMap(parameters); CanonicalHttpUriRequest canonicalHttpUrlRequest = new CanonicalHttpUriRequest(method, apiPath, null, parameterMap); JwtClaimsBuilder.appendHttpRequestClaims(jwtJsonBuilder, canonicalHttpUrlRequest); JwtWriterFactory jwtWriterFactory = new NimbusJwtWriterFactory(); String unsignedJwt = jwtJsonBuilder.build(); JwtWriter macSigningWriter = jwtWriterFactory.macSigningWriter(SigningAlgorithm.HS256, sharedSecret); String jwt = macSigningWriter.jsonToJwt(unsignedJwt); return jwt; } catch (Exception e) {
// Path: src/main/java/minhhai2209/jirapluginconverter/utils/ExceptionUtils.java // public class ExceptionUtils { // // public static void throwUnchecked(Exception e) { // throw new IllegalStateException(e); // } // // public static String getStackTrace(Exception e) { // return Throwables.getStackTraceAsString(e); // } // } // Path: src/main/java/minhhai2209/jirapluginconverter/plugin/jwt/JwtComposer.java import com.atlassian.jwt.SigningAlgorithm; import com.atlassian.jwt.core.writer.JsonSmartJwtJsonBuilder; import com.atlassian.jwt.core.writer.JwtClaimsBuilder; import com.atlassian.jwt.core.writer.NimbusJwtWriterFactory; import com.atlassian.jwt.httpclient.CanonicalHttpUriRequest; import com.atlassian.jwt.writer.JwtJsonBuilder; import com.atlassian.jwt.writer.JwtWriter; import com.atlassian.jwt.writer.JwtWriterFactory; import minhhai2209.jirapluginconverter.utils.ExceptionUtils; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URIBuilder; import java.util.List; import java.util.Map; package minhhai2209.jirapluginconverter.plugin.jwt; public class JwtComposer { public static String compose( String key, String sharedSecret, String method, String apiPath, List<NameValuePair> pairs, JwtContext context) { try { long issuedAt = System.currentTimeMillis() / 1000L; long expiresAt = issuedAt + 1800L; JwtJsonBuilder jwtJsonBuilder = new JsonSmartJwtJsonBuilder() .issuedAt(issuedAt) .expirationTime(expiresAt) .issuer(key) .claim("context", context); Map<String, List<String>> parameters = JwtHelper.getParameters(pairs); Map<String, String[]> parameterMap = JwtHelper.getParameterMap(parameters); CanonicalHttpUriRequest canonicalHttpUrlRequest = new CanonicalHttpUriRequest(method, apiPath, null, parameterMap); JwtClaimsBuilder.appendHttpRequestClaims(jwtJsonBuilder, canonicalHttpUrlRequest); JwtWriterFactory jwtWriterFactory = new NimbusJwtWriterFactory(); String unsignedJwt = jwtJsonBuilder.build(); JwtWriter macSigningWriter = jwtWriterFactory.macSigningWriter(SigningAlgorithm.HS256, sharedSecret); String jwt = macSigningWriter.jsonToJwt(unsignedJwt); return jwt; } catch (Exception e) {
ExceptionUtils.throwUnchecked(e);
minhhai2209/jira-plugin-converter
src/main/java/minhhai2209/jirapluginconverter/converter/descriptor/WebPanelConverter.java
// Path: src/main/java/minhhai2209/jirapluginconverter/connect/descriptor/webpanel/WebPanel.java // public class WebPanel extends AbstractModule { // private Map<String, String> params; // private int weight = 100; // private WebPanelLayout layout; // protected String url; // private I18nProperty tooltip; // // public Map<String, String> getParams() { // return params; // } // public void setParams(Map<String, String> params) { // this.params = params; // } // public int getWeight() { // return weight; // } // public void setWeight(int weight) { // this.weight = weight; // } // public WebPanelLayout getLayout() { // return layout; // } // public void setLayout(WebPanelLayout layout) { // this.layout = layout; // } // public String getUrl() { // return url; // } // public void setUrl(String url) { // this.url = url; // } // public I18nProperty getTooltip() { // return tooltip; // } // public void setTooltip(I18nProperty tooltip) { // this.tooltip = tooltip; // } // } // // Path: src/main/java/minhhai2209/jirapluginconverter/plugin/descriptor/Resource.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // public class Resource { // // @XmlAttribute // protected String name; // @XmlAttribute // protected String namePattern; // @XmlAttribute // protected String type; // @XmlAttribute // protected String location; // // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // public String getNamePattern() { // return namePattern; // } // public void setNamePattern(String namePattern) { // this.namePattern = namePattern; // } // public String getType() { // return type; // } // public void setType(String type) { // this.type = type; // } // public String getLocation() { // return location; // } // public void setLocation(String location) { // this.location = location; // } // } // // Path: src/main/java/minhhai2209/jirapluginconverter/plugin/descriptor/WebPanelModule.java // @XmlRootElement(name="web-panel") // @XmlAccessorType(XmlAccessType.FIELD) // public class WebPanelModule { // // @XmlAttribute // private String clazz; // @XmlAttribute(required=true) // private String key; // @XmlAttribute // private String name; // @XmlAttribute // private int weight; // @XmlAttribute(required=true) // private String location; // // @XmlElement(required=true) // private Label label = new Label(); // // @XmlElement // private Resource resource; // // private Condition condition; // private Conditions conditions; // // public String getClazz() { // return clazz; // } // // public void setClazz(String clazz) { // this.clazz = clazz; // } // // public String getKey() { // return key; // } // // public void setKey(String key) { // this.key = key; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getWeight() { // return weight; // } // // public void setWeight(int weight) { // this.weight = weight; // } // // public String getLocation() { // return location; // } // // public void setLocation(String location) { // this.location = location; // } // // public String getLabel() { // return this.label.getKey(); // } // // public void setLabel(String label) { // this.label.setKey(label);; // } // // public Condition getCondition() { // return condition; // } // // public void setCondition(Condition condition) { // this.condition = condition; // } // // public Conditions getConditions() { // return conditions; // } // // public void setConditions(Conditions conditions) { // this.conditions = conditions; // } // // public Resource getResource() { // return resource; // } // // public void setResource(Resource resource) { // this.resource = resource; // } // }
import java.util.List; import minhhai2209.jirapluginconverter.connect.descriptor.Modules; import minhhai2209.jirapluginconverter.connect.descriptor.condition.ConditionWrapper; import minhhai2209.jirapluginconverter.connect.descriptor.webpanel.WebPanel; import minhhai2209.jirapluginconverter.plugin.descriptor.Condition; import minhhai2209.jirapluginconverter.plugin.descriptor.Conditions; import minhhai2209.jirapluginconverter.plugin.descriptor.Conditions.Type; import minhhai2209.jirapluginconverter.plugin.descriptor.DefaultWebPanelResource; import minhhai2209.jirapluginconverter.plugin.descriptor.Resource; import minhhai2209.jirapluginconverter.plugin.descriptor.WebPanelModule;
package minhhai2209.jirapluginconverter.converter.descriptor; public class WebPanelConverter extends ModuleConverter<WebPanelModule, WebPanel>{ private ConditionConverter conditionConverter = new ConditionConverter(); @Override public WebPanelModule toPluginModule(WebPanel webPanel, Modules modules) { WebPanelModule module = new WebPanelModule(); module.setKey(webPanel.getKey()); module.setLabel(webPanel.getName().getValue()); module.setLocation(webPanel.getLocation()); module.setWeight(webPanel.getWeight());
// Path: src/main/java/minhhai2209/jirapluginconverter/connect/descriptor/webpanel/WebPanel.java // public class WebPanel extends AbstractModule { // private Map<String, String> params; // private int weight = 100; // private WebPanelLayout layout; // protected String url; // private I18nProperty tooltip; // // public Map<String, String> getParams() { // return params; // } // public void setParams(Map<String, String> params) { // this.params = params; // } // public int getWeight() { // return weight; // } // public void setWeight(int weight) { // this.weight = weight; // } // public WebPanelLayout getLayout() { // return layout; // } // public void setLayout(WebPanelLayout layout) { // this.layout = layout; // } // public String getUrl() { // return url; // } // public void setUrl(String url) { // this.url = url; // } // public I18nProperty getTooltip() { // return tooltip; // } // public void setTooltip(I18nProperty tooltip) { // this.tooltip = tooltip; // } // } // // Path: src/main/java/minhhai2209/jirapluginconverter/plugin/descriptor/Resource.java // @XmlRootElement // @XmlAccessorType(XmlAccessType.FIELD) // public class Resource { // // @XmlAttribute // protected String name; // @XmlAttribute // protected String namePattern; // @XmlAttribute // protected String type; // @XmlAttribute // protected String location; // // public String getName() { // return name; // } // public void setName(String name) { // this.name = name; // } // public String getNamePattern() { // return namePattern; // } // public void setNamePattern(String namePattern) { // this.namePattern = namePattern; // } // public String getType() { // return type; // } // public void setType(String type) { // this.type = type; // } // public String getLocation() { // return location; // } // public void setLocation(String location) { // this.location = location; // } // } // // Path: src/main/java/minhhai2209/jirapluginconverter/plugin/descriptor/WebPanelModule.java // @XmlRootElement(name="web-panel") // @XmlAccessorType(XmlAccessType.FIELD) // public class WebPanelModule { // // @XmlAttribute // private String clazz; // @XmlAttribute(required=true) // private String key; // @XmlAttribute // private String name; // @XmlAttribute // private int weight; // @XmlAttribute(required=true) // private String location; // // @XmlElement(required=true) // private Label label = new Label(); // // @XmlElement // private Resource resource; // // private Condition condition; // private Conditions conditions; // // public String getClazz() { // return clazz; // } // // public void setClazz(String clazz) { // this.clazz = clazz; // } // // public String getKey() { // return key; // } // // public void setKey(String key) { // this.key = key; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getWeight() { // return weight; // } // // public void setWeight(int weight) { // this.weight = weight; // } // // public String getLocation() { // return location; // } // // public void setLocation(String location) { // this.location = location; // } // // public String getLabel() { // return this.label.getKey(); // } // // public void setLabel(String label) { // this.label.setKey(label);; // } // // public Condition getCondition() { // return condition; // } // // public void setCondition(Condition condition) { // this.condition = condition; // } // // public Conditions getConditions() { // return conditions; // } // // public void setConditions(Conditions conditions) { // this.conditions = conditions; // } // // public Resource getResource() { // return resource; // } // // public void setResource(Resource resource) { // this.resource = resource; // } // } // Path: src/main/java/minhhai2209/jirapluginconverter/converter/descriptor/WebPanelConverter.java import java.util.List; import minhhai2209.jirapluginconverter.connect.descriptor.Modules; import minhhai2209.jirapluginconverter.connect.descriptor.condition.ConditionWrapper; import minhhai2209.jirapluginconverter.connect.descriptor.webpanel.WebPanel; import minhhai2209.jirapluginconverter.plugin.descriptor.Condition; import minhhai2209.jirapluginconverter.plugin.descriptor.Conditions; import minhhai2209.jirapluginconverter.plugin.descriptor.Conditions.Type; import minhhai2209.jirapluginconverter.plugin.descriptor.DefaultWebPanelResource; import minhhai2209.jirapluginconverter.plugin.descriptor.Resource; import minhhai2209.jirapluginconverter.plugin.descriptor.WebPanelModule; package minhhai2209.jirapluginconverter.converter.descriptor; public class WebPanelConverter extends ModuleConverter<WebPanelModule, WebPanel>{ private ConditionConverter conditionConverter = new ConditionConverter(); @Override public WebPanelModule toPluginModule(WebPanel webPanel, Modules modules) { WebPanelModule module = new WebPanelModule(); module.setKey(webPanel.getKey()); module.setLabel(webPanel.getName().getValue()); module.setLocation(webPanel.getLocation()); module.setWeight(webPanel.getWeight());
Resource resource = new DefaultWebPanelResource(webPanel.getKey());
minhhai2209/jira-plugin-converter
src/main/java/minhhai2209/jirapluginconverter/plugin/setting/LifeCycleUtils.java
// Path: src/main/java/minhhai2209/jirapluginconverter/connect/descriptor/LifeCycle.java // public class LifeCycle { // // private String installed; // // private String uninstalled; // // private String enabled; // // private String disabled; // // public String getInstalled() { // return installed; // } // // public void setInstalled(String installed) { // this.installed = installed; // } // // public String getUninstalled() { // return uninstalled; // } // // public void setUninstalled(String uninstalled) { // this.uninstalled = uninstalled; // } // // public String getEnabled() { // return enabled; // } // // public void setEnabled(String enabled) { // this.enabled = enabled; // } // // public String getDisabled() { // return disabled; // } // // public void setDisabled(String disabled) { // this.disabled = disabled; // } // // }
import minhhai2209.jirapluginconverter.connect.descriptor.LifeCycle;
package minhhai2209.jirapluginconverter.plugin.setting; public class LifeCycleUtils { public static String getInstalledUri() {
// Path: src/main/java/minhhai2209/jirapluginconverter/connect/descriptor/LifeCycle.java // public class LifeCycle { // // private String installed; // // private String uninstalled; // // private String enabled; // // private String disabled; // // public String getInstalled() { // return installed; // } // // public void setInstalled(String installed) { // this.installed = installed; // } // // public String getUninstalled() { // return uninstalled; // } // // public void setUninstalled(String uninstalled) { // this.uninstalled = uninstalled; // } // // public String getEnabled() { // return enabled; // } // // public void setEnabled(String enabled) { // this.enabled = enabled; // } // // public String getDisabled() { // return disabled; // } // // public void setDisabled(String disabled) { // this.disabled = disabled; // } // // } // Path: src/main/java/minhhai2209/jirapluginconverter/plugin/setting/LifeCycleUtils.java import minhhai2209.jirapluginconverter.connect.descriptor.LifeCycle; package minhhai2209.jirapluginconverter.plugin.setting; public class LifeCycleUtils { public static String getInstalledUri() {
LifeCycle lifeCycle = PluginSetting.getDescriptor().getLifecycle();
minhhai2209/jira-plugin-converter
src/main/java/minhhai2209/jirapluginconverter/plugin/utils/RequestUtils.java
// Path: src/main/java/minhhai2209/jirapluginconverter/plugin/setting/PluginSetting.java // public class PluginSetting { // // // public static final String ARTIFACT_ID = "generated_artifact_id"; // // // public static final String PLUGIN_KEY = ARTIFACT_ID; // // private static Descriptor descriptor; // // private static com.atlassian.plugin.Plugin jiraPlugin; // // private static PluginSettingsFactory pluginSettingsFactory; // // private static TransactionTemplate transactionTemplate; // // public static void load( // PluginSettingsFactory pluginSettingsFactory, // TransactionTemplate transactionTemplate, // PluginLicenseManager pluginLicenseManager, // ConsumerService consumerService) throws Exception { // // PluginSetting.pluginSettingsFactory = pluginSettingsFactory; // PluginSetting.transactionTemplate = transactionTemplate; // // LicenseUtils.setPluginLicenseManager(pluginLicenseManager); // KeyUtils.loadJiraConsumer(consumerService); // KeyUtils.loadSharedSecret(pluginSettingsFactory); // } // // public static void readDescriptor() { // InputStream is = null; // try { // is = PluginSetting.class.getResourceAsStream("/imported_atlas_connect_descriptor.json"); // String descriptorString = IOUtils.toString(is); // descriptor = JsonUtils.fromJson(descriptorString, Descriptor.class); // WebItemUtils.buildWebItemLookup(); // WebPanelUtils.buildWebPanelLookup(); // PageUtils.buildGeneralPageLookup(); // PageUtils.buildAdminPageLookup(); // PageUtils.buildConfigurePageLookup(); // IssueTabPanelUtils.buildJiraIssueTabPanelLookup(); // ProjectTabPanelUtils.buildProjectTabPanelLookup(); // WorkflowPostFunctionUtils.buildWorkflowPostFunctionLookup(); // } catch (Exception e1) { // if (is != null) { // try { // is.close(); // } catch (Exception e2) { // ExceptionUtils.throwUnchecked(e2); // } // } // ExceptionUtils.throwUnchecked(e1); // } // } // // public static Descriptor getDescriptor() { // return descriptor; // } // // public static String getPluginBaseUrl() { // String baseUrl = transactionTemplate.execute(new TransactionCallback<String>() { // // @Override // public String doInTransaction() { // PluginSettings settings = pluginSettingsFactory.createGlobalSettings(); // String url = (String) settings.get(ConfigurePluginServlet.DB_URL); // return url; // } // // }); // if (baseUrl == null) { // baseUrl = descriptor.getBaseUrl(); // } // String jiraUrl = JiraUtils.getBaseUrl(); // if (jiraUrl.startsWith("http:") && baseUrl.startsWith("https:")) { // baseUrl = baseUrl.replace("https:", "http:"); // } else if (jiraUrl.startsWith("https:")) { // baseUrl = baseUrl.replace("http:", "https:"); // } // return baseUrl; // } // // public static Modules getModules() { // return descriptor.getModules(); // } // // public static Plugin getPlugin() { // Plugin plugin = new Plugin(); // plugin.setName(descriptor.getName()); // plugin.setBaseUrl(getPluginBaseUrl()); // return plugin; // } // // public static com.atlassian.plugin.Plugin getJiraPlugin() { // return jiraPlugin; // } // // public static void setJiraPlugin(com.atlassian.plugin.Plugin jiraPlugin) { // PluginSetting.jiraPlugin = jiraPlugin; // } // // public static ApplicationUser getPluginUser() { // String userKey = transactionTemplate.execute(new TransactionCallback<String>() { // @Override // public String doInTransaction() { // // PluginSettings settings = pluginSettingsFactory.createGlobalSettings(); // String userKey = (String) settings.get(ConfigurePluginServlet.DB_USER); // return userKey; // } // }); // ApplicationUser user; // UserUtil userUtil = ComponentAccessor.getUserUtil(); // if (userKey != null) { // user = userUtil.getUserByKey(userKey); // } else { // Collection<User> admins = userUtil.getJiraAdministrators(); // User admin = Iterables.get(admins, 0); // String adminName = admin.getName(); // user = userUtil.getUserByName(adminName); // } // return user; // } // }
import minhhai2209.jirapluginconverter.plugin.setting.PluginSetting; import org.apache.commons.lang3.StringUtils; import javax.servlet.http.HttpServletRequest;
package minhhai2209.jirapluginconverter.plugin.utils; public class RequestUtils { public static String getModuleKey(HttpServletRequest request) { String servletPath = request.getServletPath(); String requestUrl = request.getRequestURL().toString(); String path = StringUtils.substringAfter(requestUrl, servletPath + "/");
// Path: src/main/java/minhhai2209/jirapluginconverter/plugin/setting/PluginSetting.java // public class PluginSetting { // // // public static final String ARTIFACT_ID = "generated_artifact_id"; // // // public static final String PLUGIN_KEY = ARTIFACT_ID; // // private static Descriptor descriptor; // // private static com.atlassian.plugin.Plugin jiraPlugin; // // private static PluginSettingsFactory pluginSettingsFactory; // // private static TransactionTemplate transactionTemplate; // // public static void load( // PluginSettingsFactory pluginSettingsFactory, // TransactionTemplate transactionTemplate, // PluginLicenseManager pluginLicenseManager, // ConsumerService consumerService) throws Exception { // // PluginSetting.pluginSettingsFactory = pluginSettingsFactory; // PluginSetting.transactionTemplate = transactionTemplate; // // LicenseUtils.setPluginLicenseManager(pluginLicenseManager); // KeyUtils.loadJiraConsumer(consumerService); // KeyUtils.loadSharedSecret(pluginSettingsFactory); // } // // public static void readDescriptor() { // InputStream is = null; // try { // is = PluginSetting.class.getResourceAsStream("/imported_atlas_connect_descriptor.json"); // String descriptorString = IOUtils.toString(is); // descriptor = JsonUtils.fromJson(descriptorString, Descriptor.class); // WebItemUtils.buildWebItemLookup(); // WebPanelUtils.buildWebPanelLookup(); // PageUtils.buildGeneralPageLookup(); // PageUtils.buildAdminPageLookup(); // PageUtils.buildConfigurePageLookup(); // IssueTabPanelUtils.buildJiraIssueTabPanelLookup(); // ProjectTabPanelUtils.buildProjectTabPanelLookup(); // WorkflowPostFunctionUtils.buildWorkflowPostFunctionLookup(); // } catch (Exception e1) { // if (is != null) { // try { // is.close(); // } catch (Exception e2) { // ExceptionUtils.throwUnchecked(e2); // } // } // ExceptionUtils.throwUnchecked(e1); // } // } // // public static Descriptor getDescriptor() { // return descriptor; // } // // public static String getPluginBaseUrl() { // String baseUrl = transactionTemplate.execute(new TransactionCallback<String>() { // // @Override // public String doInTransaction() { // PluginSettings settings = pluginSettingsFactory.createGlobalSettings(); // String url = (String) settings.get(ConfigurePluginServlet.DB_URL); // return url; // } // // }); // if (baseUrl == null) { // baseUrl = descriptor.getBaseUrl(); // } // String jiraUrl = JiraUtils.getBaseUrl(); // if (jiraUrl.startsWith("http:") && baseUrl.startsWith("https:")) { // baseUrl = baseUrl.replace("https:", "http:"); // } else if (jiraUrl.startsWith("https:")) { // baseUrl = baseUrl.replace("http:", "https:"); // } // return baseUrl; // } // // public static Modules getModules() { // return descriptor.getModules(); // } // // public static Plugin getPlugin() { // Plugin plugin = new Plugin(); // plugin.setName(descriptor.getName()); // plugin.setBaseUrl(getPluginBaseUrl()); // return plugin; // } // // public static com.atlassian.plugin.Plugin getJiraPlugin() { // return jiraPlugin; // } // // public static void setJiraPlugin(com.atlassian.plugin.Plugin jiraPlugin) { // PluginSetting.jiraPlugin = jiraPlugin; // } // // public static ApplicationUser getPluginUser() { // String userKey = transactionTemplate.execute(new TransactionCallback<String>() { // @Override // public String doInTransaction() { // // PluginSettings settings = pluginSettingsFactory.createGlobalSettings(); // String userKey = (String) settings.get(ConfigurePluginServlet.DB_USER); // return userKey; // } // }); // ApplicationUser user; // UserUtil userUtil = ComponentAccessor.getUserUtil(); // if (userKey != null) { // user = userUtil.getUserByKey(userKey); // } else { // Collection<User> admins = userUtil.getJiraAdministrators(); // User admin = Iterables.get(admins, 0); // String adminName = admin.getName(); // user = userUtil.getUserByName(adminName); // } // return user; // } // } // Path: src/main/java/minhhai2209/jirapluginconverter/plugin/utils/RequestUtils.java import minhhai2209.jirapluginconverter.plugin.setting.PluginSetting; import org.apache.commons.lang3.StringUtils; import javax.servlet.http.HttpServletRequest; package minhhai2209.jirapluginconverter.plugin.utils; public class RequestUtils { public static String getModuleKey(HttpServletRequest request) { String servletPath = request.getServletPath(); String requestUrl = request.getRequestURL().toString(); String path = StringUtils.substringAfter(requestUrl, servletPath + "/");
path = path.replace(PluginSetting.getDescriptor().getKey() + "__", "");
minhhai2209/jira-plugin-converter
src/main/java/minhhai2209/jirapluginconverter/plugin/lifecycle/PluginLifeCycleEventHandler.java
// Path: src/main/java/minhhai2209/jirapluginconverter/plugin/jwt/JwtComposer.java // public class JwtComposer { // // public static String compose( // String key, // String sharedSecret, // String method, // String apiPath, // List<NameValuePair> pairs, // JwtContext context) { // // try { // long issuedAt = System.currentTimeMillis() / 1000L; // long expiresAt = issuedAt + 1800L; // JwtJsonBuilder jwtJsonBuilder = new JsonSmartJwtJsonBuilder() // .issuedAt(issuedAt) // .expirationTime(expiresAt) // .issuer(key) // .claim("context", context); // Map<String, List<String>> parameters = JwtHelper.getParameters(pairs); // Map<String, String[]> parameterMap = JwtHelper.getParameterMap(parameters); // CanonicalHttpUriRequest canonicalHttpUrlRequest = new CanonicalHttpUriRequest(method, apiPath, null, parameterMap); // JwtClaimsBuilder.appendHttpRequestClaims(jwtJsonBuilder, canonicalHttpUrlRequest); // JwtWriterFactory jwtWriterFactory = new NimbusJwtWriterFactory(); // String unsignedJwt = jwtJsonBuilder.build(); // JwtWriter macSigningWriter = jwtWriterFactory.macSigningWriter(SigningAlgorithm.HS256, sharedSecret); // String jwt = macSigningWriter.jsonToJwt(unsignedJwt); // return jwt; // } catch (Exception e) { // ExceptionUtils.throwUnchecked(e); // } // return null; // } // // public static String compose( // String key, String sharedSecret, String method, URIBuilder uriBuilder, String userKey, String path) { // List<NameValuePair> pairs = uriBuilder.getQueryParams(); // int index = path.indexOf("?"); // if (index >= 0) { // path = path.substring(0, index); // } // JwtContext context = new JwtContext(); // JwtContextUser user = new JwtContextUser(); // user.setUserKey(userKey); // context.setUser(user); // String jwt = compose(key, sharedSecret, method, path, pairs, context); // return jwt; // } // } // // Path: src/main/java/minhhai2209/jirapluginconverter/utils/ExceptionUtils.java // public class ExceptionUtils { // // public static void throwUnchecked(Exception e) { // throw new IllegalStateException(e); // } // // public static String getStackTrace(Exception e) { // return Throwables.getStackTraceAsString(e); // } // }
import com.atlassian.jira.util.json.JSONObject; import com.atlassian.oauth.consumer.ConsumerService; import com.atlassian.plugin.Plugin; import com.atlassian.sal.api.ApplicationProperties; import com.atlassian.sal.api.pluginsettings.PluginSettingsFactory; import com.atlassian.sal.api.transaction.TransactionTemplate; import com.atlassian.upm.api.license.PluginLicenseManager; import minhhai2209.jirapluginconverter.plugin.jwt.JwtComposer; import minhhai2209.jirapluginconverter.plugin.setting.*; import minhhai2209.jirapluginconverter.plugin.utils.HttpClientFactory; import minhhai2209.jirapluginconverter.utils.ExceptionUtils; import minhhai2209.jirapluginconverter.utils.JsonUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.util.EntityUtils;
TransactionTemplate transactionTemplate, ApplicationProperties applicationProperties, PluginLicenseManager pluginLicenseManager, ConsumerService consumerService) { this.pluginSettingsFactory = pluginSettingsFactory; this.transactionTemplate = transactionTemplate; this.applicationProperties = applicationProperties; this.pluginLicenseManager = pluginLicenseManager; this.consumerService = consumerService; } public void onInstalled(StringBuilder error) throws Exception { Plugin plugin = PluginSetting.getJiraPlugin(); JiraUtils.setApplicationProperties(applicationProperties); jiraVersion = applicationProperties.getVersion(); PluginSetting.load(pluginSettingsFactory, transactionTemplate, pluginLicenseManager, consumerService); String existingSharedSecret = KeyUtils.getSharedSecret(); if (existingSharedSecret == null) { KeyUtils.generateSharedSecret(pluginSettingsFactory, transactionTemplate); } String currentSharedSecret = KeyUtils.getSharedSecret(); pluginVersion = plugin.getPluginInformation().getVersion(); String uri = LifeCycleUtils.getInstalledUri(); String jwt = (existingSharedSecret == null) ? null :
// Path: src/main/java/minhhai2209/jirapluginconverter/plugin/jwt/JwtComposer.java // public class JwtComposer { // // public static String compose( // String key, // String sharedSecret, // String method, // String apiPath, // List<NameValuePair> pairs, // JwtContext context) { // // try { // long issuedAt = System.currentTimeMillis() / 1000L; // long expiresAt = issuedAt + 1800L; // JwtJsonBuilder jwtJsonBuilder = new JsonSmartJwtJsonBuilder() // .issuedAt(issuedAt) // .expirationTime(expiresAt) // .issuer(key) // .claim("context", context); // Map<String, List<String>> parameters = JwtHelper.getParameters(pairs); // Map<String, String[]> parameterMap = JwtHelper.getParameterMap(parameters); // CanonicalHttpUriRequest canonicalHttpUrlRequest = new CanonicalHttpUriRequest(method, apiPath, null, parameterMap); // JwtClaimsBuilder.appendHttpRequestClaims(jwtJsonBuilder, canonicalHttpUrlRequest); // JwtWriterFactory jwtWriterFactory = new NimbusJwtWriterFactory(); // String unsignedJwt = jwtJsonBuilder.build(); // JwtWriter macSigningWriter = jwtWriterFactory.macSigningWriter(SigningAlgorithm.HS256, sharedSecret); // String jwt = macSigningWriter.jsonToJwt(unsignedJwt); // return jwt; // } catch (Exception e) { // ExceptionUtils.throwUnchecked(e); // } // return null; // } // // public static String compose( // String key, String sharedSecret, String method, URIBuilder uriBuilder, String userKey, String path) { // List<NameValuePair> pairs = uriBuilder.getQueryParams(); // int index = path.indexOf("?"); // if (index >= 0) { // path = path.substring(0, index); // } // JwtContext context = new JwtContext(); // JwtContextUser user = new JwtContextUser(); // user.setUserKey(userKey); // context.setUser(user); // String jwt = compose(key, sharedSecret, method, path, pairs, context); // return jwt; // } // } // // Path: src/main/java/minhhai2209/jirapluginconverter/utils/ExceptionUtils.java // public class ExceptionUtils { // // public static void throwUnchecked(Exception e) { // throw new IllegalStateException(e); // } // // public static String getStackTrace(Exception e) { // return Throwables.getStackTraceAsString(e); // } // } // Path: src/main/java/minhhai2209/jirapluginconverter/plugin/lifecycle/PluginLifeCycleEventHandler.java import com.atlassian.jira.util.json.JSONObject; import com.atlassian.oauth.consumer.ConsumerService; import com.atlassian.plugin.Plugin; import com.atlassian.sal.api.ApplicationProperties; import com.atlassian.sal.api.pluginsettings.PluginSettingsFactory; import com.atlassian.sal.api.transaction.TransactionTemplate; import com.atlassian.upm.api.license.PluginLicenseManager; import minhhai2209.jirapluginconverter.plugin.jwt.JwtComposer; import minhhai2209.jirapluginconverter.plugin.setting.*; import minhhai2209.jirapluginconverter.plugin.utils.HttpClientFactory; import minhhai2209.jirapluginconverter.utils.ExceptionUtils; import minhhai2209.jirapluginconverter.utils.JsonUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.util.EntityUtils; TransactionTemplate transactionTemplate, ApplicationProperties applicationProperties, PluginLicenseManager pluginLicenseManager, ConsumerService consumerService) { this.pluginSettingsFactory = pluginSettingsFactory; this.transactionTemplate = transactionTemplate; this.applicationProperties = applicationProperties; this.pluginLicenseManager = pluginLicenseManager; this.consumerService = consumerService; } public void onInstalled(StringBuilder error) throws Exception { Plugin plugin = PluginSetting.getJiraPlugin(); JiraUtils.setApplicationProperties(applicationProperties); jiraVersion = applicationProperties.getVersion(); PluginSetting.load(pluginSettingsFactory, transactionTemplate, pluginLicenseManager, consumerService); String existingSharedSecret = KeyUtils.getSharedSecret(); if (existingSharedSecret == null) { KeyUtils.generateSharedSecret(pluginSettingsFactory, transactionTemplate); } String currentSharedSecret = KeyUtils.getSharedSecret(); pluginVersion = plugin.getPluginInformation().getVersion(); String uri = LifeCycleUtils.getInstalledUri(); String jwt = (existingSharedSecret == null) ? null :
JwtComposer.compose(KeyUtils.getClientKey(), existingSharedSecret, "POST", uri, null, null);
minhhai2209/jira-plugin-converter
src/main/java/minhhai2209/jirapluginconverter/plugin/lifecycle/PluginLifeCycleEventHandler.java
// Path: src/main/java/minhhai2209/jirapluginconverter/plugin/jwt/JwtComposer.java // public class JwtComposer { // // public static String compose( // String key, // String sharedSecret, // String method, // String apiPath, // List<NameValuePair> pairs, // JwtContext context) { // // try { // long issuedAt = System.currentTimeMillis() / 1000L; // long expiresAt = issuedAt + 1800L; // JwtJsonBuilder jwtJsonBuilder = new JsonSmartJwtJsonBuilder() // .issuedAt(issuedAt) // .expirationTime(expiresAt) // .issuer(key) // .claim("context", context); // Map<String, List<String>> parameters = JwtHelper.getParameters(pairs); // Map<String, String[]> parameterMap = JwtHelper.getParameterMap(parameters); // CanonicalHttpUriRequest canonicalHttpUrlRequest = new CanonicalHttpUriRequest(method, apiPath, null, parameterMap); // JwtClaimsBuilder.appendHttpRequestClaims(jwtJsonBuilder, canonicalHttpUrlRequest); // JwtWriterFactory jwtWriterFactory = new NimbusJwtWriterFactory(); // String unsignedJwt = jwtJsonBuilder.build(); // JwtWriter macSigningWriter = jwtWriterFactory.macSigningWriter(SigningAlgorithm.HS256, sharedSecret); // String jwt = macSigningWriter.jsonToJwt(unsignedJwt); // return jwt; // } catch (Exception e) { // ExceptionUtils.throwUnchecked(e); // } // return null; // } // // public static String compose( // String key, String sharedSecret, String method, URIBuilder uriBuilder, String userKey, String path) { // List<NameValuePair> pairs = uriBuilder.getQueryParams(); // int index = path.indexOf("?"); // if (index >= 0) { // path = path.substring(0, index); // } // JwtContext context = new JwtContext(); // JwtContextUser user = new JwtContextUser(); // user.setUserKey(userKey); // context.setUser(user); // String jwt = compose(key, sharedSecret, method, path, pairs, context); // return jwt; // } // } // // Path: src/main/java/minhhai2209/jirapluginconverter/utils/ExceptionUtils.java // public class ExceptionUtils { // // public static void throwUnchecked(Exception e) { // throw new IllegalStateException(e); // } // // public static String getStackTrace(Exception e) { // return Throwables.getStackTraceAsString(e); // } // }
import com.atlassian.jira.util.json.JSONObject; import com.atlassian.oauth.consumer.ConsumerService; import com.atlassian.plugin.Plugin; import com.atlassian.sal.api.ApplicationProperties; import com.atlassian.sal.api.pluginsettings.PluginSettingsFactory; import com.atlassian.sal.api.transaction.TransactionTemplate; import com.atlassian.upm.api.license.PluginLicenseManager; import minhhai2209.jirapluginconverter.plugin.jwt.JwtComposer; import minhhai2209.jirapluginconverter.plugin.setting.*; import minhhai2209.jirapluginconverter.plugin.utils.HttpClientFactory; import minhhai2209.jirapluginconverter.utils.ExceptionUtils; import minhhai2209.jirapluginconverter.utils.JsonUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.util.EntityUtils;
notify(null, EventType.disabled, uri, null, jwt); } public void onUninstalled() throws Exception { String uri = LifeCycleUtils.getUninstalledUri(); String jwt = JwtComposer.compose(KeyUtils.getClientKey(), KeyUtils.getSharedSecret(), "POST", uri, null, null); notify(null, EventType.uninstalled, uri, null, jwt); } private void notify(StringBuilder error, EventType eventType, String uri, String sharedSecret, String jwt) throws Exception { try { if (uri != null) { PluginLifeCycleEvent event = new PluginLifeCycleEvent(); event.setBaseUrl(JiraUtils.getFullBaseUrl()); event.setClientKey(KeyUtils.getClientKey()); event.setDescription(""); event.setEventType(eventType); event.setKey(PluginSetting.getDescriptor().getKey()); event.setPluginsVersion(pluginVersion); event.setProductType(ProductType.jira); event.setPublicKey(KeyUtils.getPublicKey()); event.setServerVersion(jiraVersion); event.setServiceEntitlementNumber(SenUtils.getSen()); event.setSharedSecret(sharedSecret); notify(uri, event, jwt, error); } } catch (Exception e) { System.out.println(PluginSetting.getDescriptor().getKey() + " PLUGIN NOTIFY EVENT '" + eventType.toString() + "' FAILED: " + e.getMessage()); if (error != null) {
// Path: src/main/java/minhhai2209/jirapluginconverter/plugin/jwt/JwtComposer.java // public class JwtComposer { // // public static String compose( // String key, // String sharedSecret, // String method, // String apiPath, // List<NameValuePair> pairs, // JwtContext context) { // // try { // long issuedAt = System.currentTimeMillis() / 1000L; // long expiresAt = issuedAt + 1800L; // JwtJsonBuilder jwtJsonBuilder = new JsonSmartJwtJsonBuilder() // .issuedAt(issuedAt) // .expirationTime(expiresAt) // .issuer(key) // .claim("context", context); // Map<String, List<String>> parameters = JwtHelper.getParameters(pairs); // Map<String, String[]> parameterMap = JwtHelper.getParameterMap(parameters); // CanonicalHttpUriRequest canonicalHttpUrlRequest = new CanonicalHttpUriRequest(method, apiPath, null, parameterMap); // JwtClaimsBuilder.appendHttpRequestClaims(jwtJsonBuilder, canonicalHttpUrlRequest); // JwtWriterFactory jwtWriterFactory = new NimbusJwtWriterFactory(); // String unsignedJwt = jwtJsonBuilder.build(); // JwtWriter macSigningWriter = jwtWriterFactory.macSigningWriter(SigningAlgorithm.HS256, sharedSecret); // String jwt = macSigningWriter.jsonToJwt(unsignedJwt); // return jwt; // } catch (Exception e) { // ExceptionUtils.throwUnchecked(e); // } // return null; // } // // public static String compose( // String key, String sharedSecret, String method, URIBuilder uriBuilder, String userKey, String path) { // List<NameValuePair> pairs = uriBuilder.getQueryParams(); // int index = path.indexOf("?"); // if (index >= 0) { // path = path.substring(0, index); // } // JwtContext context = new JwtContext(); // JwtContextUser user = new JwtContextUser(); // user.setUserKey(userKey); // context.setUser(user); // String jwt = compose(key, sharedSecret, method, path, pairs, context); // return jwt; // } // } // // Path: src/main/java/minhhai2209/jirapluginconverter/utils/ExceptionUtils.java // public class ExceptionUtils { // // public static void throwUnchecked(Exception e) { // throw new IllegalStateException(e); // } // // public static String getStackTrace(Exception e) { // return Throwables.getStackTraceAsString(e); // } // } // Path: src/main/java/minhhai2209/jirapluginconverter/plugin/lifecycle/PluginLifeCycleEventHandler.java import com.atlassian.jira.util.json.JSONObject; import com.atlassian.oauth.consumer.ConsumerService; import com.atlassian.plugin.Plugin; import com.atlassian.sal.api.ApplicationProperties; import com.atlassian.sal.api.pluginsettings.PluginSettingsFactory; import com.atlassian.sal.api.transaction.TransactionTemplate; import com.atlassian.upm.api.license.PluginLicenseManager; import minhhai2209.jirapluginconverter.plugin.jwt.JwtComposer; import minhhai2209.jirapluginconverter.plugin.setting.*; import minhhai2209.jirapluginconverter.plugin.utils.HttpClientFactory; import minhhai2209.jirapluginconverter.utils.ExceptionUtils; import minhhai2209.jirapluginconverter.utils.JsonUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.util.EntityUtils; notify(null, EventType.disabled, uri, null, jwt); } public void onUninstalled() throws Exception { String uri = LifeCycleUtils.getUninstalledUri(); String jwt = JwtComposer.compose(KeyUtils.getClientKey(), KeyUtils.getSharedSecret(), "POST", uri, null, null); notify(null, EventType.uninstalled, uri, null, jwt); } private void notify(StringBuilder error, EventType eventType, String uri, String sharedSecret, String jwt) throws Exception { try { if (uri != null) { PluginLifeCycleEvent event = new PluginLifeCycleEvent(); event.setBaseUrl(JiraUtils.getFullBaseUrl()); event.setClientKey(KeyUtils.getClientKey()); event.setDescription(""); event.setEventType(eventType); event.setKey(PluginSetting.getDescriptor().getKey()); event.setPluginsVersion(pluginVersion); event.setProductType(ProductType.jira); event.setPublicKey(KeyUtils.getPublicKey()); event.setServerVersion(jiraVersion); event.setServiceEntitlementNumber(SenUtils.getSen()); event.setSharedSecret(sharedSecret); notify(uri, event, jwt, error); } } catch (Exception e) { System.out.println(PluginSetting.getDescriptor().getKey() + " PLUGIN NOTIFY EVENT '" + eventType.toString() + "' FAILED: " + e.getMessage()); if (error != null) {
error.append(ExceptionUtils.getStackTrace(e));
minhhai2209/jira-plugin-converter
src/main/java/minhhai2209/jirapluginconverter/plugin/lifecycle/PluginLifeCycleEventListener.java
// Path: src/main/java/minhhai2209/jirapluginconverter/plugin/setting/PluginSetting.java // public class PluginSetting { // // // public static final String ARTIFACT_ID = "generated_artifact_id"; // // // public static final String PLUGIN_KEY = ARTIFACT_ID; // // private static Descriptor descriptor; // // private static com.atlassian.plugin.Plugin jiraPlugin; // // private static PluginSettingsFactory pluginSettingsFactory; // // private static TransactionTemplate transactionTemplate; // // public static void load( // PluginSettingsFactory pluginSettingsFactory, // TransactionTemplate transactionTemplate, // PluginLicenseManager pluginLicenseManager, // ConsumerService consumerService) throws Exception { // // PluginSetting.pluginSettingsFactory = pluginSettingsFactory; // PluginSetting.transactionTemplate = transactionTemplate; // // LicenseUtils.setPluginLicenseManager(pluginLicenseManager); // KeyUtils.loadJiraConsumer(consumerService); // KeyUtils.loadSharedSecret(pluginSettingsFactory); // } // // public static void readDescriptor() { // InputStream is = null; // try { // is = PluginSetting.class.getResourceAsStream("/imported_atlas_connect_descriptor.json"); // String descriptorString = IOUtils.toString(is); // descriptor = JsonUtils.fromJson(descriptorString, Descriptor.class); // WebItemUtils.buildWebItemLookup(); // WebPanelUtils.buildWebPanelLookup(); // PageUtils.buildGeneralPageLookup(); // PageUtils.buildAdminPageLookup(); // PageUtils.buildConfigurePageLookup(); // IssueTabPanelUtils.buildJiraIssueTabPanelLookup(); // ProjectTabPanelUtils.buildProjectTabPanelLookup(); // WorkflowPostFunctionUtils.buildWorkflowPostFunctionLookup(); // } catch (Exception e1) { // if (is != null) { // try { // is.close(); // } catch (Exception e2) { // ExceptionUtils.throwUnchecked(e2); // } // } // ExceptionUtils.throwUnchecked(e1); // } // } // // public static Descriptor getDescriptor() { // return descriptor; // } // // public static String getPluginBaseUrl() { // String baseUrl = transactionTemplate.execute(new TransactionCallback<String>() { // // @Override // public String doInTransaction() { // PluginSettings settings = pluginSettingsFactory.createGlobalSettings(); // String url = (String) settings.get(ConfigurePluginServlet.DB_URL); // return url; // } // // }); // if (baseUrl == null) { // baseUrl = descriptor.getBaseUrl(); // } // String jiraUrl = JiraUtils.getBaseUrl(); // if (jiraUrl.startsWith("http:") && baseUrl.startsWith("https:")) { // baseUrl = baseUrl.replace("https:", "http:"); // } else if (jiraUrl.startsWith("https:")) { // baseUrl = baseUrl.replace("http:", "https:"); // } // return baseUrl; // } // // public static Modules getModules() { // return descriptor.getModules(); // } // // public static Plugin getPlugin() { // Plugin plugin = new Plugin(); // plugin.setName(descriptor.getName()); // plugin.setBaseUrl(getPluginBaseUrl()); // return plugin; // } // // public static com.atlassian.plugin.Plugin getJiraPlugin() { // return jiraPlugin; // } // // public static void setJiraPlugin(com.atlassian.plugin.Plugin jiraPlugin) { // PluginSetting.jiraPlugin = jiraPlugin; // } // // public static ApplicationUser getPluginUser() { // String userKey = transactionTemplate.execute(new TransactionCallback<String>() { // @Override // public String doInTransaction() { // // PluginSettings settings = pluginSettingsFactory.createGlobalSettings(); // String userKey = (String) settings.get(ConfigurePluginServlet.DB_USER); // return userKey; // } // }); // ApplicationUser user; // UserUtil userUtil = ComponentAccessor.getUserUtil(); // if (userKey != null) { // user = userUtil.getUserByKey(userKey); // } else { // Collection<User> admins = userUtil.getJiraAdministrators(); // User admin = Iterables.get(admins, 0); // String adminName = admin.getName(); // user = userUtil.getUserByName(adminName); // } // return user; // } // } // // Path: src/main/java/minhhai2209/jirapluginconverter/utils/ExceptionUtils.java // public class ExceptionUtils { // // public static void throwUnchecked(Exception e) { // throw new IllegalStateException(e); // } // // public static String getStackTrace(Exception e) { // return Throwables.getStackTraceAsString(e); // } // }
import com.atlassian.jira.component.ComponentAccessor; import com.atlassian.plugin.Plugin; import com.atlassian.plugin.event.PluginEventListener; import com.atlassian.plugin.event.PluginEventManager; import com.atlassian.plugin.event.events.PluginDisabledEvent; import com.atlassian.plugin.event.events.PluginEnabledEvent; import com.atlassian.plugin.event.events.PluginFrameworkShutdownEvent; import com.atlassian.plugin.event.events.PluginUninstalledEvent; import minhhai2209.jirapluginconverter.plugin.setting.PluginSetting; import minhhai2209.jirapluginconverter.utils.ExceptionUtils; import org.springframework.beans.factory.DisposableBean; import java.util.UUID;
package minhhai2209.jirapluginconverter.plugin.lifecycle; public class PluginLifeCycleEventListener implements DisposableBean { private EventType currentPluginStatus = null; private boolean registered = false; private String source = UUID.randomUUID().toString(); private boolean newlyInstalled = true; private PluginLifeCycleEventHandler pluginLifeCycleEventHandler; public PluginLifeCycleEventListener(PluginLifeCycleEventHandler pluginLifeCycleEventHandler) {
// Path: src/main/java/minhhai2209/jirapluginconverter/plugin/setting/PluginSetting.java // public class PluginSetting { // // // public static final String ARTIFACT_ID = "generated_artifact_id"; // // // public static final String PLUGIN_KEY = ARTIFACT_ID; // // private static Descriptor descriptor; // // private static com.atlassian.plugin.Plugin jiraPlugin; // // private static PluginSettingsFactory pluginSettingsFactory; // // private static TransactionTemplate transactionTemplate; // // public static void load( // PluginSettingsFactory pluginSettingsFactory, // TransactionTemplate transactionTemplate, // PluginLicenseManager pluginLicenseManager, // ConsumerService consumerService) throws Exception { // // PluginSetting.pluginSettingsFactory = pluginSettingsFactory; // PluginSetting.transactionTemplate = transactionTemplate; // // LicenseUtils.setPluginLicenseManager(pluginLicenseManager); // KeyUtils.loadJiraConsumer(consumerService); // KeyUtils.loadSharedSecret(pluginSettingsFactory); // } // // public static void readDescriptor() { // InputStream is = null; // try { // is = PluginSetting.class.getResourceAsStream("/imported_atlas_connect_descriptor.json"); // String descriptorString = IOUtils.toString(is); // descriptor = JsonUtils.fromJson(descriptorString, Descriptor.class); // WebItemUtils.buildWebItemLookup(); // WebPanelUtils.buildWebPanelLookup(); // PageUtils.buildGeneralPageLookup(); // PageUtils.buildAdminPageLookup(); // PageUtils.buildConfigurePageLookup(); // IssueTabPanelUtils.buildJiraIssueTabPanelLookup(); // ProjectTabPanelUtils.buildProjectTabPanelLookup(); // WorkflowPostFunctionUtils.buildWorkflowPostFunctionLookup(); // } catch (Exception e1) { // if (is != null) { // try { // is.close(); // } catch (Exception e2) { // ExceptionUtils.throwUnchecked(e2); // } // } // ExceptionUtils.throwUnchecked(e1); // } // } // // public static Descriptor getDescriptor() { // return descriptor; // } // // public static String getPluginBaseUrl() { // String baseUrl = transactionTemplate.execute(new TransactionCallback<String>() { // // @Override // public String doInTransaction() { // PluginSettings settings = pluginSettingsFactory.createGlobalSettings(); // String url = (String) settings.get(ConfigurePluginServlet.DB_URL); // return url; // } // // }); // if (baseUrl == null) { // baseUrl = descriptor.getBaseUrl(); // } // String jiraUrl = JiraUtils.getBaseUrl(); // if (jiraUrl.startsWith("http:") && baseUrl.startsWith("https:")) { // baseUrl = baseUrl.replace("https:", "http:"); // } else if (jiraUrl.startsWith("https:")) { // baseUrl = baseUrl.replace("http:", "https:"); // } // return baseUrl; // } // // public static Modules getModules() { // return descriptor.getModules(); // } // // public static Plugin getPlugin() { // Plugin plugin = new Plugin(); // plugin.setName(descriptor.getName()); // plugin.setBaseUrl(getPluginBaseUrl()); // return plugin; // } // // public static com.atlassian.plugin.Plugin getJiraPlugin() { // return jiraPlugin; // } // // public static void setJiraPlugin(com.atlassian.plugin.Plugin jiraPlugin) { // PluginSetting.jiraPlugin = jiraPlugin; // } // // public static ApplicationUser getPluginUser() { // String userKey = transactionTemplate.execute(new TransactionCallback<String>() { // @Override // public String doInTransaction() { // // PluginSettings settings = pluginSettingsFactory.createGlobalSettings(); // String userKey = (String) settings.get(ConfigurePluginServlet.DB_USER); // return userKey; // } // }); // ApplicationUser user; // UserUtil userUtil = ComponentAccessor.getUserUtil(); // if (userKey != null) { // user = userUtil.getUserByKey(userKey); // } else { // Collection<User> admins = userUtil.getJiraAdministrators(); // User admin = Iterables.get(admins, 0); // String adminName = admin.getName(); // user = userUtil.getUserByName(adminName); // } // return user; // } // } // // Path: src/main/java/minhhai2209/jirapluginconverter/utils/ExceptionUtils.java // public class ExceptionUtils { // // public static void throwUnchecked(Exception e) { // throw new IllegalStateException(e); // } // // public static String getStackTrace(Exception e) { // return Throwables.getStackTraceAsString(e); // } // } // Path: src/main/java/minhhai2209/jirapluginconverter/plugin/lifecycle/PluginLifeCycleEventListener.java import com.atlassian.jira.component.ComponentAccessor; import com.atlassian.plugin.Plugin; import com.atlassian.plugin.event.PluginEventListener; import com.atlassian.plugin.event.PluginEventManager; import com.atlassian.plugin.event.events.PluginDisabledEvent; import com.atlassian.plugin.event.events.PluginEnabledEvent; import com.atlassian.plugin.event.events.PluginFrameworkShutdownEvent; import com.atlassian.plugin.event.events.PluginUninstalledEvent; import minhhai2209.jirapluginconverter.plugin.setting.PluginSetting; import minhhai2209.jirapluginconverter.utils.ExceptionUtils; import org.springframework.beans.factory.DisposableBean; import java.util.UUID; package minhhai2209.jirapluginconverter.plugin.lifecycle; public class PluginLifeCycleEventListener implements DisposableBean { private EventType currentPluginStatus = null; private boolean registered = false; private String source = UUID.randomUUID().toString(); private boolean newlyInstalled = true; private PluginLifeCycleEventHandler pluginLifeCycleEventHandler; public PluginLifeCycleEventListener(PluginLifeCycleEventHandler pluginLifeCycleEventHandler) {
PluginSetting.readDescriptor();
minhhai2209/jira-plugin-converter
src/main/java/minhhai2209/jirapluginconverter/plugin/lifecycle/PluginLifeCycleEventListener.java
// Path: src/main/java/minhhai2209/jirapluginconverter/plugin/setting/PluginSetting.java // public class PluginSetting { // // // public static final String ARTIFACT_ID = "generated_artifact_id"; // // // public static final String PLUGIN_KEY = ARTIFACT_ID; // // private static Descriptor descriptor; // // private static com.atlassian.plugin.Plugin jiraPlugin; // // private static PluginSettingsFactory pluginSettingsFactory; // // private static TransactionTemplate transactionTemplate; // // public static void load( // PluginSettingsFactory pluginSettingsFactory, // TransactionTemplate transactionTemplate, // PluginLicenseManager pluginLicenseManager, // ConsumerService consumerService) throws Exception { // // PluginSetting.pluginSettingsFactory = pluginSettingsFactory; // PluginSetting.transactionTemplate = transactionTemplate; // // LicenseUtils.setPluginLicenseManager(pluginLicenseManager); // KeyUtils.loadJiraConsumer(consumerService); // KeyUtils.loadSharedSecret(pluginSettingsFactory); // } // // public static void readDescriptor() { // InputStream is = null; // try { // is = PluginSetting.class.getResourceAsStream("/imported_atlas_connect_descriptor.json"); // String descriptorString = IOUtils.toString(is); // descriptor = JsonUtils.fromJson(descriptorString, Descriptor.class); // WebItemUtils.buildWebItemLookup(); // WebPanelUtils.buildWebPanelLookup(); // PageUtils.buildGeneralPageLookup(); // PageUtils.buildAdminPageLookup(); // PageUtils.buildConfigurePageLookup(); // IssueTabPanelUtils.buildJiraIssueTabPanelLookup(); // ProjectTabPanelUtils.buildProjectTabPanelLookup(); // WorkflowPostFunctionUtils.buildWorkflowPostFunctionLookup(); // } catch (Exception e1) { // if (is != null) { // try { // is.close(); // } catch (Exception e2) { // ExceptionUtils.throwUnchecked(e2); // } // } // ExceptionUtils.throwUnchecked(e1); // } // } // // public static Descriptor getDescriptor() { // return descriptor; // } // // public static String getPluginBaseUrl() { // String baseUrl = transactionTemplate.execute(new TransactionCallback<String>() { // // @Override // public String doInTransaction() { // PluginSettings settings = pluginSettingsFactory.createGlobalSettings(); // String url = (String) settings.get(ConfigurePluginServlet.DB_URL); // return url; // } // // }); // if (baseUrl == null) { // baseUrl = descriptor.getBaseUrl(); // } // String jiraUrl = JiraUtils.getBaseUrl(); // if (jiraUrl.startsWith("http:") && baseUrl.startsWith("https:")) { // baseUrl = baseUrl.replace("https:", "http:"); // } else if (jiraUrl.startsWith("https:")) { // baseUrl = baseUrl.replace("http:", "https:"); // } // return baseUrl; // } // // public static Modules getModules() { // return descriptor.getModules(); // } // // public static Plugin getPlugin() { // Plugin plugin = new Plugin(); // plugin.setName(descriptor.getName()); // plugin.setBaseUrl(getPluginBaseUrl()); // return plugin; // } // // public static com.atlassian.plugin.Plugin getJiraPlugin() { // return jiraPlugin; // } // // public static void setJiraPlugin(com.atlassian.plugin.Plugin jiraPlugin) { // PluginSetting.jiraPlugin = jiraPlugin; // } // // public static ApplicationUser getPluginUser() { // String userKey = transactionTemplate.execute(new TransactionCallback<String>() { // @Override // public String doInTransaction() { // // PluginSettings settings = pluginSettingsFactory.createGlobalSettings(); // String userKey = (String) settings.get(ConfigurePluginServlet.DB_USER); // return userKey; // } // }); // ApplicationUser user; // UserUtil userUtil = ComponentAccessor.getUserUtil(); // if (userKey != null) { // user = userUtil.getUserByKey(userKey); // } else { // Collection<User> admins = userUtil.getJiraAdministrators(); // User admin = Iterables.get(admins, 0); // String adminName = admin.getName(); // user = userUtil.getUserByName(adminName); // } // return user; // } // } // // Path: src/main/java/minhhai2209/jirapluginconverter/utils/ExceptionUtils.java // public class ExceptionUtils { // // public static void throwUnchecked(Exception e) { // throw new IllegalStateException(e); // } // // public static String getStackTrace(Exception e) { // return Throwables.getStackTraceAsString(e); // } // }
import com.atlassian.jira.component.ComponentAccessor; import com.atlassian.plugin.Plugin; import com.atlassian.plugin.event.PluginEventListener; import com.atlassian.plugin.event.PluginEventManager; import com.atlassian.plugin.event.events.PluginDisabledEvent; import com.atlassian.plugin.event.events.PluginEnabledEvent; import com.atlassian.plugin.event.events.PluginFrameworkShutdownEvent; import com.atlassian.plugin.event.events.PluginUninstalledEvent; import minhhai2209.jirapluginconverter.plugin.setting.PluginSetting; import minhhai2209.jirapluginconverter.utils.ExceptionUtils; import org.springframework.beans.factory.DisposableBean; import java.util.UUID;
pluginEventManager.register(this); registered = true; } } catch (Exception e) { } } private void setPluginStatus(EventType nextPluginStatus, Plugin plugin) { log("status " + currentPluginStatus + " to " + nextPluginStatus); try { newlyInstalled = false; currentPluginStatus = nextPluginStatus; switch (currentPluginStatus) { case installed: pluginLifeCycleEventHandler.onInstalled(null); break; case uninstalled: pluginLifeCycleEventHandler.onUninstalled(); break; case enabled: pluginLifeCycleEventHandler.onEnabled(); break; case disabled: pluginLifeCycleEventHandler.onDisabled(); break; default: throw new IllegalArgumentException(); } } catch (Exception e) { log(e.getMessage());
// Path: src/main/java/minhhai2209/jirapluginconverter/plugin/setting/PluginSetting.java // public class PluginSetting { // // // public static final String ARTIFACT_ID = "generated_artifact_id"; // // // public static final String PLUGIN_KEY = ARTIFACT_ID; // // private static Descriptor descriptor; // // private static com.atlassian.plugin.Plugin jiraPlugin; // // private static PluginSettingsFactory pluginSettingsFactory; // // private static TransactionTemplate transactionTemplate; // // public static void load( // PluginSettingsFactory pluginSettingsFactory, // TransactionTemplate transactionTemplate, // PluginLicenseManager pluginLicenseManager, // ConsumerService consumerService) throws Exception { // // PluginSetting.pluginSettingsFactory = pluginSettingsFactory; // PluginSetting.transactionTemplate = transactionTemplate; // // LicenseUtils.setPluginLicenseManager(pluginLicenseManager); // KeyUtils.loadJiraConsumer(consumerService); // KeyUtils.loadSharedSecret(pluginSettingsFactory); // } // // public static void readDescriptor() { // InputStream is = null; // try { // is = PluginSetting.class.getResourceAsStream("/imported_atlas_connect_descriptor.json"); // String descriptorString = IOUtils.toString(is); // descriptor = JsonUtils.fromJson(descriptorString, Descriptor.class); // WebItemUtils.buildWebItemLookup(); // WebPanelUtils.buildWebPanelLookup(); // PageUtils.buildGeneralPageLookup(); // PageUtils.buildAdminPageLookup(); // PageUtils.buildConfigurePageLookup(); // IssueTabPanelUtils.buildJiraIssueTabPanelLookup(); // ProjectTabPanelUtils.buildProjectTabPanelLookup(); // WorkflowPostFunctionUtils.buildWorkflowPostFunctionLookup(); // } catch (Exception e1) { // if (is != null) { // try { // is.close(); // } catch (Exception e2) { // ExceptionUtils.throwUnchecked(e2); // } // } // ExceptionUtils.throwUnchecked(e1); // } // } // // public static Descriptor getDescriptor() { // return descriptor; // } // // public static String getPluginBaseUrl() { // String baseUrl = transactionTemplate.execute(new TransactionCallback<String>() { // // @Override // public String doInTransaction() { // PluginSettings settings = pluginSettingsFactory.createGlobalSettings(); // String url = (String) settings.get(ConfigurePluginServlet.DB_URL); // return url; // } // // }); // if (baseUrl == null) { // baseUrl = descriptor.getBaseUrl(); // } // String jiraUrl = JiraUtils.getBaseUrl(); // if (jiraUrl.startsWith("http:") && baseUrl.startsWith("https:")) { // baseUrl = baseUrl.replace("https:", "http:"); // } else if (jiraUrl.startsWith("https:")) { // baseUrl = baseUrl.replace("http:", "https:"); // } // return baseUrl; // } // // public static Modules getModules() { // return descriptor.getModules(); // } // // public static Plugin getPlugin() { // Plugin plugin = new Plugin(); // plugin.setName(descriptor.getName()); // plugin.setBaseUrl(getPluginBaseUrl()); // return plugin; // } // // public static com.atlassian.plugin.Plugin getJiraPlugin() { // return jiraPlugin; // } // // public static void setJiraPlugin(com.atlassian.plugin.Plugin jiraPlugin) { // PluginSetting.jiraPlugin = jiraPlugin; // } // // public static ApplicationUser getPluginUser() { // String userKey = transactionTemplate.execute(new TransactionCallback<String>() { // @Override // public String doInTransaction() { // // PluginSettings settings = pluginSettingsFactory.createGlobalSettings(); // String userKey = (String) settings.get(ConfigurePluginServlet.DB_USER); // return userKey; // } // }); // ApplicationUser user; // UserUtil userUtil = ComponentAccessor.getUserUtil(); // if (userKey != null) { // user = userUtil.getUserByKey(userKey); // } else { // Collection<User> admins = userUtil.getJiraAdministrators(); // User admin = Iterables.get(admins, 0); // String adminName = admin.getName(); // user = userUtil.getUserByName(adminName); // } // return user; // } // } // // Path: src/main/java/minhhai2209/jirapluginconverter/utils/ExceptionUtils.java // public class ExceptionUtils { // // public static void throwUnchecked(Exception e) { // throw new IllegalStateException(e); // } // // public static String getStackTrace(Exception e) { // return Throwables.getStackTraceAsString(e); // } // } // Path: src/main/java/minhhai2209/jirapluginconverter/plugin/lifecycle/PluginLifeCycleEventListener.java import com.atlassian.jira.component.ComponentAccessor; import com.atlassian.plugin.Plugin; import com.atlassian.plugin.event.PluginEventListener; import com.atlassian.plugin.event.PluginEventManager; import com.atlassian.plugin.event.events.PluginDisabledEvent; import com.atlassian.plugin.event.events.PluginEnabledEvent; import com.atlassian.plugin.event.events.PluginFrameworkShutdownEvent; import com.atlassian.plugin.event.events.PluginUninstalledEvent; import minhhai2209.jirapluginconverter.plugin.setting.PluginSetting; import minhhai2209.jirapluginconverter.utils.ExceptionUtils; import org.springframework.beans.factory.DisposableBean; import java.util.UUID; pluginEventManager.register(this); registered = true; } } catch (Exception e) { } } private void setPluginStatus(EventType nextPluginStatus, Plugin plugin) { log("status " + currentPluginStatus + " to " + nextPluginStatus); try { newlyInstalled = false; currentPluginStatus = nextPluginStatus; switch (currentPluginStatus) { case installed: pluginLifeCycleEventHandler.onInstalled(null); break; case uninstalled: pluginLifeCycleEventHandler.onUninstalled(); break; case enabled: pluginLifeCycleEventHandler.onEnabled(); break; case disabled: pluginLifeCycleEventHandler.onDisabled(); break; default: throw new IllegalArgumentException(); } } catch (Exception e) { log(e.getMessage());
ExceptionUtils.throwUnchecked(e);
osiam/addon-administration
src/main/java/org/osiam/addons/administration/controller/LoginController.java
// Path: src/main/java/org/osiam/addons/administration/model/session/GeneralSessionData.java // @Component // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class GeneralSessionData implements Serializable { // // private static final long serialVersionUID = 3937661507313495926L; // // private AccessToken accesstoken; // // public AccessToken getAccessToken() { // return accesstoken; // } // // public void setAccessToken(AccessToken accessToken) { // this.accesstoken = accessToken; // } // }
import org.osiam.addons.administration.model.session.GeneralSessionData; import org.osiam.client.OsiamConnector; import org.osiam.client.exception.ConflictException; import org.osiam.client.oauth.Scope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import javax.inject.Inject;
package org.osiam.addons.administration.controller; /** * This controller contains all handler for the login page ( the root path / ). */ @Controller @RequestMapping(LoginController.CONTROLLER_PATH) public class LoginController { public static final String CONTROLLER_PATH = "/"; private static final Logger logger = LoggerFactory.getLogger(LoginController.class); @Inject private OsiamConnector connector; @Inject
// Path: src/main/java/org/osiam/addons/administration/model/session/GeneralSessionData.java // @Component // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class GeneralSessionData implements Serializable { // // private static final long serialVersionUID = 3937661507313495926L; // // private AccessToken accesstoken; // // public AccessToken getAccessToken() { // return accesstoken; // } // // public void setAccessToken(AccessToken accessToken) { // this.accesstoken = accessToken; // } // } // Path: src/main/java/org/osiam/addons/administration/controller/LoginController.java import org.osiam.addons.administration.model.session.GeneralSessionData; import org.osiam.client.OsiamConnector; import org.osiam.client.exception.ConflictException; import org.osiam.client.oauth.Scope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import javax.inject.Inject; package org.osiam.addons.administration.controller; /** * This controller contains all handler for the login page ( the root path / ). */ @Controller @RequestMapping(LoginController.CONTROLLER_PATH) public class LoginController { public static final String CONTROLLER_PATH = "/"; private static final Logger logger = LoggerFactory.getLogger(LoginController.class); @Inject private OsiamConnector connector; @Inject
private GeneralSessionData generalSessionData;
osiam/addon-administration
src/main/java/org/osiam/addons/administration/model/command/UpdateUserCommand.java
// Path: src/main/java/org/osiam/addons/administration/model/validation/ExtensionValidator.java // public class ExtensionValidator { // private final String path; // private final Map<String, Extension> extensions; // private final BindingResult bindingResult; // // public ExtensionValidator( // String path, // Map<String, Extension> extensions, // BindingResult bindingResult) { // // this.path = path; // this.extensions = extensions; // this.bindingResult = bindingResult; // } // // public void validate(String urn, String fieldKey, String fieldValue) { // final Extension extension = extensions.get(urn); // final Field field = extension.getFields().get(fieldKey); // // try { // field.getType().fromString(fieldValue); // } catch (Exception e) { // final String fieldPath = getFieldPath(urn, fieldKey); // final String message = getMessage(field.getType(), e); // final Object[] errorArgs = new Object[] { // urn, fieldKey, fieldValue // }; // // bindingResult.rejectValue(fieldPath, message, errorArgs, message); // } // } // // private String getMessage(ExtensionFieldType<?> type, Exception e) { // return "msg.validation.error.extension." + type.getName().toLowerCase(); // } // // private String getFieldPath(String urn, String fieldKey) { // return path + "['" + urn + "']['" + fieldKey + "']"; // } // // }
import org.hibernate.validator.constraints.NotBlank; import org.hibernate.validator.constraints.URL; import org.osiam.addons.administration.model.validation.ExtensionValidator; import org.osiam.resources.scim.*; import org.osiam.resources.scim.Extension.Field; import org.springframework.validation.BindingResult; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import java.util.*; import java.util.Map.Entry;
} private void removeEmptyExtensions() { // remove empty fields for (Map<String, String> extension : extensions.values()) { Iterator<Entry<String, String>> iter = extension.entrySet().iterator(); while (iter.hasNext()) { Entry<String, String> field = iter.next(); if (field.getValue() == null || field.getValue().equals("")) { iter.remove(); } } } // remove empty extensions Iterator<Entry<String, SortedMap<String, String>>> iter = extensions.entrySet().iterator(); while (iter.hasNext()) { Entry<String, SortedMap<String, String>> extension = iter.next(); if (extension.getValue().isEmpty()) { iter.remove(); } } } public void validate(Map<String, Extension> allExtensions, BindingResult bindingResult) { validateExtensions(allExtensions, bindingResult); } private void validateExtensions(Map<String, Extension> allExtensions, BindingResult bindingResult) {
// Path: src/main/java/org/osiam/addons/administration/model/validation/ExtensionValidator.java // public class ExtensionValidator { // private final String path; // private final Map<String, Extension> extensions; // private final BindingResult bindingResult; // // public ExtensionValidator( // String path, // Map<String, Extension> extensions, // BindingResult bindingResult) { // // this.path = path; // this.extensions = extensions; // this.bindingResult = bindingResult; // } // // public void validate(String urn, String fieldKey, String fieldValue) { // final Extension extension = extensions.get(urn); // final Field field = extension.getFields().get(fieldKey); // // try { // field.getType().fromString(fieldValue); // } catch (Exception e) { // final String fieldPath = getFieldPath(urn, fieldKey); // final String message = getMessage(field.getType(), e); // final Object[] errorArgs = new Object[] { // urn, fieldKey, fieldValue // }; // // bindingResult.rejectValue(fieldPath, message, errorArgs, message); // } // } // // private String getMessage(ExtensionFieldType<?> type, Exception e) { // return "msg.validation.error.extension." + type.getName().toLowerCase(); // } // // private String getFieldPath(String urn, String fieldKey) { // return path + "['" + urn + "']['" + fieldKey + "']"; // } // // } // Path: src/main/java/org/osiam/addons/administration/model/command/UpdateUserCommand.java import org.hibernate.validator.constraints.NotBlank; import org.hibernate.validator.constraints.URL; import org.osiam.addons.administration.model.validation.ExtensionValidator; import org.osiam.resources.scim.*; import org.osiam.resources.scim.Extension.Field; import org.springframework.validation.BindingResult; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import java.util.*; import java.util.Map.Entry; } private void removeEmptyExtensions() { // remove empty fields for (Map<String, String> extension : extensions.values()) { Iterator<Entry<String, String>> iter = extension.entrySet().iterator(); while (iter.hasNext()) { Entry<String, String> field = iter.next(); if (field.getValue() == null || field.getValue().equals("")) { iter.remove(); } } } // remove empty extensions Iterator<Entry<String, SortedMap<String, String>>> iter = extensions.entrySet().iterator(); while (iter.hasNext()) { Entry<String, SortedMap<String, String>> extension = iter.next(); if (extension.getValue().isEmpty()) { iter.remove(); } } } public void validate(Map<String, Extension> allExtensions, BindingResult bindingResult) { validateExtensions(allExtensions, bindingResult); } private void validateExtensions(Map<String, Extension> allExtensions, BindingResult bindingResult) {
ExtensionValidator validator = new ExtensionValidator("extensions", allExtensions, bindingResult);
osiam/addon-administration
src/main/java/org/osiam/addons/administration/service/GroupService.java
// Path: src/main/java/org/osiam/addons/administration/model/session/GeneralSessionData.java // @Component // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class GeneralSessionData implements Serializable { // // private static final long serialVersionUID = 3937661507313495926L; // // private AccessToken accesstoken; // // public AccessToken getAccessToken() { // return accesstoken; // } // // public void setAccessToken(AccessToken accessToken) { // this.accesstoken = accessToken; // } // }
import javax.inject.Inject; import org.osiam.addons.administration.model.session.GeneralSessionData; import org.osiam.addons.administration.model.session.PagingInformation; import org.osiam.client.OsiamConnector; import org.osiam.client.oauth.AccessToken; import org.osiam.client.query.Query; import org.osiam.client.query.QueryBuilder; import org.osiam.resources.scim.Group; import org.osiam.resources.scim.MemberRef; import org.osiam.resources.scim.SCIMSearchResult; import org.springframework.stereotype.Component;
package org.osiam.addons.administration.service; @Component public class GroupService { @Inject
// Path: src/main/java/org/osiam/addons/administration/model/session/GeneralSessionData.java // @Component // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class GeneralSessionData implements Serializable { // // private static final long serialVersionUID = 3937661507313495926L; // // private AccessToken accesstoken; // // public AccessToken getAccessToken() { // return accesstoken; // } // // public void setAccessToken(AccessToken accessToken) { // this.accesstoken = accessToken; // } // } // Path: src/main/java/org/osiam/addons/administration/service/GroupService.java import javax.inject.Inject; import org.osiam.addons.administration.model.session.GeneralSessionData; import org.osiam.addons.administration.model.session.PagingInformation; import org.osiam.client.OsiamConnector; import org.osiam.client.oauth.AccessToken; import org.osiam.client.query.Query; import org.osiam.client.query.QueryBuilder; import org.osiam.resources.scim.Group; import org.osiam.resources.scim.MemberRef; import org.osiam.resources.scim.SCIMSearchResult; import org.springframework.stereotype.Component; package org.osiam.addons.administration.service; @Component public class GroupService { @Inject
private GeneralSessionData sessionData;
osiam/addon-administration
src/main/java/org/osiam/addons/administration/service/ExtensionsService.java
// Path: src/main/java/org/osiam/addons/administration/model/session/GeneralSessionData.java // @Component // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class GeneralSessionData implements Serializable { // // private static final long serialVersionUID = 3937661507313495926L; // // private AccessToken accesstoken; // // public AccessToken getAccessToken() { // return accesstoken; // } // // public void setAccessToken(AccessToken accessToken) { // this.accesstoken = accessToken; // } // }
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Strings; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.glassfish.jersey.apache.connector.ApacheClientProperties; import org.glassfish.jersey.apache.connector.ApacheConnectorProvider; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; import org.glassfish.jersey.client.RequestEntityProcessing; import org.osiam.addons.administration.model.session.GeneralSessionData; import org.osiam.client.exception.ConnectionInitializationException; import org.osiam.client.exception.OAuthErrorMessage; import org.osiam.client.exception.UnauthorizedException; import org.osiam.resources.scim.Extension; import org.osiam.resources.scim.Extension.Builder; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.ws.rs.ProcessingException; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.Response.StatusType; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import java.net.URI; import java.net.URISyntaxException; import java.nio.ByteBuffer; import java.util.*; import java.util.Map.Entry;
package org.osiam.addons.administration.service; @Component public class ExtensionsService { private static final String BEARER = "Bearer "; private static final int CONNECT_TIMEOUT = 2500; private static final int READ_TIMEOUT = 5000;
// Path: src/main/java/org/osiam/addons/administration/model/session/GeneralSessionData.java // @Component // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class GeneralSessionData implements Serializable { // // private static final long serialVersionUID = 3937661507313495926L; // // private AccessToken accesstoken; // // public AccessToken getAccessToken() { // return accesstoken; // } // // public void setAccessToken(AccessToken accessToken) { // this.accesstoken = accessToken; // } // } // Path: src/main/java/org/osiam/addons/administration/service/ExtensionsService.java import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Strings; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.glassfish.jersey.apache.connector.ApacheClientProperties; import org.glassfish.jersey.apache.connector.ApacheConnectorProvider; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; import org.glassfish.jersey.client.RequestEntityProcessing; import org.osiam.addons.administration.model.session.GeneralSessionData; import org.osiam.client.exception.ConnectionInitializationException; import org.osiam.client.exception.OAuthErrorMessage; import org.osiam.client.exception.UnauthorizedException; import org.osiam.resources.scim.Extension; import org.osiam.resources.scim.Extension.Builder; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.ws.rs.ProcessingException; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.Response.StatusType; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import java.net.URI; import java.net.URISyntaxException; import java.nio.ByteBuffer; import java.util.*; import java.util.Map.Entry; package org.osiam.addons.administration.service; @Component public class ExtensionsService { private static final String BEARER = "Bearer "; private static final int CONNECT_TIMEOUT = 2500; private static final int READ_TIMEOUT = 5000;
private final GeneralSessionData sessionData;
osiam/addon-administration
src/test/java/org/osiam/addons/administration/service/UserServiceTest.java
// Path: src/main/java/org/osiam/addons/administration/model/session/GeneralSessionData.java // @Component // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class GeneralSessionData implements Serializable { // // private static final long serialVersionUID = 3937661507313495926L; // // private AccessToken accesstoken; // // public AccessToken getAccessToken() { // return accesstoken; // } // // public void setAccessToken(AccessToken accessToken) { // this.accesstoken = accessToken; // } // }
import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import org.osiam.addons.administration.model.session.GeneralSessionData; import org.osiam.addons.administration.model.session.PagingInformation; import org.osiam.client.OsiamConnector; import org.osiam.client.oauth.AccessToken; import org.osiam.client.query.Query; import org.osiam.resources.scim.User; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.eq; import static org.mockito.Matchers.same; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify;
package org.osiam.addons.administration.service; @RunWith(MockitoJUnitRunner.class) public class UserServiceTest { @Mock OsiamConnector connector; @Mock AccessToken accessToken; @Spy @InjectMocks
// Path: src/main/java/org/osiam/addons/administration/model/session/GeneralSessionData.java // @Component // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class GeneralSessionData implements Serializable { // // private static final long serialVersionUID = 3937661507313495926L; // // private AccessToken accesstoken; // // public AccessToken getAccessToken() { // return accesstoken; // } // // public void setAccessToken(AccessToken accessToken) { // this.accesstoken = accessToken; // } // } // Path: src/test/java/org/osiam/addons/administration/service/UserServiceTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import org.osiam.addons.administration.model.session.GeneralSessionData; import org.osiam.addons.administration.model.session.PagingInformation; import org.osiam.client.OsiamConnector; import org.osiam.client.oauth.AccessToken; import org.osiam.client.query.Query; import org.osiam.resources.scim.User; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.eq; import static org.mockito.Matchers.same; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; package org.osiam.addons.administration.service; @RunWith(MockitoJUnitRunner.class) public class UserServiceTest { @Mock OsiamConnector connector; @Mock AccessToken accessToken; @Spy @InjectMocks
GeneralSessionData sessionData = new GeneralSessionData();
osiam/addon-administration
src/test/java/org/osiam/addons/administration/service/GroupServiceTest.java
// Path: src/main/java/org/osiam/addons/administration/model/session/GeneralSessionData.java // @Component // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class GeneralSessionData implements Serializable { // // private static final long serialVersionUID = 3937661507313495926L; // // private AccessToken accesstoken; // // public AccessToken getAccessToken() { // return accesstoken; // } // // public void setAccessToken(AccessToken accessToken) { // this.accesstoken = accessToken; // } // }
import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import org.osiam.addons.administration.model.session.GeneralSessionData; import org.osiam.client.OsiamConnector; import org.osiam.client.oauth.AccessToken; import org.osiam.client.query.Query; import org.osiam.resources.scim.Group; import org.osiam.resources.scim.MemberRef; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Matchers.same; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.springframework.data.jpa.domain.AbstractPersistable_.id;
package org.osiam.addons.administration.service; @RunWith(MockitoJUnitRunner.class) public class GroupServiceTest { @Mock OsiamConnector connector; @Mock AccessToken accessToken; @Spy @InjectMocks
// Path: src/main/java/org/osiam/addons/administration/model/session/GeneralSessionData.java // @Component // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class GeneralSessionData implements Serializable { // // private static final long serialVersionUID = 3937661507313495926L; // // private AccessToken accesstoken; // // public AccessToken getAccessToken() { // return accesstoken; // } // // public void setAccessToken(AccessToken accessToken) { // this.accesstoken = accessToken; // } // } // Path: src/test/java/org/osiam/addons/administration/service/GroupServiceTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.runners.MockitoJUnitRunner; import org.osiam.addons.administration.model.session.GeneralSessionData; import org.osiam.client.OsiamConnector; import org.osiam.client.oauth.AccessToken; import org.osiam.client.query.Query; import org.osiam.resources.scim.Group; import org.osiam.resources.scim.MemberRef; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Matchers.same; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.springframework.data.jpa.domain.AbstractPersistable_.id; package org.osiam.addons.administration.service; @RunWith(MockitoJUnitRunner.class) public class GroupServiceTest { @Mock OsiamConnector connector; @Mock AccessToken accessToken; @Spy @InjectMocks
GeneralSessionData sessionData = new GeneralSessionData();
osiam/addon-administration
src/main/java/org/osiam/addons/administration/mail/EmailSender.java
// Path: src/main/java/org/osiam/addons/administration/mail/exception/SendEmailException.java // public class SendEmailException extends OsiamException { // // private static final long serialVersionUID = -292158452140136468L; // // public SendEmailException() { // super(); // } // // public SendEmailException(String message, Throwable cause) { // super(message, cause); // } // // public SendEmailException(String message, String key, Throwable cause) { // super(message, key, HttpStatus.INTERNAL_SERVER_ERROR.value(), cause); // } // // public SendEmailException(String message, String key) { // super(message, key, HttpStatus.INTERNAL_SERVER_ERROR.value()); // } // // }
import org.springframework.stereotype.Component; import javax.inject.Inject; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; import com.google.common.base.Optional; import org.osiam.addons.administration.mail.exception.SendEmailException; import org.osiam.resources.scim.Email; import org.osiam.resources.scim.User; import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper;
/* * Copyright (C) 2014 tarent AG * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.osiam.addons.administration.mail; /** * Send email service for sending an email */ @Component public class EmailSender { @Inject private JavaMailSender mailSender; @Inject private EmailTemplateRenderer renderer; @Value("${org.osiam.mail.from}") private String fromAddress; public void sendDeactivateMail(User user) { sendDeactivateMail(user, new Locale(user.getLocale())); } public void sendDeactivateMail(User user, Locale locale) { Map<String, Object> variables = new HashMap<>(); variables.put("user", user); String mailContent = renderer.renderEmailBody("user/deactivate", locale, variables); String mailSubject = renderer.renderEmailSubject("user/deactivate", locale, variables); Optional<Email> email = user.getPrimaryOrFirstEmail(); if (!email.isPresent()) {
// Path: src/main/java/org/osiam/addons/administration/mail/exception/SendEmailException.java // public class SendEmailException extends OsiamException { // // private static final long serialVersionUID = -292158452140136468L; // // public SendEmailException() { // super(); // } // // public SendEmailException(String message, Throwable cause) { // super(message, cause); // } // // public SendEmailException(String message, String key, Throwable cause) { // super(message, key, HttpStatus.INTERNAL_SERVER_ERROR.value(), cause); // } // // public SendEmailException(String message, String key) { // super(message, key, HttpStatus.INTERNAL_SERVER_ERROR.value()); // } // // } // Path: src/main/java/org/osiam/addons/administration/mail/EmailSender.java import org.springframework.stereotype.Component; import javax.inject.Inject; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; import com.google.common.base.Optional; import org.osiam.addons.administration.mail.exception.SendEmailException; import org.osiam.resources.scim.Email; import org.osiam.resources.scim.User; import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; /* * Copyright (C) 2014 tarent AG * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.osiam.addons.administration.mail; /** * Send email service for sending an email */ @Component public class EmailSender { @Inject private JavaMailSender mailSender; @Inject private EmailTemplateRenderer renderer; @Value("${org.osiam.mail.from}") private String fromAddress; public void sendDeactivateMail(User user) { sendDeactivateMail(user, new Locale(user.getLocale())); } public void sendDeactivateMail(User user, Locale locale) { Map<String, Object> variables = new HashMap<>(); variables.put("user", user); String mailContent = renderer.renderEmailBody("user/deactivate", locale, variables); String mailSubject = renderer.renderEmailSubject("user/deactivate", locale, variables); Optional<Email> email = user.getPrimaryOrFirstEmail(); if (!email.isPresent()) {
throw new SendEmailException("The user has no email!", "user.no.email");
osiam/addon-administration
src/main/java/org/osiam/addons/administration/controller/user/UserViewController.java
// Path: src/main/java/org/osiam/addons/administration/mail/EmailSender.java // @Component // public class EmailSender { // // @Inject // private JavaMailSender mailSender; // // @Inject // private EmailTemplateRenderer renderer; // // @Value("${org.osiam.mail.from}") // private String fromAddress; // // public void sendDeactivateMail(User user) { // sendDeactivateMail(user, new Locale(user.getLocale())); // } // // public void sendDeactivateMail(User user, Locale locale) { // Map<String, Object> variables = new HashMap<>(); // variables.put("user", user); // // String mailContent = renderer.renderEmailBody("user/deactivate", locale, variables); // String mailSubject = renderer.renderEmailSubject("user/deactivate", locale, variables); // Optional<Email> email = user.getPrimaryOrFirstEmail(); // if (!email.isPresent()) { // throw new SendEmailException("The user has no email!", "user.no.email"); // } // // sendHTMLMail(fromAddress, email.get().getValue(), mailSubject, mailContent); // } // // public void sendActivateMail(User user) { // sendActivateMail(user, new Locale(user.getLocale())); // } // // public void sendActivateMail(User user, Locale locale) { // Map<String, Object> variables = new HashMap<>(); // variables.put("user", user); // // String mailContent = renderer.renderEmailBody("user/activate", locale, variables); // String mailSubject = renderer.renderEmailSubject("user/activate", locale, variables); // Optional<Email> email = user.getPrimaryOrFirstEmail(); // if (!email.isPresent()) { // throw new SendEmailException("The user has no email!", "user.no.email"); // } // // sendHTMLMail(fromAddress, email.get().getValue(), mailSubject, mailContent); // } // // public void sendHTMLMail(String fromAddress, String toAddress, String subject, String htmlContent) { // mailSender.send(getMimeMessage(fromAddress, toAddress, subject, htmlContent)); // } // // private MimeMessage getMimeMessage(String fromAddress, String toAddress, String subject, String mailContent) { // final MimeMessage mimeMessage = this.mailSender.createMimeMessage(); // final MimeMessageHelper message = new MimeMessageHelper(mimeMessage); // try { // message.setFrom(fromAddress); // message.setTo(toAddress); // message.setSubject(subject); // message.setText(mailContent, true); // message.setSentDate(new Date()); // } catch (MessagingException e) { // throw new SendEmailException("Could not create metadata for email", e); // } // return mimeMessage; // } // } // // Path: src/main/java/org/osiam/addons/administration/model/session/GeneralSessionData.java // @Component // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class GeneralSessionData implements Serializable { // // private static final long serialVersionUID = 3937661507313495926L; // // private AccessToken accesstoken; // // public AccessToken getAccessToken() { // return accesstoken; // } // // public void setAccessToken(AccessToken accessToken) { // this.accesstoken = accessToken; // } // } // // Path: src/main/java/org/osiam/addons/administration/model/session/UserlistSession.java // @Component // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class UserlistSession { // private PagingInformation pagingInformation = new PagingInformation(); // // public PagingInformation getPagingInformation() { // return pagingInformation; // } // // public void setPagingInformation(PagingInformation pagingInformation) { // this.pagingInformation = pagingInformation; // } // }
import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import org.osiam.addons.administration.controller.AdminController; import org.osiam.addons.administration.mail.EmailSender; import org.osiam.addons.administration.model.session.GeneralSessionData; import org.osiam.addons.administration.model.session.UserlistSession; import org.osiam.addons.administration.paging.PagingBuilder; import org.osiam.addons.administration.paging.PagingLinks; import org.osiam.addons.administration.service.UserService; import org.osiam.addons.administration.util.RedirectBuilder; import org.osiam.resources.scim.SCIMSearchResult; import org.osiam.resources.scim.User; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView;
public static final String REQUEST_PARAMETER_USER_ID_ARRAY = "idArray"; public static final String REQUEST_PARAMETER_SEND_MAIL = "sendMail"; public static final String REQUEST_PARAMETER_DELETE_SUCCESS = "deleteSuccess"; public static final String REQUEST_PARAMETER_DELETE_SELECTED_SUCCESS = "deleteSelectedSuccess"; public static final String REQUEST_PARAMETER_ACTIVATE_SUCCESS = "activateSuccess"; public static final String REQUEST_PARAMETER_ACTIVATE_SELECTED_SUCCESS = "activateSelectedSuccess"; public static final String REQUEST_PARAMETER_DEACTIVATE_SUCCESS = "deactivateSuccess"; public static final String REQUEST_PARAMETER_DEACTIVATE_SELECTED_SUCCESS = "deactivateSelectedSuccess"; public static final String MODEL_USER_LIST = "userlist"; public static final String MODEL_SESSION_DATA = "sessionData"; public static final String MODEL_PAGING_LINKS = "paging"; public static final String MODEL_ORDER_BY = "orderBy"; public static final String MODEL_ORDER_DIRECTION = "orderDirection"; private static final Integer DEFAULT_LIMIT = 20; private static final String DEFAULT_SORT_BY = "userName"; private static final Boolean DEFAULT_SORT_DIRECTION = true; @Inject private UserService userService; @Inject private UserlistSession session; @Inject private EmailSender emailSender; @Inject
// Path: src/main/java/org/osiam/addons/administration/mail/EmailSender.java // @Component // public class EmailSender { // // @Inject // private JavaMailSender mailSender; // // @Inject // private EmailTemplateRenderer renderer; // // @Value("${org.osiam.mail.from}") // private String fromAddress; // // public void sendDeactivateMail(User user) { // sendDeactivateMail(user, new Locale(user.getLocale())); // } // // public void sendDeactivateMail(User user, Locale locale) { // Map<String, Object> variables = new HashMap<>(); // variables.put("user", user); // // String mailContent = renderer.renderEmailBody("user/deactivate", locale, variables); // String mailSubject = renderer.renderEmailSubject("user/deactivate", locale, variables); // Optional<Email> email = user.getPrimaryOrFirstEmail(); // if (!email.isPresent()) { // throw new SendEmailException("The user has no email!", "user.no.email"); // } // // sendHTMLMail(fromAddress, email.get().getValue(), mailSubject, mailContent); // } // // public void sendActivateMail(User user) { // sendActivateMail(user, new Locale(user.getLocale())); // } // // public void sendActivateMail(User user, Locale locale) { // Map<String, Object> variables = new HashMap<>(); // variables.put("user", user); // // String mailContent = renderer.renderEmailBody("user/activate", locale, variables); // String mailSubject = renderer.renderEmailSubject("user/activate", locale, variables); // Optional<Email> email = user.getPrimaryOrFirstEmail(); // if (!email.isPresent()) { // throw new SendEmailException("The user has no email!", "user.no.email"); // } // // sendHTMLMail(fromAddress, email.get().getValue(), mailSubject, mailContent); // } // // public void sendHTMLMail(String fromAddress, String toAddress, String subject, String htmlContent) { // mailSender.send(getMimeMessage(fromAddress, toAddress, subject, htmlContent)); // } // // private MimeMessage getMimeMessage(String fromAddress, String toAddress, String subject, String mailContent) { // final MimeMessage mimeMessage = this.mailSender.createMimeMessage(); // final MimeMessageHelper message = new MimeMessageHelper(mimeMessage); // try { // message.setFrom(fromAddress); // message.setTo(toAddress); // message.setSubject(subject); // message.setText(mailContent, true); // message.setSentDate(new Date()); // } catch (MessagingException e) { // throw new SendEmailException("Could not create metadata for email", e); // } // return mimeMessage; // } // } // // Path: src/main/java/org/osiam/addons/administration/model/session/GeneralSessionData.java // @Component // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class GeneralSessionData implements Serializable { // // private static final long serialVersionUID = 3937661507313495926L; // // private AccessToken accesstoken; // // public AccessToken getAccessToken() { // return accesstoken; // } // // public void setAccessToken(AccessToken accessToken) { // this.accesstoken = accessToken; // } // } // // Path: src/main/java/org/osiam/addons/administration/model/session/UserlistSession.java // @Component // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class UserlistSession { // private PagingInformation pagingInformation = new PagingInformation(); // // public PagingInformation getPagingInformation() { // return pagingInformation; // } // // public void setPagingInformation(PagingInformation pagingInformation) { // this.pagingInformation = pagingInformation; // } // } // Path: src/main/java/org/osiam/addons/administration/controller/user/UserViewController.java import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import org.osiam.addons.administration.controller.AdminController; import org.osiam.addons.administration.mail.EmailSender; import org.osiam.addons.administration.model.session.GeneralSessionData; import org.osiam.addons.administration.model.session.UserlistSession; import org.osiam.addons.administration.paging.PagingBuilder; import org.osiam.addons.administration.paging.PagingLinks; import org.osiam.addons.administration.service.UserService; import org.osiam.addons.administration.util.RedirectBuilder; import org.osiam.resources.scim.SCIMSearchResult; import org.osiam.resources.scim.User; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; public static final String REQUEST_PARAMETER_USER_ID_ARRAY = "idArray"; public static final String REQUEST_PARAMETER_SEND_MAIL = "sendMail"; public static final String REQUEST_PARAMETER_DELETE_SUCCESS = "deleteSuccess"; public static final String REQUEST_PARAMETER_DELETE_SELECTED_SUCCESS = "deleteSelectedSuccess"; public static final String REQUEST_PARAMETER_ACTIVATE_SUCCESS = "activateSuccess"; public static final String REQUEST_PARAMETER_ACTIVATE_SELECTED_SUCCESS = "activateSelectedSuccess"; public static final String REQUEST_PARAMETER_DEACTIVATE_SUCCESS = "deactivateSuccess"; public static final String REQUEST_PARAMETER_DEACTIVATE_SELECTED_SUCCESS = "deactivateSelectedSuccess"; public static final String MODEL_USER_LIST = "userlist"; public static final String MODEL_SESSION_DATA = "sessionData"; public static final String MODEL_PAGING_LINKS = "paging"; public static final String MODEL_ORDER_BY = "orderBy"; public static final String MODEL_ORDER_DIRECTION = "orderDirection"; private static final Integer DEFAULT_LIMIT = 20; private static final String DEFAULT_SORT_BY = "userName"; private static final Boolean DEFAULT_SORT_DIRECTION = true; @Inject private UserService userService; @Inject private UserlistSession session; @Inject private EmailSender emailSender; @Inject
private GeneralSessionData generalSessionData;
osiam/addon-administration
src/main/java/org/osiam/addons/administration/controller/GlobalExceptionHandler.java
// Path: src/main/java/org/osiam/addons/administration/model/session/GeneralSessionData.java // @Component // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class GeneralSessionData implements Serializable { // // private static final long serialVersionUID = 3937661507313495926L; // // private AccessToken accesstoken; // // public AccessToken getAccessToken() { // return accesstoken; // } // // public void setAccessToken(AccessToken accessToken) { // this.accesstoken = accessToken; // } // }
import java.io.IOException; import javax.inject.Inject; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.osiam.addons.administration.model.session.GeneralSessionData; import org.osiam.addons.administration.util.RedirectBuilder; import org.osiam.client.exception.UnauthorizedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.ModelAndView; import com.google.common.base.Throwables;
package org.osiam.addons.administration.controller; /** * This class is responsible for handling all exceptions thrown by any controller-handler. */ @ControllerAdvice public class GlobalExceptionHandler implements AccessDeniedHandler { private static final Logger LOG = LoggerFactory.getLogger(GlobalExceptionHandler.class); @Inject
// Path: src/main/java/org/osiam/addons/administration/model/session/GeneralSessionData.java // @Component // @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS) // public class GeneralSessionData implements Serializable { // // private static final long serialVersionUID = 3937661507313495926L; // // private AccessToken accesstoken; // // public AccessToken getAccessToken() { // return accesstoken; // } // // public void setAccessToken(AccessToken accessToken) { // this.accesstoken = accessToken; // } // } // Path: src/main/java/org/osiam/addons/administration/controller/GlobalExceptionHandler.java import java.io.IOException; import javax.inject.Inject; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.osiam.addons.administration.model.session.GeneralSessionData; import org.osiam.addons.administration.util.RedirectBuilder; import org.osiam.client.exception.UnauthorizedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.ModelAndView; import com.google.common.base.Throwables; package org.osiam.addons.administration.controller; /** * This class is responsible for handling all exceptions thrown by any controller-handler. */ @ControllerAdvice public class GlobalExceptionHandler implements AccessDeniedHandler { private static final Logger LOG = LoggerFactory.getLogger(GlobalExceptionHandler.class); @Inject
private GeneralSessionData session;